diff options
Diffstat (limited to 'harmony-tests/src')
132 files changed, 39809 insertions, 0 deletions
diff --git a/harmony-tests/src/test/java/org/apache/harmony/annotation/tests/java/lang/annotation/AnnotationFormatErrorTest.java b/harmony-tests/src/test/java/org/apache/harmony/annotation/tests/java/lang/annotation/AnnotationFormatErrorTest.java new file mode 100644 index 0000000..b80f3a9 --- /dev/null +++ b/harmony-tests/src/test/java/org/apache/harmony/annotation/tests/java/lang/annotation/AnnotationFormatErrorTest.java @@ -0,0 +1,56 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.harmony.annotation.tests.java.lang.annotation; + +import java.lang.annotation.AnnotationFormatError; + +import junit.framework.TestCase; + +/** + * Test case of java.lang.annotation.AnnotationFormatError + */ +public class AnnotationFormatErrorTest extends TestCase { + /** + * @tests java.lang.annotation.AnnotationFormatError#AnnotationFormatError(String) + */ + @SuppressWarnings("nls") + public void test_constructorLjava_lang_String() { + AnnotationFormatError e = new AnnotationFormatError("some message"); + assertEquals("some message", e.getMessage()); + } + + /** + * @tests java.lang.annotation.AnnotationFormatError#AnnotationFormatError(Throwable) + */ + public void test_constructorLjava_lang_Throwable() { + IllegalArgumentException iae = new IllegalArgumentException(); + AnnotationFormatError e = new AnnotationFormatError(iae); + assertSame(iae, e.getCause()); + } + + /** + * @tests java.lang.annotation.AnnotationFormatError#AnnotationFormatError(String,Throwable) + */ + @SuppressWarnings("nls") + public void test_constructorLjava_lang_StringLjava_lang_Throwable() { + IllegalArgumentException iae = new IllegalArgumentException(); + AnnotationFormatError e = new AnnotationFormatError("some message", iae); + assertEquals("some message", e.getMessage()); + assertSame(iae, e.getCause()); + } +} diff --git a/harmony-tests/src/test/java/org/apache/harmony/annotation/tests/java/lang/annotation/AnnotationTypeMismatchExceptionTest.java b/harmony-tests/src/test/java/org/apache/harmony/annotation/tests/java/lang/annotation/AnnotationTypeMismatchExceptionTest.java new file mode 100644 index 0000000..37ee8c1 --- /dev/null +++ b/harmony-tests/src/test/java/org/apache/harmony/annotation/tests/java/lang/annotation/AnnotationTypeMismatchExceptionTest.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.annotation.tests.java.lang.annotation; + +import java.lang.annotation.AnnotationTypeMismatchException; +import java.lang.reflect.Method; + +import junit.framework.TestCase; + +/** + * Test case of java.lang.annotation.AnnotationTypeMismatchException + */ +public class AnnotationTypeMismatchExceptionTest extends TestCase { + + /** + * @throws ClassNotFoundException + * @throws SecurityException + * @tests java.lang.annotation.AnnotationTypeMismatchException#AnnotationTypeMismatchException(Method, + * String) + */ + @SuppressWarnings("nls") + public void test_constructorLjava_lang_reflect_MethodLjava_lang_String() throws SecurityException, ClassNotFoundException { + Method[] methods = Class.forName("java.lang.String").getMethods(); + Method m = methods[0]; + AnnotationTypeMismatchException e = new AnnotationTypeMismatchException( + m, "some type"); + assertNotNull("can not instantiate AnnotationTypeMismatchException", e); + assertSame("wrong method name", m, e.element()); + assertEquals("wrong found type", "some type", e.foundType()); + } +} diff --git a/harmony-tests/src/test/java/org/apache/harmony/annotation/tests/java/lang/annotation/ElementTypeTest.java b/harmony-tests/src/test/java/org/apache/harmony/annotation/tests/java/lang/annotation/ElementTypeTest.java new file mode 100644 index 0000000..d81cabd --- /dev/null +++ b/harmony-tests/src/test/java/org/apache/harmony/annotation/tests/java/lang/annotation/ElementTypeTest.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.annotation.tests.java.lang.annotation; + +import java.lang.annotation.ElementType; +import java.util.Arrays; + +import junit.framework.TestCase; + +/** + * Test case of java.lang.annotation.ElementType + */ +public class ElementTypeTest extends TestCase { + + /** + * @throws Exception + * @tests java.lang.annotation.ElementType#valueOf(String) + */ + @SuppressWarnings("nls") + public void test_valueOfLjava_lang_String() throws Exception { + assertSame(ElementType.ANNOTATION_TYPE, ElementType + .valueOf("ANNOTATION_TYPE")); + assertSame(ElementType.CONSTRUCTOR, ElementType.valueOf("CONSTRUCTOR")); + assertSame(ElementType.FIELD, ElementType.valueOf("FIELD")); + assertSame(ElementType.LOCAL_VARIABLE, ElementType + .valueOf("LOCAL_VARIABLE")); + assertSame(ElementType.METHOD, ElementType.valueOf("METHOD")); + assertSame(ElementType.PACKAGE, ElementType.valueOf("PACKAGE")); + assertSame(ElementType.PARAMETER, ElementType.valueOf("PARAMETER")); + assertSame(ElementType.TYPE, ElementType.valueOf("TYPE")); + try { + ElementType.valueOf("OTHER"); + fail("Should throw an IllegalArgumentException"); + } catch (IllegalArgumentException e) { + // expected + } + } + + /** + * @throws Exception + * @tests java.lang.annotation.ElementType#values() + */ + @SuppressWarnings("nls") + public void test_values() throws Exception { + ElementType[] values = ElementType.values(); + assertTrue(values.length > 1); + Arrays.sort(values); + assertTrue(Arrays.binarySearch(values, ElementType.METHOD) >= 0); + } +} diff --git a/harmony-tests/src/test/java/org/apache/harmony/annotation/tests/java/lang/annotation/IncompleteAnnotationExceptionTest.java b/harmony-tests/src/test/java/org/apache/harmony/annotation/tests/java/lang/annotation/IncompleteAnnotationExceptionTest.java new file mode 100644 index 0000000..d44b90a --- /dev/null +++ b/harmony-tests/src/test/java/org/apache/harmony/annotation/tests/java/lang/annotation/IncompleteAnnotationExceptionTest.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.annotation.tests.java.lang.annotation; + +import java.lang.annotation.IncompleteAnnotationException; + +import junit.framework.TestCase; + +/** + * + */ +public class IncompleteAnnotationExceptionTest extends TestCase { + + /* + * Class under test for void IncompleteAnnotationException(String) + * Regression for HARMONY-2477 + */ + public void testNullType() { + try { + new IncompleteAnnotationException(null, "str"); + fail("NullPointerException must be thrown"); + } catch (NullPointerException e) { + // Expected + } + } + + /** + * @throws Exception + * @tests java.lang.annotation.IncompleteAnnotationException#IncompleteAnnotationException(Class, + * String) + */ + @SuppressWarnings("nls") + public void test_constructorLjava_lang_Class_Ljava_lang_String() + throws Exception { + Class clazz = String.class; + String elementName = "some element"; + IncompleteAnnotationException e = new IncompleteAnnotationException( + clazz, elementName); + assertNotNull("can not instantiate IncompleteAnnotationException", e); + assertSame("wrong annotation type", clazz, e.annotationType()); + assertSame("wrong element name", elementName, e.elementName()); + } +} diff --git a/harmony-tests/src/test/java/org/apache/harmony/annotation/tests/java/lang/annotation/RetentionPolicyTest.java b/harmony-tests/src/test/java/org/apache/harmony/annotation/tests/java/lang/annotation/RetentionPolicyTest.java new file mode 100644 index 0000000..c4f7c03 --- /dev/null +++ b/harmony-tests/src/test/java/org/apache/harmony/annotation/tests/java/lang/annotation/RetentionPolicyTest.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.annotation.tests.java.lang.annotation; + +import java.lang.annotation.RetentionPolicy; +import java.util.Arrays; + +import junit.framework.TestCase; + +/** + * Test case of java.lang.annotation.RetentionPolicy + */ +public class RetentionPolicyTest extends TestCase { + /** + * @throws Exception + * @tests java.lang.annotation.RetentionPolicy#valueOf(String) + */ + @SuppressWarnings("nls") + public void test_valueOfLjava_lang_String() throws Exception { + assertSame(RetentionPolicy.CLASS, RetentionPolicy + .valueOf("CLASS")); + assertSame(RetentionPolicy.RUNTIME, RetentionPolicy + .valueOf("RUNTIME")); + assertSame(RetentionPolicy.SOURCE, RetentionPolicy + .valueOf("SOURCE")); + try { + RetentionPolicy.valueOf("OTHER"); + fail("Should throw an IllegalArgumentException"); + } catch (IllegalArgumentException e) { + // expected + } + } + + /** + * @throws Exception + * @tests java.lang.annotation.RetentionPolicy#values() + */ + @SuppressWarnings("nls") + public void test_values() throws Exception { + RetentionPolicy[] values = RetentionPolicy.values(); + assertTrue(values.length > 1); + Arrays.sort(values); + assertTrue(Arrays.binarySearch(values, RetentionPolicy.RUNTIME) >= 0); + } +} 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/luni/tests/java/util/UUIDTest.java new file mode 100644 index 0000000..d8f4cc4 --- /dev/null +++ b/harmony-tests/src/test/java/org/apache/harmony/luni/tests/java/util/UUIDTest.java @@ -0,0 +1,457 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations under + * the License. + */ + +package org.apache.harmony.luni.tests.java.util; + +import java.util.UUID; + +import org.apache.harmony.testframework.serialization.SerializationTest; + +import junit.framework.TestCase; + +public class UUIDTest extends TestCase { + + /** + * @see UUID#UUID(long, long) + */ + public void test_ConstructorJJ() { + UUID uuid = new UUID(0xf81d4fae7dec11d0L, 0xa76500a0c91e6bf6L); + assertEquals(2, uuid.variant()); + assertEquals(1, uuid.version()); + assertEquals(0x1d07decf81d4faeL, uuid.timestamp()); + assertEquals(130742845922168750L, uuid.timestamp()); + assertEquals(0x2765, uuid.clockSequence()); + assertEquals(0xA0C91E6BF6L, uuid.node()); + } + + /** + * @see UUID#getLeastSignificantBits() + */ + public void test_getLeastSignificantBits() { + UUID uuid = new UUID(0, 0); + assertEquals(0, uuid.getLeastSignificantBits()); + uuid = new UUID(0, Long.MIN_VALUE); + assertEquals(Long.MIN_VALUE, uuid.getLeastSignificantBits()); + uuid = new UUID(0, Long.MAX_VALUE); + assertEquals(Long.MAX_VALUE, uuid.getLeastSignificantBits()); + } + + /** + * @see UUID#getMostSignificantBits() + */ + public void test_getMostSignificantBits() { + UUID uuid = new UUID(0, 0); + assertEquals(0, uuid.getMostSignificantBits()); + uuid = new UUID(Long.MIN_VALUE, 0); + assertEquals(Long.MIN_VALUE, uuid.getMostSignificantBits()); + uuid = new UUID(Long.MAX_VALUE, 0); + assertEquals(Long.MAX_VALUE, uuid.getMostSignificantBits()); + } + + /** + * @see UUID#version() + */ + public void test_version() { + UUID uuid = new UUID(0, 0); + assertEquals(0, uuid.version()); + uuid = new UUID(0x0000000000001000L, 0); + assertEquals(1, uuid.version()); + uuid = new UUID(0x0000000000002000L, 0); + assertEquals(2, uuid.version()); + uuid = new UUID(0x0000000000003000L, 0); + assertEquals(3, uuid.version()); + uuid = new UUID(0x0000000000004000L, 0); + assertEquals(4, uuid.version()); + uuid = new UUID(0x0000000000005000L, 0); + assertEquals(5, uuid.version()); + } + + /** + * @see UUID#variant() + */ + public void test_variant() { + UUID uuid = new UUID(0, 0x0000000000000000L); + assertEquals(0, uuid.variant()); + uuid = new UUID(0, 0x7000000000000000L); + assertEquals(0, uuid.variant()); + uuid = new UUID(0, 0x3000000000000000L); + assertEquals(0, uuid.variant()); + uuid = new UUID(0, 0x1000000000000000L); + assertEquals(0, uuid.variant()); + + uuid = new UUID(0, 0x8000000000000000L); + assertEquals(2, uuid.variant()); + uuid = new UUID(0, 0xB000000000000000L); + assertEquals(2, uuid.variant()); + uuid = new UUID(0, 0xA000000000000000L); + assertEquals(2, uuid.variant()); + uuid = new UUID(0, 0x9000000000000000L); + assertEquals(2, uuid.variant()); + + uuid = new UUID(0, 0xC000000000000000L); + assertEquals(6, uuid.variant()); + uuid = new UUID(0, 0xD000000000000000L); + assertEquals(6, uuid.variant()); + + uuid = new UUID(0, 0xE000000000000000L); + assertEquals(7, uuid.variant()); + uuid = new UUID(0, 0xF000000000000000L); + assertEquals(7, uuid.variant()); + } + + /** + * @see UUID#timestamp() + */ + public void test_timestamp() { + UUID uuid = new UUID(0x0000000000001000L, 0x8000000000000000L); + assertEquals(0x0, uuid.timestamp()); + + uuid = new UUID(0x7777777755551333L, 0x8000000000000000L); + assertEquals(0x333555577777777L, uuid.timestamp()); + + uuid = new UUID(0x0000000000000000L, 0x8000000000000000L); + try { + uuid.timestamp(); + fail("No UnsupportedOperationException"); + } catch (UnsupportedOperationException e) {} + + uuid = new UUID(0x0000000000002000L, 0x8000000000000000L); + try { + uuid.timestamp(); + fail("No UnsupportedOperationException"); + } catch (UnsupportedOperationException e) {} + } + + /** + * @see UUID#clockSequence() + */ + public void test_clockSequence() { + UUID uuid = new UUID(0x0000000000001000L, 0x8000000000000000L); + assertEquals(0x0, uuid.clockSequence()); + + uuid = new UUID(0x0000000000001000L, 0x8FFF000000000000L); + assertEquals(0x0FFF, uuid.clockSequence()); + + uuid = new UUID(0x0000000000001000L, 0xBFFF000000000000L); + assertEquals(0x3FFF, uuid.clockSequence()); + + uuid = new UUID(0x0000000000000000L, 0x8000000000000000L); + try { + uuid.clockSequence(); + fail("No UnsupportedOperationException"); + } catch (UnsupportedOperationException e) {} + + uuid = new UUID(0x0000000000002000L, 0x8000000000000000L); + try { + uuid.clockSequence(); + fail("No UnsupportedOperationException"); + } catch (UnsupportedOperationException e) {} + } + + /** + * @see UUID#node() + */ + public void test_node() { + UUID uuid = new UUID(0x0000000000001000L, 0x8000000000000000L); + assertEquals(0x0, uuid.node()); + + uuid = new UUID(0x0000000000001000L, 0x8000FFFFFFFFFFFFL); + assertEquals(0xFFFFFFFFFFFFL, uuid.node()); + + uuid = new UUID(0x0000000000000000L, 0x8000000000000000L); + try { + uuid.node(); + fail("No UnsupportedOperationException"); + } catch (UnsupportedOperationException e) {} + + uuid = new UUID(0x0000000000002000L, 0x8000000000000000L); + try { + uuid.node(); + fail("No UnsupportedOperationException"); + } catch (UnsupportedOperationException e) {} + } + + /** + * @see UUID#compareTo(UUID) + */ + public void test_compareTo() { + UUID uuid1 = new UUID(0, 0); + assertEquals(0, uuid1.compareTo(uuid1)); + UUID uuid2 = new UUID(1, 0); + assertEquals(-1, uuid1.compareTo(uuid2)); + assertEquals(1, uuid2.compareTo(uuid1)); + + uuid2 = new UUID(0, 1); + assertEquals(-1, uuid1.compareTo(uuid2)); + assertEquals(1, uuid2.compareTo(uuid1)); + } + + /** + * @see UUID#hashCode() + */ + public void test_hashCode() { + UUID uuid = new UUID(0, 0); + assertEquals(0, uuid.hashCode()); + uuid = new UUID(123, 123); + UUID uuidClone = new UUID(123, 123); + assertEquals(uuid.hashCode(), uuidClone.hashCode()); + } + + /** + * @see UUID#equals(Object) + */ + public void test_equalsObject() { + UUID uuid1 = new UUID(0, 0); + assertEquals(uuid1, uuid1); + assertFalse(uuid1.equals(null)); + assertFalse(uuid1.equals("NOT A UUID")); + UUID uuid2 = new UUID(0, 0); + assertEquals(uuid1, uuid2); + assertEquals(uuid2, uuid1); + + uuid1 = new UUID(0xf81d4fae7dec11d0L, 0xa76500a0c91e6bf6L); + uuid2 = new UUID(0xf81d4fae7dec11d0L, 0xa76500a0c91e6bf6L); + assertEquals(uuid1, uuid2); + assertEquals(uuid2, uuid1); + + uuid2 = new UUID(0xf81d4fae7dec11d0L, 0xa76500a0c91e6bf7L); + assertFalse(uuid1.equals(uuid2)); + assertFalse(uuid2.equals(uuid1)); + } + + /** + * @see UUID#toString() + */ + public void test_toString() { + UUID uuid = new UUID(0xf81d4fae7dec11d0L, 0xa76500a0c91e6bf6L); + String actual = uuid.toString(); + assertEquals("f81d4fae-7dec-11d0-a765-00a0c91e6bf6", actual); + + uuid = new UUID(0x0000000000001000L, 0x8000000000000000L); + actual = uuid.toString(); + assertEquals("00000000-0000-1000-8000-000000000000", actual); + } + + /** + * @tests serialization/deserialization. + */ + public void testSerializationSelf() throws Exception { + SerializationTest.verifySelf(new UUID(0xf81d4fae7dec11d0L, + 0xa76500a0c91e6bf6L)); + } + + /** + * @tests serialization/deserialization compatibility with RI. + */ + public void testSerializationCompatibility() throws Exception { + SerializationTest.verifyGolden(this, new UUID(0xf81d4fae7dec11d0L, + 0xa76500a0c91e6bf6L)); + } + + /** + * @see UUID#randomUUID() + */ + public void test_randomUUID() { + UUID uuid = UUID.randomUUID(); + assertEquals(2, uuid.variant()); + assertEquals(4, uuid.version()); + } + + /** + * @see UUID#nameUUIDFromBytes(byte[]) + */ + public void test_nameUUIDFromBytes() throws Exception { + byte[] name = { (byte) 0x6b, (byte) 0xa7, (byte) 0xb8, (byte) 0x11, + (byte) 0x9d, (byte) 0xad, (byte) 0x11, (byte) 0xd1, + (byte) 0x80, (byte) 0xb4, (byte) 0x00, (byte) 0xc0, + (byte) 0x4f, (byte) 0xd4, (byte) 0x30, (byte) 0xc8 }; + + UUID uuid = UUID.nameUUIDFromBytes(name); + + assertEquals(2, uuid.variant()); + assertEquals(3, uuid.version()); + + assertEquals(0xaff565bc2f771745L, uuid.getLeastSignificantBits()); + assertEquals(0x14cdb9b4de013faaL, uuid.getMostSignificantBits()); + + uuid = UUID.nameUUIDFromBytes(new byte[0]); + assertEquals(2, uuid.variant()); + assertEquals(3, uuid.version()); + + assertEquals(0xa9800998ecf8427eL, uuid.getLeastSignificantBits()); + assertEquals(0xd41d8cd98f003204L, uuid.getMostSignificantBits()); + + try { + UUID.nameUUIDFromBytes(null); + fail("No NPE"); + } catch (NullPointerException e) {} + } + + /** + * @see UUID#fromString(String) + */ + public void test_fromString() { + UUID actual = UUID.fromString("f81d4fae-7dec-11d0-a765-00a0c91e6bf6"); + UUID expected = new UUID(0xf81d4fae7dec11d0L, 0xa76500a0c91e6bf6L); + assertEquals(expected, actual); + + assertEquals(2, actual.variant()); + assertEquals(1, actual.version()); + assertEquals(130742845922168750L, actual.timestamp()); + assertEquals(10085, actual.clockSequence()); + assertEquals(690568981494L, actual.node()); + + actual = UUID.fromString("00000000-0000-1000-8000-000000000000"); + expected = new UUID(0x0000000000001000L, 0x8000000000000000L); + assertEquals(expected, actual); + + assertEquals(2, actual.variant()); + assertEquals(1, actual.version()); + assertEquals(0L, actual.timestamp()); + assertEquals(0, actual.clockSequence()); + assertEquals(0L, actual.node()); + + try { + UUID.fromString(null); + fail("No NPE"); + } catch (NullPointerException e) {} + + try { + UUID.fromString(""); + fail("No IAE"); + } catch (IllegalArgumentException e) {} + + try { + UUID.fromString("f81d4fae_7dec-11d0-a765-00a0c91e6bf6"); + fail("No IAE"); + } catch (IllegalArgumentException e) {} + + try { + UUID.fromString("f81d4fae-7dec_11d0-a765-00a0c91e6bf6"); + fail("No IAE"); + } catch (IllegalArgumentException e) {} + + try { + UUID.fromString("f81d4fae-7dec-11d0_a765-00a0c91e6bf6"); + fail("No IAE"); + } catch (IllegalArgumentException e) {} + + try { + UUID.fromString("f81d4fae-7dec-11d0-a765_00a0c91e6bf6"); + fail("No IAE"); + } catch (IllegalArgumentException e) {} + } + + /** + * @tests java.util.UUID#fromString(String) + */ + public void test_fromString_LString_Exception() { + + UUID uuid = UUID.fromString("0-0-0-0-0"); + + try { + uuid = UUID.fromString("0-0-0-0-"); + fail("should throw IllegalArgumentException"); + } catch (IllegalArgumentException e) { + // expected + } + + try { + uuid = UUID.fromString("-0-0-0-0-0"); + fail("should throw IllegalArgumentException"); + } catch (IllegalArgumentException e) { + // expected + } + + try { + uuid = UUID.fromString("-0-0-0-0"); + fail("should throw IllegalArgumentException"); + } catch (IllegalArgumentException e) { + // expected + } + + try { + uuid = UUID.fromString("-0-0-0-"); + fail("should throw IllegalArgumentException"); + } catch (IllegalArgumentException e) { + // expected + } + + try { + uuid = UUID.fromString("0--0-0-0"); + fail("should throw IllegalArgumentException"); + } catch (IllegalArgumentException e) { + // expected + } + + try { + uuid = UUID.fromString("0-0-0-0-"); + fail("should throw IllegalArgumentException"); + } catch (IllegalArgumentException e) { + // expected + } + + try { + uuid = UUID.fromString("-1-0-0-0-0"); + fail("should throw IllegalArgumentException"); + } catch (IllegalArgumentException e) { + // expected + } + + uuid = UUID.fromString("123456789-0-0-0-0"); + assertEquals(0x2345678900000000L, uuid.getMostSignificantBits()); + assertEquals(0x0L, uuid.getLeastSignificantBits()); + + uuid = UUID.fromString("111123456789-0-0-0-0"); + assertEquals(0x2345678900000000L, uuid.getMostSignificantBits()); + assertEquals(0x0L, uuid.getLeastSignificantBits()); + + uuid = UUID.fromString("7fffffffffffffff-0-0-0-0"); + assertEquals(0xffffffff00000000L, uuid.getMostSignificantBits()); + assertEquals(0x0L, uuid.getLeastSignificantBits()); + + try { + uuid = UUID.fromString("8000000000000000-0-0-0-0"); + fail("should throw NumberFormatException"); + } catch (NumberFormatException e) { + // expected + } + + uuid = UUID + .fromString("7fffffffffffffff-7fffffffffffffff-7fffffffffffffff-0-0"); + assertEquals(0xffffffffffffffffL, uuid.getMostSignificantBits()); + assertEquals(0x0L, uuid.getLeastSignificantBits()); + + uuid = UUID.fromString("0-0-0-7fffffffffffffff-7fffffffffffffff"); + assertEquals(0x0L, uuid.getMostSignificantBits()); + assertEquals(0xffffffffffffffffL, uuid.getLeastSignificantBits()); + + try { + uuid = UUID.fromString("0-0-0-8000000000000000-0"); + fail("should throw NumberFormatException"); + } catch (NumberFormatException e) { + // expected + } + + try { + uuid = UUID.fromString("0-0-0-0-8000000000000000"); + fail("should throw NumberFormatException"); + } catch (NumberFormatException e) { + // expected + } + } +} diff --git a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/AbstractBufferTest.java b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/AbstractBufferTest.java new file mode 100644 index 0000000..eb48992 --- /dev/null +++ b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/AbstractBufferTest.java @@ -0,0 +1,306 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.harmony.nio.tests.java.nio; + +import java.nio.Buffer; +import java.nio.ByteBuffer; +import java.nio.InvalidMarkException; + +import junit.framework.TestCase; + +/** + * Tests a java.nio.Buffer instance. + */ +public class AbstractBufferTest extends TestCase { + + protected Buffer baseBuf; + + protected void setUp() throws Exception{ + super.setUp(); + baseBuf = ByteBuffer.allocate(10); + } + + protected void tearDown() throws Exception{ + super.tearDown(); + } + + public void testCapacity() { + assertTrue(0 <= baseBuf.position() && baseBuf.position() <= baseBuf.limit() + && baseBuf.limit() <= baseBuf.capacity()); + } + + public void testClear() { + // save state + int oldPosition = baseBuf.position(); + int oldLimit = baseBuf.limit(); + + Buffer ret = baseBuf.clear(); + assertSame(ret, baseBuf); + assertEquals(baseBuf.position(), 0); + assertEquals(baseBuf.limit(), baseBuf.capacity()); + try { + baseBuf.reset(); + fail("Should throw Exception"); //$NON-NLS-1$S + } catch (InvalidMarkException e) { + // expected + } + + // restore state + baseBuf.limit(oldLimit); + baseBuf.position(oldPosition); + } + + public void testFlip() { + // save state + int oldPosition = baseBuf.position(); + int oldLimit = baseBuf.limit(); + + Buffer ret = baseBuf.flip(); + assertSame(ret, baseBuf); + assertEquals(baseBuf.position(), 0); + assertEquals(baseBuf.limit(), oldPosition); + try { + baseBuf.reset(); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (InvalidMarkException e) { + // expected + } + + // restore state + baseBuf.limit(oldLimit); + baseBuf.position(oldPosition); + } + + public void testHasRemaining() { + // save state + int oldPosition = baseBuf.position(); + int oldLimit = baseBuf.limit(); + + assertEquals(baseBuf.hasRemaining(), baseBuf.position() < baseBuf.limit()); + baseBuf.position(baseBuf.limit()); + assertFalse(baseBuf.hasRemaining()); + + // restore state + baseBuf.limit(oldLimit); + baseBuf.position(oldPosition); + } + + public void testIsReadOnly() { + baseBuf.isReadOnly(); + } + + /* + * Class under test for int limit() + */ + public void testLimit() { + assertTrue(0 <= baseBuf.position() && baseBuf.position() <= baseBuf.limit() + && baseBuf.limit() <= baseBuf.capacity()); + } + + /* + * Class under test for Buffer limit(int) + */ + public void testLimitint() { + // save state + int oldPosition = baseBuf.position(); + int oldLimit = baseBuf.limit(); + + Buffer ret = baseBuf.limit(baseBuf.limit()); + assertSame(ret, baseBuf); + + baseBuf.mark(); + baseBuf.limit(baseBuf.capacity()); + assertEquals(baseBuf.limit(), baseBuf.capacity()); + // position should not change + assertEquals(baseBuf.position(), oldPosition); + // mark should be valid + baseBuf.reset(); + + if (baseBuf.capacity() > 0) { + baseBuf.limit(baseBuf.capacity()); + baseBuf.position(baseBuf.capacity()); + baseBuf.mark(); + baseBuf.limit(baseBuf.capacity() - 1); + // position should be the new limit + assertEquals(baseBuf.position(), baseBuf.limit()); + // mark should be invalid + try { + baseBuf.reset(); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (InvalidMarkException e) { + // expected + } + } + + try { + baseBuf.limit(-1); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (IllegalArgumentException e) { + // expected + } + try { + baseBuf.limit(baseBuf.capacity() + 1); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (IllegalArgumentException e) { + // expected + } + + // restore state + baseBuf.limit(oldLimit); + baseBuf.position(oldPosition); + } + + public void testMark() { + // save state + int oldPosition = baseBuf.position(); + int oldLimit = baseBuf.limit(); + + Buffer ret = baseBuf.mark(); + assertSame(ret, baseBuf); + + baseBuf.mark(); + baseBuf.position(baseBuf.limit()); + baseBuf.reset(); + assertEquals(baseBuf.position(), oldPosition); + + baseBuf.mark(); + baseBuf.position(baseBuf.limit()); + baseBuf.reset(); + assertEquals(baseBuf.position(), oldPosition); + + // restore state + baseBuf.limit(oldLimit); + baseBuf.position(oldPosition); + } + + /* + * Class under test for int position() + */ + public void testPosition() { + assertTrue(0 <= baseBuf.position() && baseBuf.position() <= baseBuf.limit() + && baseBuf.limit() <= baseBuf.capacity()); + } + + /* + * Class under test for Buffer position(int) + */ + public void testPositionint() { + // save state + int oldPosition = baseBuf.position(); + int oldLimit = baseBuf.limit(); + + try { + baseBuf.position(-1); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (IllegalArgumentException e) { + // expected + } + try { + baseBuf.position(baseBuf.limit() + 1); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (IllegalArgumentException e) { + // expected + } + + baseBuf.mark(); + baseBuf.position(baseBuf.position()); + baseBuf.reset(); + assertEquals(baseBuf.position(), oldPosition); + + baseBuf.position(0); + assertEquals(baseBuf.position(), 0); + baseBuf.position(baseBuf.limit()); + assertEquals(baseBuf.position(), baseBuf.limit()); + + if (baseBuf.capacity() > 0) { + baseBuf.limit(baseBuf.capacity()); + baseBuf.position(baseBuf.limit()); + baseBuf.mark(); + baseBuf.position(baseBuf.limit() - 1); + assertEquals(baseBuf.position(), baseBuf.limit() - 1); + // mark should be invalid + try { + baseBuf.reset(); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (InvalidMarkException e) { + // expected + } + } + + Buffer ret = baseBuf.position(0); + assertSame(ret, baseBuf); + + // restore state + baseBuf.limit(oldLimit); + baseBuf.position(oldPosition); + } + + public void testRemaining() { + assertEquals(baseBuf.remaining(), baseBuf.limit() - baseBuf.position()); + } + + public void testReset() { + // save state + int oldPosition = baseBuf.position(); + int oldLimit = baseBuf.limit(); + + baseBuf.mark(); + baseBuf.position(baseBuf.limit()); + baseBuf.reset(); + assertEquals(baseBuf.position(), oldPosition); + + baseBuf.mark(); + baseBuf.position(baseBuf.limit()); + baseBuf.reset(); + assertEquals(baseBuf.position(), oldPosition); + + Buffer ret = baseBuf.reset(); + assertSame(ret, baseBuf); + + baseBuf.clear(); + try { + baseBuf.reset(); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (InvalidMarkException e) { + // expected + } + + // restore state + baseBuf.limit(oldLimit); + baseBuf.position(oldPosition); + } + + public void testRewind() { + // save state + int oldPosition = baseBuf.position(); + int oldLimit = baseBuf.limit(); + + Buffer ret = baseBuf.rewind(); + assertEquals(baseBuf.position(), 0); + assertSame(ret, baseBuf); + try { + baseBuf.reset(); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (InvalidMarkException e) { + // expected + } + + // restore state + baseBuf.limit(oldLimit); + baseBuf.position(oldPosition); + } +} 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/nio/tests/java/nio/BufferOverflowExceptionTest.java new file mode 100644 index 0000000..39059fe --- /dev/null +++ b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/BufferOverflowExceptionTest.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.nio.tests.java.nio; + +import java.nio.BufferOverflowException; + +import junit.framework.TestCase; + +import org.apache.harmony.testframework.serialization.SerializationTest; + +public class BufferOverflowExceptionTest extends TestCase { + + /** + * @tests serialization/deserialization compatibility. + */ + public void testSerializationSelf() throws Exception { + + SerializationTest.verifySelf(new BufferOverflowException()); + } + + /** + * @tests serialization/deserialization compatibility with RI. + */ + public void testSerializationCompatibility() throws Exception { + + SerializationTest.verifyGolden(this, new BufferOverflowException()); + } + + /** + *@tests {@link java.nio.BufferOverflowException#BufferOverflowException()} + */ + public void test_Constructor() { + BufferOverflowException exception = new BufferOverflowException(); + assertNull(exception.getMessage()); + assertNull(exception.getLocalizedMessage()); + assertNull(exception.getCause()); + } +} 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/nio/tests/java/nio/BufferUnderflowExceptionTest.java new file mode 100644 index 0000000..a056ebf --- /dev/null +++ b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/BufferUnderflowExceptionTest.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.nio.tests.java.nio; + +import java.nio.BufferUnderflowException; + +import junit.framework.TestCase; + +import org.apache.harmony.testframework.serialization.SerializationTest; + +/** + * Tests for BufferUnderflowException + */ +public class BufferUnderflowExceptionTest extends TestCase { + + /** + * @tests serialization/deserialization compatibility. + */ + public void testSerializationSelf() throws Exception { + + SerializationTest.verifySelf(new BufferUnderflowException()); + } + + /** + * @tests serialization/deserialization compatibility with RI. + */ + public void testSerializationCompatibility() throws Exception { + + SerializationTest.verifyGolden(this, new BufferUnderflowException()); + } + + /** + *@tests {@link java.nio.BufferUnderflowException#BufferUnderflowException()} + */ + public void test_Constructor() { + BufferUnderflowException exception = new BufferUnderflowException(); + assertNull(exception.getMessage()); + assertNull(exception.getLocalizedMessage()); + assertNull(exception.getCause()); + } +} 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/nio/tests/java/nio/ByteBufferTest.java new file mode 100644 index 0000000..d6d8681 --- /dev/null +++ b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/ByteBufferTest.java @@ -0,0 +1,2177 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.harmony.nio.tests.java.nio; + +import java.nio.BufferOverflowException; +import java.nio.BufferUnderflowException; +import java.nio.ByteBuffer; +import java.nio.ByteOrder; +import java.nio.CharBuffer; +import java.nio.DoubleBuffer; +import java.nio.FloatBuffer; +import java.nio.IntBuffer; +import java.nio.InvalidMarkException; +import java.nio.LongBuffer; +import java.nio.ReadOnlyBufferException; +import java.nio.ShortBuffer; +import java.util.Arrays; + +/** + * Tests java.nio.ByteBuffer + * + */ +public class ByteBufferTest extends AbstractBufferTest { + protected static final int SMALL_TEST_LENGTH = 5; + protected static final int BUFFER_LENGTH = 250; + + protected ByteBuffer buf; + + protected void setUp() throws Exception { + buf = ByteBuffer.allocate(10); + loadTestData1(buf); + baseBuf = buf; + } + + protected void tearDown() throws Exception { + super.tearDown(); + } + + public void testArray() { + if (buf.hasArray()) { + byte array[] = buf.array(); + assertContentEquals(buf, array, buf.arrayOffset(), buf.capacity()); + + loadTestData1(array, buf.arrayOffset(), buf.capacity()); + assertContentEquals(buf, array, buf.arrayOffset(), buf.capacity()); + + loadTestData2(array, buf.arrayOffset(), buf.capacity()); + assertContentEquals(buf, array, buf.arrayOffset(), buf.capacity()); + + loadTestData1(buf); + assertContentEquals(buf, array, buf.arrayOffset(), buf.capacity()); + + loadTestData2(buf); + assertContentEquals(buf, array, buf.arrayOffset(), buf.capacity()); + } else { + if (buf.isReadOnly()) { + try { + buf.array(); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (UnsupportedOperationException e) { + // expected + // Note:can not tell when to throw + // UnsupportedOperationException + // or ReadOnlyBufferException, so catch all. + } + } else { + try { + buf.array(); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (UnsupportedOperationException e) { + // expected + } + } + } + } + + public void testArrayOffset() { + if (buf.hasArray()) { + byte array[] = buf.array(); + assertContentEquals(buf, array, buf.arrayOffset(), buf.capacity()); + + loadTestData1(array, buf.arrayOffset(), buf.capacity()); + assertContentEquals(buf, array, buf.arrayOffset(), buf.capacity()); + + loadTestData2(array, buf.arrayOffset(), buf.capacity()); + assertContentEquals(buf, array, buf.arrayOffset(), buf.capacity()); + + loadTestData1(buf); + assertContentEquals(buf, array, buf.arrayOffset(), buf.capacity()); + + loadTestData2(buf); + assertContentEquals(buf, array, buf.arrayOffset(), buf.capacity()); + } else { + if (buf.isReadOnly()) { + try { + buf.arrayOffset(); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (UnsupportedOperationException e) { + // expected + // Note:can not tell when to throw + // UnsupportedOperationException + // or ReadOnlyBufferException, so catch all. + } + } else { + try { + buf.arrayOffset(); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (UnsupportedOperationException e) { + // expected + } + } + } + } + + public void testAsReadOnlyBuffer() { + buf.clear(); + buf.mark(); + buf.position(buf.limit()); + + // readonly's contents should be the same as buf + ByteBuffer readonly = buf.asReadOnlyBuffer(); + assertNotSame(buf, readonly); + assertTrue(readonly.isReadOnly()); + assertEquals(buf.position(), readonly.position()); + assertEquals(buf.limit(), readonly.limit()); + assertEquals(buf.isDirect(), readonly.isDirect()); + assertEquals(buf.order(), readonly.order()); + assertContentEquals(buf, readonly); + + // readonly's position, mark, and limit should be independent to buf + readonly.reset(); + assertEquals(readonly.position(), 0); + readonly.clear(); + assertEquals(buf.position(), buf.limit()); + buf.reset(); + assertEquals(buf.position(), 0); + } + + public void testCompact() { + if (buf.isReadOnly()) { + try { + buf.compact(); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (ReadOnlyBufferException e) { + // expected + } + return; + } + + // case: buffer is full + buf.clear(); + buf.mark(); + loadTestData1(buf); + ByteBuffer ret = buf.compact(); + assertSame(ret, buf); + assertEquals(buf.position(), buf.capacity()); + assertEquals(buf.limit(), buf.capacity()); + assertContentLikeTestData1(buf, 0, (byte) 0, buf.capacity()); + try { + buf.reset(); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (InvalidMarkException e) { + // expected + } + + // case: buffer is empty + buf.position(0); + buf.limit(0); + buf.mark(); + ret = buf.compact(); + assertSame(ret, buf); + assertEquals(buf.position(), 0); + assertEquals(buf.limit(), buf.capacity()); + assertContentLikeTestData1(buf, 0, (byte) 0, buf.capacity()); + try { + buf.reset(); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (InvalidMarkException e) { + // expected + } + + // case: normal + assertTrue(buf.capacity() > SMALL_TEST_LENGTH); + buf.position(1); + buf.limit(SMALL_TEST_LENGTH); + buf.mark(); + ret = buf.compact(); + assertSame(ret, buf); + assertEquals(buf.position(), 4); + assertEquals(buf.limit(), buf.capacity()); + assertContentLikeTestData1(buf, 0, (byte) 1, 4); + try { + buf.reset(); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (InvalidMarkException e) { + // expected + } + } + + public void testCompareTo() { + // compare to self + assertEquals(0, buf.compareTo(buf)); + + // normal cases + if (!buf.isReadOnly()) { + assertTrue(buf.capacity() > SMALL_TEST_LENGTH); + buf.clear(); + ByteBuffer other = ByteBuffer.allocate(buf.capacity()); + loadTestData1(buf); + loadTestData1(other); + assertEquals(0, buf.compareTo(other)); + assertEquals(0, other.compareTo(buf)); + buf.position(1); + assertTrue(buf.compareTo(other) > 0); + assertTrue(other.compareTo(buf) < 0); + other.position(2); + assertTrue(buf.compareTo(other) < 0); + assertTrue(other.compareTo(buf) > 0); + buf.position(2); + other.limit(SMALL_TEST_LENGTH); + assertTrue(buf.compareTo(other) > 0); + assertTrue(other.compareTo(buf) < 0); + } + + assertTrue(ByteBuffer.wrap(new byte[21]).compareTo(ByteBuffer.allocateDirect(21)) == 0); + } + + public void testDuplicate() { + buf.clear(); + buf.mark(); + buf.position(buf.limit()); + + // duplicate's contents should be the same as buf + ByteBuffer duplicate = buf.duplicate(); + assertNotSame(buf, duplicate); + assertEquals(buf.position(), duplicate.position()); + assertEquals(buf.limit(), duplicate.limit()); + assertEquals(buf.isReadOnly(), duplicate.isReadOnly()); + assertEquals(buf.isDirect(), duplicate.isDirect()); + assertEquals(buf.order(), duplicate.order()); + assertContentEquals(buf, duplicate); + + // duplicate's position, mark, and limit should be independent to buf + duplicate.reset(); + assertEquals(duplicate.position(), 0); + duplicate.clear(); + assertEquals(buf.position(), buf.limit()); + buf.reset(); + assertEquals(buf.position(), 0); + + // duplicate share the same content with buf + if (!duplicate.isReadOnly()) { + loadTestData1(buf); + assertContentEquals(buf, duplicate); + loadTestData2(duplicate); + assertContentEquals(buf, duplicate); + } + } + + public void testEquals() { + // equal to self + assertTrue(buf.equals(buf)); + ByteBuffer readonly = buf.asReadOnlyBuffer(); + assertTrue(buf.equals(readonly)); + ByteBuffer duplicate = buf.duplicate(); + assertTrue(buf.equals(duplicate)); + + // always false, if type mismatch + assertFalse(buf.equals(Boolean.TRUE)); + + assertTrue(buf.capacity() > SMALL_TEST_LENGTH); + + buf.limit(buf.capacity()).position(0); + readonly.limit(readonly.capacity()).position(1); + assertFalse(buf.equals(readonly)); + + buf.limit(buf.capacity() - 1).position(0); + duplicate.limit(duplicate.capacity()).position(0); + assertFalse(buf.equals(duplicate)); + } + + /* + * Class under test for byte get() + */ + public void testGet() { + buf.clear(); + for (int i = 0; i < buf.capacity(); i++) { + assertEquals(buf.position(), i); + assertEquals(buf.get(), buf.get(i)); + } + try { + buf.get(); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (BufferUnderflowException e) { + // expected + } + } + + /* + * Class under test for java.nio.ByteBuffer get(byte[]) + */ + public void testGetbyteArray() { + byte array[] = new byte[1]; + buf.clear(); + for (int i = 0; i < buf.capacity(); i++) { + assertEquals(buf.position(), i); + ByteBuffer ret = buf.get(array); + assertEquals(array[0], buf.get(i)); + assertSame(ret, buf); + } + try { + buf.get(array); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (BufferUnderflowException e) { + // expected + } + try { + buf.get((byte[])null); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (NullPointerException e) { + // expected + } + } + + /* + * Class under test for java.nio.ByteBuffer get(byte[], int, int) + */ + public void testGetbyteArrayintint() { + buf.clear(); + byte array[] = new byte[buf.capacity()]; + + try { + buf.get(new byte[buf.capacity() + 1], 0, buf.capacity() + 1); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (BufferUnderflowException e) { + // expected + } + assertEquals(buf.position(), 0); + try { + buf.get(array, -1, array.length); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (IndexOutOfBoundsException e) { + // expected + } + buf.get(array, array.length, 0); + try { + buf.get(array, array.length + 1, 1); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (IndexOutOfBoundsException e) { + // expected + } + assertEquals(buf.position(), 0); + try { + buf.get(array, 2, -1); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (IndexOutOfBoundsException e) { + // expected + } + try { + buf.get(array, 2, array.length); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (IndexOutOfBoundsException e) { + // expected + } + try { + buf.get((byte[])null, -1, 0); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (NullPointerException e) { + // expected + } + try { + buf.get(array, 1, Integer.MAX_VALUE); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (IndexOutOfBoundsException e) { + // expected + } + try { + buf.get(array, Integer.MAX_VALUE, 1); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (IndexOutOfBoundsException e) { + // expected + } + assertEquals(buf.position(), 0); + + buf.clear(); + ByteBuffer ret = buf.get(array, 0, array.length); + assertEquals(buf.position(), buf.capacity()); + assertContentEquals(buf, array, 0, array.length); + assertSame(ret, buf); + } + + /* + * Class under test for byte get(int) + */ + public void testGetint() { + buf.clear(); + for (int i = 0; i < buf.capacity(); i++) { + assertEquals(buf.position(), i); + assertEquals(buf.get(), buf.get(i)); + } + try { + buf.get(-1); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (IndexOutOfBoundsException e) { + // expected + } + try { + buf.get(buf.limit()); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (IndexOutOfBoundsException e) { + // expected + } + } + + public void testHasArray() { + if (buf.hasArray()) { + assertNotNull(buf.array()); + } else { + if (buf.isReadOnly()) { + try { + buf.array(); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (UnsupportedOperationException e) { + // expected + // Note:can not tell when to throw + // UnsupportedOperationException + // or ReadOnlyBufferException, so catch all. + } + } else { + try { + buf.array(); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (UnsupportedOperationException e) { + // expected + } + } + } + } + + public void testHashCode() { + buf.clear(); + loadTestData1(buf); + ByteBuffer readonly = buf.asReadOnlyBuffer(); + ByteBuffer duplicate = buf.duplicate(); + assertTrue(buf.hashCode() == readonly.hashCode()); + assertTrue(buf.capacity() > SMALL_TEST_LENGTH); + duplicate.position(buf.capacity()/2); + assertTrue(buf.hashCode()!= duplicate.hashCode()); + } + + //for the testHashCode() method of readonly subclasses + protected void readOnlyHashCode() { + //create a new buffer initiated with some data + ByteBuffer buf = ByteBuffer.allocate(BUFFER_LENGTH); + loadTestData1(buf); + buf = buf.asReadOnlyBuffer(); + buf.clear(); + ByteBuffer readonly = buf.asReadOnlyBuffer(); + ByteBuffer duplicate = buf.duplicate(); + assertEquals(buf.hashCode(),readonly.hashCode()); + duplicate.position(buf.capacity()/2); + assertTrue(buf.hashCode()!= duplicate.hashCode()); + } + + public void testIsDirect() { + buf.isDirect(); + } + + public void testOrder() { + // BIG_ENDIAN is the default byte order + assertEquals(ByteOrder.BIG_ENDIAN, buf.order()); + + buf.order(ByteOrder.LITTLE_ENDIAN); + assertEquals(ByteOrder.LITTLE_ENDIAN, buf.order()); + + buf.order(ByteOrder.BIG_ENDIAN); + assertEquals(ByteOrder.BIG_ENDIAN, buf.order()); + + // Regression test for HARMONY-798 + buf.order((ByteOrder)null); + assertEquals(ByteOrder.LITTLE_ENDIAN, buf.order()); + + buf.order(ByteOrder.BIG_ENDIAN); + } + + /* + * Class under test for java.nio.ByteBuffer put(byte) + */ + public void testPutbyte() { + if (buf.isReadOnly()) { + try { + buf.clear(); + buf.put((byte) 0); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (ReadOnlyBufferException e) { + // expected + } + return; + } + + buf.clear(); + for (int i = 0; i < buf.capacity(); i++) { + assertEquals(buf.position(), i); + ByteBuffer ret = buf.put((byte) i); + assertEquals(buf.get(i), (byte) i); + assertSame(ret, buf); + } + try { + buf.put((byte) 0); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (BufferOverflowException e) { + // expected + } + } + + /* + * Class under test for java.nio.ByteBuffer put(byte[]) + */ + public void testPutbyteArray() { + byte array[] = new byte[1]; + if (buf.isReadOnly()) { + try { + buf.put(array); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (ReadOnlyBufferException e) { + // expected + } + return; + } + + buf.clear(); + for (int i = 0; i < buf.capacity(); i++) { + assertEquals(buf.position(), i); + array[0] = (byte) i; + ByteBuffer ret = buf.put(array); + assertEquals(buf.get(i), (byte) i); + assertSame(ret, buf); + } + try { + buf.put(array); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (BufferOverflowException e) { + // expected + } + try { + buf.put((byte[])null); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (NullPointerException e) { + // expected + } + } + + /* + * Class under test for java.nio.ByteBuffer put(byte[], int, int) + */ + public void testPutbyteArrayintint() { + buf.clear(); + byte array[] = new byte[buf.capacity()]; + if (buf.isReadOnly()) { + try { + buf.put(array, 0, array.length); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (ReadOnlyBufferException e) { + // expected + } + return; + } + + try { + buf.put(new byte[buf.capacity() + 1], 0, buf.capacity() + 1); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (BufferOverflowException e) { + // expected + } + assertEquals(buf.position(), 0); + try { + buf.put(array, -1, array.length); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (IndexOutOfBoundsException e) { + // expected + } + try { + buf.put(array, array.length + 1, 0); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (IndexOutOfBoundsException e) { + // expected + } + buf.put(array, array.length, 0); + assertEquals(buf.position(), 0); + try { + buf.put(array, 0, -1); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (IndexOutOfBoundsException e) { + // expected + } + try { + buf.put(array, 2, array.length); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (IndexOutOfBoundsException e) { + // expected + } + + try { + buf.put(array, 2, Integer.MAX_VALUE); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (IndexOutOfBoundsException e) { + // expected + } + try { + buf.put(array, Integer.MAX_VALUE, 1); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (IndexOutOfBoundsException e) { + // expected + } + try { + buf.put((byte[])null, 2, Integer.MAX_VALUE); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (NullPointerException e) { + // expected + } + + assertEquals(buf.position(), 0); + + loadTestData2(array, 0, array.length); + ByteBuffer ret = buf.put(array, 0, array.length); + assertEquals(buf.position(), buf.capacity()); + assertContentEquals(buf, array, 0, array.length); + assertSame(ret, buf); + } + + /* + * Class under test for java.nio.ByteBuffer put(java.nio.ByteBuffer) + */ + public void testPutByteBuffer() { + ByteBuffer other = ByteBuffer.allocate(buf.capacity()); + if (buf.isReadOnly()) { + try { + buf.clear(); + buf.put(other); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (ReadOnlyBufferException e) { + // expected + } + try { + buf.clear(); + buf.put((ByteBuffer)null); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (ReadOnlyBufferException e) { + // expected + } + return; + } + + try { + buf.put(buf); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (IllegalArgumentException e) { + // expected + } + try { + buf.put(ByteBuffer.allocate(buf.capacity() + 1)); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (BufferOverflowException e) { + // expected + } + + try { + buf.put((ByteBuffer)null); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (NullPointerException e) { + // expected + } + loadTestData2(other); + other.clear(); + buf.clear(); + ByteBuffer ret = buf.put(other); + assertEquals(other.position(), other.capacity()); + assertEquals(buf.position(), buf.capacity()); + assertContentEquals(other, buf); + assertSame(ret, buf); + } + + /* + * Class under test for java.nio.ByteBuffer put(int, byte) + */ + public void testPutintbyte() { + if (buf.isReadOnly()) { + try { + buf.put(0, (byte) 0); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (ReadOnlyBufferException e) { + // expected + } + return; + } + + buf.clear(); + for (int i = 0; i < buf.capacity(); i++) { + assertEquals(buf.position(), 0); + ByteBuffer ret = buf.put(i, (byte) i); + assertEquals(buf.get(i), (byte) i); + assertSame(ret, buf); + } + try { + buf.put(-1, (byte) 0); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (IndexOutOfBoundsException e) { + // expected + } + try { + buf.put(buf.limit(), (byte) 0); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (IndexOutOfBoundsException e) { + // expected + } + } + + public void testSlice() { + assertTrue(buf.capacity() > SMALL_TEST_LENGTH); + buf.position(1); + buf.limit(buf.capacity() - 1); + + ByteBuffer slice = buf.slice(); + assertEquals(buf.isReadOnly(), slice.isReadOnly()); + assertEquals(buf.isDirect(), slice.isDirect()); + assertEquals(buf.order(), slice.order()); + assertEquals(slice.position(), 0); + assertEquals(slice.limit(), buf.remaining()); + assertEquals(slice.capacity(), buf.remaining()); + try { + slice.reset(); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (InvalidMarkException e) { + // expected + } + + // slice share the same content with buf + if (!slice.isReadOnly()) { + loadTestData1(slice); + assertContentLikeTestData1(buf, 1, (byte) 0, slice.capacity()); + buf.put(2, (byte) 100); + assertEquals(slice.get(1), 100); + } + } + + public void testToString() { + String str = buf.toString(); + assertTrue(str.indexOf("Byte") >= 0 || str.indexOf("byte") >= 0); + assertTrue(str.indexOf("" + buf.position()) >= 0); + assertTrue(str.indexOf("" + buf.limit()) >= 0); + assertTrue(str.indexOf("" + buf.capacity()) >= 0); + } + + public void testAsCharBuffer() { + CharBuffer charBuffer; + byte bytes[] = new byte[2]; + char value; + + // test BIG_ENDIAN char buffer, read + buf.clear(); + buf.order(ByteOrder.BIG_ENDIAN); + charBuffer = buf.asCharBuffer(); + assertSame(ByteOrder.BIG_ENDIAN, charBuffer.order()); + while (charBuffer.remaining() > 0) { + buf.get(bytes); + value = charBuffer.get(); + assertEquals(bytes2char(bytes, buf.order()), value); + } + + // test LITTLE_ENDIAN char buffer, read + buf.clear(); + buf.order(ByteOrder.LITTLE_ENDIAN); + charBuffer = buf.asCharBuffer(); + assertSame(ByteOrder.LITTLE_ENDIAN, charBuffer.order()); + while (charBuffer.remaining() > 0) { + buf.get(bytes); + value = charBuffer.get(); + assertEquals(bytes2char(bytes, buf.order()), value); + } + + if (!buf.isReadOnly()) { + // test BIG_ENDIAN char buffer, write + buf.clear(); + buf.order(ByteOrder.BIG_ENDIAN); + charBuffer = buf.asCharBuffer(); + assertSame(ByteOrder.BIG_ENDIAN, charBuffer.order()); + while (charBuffer.remaining() > 0) { + value = (char) charBuffer.remaining(); + charBuffer.put(value); + buf.get(bytes); + assertTrue(Arrays.equals(bytes, char2bytes(value, buf.order()))); + } + + // test LITTLE_ENDIAN char buffer, write + buf.clear(); + buf.order(ByteOrder.LITTLE_ENDIAN); + charBuffer = buf.asCharBuffer(); + assertSame(ByteOrder.LITTLE_ENDIAN, charBuffer.order()); + while (charBuffer.remaining() > 0) { + value = (char) charBuffer.remaining(); + charBuffer.put(value); + buf.get(bytes); + assertTrue(Arrays.equals(bytes, char2bytes(value, buf.order()))); + } + } + buf.clear(); + buf.order(ByteOrder.BIG_ENDIAN); + } + + public void testAsDoubleBuffer() { + DoubleBuffer doubleBuffer; + byte bytes[] = new byte[8]; + double value; + + // test BIG_ENDIAN double buffer, read + buf.clear(); + buf.order(ByteOrder.BIG_ENDIAN); + doubleBuffer = buf.asDoubleBuffer(); + assertSame(ByteOrder.BIG_ENDIAN, doubleBuffer.order()); + while (doubleBuffer.remaining() > 0) { + buf.get(bytes); + value = doubleBuffer.get(); + if (!(Double.isNaN(bytes2double(bytes, buf.order())) && Double + .isNaN(value))) { + assertEquals(bytes2double(bytes, buf.order()), value, 0.00); + } + } + + // test LITTLE_ENDIAN double buffer, read + buf.clear(); + buf.order(ByteOrder.LITTLE_ENDIAN); + doubleBuffer = buf.asDoubleBuffer(); + assertSame(ByteOrder.LITTLE_ENDIAN, doubleBuffer.order()); + while (doubleBuffer.remaining() > 0) { + buf.get(bytes); + value = doubleBuffer.get(); + if (!(Double.isNaN(bytes2double(bytes, buf.order())) && Double + .isNaN(value))) { + assertEquals(bytes2double(bytes, buf.order()), value, 0.00); + } + } + + if (!buf.isReadOnly()) { + // test BIG_ENDIAN double buffer, write + buf.clear(); + buf.order(ByteOrder.BIG_ENDIAN); + doubleBuffer = buf.asDoubleBuffer(); + assertSame(ByteOrder.BIG_ENDIAN, doubleBuffer.order()); + while (doubleBuffer.remaining() > 0) { + value = (double) doubleBuffer.remaining(); + doubleBuffer.put(value); + buf.get(bytes); + assertTrue(Arrays.equals(bytes, double2bytes(value, buf.order()))); + } + + // test LITTLE_ENDIAN double buffer, write + buf.clear(); + buf.order(ByteOrder.LITTLE_ENDIAN); + doubleBuffer = buf.asDoubleBuffer(); + assertSame(ByteOrder.LITTLE_ENDIAN, doubleBuffer.order()); + while (doubleBuffer.remaining() > 0) { + value = (double) doubleBuffer.remaining(); + doubleBuffer.put(value); + buf.get(bytes); + assertTrue(Arrays.equals(bytes, double2bytes(value, buf.order()))); + } + } + + buf.clear(); + buf.order(ByteOrder.BIG_ENDIAN); + } + + public void testAsFloatBuffer() { + FloatBuffer floatBuffer; + byte bytes[] = new byte[4]; + float value; + + // test BIG_ENDIAN float buffer, read + buf.clear(); + buf.order(ByteOrder.BIG_ENDIAN); + floatBuffer = buf.asFloatBuffer(); + assertSame(ByteOrder.BIG_ENDIAN, floatBuffer.order()); + while (floatBuffer.remaining() > 0) { + buf.get(bytes); + value = floatBuffer.get(); + if (!(Float.isNaN(bytes2float(bytes, buf.order())) && Float + .isNaN(value))) { + assertEquals(bytes2float(bytes, buf.order()), value, 0.00); + } + } + + // test LITTLE_ENDIAN float buffer, read + buf.clear(); + buf.order(ByteOrder.LITTLE_ENDIAN); + floatBuffer = buf.asFloatBuffer(); + assertSame(ByteOrder.LITTLE_ENDIAN, floatBuffer.order()); + while (floatBuffer.remaining() > 0) { + buf.get(bytes); + value = floatBuffer.get(); + if (!(Float.isNaN(bytes2float(bytes, buf.order())) && Float + .isNaN(value))) { + assertEquals(bytes2float(bytes, buf.order()), value, 0.00); + } + } + + if (!buf.isReadOnly()) { + // test BIG_ENDIAN float buffer, write + buf.clear(); + buf.order(ByteOrder.BIG_ENDIAN); + floatBuffer = buf.asFloatBuffer(); + assertSame(ByteOrder.BIG_ENDIAN, floatBuffer.order()); + while (floatBuffer.remaining() > 0) { + value = (float) floatBuffer.remaining(); + floatBuffer.put(value); + buf.get(bytes); + assertTrue(Arrays.equals(bytes, float2bytes(value, buf.order()))); + } + + // test LITTLE_ENDIAN float buffer, write + buf.clear(); + buf.order(ByteOrder.LITTLE_ENDIAN); + floatBuffer = buf.asFloatBuffer(); + assertSame(ByteOrder.LITTLE_ENDIAN, floatBuffer.order()); + while (floatBuffer.remaining() > 0) { + value = (float) floatBuffer.remaining(); + floatBuffer.put(value); + buf.get(bytes); + assertTrue(Arrays.equals(bytes, float2bytes(value, buf.order()))); + } + } + + buf.clear(); + buf.order(ByteOrder.BIG_ENDIAN); + } + + public void testAsIntBuffer() { + IntBuffer intBuffer; + byte bytes[] = new byte[4]; + int value; + + // test BIG_ENDIAN int buffer, read + buf.clear(); + buf.order(ByteOrder.BIG_ENDIAN); + intBuffer = buf.asIntBuffer(); + assertSame(ByteOrder.BIG_ENDIAN, intBuffer.order()); + while (intBuffer.remaining() > 0) { + buf.get(bytes); + value = intBuffer.get(); + assertEquals(bytes2int(bytes, buf.order()), value); + } + + // test LITTLE_ENDIAN int buffer, read + buf.clear(); + buf.order(ByteOrder.LITTLE_ENDIAN); + intBuffer = buf.asIntBuffer(); + assertSame(ByteOrder.LITTLE_ENDIAN, intBuffer.order()); + while (intBuffer.remaining() > 0) { + buf.get(bytes); + value = intBuffer.get(); + assertEquals(bytes2int(bytes, buf.order()), value); + } + + if (!buf.isReadOnly()) { + // test BIG_ENDIAN int buffer, write + buf.clear(); + buf.order(ByteOrder.BIG_ENDIAN); + intBuffer = buf.asIntBuffer(); + assertSame(ByteOrder.BIG_ENDIAN, intBuffer.order()); + while (intBuffer.remaining() > 0) { + value = (int) intBuffer.remaining(); + intBuffer.put(value); + buf.get(bytes); + assertTrue(Arrays.equals(bytes, int2bytes(value, buf.order()))); + } + + // test LITTLE_ENDIAN int buffer, write + buf.clear(); + buf.order(ByteOrder.LITTLE_ENDIAN); + intBuffer = buf.asIntBuffer(); + assertSame(ByteOrder.LITTLE_ENDIAN, intBuffer.order()); + while (intBuffer.remaining() > 0) { + value = (int) intBuffer.remaining(); + intBuffer.put(value); + buf.get(bytes); + assertTrue(Arrays.equals(bytes, int2bytes(value, buf.order()))); + } + } + + buf.clear(); + buf.order(ByteOrder.BIG_ENDIAN); + } + + public void testAsLongBuffer() { + LongBuffer longBuffer; + byte bytes[] = new byte[8]; + long value; + + // test BIG_ENDIAN long buffer, read + buf.clear(); + buf.order(ByteOrder.BIG_ENDIAN); + longBuffer = buf.asLongBuffer(); + assertSame(ByteOrder.BIG_ENDIAN, longBuffer.order()); + while (longBuffer.remaining() > 0) { + buf.get(bytes); + value = longBuffer.get(); + assertEquals(bytes2long(bytes, buf.order()), value); + } + + // test LITTLE_ENDIAN long buffer, read + buf.clear(); + buf.order(ByteOrder.LITTLE_ENDIAN); + longBuffer = buf.asLongBuffer(); + assertSame(ByteOrder.LITTLE_ENDIAN, longBuffer.order()); + while (longBuffer.remaining() > 0) { + buf.get(bytes); + value = longBuffer.get(); + assertEquals(bytes2long(bytes, buf.order()), value); + } + + if (!buf.isReadOnly()) { + // test BIG_ENDIAN long buffer, write + buf.clear(); + buf.order(ByteOrder.BIG_ENDIAN); + longBuffer = buf.asLongBuffer(); + assertSame(ByteOrder.BIG_ENDIAN, longBuffer.order()); + while (longBuffer.remaining() > 0) { + value = (long) longBuffer.remaining(); + longBuffer.put(value); + buf.get(bytes); + assertTrue(Arrays.equals(bytes, long2bytes(value, buf.order()))); + } + + // test LITTLE_ENDIAN long buffer, write + buf.clear(); + buf.order(ByteOrder.LITTLE_ENDIAN); + longBuffer = buf.asLongBuffer(); + assertSame(ByteOrder.LITTLE_ENDIAN, longBuffer.order()); + while (longBuffer.remaining() > 0) { + value = (long) longBuffer.remaining(); + longBuffer.put(value); + buf.get(bytes); + assertTrue(Arrays.equals(bytes, long2bytes(value, buf.order()))); + } + } + + buf.clear(); + buf.order(ByteOrder.BIG_ENDIAN); + } + + public void testAsShortBuffer() { + ShortBuffer shortBuffer; + byte bytes[] = new byte[2]; + short value; + + // test BIG_ENDIAN short buffer, read + buf.clear(); + buf.order(ByteOrder.BIG_ENDIAN); + shortBuffer = buf.asShortBuffer(); + assertSame(ByteOrder.BIG_ENDIAN, shortBuffer.order()); + while (shortBuffer.remaining() > 0) { + buf.get(bytes); + value = shortBuffer.get(); + assertEquals(bytes2short(bytes, buf.order()), value); + } + + // test LITTLE_ENDIAN short buffer, read + buf.clear(); + buf.order(ByteOrder.LITTLE_ENDIAN); + shortBuffer = buf.asShortBuffer(); + assertSame(ByteOrder.LITTLE_ENDIAN, shortBuffer.order()); + while (shortBuffer.remaining() > 0) { + buf.get(bytes); + value = shortBuffer.get(); + assertEquals(bytes2short(bytes, buf.order()), value); + } + + if (!buf.isReadOnly()) { + // test BIG_ENDIAN short buffer, write + buf.clear(); + buf.order(ByteOrder.BIG_ENDIAN); + shortBuffer = buf.asShortBuffer(); + assertSame(ByteOrder.BIG_ENDIAN, shortBuffer.order()); + while (shortBuffer.remaining() > 0) { + value = (short) shortBuffer.remaining(); + shortBuffer.put(value); + buf.get(bytes); + assertTrue(Arrays.equals(bytes, short2bytes(value, buf.order()))); + } + + // test LITTLE_ENDIAN short buffer, write + buf.clear(); + buf.order(ByteOrder.LITTLE_ENDIAN); + shortBuffer = buf.asShortBuffer(); + assertSame(ByteOrder.LITTLE_ENDIAN, shortBuffer.order()); + while (shortBuffer.remaining() > 0) { + value = (short) shortBuffer.remaining(); + shortBuffer.put(value); + buf.get(bytes); + assertTrue(Arrays.equals(bytes, short2bytes(value, buf.order()))); + } + } + + buf.clear(); + buf.order(ByteOrder.BIG_ENDIAN); + } + + public void testGetChar() { + int nbytes = 2; + byte bytes[] = new byte[nbytes]; + char value; + buf.clear(); + for (int i = 0; buf.remaining() >= nbytes; i++) { + buf.order(i % 2 == 0 ? ByteOrder.BIG_ENDIAN + : ByteOrder.LITTLE_ENDIAN); + assertEquals(i * nbytes, buf.position()); + buf.mark(); + buf.get(bytes); + buf.reset(); + value = buf.getChar(); + assertEquals(bytes2char(bytes, buf.order()), value); + } + + try { + buf.getChar(); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (BufferUnderflowException e) { + // expected + } + + buf.order(ByteOrder.BIG_ENDIAN); + } + + public void testGetCharint() { + int nbytes = 2; + byte bytes[] = new byte[nbytes]; + char value; + buf.clear(); + for (int i = 0; i <= buf.limit() - nbytes; i++) { + buf.order(i % 2 == 0 ? ByteOrder.BIG_ENDIAN + : ByteOrder.LITTLE_ENDIAN); + buf.position(i); + value = buf.getChar(i); + assertEquals(i, buf.position()); + buf.get(bytes); + assertEquals(bytes2char(bytes, buf.order()), value); + } + + try { + buf.getChar(-1); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (IndexOutOfBoundsException e) { + // expected + } + try { + buf.getChar(buf.limit() - nbytes + 1); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (IndexOutOfBoundsException e) { + // expected + } + + buf.order(ByteOrder.BIG_ENDIAN); + } + + public void testPutChar() { + if (buf.isReadOnly()) { + try { + buf.clear(); + buf.putChar((char) 1); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (ReadOnlyBufferException e) { + // expected + } + return; + } + + int nbytes = 2; + byte bytes[] = new byte[nbytes]; + char value = 0; + buf.clear(); + for (int i = 0; buf.remaining() >= nbytes; i++) { + buf.order(i % 2 == 0 ? ByteOrder.BIG_ENDIAN + : ByteOrder.LITTLE_ENDIAN); + value = (char) i; + buf.mark(); + buf.putChar(value); + assertEquals((i + 1) * nbytes, buf.position()); + buf.reset(); + buf.get(bytes); + assertTrue(Arrays.equals(char2bytes(value, buf.order()), bytes)); + } + + try { + buf.putChar(value); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (BufferOverflowException e) { + // expected + } + + buf.order(ByteOrder.BIG_ENDIAN); + } + + public void testPutCharint() { + if (buf.isReadOnly()) { + try { + buf.putChar(0, (char) 1); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (ReadOnlyBufferException e) { + // expected + } + return; + } + + int nbytes = 2; + byte bytes[] = new byte[nbytes]; + char value = 0; + buf.clear(); + for (int i = 0; i <= buf.limit() - nbytes; i++) { + buf.order(i % 2 == 0 ? ByteOrder.BIG_ENDIAN + : ByteOrder.LITTLE_ENDIAN); + value = (char) i; + buf.position(i); + buf.putChar(i, value); + assertEquals(i, buf.position()); + buf.get(bytes); + assertTrue(Arrays.equals(char2bytes(value, buf.order()), bytes)); + } + + try { + buf.putChar(-1, value); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (IndexOutOfBoundsException e) { + // expected + } + try { + buf.putChar(buf.limit() - nbytes + 1, value); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (IndexOutOfBoundsException e) { + // expected + } + + buf.order(ByteOrder.BIG_ENDIAN); + + try { + ByteBuffer.allocateDirect(16).putChar(Integer.MAX_VALUE, 'h'); + } catch (IndexOutOfBoundsException e) { + //expected + } + } + + public void testGetDouble() { + int nbytes = 8; + byte bytes[] = new byte[nbytes]; + double value; + buf.clear(); + for (int i = 0; buf.remaining() >= nbytes; i++) { + buf.order(i % 2 == 0 ? ByteOrder.BIG_ENDIAN + : ByteOrder.LITTLE_ENDIAN); + assertEquals(i * nbytes, buf.position()); + buf.mark(); + buf.get(bytes); + buf.reset(); + value = buf.getDouble(); + if (!(Double.isNaN(bytes2double(bytes, buf.order())) && Double + .isNaN(value))) { + assertEquals(bytes2double(bytes, buf.order()), value, 0.00); + } + } + + try { + buf.getDouble(); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (BufferUnderflowException e) { + // expected + } + + buf.order(ByteOrder.BIG_ENDIAN); + } + + public void testGetDoubleint() { + int nbytes = 8; + byte bytes[] = new byte[nbytes]; + double value; + buf.clear(); + for (int i = 0; i <= buf.limit() - nbytes; i++) { + buf.order(i % 2 == 0 ? ByteOrder.BIG_ENDIAN + : ByteOrder.LITTLE_ENDIAN); + buf.position(i); + value = buf.getDouble(i); + assertEquals(i, buf.position()); + buf.get(bytes); + if (!(Double.isNaN(bytes2double(bytes, buf.order())) && Double + .isNaN(value))) { + assertEquals(bytes2double(bytes, buf.order()), value, 0.00); + } + } + + try { + buf.getDouble(-1); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (IndexOutOfBoundsException e) { + // expected + } + try { + buf.getDouble(buf.limit() - nbytes + 1); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (IndexOutOfBoundsException e) { + // expected + } + + buf.order(ByteOrder.BIG_ENDIAN); + + try { + ByteBuffer.allocateDirect(16).getDouble(Integer.MAX_VALUE); + } catch (IndexOutOfBoundsException e) { + //expected + } + } + + public void testPutDouble() { + if (buf.isReadOnly()) { + try { + buf.clear(); + buf.putDouble((double) 1); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (ReadOnlyBufferException e) { + // expected + } + return; + } + + int nbytes = 8; + byte bytes[] = new byte[nbytes]; + double value = 0; + buf.clear(); + for (int i = 0; buf.remaining() >= nbytes; i++) { + buf.order(i % 2 == 0 ? ByteOrder.BIG_ENDIAN + : ByteOrder.LITTLE_ENDIAN); + value = (double) i; + buf.mark(); + buf.putDouble(value); + assertEquals((i + 1) * nbytes, buf.position()); + buf.reset(); + buf.get(bytes); + assertTrue(Arrays.equals(double2bytes(value, buf.order()), bytes)); + } + + try { + buf.putDouble(value); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (BufferOverflowException e) { + // expected + } + + buf.order(ByteOrder.BIG_ENDIAN); + } + + public void testPutDoubleint() { + if (buf.isReadOnly()) { + try { + buf.putDouble(0, (double) 1); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (ReadOnlyBufferException e) { + // expected + } + return; + } + + int nbytes = 8; + byte bytes[] = new byte[nbytes]; + double value = 0; + buf.clear(); + for (int i = 0; i <= buf.limit() - nbytes; i++) { + buf.order(i % 2 == 0 ? ByteOrder.BIG_ENDIAN + : ByteOrder.LITTLE_ENDIAN); + value = (double) i; + buf.position(i); + buf.putDouble(i, value); + assertEquals(i, buf.position()); + buf.get(bytes); + assertTrue(Arrays.equals(double2bytes(value, buf.order()), bytes)); + } + + try { + buf.putDouble(-1, value); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (IndexOutOfBoundsException e) { + // expected + } + try { + buf.putDouble(buf.limit() - nbytes + 1, value); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (IndexOutOfBoundsException e) { + // expected + } + + buf.order(ByteOrder.BIG_ENDIAN); + } + + public void testGetFloat() { + int nbytes = 4; + byte bytes[] = new byte[nbytes]; + float value; + buf.clear(); + for (int i = 0; buf.remaining() >= nbytes; i++) { + buf.order(i % 2 == 0 ? ByteOrder.BIG_ENDIAN + : ByteOrder.LITTLE_ENDIAN); + assertEquals(i * nbytes, buf.position()); + buf.mark(); + buf.get(bytes); + buf.reset(); + value = buf.getFloat(); + if (!(Float.isNaN(bytes2float(bytes, buf.order())) && Float + .isNaN(value))) { + assertEquals(bytes2float(bytes, buf.order()), value, 0.00); + } + } + + try { + buf.getFloat(); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (BufferUnderflowException e) { + // expected + } + + buf.order(ByteOrder.BIG_ENDIAN); + } + + public void testGetFloatint() { + int nbytes = 4; + byte bytes[] = new byte[nbytes]; + float value; + buf.clear(); + for (int i = 0; i <= buf.limit() - nbytes; i++) { + buf.order(i % 2 == 0 ? ByteOrder.BIG_ENDIAN + : ByteOrder.LITTLE_ENDIAN); + buf.position(i); + value = buf.getFloat(i); + assertEquals(i, buf.position()); + buf.get(bytes); + if (!(Float.isNaN(bytes2float(bytes, buf.order())) && Float + .isNaN(value))) { + assertEquals(bytes2float(bytes, buf.order()), value, 0.00); + } + } + + try { + buf.getFloat(-1); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (IndexOutOfBoundsException e) { + // expected + } + try { + buf.getFloat(buf.limit() - nbytes + 1); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (IndexOutOfBoundsException e) { + // expected + } + + buf.order(ByteOrder.BIG_ENDIAN); + } + + public void testPutFloat() { + if (buf.isReadOnly()) { + try { + buf.clear(); + buf.putFloat((float) 1); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (ReadOnlyBufferException e) { + // expected + } + return; + } + + int nbytes = 4; + byte bytes[] = new byte[nbytes]; + float value = 0; + buf.clear(); + for (int i = 0; buf.remaining() >= nbytes; i++) { + buf.order(i % 2 == 0 ? ByteOrder.BIG_ENDIAN + : ByteOrder.LITTLE_ENDIAN); + value = (float) i; + buf.mark(); + buf.putFloat(value); + assertEquals((i + 1) * nbytes, buf.position()); + buf.reset(); + buf.get(bytes); + assertTrue(Arrays.equals(float2bytes(value, buf.order()), bytes)); + } + + try { + buf.putFloat(value); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (BufferOverflowException e) { + // expected + } + + buf.order(ByteOrder.BIG_ENDIAN); + } + + public void testPutFloatint() { + if (buf.isReadOnly()) { + try { + buf.putFloat(0, (float) 1); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (ReadOnlyBufferException e) { + // expected + } + return; + } + + int nbytes = 4; + byte bytes[] = new byte[nbytes]; + float value = 0; + buf.clear(); + for (int i = 0; i <= buf.limit() - nbytes; i++) { + buf.order(i % 2 == 0 ? ByteOrder.BIG_ENDIAN + : ByteOrder.LITTLE_ENDIAN); + value = (float) i; + buf.position(i); + buf.putFloat(i, value); + assertEquals(i, buf.position()); + buf.get(bytes); + assertTrue(Arrays.equals(float2bytes(value, buf.order()), bytes)); + } + + try { + buf.putFloat(-1, value); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (IndexOutOfBoundsException e) { + // expected + } + try { + buf.putFloat(buf.limit() - nbytes + 1, value); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (IndexOutOfBoundsException e) { + // expected + } + + buf.order(ByteOrder.BIG_ENDIAN); + } + + public void testGetInt() { + int nbytes = 4; + byte bytes[] = new byte[nbytes]; + int value; + buf.clear(); + for (int i = 0; buf.remaining() >= nbytes; i++) { + buf.order(i % 2 == 0 ? ByteOrder.BIG_ENDIAN + : ByteOrder.LITTLE_ENDIAN); + assertEquals(i * nbytes, buf.position()); + buf.mark(); + buf.get(bytes); + buf.reset(); + value = buf.getInt(); + assertEquals(bytes2int(bytes, buf.order()), value); + } + + try { + buf.getInt(); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (BufferUnderflowException e) { + // expected + } + + buf.order(ByteOrder.BIG_ENDIAN); + } + + public void testGetIntint() { + int nbytes = 4; + byte bytes[] = new byte[nbytes]; + int value; + buf.clear(); + for (int i = 0; i <= buf.limit() - nbytes; i++) { + buf.order(i % 2 == 0 ? ByteOrder.BIG_ENDIAN + : ByteOrder.LITTLE_ENDIAN); + buf.position(i); + value = buf.getInt(i); + assertEquals(i, buf.position()); + buf.get(bytes); + assertEquals(bytes2int(bytes, buf.order()), value); + } + + try { + buf.getInt(-1); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (IndexOutOfBoundsException e) { + // expected + } + try { + buf.getInt(buf.limit() - nbytes + 1); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (IndexOutOfBoundsException e) { + // expected + } + + buf.order(ByteOrder.BIG_ENDIAN); + try { + ByteBuffer.allocateDirect(16).getInt(Integer.MAX_VALUE); + } catch (IndexOutOfBoundsException e) { + //expected + } + } + + public void testPutInt() { + if (buf.isReadOnly()) { + try { + buf.clear(); + buf.putInt((int) 1); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (ReadOnlyBufferException e) { + // expected + } + return; + } + + int nbytes = 4; + byte bytes[] = new byte[nbytes]; + int value = 0; + buf.clear(); + for (int i = 0; buf.remaining() >= nbytes; i++) { + buf.order(i % 2 == 0 ? ByteOrder.BIG_ENDIAN + : ByteOrder.LITTLE_ENDIAN); + value = (int) i; + buf.mark(); + buf.putInt(value); + assertEquals((i + 1) * nbytes, buf.position()); + buf.reset(); + buf.get(bytes); + assertTrue(Arrays.equals(int2bytes(value, buf.order()), bytes)); + } + + try { + buf.putInt(value); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (BufferOverflowException e) { + // expected + } + + buf.order(ByteOrder.BIG_ENDIAN); + } + + public void testPutIntint() { + if (buf.isReadOnly()) { + try { + buf.putInt(0, (int) 1); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (ReadOnlyBufferException e) { + // expected + } + return; + } + + int nbytes = 4; + byte bytes[] = new byte[nbytes]; + int value = 0; + buf.clear(); + for (int i = 0; i <= buf.limit() - nbytes; i++) { + buf.order(i % 2 == 0 ? ByteOrder.BIG_ENDIAN + : ByteOrder.LITTLE_ENDIAN); + value = (int) i; + buf.position(i); + buf.putInt(i, value); + assertEquals(i, buf.position()); + buf.get(bytes); + assertTrue(Arrays.equals(int2bytes(value, buf.order()), bytes)); + } + + try { + buf.putInt(-1, value); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (IndexOutOfBoundsException e) { + // expected + } + try { + buf.putInt(buf.limit() - nbytes + 1, value); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (IndexOutOfBoundsException e) { + // expected + } + + buf.order(ByteOrder.BIG_ENDIAN); + } + + public void testGetLong() { + int nbytes = 8; + byte bytes[] = new byte[nbytes]; + long value; + buf.clear(); + for (int i = 0; buf.remaining() >= nbytes; i++) { + buf.order(i % 2 == 0 ? ByteOrder.BIG_ENDIAN + : ByteOrder.LITTLE_ENDIAN); + assertEquals(i * nbytes, buf.position()); + buf.mark(); + buf.get(bytes); + buf.reset(); + value = buf.getLong(); + assertEquals(bytes2long(bytes, buf.order()), value); + } + + try { + buf.getLong(); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (BufferUnderflowException e) { + // expected + } + + buf.order(ByteOrder.BIG_ENDIAN); + } + + public void testGetLongint() { + int nbytes = 8; + byte bytes[] = new byte[nbytes]; + long value; + buf.clear(); + for (int i = 0; i <= buf.limit() - nbytes; i++) { + buf.order(i % 2 == 0 ? ByteOrder.BIG_ENDIAN + : ByteOrder.LITTLE_ENDIAN); + buf.position(i); + value = buf.getLong(i); + assertEquals(i, buf.position()); + buf.get(bytes); + assertEquals(bytes2long(bytes, buf.order()), value); + } + + try { + buf.getLong(-1); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (IndexOutOfBoundsException e) { + // expected + } + try { + buf.getLong(buf.limit() - nbytes + 1); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (IndexOutOfBoundsException e) { + // expected + } + + buf.order(ByteOrder.BIG_ENDIAN); + } + + public void testPutLong() { + if (buf.isReadOnly()) { + try { + buf.clear(); + buf.putLong((long) 1); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (ReadOnlyBufferException e) { + // expected + } + return; + } + + int nbytes = 8; + byte bytes[] = new byte[nbytes]; + long value = 0; + buf.clear(); + for (int i = 0; buf.remaining() >= nbytes; i++) { + buf.order(i % 2 == 0 ? ByteOrder.BIG_ENDIAN + : ByteOrder.LITTLE_ENDIAN); + value = (long) i; + buf.mark(); + buf.putLong(value); + assertEquals((i + 1) * nbytes, buf.position()); + buf.reset(); + buf.get(bytes); + assertTrue(Arrays.equals(long2bytes(value, buf.order()), bytes)); + } + + try { + buf.putLong(value); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (BufferOverflowException e) { + // expected + } + + buf.order(ByteOrder.BIG_ENDIAN); + } + + public void testPutLongint() { + if (buf.isReadOnly()) { + try { + buf.putLong(0, (long) 1); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (ReadOnlyBufferException e) { + // expected + } + return; + } + + int nbytes = 8; + byte bytes[] = new byte[nbytes]; + long value = 0; + buf.clear(); + for (int i = 0; i <= buf.limit() - nbytes; i++) { + buf.order(i % 2 == 0 ? ByteOrder.BIG_ENDIAN + : ByteOrder.LITTLE_ENDIAN); + value = (long) i; + buf.position(i); + buf.putLong(i, value); + assertEquals(i, buf.position()); + buf.get(bytes); + assertTrue(Arrays.equals(long2bytes(value, buf.order()), bytes)); + } + + try { + buf.putLong(-1, value); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (IndexOutOfBoundsException e) { + // expected + } + try { + buf.putLong(buf.limit() - nbytes + 1, value); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (IndexOutOfBoundsException e) { + // expected + } + + buf.order(ByteOrder.BIG_ENDIAN); + } + + public void testGetShort() { + int nbytes = 2; + byte bytes[] = new byte[nbytes]; + short value; + buf.clear(); + for (int i = 0; buf.remaining() >= nbytes; i++) { + buf.order(i % 2 == 0 ? ByteOrder.BIG_ENDIAN + : ByteOrder.LITTLE_ENDIAN); + assertEquals(i * nbytes, buf.position()); + buf.mark(); + buf.get(bytes); + buf.reset(); + value = buf.getShort(); + assertEquals(bytes2short(bytes, buf.order()), value); + } + + try { + buf.getShort(); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (BufferUnderflowException e) { + // expected + } + + buf.order(ByteOrder.BIG_ENDIAN); + } + + public void testGetShortint() { + int nbytes = 2; + byte bytes[] = new byte[nbytes]; + short value; + buf.clear(); + for (int i = 0; i <= buf.limit() - nbytes; i++) { + buf.order(i % 2 == 0 ? ByteOrder.BIG_ENDIAN + : ByteOrder.LITTLE_ENDIAN); + buf.position(i); + value = buf.getShort(i); + assertEquals(i, buf.position()); + buf.get(bytes); + assertEquals(bytes2short(bytes, buf.order()), value); + } + + try { + buf.getShort(-1); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (IndexOutOfBoundsException e) { + // expected + } + try { + buf.getShort(buf.limit() - nbytes + 1); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (IndexOutOfBoundsException e) { + // expected + } + + buf.order(ByteOrder.BIG_ENDIAN); + } + + public void testPutShort() { + if (buf.isReadOnly()) { + try { + buf.clear(); + buf.putShort((short) 1); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (ReadOnlyBufferException e) { + // expected + } + return; + } + + int nbytes = 2; + byte bytes[] = new byte[nbytes]; + short value = 0; + buf.clear(); + for (int i = 0; buf.remaining() >= nbytes; i++) { + buf.order(i % 2 == 0 ? ByteOrder.BIG_ENDIAN + : ByteOrder.LITTLE_ENDIAN); + value = (short) i; + buf.mark(); + buf.putShort(value); + assertEquals((i + 1) * nbytes, buf.position()); + buf.reset(); + buf.get(bytes); + assertTrue(Arrays.equals(short2bytes(value, buf.order()), bytes)); + } + + try { + buf.putShort(value); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (BufferOverflowException e) { + // expected + } + + buf.order(ByteOrder.BIG_ENDIAN); + } + + public void testPutShortint() { + if (buf.isReadOnly()) { + try { + buf.putShort(0, (short) 1); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (ReadOnlyBufferException e) { + // expected + } + return; + } + + int nbytes = 2; + byte bytes[] = new byte[nbytes]; + short value = 0; + buf.clear(); + for (int i = 0; i <= buf.limit() - nbytes; i++) { + buf.order(i % 2 == 0 ? ByteOrder.BIG_ENDIAN + : ByteOrder.LITTLE_ENDIAN); + value = (short) i; + buf.position(i); + buf.putShort(i, value); + assertEquals(i, buf.position()); + buf.get(bytes); + assertTrue(Arrays.equals(short2bytes(value, buf.order()), bytes)); + } + + try { + buf.putShort(-1, value); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (IndexOutOfBoundsException e) { + // expected + } + try { + buf.putShort(buf.limit() - nbytes + 1, value); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (IndexOutOfBoundsException e) { + // expected + } + + buf.order(ByteOrder.BIG_ENDIAN); + } + + /** + * @tests java.nio.ByteBuffer.wrap(byte[],int,int) + */ + public void testWrappedByteBuffer_null_array() { + // Regression for HARMONY-264 + byte array[] = null; + try { + ByteBuffer.wrap(array, -1, 0); + fail("Should throw NPE"); //$NON-NLS-1$ + } catch (NullPointerException e) { + } + try { + ByteBuffer.wrap(new byte[10], Integer.MAX_VALUE, 2); + fail("Should throw IndexOutOfBoundsException"); //$NON-NLS-1$ + } catch (IndexOutOfBoundsException e) { + } + } + + private void loadTestData1(byte array[], int offset, int length) { + for (int i = 0; i < length; i++) { + array[offset + i] = (byte) i; + } + } + + private void loadTestData2(byte array[], int offset, int length) { + for (int i = 0; i < length; i++) { + array[offset + i] = (byte) (length - i); + } + } + + private void loadTestData1(ByteBuffer buf) { + buf.clear(); + for (int i = 0; i < buf.capacity(); i++) { + buf.put(i, (byte) i); + } + } + + private void loadTestData2(ByteBuffer buf) { + buf.clear(); + for (int i = 0; i < buf.capacity(); i++) { + buf.put(i, (byte) (buf.capacity() - i)); + } + } + + private void assertContentEquals(ByteBuffer buf, byte array[], + int offset, int length) { + for (int i = 0; i < length; i++) { + assertEquals(buf.get(i), array[offset + i]); + } + } + + private void assertContentEquals(ByteBuffer buf, ByteBuffer other) { + assertEquals(buf.capacity(), other.capacity()); + for (int i = 0; i < buf.capacity(); i++) { + assertEquals(buf.get(i), other.get(i)); + } + } + + private void assertContentLikeTestData1(ByteBuffer buf, + int startIndex, byte startValue, int length) { + byte value = startValue; + for (int i = 0; i < length; i++) { + assertEquals(buf.get(startIndex + i), value); + value = (byte) (value + 1); + } + } + + private int bytes2int(byte bytes[], ByteOrder order) { + int nbytes = 4, bigHead, step; + if (order == ByteOrder.BIG_ENDIAN) { + bigHead = 0; + step = 1; + } else { + bigHead = nbytes - 1; + step = -1; + } + int result = 0; + int p = bigHead; + for (int i = 0; i < nbytes; i++) { + result = result << 8; + result = result | (bytes[p] & 0xff); + p += step; + } + return result; + } + + private long bytes2long(byte bytes[], ByteOrder order) { + int nbytes = 8, bigHead, step; + if (order == ByteOrder.BIG_ENDIAN) { + bigHead = 0; + step = 1; + } else { + bigHead = nbytes - 1; + step = -1; + } + long result = 0; + int p = bigHead; + for (int i = 0; i < nbytes; i++) { + result = result << 8; + result = result | (bytes[p] & 0xff); + p += step; + } + return result; + } + + private short bytes2short(byte bytes[], ByteOrder order) { + int nbytes = 2, bigHead, step; + if (order == ByteOrder.BIG_ENDIAN) { + bigHead = 0; + step = 1; + } else { + bigHead = nbytes - 1; + step = -1; + } + short result = 0; + int p = bigHead; + for (int i = 0; i < nbytes; i++) { + result = (short) (result << 8); + result = (short) (result | (bytes[p] & 0xff)); + p += step; + } + return result; + } + + private char bytes2char(byte bytes[], ByteOrder order) { + return (char) bytes2short(bytes, order); + } + + private float bytes2float(byte bytes[], ByteOrder order) { + return Float.intBitsToFloat(bytes2int(bytes, order)); + } + + private double bytes2double(byte bytes[], ByteOrder order) { + return Double.longBitsToDouble(bytes2long(bytes, order)); + } + + private byte[] int2bytes(int value, ByteOrder order) { + int nbytes = 4, smallHead, step; + if (order == ByteOrder.BIG_ENDIAN) { + smallHead = nbytes - 1; + step = -1; + } else { + smallHead = 0; + step = 1; + } + byte bytes[] = new byte[nbytes]; + int p = smallHead; + for (int i = 0; i < nbytes; i++) { + bytes[p] = (byte) (value & 0xff); + value = value >> 8; + p += step; + } + return bytes; + } + + private byte[] long2bytes(long value, ByteOrder order) { + int nbytes = 8, smallHead, step; + if (order == ByteOrder.BIG_ENDIAN) { + smallHead = nbytes - 1; + step = -1; + } else { + smallHead = 0; + step = 1; + } + byte bytes[] = new byte[nbytes]; + int p = smallHead; + for (int i = 0; i < nbytes; i++) { + bytes[p] = (byte) (value & 0xff); + value = value >> 8; + p += step; + } + return bytes; + } + + private byte[] short2bytes(short value, ByteOrder order) { + int nbytes = 2, smallHead, step; + if (order == ByteOrder.BIG_ENDIAN) { + smallHead = nbytes - 1; + step = -1; + } else { + smallHead = 0; + step = 1; + } + byte bytes[] = new byte[nbytes]; + int p = smallHead; + for (int i = 0; i < nbytes; i++) { + bytes[p] = (byte) (value & 0xff); + value = (short) (value >> 8); + p += step; + } + return bytes; + } + + private byte[] char2bytes(char value, ByteOrder order) { + return short2bytes((short) value, order); + } + + private byte[] float2bytes(float value, ByteOrder order) { + return int2bytes(Float.floatToRawIntBits(value), order); + } + + private byte[] double2bytes(double value, ByteOrder order) { + return long2bytes(Double.doubleToRawLongBits(value), order); + } +} diff --git a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/ByteOrderTest.java b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/ByteOrderTest.java new file mode 100644 index 0000000..8f41904 --- /dev/null +++ b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/ByteOrderTest.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.nio.tests.java.nio; + +import java.nio.ByteOrder; + +import junit.framework.TestCase; + +/** + * Test java.nio.ByteOrder + * + */ +public class ByteOrderTest extends TestCase { + + public void testToString() { + assertEquals(ByteOrder.BIG_ENDIAN.toString(), "BIG_ENDIAN"); + assertEquals(ByteOrder.LITTLE_ENDIAN.toString(), "LITTLE_ENDIAN"); + } + + public void testNativeOrder() { + ByteOrder o = ByteOrder.nativeOrder(); + assertTrue(o == ByteOrder.BIG_ENDIAN || o == ByteOrder.LITTLE_ENDIAN); + } + +} 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/nio/tests/java/nio/CharBufferTest.java new file mode 100644 index 0000000..8a7c5f3 --- /dev/null +++ b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/CharBufferTest.java @@ -0,0 +1,1081 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.harmony.nio.tests.java.nio; + +import java.io.IOException; +import java.nio.BufferOverflowException; +import java.nio.BufferUnderflowException; +import java.nio.ByteOrder; +import java.nio.CharBuffer; +import java.nio.InvalidMarkException; +import java.nio.ReadOnlyBufferException; + +/** + * Tests java.nio.CharBuffer + * + */ +public class CharBufferTest extends AbstractBufferTest { + protected static final int SMALL_TEST_LENGTH = 5; + + protected static final int BUFFER_LENGTH = 20; + + protected CharBuffer buf; + + private static char[] chars = "123456789a".toCharArray(); + + protected void setUp() throws Exception{ + char[] charscopy = new char[chars.length]; + System.arraycopy(chars, 0, charscopy, 0, chars.length); + buf = CharBuffer.wrap(charscopy); + baseBuf = buf; + } + + protected void tearDown() throws Exception{ + buf = null; + baseBuf = null; + } + + public void testArray() { + char array[] = buf.array(); + assertContentEquals(buf, array, buf.arrayOffset(), buf.capacity()); + + loadTestData1(array, buf.arrayOffset(), buf.capacity()); + assertContentEquals(buf, array, buf.arrayOffset(), buf.capacity()); + + loadTestData2(array, buf.arrayOffset(), buf.capacity()); + assertContentEquals(buf, array, buf.arrayOffset(), buf.capacity()); + + loadTestData1(buf); + assertContentEquals(buf, array, buf.arrayOffset(), buf.capacity()); + + loadTestData2(buf); + assertContentEquals(buf, array, buf.arrayOffset(), buf.capacity()); + } + + public void testArrayOffset() { + char array[] = buf.array(); + assertContentEquals(buf, array, buf.arrayOffset(), buf.capacity()); + + loadTestData1(array, buf.arrayOffset(), buf.capacity()); + assertContentEquals(buf, array, buf.arrayOffset(), buf.capacity()); + + loadTestData2(array, buf.arrayOffset(), buf.capacity()); + assertContentEquals(buf, array, buf.arrayOffset(), buf.capacity()); + + loadTestData1(buf); + assertContentEquals(buf, array, buf.arrayOffset(), buf.capacity()); + + loadTestData2(buf); + assertContentEquals(buf, array, buf.arrayOffset(), buf.capacity()); + } + + public void testAsReadOnlyBuffer() { + buf.clear(); + buf.mark(); + buf.position(buf.limit()); + + // readonly's contents should be the same as buf + CharBuffer readonly = buf.asReadOnlyBuffer(); + assertNotSame(buf, readonly); + assertTrue(readonly.isReadOnly()); + assertEquals(buf.position(), readonly.position()); + assertEquals(buf.limit(), readonly.limit()); + assertEquals(buf.isDirect(), readonly.isDirect()); + assertEquals(buf.order(), readonly.order()); + assertEquals(buf.capacity(), readonly.capacity()); + assertContentEquals(buf, readonly); + + // readonly's position, mark, and limit should be independent to buf + readonly.reset(); + assertEquals(readonly.position(), 0); + readonly.clear(); + assertEquals(buf.position(), buf.limit()); + buf.reset(); + assertEquals(buf.position(), 0); + + buf.clear(); + int originalPosition = (buf.position() + buf.limit()) / 2; + buf.position(originalPosition); + buf.mark(); + buf.position(buf.limit()); + + // readonly's contents should be the same as buf + readonly = buf.asReadOnlyBuffer(); + assertNotSame(buf, readonly); + assertTrue(readonly.isReadOnly()); + assertEquals(buf.position(), readonly.position()); + assertEquals(buf.limit(), readonly.limit()); + assertEquals(buf.isDirect(), readonly.isDirect()); + assertEquals(buf.order(), readonly.order()); + assertEquals(buf.capacity(), readonly.capacity()); + assertContentEquals(buf, readonly); + + // readonly's position, mark, and limit should be independent to buf + readonly.reset(); + assertEquals(readonly.position(), originalPosition); + readonly.clear(); + assertEquals(buf.position(), buf.limit()); + buf.reset(); + assertEquals(buf.position(), originalPosition); + } + + public void testCompact() { + // case: buffer is full + buf.clear(); + buf.mark(); + loadTestData1(buf); + CharBuffer ret = buf.compact(); + assertSame(ret, buf); + assertEquals(buf.position(), buf.capacity()); + assertEquals(buf.limit(), buf.capacity()); + assertContentLikeTestData1(buf, 0, (char) 0, buf.capacity()); + try { + buf.reset(); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (InvalidMarkException e) { + // expected + } + + // case: buffer is empty + buf.position(0); + buf.limit(0); + buf.mark(); + ret = buf.compact(); + assertSame(ret, buf); + assertEquals(buf.position(), 0); + assertEquals(buf.limit(), buf.capacity()); + assertContentLikeTestData1(buf, 0, (char) 0, buf.capacity()); + try { + buf.reset(); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (InvalidMarkException e) { + // expected + } + + // case: normal + assertTrue(buf.capacity() > 5); + buf.position(1); + buf.limit(5); + buf.mark(); + ret = buf.compact(); + assertSame(ret, buf); + assertEquals(buf.position(), 4); + assertEquals(buf.limit(), buf.capacity()); + assertContentLikeTestData1(buf, 0, (char) 1, 4); + try { + buf.reset(); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (InvalidMarkException e) { + // expected + } + } + + public void testCompareTo() { + // compare to self + assertEquals(0, buf.compareTo(buf)); + + assertTrue(buf.capacity() > SMALL_TEST_LENGTH); + buf.clear(); + CharBuffer other = CharBuffer.allocate(buf.capacity()); + other.put(buf); + other.clear(); + buf.clear(); + assertEquals(0, buf.compareTo(other)); + assertEquals(0, other.compareTo(buf)); + buf.position(1); + assertTrue(buf.compareTo(other) > 0); + assertTrue(other.compareTo(buf) < 0); + other.position(2); + assertTrue(buf.compareTo(other) < 0); + assertTrue(other.compareTo(buf) > 0); + buf.position(2); + assertTrue(buf.compareTo(other) == 0); + assertTrue(other.compareTo(buf) == 0); + other.limit(SMALL_TEST_LENGTH); + assertTrue(buf.compareTo(other) > 0); + assertTrue(other.compareTo(buf) < 0); + } + + public void testDuplicate() { + // mark the position 0 + buf.clear(); + buf.mark(); + buf.position(buf.limit()); + + // duplicate's contents should be the same as buf + CharBuffer duplicate = buf.duplicate(); + assertNotSame(buf, duplicate); + assertEquals(buf.position(), duplicate.position()); + assertEquals(buf.limit(), duplicate.limit()); + assertEquals(buf.isReadOnly(), duplicate.isReadOnly()); + assertEquals(buf.isDirect(), duplicate.isDirect()); + assertEquals(buf.order(), duplicate.order()); + assertEquals(buf.capacity(), duplicate.capacity()); + assertContentEquals(buf, duplicate); + + // duplicate's position, mark, and limit should be independent to + // buf + duplicate.reset(); + assertEquals(duplicate.position(), 0); + duplicate.clear(); + assertEquals(buf.position(), buf.limit()); + buf.reset(); + assertEquals(buf.position(), 0); + + // mark another position + buf.clear(); + int originalPosition = (buf.position() + buf.limit()) / 2; + buf.position(originalPosition); + buf.mark(); + buf.position(buf.limit()); + + // duplicate's contents should be the same as buf + duplicate = buf.duplicate(); + assertNotSame(buf, duplicate); + assertEquals(buf.position(), duplicate.position()); + assertEquals(buf.limit(), duplicate.limit()); + assertEquals(buf.isReadOnly(), duplicate.isReadOnly()); + assertEquals(buf.isDirect(), duplicate.isDirect()); + assertEquals(buf.order(), duplicate.order()); + assertEquals(buf.capacity(), duplicate.capacity()); + assertContentEquals(buf, duplicate); + + // duplicate's position, mark, and limit should be independent to + // buf + duplicate.reset(); + assertEquals(duplicate.position(), originalPosition); + duplicate.clear(); + assertEquals(buf.position(), buf.limit()); + buf.reset(); + assertEquals(buf.position(), originalPosition); + + // duplicate share the same content with buf + if (!duplicate.isReadOnly()) { + loadTestData1(buf); + assertContentEquals(buf, duplicate); + loadTestData2(duplicate); + assertContentEquals(buf, duplicate); + } + } + + public void testEquals() { + // equal to self + assertTrue(buf.equals(buf)); + CharBuffer readonly = buf.asReadOnlyBuffer(); + assertTrue(buf.equals(readonly)); + CharBuffer duplicate = buf.duplicate(); + assertTrue(buf.equals(duplicate)); + + // always false, if type mismatch + assertFalse(buf.equals(Boolean.TRUE)); + + assertTrue(buf.capacity() > 5); + + buf.limit(buf.capacity()).position(0); + readonly.limit(readonly.capacity()).position(1); + assertFalse(buf.equals(readonly)); + + buf.limit(buf.capacity() - 1).position(0); + duplicate.limit(duplicate.capacity()).position(0); + assertFalse(buf.equals(duplicate)); + } + + /* + * Class under test for char get() + */ + public void testGet() { + buf.clear(); + for (int i = 0; i < buf.capacity(); i++) { + assertEquals(buf.position(), i); + assertEquals(buf.get(), buf.get(i)); + } + try { + buf.get(); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (BufferUnderflowException e) { + // expected + } + } + + /* + * Class under test for java.nio.CharBuffer get(char[]) + */ + public void testGetcharArray() { + char array[] = new char[1]; + buf.clear(); + for (int i = 0; i < buf.capacity(); i++) { + assertEquals(buf.position(), i); + CharBuffer ret = buf.get(array); + assertEquals(array[0], buf.get(i)); + assertSame(ret, buf); + } + try { + buf.get(array); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (BufferUnderflowException e) { + // expected + } + } + + /* + * Class under test for java.nio.CharBuffer get(char[], int, int) + */ + public void testGetcharArrayintint() { + buf.clear(); + char array[] = new char[buf.capacity()]; + + try { + buf.get(new char[buf.capacity() + 1], 0, buf.capacity() + 1); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (BufferUnderflowException e) { + // expected + } + assertEquals(buf.position(), 0); + try { + buf.get(array, -1, array.length); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (IndexOutOfBoundsException e) { + // expected + } + buf.get(array, array.length, 0); + try { + buf.get(array, array.length + 1, 1); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (IndexOutOfBoundsException e) { + // expected + } + assertEquals(buf.position(), 0); + try { + buf.get(array, 2, -1); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (IndexOutOfBoundsException e) { + // expected + } + try { + buf.get((char[])null, 2, -1); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (NullPointerException e) { + // expected + } + try { + buf.get(array, 2, array.length); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (IndexOutOfBoundsException e) { + // expected + } + try { + buf.get(array, 1, Integer.MAX_VALUE); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (BufferUnderflowException expected) { + } catch (IndexOutOfBoundsException expected) { + } + try { + buf.get(array, Integer.MAX_VALUE, 1); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (IndexOutOfBoundsException e) { + // expected + } + assertEquals(buf.position(), 0); + + buf.clear(); + CharBuffer ret = buf.get(array, 0, array.length); + assertEquals(buf.position(), buf.capacity()); + assertContentEquals(buf, array, 0, array.length); + assertSame(ret, buf); + } + + /* + * Class under test for char get(int) + */ + public void testGetint() { + buf.clear(); + for (int i = 0; i < buf.capacity(); i++) { + assertEquals(buf.position(), i); + assertEquals(buf.get(), buf.get(i)); + } + try { + buf.get(-1); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (IndexOutOfBoundsException e) { + // expected + } + try { + buf.get(buf.limit()); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (IndexOutOfBoundsException e) { + // expected + } + } + + public void testHashCode() { + buf.clear(); + loadTestData1(buf); + CharBuffer readonly = buf.asReadOnlyBuffer(); + CharBuffer duplicate = buf.duplicate(); + assertTrue(buf.hashCode() == readonly.hashCode()); + assertTrue(buf.capacity() > SMALL_TEST_LENGTH); + duplicate.position(buf.capacity() / 2); + assertTrue(buf.hashCode() != duplicate.hashCode()); + } + + /* + * Class under test for java.nio.CharBuffer put(char) + */ + public void testPutchar() { + buf.clear(); + for (int i = 0; i < buf.capacity(); i++) { + assertEquals(buf.position(), i); + CharBuffer ret = buf.put((char) i); + assertEquals(buf.get(i), (char) i); + assertSame(ret, buf); + } + try { + buf.put((char) 0); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (BufferOverflowException e) { + // expected + } + } + + /* + * Class under test for java.nio.CharBuffer put(char[]) + */ + public void testPutcharArray() { + char array[] = new char[1]; + + buf.clear(); + for (int i = 0; i < buf.capacity(); i++) { + assertEquals(buf.position(), i); + array[0] = (char) i; + CharBuffer ret = buf.put(array); + assertEquals(buf.get(i), (char) i); + assertSame(ret, buf); + } + try { + buf.put(array); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (BufferOverflowException e) { + // expected + } + try { + buf.put((char[]) null); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (NullPointerException e) { + // expected + } + } + + /* + * Class under test for java.nio.CharBuffer put(char[], int, int) + */ + public void testPutcharArrayintint() { + buf.clear(); + char array[] = new char[buf.capacity()]; + try { + buf.put((char[]) null, 0, 1); + fail("Should throw NullPointerException"); //$NON-NLS-1$ + } catch (NullPointerException e) { + // expected + } + try { + buf.put(new char[buf.capacity() + 1], 0, buf.capacity() + 1); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (BufferOverflowException e) { + // expected + } + assertEquals(buf.position(), 0); + try { + buf.put(array, -1, array.length); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (IndexOutOfBoundsException e) { + // expected + } + try { + buf.put(array, array.length + 1, 0); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (IndexOutOfBoundsException e) { + // expected + } + buf.put(array, array.length, 0); + assertEquals(buf.position(), 0); + try { + buf.put(array, 0, -1); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (IndexOutOfBoundsException e) { + // expected + } + try { + buf.put((char[])null, 0, -1); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (NullPointerException e) { + // expected + } + try { + buf.put(array, 2, array.length); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (IndexOutOfBoundsException e) { + // expected + } + try { + buf.put(array, Integer.MAX_VALUE, 1); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (IndexOutOfBoundsException e) { + // expected + } + try { + buf.put(array, 1, Integer.MAX_VALUE); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (BufferOverflowException expected) { + } catch (IndexOutOfBoundsException expected) { + } + assertEquals(buf.position(), 0); + + loadTestData2(array, 0, array.length); + CharBuffer ret = buf.put(array, 0, array.length); + assertEquals(buf.position(), buf.capacity()); + assertContentEquals(buf, array, 0, array.length); + assertSame(ret, buf); + } + + /* + * Class under test for java.nio.CharBuffer put(java.nio.CharBuffer) + */ + public void testPutCharBuffer() { + CharBuffer other = CharBuffer.allocate(buf.capacity()); + + try { + buf.put((CharBuffer) null); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (NullPointerException e) { + // expected + } + try { + buf.put(buf); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (IllegalArgumentException e) { + // expected + } + try { + buf.put(CharBuffer.allocate(buf.capacity() + 1)); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (BufferOverflowException e) { + // expected + } + try { + buf.flip(); + buf.put((CharBuffer)null); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (NullPointerException e) { + // expected + } + + loadTestData2(other); + other.clear(); + buf.clear(); + CharBuffer ret = buf.put(other); + assertEquals(other.position(), other.capacity()); + assertEquals(buf.position(), buf.capacity()); + assertContentEquals(other, buf); + assertSame(ret, buf); + } + + /* + * Class under test for java.nio.CharBuffer put(int, char) + */ + public void testPutintchar() { + buf.clear(); + for (int i = 0; i < buf.capacity(); i++) { + assertEquals(buf.position(), 0); + CharBuffer ret = buf.put(i, (char) i); + assertEquals(buf.get(i), (char) i); + assertSame(ret, buf); + } + try { + buf.put(-1, (char) 0); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (IndexOutOfBoundsException e) { + // expected + } + try { + buf.put(buf.limit(), (char) 0); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (IndexOutOfBoundsException e) { + // expected + } + } + + public void testSlice() { + assertTrue(buf.capacity() > 5); + buf.position(1); + buf.limit(buf.capacity() - 1); + + CharBuffer slice = buf.slice(); + assertEquals(buf.isReadOnly(), slice.isReadOnly()); + assertEquals(buf.isDirect(), slice.isDirect()); + assertEquals(buf.order(), slice.order()); + assertEquals(slice.position(), 0); + assertEquals(slice.limit(), buf.remaining()); + assertEquals(slice.capacity(), buf.remaining()); + try { + slice.reset(); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (InvalidMarkException e) { + // expected + } + + // slice share the same content with buf + if (!slice.isReadOnly()) { + loadTestData1(slice); + assertContentLikeTestData1(buf, 1, (char) 0, slice.capacity()); + buf.put(2, (char) 500); + assertEquals(slice.get(1), 500); + } + } + + public void testToString() { + String expected = ""; + for (int i = buf.position(); i < buf.limit(); i++) { + expected += buf.get(i); + } + String str = buf.toString(); + assertEquals(expected, str); + } + + public void testCharAt() { + for (int i = 0; i < buf.remaining(); i++) { + assertEquals(buf.get(buf.position() + i), buf.charAt(i)); + } + try { + buf.charAt(-1); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (IndexOutOfBoundsException e) { + // expected + } + try { + buf.charAt(buf.remaining()); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (IndexOutOfBoundsException e) { + // expected + } + } + + public void testLength() { + assertEquals(buf.length(), buf.remaining()); + } + + public void testSubSequence() { + try { + buf.subSequence(-1, buf.length()); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (IndexOutOfBoundsException e) { + // expected + } + try { + buf.subSequence(buf.length() + 1, buf.length() + 1); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (IndexOutOfBoundsException e) { + // expected + } + assertEquals(buf.subSequence(buf.length(), buf.length()).length(), 0); + try { + buf.subSequence(1, 0); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (IndexOutOfBoundsException e) { + // expected + } + try { + buf.subSequence(1, buf.length() + 1); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (IndexOutOfBoundsException e) { + // expected + } + + assertEquals(buf.subSequence(0, buf.length()).toString(), buf + .toString()); + + if (buf.length() >= 2) { + assertEquals(buf.subSequence(1, buf.length() - 1).toString(), buf + .toString().substring(1, buf.length() - 1)); + } + } + + public void testPutString() { + String str = " "; + + buf.clear(); + for (int i = 0; i < buf.capacity(); i++) { + assertEquals(buf.position(), i); + str = "" + (char) i; + CharBuffer ret = buf.put(str); + assertEquals(buf.get(i), (char) i); + assertSame(ret, buf); + } + try { + buf.put(str); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (BufferOverflowException e) { + // expected + } + try { + buf.put((String) null); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (NullPointerException e) { + // expected + } + } + + public void testPutStringintint() { + buf.clear(); + String str = String.valueOf(new char[buf.capacity()]); + + // Throw a BufferOverflowException and no character is transfered to + // CharBuffer + try { + buf.put(String.valueOf(new char[buf.capacity() + 1]), 0, buf + .capacity() + 1); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (BufferOverflowException e) { + // expected + } + try { + buf.put((String) null, 0, buf.capacity() + 1); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (NullPointerException e) { + // expected + } + assertEquals(0, buf.position()); + + buf.clear(); + try { + buf.put(str, -1, str.length()); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (IndexOutOfBoundsException e) { + // expected + } + try { + buf.put(str, str.length() + 1, str.length() + 2); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (IndexOutOfBoundsException e) { + // expected + } + try { + buf.put((String) null, -1, 0); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (NullPointerException e) { + // expected + } + buf.put(str, str.length(), str.length()); + assertEquals(buf.position(), 0); + try { + buf.put(str, 2, 1); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (IndexOutOfBoundsException e) { + // expected + } + try { + buf.put(str, 2, str.length() + 1); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (IndexOutOfBoundsException e) { + // expected + } + assertEquals(buf.position(), 0); + + char array[] = new char[buf.capacity()]; + loadTestData2(array, 0, array.length); + str = String.valueOf(array); + + CharBuffer ret = buf.put(str, 0, str.length()); + assertEquals(buf.position(), buf.capacity()); + assertContentEquals(buf, str.toCharArray(), 0, str.length()); + assertSame(ret, buf); + } + + void loadTestData1(char array[], int offset, int length) { + for (int i = 0; i < length; i++) { + array[offset + i] = (char) i; + } + } + + void loadTestData2(char array[], int offset, int length) { + for (int i = 0; i < length; i++) { + array[offset + i] = (char) (length - i); + } + } + + void loadTestData1(CharBuffer buf) { + buf.clear(); + for (int i = 0; i < buf.capacity(); i++) { + buf.put(i, (char) i); + } + } + + void loadTestData2(CharBuffer buf) { + buf.clear(); + for (int i = 0; i < buf.capacity(); i++) { + buf.put(i, (char) (buf.capacity() - i)); + } + } + + private void assertContentEquals(CharBuffer buf, char array[], int offset, + int length) { + for (int i = 0; i < length; i++) { + assertEquals(buf.get(i), array[offset + i]); + } + } + + private void assertContentEquals(CharBuffer buf, CharBuffer other) { + assertEquals(buf.capacity(), other.capacity()); + for (int i = 0; i < buf.capacity(); i++) { + assertEquals(buf.get(i), other.get(i)); + } + } + + private void assertContentLikeTestData1(CharBuffer buf, int startIndex, + char startValue, int length) { + char value = startValue; + for (int i = 0; i < length; i++) { + assertEquals(buf.get(startIndex + i), value); + value = (char) (value + 1); + } + } + + public void testAppendSelf() throws Exception { + CharBuffer cb = CharBuffer.allocate(10); + CharBuffer cb2 = cb.duplicate(); + cb.append(cb); + assertEquals(10, cb.position()); + cb.clear(); + assertEquals(cb2, cb); + + cb.put("abc"); + cb2 = cb.duplicate(); + cb.append(cb); + assertEquals(10, cb.position()); + cb.clear(); + cb2.clear(); + assertEquals(cb2, cb); + + cb.put("edfg"); + cb.clear(); + cb2 = cb.duplicate(); + cb.append(cb); + assertEquals(10, cb.position()); + cb.clear(); + cb2.clear(); + assertEquals(cb, cb2); + } + + public void testAppendOverFlow() throws IOException { + CharBuffer cb = CharBuffer.allocate(1); + CharSequence cs = "String"; + cb.put('A'); + try { + cb.append('C'); + fail("should throw BufferOverflowException."); + } catch (BufferOverflowException ex) { + // expected; + } + try { + cb.append(cs); + fail("should throw BufferOverflowException."); + } catch (BufferOverflowException ex) { + // expected; + } + try { + cb.append(cs, 1, 2); + fail("should throw BufferOverflowException."); + } catch (BufferOverflowException ex) { + // expected; + } + } + + public void testReadOnlyMap() throws IOException { + CharBuffer cb = CharBuffer.wrap("ABCDE").asReadOnlyBuffer(); + CharSequence cs = "String"; + try { + cb.append('A'); + fail("should throw ReadOnlyBufferException."); + } catch (ReadOnlyBufferException ex) { + // expected; + } + try { + cb.append(cs); + fail("should throw ReadOnlyBufferException."); + } catch (ReadOnlyBufferException ex) { + // expected; + } + try { + cb.append(cs, 1, 2); + fail("should throw ReadOnlyBufferException."); + } catch (ReadOnlyBufferException ex) { + // expected; + } + cb.append(cs, 1, 1); + } + + public void testAppendCNormal() throws IOException { + CharBuffer cb = CharBuffer.allocate(2); + cb.put('A'); + assertSame(cb, cb.append('B')); + assertEquals('B', cb.get(1)); + } + + public void testAppendCharSequenceNormal() throws IOException { + CharBuffer cb = CharBuffer.allocate(10); + cb.put('A'); + assertSame(cb, cb.append("String")); + assertEquals("AString", cb.flip().toString()); + cb.append(null); + assertEquals("null", cb.flip().toString()); + } + + public void testAppendCharSequenceIINormal() throws IOException { + CharBuffer cb = CharBuffer.allocate(10); + cb.put('A'); + assertSame(cb, cb.append("String", 1, 3)); + assertEquals("Atr", cb.flip().toString()); + + cb.append(null, 0, 1); + assertEquals("n", cb.flip().toString()); + } + + public void testAppendCharSequenceII_IllegalArgument() throws IOException { + CharBuffer cb = CharBuffer.allocate(10); + cb.append("String", 0, 0); + cb.append("String", 2, 2); + try { + cb.append("String", -1, 1); + fail("should throw IndexOutOfBoundsException."); + } catch (IndexOutOfBoundsException ex) { + // expected; + } + try { + cb.append("String", -1, -1); + fail("should throw IndexOutOfBoundsException."); + } catch (IndexOutOfBoundsException ex) { + // expected; + } + try { + cb.append("String", 3, 2); + fail("should throw IndexOutOfBoundsException."); + } catch (IndexOutOfBoundsException ex) { + // expected; + } + try { + cb.append("String", 3, 0); + fail("should throw IndexOutOfBoundsException."); + } catch (IndexOutOfBoundsException ex) { + // expected; + } + try { + cb.append("String", 3, 110); + fail("should throw IndexOutOfBoundsException."); + } catch (IndexOutOfBoundsException ex) { + // expected; + } + } + + public void testReadCharBuffer() throws IOException { + CharBuffer source = CharBuffer.wrap("String"); + CharBuffer target = CharBuffer.allocate(10); + assertEquals(6, source.read(target)); + assertEquals("String", target.flip().toString()); + // return -1 when nothing to read + assertEquals(-1, source.read(target)); + // NullPointerException + try { + assertEquals(-1, source.read(null)); + fail("should throw NullPointerException."); + } catch (NullPointerException ex) { + // expected; + } + + } + + public void testReadReadOnly() throws IOException { + CharBuffer source = CharBuffer.wrap("String"); + CharBuffer target = CharBuffer.allocate(10).asReadOnlyBuffer(); + try { + source.read(target); + fail("should throw ReadOnlyBufferException."); + } catch (ReadOnlyBufferException ex) { + // expected; + } + // if target has no remaining, needn't to check the isReadOnly + target.flip(); + assertEquals(0, source.read(target)); + } + + public void testReadOverflow() throws IOException { + CharBuffer source = CharBuffer.wrap("String"); + CharBuffer target = CharBuffer.allocate(1); + assertEquals(1, source.read(target)); + assertEquals("S", target.flip().toString()); + assertEquals(1, source.position()); + } + + public void testReadSelf() throws Exception { + CharBuffer source = CharBuffer.wrap("abuffer"); + try { + source.read(source); + fail("should throw IAE."); + } catch (IllegalArgumentException e) { + //expected + } + } + + public void testRead_scenario1() throws Exception { + char[] charArray = new char[] { 'a', 'b' }; + CharBuffer charBuffer = CharBuffer.wrap(charArray); + try { + charBuffer.read(charBuffer); + fail("should throw IllegalArgumentException"); + } catch (IllegalArgumentException e) { + // expected + } + charBuffer.put(charArray); + assertEquals(-1, charBuffer.read(charBuffer)); + } + + public void testRead_scenario2() throws Exception { + CharBuffer charBufferA = CharBuffer.allocate(0); + CharBuffer allocateBuffer = CharBuffer.allocate(1); + CharBuffer charBufferB = CharBuffer.wrap(allocateBuffer); + assertEquals(-1, charBufferA.read(charBufferB)); + + allocateBuffer.append(allocateBuffer); + charBufferB = CharBuffer.wrap(allocateBuffer); + assertEquals(-1, charBufferA.read(charBufferB)); + } + + public void testIsDirect() { + assertFalse(buf.isDirect()); + } + + public void testHasArray() { + assertTrue(buf.hasArray()); + } + + public void testOrder() { + assertEquals(ByteOrder.nativeOrder(), buf.order()); + } + + public void testIsReadOnly() { + assertFalse(buf.isReadOnly()); + } +} 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/nio/tests/java/nio/DirectByteBufferTest.java new file mode 100644 index 0000000..f274676 --- /dev/null +++ b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/DirectByteBufferTest.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.nio.tests.java.nio; + +import java.nio.ByteBuffer; + +public class DirectByteBufferTest extends ByteBufferTest { + + protected void setUp() throws Exception { + super.setUp(); + buf = ByteBuffer.allocateDirect(BUFFER_LENGTH); + baseBuf = buf; + } + + protected void tearDown() throws Exception { + super.tearDown(); + buf = null; + baseBuf = null; + } + + /** + * @tests java.nio.ByteBuffer#allocateDirect(int) + * + */ + public void testAllocatedByteBuffer_IllegalArg() { + try { + ByteBuffer.allocateDirect(-1); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (IllegalArgumentException e) { + // expected + } + } + + public void testIsDirect() { + assertTrue(buf.isDirect()); + } + + public void testHasArray() { + // Android direct byte buffers have backing arrays. + assertTrue(buf.hasArray()); + // assertFalse(buf.hasArray()); + } + + public void testIsReadOnly() { + assertFalse(buf.isReadOnly()); + } +} 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/nio/tests/java/nio/DirectCharBufferTest.java new file mode 100644 index 0000000..83cfc9d --- /dev/null +++ b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/DirectCharBufferTest.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.nio.tests.java.nio; + +import java.nio.ByteBuffer; +import java.nio.ByteOrder; + +public class DirectCharBufferTest extends CharBufferTest { + + public void setUp(){ + buf = ByteBuffer.allocateDirect(BUFFER_LENGTH*2).asCharBuffer(); + super.loadTestData1(buf); + baseBuf = buf; + } + + public void tearDown(){ + buf = null; + baseBuf = null; + } + + public void testHasArray() { + assertFalse(buf.hasArray()); + } + + public void testArray() { + try { + buf.array(); + fail("Should throw UnsupportedOperationException"); //$NON-NLS-1$ + } catch (UnsupportedOperationException e) { + } + } + + public void testArrayOffset() { + try { + buf.arrayOffset(); + fail("Should throw UnsupportedOperationException"); //$NON-NLS-1$ + } catch (UnsupportedOperationException e) { + } + } + + public void testIsDirect() { + assertTrue(buf.isDirect()); + } + + public void testOrder() { + assertEquals(ByteOrder.BIG_ENDIAN, buf.order()); + } +} 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/nio/tests/java/nio/DirectDoubleBufferTest.java new file mode 100644 index 0000000..561c0fa --- /dev/null +++ b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/DirectDoubleBufferTest.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.nio.tests.java.nio; + +import java.nio.ByteBuffer; +import java.nio.ByteOrder; + +public class DirectDoubleBufferTest extends DoubleBufferTest { + public void setUp(){ + buf = ByteBuffer.allocateDirect(BUFFER_LENGTH*8).asDoubleBuffer(); + loadTestData1(buf); + baseBuf = buf; + } + + public void tearDown(){ + buf = null; + baseBuf = null; + } + + public void testHasArray() { + assertFalse(buf.hasArray()); + } + + public void testArray() { + try { + buf.array(); + fail("Should throw UnsupportedOperationException"); //$NON-NLS-1$ + } catch (UnsupportedOperationException e) { + } + } + + public void testArrayOffset() { + try { + buf.arrayOffset(); + fail("Should throw UnsupportedOperationException"); //$NON-NLS-1$ + } catch (UnsupportedOperationException e) { + } + } + + public void testIsDirect() { + assertTrue(buf.isDirect()); + } + + public void testOrder() { + assertEquals(ByteOrder.BIG_ENDIAN, buf.order()); + } +} 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/nio/tests/java/nio/DirectFloatBufferTest.java new file mode 100644 index 0000000..8739c1b --- /dev/null +++ b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/DirectFloatBufferTest.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.nio.tests.java.nio; + +import java.nio.ByteBuffer; +import java.nio.ByteOrder; + +public class DirectFloatBufferTest extends FloatBufferTest { + public void setUp(){ + buf = ByteBuffer.allocateDirect(BUFFER_LENGTH*4).asFloatBuffer(); + loadTestData1(buf); + baseBuf = buf; + } + + public void tearDown(){ + buf = null; + baseBuf = null; + } + + public void testHasArray() { + assertFalse(buf.hasArray()); + } + + public void testArray() { + try { + buf.array(); + fail("Should throw UnsupportedOperationException"); //$NON-NLS-1$ + } catch (UnsupportedOperationException e) { + } + } + + public void testArrayOffset() { + try { + buf.arrayOffset(); + fail("Should throw UnsupportedOperationException"); //$NON-NLS-1$ + } catch (UnsupportedOperationException e) { + //expected + } + } + + public void testIsDirect() { + assertTrue(buf.isDirect()); + } + + public void testOrder() { + assertEquals(ByteOrder.BIG_ENDIAN, buf.order()); + } +} 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/nio/tests/java/nio/DirectIntBufferTest.java new file mode 100644 index 0000000..393366e --- /dev/null +++ b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/DirectIntBufferTest.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.nio.tests.java.nio; + +import java.nio.ByteBuffer; +import java.nio.ByteOrder; + +public class DirectIntBufferTest extends IntBufferTest { + public void setUp(){ + buf = ByteBuffer.allocateDirect(BUFFER_LENGTH*4).asIntBuffer(); + loadTestData1(buf); + baseBuf = buf; + } + + public void tearDown(){ + buf = null; + baseBuf = null; + } + + public void testHasArray() { + assertFalse(buf.hasArray()); + } + + public void testArray() { + try { + buf.array(); + fail("Should throw UnsupportedOperationException"); //$NON-NLS-1$ + } catch (UnsupportedOperationException e) { + } + } + + public void testArrayOffset() { + try { + buf.arrayOffset(); + fail("Should throw UnsupportedOperationException"); //$NON-NLS-1$ + } catch (UnsupportedOperationException e) { + //expected + } + } + + public void testIsDirect() { + assertTrue(buf.isDirect()); + } + + public void testOrder() { + assertEquals(ByteOrder.BIG_ENDIAN, buf.order()); + } +} 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/nio/tests/java/nio/DirectLongBufferTest.java new file mode 100644 index 0000000..245cd25 --- /dev/null +++ b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/DirectLongBufferTest.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.nio.tests.java.nio; + +import java.nio.ByteBuffer; +import java.nio.ByteOrder; + + +public class DirectLongBufferTest extends LongBufferTest { + public void setUp(){ + buf = ByteBuffer.allocateDirect(BUFFER_LENGTH*8).asLongBuffer(); + loadTestData1(buf); + baseBuf = buf; + } + + public void tearDown(){ + buf = null; + baseBuf = null; + } + + public void testHasArray() { + assertFalse(buf.hasArray()); + } + + public void testArray() { + try { + buf.array(); + fail("Should throw UnsupportedOperationException"); //$NON-NLS-1$ + } catch (UnsupportedOperationException e) { + } + } + + public void testArrayOffset() { + try { + buf.arrayOffset(); + fail("Should throw UnsupportedOperationException"); //$NON-NLS-1$ + } catch (UnsupportedOperationException e) { + //expected + } + } + + public void testIsDirect() { + assertTrue(buf.isDirect()); + } + + public void testOrder() { + assertEquals(ByteOrder.BIG_ENDIAN, buf.order()); + } +} 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/nio/tests/java/nio/DirectShortBufferTest.java new file mode 100644 index 0000000..9ae290a --- /dev/null +++ b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/DirectShortBufferTest.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.nio.tests.java.nio; + +import java.nio.ByteBuffer; +import java.nio.ByteOrder; + +public class DirectShortBufferTest extends ShortBufferTest { + public void setUp(){ + buf = ByteBuffer.allocateDirect(BUFFER_LENGTH*2).asShortBuffer(); + loadTestData1(buf); + baseBuf = buf; + } + + public void tearDown(){ + buf = null; + baseBuf = null; + } + + public void testHasArray() { + assertFalse(buf.hasArray()); + } + + public void testArray() { + try { + buf.array(); + fail("Should throw UnsupportedOperationException"); //$NON-NLS-1$ + } catch (UnsupportedOperationException e) { + } + } + + public void testArrayOffset() { + try { + buf.arrayOffset(); + fail("Should throw UnsupportedOperationException"); //$NON-NLS-1$ + } catch (UnsupportedOperationException e) { + //expected + } + } + + public void testIsDirect() { + assertTrue(buf.isDirect()); + } + + public void testOrder() { + assertEquals(ByteOrder.BIG_ENDIAN, buf.order()); + } +} 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/nio/tests/java/nio/DoubleBufferTest.java new file mode 100644 index 0000000..40ff2e0 --- /dev/null +++ b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/DoubleBufferTest.java @@ -0,0 +1,664 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.harmony.nio.tests.java.nio; + +import java.nio.BufferOverflowException; +import java.nio.BufferUnderflowException; +import java.nio.ByteBuffer; +import java.nio.ByteOrder; +import java.nio.DoubleBuffer; +import java.nio.InvalidMarkException; + +/** + * Tests java.nio.DoubleBuffer + */ +public class DoubleBufferTest extends AbstractBufferTest { + + protected static final int SMALL_TEST_LENGTH = 5; + + protected static final int BUFFER_LENGTH = 20; + + protected DoubleBuffer buf; + + protected void setUp() throws Exception { + buf = DoubleBuffer.allocate(BUFFER_LENGTH); + loadTestData1(buf); + baseBuf = buf; + } + + protected void tearDown() throws Exception { + buf = null; + baseBuf = null; + } + + /* + * Test with bit sequences that represent the IEEE754 doubles Positive + * infinity, negative infinity, and NaN. + */ + public void testNaNs() { + long[] nans = new long[] { 0x7ff0000000000000L, 0xfff0000000000000L, + 0x7ff8000000000000L }; + for (int i = 0; i < nans.length; i++) { + long longBitsIn = nans[i]; + double dbl = Double.longBitsToDouble(longBitsIn); + long longBitsOut = Double.doubleToRawLongBits(dbl); + // Sanity check + assertTrue(longBitsIn == longBitsOut); + + // Store the double and retrieve it + ByteBuffer buffer = ByteBuffer.allocate(8); + buffer.putDouble(dbl); + double bufDoubleOut = buffer.getDouble(0); + + // Check the bits sequence was not normalized + long bufLongOut = Double.doubleToRawLongBits(bufDoubleOut); + assertTrue(longBitsIn == bufLongOut); + } + } + + public void testArray() { + double array[] = buf.array(); + assertContentEquals(buf, array, buf.arrayOffset(), buf.capacity()); + + loadTestData1(array, buf.arrayOffset(), buf.capacity()); + assertContentEquals(buf, array, buf.arrayOffset(), buf.capacity()); + + loadTestData2(array, buf.arrayOffset(), buf.capacity()); + assertContentEquals(buf, array, buf.arrayOffset(), buf.capacity()); + + loadTestData1(buf); + assertContentEquals(buf, array, buf.arrayOffset(), buf.capacity()); + + loadTestData2(buf); + assertContentEquals(buf, array, buf.arrayOffset(), buf.capacity()); + } + + public void testArrayOffset() { + double array[] = buf.array(); + assertContentEquals(buf, array, buf.arrayOffset(), buf.capacity()); + + loadTestData1(array, buf.arrayOffset(), buf.capacity()); + assertContentEquals(buf, array, buf.arrayOffset(), buf.capacity()); + + loadTestData2(array, buf.arrayOffset(), buf.capacity()); + assertContentEquals(buf, array, buf.arrayOffset(), buf.capacity()); + + loadTestData1(buf); + assertContentEquals(buf, array, buf.arrayOffset(), buf.capacity()); + + loadTestData2(buf); + assertContentEquals(buf, array, buf.arrayOffset(), buf.capacity()); + } + + public void testAsReadOnlyBuffer() { + buf.clear(); + buf.mark(); + buf.position(buf.limit()); + + // readonly's contents should be the same as buf + DoubleBuffer readonly = buf.asReadOnlyBuffer(); + assertNotSame(buf, readonly); + assertTrue(readonly.isReadOnly()); + assertEquals(buf.position(), readonly.position()); + assertEquals(buf.limit(), readonly.limit()); + assertEquals(buf.isDirect(), readonly.isDirect()); + assertEquals(buf.order(), readonly.order()); + assertContentEquals(buf, readonly); + + // readonly's position, mark, and limit should be independent to buf + readonly.reset(); + assertEquals(readonly.position(), 0); + readonly.clear(); + assertEquals(buf.position(), buf.limit()); + buf.reset(); + assertEquals(buf.position(), 0); + } + + public void testCompact() { + // case: buffer is full + buf.clear(); + buf.mark(); + loadTestData1(buf); + DoubleBuffer ret = buf.compact(); + assertSame(ret, buf); + assertEquals(buf.position(), buf.capacity()); + assertEquals(buf.limit(), buf.capacity()); + assertContentLikeTestData1(buf, 0, 0.0, buf.capacity()); + try { + buf.reset(); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (InvalidMarkException e) { + // expected + } + + // case: buffer is empty + buf.position(0); + buf.limit(0); + buf.mark(); + ret = buf.compact(); + assertSame(ret, buf); + assertEquals(buf.position(), 0); + assertEquals(buf.limit(), buf.capacity()); + assertContentLikeTestData1(buf, 0, 0.0, buf.capacity()); + try { + buf.reset(); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (InvalidMarkException e) { + // expected + } + + // case: normal + assertTrue(buf.capacity() > 5); + buf.position(1); + buf.limit(5); + buf.mark(); + ret = buf.compact(); + assertSame(ret, buf); + assertEquals(buf.position(), 4); + assertEquals(buf.limit(), buf.capacity()); + assertContentLikeTestData1(buf, 0, 1.0, 4); + try { + buf.reset(); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (InvalidMarkException e) { + // expected + } + } + + public void testCompareTo() { + DoubleBuffer other = DoubleBuffer.allocate(buf.capacity()); + loadTestData1(other); + assertEquals(0, buf.compareTo(other)); + assertEquals(0, other.compareTo(buf)); + buf.position(1); + assertTrue(buf.compareTo(other) > 0); + assertTrue(other.compareTo(buf) < 0); + other.position(2); + assertTrue(buf.compareTo(other) < 0); + assertTrue(other.compareTo(buf) > 0); + buf.position(2); + other.limit(5); + assertTrue(buf.compareTo(other) > 0); + assertTrue(other.compareTo(buf) < 0); + + DoubleBuffer dbuffer1 = DoubleBuffer.wrap(new double[] { Double.NaN }); + DoubleBuffer dbuffer2 = DoubleBuffer.wrap(new double[] { Double.NaN }); + DoubleBuffer dbuffer3 = DoubleBuffer.wrap(new double[] { 42d }); + + assertEquals("Failed equal comparison with NaN entry", 0, dbuffer1 + .compareTo(dbuffer2)); + assertEquals("Failed greater than comparison with NaN entry", 1, dbuffer3 + .compareTo(dbuffer1)); + assertEquals("Failed greater than comparison with NaN entry", 1, dbuffer1 + .compareTo(dbuffer3)); + } + + public void testDuplicate() { + buf.clear(); + buf.mark(); + buf.position(buf.limit()); + + // duplicate's contents should be the same as buf + DoubleBuffer duplicate = buf.duplicate(); + assertNotSame(buf, duplicate); + assertEquals(buf.position(), duplicate.position()); + assertEquals(buf.limit(), duplicate.limit()); + assertEquals(buf.isReadOnly(), duplicate.isReadOnly()); + assertEquals(buf.isDirect(), duplicate.isDirect()); + assertEquals(buf.order(), duplicate.order()); + assertContentEquals(buf, duplicate); + + // duplicate's position, mark, and limit should be independent to buf + duplicate.reset(); + assertEquals(duplicate.position(), 0); + duplicate.clear(); + assertEquals(buf.position(), buf.limit()); + buf.reset(); + assertEquals(buf.position(), 0); + + // duplicate share the same content with buf + // FIXME + if (!duplicate.isReadOnly()) { + loadTestData1(buf); + assertContentEquals(buf, duplicate); + loadTestData2(duplicate); + assertContentEquals(buf, duplicate); + } + } + + public void testEquals() { + // equal to self + assertTrue(buf.equals(buf)); + DoubleBuffer readonly = buf.asReadOnlyBuffer(); + assertTrue(buf.equals(readonly)); + DoubleBuffer duplicate = buf.duplicate(); + assertTrue(buf.equals(duplicate)); + + // always false, if type mismatch + assertFalse(buf.equals(Boolean.TRUE)); + + assertTrue(buf.capacity() > 5); + + buf.limit(buf.capacity()).position(0); + readonly.limit(readonly.capacity()).position(1); + assertFalse(buf.equals(readonly)); + + buf.limit(buf.capacity() - 1).position(0); + duplicate.limit(duplicate.capacity()).position(0); + assertFalse(buf.equals(duplicate)); + } + + /* + * Class under test for double get() + */ + public void testGet() { + buf.clear(); + for (int i = 0; i < buf.capacity(); i++) { + assertEquals(buf.position(), i); + assertEquals(buf.get(), buf.get(i), 0.01); + } + try { + buf.get(); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (BufferUnderflowException e) { + // expected + } + } + + /* + * Class under test for java.nio.DoubleBuffer get(double[]) + */ + public void testGetdoubleArray() { + double array[] = new double[1]; + buf.clear(); + for (int i = 0; i < buf.capacity(); i++) { + assertEquals(buf.position(), i); + DoubleBuffer ret = buf.get(array); + assertEquals(array[0], buf.get(i), 0.01); + assertSame(ret, buf); + } + try { + buf.get(array); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (BufferUnderflowException e) { + // expected + } + } + + /* + * Class under test for java.nio.DoubleBuffer get(double[], int, int) + */ + public void testGetdoubleArrayintint() { + buf.clear(); + double array[] = new double[buf.capacity()]; + + try { + buf.get(new double[buf.capacity() + 1], 0, buf.capacity() + 1); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (BufferUnderflowException e) { + // expected + } + assertEquals(buf.position(), 0); + try { + buf.get(array, -1, array.length); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (IndexOutOfBoundsException e) { + // expected + } + buf.get(array, array.length, 0); + try { + buf.get(array, array.length + 1, 1); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (IndexOutOfBoundsException e) { + // expected + } + assertEquals(buf.position(), 0); + try { + buf.get(array, 2, -1); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (IndexOutOfBoundsException e) { + // expected + } + try { + buf.get((double[])null, 0, -1); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (NullPointerException e) { + // expected + } + try { + buf.get(array, 2, array.length); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (IndexOutOfBoundsException e) { + // expected + } + try { + buf.get(array, 1, Integer.MAX_VALUE); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (BufferUnderflowException expected) { + } catch (IndexOutOfBoundsException expected) { + } + try { + buf.get(array, Integer.MAX_VALUE, 1); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (IndexOutOfBoundsException e) { + // expected + } + assertEquals(buf.position(), 0); + + buf.clear(); + DoubleBuffer ret = buf.get(array, 0, array.length); + assertEquals(buf.position(), buf.capacity()); + assertContentEquals(buf, array, 0, array.length); + assertSame(ret, buf); + } + + /* + * Class under test for double get(int) + */ + public void testGetint() { + buf.clear(); + for (int i = 0; i < buf.capacity(); i++) { + assertEquals(buf.position(), i); + assertEquals(buf.get(), buf.get(i), 0.01); + } + try { + buf.get(-1); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (IndexOutOfBoundsException e) { + // expected + } + try { + buf.get(buf.limit()); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (IndexOutOfBoundsException e) { + // expected + } + } + + public void testHasArray() { + assertTrue(buf.hasArray()); + } + + public void testHashCode() { + buf.clear(); + DoubleBuffer readonly = buf.asReadOnlyBuffer(); + DoubleBuffer duplicate = buf.duplicate(); + assertTrue(buf.hashCode() == readonly.hashCode()); + + assertTrue(buf.capacity() > 5); + duplicate.position(buf.capacity() / 2); + assertTrue(buf.hashCode() != duplicate.hashCode()); + } + + public void testIsDirect() { + assertFalse(buf.isDirect()); + } + + public void testOrder() { + assertEquals(ByteOrder.nativeOrder(), buf.order()); + } + + /* + * Class under test for java.nio.DoubleBuffer put(double) + */ + public void testPutdouble() { + + buf.clear(); + for (int i = 0; i < buf.capacity(); i++) { + assertEquals(buf.position(), i); + DoubleBuffer ret = buf.put((double) i); + assertEquals(buf.get(i), (double) i, 0.0); + assertSame(ret, buf); + } + try { + buf.put(0); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (BufferOverflowException e) { + // expected + } + } + + /* + * Class under test for java.nio.DoubleBuffer put(double[]) + */ + public void testPutdoubleArray() { + double array[] = new double[1]; + + buf.clear(); + for (int i = 0; i < buf.capacity(); i++) { + assertEquals(buf.position(), i); + array[0] = (double) i; + DoubleBuffer ret = buf.put(array); + assertEquals(buf.get(i), (double) i, 0.0); + assertSame(ret, buf); + } + try { + buf.put(array); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (BufferOverflowException e) { + // expected + } + } + + /* + * Class under test for java.nio.DoubleBuffer put(double[], int, int) + */ + public void testPutdoubleArrayintint() { + buf.clear(); + double array[] = new double[buf.capacity()]; + + try { + buf.put(new double[buf.capacity() + 1], 0, buf.capacity() + 1); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (BufferOverflowException e) { + // expected + } + assertEquals(buf.position(), 0); + try { + buf.put(array, -1, array.length); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (IndexOutOfBoundsException e) { + // expected + } + try { + buf.put(array, array.length + 1, 0); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (IndexOutOfBoundsException e) { + // expected + } + buf.put(array, array.length, 0); + assertEquals(buf.position(), 0); + try { + buf.put(array, 0, -1); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (IndexOutOfBoundsException e) { + // expected + } + try { + buf.put((double[])null, 0, -1); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (NullPointerException e) { + // expected + } + try { + buf.put(array, 2, array.length); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (IndexOutOfBoundsException e) { + // expected + } + try { + buf.put(array, Integer.MAX_VALUE, 1); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (IndexOutOfBoundsException e) { + // expected + } + try { + buf.put(array, 1, Integer.MAX_VALUE); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (BufferOverflowException expected) { + } catch (IndexOutOfBoundsException expected) { + } + assertEquals(buf.position(), 0); + + loadTestData2(array, 0, array.length); + DoubleBuffer ret = buf.put(array, 0, array.length); + assertEquals(buf.position(), buf.capacity()); + assertContentEquals(buf, array, 0, array.length); + assertSame(ret, buf); + } + + /* + * Class under test for java.nio.DoubleBuffer put(java.nio.DoubleBuffer) + */ + public void testPutDoubleBuffer() { + DoubleBuffer other = DoubleBuffer.allocate(buf.capacity()); + + try { + buf.put(buf); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (IllegalArgumentException e) { + // expected + } + try { + buf.put(DoubleBuffer.allocate(buf.capacity() + 1)); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (BufferOverflowException e) { + // expected + } + + loadTestData2(other); + other.clear(); + buf.clear(); + DoubleBuffer ret = buf.put(other); + assertEquals(other.position(), other.capacity()); + assertEquals(buf.position(), buf.capacity()); + assertContentEquals(other, buf); + assertSame(ret, buf); + } + + /* + * Class under test for java.nio.DoubleBuffer put(int, double) + */ + public void testPutintdouble() { + buf.clear(); + for (int i = 0; i < buf.capacity(); i++) { + assertEquals(buf.position(), 0); + DoubleBuffer ret = buf.put(i, (double) i); + assertEquals(buf.get(i), (double) i, 0.0); + assertSame(ret, buf); + } + try { + buf.put(-1, 0); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (IndexOutOfBoundsException e) { + // expected + } + try { + buf.put(buf.limit(), 0); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (IndexOutOfBoundsException e) { + // expected + } + } + + public void testSlice() { + assertTrue(buf.capacity() > 5); + buf.position(1); + buf.limit(buf.capacity() - 1); + + DoubleBuffer slice = buf.slice(); + assertEquals(buf.isReadOnly(), slice.isReadOnly()); + assertEquals(buf.isDirect(), slice.isDirect()); + assertEquals(buf.order(), slice.order()); + assertEquals(slice.position(), 0); + assertEquals(slice.limit(), buf.remaining()); + assertEquals(slice.capacity(), buf.remaining()); + try { + slice.reset(); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (InvalidMarkException e) { + // expected + } + + // slice share the same content with buf + // FIXME: + if (!slice.isReadOnly()) { + loadTestData1(slice); + assertContentLikeTestData1(buf, 1, 0, slice.capacity()); + buf.put(2, 500); + assertEquals(slice.get(1), 500, 0.0); + } + } + + public void testToString() { + String str = buf.toString(); + assertTrue(str.indexOf("Double") >= 0 || str.indexOf("double") >= 0); + assertTrue(str.indexOf("" + buf.position()) >= 0); + assertTrue(str.indexOf("" + buf.limit()) >= 0); + assertTrue(str.indexOf("" + buf.capacity()) >= 0); + } + + void loadTestData1(double array[], int offset, int length) { + for (int i = 0; i < length; i++) { + array[offset + i] = (double) i; + } + } + + void loadTestData2(double array[], int offset, int length) { + for (int i = 0; i < length; i++) { + array[offset + i] = (double) length - i; + } + } + + void loadTestData1(DoubleBuffer buf) { + buf.clear(); + for (int i = 0; i < buf.capacity(); i++) { + buf.put(i, (double) i); + } + } + + void loadTestData2(DoubleBuffer buf) { + buf.clear(); + for (int i = 0; i < buf.capacity(); i++) { + buf.put(i, (double) buf.capacity() - i); + } + } + + private void assertContentEquals(DoubleBuffer buf, double array[], + int offset, int length) { + for (int i = 0; i < length; i++) { + assertEquals(buf.get(i), array[offset + i], 0.01); + } + } + + private void assertContentEquals(DoubleBuffer buf, DoubleBuffer other) { + assertEquals(buf.capacity(), other.capacity()); + for (int i = 0; i < buf.capacity(); i++) { + assertEquals(buf.get(i), other.get(i), 0.01); + } + } + + private void assertContentLikeTestData1(DoubleBuffer buf, int startIndex, + double startValue, int length) { + double value = startValue; + for (int i = 0; i < length; i++) { + assertEquals(buf.get(startIndex + i), value, 0.01); + value = value + 1.0; + } + } +} diff --git a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/DuplicateDirectByteBufferTest.java b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/DuplicateDirectByteBufferTest.java new file mode 100644 index 0000000..656241a --- /dev/null +++ b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/DuplicateDirectByteBufferTest.java @@ -0,0 +1,31 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.harmony.nio.tests.java.nio; + + +public class DuplicateDirectByteBufferTest extends DirectByteBufferTest { + + protected void setUp() throws Exception { + super.setUp(); + buf = buf.duplicate(); + baseBuf = buf; + } + + protected void tearDown() throws Exception { + super.tearDown(); + } +} diff --git a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/DuplicateHeapByteBufferTest.java b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/DuplicateHeapByteBufferTest.java new file mode 100644 index 0000000..9f44d7a --- /dev/null +++ b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/DuplicateHeapByteBufferTest.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.nio.tests.java.nio; + + +public class DuplicateHeapByteBufferTest extends HeapByteBufferTest { + + protected void setUp() throws Exception { + super.setUp(); + buf = buf.duplicate(); + baseBuf = buf; + } + + protected void tearDown() throws Exception { + super.tearDown(); + } + +} diff --git a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/DuplicateWrappedByteBufferTest.java b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/DuplicateWrappedByteBufferTest.java new file mode 100644 index 0000000..2796b88 --- /dev/null +++ b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/DuplicateWrappedByteBufferTest.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.nio.tests.java.nio; + + +public class DuplicateWrappedByteBufferTest extends WrappedByteBufferTest { + + protected void setUp() throws Exception { + super.setUp(); + buf = buf.duplicate(); + baseBuf = buf; + } + + protected void tearDown() throws Exception { + super.tearDown(); + } + +} diff --git a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/FloatBufferTest.java b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/FloatBufferTest.java new file mode 100644 index 0000000..cfef096 --- /dev/null +++ b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/FloatBufferTest.java @@ -0,0 +1,674 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.harmony.nio.tests.java.nio; + +import java.nio.BufferOverflowException; +import java.nio.BufferUnderflowException; +import java.nio.ByteOrder; +import java.nio.DoubleBuffer; +import java.nio.FloatBuffer; +import java.nio.InvalidMarkException; + +/** + * Tests java.nio.FloatBuffer + * + */ +public class FloatBufferTest extends AbstractBufferTest { + + protected static final int SMALL_TEST_LENGTH = 5; + + protected static final int BUFFER_LENGTH = 20; + + protected FloatBuffer buf; + + protected void setUp() throws Exception { + buf = FloatBuffer.allocate(BUFFER_LENGTH); + loadTestData1(buf); + baseBuf = buf; + } + + protected void tearDown() throws Exception { + buf = null; + baseBuf = null; + } + + public void testArray() { + float array[] = buf.array(); + assertContentEquals(buf, array, buf.arrayOffset(), buf.capacity()); + + loadTestData1(array, buf.arrayOffset(), buf.capacity()); + assertContentEquals(buf, array, buf.arrayOffset(), buf.capacity()); + + loadTestData2(array, buf.arrayOffset(), buf.capacity()); + assertContentEquals(buf, array, buf.arrayOffset(), buf.capacity()); + + loadTestData1(buf); + assertContentEquals(buf, array, buf.arrayOffset(), buf.capacity()); + + loadTestData2(buf); + assertContentEquals(buf, array, buf.arrayOffset(), buf.capacity()); + } + + public void testArrayOffset() { + float array[] = buf.array(); + assertContentEquals(buf, array, buf.arrayOffset(), buf.capacity()); + + loadTestData1(array, buf.arrayOffset(), buf.capacity()); + assertContentEquals(buf, array, buf.arrayOffset(), buf.capacity()); + + loadTestData2(array, buf.arrayOffset(), buf.capacity()); + assertContentEquals(buf, array, buf.arrayOffset(), buf.capacity()); + + loadTestData1(buf); + assertContentEquals(buf, array, buf.arrayOffset(), buf.capacity()); + + loadTestData2(buf); + assertContentEquals(buf, array, buf.arrayOffset(), buf.capacity()); + } + + public void testAsReadOnlyBuffer() { + buf.clear(); + buf.mark(); + buf.position(buf.limit()); + + // readonly's contents should be the same as buf + FloatBuffer readonly = buf.asReadOnlyBuffer(); + assertNotSame(buf, readonly); + assertTrue(readonly.isReadOnly()); + assertEquals(buf.position(), readonly.position()); + assertEquals(buf.limit(), readonly.limit()); + assertEquals(buf.isDirect(), readonly.isDirect()); + assertEquals(buf.order(), readonly.order()); + assertContentEquals(buf, readonly); + + // readonly's position, mark, and limit should be independent to buf + readonly.reset(); + assertEquals(readonly.position(), 0); + readonly.clear(); + assertEquals(buf.position(), buf.limit()); + buf.reset(); + assertEquals(buf.position(), 0); + } + + public void testCompact() { + + // case: buffer is full + buf.clear(); + buf.mark(); + loadTestData1(buf); + FloatBuffer ret = buf.compact(); + assertSame(ret, buf); + assertEquals(buf.position(), buf.capacity()); + assertEquals(buf.limit(), buf.capacity()); + assertContentLikeTestData1(buf, 0, 0.0f, buf.capacity()); + try { + buf.reset(); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (InvalidMarkException e) { + // expected + } + + // case: buffer is empty + buf.position(0); + buf.limit(0); + buf.mark(); + ret = buf.compact(); + assertSame(ret, buf); + assertEquals(buf.position(), 0); + assertEquals(buf.limit(), buf.capacity()); + assertContentLikeTestData1(buf, 0, 0.0f, buf.capacity()); + try { + buf.reset(); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (InvalidMarkException e) { + // expected + } + + // case: normal + assertTrue(buf.capacity() > 5); + buf.position(1); + buf.limit(5); + buf.mark(); + ret = buf.compact(); + assertSame(ret, buf); + assertEquals(buf.position(), 4); + assertEquals(buf.limit(), buf.capacity()); + assertContentLikeTestData1(buf, 0, 1.0f, 4); + try { + buf.reset(); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (InvalidMarkException e) { + // expected + } + } + + public void testCompareTo() { + try { + buf.compareTo(null); + fail("Should throw NPE"); + } catch (NullPointerException e) { + // expected + } + + // compare to self + assertEquals(0, buf.compareTo(buf)); + + // normal cases + assertTrue(buf.capacity() > 5); + buf.clear(); + FloatBuffer other = FloatBuffer.allocate(buf.capacity()); + loadTestData1(other); + assertEquals(0, buf.compareTo(other)); + assertEquals(0, other.compareTo(buf)); + buf.position(1); + assertTrue(buf.compareTo(other) > 0); + assertTrue(other.compareTo(buf) < 0); + other.position(2); + assertTrue(buf.compareTo(other) < 0); + assertTrue(other.compareTo(buf) > 0); + buf.position(2); + other.limit(5); + assertTrue(buf.compareTo(other) > 0); + assertTrue(other.compareTo(buf) < 0); + + FloatBuffer fbuffer1 = FloatBuffer.wrap(new float[] { Float.NaN }); + FloatBuffer fbuffer2 = FloatBuffer.wrap(new float[] { Float.NaN }); + FloatBuffer fbuffer3 = FloatBuffer.wrap(new float[] { 42f }); + + assertEquals("Failed equal comparison with NaN entry", 0, fbuffer1 + .compareTo(fbuffer2)); + assertEquals("Failed greater than comparison with NaN entry", 1, fbuffer3 + .compareTo(fbuffer1)); + assertEquals("Failed greater than comparison with NaN entry", 1, fbuffer1 + .compareTo(fbuffer3)); + + } + + public void testDuplicate() { + buf.clear(); + buf.mark(); + buf.position(buf.limit()); + + // duplicate's contents should be the same as buf + FloatBuffer duplicate = buf.duplicate(); + assertNotSame(buf, duplicate); + assertEquals(buf.position(), duplicate.position()); + assertEquals(buf.limit(), duplicate.limit()); + assertEquals(buf.isReadOnly(), duplicate.isReadOnly()); + assertEquals(buf.isDirect(), duplicate.isDirect()); + assertEquals(buf.order(), duplicate.order()); + assertContentEquals(buf, duplicate); + + // duplicate's position, mark, and limit should be independent to buf + duplicate.reset(); + assertEquals(duplicate.position(), 0); + duplicate.clear(); + assertEquals(buf.position(), buf.limit()); + buf.reset(); + assertEquals(buf.position(), 0); + + // duplicate share the same content with buf + if (!duplicate.isReadOnly()) { + loadTestData1(buf); + assertContentEquals(buf, duplicate); + loadTestData2(duplicate); + assertContentEquals(buf, duplicate); + } + } + + public void testEquals() { + // equal to self + assertTrue(buf.equals(buf)); + FloatBuffer readonly = buf.asReadOnlyBuffer(); + assertTrue(buf.equals(readonly)); + FloatBuffer duplicate = buf.duplicate(); + assertTrue(buf.equals(duplicate)); + + // always false, if type mismatch + assertFalse(buf.equals(Boolean.TRUE)); + + assertTrue(buf.capacity() > 5); + + buf.limit(buf.capacity()).position(0); + readonly.limit(readonly.capacity()).position(1); + assertFalse(buf.equals(readonly)); + + buf.limit(buf.capacity() - 1).position(0); + duplicate.limit(duplicate.capacity()).position(0); + assertFalse(buf.equals(duplicate)); + } + + /* + * Class under test for float get() + */ + public void testGet() { + buf.clear(); + for (int i = 0; i < buf.capacity(); i++) { + assertEquals(buf.position(), i); + assertEquals(buf.get(), buf.get(i), 0.01); + } + try { + buf.get(); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (BufferUnderflowException e) { + // expected + } + } + + /* + * Class under test for java.nio.FloatBuffer get(float[]) + */ + public void testGetfloatArray() { + float array[] = new float[1]; + buf.clear(); + for (int i = 0; i < buf.capacity(); i++) { + assertEquals(buf.position(), i); + FloatBuffer ret = buf.get(array); + assertEquals(array[0], buf.get(i), 0.01); + assertSame(ret, buf); + } + try { + buf.get(array); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (BufferUnderflowException e) { + // expected + } + try { + buf.position(buf.limit()); + buf.get((float[])null); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (NullPointerException e) { + // expected + } + buf.get(new float[0]); + } + + /* + * Class under test for java.nio.FloatBuffer get(float[], int, int) + */ + public void testGetfloatArrayintint() { + buf.clear(); + float array[] = new float[buf.capacity()]; + + try { + buf.get(new float[buf.capacity() + 1], 0, buf.capacity() + 1); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (BufferUnderflowException e) { + // expected + } + assertEquals(buf.position(), 0); + try { + buf.get(array, -1, array.length); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (IndexOutOfBoundsException e) { + // expected + } + buf.get(array, array.length, 0); + try { + buf.get(array, array.length + 1, 1); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (IndexOutOfBoundsException e) { + // expected + } + assertEquals(buf.position(), 0); + try { + buf.get(array, 2, -1); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (IndexOutOfBoundsException e) { + // expected + } + try { + buf.get((float[])null, 2, -1); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (NullPointerException e) { + // expected + } + try { + buf.get(array, 2, array.length); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (IndexOutOfBoundsException e) { + // expected + } + try { + buf.get(array, 1, Integer.MAX_VALUE); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (BufferUnderflowException expected) { + } catch (IndexOutOfBoundsException expected) { + } + try { + buf.get(array, Integer.MAX_VALUE, 1); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (IndexOutOfBoundsException e) { + // expected + } + assertEquals(buf.position(), 0); + + buf.clear(); + FloatBuffer ret = buf.get(array, 0, array.length); + assertEquals(buf.position(), buf.capacity()); + assertContentEquals(buf, array, 0, array.length); + assertSame(ret, buf); + } + + /* + * Class under test for float get(int) + */ + public void testGetint() { + buf.clear(); + for (int i = 0; i < buf.capacity(); i++) { + assertEquals(buf.position(), i); + assertEquals(buf.get(), buf.get(i), 0.01); + } + try { + buf.get(-1); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (IndexOutOfBoundsException e) { + // expected + } + try { + buf.get(buf.limit()); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (IndexOutOfBoundsException e) { + // expected + } + } + + public void testHasArray() { + assertNotNull(buf.array()); + } + + public void testHashCode() { + buf.clear(); + FloatBuffer readonly = buf.asReadOnlyBuffer(); + FloatBuffer duplicate = buf.duplicate(); + assertTrue(buf.hashCode() == readonly.hashCode()); + + assertTrue(buf.capacity() > 5); + duplicate.position(buf.capacity() / 2); + assertTrue(buf.hashCode() != duplicate.hashCode()); + } + + public void testIsDirect() { + assertFalse(buf.isDirect()); + } + + public void testOrder() { + buf.order(); + if (buf.hasArray()) { + assertEquals(ByteOrder.nativeOrder(), buf.order()); + } + } + + /* + * Class under test for java.nio.FloatBuffer put(float) + */ + public void testPutfloat() { + buf.clear(); + for (int i = 0; i < buf.capacity(); i++) { + assertEquals(buf.position(), i); + FloatBuffer ret = buf.put((float) i); + assertEquals(buf.get(i), (float) i, 0.0); + assertSame(ret, buf); + } + try { + buf.put(0); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (BufferOverflowException e) { + // expected + } + } + + /* + * Class under test for java.nio.FloatBuffer put(float[]) + */ + public void testPutfloatArray() { + float array[] = new float[1]; + buf.clear(); + for (int i = 0; i < buf.capacity(); i++) { + assertEquals(buf.position(), i); + array[0] = (float) i; + FloatBuffer ret = buf.put(array); + assertEquals(buf.get(i), (float) i, 0.0); + assertSame(ret, buf); + } + try { + buf.put(array); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (BufferOverflowException e) { + // expected + } + try { + buf.position(buf.limit()); + buf.put((float[])null); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (NullPointerException e) { + // expected + } + } + + /* + * Class under test for java.nio.FloatBuffer put(float[], int, int) + */ + public void testPutfloatArrayintint() { + buf.clear(); + float array[] = new float[buf.capacity()]; + try { + buf.put(new float[buf.capacity() + 1], 0, buf.capacity() + 1); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (BufferOverflowException e) { + // expected + } + assertEquals(buf.position(), 0); + try { + buf.put(array, -1, array.length); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (IndexOutOfBoundsException e) { + // expected + } + try { + buf.put(array, array.length + 1, 0); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (IndexOutOfBoundsException e) { + // expected + } + buf.put(array, array.length, 0); + assertEquals(buf.position(), 0); + try { + buf.put(array, 0, -1); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (IndexOutOfBoundsException e) { + // expected + } + try { + buf.put((float[])null, 0, -1); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (NullPointerException e) { + // expected + } + try { + buf.put(array, 2, array.length); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (IndexOutOfBoundsException e) { + // expected + } + try { + buf.put(array, Integer.MAX_VALUE, 1); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (IndexOutOfBoundsException e) { + // expected + } + try { + buf.put(array, 1, Integer.MAX_VALUE); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (BufferOverflowException expected) { + } catch (IndexOutOfBoundsException expected) { + } + assertEquals(buf.position(), 0); + + loadTestData2(array, 0, array.length); + FloatBuffer ret = buf.put(array, 0, array.length); + assertEquals(buf.position(), buf.capacity()); + assertContentEquals(buf, array, 0, array.length); + assertSame(ret, buf); + } + + /* + * Class under test for java.nio.FloatBuffer put(java.nio.FloatBuffer) + */ + public void testPutFloatBuffer() { + FloatBuffer other = FloatBuffer.allocate(buf.capacity()); + try { + buf.put(buf); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (IllegalArgumentException e) { + // expected + } + try { + buf.put(FloatBuffer.allocate(buf.capacity() + 1)); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (BufferOverflowException e) { + // expected + } + try { + buf.flip(); + buf.put((FloatBuffer)null); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (NullPointerException e) { + // expected + } + buf.clear(); + loadTestData2(other); + other.clear(); + buf.clear(); + FloatBuffer ret = buf.put(other); + assertEquals(other.position(), other.capacity()); + assertEquals(buf.position(), buf.capacity()); + assertContentEquals(other, buf); + assertSame(ret, buf); + } + + /* + * Class under test for java.nio.FloatBuffer put(int, float) + */ + public void testPutintfloat() { + buf.clear(); + for (int i = 0; i < buf.capacity(); i++) { + assertEquals(buf.position(), 0); + FloatBuffer ret = buf.put(i, (float) i); + assertEquals(buf.get(i), (float) i, 0.0); + assertSame(ret, buf); + } + try { + buf.put(-1, 0); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (IndexOutOfBoundsException e) { + // expected + } + try { + buf.put(buf.limit(), 0); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (IndexOutOfBoundsException e) { + // expected + } + } + + public void testSlice() { + assertTrue(buf.capacity() > 5); + buf.position(1); + buf.limit(buf.capacity() - 1); + + FloatBuffer slice = buf.slice(); + assertEquals(buf.isReadOnly(), slice.isReadOnly()); + assertEquals(buf.isDirect(), slice.isDirect()); + assertEquals(buf.order(), slice.order()); + assertEquals(slice.position(), 0); + assertEquals(slice.limit(), buf.remaining()); + assertEquals(slice.capacity(), buf.remaining()); + try { + slice.reset(); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (InvalidMarkException e) { + // expected + } + + // slice share the same content with buf + if (!slice.isReadOnly()) { + loadTestData1(slice); + assertContentLikeTestData1(buf, 1, 0, slice.capacity()); + buf.put(2, 500); + assertEquals(slice.get(1), 500, 0.0); + } + } + + public void testToString() { + String str = buf.toString(); + assertTrue(str.indexOf("Float") >= 0 || str.indexOf("float") >= 0); + assertTrue(str.indexOf("" + buf.position()) >= 0); + assertTrue(str.indexOf("" + buf.limit()) >= 0); + assertTrue(str.indexOf("" + buf.capacity()) >= 0); + } + + void loadTestData1(float array[], int offset, int length) { + for (int i = 0; i < length; i++) { + array[offset + i] = (float) i; + } + } + + void loadTestData2(float array[], int offset, int length) { + for (int i = 0; i < length; i++) { + array[offset + i] = (float) length - i; + } + } + + void loadTestData1(FloatBuffer buf) { + buf.clear(); + for (int i = 0; i < buf.capacity(); i++) { + buf.put(i, (float) i); + } + } + + void loadTestData2(FloatBuffer buf) { + buf.clear(); + for (int i = 0; i < buf.capacity(); i++) { + buf.put(i, (float) buf.capacity() - i); + } + } + + void assertContentEquals(FloatBuffer buf, float array[], + int offset, int length) { + for (int i = 0; i < length; i++) { + assertEquals(buf.get(i), array[offset + i], 0.01); + } + } + + void assertContentEquals(FloatBuffer buf, FloatBuffer other) { + assertEquals(buf.capacity(), other.capacity()); + for (int i = 0; i < buf.capacity(); i++) { + assertEquals(buf.get(i), other.get(i), 0.01); + } + } + + void assertContentLikeTestData1(FloatBuffer buf, + int startIndex, float startValue, int length) { + float value = startValue; + for (int i = 0; i < length; i++) { + assertEquals(buf.get(startIndex + i), value, 0.01); + value = value + 1.0f; + } + } +} diff --git a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/HeapByteBufferTest.java b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/HeapByteBufferTest.java new file mode 100644 index 0000000..2f8e44b --- /dev/null +++ b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/HeapByteBufferTest.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.nio.tests.java.nio; + +import java.nio.ByteBuffer; + + +public class HeapByteBufferTest extends ByteBufferTest { + + protected void setUp() throws Exception { + super.setUp(); + buf = ByteBuffer.allocate(BUFFER_LENGTH); + baseBuf = buf; + } + + protected void tearDown() throws Exception { + super.tearDown(); + buf = null; + baseBuf = null; + } + + /** + * @tests java.nio.ByteBuffer#allocate(int) + * + */ + public void testAllocatedByteBuffer_IllegalArg() { + try { + ByteBuffer.allocate(-1); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (IllegalArgumentException e) { + // expected + } + } + + public void testIsDirect() { + assertFalse(buf.isDirect()); + } + + public void testHasArray() { + assertTrue(buf.hasArray()); + } + + public void testIsReadOnly() { + assertFalse(buf.isReadOnly()); + } +} 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/nio/tests/java/nio/HeapCharBufferTest.java new file mode 100644 index 0000000..a0c8d74 --- /dev/null +++ b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/HeapCharBufferTest.java @@ -0,0 +1,44 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.harmony.nio.tests.java.nio; + +import java.nio.CharBuffer; + + +public class HeapCharBufferTest extends CharBufferTest { + protected void setUp() throws Exception { + super.setUp(); + buf = CharBuffer.allocate(BUFFER_LENGTH); + loadTestData1(buf); + baseBuf = buf; + } + + protected void tearDown() throws Exception { + super.tearDown(); + buf = null; + baseBuf = null; + } + + public void testAllocatedCharBuffer_IllegalArg() { + try { + CharBuffer.allocate(-1); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (IllegalArgumentException e) { + // expected + } + } +} 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/nio/tests/java/nio/HeapDoubleBufferTest.java new file mode 100644 index 0000000..2985899 --- /dev/null +++ b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/HeapDoubleBufferTest.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.nio.tests.java.nio; + +import java.nio.DoubleBuffer; + +public class HeapDoubleBufferTest extends DoubleBufferTest { + protected void setUp() throws Exception { + super.setUp(); + buf = DoubleBuffer.allocate(BUFFER_LENGTH); + loadTestData1(buf); + baseBuf = buf; + } + + protected void tearDown() throws Exception { + super.tearDown(); + buf = null; + baseBuf = null; + } + + public void testAllocatedDoubleBuffer_IllegalArg() { + try { + DoubleBuffer.allocate(-1); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (IllegalArgumentException e) { + // expected + } + } +} 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/nio/tests/java/nio/HeapFloatBufferTest.java new file mode 100644 index 0000000..f90b34e --- /dev/null +++ b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/HeapFloatBufferTest.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.nio.tests.java.nio; + +import java.nio.FloatBuffer; + +public class HeapFloatBufferTest extends FloatBufferTest { + protected void setUp() throws Exception { + super.setUp(); + buf = FloatBuffer.allocate(BUFFER_LENGTH); + loadTestData1(buf); + baseBuf = buf; + } + + protected void tearDown() throws Exception { + super.tearDown(); + buf = null; + baseBuf = null; + } + + public void testAllocatedFloatBuffer_IllegalArg() { + try { + FloatBuffer.allocate(-1); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (IllegalArgumentException e) { + // expected + } + } +} 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/nio/tests/java/nio/HeapIntBufferTest.java new file mode 100644 index 0000000..0d68835 --- /dev/null +++ b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/HeapIntBufferTest.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.nio.tests.java.nio; + +import java.nio.IntBuffer; + +public class HeapIntBufferTest extends IntBufferTest { + protected void setUp() throws Exception { + super.setUp(); + buf = IntBuffer.allocate(BUFFER_LENGTH); + loadTestData1(buf); + baseBuf = buf; + } + + protected void tearDown() throws Exception { + super.tearDown(); + buf = null; + baseBuf = null; + } + + public void testAllocatedIntBuffer_IllegalArg() { + try { + IntBuffer.allocate(-1); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (IllegalArgumentException e) { + // expected + } + } +} 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/nio/tests/java/nio/HeapLongBufferTest.java new file mode 100644 index 0000000..f4f2ae1 --- /dev/null +++ b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/HeapLongBufferTest.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.nio.tests.java.nio; + +import java.nio.LongBuffer; + +public class HeapLongBufferTest extends LongBufferTest { + protected void setUp() throws Exception { + super.setUp(); + buf = LongBuffer.allocate(BUFFER_LENGTH); + loadTestData1(buf); + baseBuf = buf; + } + + protected void tearDown() throws Exception { + super.tearDown(); + buf = null; + baseBuf = null; + } + + public void testAllocatedLongBuffer_IllegalArg() { + try { + LongBuffer.allocate(-1); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (IllegalArgumentException e) { + // expected + } + } +} 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/nio/tests/java/nio/HeapShortBufferTest.java new file mode 100644 index 0000000..327a035 --- /dev/null +++ b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/HeapShortBufferTest.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.nio.tests.java.nio; + +import java.nio.ShortBuffer; + +public class HeapShortBufferTest extends ShortBufferTest { + protected void setUp() throws Exception { + super.setUp(); + buf = ShortBuffer.allocate(BUFFER_LENGTH); + loadTestData1(buf); + baseBuf = buf; + } + + protected void tearDown() throws Exception { + super.tearDown(); + buf = null; + baseBuf = null; + } + + public void testAllocatedShortBuffer_IllegalArg() { + try { + ShortBuffer.allocate(-1); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (IllegalArgumentException e) { + // expected + } + } +} 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/nio/tests/java/nio/IntBufferTest.java new file mode 100644 index 0000000..97babcf --- /dev/null +++ b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/IntBufferTest.java @@ -0,0 +1,650 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.harmony.nio.tests.java.nio; + +import java.nio.BufferOverflowException; +import java.nio.BufferUnderflowException; +import java.nio.ByteOrder; +import java.nio.IntBuffer; +import java.nio.InvalidMarkException; + +/** + * Tests java.nio.IntBuffer + * + */ +public class IntBufferTest extends AbstractBufferTest { + + + protected static final int SMALL_TEST_LENGTH = 5; + + protected static final int BUFFER_LENGTH = 20; + + protected IntBuffer buf; + + protected void setUp() throws Exception { + buf = IntBuffer.allocate(BUFFER_LENGTH); + loadTestData1(buf); + baseBuf = buf; + } + + protected void tearDown() throws Exception { + buf = null; + baseBuf = null; + } + + public void testArray() { + int array[] = buf.array(); + assertContentEquals(buf, array, buf.arrayOffset(), buf.capacity()); + + loadTestData1(array, buf.arrayOffset(), buf.capacity()); + assertContentEquals(buf, array, buf.arrayOffset(), buf.capacity()); + + loadTestData2(array, buf.arrayOffset(), buf.capacity()); + assertContentEquals(buf, array, buf.arrayOffset(), buf.capacity()); + + loadTestData1(buf); + assertContentEquals(buf, array, buf.arrayOffset(), buf.capacity()); + + loadTestData2(buf); + assertContentEquals(buf, array, buf.arrayOffset(), buf.capacity()); + } + + public void testArrayOffset() { + int array[] = buf.array(); + assertContentEquals(buf, array, buf.arrayOffset(), buf.capacity()); + + loadTestData1(array, buf.arrayOffset(), buf.capacity()); + assertContentEquals(buf, array, buf.arrayOffset(), buf.capacity()); + + loadTestData2(array, buf.arrayOffset(), buf.capacity()); + assertContentEquals(buf, array, buf.arrayOffset(), buf.capacity()); + + loadTestData1(buf); + assertContentEquals(buf, array, buf.arrayOffset(), buf.capacity()); + + loadTestData2(buf); + assertContentEquals(buf, array, buf.arrayOffset(), buf.capacity()); + } + + public void testAsReadOnlyBuffer() { + buf.clear(); + buf.mark(); + buf.position(buf.limit()); + + // readonly's contents should be the same as buf + IntBuffer readonly = buf.asReadOnlyBuffer(); + assertNotSame(buf, readonly); + assertTrue(readonly.isReadOnly()); + assertEquals(buf.position(), readonly.position()); + assertEquals(buf.limit(), readonly.limit()); + assertEquals(buf.isDirect(), readonly.isDirect()); + assertEquals(buf.order(), readonly.order()); + assertContentEquals(buf, readonly); + + // readonly's position, mark, and limit should be independent to buf + readonly.reset(); + assertEquals(readonly.position(), 0); + readonly.clear(); + assertEquals(buf.position(), buf.limit()); + buf.reset(); + assertEquals(buf.position(), 0); + } + + public void testCompact() { + // case: buffer is full + buf.clear(); + buf.mark(); + loadTestData1(buf); + IntBuffer ret = buf.compact(); + assertSame(ret, buf); + assertEquals(buf.position(), buf.capacity()); + assertEquals(buf.limit(), buf.capacity()); + assertContentLikeTestData1(buf, 0, 0, buf.capacity()); + try { + buf.reset(); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (InvalidMarkException e) { + // expected + } + + // case: buffer is empty + buf.position(0); + buf.limit(0); + buf.mark(); + ret = buf.compact(); + assertSame(ret, buf); + assertEquals(buf.position(), 0); + assertEquals(buf.limit(), buf.capacity()); + assertContentLikeTestData1(buf, 0, 0, buf.capacity()); + try { + buf.reset(); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (InvalidMarkException e) { + // expected + } + + // case: normal + assertTrue(buf.capacity() > 5); + buf.position(1); + buf.limit(5); + buf.mark(); + ret = buf.compact(); + assertSame(ret, buf); + assertEquals(buf.position(), 4); + assertEquals(buf.limit(), buf.capacity()); + assertContentLikeTestData1(buf, 0, 1, 4); + try { + buf.reset(); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (InvalidMarkException e) { + // expected + } + } + + public void testCompareTo() { + // compare to self + assertEquals(0, buf.compareTo(buf)); + + // normal cases + assertTrue(buf.capacity() > 5); + buf.clear(); + IntBuffer other = IntBuffer.allocate(buf.capacity()); + loadTestData1(other); + assertEquals(0, buf.compareTo(other)); + assertEquals(0, other.compareTo(buf)); + buf.position(1); + assertTrue(buf.compareTo(other) > 0); + assertTrue(other.compareTo(buf) < 0); + other.position(2); + assertTrue(buf.compareTo(other) < 0); + assertTrue(other.compareTo(buf) > 0); + buf.position(2); + other.limit(5); + assertTrue(buf.compareTo(other) > 0); + assertTrue(other.compareTo(buf) < 0); + } + + public void testDuplicate() { + buf.clear(); + buf.mark(); + buf.position(buf.limit()); + + // duplicate's contents should be the same as buf + IntBuffer duplicate = buf.duplicate(); + assertNotSame(buf, duplicate); + assertEquals(buf.position(), duplicate.position()); + assertEquals(buf.limit(), duplicate.limit()); + assertEquals(buf.isReadOnly(), duplicate.isReadOnly()); + assertEquals(buf.isDirect(), duplicate.isDirect()); + assertEquals(buf.order(), duplicate.order()); + assertContentEquals(buf, duplicate); + + // duplicate's position, mark, and limit should be independent to buf + duplicate.reset(); + assertEquals(duplicate.position(), 0); + duplicate.clear(); + assertEquals(buf.position(), buf.limit()); + buf.reset(); + assertEquals(buf.position(), 0); + + // duplicate share the same content with buf + if (!duplicate.isReadOnly()) { + loadTestData1(buf); + assertContentEquals(buf, duplicate); + loadTestData2(duplicate); + assertContentEquals(buf, duplicate); + } + } + + public void testEquals() { + // equal to self + assertTrue(buf.equals(buf)); + IntBuffer readonly = buf.asReadOnlyBuffer(); + assertTrue(buf.equals(readonly)); + IntBuffer duplicate = buf.duplicate(); + assertTrue(buf.equals(duplicate)); + + // always false, if type mismatch + assertFalse(buf.equals(Boolean.TRUE)); + + assertTrue(buf.capacity() > 5); + + buf.limit(buf.capacity()).position(0); + readonly.limit(readonly.capacity()).position(1); + assertFalse(buf.equals(readonly)); + + buf.limit(buf.capacity() - 1).position(0); + duplicate.limit(duplicate.capacity()).position(0); + assertFalse(buf.equals(duplicate)); + } + + /* + * Class under test for int get() + */ + public void testGet() { + buf.clear(); + for (int i = 0; i < buf.capacity(); i++) { + assertEquals(buf.position(), i); + assertEquals(buf.get(), buf.get(i)); + } + try { + buf.get(); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (BufferUnderflowException e) { + // expected + } + } + + /* + * Class under test for java.nio.IntBuffer get(int[]) + */ + public void testGetintArray() { + int array[] = new int[1]; + buf.clear(); + for (int i = 0; i < buf.capacity(); i++) { + assertEquals(buf.position(), i); + IntBuffer ret = buf.get(array); + assertEquals(array[0], buf.get(i)); + assertSame(ret, buf); + } + try { + buf.get(array); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (BufferUnderflowException e) { + // expected + } + try { + buf.get((int[])null); + fail("Should throw NPE"); //$NON-NLS-1$ + } catch (NullPointerException e) { + // expected + } + } + + /* + * Class under test for java.nio.IntBuffer get(int[], int, int) + */ + public void testGetintArrayintint() { + buf.clear(); + int array[] = new int[buf.capacity()]; + + try { + buf.get(new int[buf.capacity() + 1], 0, buf.capacity() + 1); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (BufferUnderflowException e) { + // expected + } + assertEquals(buf.position(), 0); + try { + buf.get(array, -1, array.length); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (IndexOutOfBoundsException e) { + // expected + } + buf.get(array, array.length, 0); + try { + buf.get(array, array.length + 1, 1); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (IndexOutOfBoundsException e) { + // expected + } + assertEquals(buf.position(), 0); + try { + buf.get(array, 2, -1); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (IndexOutOfBoundsException e) { + // expected + } + try { + buf.get((int[])null, 2, -1); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (NullPointerException e) { + // expected + } + try { + buf.get(array, 2, array.length); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (IndexOutOfBoundsException e) { + // expected + } + try { + buf.get(array, 1, Integer.MAX_VALUE); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (BufferUnderflowException expected) { + } catch (IndexOutOfBoundsException expected) { + } + try { + buf.get(array, Integer.MAX_VALUE, 1); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (IndexOutOfBoundsException e) { + // expected + } + assertEquals(buf.position(), 0); + + buf.clear(); + IntBuffer ret = buf.get(array, 0, array.length); + assertEquals(buf.position(), buf.capacity()); + assertContentEquals(buf, array, 0, array.length); + assertSame(ret, buf); + } + + /* + * Class under test for int get(int) + */ + public void testGetint() { + buf.clear(); + for (int i = 0; i < buf.capacity(); i++) { + assertEquals(buf.position(), i); + assertEquals(buf.get(), buf.get(i)); + } + try { + buf.get(-1); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (IndexOutOfBoundsException e) { + // expected + } + try { + buf.get(buf.limit()); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (IndexOutOfBoundsException e) { + // expected + } + } + + public void testHasArray() { + assertNotNull(buf.array()); + } + + public void testHashCode() { + buf.clear(); + IntBuffer readonly = buf.asReadOnlyBuffer(); + IntBuffer duplicate = buf.duplicate(); + assertTrue(buf.hashCode() == readonly.hashCode()); + + assertTrue(buf.capacity() > 5); + duplicate.position(buf.capacity() / 2); + assertTrue(buf.hashCode() != duplicate.hashCode()); + } + + public void testIsDirect() { + assertFalse(buf.isDirect()); + } + + public void testOrder() { + buf.order(); + assertEquals(ByteOrder.nativeOrder(), buf.order()); + } + + /* + * Class under test for java.nio.IntBuffer put(int) + */ + public void testPutint() { + buf.clear(); + for (int i = 0; i < buf.capacity(); i++) { + assertEquals(buf.position(), i); + IntBuffer ret = buf.put((int) i); + assertEquals(buf.get(i), (int) i); + assertSame(ret, buf); + } + try { + buf.put(0); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (BufferOverflowException e) { + // expected + } + } + + /* + * Class under test for java.nio.IntBuffer put(int[]) + */ + public void testPutintArray() { + int array[] = new int[1]; + buf.clear(); + for (int i = 0; i < buf.capacity(); i++) { + assertEquals(buf.position(), i); + array[0] = (int) i; + IntBuffer ret = buf.put(array); + assertEquals(buf.get(i), (int) i); + assertSame(ret, buf); + } + try { + buf.put(array); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (BufferOverflowException e) { + // expected + } + try { + buf.position(buf.limit()); + buf.put((int[])null); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (NullPointerException e) { + // expected + } + } + + /* + * Class under test for java.nio.IntBuffer put(int[], int, int) + */ + public void testPutintArrayintint() { + buf.clear(); + int array[] = new int[buf.capacity()]; + try { + buf.put(new int[buf.capacity() + 1], 0, buf.capacity() + 1); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (BufferOverflowException e) { + // expected + } + assertEquals(buf.position(), 0); + try { + buf.put(array, -1, array.length); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (IndexOutOfBoundsException e) { + // expected + } + try { + buf.put(array, array.length + 1, 0); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (IndexOutOfBoundsException e) { + // expected + } + buf.put(array, array.length, 0); + assertEquals(buf.position(), 0); + try { + buf.put(array, 0, -1); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (IndexOutOfBoundsException e) { + // expected + } + try { + buf.put((int[])null, 0, -1); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (NullPointerException e) { + // expected + } + try { + buf.put(array, 2, array.length); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (IndexOutOfBoundsException e) { + // expected + } + try { + buf.put(array, Integer.MAX_VALUE, 1); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (IndexOutOfBoundsException e) { + // expected + } + try { + buf.put(array, 1, Integer.MAX_VALUE); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (BufferOverflowException expected) { + } catch (IndexOutOfBoundsException expected) { + } + assertEquals(buf.position(), 0); + + loadTestData2(array, 0, array.length); + IntBuffer ret = buf.put(array, 0, array.length); + assertEquals(buf.position(), buf.capacity()); + assertContentEquals(buf, array, 0, array.length); + assertSame(ret, buf); + } + + /* + * Class under test for java.nio.IntBuffer put(java.nio.IntBuffer) + */ + public void testPutIntBuffer() { + IntBuffer other = IntBuffer.allocate(buf.capacity()); + try { + buf.put(buf); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (IllegalArgumentException e) { + // expected + } + try { + buf.put(IntBuffer.allocate(buf.capacity() + 1)); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (BufferOverflowException e) { + // expected + } + try { + buf.flip(); + buf.put((IntBuffer)null); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (NullPointerException e) { + // expected + } + + loadTestData2(other); + other.clear(); + buf.clear(); + IntBuffer ret = buf.put(other); + assertEquals(other.position(), other.capacity()); + assertEquals(buf.position(), buf.capacity()); + assertContentEquals(other, buf); + assertSame(ret, buf); + } + + /* + * Class under test for java.nio.IntBuffer put(int, int) + */ + public void testPutintint() { + buf.clear(); + for (int i = 0; i < buf.capacity(); i++) { + assertEquals(buf.position(), 0); + IntBuffer ret = buf.put(i, (int) i); + assertEquals(buf.get(i), (int) i); + assertSame(ret, buf); + } + try { + buf.put(-1, 0); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (IndexOutOfBoundsException e) { + // expected + } + try { + buf.put(buf.limit(), 0); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (IndexOutOfBoundsException e) { + // expected + } + } + + public void testSlice() { + assertTrue(buf.capacity() > 5); + buf.position(1); + buf.limit(buf.capacity() - 1); + + IntBuffer slice = buf.slice(); + assertEquals(buf.isReadOnly(), slice.isReadOnly()); + assertEquals(buf.isDirect(), slice.isDirect()); + assertEquals(buf.order(), slice.order()); + assertEquals(slice.position(), 0); + assertEquals(slice.limit(), buf.remaining()); + assertEquals(slice.capacity(), buf.remaining()); + try { + slice.reset(); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (InvalidMarkException e) { + // expected + } + + // slice share the same content with buf + if (!slice.isReadOnly()) { + loadTestData1(slice); + assertContentLikeTestData1(buf, 1, 0, slice.capacity()); + buf.put(2, 500); + assertEquals(slice.get(1), 500); + } + } + + public void testToString() { + String str = buf.toString(); + assertTrue(str.indexOf("Int") >= 0 || str.indexOf("int") >= 0); + assertTrue(str.indexOf("" + buf.position()) >= 0); + assertTrue(str.indexOf("" + buf.limit()) >= 0); + assertTrue(str.indexOf("" + buf.capacity()) >= 0); + } + + void loadTestData1(int array[], int offset, int length) { + for (int i = 0; i < length; i++) { + array[offset + i] = (int) i; + } + } + + void loadTestData2(int array[], int offset, int length) { + for (int i = 0; i < length; i++) { + array[offset + i] = (int) length - i; + } + } + + void loadTestData1(IntBuffer buf) { + buf.clear(); + for (int i = 0; i < buf.capacity(); i++) { + buf.put(i, (int) i); + } + } + + void loadTestData2(IntBuffer buf) { + buf.clear(); + for (int i = 0; i < buf.capacity(); i++) { + buf.put(i, (int) buf.capacity() - i); + } + } + + void assertContentEquals(IntBuffer buf, int array[], + int offset, int length) { + for (int i = 0; i < length; i++) { + assertEquals(buf.get(i), array[offset + i]); + } + } + + void assertContentEquals(IntBuffer buf, IntBuffer other) { + assertEquals(buf.capacity(), other.capacity()); + for (int i = 0; i < buf.capacity(); i++) { + assertEquals(buf.get(i), other.get(i)); + } + } + + void assertContentLikeTestData1(IntBuffer buf, + int startIndex, int startValue, int length) { + int value = startValue; + for (int i = 0; i < length; i++) { + assertEquals(buf.get(startIndex + i), value); + value = value + 1; + } + } +} diff --git a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/InvalidMarkExceptionTest.java b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/InvalidMarkExceptionTest.java new file mode 100644 index 0000000..4b7682d --- /dev/null +++ b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/InvalidMarkExceptionTest.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.nio.tests.java.nio; + +import java.nio.InvalidMarkException; + +import junit.framework.TestCase; + +import org.apache.harmony.testframework.serialization.SerializationTest; + +public class InvalidMarkExceptionTest extends TestCase { + + /** + * @tests serialization/deserialization compatibility. + */ + public void testSerializationSelf() throws Exception { + + SerializationTest.verifySelf(new InvalidMarkException()); + } + + /** + * @tests serialization/deserialization compatibility with RI. + */ + public void testSerializationCompatibility() throws Exception { + + SerializationTest.verifyGolden(this, new InvalidMarkException()); + } + + /** + *@tests {@link java.nio.InvalidMarkException#InvalidMarkException()} + */ + public void test_Constructor() { + InvalidMarkException exception = new InvalidMarkException(); + assertNull(exception.getMessage()); + assertNull(exception.getLocalizedMessage()); + assertNull(exception.getCause()); + } +} 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/nio/tests/java/nio/LongBufferTest.java new file mode 100644 index 0000000..371351b --- /dev/null +++ b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/LongBufferTest.java @@ -0,0 +1,657 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.harmony.nio.tests.java.nio; + +import java.nio.BufferOverflowException; +import java.nio.BufferUnderflowException; +import java.nio.ByteOrder; +import java.nio.InvalidMarkException; +import java.nio.LongBuffer; + +/** + * Tests java.nio.LongBuffer + * + */ +public class LongBufferTest extends AbstractBufferTest { + + + protected static final int SMALL_TEST_LENGTH = 5; + + protected static final int BUFFER_LENGTH = 20; + + protected LongBuffer buf; + + protected void setUp() throws Exception { + buf = LongBuffer.allocate(BUFFER_LENGTH); + loadTestData1(buf); + baseBuf = buf; + } + + protected void tearDown() throws Exception { + buf = null; + baseBuf = null; + } + + public void testArray() { + long array[] = buf.array(); + assertContentEquals(buf, array, buf.arrayOffset(), buf.capacity()); + + loadTestData1(array, buf.arrayOffset(), buf.capacity()); + assertContentEquals(buf, array, buf.arrayOffset(), buf.capacity()); + + loadTestData2(array, buf.arrayOffset(), buf.capacity()); + assertContentEquals(buf, array, buf.arrayOffset(), buf.capacity()); + + loadTestData1(buf); + assertContentEquals(buf, array, buf.arrayOffset(), buf.capacity()); + + loadTestData2(buf); + assertContentEquals(buf, array, buf.arrayOffset(), buf.capacity()); + } + + public void testArrayOffset() { + long array[] = buf.array(); + assertContentEquals(buf, array, buf.arrayOffset(), buf.capacity()); + + loadTestData1(array, buf.arrayOffset(), buf.capacity()); + assertContentEquals(buf, array, buf.arrayOffset(), buf.capacity()); + + loadTestData2(array, buf.arrayOffset(), buf.capacity()); + assertContentEquals(buf, array, buf.arrayOffset(), buf.capacity()); + + loadTestData1(buf); + assertContentEquals(buf, array, buf.arrayOffset(), buf.capacity()); + + loadTestData2(buf); + assertContentEquals(buf, array, buf.arrayOffset(), buf.capacity()); + } + + public void testAsReadOnlyBuffer() { + buf.clear(); + buf.mark(); + buf.position(buf.limit()); + + // readonly's contents should be the same as buf + LongBuffer readonly = buf.asReadOnlyBuffer(); + assertNotSame(buf, readonly); + assertTrue(readonly.isReadOnly()); + assertEquals(buf.position(), readonly.position()); + assertEquals(buf.limit(), readonly.limit()); + assertEquals(buf.isDirect(), readonly.isDirect()); + assertEquals(buf.order(), readonly.order()); + assertContentEquals(buf, readonly); + + // readonly's position, mark, and limit should be independent to buf + readonly.reset(); + assertEquals(readonly.position(), 0); + readonly.clear(); + assertEquals(buf.position(), buf.limit()); + buf.reset(); + assertEquals(buf.position(), 0); + } + + public void testCompact() { + // case: buffer is full + buf.clear(); + buf.mark(); + loadTestData1(buf); + LongBuffer ret = buf.compact(); + assertSame(ret, buf); + assertEquals(buf.position(), buf.capacity()); + assertEquals(buf.limit(), buf.capacity()); + assertContentLikeTestData1(buf, 0, 0, buf.capacity()); + try { + buf.reset(); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (InvalidMarkException e) { + // expected + } + + // case: buffer is empty + buf.position(0); + buf.limit(0); + buf.mark(); + ret = buf.compact(); + assertSame(ret, buf); + assertEquals(buf.position(), 0); + assertEquals(buf.limit(), buf.capacity()); + assertContentLikeTestData1(buf, 0, 0, buf.capacity()); + try { + buf.reset(); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (InvalidMarkException e) { + // expected + } + + // case: normal + assertTrue(buf.capacity() > 5); + buf.position(1); + buf.limit(5); + buf.mark(); + ret = buf.compact(); + assertSame(ret, buf); + assertEquals(buf.position(), 4); + assertEquals(buf.limit(), buf.capacity()); + assertContentLikeTestData1(buf, 0, 1, 4); + try { + buf.reset(); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (InvalidMarkException e) { + // expected + } + } + + public void testCompareTo() { + // compare to self + assertEquals(0, buf.compareTo(buf)); + + // normal cases + assertTrue(buf.capacity() > 5); + buf.clear(); + LongBuffer other = LongBuffer.allocate(buf.capacity()); + loadTestData1(other); + assertEquals(0, buf.compareTo(other)); + assertEquals(0, other.compareTo(buf)); + buf.position(1); + assertTrue(buf.compareTo(other) > 0); + assertTrue(other.compareTo(buf) < 0); + other.position(2); + assertTrue(buf.compareTo(other) < 0); + assertTrue(other.compareTo(buf) > 0); + buf.position(2); + other.limit(5); + assertTrue(buf.compareTo(other) > 0); + assertTrue(other.compareTo(buf) < 0); + } + + public void testDuplicate() { + buf.clear(); + buf.mark(); + buf.position(buf.limit()); + + // duplicate's contents should be the same as buf + LongBuffer duplicate = buf.duplicate(); + assertNotSame(buf, duplicate); + assertEquals(buf.position(), duplicate.position()); + assertEquals(buf.limit(), duplicate.limit()); + assertEquals(buf.isReadOnly(), duplicate.isReadOnly()); + assertEquals(buf.isDirect(), duplicate.isDirect()); + assertEquals(buf.order(), duplicate.order()); + assertContentEquals(buf, duplicate); + + // duplicate's position, mark, and limit should be independent to buf + duplicate.reset(); + assertEquals(duplicate.position(), 0); + duplicate.clear(); + assertEquals(buf.position(), buf.limit()); + buf.reset(); + assertEquals(buf.position(), 0); + + // duplicate share the same content with buf + if (!duplicate.isReadOnly()) { + loadTestData1(buf); + assertContentEquals(buf, duplicate); + loadTestData2(duplicate); + assertContentEquals(buf, duplicate); + } + } + + public void testEquals() { + // equal to self + assertTrue(buf.equals(buf)); + LongBuffer readonly = buf.asReadOnlyBuffer(); + assertTrue(buf.equals(readonly)); + LongBuffer duplicate = buf.duplicate(); + assertTrue(buf.equals(duplicate)); + + // always false, if type mismatch + assertFalse(buf.equals(Boolean.TRUE)); + + assertTrue(buf.capacity() > 5); + + buf.limit(buf.capacity()).position(0); + readonly.limit(readonly.capacity()).position(1); + assertFalse(buf.equals(readonly)); + + buf.limit(buf.capacity() - 1).position(0); + duplicate.limit(duplicate.capacity()).position(0); + assertFalse(buf.equals(duplicate)); + } + + /* + * Class under test for long get() + */ + public void testGet() { + buf.clear(); + for (int i = 0; i < buf.capacity(); i++) { + assertEquals(buf.position(), i); + assertEquals(buf.get(), buf.get(i)); + } + try { + buf.get(); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (BufferUnderflowException e) { + // expected + } + } + + /* + * Class under test for java.nio.LongBuffer get(long[]) + */ + public void testGetlongArray() { + long array[] = new long[1]; + buf.clear(); + for (int i = 0; i < buf.capacity(); i++) { + assertEquals(buf.position(), i); + LongBuffer ret = buf.get(array); + assertEquals(array[0], buf.get(i)); + assertSame(ret, buf); + } + try { + buf.get(array); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (BufferUnderflowException e) { + // expected + } + try { + buf.position(buf.limit()); + buf.get((long[])null); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (NullPointerException e) { + // expected + } + } + + /* + * Class under test for java.nio.LongBuffer get(long[], int, int) + */ + public void testGetlongArrayintint() { + buf.clear(); + long array[] = new long[buf.capacity()]; + + try { + buf.get(new long[buf.capacity() + 1], 0, buf.capacity() + 1); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (BufferUnderflowException e) { + // expected + } + assertEquals(buf.position(), 0); + try { + buf.get(array, -1, array.length); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (IndexOutOfBoundsException e) { + // expected + } + buf.get(array, array.length, 0); + try { + buf.get(array, array.length + 1, 1); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (IndexOutOfBoundsException e) { + // expected + } + assertEquals(buf.position(), 0); + try { + buf.get(array, 2, -1); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (IndexOutOfBoundsException e) { + // expected + } + try { + buf.get((long[])null, 2, -1); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (NullPointerException e) { + // expected + } + try { + buf.get(array, 2, array.length); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (IndexOutOfBoundsException e) { + // expected + } + try { + buf.get(array, 1, Integer.MAX_VALUE); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (BufferUnderflowException expected) { + } catch (IndexOutOfBoundsException expected) { + } + try { + buf.get(array, Integer.MAX_VALUE, 1); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (IndexOutOfBoundsException e) { + // expected + } + assertEquals(buf.position(), 0); + + buf.clear(); + LongBuffer ret = buf.get(array, 0, array.length); + assertEquals(buf.position(), buf.capacity()); + assertContentEquals(buf, array, 0, array.length); + assertSame(ret, buf); + } + + /* + * Class under test for long get(int) + */ + public void testGetint() { + buf.clear(); + for (int i = 0; i < buf.capacity(); i++) { + assertEquals(buf.position(), i); + assertEquals(buf.get(), buf.get(i)); + } + try { + buf.get(-1); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (IndexOutOfBoundsException e) { + // expected + } + try { + buf.get(buf.limit()); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (IndexOutOfBoundsException e) { + // expected + } + } + + public void testHasArray() { + assertNotNull(buf.array()); + } + + public void testHashCode() { + buf.clear(); + LongBuffer readonly = buf.asReadOnlyBuffer(); + LongBuffer duplicate = buf.duplicate(); + assertTrue(buf.hashCode() == readonly.hashCode()); + + assertTrue(buf.capacity() > 5); + duplicate.position(buf.capacity() / 2); + assertTrue(buf.hashCode() != duplicate.hashCode()); + } + + public void testIsDirect() { + assertFalse(buf.isDirect()); + } + + public void testOrder() { + buf.order(); + assertEquals(ByteOrder.nativeOrder(), buf.order()); + } + + /* + * Class under test for java.nio.LongBuffer put(long) + */ + public void testPutlong() { + buf.clear(); + for (int i = 0; i < buf.capacity(); i++) { + assertEquals(buf.position(), i); + LongBuffer ret = buf.put((long) i); + assertEquals(buf.get(i), (long) i); + assertSame(ret, buf); + } + try { + buf.put(0); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (BufferOverflowException e) { + // expected + } + } + + /* + * Class under test for java.nio.LongBuffer put(long[]) + */ + public void testPutlongArray() { + long array[] = new long[1]; + buf.clear(); + for (int i = 0; i < buf.capacity(); i++) { + assertEquals(buf.position(), i); + array[0] = (long) i; + LongBuffer ret = buf.put(array); + assertEquals(buf.get(i), (long) i); + assertSame(ret, buf); + } + try { + buf.put(array); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (BufferOverflowException e) { + // expected + } + try { + buf.position(buf.limit()); + buf.put((long[])null); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (NullPointerException e) { + // expected + } + } + + /* + * Class under test for java.nio.LongBuffer put(long[], int, int) + */ + public void testPutlongArrayintint() { + buf.clear(); + long array[] = new long[buf.capacity()]; + try { + buf.put(new long[buf.capacity() + 1], 0, buf.capacity() + 1); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (BufferOverflowException e) { + // expected + } + assertEquals(buf.position(), 0); + try { + buf.put(array, -1, array.length); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (IndexOutOfBoundsException e) { + // expected + } + try { + buf.put(array, array.length + 1, 0); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (IndexOutOfBoundsException e) { + // expected + } + buf.put(array, array.length, 0); + assertEquals(buf.position(), 0); + try { + buf.put(array, 0, -1); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (IndexOutOfBoundsException e) { + // expected + } + try { + buf.put(array, 2, array.length); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (IndexOutOfBoundsException e) { + // expected + } + try { + buf.put((long[])null, 0, -1); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (NullPointerException e) { + // expected + } + try { + buf.put(array, 2, array.length); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (IndexOutOfBoundsException e) { + // expected + } + try { + buf.put(array, Integer.MAX_VALUE, 1); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (IndexOutOfBoundsException e) { + // expected + } + try { + buf.put(array, 1, Integer.MAX_VALUE); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (BufferOverflowException expected) { + } catch (IndexOutOfBoundsException expected) { + } + assertEquals(buf.position(), 0); + + loadTestData2(array, 0, array.length); + LongBuffer ret = buf.put(array, 0, array.length); + assertEquals(buf.position(), buf.capacity()); + assertContentEquals(buf, array, 0, array.length); + assertSame(ret, buf); + } + + /* + * Class under test for java.nio.LongBuffer put(java.nio.LongBuffer) + */ + public void testPutLongBuffer() { + LongBuffer other = LongBuffer.allocate(buf.capacity()); + try { + buf.put(buf); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (IllegalArgumentException e) { + // expected + } + try { + buf.put(LongBuffer.allocate(buf.capacity() + 1)); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (BufferOverflowException e) { + // expected + } + try { + buf.flip(); + buf.put((LongBuffer)null); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (NullPointerException e) { + // expected + } + + loadTestData2(other); + other.clear(); + buf.clear(); + LongBuffer ret = buf.put(other); + assertEquals(other.position(), other.capacity()); + assertEquals(buf.position(), buf.capacity()); + assertContentEquals(other, buf); + assertSame(ret, buf); + } + + /* + * Class under test for java.nio.LongBuffer put(int, long) + */ + public void testPutintlong() { + buf.clear(); + for (int i = 0; i < buf.capacity(); i++) { + assertEquals(buf.position(), 0); + LongBuffer ret = buf.put(i, (long) i); + assertEquals(buf.get(i), (long) i); + assertSame(ret, buf); + } + try { + buf.put(-1, 0); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (IndexOutOfBoundsException e) { + // expected + } + try { + buf.put(buf.limit(), 0); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (IndexOutOfBoundsException e) { + // expected + } + } + + public void testSlice() { + assertTrue(buf.capacity() > 5); + buf.position(1); + buf.limit(buf.capacity() - 1); + + LongBuffer slice = buf.slice(); + assertEquals(buf.isReadOnly(), slice.isReadOnly()); + assertEquals(buf.isDirect(), slice.isDirect()); + assertEquals(buf.order(), slice.order()); + assertEquals(slice.position(), 0); + assertEquals(slice.limit(), buf.remaining()); + assertEquals(slice.capacity(), buf.remaining()); + try { + slice.reset(); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (InvalidMarkException e) { + // expected + } + + // slice share the same content with buf + if (!slice.isReadOnly()) { + loadTestData1(slice); + assertContentLikeTestData1(buf, 1, 0, slice.capacity()); + buf.put(2, 500); + assertEquals(slice.get(1), 500); + } + } + + public void testToString() { + String str = buf.toString(); + assertTrue(str.indexOf("Long") >= 0 || str.indexOf("long") >= 0); + assertTrue(str.indexOf("" + buf.position()) >= 0); + assertTrue(str.indexOf("" + buf.limit()) >= 0); + assertTrue(str.indexOf("" + buf.capacity()) >= 0); + } + + void loadTestData1(long array[], int offset, int length) { + for (int i = 0; i < length; i++) { + array[offset + i] = (long) i; + } + } + + void loadTestData2(long array[], int offset, int length) { + for (int i = 0; i < length; i++) { + array[offset + i] = (long) length - i; + } + } + + void loadTestData1(LongBuffer buf) { + buf.clear(); + for (int i = 0; i < buf.capacity(); i++) { + buf.put(i, (long) i); + } + } + + void loadTestData2(LongBuffer buf) { + buf.clear(); + for (int i = 0; i < buf.capacity(); i++) { + buf.put(i, (long) buf.capacity() - i); + } + } + + void assertContentEquals(LongBuffer buf, long array[], + int offset, int length) { + for (int i = 0; i < length; i++) { + assertEquals(buf.get(i), array[offset + i]); + } + } + + void assertContentEquals(LongBuffer buf, LongBuffer other) { + assertEquals(buf.capacity(), other.capacity()); + for (int i = 0; i < buf.capacity(); i++) { + assertEquals(buf.get(i), other.get(i)); + } + } + + void assertContentLikeTestData1(LongBuffer buf, + int startIndex, long startValue, int length) { + long value = startValue; + for (int i = 0; i < length; i++) { + assertEquals(buf.get(startIndex + i), value); + value = value + 1; + } + } +} diff --git a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/MappedByteBufferTest.java b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/MappedByteBufferTest.java new file mode 100644 index 0000000..308db21 --- /dev/null +++ b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/MappedByteBufferTest.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.nio.tests.java.nio; + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.RandomAccessFile; +import java.nio.BufferUnderflowException; +import java.nio.ByteBuffer; +import java.nio.IntBuffer; +import java.nio.MappedByteBuffer; +import java.nio.channels.FileChannel; +import java.nio.channels.NonWritableChannelException; +import java.nio.channels.FileChannel.MapMode; + +import junit.framework.TestCase; + +public class MappedByteBufferTest extends TestCase { + + File tmpFile, emptyFile; + + /** + * A regression test for failing to correctly set capacity of underlying + * wrapped buffer from a mapped byte buffer. + */ + public void testasIntBuffer() throws IOException { + // Map file + FileInputStream fis = new FileInputStream(tmpFile); + FileChannel fc = fis.getChannel(); + MappedByteBuffer mmb = fc.map(FileChannel.MapMode.READ_ONLY, 0, fc + .size()); + int len = mmb.capacity(); + assertEquals("Got wrong number of bytes", 46, len); //$NON-NLS-1$ + + // Read in our 26 bytes + for (int i = 0; i < 26; i++) { + byte b = mmb.get(); + assertEquals("Got wrong byte value", (byte) 'A' + i, b); //$NON-NLS-1$ + } + + // Now convert to an IntBuffer to read our ints + IntBuffer ibuffer = mmb.asIntBuffer(); + for (int i = 0; i < 5; i++) { + int val = ibuffer.get(); + assertEquals("Got wrong int value", i + 1, val); //$NON-NLS-1$ + } + fc.close(); + } + + /** + * Regression for HARMONY-6315 - FileChannel.map throws IOException + * when called with size 0 + * + * @throws IOException + */ + public void testEmptyBuffer() throws IOException { + // Map empty file + FileInputStream fis = new FileInputStream(emptyFile); + FileChannel fc = fis.getChannel(); + MappedByteBuffer mmb = fc.map(FileChannel.MapMode.READ_ONLY, 0, fc.size()); + + // check non-null + assertNotNull("MappedByteBuffer created from empty file should not be null", + mmb); + + // check capacity is 0 + int len = mmb.capacity(); + assertEquals("MappedByteBuffer created from empty file should have 0 capacity", + 0, len); + + assertFalse("MappedByteBuffer from empty file shouldn't be backed by an array ", + mmb.hasArray()); + + try + { + byte b = mmb.get(); + fail("Calling MappedByteBuffer.get() on empty buffer should throw a BufferUnderflowException"); + } + catch (BufferUnderflowException e) + { + // expected behaviour + } + + // test expected exceptions thrown + try + { + mmb = fc.map(FileChannel.MapMode.READ_WRITE, 0, fc.size()); + fail("Expected NonWritableChannelException to be thrown"); + } + catch (NonWritableChannelException e) + { + // expected behaviour + } + try + { + mmb = fc.map(FileChannel.MapMode.PRIVATE, 0, fc.size()); + fail("Expected NonWritableChannelException to be thrown"); + } + catch (NonWritableChannelException e) + { + // expected behaviour + } + fc.close(); + } + + /** + * @tests {@link java.nio.MappedByteBuffer#force()} + */ + public void test_force() throws IOException { + // buffer was not mapped in read/write mode + FileInputStream fileInputStream = new FileInputStream(tmpFile); + FileChannel fileChannelRead = fileInputStream.getChannel(); + MappedByteBuffer mmbRead = fileChannelRead.map(MapMode.READ_ONLY, 0, + fileChannelRead.size()); + + mmbRead.force(); + + FileInputStream inputStream = new FileInputStream(tmpFile); + FileChannel fileChannelR = inputStream.getChannel(); + MappedByteBuffer resultRead = fileChannelR.map(MapMode.READ_ONLY, 0, + fileChannelR.size()); + + //If this buffer was not mapped in read/write mode, then invoking this method has no effect. + assertEquals( + "Invoking force() should have no effect when this buffer was not mapped in read/write mode", + mmbRead, resultRead); + + // Buffer was mapped in read/write mode + RandomAccessFile randomFile = new RandomAccessFile(tmpFile, "rw"); + FileChannel fileChannelReadWrite = randomFile.getChannel(); + MappedByteBuffer mmbReadWrite = fileChannelReadWrite.map( + FileChannel.MapMode.READ_WRITE, 0, fileChannelReadWrite.size()); + + mmbReadWrite.put((byte) 'o'); + mmbReadWrite.force(); + + RandomAccessFile random = new RandomAccessFile(tmpFile, "rw"); + FileChannel fileChannelRW = random.getChannel(); + MappedByteBuffer resultReadWrite = fileChannelRW.map( + FileChannel.MapMode.READ_WRITE, 0, fileChannelRW.size()); + + // Invoking force() will change the buffer + assertFalse(mmbReadWrite.equals(resultReadWrite)); + + fileChannelRead.close(); + fileChannelR.close(); + fileChannelReadWrite.close(); + fileChannelRW.close(); + } + + /** + * @tests {@link java.nio.MappedByteBuffer#load()} + */ + public void test_load() throws IOException { + FileInputStream fileInputStream = new FileInputStream(tmpFile); + FileChannel fileChannelRead = fileInputStream.getChannel(); + MappedByteBuffer mmbRead = fileChannelRead.map(MapMode.READ_ONLY, 0, + fileChannelRead.size()); + + assertEquals(mmbRead, mmbRead.load()); + + RandomAccessFile randomFile = new RandomAccessFile(tmpFile, "rw"); + FileChannel fileChannelReadWrite = randomFile.getChannel(); + MappedByteBuffer mmbReadWrite = fileChannelReadWrite.map( + FileChannel.MapMode.READ_WRITE, 0, fileChannelReadWrite.size()); + + assertEquals(mmbReadWrite, mmbReadWrite.load()); + + fileChannelRead.close(); + fileChannelReadWrite.close(); + } + + protected void setUp() throws IOException { + // Create temp file with 26 bytes and 5 ints + tmpFile = File.createTempFile("harmony", "test"); //$NON-NLS-1$//$NON-NLS-2$ + tmpFile.deleteOnExit(); + FileOutputStream fileOutputStream = new FileOutputStream(tmpFile); + FileChannel fileChannel = fileOutputStream.getChannel(); + ByteBuffer byteBuffer = ByteBuffer.allocateDirect(26 + 20); + for (int i = 0; i < 26; i++) { + byteBuffer.put((byte) ('A' + i)); + } + for (int i = 0; i < 5; i++) { + byteBuffer.putInt(i + 1); + } + byteBuffer.rewind(); + fileChannel.write(byteBuffer); + fileChannel.close(); + fileOutputStream.close(); + + emptyFile = File.createTempFile("harmony", "test"); //$NON-NLS-1$//$NON-NLS-2$ + emptyFile.deleteOnExit(); + } + + public void test_position() throws IOException { + File tmp = File.createTempFile("hmy", "tmp"); + tmp.deleteOnExit(); + RandomAccessFile f = new RandomAccessFile(tmp, "rw"); + FileChannel ch = f.getChannel(); + MappedByteBuffer mbb = ch.map(MapMode.READ_WRITE, 0L, 100L); + ch.close(); + + mbb.putInt(1, 1); + mbb.position(50); + mbb.putInt(50); + + mbb.flip(); + mbb.get(); + assertEquals(1, mbb.getInt()); + + mbb.position(50); + assertEquals(50, mbb.getInt()); + } +} 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/nio/tests/java/nio/ReadOnlyBufferExceptionTest.java new file mode 100644 index 0000000..cbacbc5 --- /dev/null +++ b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/ReadOnlyBufferExceptionTest.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.nio.tests.java.nio; + +import java.nio.ReadOnlyBufferException; + +import junit.framework.TestCase; + +import org.apache.harmony.testframework.serialization.SerializationTest; + +public class ReadOnlyBufferExceptionTest extends TestCase { + + /** + * @tests serialization/deserialization compatibility. + */ + public void testSerializationSelf() throws Exception { + + SerializationTest.verifySelf(new ReadOnlyBufferException()); + } + + /** + * @tests serialization/deserialization compatibility with RI. + */ + public void testSerializationCompatibility() throws Exception { + + SerializationTest.verifyGolden(this, new ReadOnlyBufferException()); + } + + /** + *@tests {@link java.nio.ReadOnlyBufferException#ReadOnlyBufferException()} + */ + public void test_Constructor() { + ReadOnlyBufferException exception = new ReadOnlyBufferException(); + assertNull(exception.getMessage()); + assertNull(exception.getLocalizedMessage()); + assertNull(exception.getCause()); + } +} 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/nio/tests/java/nio/ReadOnlyCharBufferTest.java new file mode 100644 index 0000000..f951962 --- /dev/null +++ b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/ReadOnlyCharBufferTest.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.nio.tests.java.nio; + +import java.nio.CharBuffer; +import java.nio.ReadOnlyBufferException; + +public class ReadOnlyCharBufferTest extends CharBufferTest { + + protected void setUp() throws Exception { + super.setUp(); + loadTestData1(buf); + buf = buf.asReadOnlyBuffer(); + baseBuf = buf; + } + + protected void tearDown() throws Exception { + buf = null; + baseBuf = null; + super.tearDown(); + } + + public void testIsReadOnly() { + assertTrue(buf.isReadOnly()); + } + + public void testHasArray() { + assertFalse(buf.hasArray()); + } + + public void testArray() { + try { + buf.array(); + fail("Should throw ReadOnlyBufferException"); //$NON-NLS-1$ + } catch (ReadOnlyBufferException e) { + } + } + + public void testHashCode() { + CharBuffer duplicate = buf.duplicate(); + assertEquals(buf.hashCode(), duplicate.hashCode()); + } + + public void testArrayOffset() { + try { + buf.arrayOffset(); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (UnsupportedOperationException e) { + } + } + + public void testCompact() { + try { + buf.compact(); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (ReadOnlyBufferException e) { + // expected + } + } + + public void testPutchar() { + try { + buf.put((char) 0); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (ReadOnlyBufferException e) { + // expected + } + } + + public void testPutcharArray() { + char array[] = new char[1]; + try { + buf.put(array); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (ReadOnlyBufferException e) { + // expected + } + try { + buf.put((char[]) null); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (NullPointerException e) { + // expected + } + } + + public void testPutcharArrayintint() { + char array[] = new char[1]; + try { + buf.put(array, 0, array.length); + fail("Should throw ReadOnlyBufferException"); //$NON-NLS-1$ + } catch (ReadOnlyBufferException e) { + // expected + } + try { + buf.put((char[]) null, 0, 1); + fail("Should throw ReadOnlyBufferException"); //$NON-NLS-1$ + } catch (ReadOnlyBufferException e) { + // expected + } + try { + buf.put(new char[buf.capacity() + 1], 0, buf.capacity() + 1); + fail("Should throw ReadOnlyBufferException"); //$NON-NLS-1$ + } catch (ReadOnlyBufferException e) { + // expected + } + try { + buf.put(array, -1, array.length); + fail("Should throw ReadOnlyBufferException"); //$NON-NLS-1$ + } catch (ReadOnlyBufferException e) { + // expected + } + } + + public void testPutCharBuffer() { + CharBuffer other = CharBuffer.allocate(1); + try { + buf.put(other); + fail("Should throw ReadOnlyBufferException"); //$NON-NLS-1$ + } catch (ReadOnlyBufferException e) { + // expected + } + try { + buf.put((CharBuffer) null); + fail("Should throw ReadOnlyBufferException"); //$NON-NLS-1$ + } catch (ReadOnlyBufferException e) { + // expected + } + try { + buf.put(buf); + fail("Should throw ReadOnlyBufferException"); //$NON-NLS-1$ + } catch (ReadOnlyBufferException e) { + // expected + } + } + + public void testPutintchar() { + try { + buf.put(0, (char) 0); + fail("Should throw ReadOnlyBufferException"); //$NON-NLS-1$ + } catch (ReadOnlyBufferException e) { + // expected + } + try { + buf.put(-1, (char) 0); + fail("Should throw ReadOnlyBufferException"); //$NON-NLS-1$ + } catch (ReadOnlyBufferException e) { + // expected + } + } + + public void testPutStringintint() { + buf.clear(); + String str = String.valueOf(new char[buf.capacity()]); + try { + buf.put(str, 0, str.length()); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (ReadOnlyBufferException e) { + // expected + } + try { + buf.put((String) null, 0, 0); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (ReadOnlyBufferException expected) { + } catch (NullPointerException expected) { + } + try { + buf.put(str, -1, str.length()); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (ReadOnlyBufferException expected) { + } catch (NullPointerException expected) { + } + String longStr = String.valueOf(new char[buf.capacity()+1]); + try { + buf.put(longStr, 0, longStr.length()); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (ReadOnlyBufferException e) { + // expected + } + } + + public void testPutString() { + String str = " "; + try { + buf.put(str); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (ReadOnlyBufferException e) { + // expected + } + try { + buf.put((String)null); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (NullPointerException e) { + // expected + } + } +} 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/nio/tests/java/nio/ReadOnlyDirectByteBufferTest.java new file mode 100644 index 0000000..20c7914 --- /dev/null +++ b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/ReadOnlyDirectByteBufferTest.java @@ -0,0 +1,44 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.harmony.nio.tests.java.nio; + + +public class ReadOnlyDirectByteBufferTest extends DirectByteBufferTest { + + protected void setUp() throws Exception { + super.setUp(); + buf = buf.asReadOnlyBuffer(); + baseBuf = buf; + } + + protected void tearDown() throws Exception { + super.tearDown(); + } + + public void testIsReadOnly() { + assertTrue(buf.isReadOnly()); + } + + public void testHasArray() { + assertFalse(buf.hasArray()); + } + + public void testHashCode() { + super.readOnlyHashCode(); + } + +} 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/nio/tests/java/nio/ReadOnlyDoubleBufferTest.java new file mode 100644 index 0000000..d87e81d --- /dev/null +++ b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/ReadOnlyDoubleBufferTest.java @@ -0,0 +1,160 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.harmony.nio.tests.java.nio; + +import java.nio.DoubleBuffer; +import java.nio.ReadOnlyBufferException; + +public class ReadOnlyDoubleBufferTest extends DoubleBufferTest { + + protected void setUp() throws Exception { + super.setUp(); + buf = buf.asReadOnlyBuffer(); + baseBuf = buf; + } + + protected void tearDown() throws Exception { + super.tearDown(); + } + + public void testIsReadOnly() { + assertTrue(buf.isReadOnly()); + } + + public void testHasArray() { + assertFalse(buf.hasArray()); + } + + public void testArray() { + try { + buf.array(); + fail("Should throw ReadOnlyBufferException"); //$NON-NLS-1$ + } catch (ReadOnlyBufferException e) { + } + } + + public void testHashCode() { + DoubleBuffer duplicate = buf.duplicate(); + assertEquals(buf.hashCode(), duplicate.hashCode()); + } + + public void testArrayOffset() { + try { + buf.arrayOffset(); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (UnsupportedOperationException e) { + } + } + + public void testCompact() { + try { + buf.compact(); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (ReadOnlyBufferException e) { + // expected + } + } + + public void testPutdouble() { + try { + buf.put(0); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (ReadOnlyBufferException e) { + // expected + } + } + + public void testPutdoubleArray() { + double array[] = new double[1]; + try { + buf.put(array); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (ReadOnlyBufferException e) { + // expected + } + try { + buf.put((double[]) null); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (NullPointerException e) { + // expected + } + } + + public void testPutdoubleArrayintint() { + double array[] = new double[1]; + try { + buf.put(array, 0, array.length); + fail("Should throw ReadOnlyBufferException"); //$NON-NLS-1$ + } catch (ReadOnlyBufferException e) { + // expected + } + try { + buf.put((double[]) null, 0, 1); + fail("Should throw ReadOnlyBufferException"); //$NON-NLS-1$ + } catch (ReadOnlyBufferException e) { + // expected + } + try { + buf.put(new double[buf.capacity() + 1], 0, buf.capacity() + 1); + fail("Should throw ReadOnlyBufferException"); //$NON-NLS-1$ + } catch (ReadOnlyBufferException e) { + // expected + } + try { + buf.put(array, -1, array.length); + fail("Should throw ReadOnlyBufferException"); //$NON-NLS-1$ + } catch (ReadOnlyBufferException e) { + // expected + } + } + + public void testPutDoubleBuffer() { + DoubleBuffer other = DoubleBuffer.allocate(1); + try { + buf.put(other); + fail("Should throw ReadOnlyBufferException"); //$NON-NLS-1$ + } catch (ReadOnlyBufferException e) { + // expected + } + try { + buf.put((DoubleBuffer) null); + fail("Should throw ReadOnlyBufferException"); //$NON-NLS-1$ + } catch (ReadOnlyBufferException e) { + // expected + } + try { + buf.put(buf); + fail("Should throw ReadOnlyBufferException"); //$NON-NLS-1$ + } catch (ReadOnlyBufferException e) { + // expected + } + } + + public void testPutintdouble() { + try { + buf.put(0, (double) 0); + fail("Should throw ReadOnlyBufferException"); //$NON-NLS-1$ + } catch (ReadOnlyBufferException e) { + // expected + } + try { + buf.put(-1, (double) 0); + fail("Should throw ReadOnlyBufferException"); //$NON-NLS-1$ + } catch (ReadOnlyBufferException e) { + // expected + } + } +} 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/nio/tests/java/nio/ReadOnlyFloatBufferTest.java new file mode 100644 index 0000000..3acc5c4 --- /dev/null +++ b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/ReadOnlyFloatBufferTest.java @@ -0,0 +1,161 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.harmony.nio.tests.java.nio; + +import java.nio.FloatBuffer; +import java.nio.ReadOnlyBufferException; + +public class ReadOnlyFloatBufferTest extends FloatBufferTest { + protected void setUp() throws Exception { + super.setUp(); + buf = buf.asReadOnlyBuffer(); + baseBuf = buf; + } + + protected void tearDown() throws Exception { + super.tearDown(); + } + + public void testIsReadOnly() { + assertTrue(buf.isReadOnly()); + } + + public void testHasArray() { + assertFalse(buf.hasArray()); + } + + public void testArray() { + try { + buf.array(); + fail("Should throw ReadOnlyBufferException"); //$NON-NLS-1$ + } catch (ReadOnlyBufferException e) { + //expected + } + } + + public void testHashCode() { + FloatBuffer duplicate = buf.duplicate(); + assertEquals(buf.hashCode(), duplicate.hashCode()); + } + + public void testArrayOffset() { + try { + buf.arrayOffset(); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (UnsupportedOperationException e) { + //expected + } + } + + public void testCompact() { + try { + buf.compact(); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (ReadOnlyBufferException e) { + // expected + } + } + + public void testPutfloat() { + try { + buf.put(0); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (ReadOnlyBufferException e) { + // expected + } + } + + public void testPutfloatArray() { + float array[] = new float[1]; + try { + buf.put(array); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (ReadOnlyBufferException e) { + // expected + } + try { + buf.put((float[]) null); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (NullPointerException e) { + // expected + } + } + + public void testPutfloatArrayintint() { + float array[] = new float[1]; + try { + buf.put(array, 0, array.length); + fail("Should throw ReadOnlyBufferException"); //$NON-NLS-1$ + } catch (ReadOnlyBufferException e) { + // expected + } + try { + buf.put((float[]) null, 0, 1); + fail("Should throw ReadOnlyBufferException"); //$NON-NLS-1$ + } catch (ReadOnlyBufferException e) { + // expected + } + try { + buf.put(new float[buf.capacity() + 1], 0, buf.capacity() + 1); + fail("Should throw ReadOnlyBufferException"); //$NON-NLS-1$ + } catch (ReadOnlyBufferException e) { + // expected + } + try { + buf.put(array, -1, array.length); + fail("Should throw ReadOnlyBufferException"); //$NON-NLS-1$ + } catch (ReadOnlyBufferException e) { + // expected + } + } + + public void testPutFloatBuffer() { + FloatBuffer other = FloatBuffer.allocate(1); + try { + buf.put(other); + fail("Should throw ReadOnlyBufferException"); //$NON-NLS-1$ + } catch (ReadOnlyBufferException e) { + // expected + } + try { + buf.put((FloatBuffer) null); + fail("Should throw ReadOnlyBufferException"); //$NON-NLS-1$ + } catch (ReadOnlyBufferException e) { + // expected + } + try { + buf.put(buf); + fail("Should throw ReadOnlyBufferException"); //$NON-NLS-1$ + } catch (ReadOnlyBufferException e) { + // expected + } + } + + public void testPutintfloat() { + try { + buf.put(0, (float) 0); + fail("Should throw ReadOnlyBufferException"); //$NON-NLS-1$ + } catch (ReadOnlyBufferException e) { + // expected + } + try { + buf.put(-1, (float) 0); + fail("Should throw ReadOnlyBufferException"); //$NON-NLS-1$ + } catch (ReadOnlyBufferException e) { + // expected + } + } +} 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/nio/tests/java/nio/ReadOnlyHeapByteBufferTest.java new file mode 100644 index 0000000..7452a24 --- /dev/null +++ b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/ReadOnlyHeapByteBufferTest.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.nio.tests.java.nio; + + +public class ReadOnlyHeapByteBufferTest extends HeapByteBufferTest { + + protected void setUp() throws Exception { + super.setUp(); + buf = buf.asReadOnlyBuffer(); + baseBuf = buf; + } + + protected void tearDown() throws Exception { + super.tearDown(); + } + + public void testIsReadOnly() { + assertTrue(buf.isReadOnly()); + } + + public void testHasArray() { + assertFalse(buf.hasArray()); + } + + public void testHashCode() { + super.readOnlyHashCode(); + } +} 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/nio/tests/java/nio/ReadOnlyHeapCharBufferTest.java new file mode 100644 index 0000000..4c7792a --- /dev/null +++ b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/ReadOnlyHeapCharBufferTest.java @@ -0,0 +1,35 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.harmony.nio.tests.java.nio; + +import java.nio.CharBuffer; + + +public class ReadOnlyHeapCharBufferTest extends ReadOnlyCharBufferTest { + + protected void setUp() throws Exception { + super.setUp(); + buf = CharBuffer.allocate(BUFFER_LENGTH); + super.loadTestData1(buf); + buf = buf.asReadOnlyBuffer(); + baseBuf = buf; + } + + protected void tearDown() throws Exception { + super.tearDown(); + } +} 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/nio/tests/java/nio/ReadOnlyHeapDoubleBufferTest.java new file mode 100644 index 0000000..f95c4c2 --- /dev/null +++ b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/ReadOnlyHeapDoubleBufferTest.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.nio.tests.java.nio; + +import java.nio.DoubleBuffer; + +public class ReadOnlyHeapDoubleBufferTest extends ReadOnlyDoubleBufferTest { + + protected void setUp() throws Exception { + super.setUp(); + buf = DoubleBuffer.allocate(BUFFER_LENGTH); + super.loadTestData1(buf); + buf = buf.asReadOnlyBuffer(); + baseBuf = buf; + } + + protected void tearDown() throws Exception { + super.tearDown(); + } + +} 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/nio/tests/java/nio/ReadOnlyHeapFloatBufferTest.java new file mode 100644 index 0000000..f2c6644 --- /dev/null +++ b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/ReadOnlyHeapFloatBufferTest.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.nio.tests.java.nio; + +import java.nio.FloatBuffer; + +public class ReadOnlyHeapFloatBufferTest extends ReadOnlyFloatBufferTest { + protected void setUp() throws Exception { + super.setUp(); + buf = FloatBuffer.allocate(BUFFER_LENGTH); + super.loadTestData1(buf); + buf = buf.asReadOnlyBuffer(); + baseBuf = buf; + } + + protected void tearDown() throws Exception { + super.tearDown(); + } +} 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/nio/tests/java/nio/ReadOnlyHeapIntBufferTest.java new file mode 100644 index 0000000..f9a3877 --- /dev/null +++ b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/ReadOnlyHeapIntBufferTest.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.nio.tests.java.nio; + +import java.nio.IntBuffer; + +public class ReadOnlyHeapIntBufferTest extends ReadOnlyIntBufferTest { + protected void setUp() throws Exception { + super.setUp(); + buf = IntBuffer.allocate(BUFFER_LENGTH); + super.loadTestData1(buf); + buf = buf.asReadOnlyBuffer(); + baseBuf = buf; + } + + protected void tearDown() throws Exception { + super.tearDown(); + } +} 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/nio/tests/java/nio/ReadOnlyHeapLongBufferTest.java new file mode 100644 index 0000000..efba978 --- /dev/null +++ b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/ReadOnlyHeapLongBufferTest.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.nio.tests.java.nio; + +import java.nio.LongBuffer; + +public class ReadOnlyHeapLongBufferTest extends ReadOnlyLongBufferTest{ + protected void setUp() throws Exception { + super.setUp(); + buf = LongBuffer.allocate(BUFFER_LENGTH); + super.loadTestData1(buf); + buf = buf.asReadOnlyBuffer(); + baseBuf = buf; + } + + protected void tearDown() throws Exception { + super.tearDown(); + } +} 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/nio/tests/java/nio/ReadOnlyHeapShortBufferTest.java new file mode 100644 index 0000000..bbbd616 --- /dev/null +++ b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/ReadOnlyHeapShortBufferTest.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.nio.tests.java.nio; + +import java.nio.ShortBuffer; + +public class ReadOnlyHeapShortBufferTest extends ReadOnlyShortBufferTest { + protected void setUp() throws Exception { + super.setUp(); + buf = ShortBuffer.allocate(BUFFER_LENGTH); + super.loadTestData1(buf); + buf = buf.asReadOnlyBuffer(); + baseBuf = buf; + } + + protected void tearDown() throws Exception { + super.tearDown(); + } +} 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/nio/tests/java/nio/ReadOnlyIntBufferTest.java new file mode 100644 index 0000000..61e78a6 --- /dev/null +++ b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/ReadOnlyIntBufferTest.java @@ -0,0 +1,161 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.harmony.nio.tests.java.nio; + +import java.nio.IntBuffer; +import java.nio.ReadOnlyBufferException; + +public class ReadOnlyIntBufferTest extends IntBufferTest { + protected void setUp() throws Exception { + super.setUp(); + buf = buf.asReadOnlyBuffer(); + baseBuf = buf; + } + + protected void tearDown() throws Exception { + super.tearDown(); + } + + public void testIsReadOnly() { + assertTrue(buf.isReadOnly()); + } + + public void testHasArray() { + assertFalse(buf.hasArray()); + } + + public void testArray() { + try { + buf.array(); + fail("Should throw ReadOnlyBufferException"); //$NON-NLS-1$ + } catch (ReadOnlyBufferException e) { + //expected + } + } + + public void testHashCode() { + IntBuffer duplicate = buf.duplicate(); + assertEquals(buf.hashCode(), duplicate.hashCode()); + } + + public void testArrayOffset() { + try { + buf.arrayOffset(); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (UnsupportedOperationException e) { + //expected + } + } + + public void testCompact() { + try { + buf.compact(); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (ReadOnlyBufferException e) { + // expected + } + } + + public void testPutint() { + try { + buf.put(0); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (ReadOnlyBufferException e) { + // expected + } + } + + public void testPutintArray() { + int array[] = new int[1]; + try { + buf.put(array); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (ReadOnlyBufferException e) { + // expected + } + try { + buf.put((int[]) null); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (NullPointerException e) { + // expected + } + } + + public void testPutintArrayintint() { + int array[] = new int[1]; + try { + buf.put(array, 0, array.length); + fail("Should throw ReadOnlyBufferException"); //$NON-NLS-1$ + } catch (ReadOnlyBufferException e) { + // expected + } + try { + buf.put((int[]) null, -1, 1); + fail("Should throw ReadOnlyBufferException"); //$NON-NLS-1$ + } catch (ReadOnlyBufferException e) { + // expected + } + try { + buf.put(new int[buf.capacity() + 1], 0, buf.capacity() + 1); + fail("Should throw ReadOnlyBufferException"); //$NON-NLS-1$ + } catch (ReadOnlyBufferException e) { + // expected + } + try { + buf.put(array, -1, array.length); + fail("Should throw ReadOnlyBufferException"); //$NON-NLS-1$ + } catch (ReadOnlyBufferException e) { + // expected + } + } + + public void testPutIntBuffer() { + IntBuffer other = IntBuffer.allocate(1); + try { + buf.put(other); + fail("Should throw ReadOnlyBufferException"); //$NON-NLS-1$ + } catch (ReadOnlyBufferException e) { + // expected + } + try { + buf.put((IntBuffer) null); + fail("Should throw ReadOnlyBufferException"); //$NON-NLS-1$ + } catch (ReadOnlyBufferException e) { + // expected + } + try { + buf.put(buf); + fail("Should throw ReadOnlyBufferException"); //$NON-NLS-1$ + } catch (ReadOnlyBufferException e) { + // expected + } + } + + public void testPutintint() { + try { + buf.put(0, (int) 0); + fail("Should throw ReadOnlyBufferException"); //$NON-NLS-1$ + } catch (ReadOnlyBufferException e) { + // expected + } + try { + buf.put(-1, (int) 0); + fail("Should throw ReadOnlyBufferException"); //$NON-NLS-1$ + } catch (ReadOnlyBufferException e) { + // expected + } + } +} 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/nio/tests/java/nio/ReadOnlyLongBufferTest.java new file mode 100644 index 0000000..b670606 --- /dev/null +++ b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/ReadOnlyLongBufferTest.java @@ -0,0 +1,161 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.harmony.nio.tests.java.nio; + +import java.nio.LongBuffer; +import java.nio.ReadOnlyBufferException; + +public class ReadOnlyLongBufferTest extends LongBufferTest { + protected void setUp() throws Exception { + super.setUp(); + buf = buf.asReadOnlyBuffer(); + baseBuf = buf; + } + + protected void tearDown() throws Exception { + super.tearDown(); + } + + public void testIsReadOnly() { + assertTrue(buf.isReadOnly()); + } + + public void testHasArray() { + assertFalse(buf.hasArray()); + } + + public void testArray() { + try { + buf.array(); + fail("Should throw ReadOnlyBufferException"); //$NON-NLS-1$ + } catch (ReadOnlyBufferException e) { + //expected + } + } + + public void testHashCode() { + LongBuffer duplicate = buf.duplicate(); + assertEquals(buf.hashCode(), duplicate.hashCode()); + } + + public void testArrayOffset() { + try { + buf.arrayOffset(); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (UnsupportedOperationException e) { + //expected + } + } + + public void testCompact() { + try { + buf.compact(); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (ReadOnlyBufferException e) { + // expected + } + } + + public void testPutlong() { + try { + buf.put(0); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (ReadOnlyBufferException e) { + // expected + } + } + + public void testPutlongArray() { + long array[] = new long[1]; + try { + buf.put(array); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (ReadOnlyBufferException e) { + // expected + } + try { + buf.put((long[]) null); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (NullPointerException e) { + // expected + } + } + + public void testPutlongArrayintint() { + long array[] = new long[1]; + try { + buf.put(array, 0, array.length); + fail("Should throw ReadOnlyBufferException"); //$NON-NLS-1$ + } catch (ReadOnlyBufferException e) { + // expected + } + try { + buf.put((long[]) null, 0, 1); + fail("Should throw ReadOnlyBufferException"); //$NON-NLS-1$ + } catch (ReadOnlyBufferException e) { + // expected + } + try { + buf.put(new long[buf.capacity() + 1], 0, buf.capacity() + 1); + fail("Should throw ReadOnlyBufferException"); //$NON-NLS-1$ + } catch (ReadOnlyBufferException e) { + // expected + } + try { + buf.put(array, -1, array.length); + fail("Should throw ReadOnlyBufferException"); //$NON-NLS-1$ + } catch (ReadOnlyBufferException e) { + // expected + } + } + + public void testPutLongBuffer() { + LongBuffer other = LongBuffer.allocate(1); + try { + buf.put(other); + fail("Should throw ReadOnlyBufferException"); //$NON-NLS-1$ + } catch (ReadOnlyBufferException e) { + // expected + } + try { + buf.put((LongBuffer) null); + fail("Should throw ReadOnlyBufferException"); //$NON-NLS-1$ + } catch (ReadOnlyBufferException e) { + // expected + } + try { + buf.put(buf); + fail("Should throw ReadOnlyBufferException"); //$NON-NLS-1$ + } catch (ReadOnlyBufferException e) { + // expected + } + } + + public void testPutintlong() { + try { + buf.put(0, (long) 0); + fail("Should throw ReadOnlyBufferException"); //$NON-NLS-1$ + } catch (ReadOnlyBufferException e) { + // expected + } + try { + buf.put(-1, (long) 0); + fail("Should throw ReadOnlyBufferException"); //$NON-NLS-1$ + } catch (ReadOnlyBufferException e) { + // expected + } + } +} 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/nio/tests/java/nio/ReadOnlyShortBufferTest.java new file mode 100644 index 0000000..611f6bf --- /dev/null +++ b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/ReadOnlyShortBufferTest.java @@ -0,0 +1,161 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.harmony.nio.tests.java.nio; + +import java.nio.ReadOnlyBufferException; +import java.nio.ShortBuffer; + +public class ReadOnlyShortBufferTest extends ShortBufferTest { + protected void setUp() throws Exception { + super.setUp(); + buf = buf.asReadOnlyBuffer(); + baseBuf = buf; + } + + protected void tearDown() throws Exception { + super.tearDown(); + } + + public void testIsReadOnly() { + assertTrue(buf.isReadOnly()); + } + + public void testHasArray() { + assertFalse(buf.hasArray()); + } + + public void testArray() { + try { + buf.array(); + fail("Should throw ReadOnlyBufferException"); //$NON-NLS-1$ + } catch (ReadOnlyBufferException e) { + //expected + } + } + + public void testHashCode() { + ShortBuffer duplicate = buf.duplicate(); + assertEquals(buf.hashCode(), duplicate.hashCode()); + } + + public void testArrayOffset() { + try { + buf.arrayOffset(); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (UnsupportedOperationException e) { + //expected + } + } + + public void testCompact() { + try { + buf.compact(); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (ReadOnlyBufferException e) { + // expected + } + } + + public void testPutshort() { + try { + buf.put((short)0); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (ReadOnlyBufferException e) { + // expected + } + } + + public void testPutshortArray() { + short array[] = new short[1]; + try { + buf.put(array); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (ReadOnlyBufferException e) { + // expected + } + try { + buf.put((short[]) null); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (NullPointerException e) { + // expected + } + } + + public void testPutshortArrayintint() { + short array[] = new short[1]; + try { + buf.put(array, 0, array.length); + fail("Should throw ReadOnlyBufferException"); //$NON-NLS-1$ + } catch (ReadOnlyBufferException e) { + // expected + } + try { + buf.put((short[]) null, 0, 1); + fail("Should throw ReadOnlyBufferException"); //$NON-NLS-1$ + } catch (ReadOnlyBufferException e) { + // expected + } + try { + buf.put(new short[buf.capacity() + 1], 0, buf.capacity() + 1); + fail("Should throw ReadOnlyBufferException"); //$NON-NLS-1$ + } catch (ReadOnlyBufferException e) { + // expected + } + try { + buf.put(array, -1, array.length); + fail("Should throw ReadOnlyBufferException"); //$NON-NLS-1$ + } catch (ReadOnlyBufferException e) { + // expected + } + } + + public void testPutShortBuffer() { + ShortBuffer other = ShortBuffer.allocate(1); + try { + buf.put(other); + fail("Should throw ReadOnlyBufferException"); //$NON-NLS-1$ + } catch (ReadOnlyBufferException e) { + // expected + } + try { + buf.put((ShortBuffer) null); + fail("Should throw ReadOnlyBufferException"); //$NON-NLS-1$ + } catch (ReadOnlyBufferException e) { + // expected + } + try { + buf.put(buf); + fail("Should throw ReadOnlyBufferException"); //$NON-NLS-1$ + } catch (ReadOnlyBufferException e) { + // expected + } + } + + public void testPutintshort() { + try { + buf.put(0, (short) 0); + fail("Should throw ReadOnlyBufferException"); //$NON-NLS-1$ + } catch (ReadOnlyBufferException e) { + // expected + } + try { + buf.put(-1, (short) 0); + fail("Should throw ReadOnlyBufferException"); //$NON-NLS-1$ + } catch (ReadOnlyBufferException e) { + // expected + } + } +} 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/nio/tests/java/nio/ReadOnlyWrappedByteBufferTest.java new file mode 100644 index 0000000..031d75b --- /dev/null +++ b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/ReadOnlyWrappedByteBufferTest.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.nio.tests.java.nio; + + +public class ReadOnlyWrappedByteBufferTest extends WrappedByteBufferTest { + + protected void setUp() throws Exception { + super.setUp(); + buf = buf.asReadOnlyBuffer(); + baseBuf = buf; + } + + protected void tearDown() throws Exception { + super.tearDown(); + } + + public void testIsReadOnly() { + assertTrue(buf.isReadOnly()); + } + + public void testHasArray() { + assertFalse(buf.hasArray()); + } + + public void testHashCode() { + super.readOnlyHashCode(); + } + + +} 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/nio/tests/java/nio/ReadOnlyWrappedCharBufferTest1.java new file mode 100644 index 0000000..57c04bf --- /dev/null +++ b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/ReadOnlyWrappedCharBufferTest1.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.nio.tests.java.nio; + +import java.nio.CharBuffer; + +public class ReadOnlyWrappedCharBufferTest1 extends ReadOnlyCharBufferTest { + + protected void setUp() throws Exception { + super.setUp(); + buf = CharBuffer.wrap(new char[BUFFER_LENGTH]); + super.loadTestData1(buf); + buf = buf.asReadOnlyBuffer(); + baseBuf = buf; + } + + protected void tearDown() throws Exception { + super.tearDown(); + } +} 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/nio/tests/java/nio/ReadOnlyWrappedDoubleBufferTest.java new file mode 100644 index 0000000..d1ba9df --- /dev/null +++ b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/ReadOnlyWrappedDoubleBufferTest.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.nio.tests.java.nio; + +import java.nio.DoubleBuffer; + +public class ReadOnlyWrappedDoubleBufferTest extends ReadOnlyDoubleBufferTest { + protected void setUp() throws Exception { + super.setUp(); + buf = DoubleBuffer.wrap(new double[BUFFER_LENGTH]); + super.loadTestData1(buf); + buf = buf.asReadOnlyBuffer(); + baseBuf = buf; + } + + protected void tearDown() throws Exception { + super.tearDown(); + } +} 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/nio/tests/java/nio/ReadOnlyWrappedFloatBufferTest.java new file mode 100644 index 0000000..affddaa --- /dev/null +++ b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/ReadOnlyWrappedFloatBufferTest.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.nio.tests.java.nio; + +import java.nio.FloatBuffer; + +public class ReadOnlyWrappedFloatBufferTest extends ReadOnlyFloatBufferTest { + protected void setUp() throws Exception { + super.setUp(); + buf = FloatBuffer.wrap(new float[BUFFER_LENGTH]); + super.loadTestData1(buf); + buf = buf.asReadOnlyBuffer(); + baseBuf = buf; + } + + protected void tearDown() throws Exception { + super.tearDown(); + } +} 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/nio/tests/java/nio/ReadOnlyWrappedIntBufferTest.java new file mode 100644 index 0000000..a4d0155 --- /dev/null +++ b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/ReadOnlyWrappedIntBufferTest.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.nio.tests.java.nio; + +import java.nio.IntBuffer; + +public class ReadOnlyWrappedIntBufferTest extends ReadOnlyIntBufferTest { + protected void setUp() throws Exception { + super.setUp(); + buf = IntBuffer.wrap(new int[BUFFER_LENGTH]); + super.loadTestData1(buf); + buf = buf.asReadOnlyBuffer(); + baseBuf = buf; + } + + protected void tearDown() throws Exception { + super.tearDown(); + } +} 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/nio/tests/java/nio/ReadOnlyWrappedLongBufferTest.java new file mode 100644 index 0000000..58491da --- /dev/null +++ b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/ReadOnlyWrappedLongBufferTest.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.nio.tests.java.nio; + +import java.nio.LongBuffer; + +public class ReadOnlyWrappedLongBufferTest extends ReadOnlyLongBufferTest{ + protected void setUp() throws Exception { + super.setUp(); + buf = LongBuffer.wrap(new long[BUFFER_LENGTH]); + super.loadTestData1(buf); + buf = buf.asReadOnlyBuffer(); + baseBuf = buf; + } + + protected void tearDown() throws Exception { + super.tearDown(); + } +} 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/nio/tests/java/nio/ReadOnlyWrappedShortBufferTest.java new file mode 100644 index 0000000..0ecb3a4 --- /dev/null +++ b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/ReadOnlyWrappedShortBufferTest.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.nio.tests.java.nio; + +import java.nio.ShortBuffer; + +public class ReadOnlyWrappedShortBufferTest extends ReadOnlyShortBufferTest { + protected void setUp() throws Exception { + super.setUp(); + buf = ShortBuffer.wrap(new short[BUFFER_LENGTH]); + super.loadTestData1(buf); + buf = buf.asReadOnlyBuffer(); + baseBuf = buf; + } + + protected void tearDown() throws Exception { + super.tearDown(); + } +} 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/nio/tests/java/nio/ShortBufferTest.java new file mode 100644 index 0000000..98d7659 --- /dev/null +++ b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/ShortBufferTest.java @@ -0,0 +1,637 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.harmony.nio.tests.java.nio; + +import java.nio.BufferOverflowException; +import java.nio.BufferUnderflowException; +import java.nio.ByteOrder; +import java.nio.InvalidMarkException; +import java.nio.ShortBuffer; + +/** + * Tests java.nio.ShortBuffer + * + */ +public class ShortBufferTest extends AbstractBufferTest { + + protected static final int SMALL_TEST_LENGTH = 5; + + protected static final int BUFFER_LENGTH = 20; + + protected ShortBuffer buf; + + protected void setUp() throws Exception { + buf = ShortBuffer.allocate(BUFFER_LENGTH); + loadTestData1(buf); + baseBuf = buf; + } + + protected void tearDown() throws Exception { + buf = null; + baseBuf = null; + } + + public void testArray() { + short array[] = buf.array(); + assertContentEquals(buf, array, buf.arrayOffset(), buf.capacity()); + + loadTestData1(array, buf.arrayOffset(), buf.capacity()); + assertContentEquals(buf, array, buf.arrayOffset(), buf.capacity()); + + loadTestData2(array, buf.arrayOffset(), buf.capacity()); + assertContentEquals(buf, array, buf.arrayOffset(), buf.capacity()); + + loadTestData1(buf); + assertContentEquals(buf, array, buf.arrayOffset(), buf.capacity()); + + loadTestData2(buf); + assertContentEquals(buf, array, buf.arrayOffset(), buf.capacity()); + } + + public void testArrayOffset() { + short array[] = buf.array(); + assertContentEquals(buf, array, buf.arrayOffset(), buf.capacity()); + + loadTestData1(array, buf.arrayOffset(), buf.capacity()); + assertContentEquals(buf, array, buf.arrayOffset(), buf.capacity()); + + loadTestData2(array, buf.arrayOffset(), buf.capacity()); + assertContentEquals(buf, array, buf.arrayOffset(), buf.capacity()); + + loadTestData1(buf); + assertContentEquals(buf, array, buf.arrayOffset(), buf.capacity()); + + loadTestData2(buf); + assertContentEquals(buf, array, buf.arrayOffset(), buf.capacity()); + } + + public void testAsReadOnlyBuffer() { + buf.clear(); + buf.mark(); + buf.position(buf.limit()); + + // readonly's contents should be the same as buf + ShortBuffer readonly = buf.asReadOnlyBuffer(); + assertNotSame(buf, readonly); + assertTrue(readonly.isReadOnly()); + assertEquals(buf.position(), readonly.position()); + assertEquals(buf.limit(), readonly.limit()); + assertEquals(buf.isDirect(), readonly.isDirect()); + assertEquals(buf.order(), readonly.order()); + assertContentEquals(buf, readonly); + + // readonly's position, mark, and limit should be independent to buf + readonly.reset(); + assertEquals(readonly.position(), 0); + readonly.clear(); + assertEquals(buf.position(), buf.limit()); + buf.reset(); + assertEquals(buf.position(), 0); + } + + public void testCompact() { + // case: buffer is full + buf.clear(); + buf.mark(); + loadTestData1(buf); + ShortBuffer ret = buf.compact(); + assertSame(ret, buf); + assertEquals(buf.position(), buf.capacity()); + assertEquals(buf.limit(), buf.capacity()); + assertContentLikeTestData1(buf, 0, (short) 0, buf.capacity()); + try { + buf.reset(); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (InvalidMarkException e) { + // expected + } + + // case: buffer is empty + buf.position(0); + buf.limit(0); + buf.mark(); + ret = buf.compact(); + assertSame(ret, buf); + assertEquals(buf.position(), 0); + assertEquals(buf.limit(), buf.capacity()); + assertContentLikeTestData1(buf, 0, (short) 0, buf.capacity()); + try { + buf.reset(); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (InvalidMarkException e) { + // expected + } + + // case: normal + assertTrue(buf.capacity() > 5); + buf.position(1); + buf.limit(5); + buf.mark(); + ret = buf.compact(); + assertSame(ret, buf); + assertEquals(buf.position(), 4); + assertEquals(buf.limit(), buf.capacity()); + assertContentLikeTestData1(buf, 0, (short) 1, 4); + try { + buf.reset(); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (InvalidMarkException e) { + // expected + } + } + + public void testCompareTo() { + // compare to self + assertEquals(0, buf.compareTo(buf)); + + // normal cases + assertTrue(buf.capacity() > 5); + buf.clear(); + ShortBuffer other = ShortBuffer.allocate(buf.capacity()); + loadTestData1(other); + assertEquals(0, buf.compareTo(other)); + assertEquals(0, other.compareTo(buf)); + buf.position(1); + assertTrue(buf.compareTo(other) > 0); + assertTrue(other.compareTo(buf) < 0); + other.position(2); + assertTrue(buf.compareTo(other) < 0); + assertTrue(other.compareTo(buf) > 0); + buf.position(2); + other.limit(5); + assertTrue(buf.compareTo(other) > 0); + assertTrue(other.compareTo(buf) < 0); + } + + public void testDuplicate() { + buf.clear(); + buf.mark(); + buf.position(buf.limit()); + + // duplicate's contents should be the same as buf + ShortBuffer duplicate = buf.duplicate(); + assertNotSame(buf, duplicate); + assertEquals(buf.position(), duplicate.position()); + assertEquals(buf.limit(), duplicate.limit()); + assertEquals(buf.isReadOnly(), duplicate.isReadOnly()); + assertEquals(buf.isDirect(), duplicate.isDirect()); + assertEquals(buf.order(), duplicate.order()); + assertContentEquals(buf, duplicate); + + // duplicate's position, mark, and limit should be independent to buf + duplicate.reset(); + assertEquals(duplicate.position(), 0); + duplicate.clear(); + assertEquals(buf.position(), buf.limit()); + buf.reset(); + assertEquals(buf.position(), 0); + + // duplicate share the same content with buf + if (!duplicate.isReadOnly()) { + loadTestData1(buf); + assertContentEquals(buf, duplicate); + loadTestData2(duplicate); + assertContentEquals(buf, duplicate); + } + } + + public void testEquals() { + // equal to self + assertTrue(buf.equals(buf)); + ShortBuffer readonly = buf.asReadOnlyBuffer(); + assertTrue(buf.equals(readonly)); + ShortBuffer duplicate = buf.duplicate(); + assertTrue(buf.equals(duplicate)); + + // always false, if type mismatch + assertFalse(buf.equals(Boolean.TRUE)); + + assertTrue(buf.capacity() > 5); + + buf.limit(buf.capacity()).position(0); + readonly.limit(readonly.capacity()).position(1); + assertFalse(buf.equals(readonly)); + + buf.limit(buf.capacity() - 1).position(0); + duplicate.limit(duplicate.capacity()).position(0); + assertFalse(buf.equals(duplicate)); + } + + /* + * Class under test for short get() + */ + public void testGet() { + buf.clear(); + for (int i = 0; i < buf.capacity(); i++) { + assertEquals(buf.position(), i); + assertEquals(buf.get(), buf.get(i)); + } + try { + buf.get(); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (BufferUnderflowException e) { + // expected + } + } + + /* + * Class under test for java.nio.ShortBuffer get(short[]) + */ + public void testGetshortArray() { + short array[] = new short[1]; + buf.clear(); + for (int i = 0; i < buf.capacity(); i++) { + assertEquals(buf.position(), i); + ShortBuffer ret = buf.get(array); + assertEquals(array[0], buf.get(i)); + assertSame(ret, buf); + } + try { + buf.get(array); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (BufferUnderflowException e) { + // expected + } + } + + /* + * Class under test for java.nio.ShortBuffer get(short[], int, int) + */ + public void testGetshortArrayintint() { + buf.clear(); + short array[] = new short[buf.capacity()]; + + try { + buf.get(new short[buf.capacity() + 1], 0, buf.capacity() + 1); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (BufferUnderflowException e) { + // expected + } + assertEquals(buf.position(), 0); + try { + buf.get(array, -1, array.length); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (IndexOutOfBoundsException e) { + // expected + } + buf.get(array, array.length, 0); + try { + buf.get(array, array.length + 1, 1); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (IndexOutOfBoundsException e) { + // expected + } + assertEquals(buf.position(), 0); + try { + buf.get((short[])null, 2, -1); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (NullPointerException e) { + // expected + } + try { + buf.get(array, 2, array.length); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (IndexOutOfBoundsException e) { + // expected + } + try { + buf.get(array, 1, Integer.MAX_VALUE); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (BufferUnderflowException expected) { + } catch (IndexOutOfBoundsException expected) { + } + try { + buf.get(array, Integer.MAX_VALUE, 1); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (IndexOutOfBoundsException e) { + // expected + } + assertEquals(buf.position(), 0); + + buf.clear(); + ShortBuffer ret = buf.get(array, 0, array.length); + assertEquals(buf.position(), buf.capacity()); + assertContentEquals(buf, array, 0, array.length); + assertSame(ret, buf); + } + + /* + * Class under test for short get(int) + */ + public void testGetint() { + buf.clear(); + for (int i = 0; i < buf.capacity(); i++) { + assertEquals(buf.position(), i); + assertEquals(buf.get(), buf.get(i)); + } + try { + buf.get(-1); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (IndexOutOfBoundsException e) { + // expected + } + try { + buf.get(buf.limit()); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (IndexOutOfBoundsException e) { + // expected + } + } + + public void testHasArray() { + assertNotNull(buf.array()); + } + + public void testHashCode() { + buf.clear(); + ShortBuffer readonly = buf.asReadOnlyBuffer(); + ShortBuffer duplicate = buf.duplicate(); + assertTrue(buf.hashCode() == readonly.hashCode()); + + assertTrue(buf.capacity() > 5); + duplicate.position(buf.capacity() / 2); + assertTrue(buf.hashCode() != duplicate.hashCode()); + } + + public void testIsDirect() { + assertFalse(buf.isDirect()); + } + + public void testOrder() { + buf.order(); + assertEquals(ByteOrder.nativeOrder(), buf.order()); + } + + /* + * Class under test for java.nio.ShortBuffer put(short) + */ + public void testPutshort() { + buf.clear(); + for (int i = 0; i < buf.capacity(); i++) { + assertEquals(buf.position(), i); + ShortBuffer ret = buf.put((short) i); + assertEquals(buf.get(i), (short) i); + assertSame(ret, buf); + } + try { + buf.put((short) 0); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (BufferOverflowException e) { + // expected + } + } + + /* + * Class under test for java.nio.ShortBuffer put(short[]) + */ + public void testPutshortArray() { + short array[] = new short[1]; + buf.clear(); + for (int i = 0; i < buf.capacity(); i++) { + assertEquals(buf.position(), i); + array[0] = (short) i; + ShortBuffer ret = buf.put(array); + assertEquals(buf.get(i), (short) i); + assertSame(ret, buf); + } + try { + buf.put(array); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (BufferOverflowException e) { + // expected + } + try { + buf.position(buf.limit()); + buf.put((short[])null); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (NullPointerException e) { + // expected + } + } + + /* + * Class under test for java.nio.ShortBuffer put(short[], int, int) + */ + public void testPutshortArrayintint() { + buf.clear(); + short array[] = new short[buf.capacity()]; + try { + buf.put(new short[buf.capacity() + 1], 0, buf.capacity() + 1); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (BufferOverflowException e) { + // expected + } + assertEquals(buf.position(), 0); + try { + buf.put(array, -1, array.length); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (IndexOutOfBoundsException e) { + // expected + } + try { + buf.put(array, array.length + 1, 0); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (IndexOutOfBoundsException e) { + // expected + } + buf.put(array, array.length, 0); + assertEquals(buf.position(), 0); + try { + buf.put(array, 0, -1); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (IndexOutOfBoundsException e) { + // expected + } + try { + buf.put((short[])null, 0, -1); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (NullPointerException e) { + // expected + } + try { + buf.put(array, 2, array.length); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (IndexOutOfBoundsException e) { + // expected + } + try { + buf.put(array, Integer.MAX_VALUE, 1); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (IndexOutOfBoundsException e) { + // expected + } + try { + buf.put(array, 1, Integer.MAX_VALUE); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (BufferOverflowException expected) { + } catch (IndexOutOfBoundsException expected) { + } + assertEquals(buf.position(), 0); + + loadTestData2(array, 0, array.length); + ShortBuffer ret = buf.put(array, 0, array.length); + assertEquals(buf.position(), buf.capacity()); + assertContentEquals(buf, array, 0, array.length); + assertSame(ret, buf); + } + + /* + * Class under test for java.nio.ShortBuffer put(java.nio.ShortBuffer) + */ + public void testPutShortBuffer() { + ShortBuffer other = ShortBuffer.allocate(buf.capacity()); + try { + buf.put(buf); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (IllegalArgumentException e) { + // expected + } + try { + buf.put(ShortBuffer.allocate(buf.capacity() + 1)); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (BufferOverflowException e) { + // expected + } + try { + buf.flip(); + buf.put((ShortBuffer)null); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (NullPointerException e) { + // expected + } + + loadTestData2(other); + other.clear(); + buf.clear(); + ShortBuffer ret = buf.put(other); + assertEquals(other.position(), other.capacity()); + assertEquals(buf.position(), buf.capacity()); + assertContentEquals(other, buf); + assertSame(ret, buf); + } + + /* + * Class under test for java.nio.ShortBuffer put(int, short) + */ + public void testPutintshort() { + buf.clear(); + for (int i = 0; i < buf.capacity(); i++) { + assertEquals(buf.position(), 0); + ShortBuffer ret = buf.put(i, (short) i); + assertEquals(buf.get(i), (short) i); + assertSame(ret, buf); + } + try { + buf.put(-1, (short) 0); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (IndexOutOfBoundsException e) { + // expected + } + try { + buf.put(buf.limit(), (short) 0); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (IndexOutOfBoundsException e) { + // expected + } + } + + public void testSlice() { + assertTrue(buf.capacity() > 5); + buf.position(1); + buf.limit(buf.capacity() - 1); + + ShortBuffer slice = buf.slice(); + assertEquals(buf.isReadOnly(), slice.isReadOnly()); + assertEquals(buf.isDirect(), slice.isDirect()); + assertEquals(buf.order(), slice.order()); + assertEquals(slice.position(), 0); + assertEquals(slice.limit(), buf.remaining()); + assertEquals(slice.capacity(), buf.remaining()); + try { + slice.reset(); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (InvalidMarkException e) { + // expected + } + + // slice share the same content with buf + if (!slice.isReadOnly()) { + loadTestData1(slice); + assertContentLikeTestData1(buf, 1, (short) 0, slice.capacity()); + buf.put(2, (short) 500); + assertEquals(slice.get(1), 500); + } + } + + public void testToString() { + String str = buf.toString(); + assertTrue(str.indexOf("Short") >= 0 || str.indexOf("short") >= 0); + assertTrue(str.indexOf("" + buf.position()) >= 0); + assertTrue(str.indexOf("" + buf.limit()) >= 0); + assertTrue(str.indexOf("" + buf.capacity()) >= 0); + } + + void loadTestData1(short array[], int offset, int length) { + for (int i = 0; i < length; i++) { + array[offset + i] = (short) i; + } + } + + void loadTestData2(short array[], int offset, int length) { + for (int i = 0; i < length; i++) { + array[offset + i] = (short) (length - i); + } + } + + void loadTestData1(ShortBuffer buf) { + buf.clear(); + for (int i = 0; i < buf.capacity(); i++) { + buf.put(i, (short) i); + } + } + + void loadTestData2(ShortBuffer buf) { + buf.clear(); + for (int i = 0; i < buf.capacity(); i++) { + buf.put(i, (short) (buf.capacity() - i)); + } + } + + void assertContentEquals(ShortBuffer buf, short array[], + int offset, int length) { + for (int i = 0; i < length; i++) { + assertEquals(buf.get(i), array[offset + i]); + } + } + + void assertContentEquals(ShortBuffer buf, ShortBuffer other) { + assertEquals(buf.capacity(), other.capacity()); + for (int i = 0; i < buf.capacity(); i++) { + assertEquals(buf.get(i), other.get(i)); + } + } + + void assertContentLikeTestData1(ShortBuffer buf, + int startIndex, short startValue, int length) { + short value = startValue; + for (int i = 0; i < length; i++) { + assertEquals(buf.get(startIndex + i), value); + value = (short) (value + 1); + } + } +} diff --git a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/SliceDirectByteBufferTest.java b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/SliceDirectByteBufferTest.java new file mode 100644 index 0000000..541cde0 --- /dev/null +++ b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/SliceDirectByteBufferTest.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.nio.tests.java.nio; + + +public class SliceDirectByteBufferTest extends DirectByteBufferTest { + + protected void setUp() throws Exception { + super.setUp(); + buf.position(1).limit(BUFFER_LENGTH-1); + buf = buf.slice(); + baseBuf = buf; + } + + protected void tearDown() throws Exception { + super.tearDown(); + } +} 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/nio/tests/java/nio/SliceHeapByteBufferTest.java new file mode 100644 index 0000000..9f9f7aa --- /dev/null +++ b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/SliceHeapByteBufferTest.java @@ -0,0 +1,33 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.harmony.nio.tests.java.nio; + + +public class SliceHeapByteBufferTest extends HeapByteBufferTest { + + protected void setUp() throws Exception { + super.setUp(); + buf.position(1).limit(BUFFER_LENGTH-1); + buf = buf.slice(); + baseBuf = buf; + } + + protected void tearDown() throws Exception { + super.tearDown(); + } + +} 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/nio/tests/java/nio/SliceWrappedByteBufferTest.java new file mode 100644 index 0000000..f1ddfb9 --- /dev/null +++ b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/SliceWrappedByteBufferTest.java @@ -0,0 +1,33 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.harmony.nio.tests.java.nio; + + +public class SliceWrappedByteBufferTest extends WrappedByteBufferTest { + + protected void setUp() throws Exception { + super.setUp(); + buf.position(1).limit(BUFFER_LENGTH-1); + buf = buf.slice(); + baseBuf = buf; + } + + protected void tearDown() throws Exception { + super.tearDown(); + } + +} 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/nio/tests/java/nio/WrappedByteBufferTest.java new file mode 100644 index 0000000..6460d2e --- /dev/null +++ b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/WrappedByteBufferTest.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.nio.tests.java.nio; + +import java.nio.ByteBuffer; + +public class WrappedByteBufferTest extends ByteBufferTest { + + protected void setUp() throws Exception { + super.setUp(); + buf = ByteBuffer.wrap(new byte[BUFFER_LENGTH]); + baseBuf = buf; + } + + protected void tearDown() throws Exception { + super.tearDown(); + buf = null; + baseBuf = null; + } + + /** + * @tests java.nio.ByteBuffer#allocate(byte[],int,int) + * + */ + public void testWrappedByteBuffer_IllegalArg() { + byte array[] = new byte[BUFFER_LENGTH]; + try { + ByteBuffer.wrap(array, -1, 0); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (IndexOutOfBoundsException e) { + // expected + } + try { + ByteBuffer.wrap(array, BUFFER_LENGTH + 1, 0); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (IndexOutOfBoundsException e) { + // expected + } + try { + ByteBuffer.wrap(array, 0, -1); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (IndexOutOfBoundsException e) { + // expected + } + try { + ByteBuffer.wrap(array, 0, BUFFER_LENGTH + 1); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (IndexOutOfBoundsException e) { + // expected + } + try { + ByteBuffer.wrap(array, 1, Integer.MAX_VALUE); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (IndexOutOfBoundsException e) { + // expected + } + try { + ByteBuffer.wrap(array, Integer.MAX_VALUE, 1); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (IndexOutOfBoundsException e) { + // expected + } + try { + ByteBuffer.wrap((byte[])null, 1, Integer.MAX_VALUE); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (NullPointerException e) { + // expected + } + } + + public void testIsDirect() { + assertFalse(buf.isDirect()); + } + + public void testHasArray() { + assertTrue(buf.hasArray()); + } + + public void testIsReadOnly() { + assertFalse(buf.isReadOnly()); + } + +} 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/nio/tests/java/nio/WrappedCharBufferTest1.java new file mode 100644 index 0000000..9181a77 --- /dev/null +++ b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/WrappedCharBufferTest1.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.nio.tests.java.nio; + +import java.nio.CharBuffer; + +public class WrappedCharBufferTest1 extends CharBufferTest { + + protected void setUp() throws Exception { + super.setUp(); + buf = CharBuffer.wrap(new char[BUFFER_LENGTH]); + loadTestData1(buf); + baseBuf = buf; + } + + protected void tearDown() throws Exception { + super.tearDown(); + baseBuf = null; + buf = null; + } + + /** + * @tests java.nio.CharBuffer#allocate(char[],int,int) + * + */ + public void testWrappedCharBuffer_IllegalArg() { + char array[] = new char[BUFFER_LENGTH]; + try { + CharBuffer.wrap(array, -1, 0); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (IndexOutOfBoundsException e) { + // expected + } + try { + CharBuffer.wrap(array, BUFFER_LENGTH + 1, 0); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (IndexOutOfBoundsException e) { + // expected + } + try { + CharBuffer.wrap(array, 0, -1); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (IndexOutOfBoundsException e) { + // expected + } + try { + CharBuffer.wrap(array, 0, BUFFER_LENGTH + 1); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (IndexOutOfBoundsException e) { + // expected + } + try { + CharBuffer.wrap(array, Integer.MAX_VALUE, 1); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (IndexOutOfBoundsException e) { + // expected + } + try { + CharBuffer.wrap(array, 1, Integer.MAX_VALUE); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (IndexOutOfBoundsException e) { + // expected + } + try { + CharBuffer.wrap((char[])null, -1, 0); + fail("Should throw NPE"); //$NON-NLS-1$ + } catch (NullPointerException e) { + } + } +} 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/nio/tests/java/nio/WrappedCharBufferTest2.java new file mode 100644 index 0000000..5fa9335 --- /dev/null +++ b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/WrappedCharBufferTest2.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.nio.tests.java.nio; + +import java.nio.BufferOverflowException; +import java.nio.CharBuffer; +import java.nio.ReadOnlyBufferException; + +public class WrappedCharBufferTest2 extends ReadOnlyCharBufferTest { + protected static final String TEST_STRING = "123456789abcdef12345"; + + protected void setUp() throws Exception { + super.setUp(); + buf = CharBuffer.wrap(TEST_STRING); + baseBuf = buf; + } + + protected void tearDown() throws Exception { + super.tearDown(); + baseBuf = null; + buf = null; + } + + public void testWrappedCharSequence_IllegalArg() { + String str = TEST_STRING; + try { + CharBuffer.wrap(str, -1, 0); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (IndexOutOfBoundsException e) { + // expected + } + try { + CharBuffer.wrap(str, 21, 21); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (IndexOutOfBoundsException e) { + // expected + } + try { + CharBuffer.wrap(str, 2, 1); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (IndexOutOfBoundsException e) { + // expected + } + try { + CharBuffer.wrap(str, 0, 21); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (IndexOutOfBoundsException e) { + // expected + } + try { + CharBuffer.wrap((String)null, -1, 21); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (NullPointerException e) { + // expected + } + } + + public void testArray() { + try { + buf.array(); + fail("Should throw UnsupportedOperationException"); //$NON-NLS-1$ + } catch (UnsupportedOperationException e) { + } + } + + public void testPutcharArrayintint() { + char array[] = new char[1]; + try { + buf.put(array, 0, array.length); + fail("Should throw ReadOnlyBufferException"); //$NON-NLS-1$ + } catch (ReadOnlyBufferException e) { + // expected + } + try { + buf.put((char[]) null, 0, 1); + fail("Should throw NullPointerException"); //$NON-NLS-1$ + } catch (ReadOnlyBufferException expected) { + } catch (NullPointerException expected) { + } + try { + buf.put(new char[buf.capacity() + 1], 0, buf.capacity() + 1); + fail("Should throw BufferOverflowException"); //$NON-NLS-1$ + } catch (ReadOnlyBufferException expected) { + } catch (BufferOverflowException expected) { + } + try { + buf.put(array, -1, array.length); + fail("Should throw IndexOutOfBoundsException"); //$NON-NLS-1$ + } catch (ReadOnlyBufferException expected) { + } catch (IndexOutOfBoundsException expected) { + } + } + + public void testPutCharBuffer() { + CharBuffer other = CharBuffer.allocate(1); + try { + buf.put(other); + fail(); + } catch (ReadOnlyBufferException expected) { + } + try { + buf.put((CharBuffer) null); + fail(); + } catch (ReadOnlyBufferException expected) { + } catch (NullPointerException expected) { + } + try { + buf.put(buf); + fail(); + } catch (ReadOnlyBufferException expected) { + } catch (IllegalArgumentException expected) { + } + } +} 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/nio/tests/java/nio/WrappedDoubleBufferTest.java new file mode 100644 index 0000000..f970849 --- /dev/null +++ b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/WrappedDoubleBufferTest.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.nio.tests.java.nio; + +import java.nio.DoubleBuffer; + +public class WrappedDoubleBufferTest extends DoubleBufferTest { + protected void setUp() throws Exception { + super.setUp(); + buf = DoubleBuffer.wrap(new double[BUFFER_LENGTH]); + loadTestData1(buf); + baseBuf = buf; + } + + protected void tearDown() throws Exception { + super.tearDown(); + baseBuf = null; + buf = null; + } + + /** + * @tests java.nio.CharBuffer#allocate(char[],int,int) + * + */ + public void testWrappedDoubleuffer_IllegalArg() { + double array[] = new double[20]; + try { + DoubleBuffer.wrap(array, -1, 0); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (IndexOutOfBoundsException e) { + // expected + } + try { + DoubleBuffer.wrap(array, 21, 0); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (IndexOutOfBoundsException e) { + // expected + } + try { + DoubleBuffer.wrap(array, 0, -1); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (IndexOutOfBoundsException e) { + // expected + } + try { + DoubleBuffer.wrap(array, 0, 21); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (IndexOutOfBoundsException e) { + // expected + } + try { + DoubleBuffer.wrap(array, Integer.MAX_VALUE, 1); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (IndexOutOfBoundsException e) { + // expected + } + try { + DoubleBuffer.wrap(array, 1, Integer.MAX_VALUE); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (IndexOutOfBoundsException e) { + // expected + } + try { + DoubleBuffer.wrap((double[])null, -1, 0); + fail("Should throw NPE"); //$NON-NLS-1$ + } catch (NullPointerException e) { + } + + DoubleBuffer buf = DoubleBuffer.wrap(array, 2, 16); + assertEquals(buf.position(), 2); + assertEquals(buf.limit(), 18); + assertEquals(buf.capacity(), 20); + } +} diff --git a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/WrappedFloatBufferTest.java b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/WrappedFloatBufferTest.java new file mode 100644 index 0000000..43b13c3 --- /dev/null +++ b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/WrappedFloatBufferTest.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.nio.tests.java.nio; + +import java.nio.FloatBuffer; + +public class WrappedFloatBufferTest extends FloatBufferTest { + protected void setUp() throws Exception { + super.setUp(); + buf = FloatBuffer.wrap(new float[BUFFER_LENGTH]); + loadTestData1(buf); + baseBuf = buf; + } + + protected void tearDown() throws Exception { + super.tearDown(); + baseBuf = null; + buf = null; + } + + /** + * @tests java.nio.CharBuffer#allocate(char[],int,int) + * + */ + public void testWrappedFloatBuffer_IllegalArg() { + float array[] = new float[20]; + try { + FloatBuffer.wrap(array, -1, 0); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (IndexOutOfBoundsException e) { + // expected + } + try { + FloatBuffer.wrap(array, 21, 0); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (IndexOutOfBoundsException e) { + // expected + } + try { + FloatBuffer.wrap(array, 0, -1); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (IndexOutOfBoundsException e) { + // expected + } + try { + FloatBuffer.wrap(array, 0, 21); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (IndexOutOfBoundsException e) { + // expected + } + try { + FloatBuffer.wrap(array, Integer.MAX_VALUE, 1); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (IndexOutOfBoundsException e) { + // expected + } + try { + FloatBuffer.wrap(array, 1, Integer.MAX_VALUE); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (IndexOutOfBoundsException e) { + // expected + } + try { + FloatBuffer.wrap((float[])null, -1, 0); + fail("Should throw NPE"); //$NON-NLS-1$ + } catch (NullPointerException e) { + } + + FloatBuffer buf = FloatBuffer.wrap(array, 2, 16); + assertEquals(buf.position(), 2); + assertEquals(buf.limit(), 18); + assertEquals(buf.capacity(), 20); + } +} diff --git a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/WrappedIntBufferTest.java b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/WrappedIntBufferTest.java new file mode 100644 index 0000000..383e964 --- /dev/null +++ b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/WrappedIntBufferTest.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.nio.tests.java.nio; + +import java.nio.IntBuffer; + +public class WrappedIntBufferTest extends IntBufferTest { + protected void setUp() throws Exception { + super.setUp(); + buf = IntBuffer.wrap(new int[BUFFER_LENGTH]); + loadTestData1(buf); + baseBuf = buf; + } + + protected void tearDown() throws Exception { + super.tearDown(); + baseBuf = null; + buf = null; + } + + /** + * @tests java.nio.CharBuffer#allocate(char[],int,int) + * + */ + public void testWrappedIntBuffer_IllegalArg() { + int array[] = new int[20]; + try { + IntBuffer.wrap(array, -1, 0); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (IndexOutOfBoundsException e) { + // expected + } + try { + IntBuffer.wrap(array, 21, 0); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (IndexOutOfBoundsException e) { + // expected + } + try { + IntBuffer.wrap(array, 0, -1); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (IndexOutOfBoundsException e) { + // expected + } + try { + IntBuffer.wrap(array, 0, 21); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (IndexOutOfBoundsException e) { + // expected + } + try { + IntBuffer.wrap(array, Integer.MAX_VALUE, 1); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (IndexOutOfBoundsException e) { + // expected + } + try { + IntBuffer.wrap(array, 1, Integer.MAX_VALUE); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (IndexOutOfBoundsException e) { + // expected + } + try { + IntBuffer.wrap((int[])null, -1, 0); + fail("Should throw NPE"); //$NON-NLS-1$ + } catch (NullPointerException e) { + } + + IntBuffer buf = IntBuffer.wrap(array, 2, 16); + assertEquals(buf.position(), 2); + assertEquals(buf.limit(), 18); + assertEquals(buf.capacity(), 20); + } +} diff --git a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/WrappedLongBufferTest.java b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/WrappedLongBufferTest.java new file mode 100644 index 0000000..581c912 --- /dev/null +++ b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/WrappedLongBufferTest.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.nio.tests.java.nio; + +import java.nio.LongBuffer; + +public class WrappedLongBufferTest extends LongBufferTest { + protected void setUp() throws Exception { + super.setUp(); + buf = LongBuffer.wrap(new long[BUFFER_LENGTH]); + loadTestData1(buf); + baseBuf = buf; + } + + protected void tearDown() throws Exception { + super.tearDown(); + baseBuf = null; + buf = null; + } + + /** + * @tests java.nio.CharBuffer#allocate(char[],int,int) + * + */ + public void testWrappedLongBuffer_IllegalArg() { + long array[] = new long[20]; + try { + LongBuffer.wrap(array, -1, 0); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (IndexOutOfBoundsException e) { + // expected + } + try { + LongBuffer.wrap(array, 21, 0); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (IndexOutOfBoundsException e) { + // expected + } + try { + LongBuffer.wrap(array, 0, -1); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (IndexOutOfBoundsException e) { + // expected + } + try { + LongBuffer.wrap(array, 0, 21); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (IndexOutOfBoundsException e) { + // expected + } + try { + LongBuffer.wrap(array, Integer.MAX_VALUE, 1); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (IndexOutOfBoundsException e) { + // expected + } + try { + LongBuffer.wrap(array, 1, Integer.MAX_VALUE); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (IndexOutOfBoundsException e) { + // expected + } + try { + LongBuffer.wrap((long[])null, -1, 0); + fail("Should throw NPE"); //$NON-NLS-1$ + } catch (NullPointerException e) { + } + + LongBuffer buf = LongBuffer.wrap(array, 2, 16); + assertEquals(buf.position(), 2); + assertEquals(buf.limit(), 18); + assertEquals(buf.capacity(), 20); + } +} diff --git a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/WrappedShortBufferTest.java b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/WrappedShortBufferTest.java new file mode 100644 index 0000000..9c6f781 --- /dev/null +++ b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/WrappedShortBufferTest.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.nio.tests.java.nio; + +import java.nio.ShortBuffer; + +public class WrappedShortBufferTest extends ShortBufferTest { + protected void setUp() throws Exception { + super.setUp(); + buf = ShortBuffer.wrap(new short[BUFFER_LENGTH]); + loadTestData1(buf); + baseBuf = buf; + } + + protected void tearDown() throws Exception { + super.tearDown(); + baseBuf = null; + buf = null; + } + + /** + * @tests java.nio.CharBuffer#allocate(char[],int,int) + * + */ + public void testWrappedShortBuffer_IllegalArg() { + short array[] = new short[20]; + try { + ShortBuffer.wrap(array, -1, 0); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (IndexOutOfBoundsException e) { + // expected + } + try { + ShortBuffer.wrap(array, 21, 0); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (IndexOutOfBoundsException e) { + // expected + } + try { + ShortBuffer.wrap(array, 0, -1); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (IndexOutOfBoundsException e) { + // expected + } + try { + ShortBuffer.wrap(array, 0, 21); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (IndexOutOfBoundsException e) { + // expected + } + try { + ShortBuffer.wrap(array, Integer.MAX_VALUE, 1); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (IndexOutOfBoundsException e) { + // expected + } + try { + ShortBuffer.wrap(array, 1, Integer.MAX_VALUE); + fail("Should throw Exception"); //$NON-NLS-1$ + } catch (IndexOutOfBoundsException e) { + // expected + } + try { + ShortBuffer.wrap((short[])null, -1, 0); + fail("Should throw NPE"); //$NON-NLS-1$ + } catch (NullPointerException e) { + } + + ShortBuffer buf = ShortBuffer.wrap(array, 2, 16); + assertEquals(buf.position(), 2); + assertEquals(buf.limit(), 18); + assertEquals(buf.capacity(), 20); + } +} diff --git a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/AlreadyConnectedExceptionTest.java b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/AlreadyConnectedExceptionTest.java new file mode 100644 index 0000000..ac820a4 --- /dev/null +++ b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/AlreadyConnectedExceptionTest.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.nio.tests.java.nio.channels; + +import java.nio.channels.AlreadyConnectedException; + +import junit.framework.TestCase; + +import org.apache.harmony.testframework.serialization.SerializationTest; + +/** + * Tests for AlreadyConnectedException + */ +public class AlreadyConnectedExceptionTest extends TestCase { + + /** + * @tests {@link java.nio.channels.AlreadyConnectedException#AlreadyConnectedException()} + */ + public void test_Constructor() { + AlreadyConnectedException e = new AlreadyConnectedException(); + assertNull(e.getMessage()); + assertNull(e.getLocalizedMessage()); + assertNull(e.getCause()); + } + + /** + * @tests serialization/deserialization compatibility. + */ + public void testSerializationSelf() throws Exception { + + SerializationTest.verifySelf(new AlreadyConnectedException()); + } + + /** + * @tests serialization/deserialization compatibility with RI. + */ + public void testSerializationCompatibility() throws Exception { + + SerializationTest.verifyGolden(this, new 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/nio/tests/java/nio/channels/AsynchronousCloseExceptionTest.java new file mode 100644 index 0000000..123eb1f --- /dev/null +++ b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/AsynchronousCloseExceptionTest.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.nio.tests.java.nio.channels; + +import java.nio.channels.AsynchronousCloseException; + +import junit.framework.TestCase; + +import org.apache.harmony.testframework.serialization.SerializationTest; + +/** + * Tests for AsynchronousCloseException + */ +public class AsynchronousCloseExceptionTest extends TestCase { + + /** + * @tests {@link java.nio.channels.AsynchronousCloseException#AsynchronousCloseException()} + */ + public void test_Constructor() { + AsynchronousCloseException e = new AsynchronousCloseException(); + assertNull(e.getMessage()); + assertNull(e.getLocalizedMessage()); + assertNull(e.getCause()); + } + + /** + * @tests serialization/deserialization compatibility. + */ + public void testSerializationSelf() throws Exception { + + SerializationTest.verifySelf(new AsynchronousCloseException()); + } + + /** + * @tests serialization/deserialization compatibility with RI. + */ + public void testSerializationCompatibility() throws Exception { + + SerializationTest.verifyGolden(this, new 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/nio/tests/java/nio/channels/CancelledKeyExceptionTest.java new file mode 100644 index 0000000..7a73322 --- /dev/null +++ b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/CancelledKeyExceptionTest.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.nio.tests.java.nio.channels; + +import java.nio.channels.CancelledKeyException; + +import junit.framework.TestCase; + +import org.apache.harmony.testframework.serialization.SerializationTest; + +/** + * Tests for CancelledKeyException + */ +public class CancelledKeyExceptionTest extends TestCase { + + /** + * @tests {@link java.nio.channels.CancelledKeyException#CancelledKeyException()} + */ + public void test_Constructor() { + CancelledKeyException e = new CancelledKeyException(); + assertNull(e.getMessage()); + assertNull(e.getLocalizedMessage()); + assertNull(e.getCause()); + } + + /** + * @tests serialization/deserialization compatibility. + */ + public void testSerializationSelf() throws Exception { + + SerializationTest.verifySelf(new CancelledKeyException()); + } + + /** + * @tests serialization/deserialization compatibility with RI. + */ + public void testSerializationCompatibility() throws Exception { + + SerializationTest.verifyGolden(this, new 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/nio/tests/java/nio/channels/ChannelsTest.java new file mode 100644 index 0000000..4223fb8 --- /dev/null +++ b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/ChannelsTest.java @@ -0,0 +1,622 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.harmony.nio.tests.java.nio.channels; + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.io.Reader; +import java.io.Writer; +import java.net.InetSocketAddress; +import java.nio.ByteBuffer; +import java.nio.CharBuffer; +import java.nio.channels.Channels; +import java.nio.channels.ClosedChannelException; +import java.nio.channels.IllegalBlockingModeException; +import java.nio.channels.ReadableByteChannel; +import java.nio.channels.ServerSocketChannel; +import java.nio.channels.SocketChannel; +import java.nio.channels.WritableByteChannel; +import java.nio.charset.Charset; +import java.nio.charset.UnsupportedCharsetException; + +import tests.support.Support_PortManager; + +import junit.framework.TestCase; + +/** + * Note: the test case uses a temp text file named "test" which contains 31 + * characters : "P@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]" + * + */ + +public class ChannelsTest extends TestCase { + private static final String CODE_SET = "GB2312"; //$NON-NLS-1$ + + private static final String BAD_CODE_SET = "GB2313"; //$NON-NLS-1$ + + private FileInputStream fins; + + private FileOutputStream fouts; + + private final int writebufSize = 60; + + private final int testNum = 10; + + private final int fileSize = 31;// the file size + + private File tmpFile; + + protected void setUp() throws Exception { + super.setUp(); + // Make the test file same in every test + tmpFile = File.createTempFile("test","tmp"); + tmpFile.deleteOnExit(); + this.writeFileSame(); + } + + protected void tearDown() throws Exception { + if (null != this.fins) { + this.fins.close(); + this.fins = null; + } + if (null != this.fouts) { + this.fouts.close(); + this.fouts = null; + } + + tmpFile.delete(); + super.tearDown(); + + } + + private void writeFileSame() throws IOException { + this.fouts = new FileOutputStream(tmpFile); + byte[] bit = new byte[1]; + bit[0] = 80; + this.fouts.write(bit); + this.fouts.flush(); + String writebuf = ""; //$NON-NLS-1$ + for (int val = 0; val < this.writebufSize / 2; val++) { + writebuf = writebuf + ((char) (val + 64)); + } + this.fouts.write(writebuf.getBytes()); + } + + /* + * This private method is to assert if the file size is the same as the + * compare Number in the test + */ + private void assertFileSizeSame(File fileToTest, int compareNumber) + throws IOException { + FileInputStream file = new FileInputStream(fileToTest); + assertEquals(file.available(), compareNumber); + file.close(); + } + + // test if new Channel to input is null + public void testNewChannelInputStream_InputNull() throws IOException { + ByteBuffer byteBuf = ByteBuffer.allocate(this.testNum); + this.fins = null; + int readres = this.testNum; + try { + ReadableByteChannel rbChannel = Channels.newChannel(this.fins); + assertNotNull(rbChannel); + readres = rbChannel.read(byteBuf); + fail(); + } catch (NullPointerException expected) { + } + assertEquals(this.testNum, readres); + } + + // test if buffer to read is null + public void testNewChannelInputStream_BufferNull() throws IOException { + ByteBuffer byteBuf = ByteBuffer.allocate(this.testNum); + int readres = this.testNum; + this.fins = new FileInputStream(tmpFile); + ReadableByteChannel rbChannel = Channels.newChannel(this.fins); + assertNotNull(rbChannel); + try { + readres = rbChannel.read(null); + fail(); + } catch (NullPointerException e) { + // correct + } + assertEquals(this.testNum, readres); + readres = 0; + try { + readres = rbChannel.read(byteBuf); + } catch (NullPointerException e) { + fail(); + } + assertEquals(this.testNum, readres); + } + + /* + * Test method for 'java.nio.channels.Channels.NewChannel' + */ + public void testNewChannelInputStream() throws IOException { + int bufSize = 10; + int readres = 0; + byte[] byteArray = new byte[bufSize]; + ByteBuffer byteBuf = ByteBuffer.allocate(bufSize); + this.fins = new FileInputStream(tmpFile); + readres = this.fins.read(byteArray); + + assertEquals(bufSize, readres); + assertFalse(0 == this.fins.available()); + + ReadableByteChannel rbChannel = Channels.newChannel(this.fins); + // fins still reads. + assertFalse(0 == this.fins.available()); + readres = this.fins.read(byteArray); + assertEquals(bufSize, readres); + + // rbChannel also reads. + assertNotNull(rbChannel); + readres = rbChannel.read(byteBuf); + + assertEquals(bufSize, readres); + InputStream ins = Channels.newInputStream(rbChannel); + assertNotNull(ins); + assertEquals(0, ins.available()); + } + + // test if fout to change is null + public void testNewChannelOutputStream_inputNull() throws IOException { + int writeres = this.testNum; + ByteBuffer writebuf = ByteBuffer.allocate(this.writebufSize); + for (int val = 0; val < this.writebufSize / 2; val++) { + writebuf.putChar((char) (val + 64)); + } + this.fouts = null; + try { + WritableByteChannel rbChannel = Channels.newChannel(this.fouts); + writeres = rbChannel.write(writebuf); + assertEquals(0, writeres); + + writebuf.flip(); + writeres = rbChannel.write(writebuf); + fail("Should throw NPE."); + } catch (NullPointerException expected) { + } + } + + // test if write buf is null + public void testNewChannelOutputStream_BufNull() throws IOException { + int writeres = this.testNum; + ByteBuffer writebuf = null; + try { + this.fouts = new FileOutputStream(tmpFile); + } catch (FileNotFoundException e) { + fail(); + } + + WritableByteChannel rbChannel = Channels.newChannel(this.fouts); + try { + writeres = rbChannel.write(writebuf); + fail(); + } catch (NullPointerException e) { + // correct + } + assertEquals(this.testNum, writeres); + } + + /* + * Test method for 'java.nio.channels.Channels.NewChannel(OutputStream)' + */ + public void testNewChannelOutputStream() throws IOException { + int writeNum = 0; + ByteBuffer writebuf = ByteBuffer.allocateDirect(this.writebufSize); + for (int val = 0; val < this.writebufSize / 2; val++) { + writebuf.putChar((char) (val + 64)); + } + this.fouts = new FileOutputStream(tmpFile); + WritableByteChannel testChannel = this.fouts.getChannel(); + WritableByteChannel rbChannel = Channels.newChannel(this.fouts); + + assertTrue(testChannel.isOpen()); + assertTrue(rbChannel.isOpen()); + + byte[] bit = new byte[1]; + bit[0] = 80; + this.fouts.write(bit); + this.fouts.flush(); + this.fins = new FileInputStream(tmpFile); + assertEquals(this.fins.available(), 1); + this.fins.close(); + + writeNum = rbChannel.write(writebuf); + // write success ,but output null + assertEquals(0, writeNum); + // close of fouts does not affect on channel + this.fouts.close(); + writeNum = rbChannel.write(writebuf); + assertEquals(0, writeNum); + try { + writeNum = testChannel.write(writebuf); + fail(); + } catch (ClosedChannelException e) { + // correct + } + assertEquals(0, writeNum); + // close of rbchannel does affect on testchannel(same channel) + rbChannel.close(); + try { + writeNum = testChannel.write(writebuf); + fail(); + } catch (ClosedChannelException e) { + // correct + } + } + + public void testNewInputStreamReadableByteChannel_InputNull() + throws Exception { + byte[] readbuf = new byte[this.testNum]; + this.fins = new FileInputStream(tmpFile); + ReadableByteChannel readbc = this.fins.getChannel(); + assertEquals(this.fileSize, this.fins.available()); + assertTrue(readbc.isOpen()); + + try { + InputStream testins = Channels.newInputStream(null); + assertNotNull(testins); + testins.read(readbuf); + fail(); + } catch (NullPointerException expected) { + } + } + + public void testNewInputStreamReadableByteChannel() throws Exception { + ByteBuffer readbcbuf = ByteBuffer.allocateDirect(this.testNum); + byte[] readbuf = new byte[this.testNum]; + this.fins = new FileInputStream(tmpFile); + ReadableByteChannel readbc = this.fins.getChannel(); + assertEquals(this.fileSize, this.fins.available()); + assertTrue(readbc.isOpen()); + InputStream testins = Channels.newInputStream(readbc); + // read in testins and fins use the same pointer + testins.read(readbuf); + assertEquals(this.fins.available(), this.fileSize - this.testNum); + int readNum = readbc.read(readbcbuf); + assertEquals(readNum, this.testNum); + assertEquals(this.fins.available(), this.fileSize - this.testNum * 2); + testins.read(readbuf); + assertEquals(this.fins.available(), this.fileSize - this.testNum * 3); + // readbc.close() affect testins + readbc.close(); + assertFalse(readbc.isOpen()); + try { + testins.read(readbuf); + fail(); + } catch (ClosedChannelException e) { + // correct + } + } + + public void testNewOutputStreamWritableByteChannel_InputNull() + throws Exception { + byte[] writebuf = new byte[this.testNum]; + try { + OutputStream testouts = Channels.newOutputStream(null); + assertNotNull(testouts); + testouts.write(writebuf); + fail(); + } catch (NullPointerException expected) { + } + try { + WritableByteChannel writebc = Channels.newChannel((OutputStream) null); + assertTrue(writebc.isOpen()); + OutputStream testoutputS = Channels.newOutputStream(writebc); + testoutputS.write(writebuf); + fail(); + } catch (NullPointerException expected) { + } + } + + public void testNewOutputStreamWritableByteChannel() throws Exception { + byte[] writebuf = new byte[this.testNum]; + ByteBuffer writebcbuf = ByteBuffer.allocateDirect(this.testNum); + this.fouts = new FileOutputStream(tmpFile); + WritableByteChannel writebc = this.fouts.getChannel(); + + assertTrue(writebc.isOpen()); + OutputStream testouts = Channels.newOutputStream(writebc); + + // read in testins and fins use the same pointer + testouts.write(writebuf); + this.assertFileSizeSame(tmpFile, this.testNum); + writebc.write(writebcbuf); + this.assertFileSizeSame(tmpFile, this.testNum * 2); + testouts.write(writebuf); + this.assertFileSizeSame(tmpFile, this.testNum * 3); + // readbc.close() affect testins + writebc.close(); + assertFalse(writebc.isOpen()); + try { + testouts.write(writebuf); + fail(); + } catch (ClosedChannelException e) { + // correct + } + } + + public void testnewReaderCharsetError() throws Exception { + this.fins = new FileInputStream(tmpFile); + + ReadableByteChannel rbChannel = Channels.newChannel(this.fins); + try { + Channels.newReader(rbChannel, Charset.forName(BAD_CODE_SET) + .newDecoder(), //$NON-NLS-1$ + -1); + fail(); + } catch (UnsupportedCharsetException e) { + // correct + } + } + + public void testnewWriterCharsetError() throws Exception { + this.fouts = new FileOutputStream(tmpFile); + WritableByteChannel wbChannel = Channels.newChannel(this.fouts); + try { + Channels.newWriter(wbChannel, Charset.forName(BAD_CODE_SET) + .newEncoder(), -1); + fail(); + } catch (UnsupportedCharsetException e) { + // correct + } + } + + /* + * Test method for + * 'java.nio.channels.Channels.newReader(ReadableByteChannel, String)' + */ + public void testNewReaderReadableByteChannelString_InputNull() + throws IOException { + int bufSize = this.testNum; + int readres = 0; + CharBuffer charBuf = CharBuffer.allocate(bufSize); + this.fins = new FileInputStream(tmpFile); + // channel null + Reader testReader; + try { + testReader = Channels.newReader(null, Charset.forName(CODE_SET).newDecoder(), -1); + assertNotNull(testReader); + assertFalse(testReader.ready()); + readres = testReader.read((CharBuffer) null); + fail(); + } catch (NullPointerException e) { + // correct + } + assertEquals(0, readres); + + this.fins = null; + // channel with null inputs + try { + ReadableByteChannel rbChannel = Channels.newChannel(this.fins); + testReader = Channels.newReader(rbChannel, Charset.forName(CODE_SET).newDecoder(), -1); + assertNotNull(testReader); + assertFalse(testReader.ready()); + readres = testReader.read(charBuf); + fail(); + } catch (NullPointerException e) { + // correct + } + } + + /* + * Test method for + * 'java.nio.channels.Channels.newReader(ReadableByteChannel, String)' + */ + public void testNewReaderReadableByteChannelString_internalBufferZero() + throws IOException { + int bufSize = this.testNum; + int readres = 0; + CharBuffer charBuf = CharBuffer.allocate(bufSize); + this.fins = new FileInputStream(tmpFile); + // channel null + Reader testReader; + try { + testReader = Channels.newReader(null, Charset.forName(CODE_SET).newDecoder(), 0); + assertNotNull(testReader); + assertFalse(testReader.ready()); + readres = testReader.read((CharBuffer) null); + fail(); + } catch (NullPointerException expected) { + } + assertEquals(0, readres); + + this.fins = null; + // channel with null inputs + try { + ReadableByteChannel rbChannel = Channels.newChannel(this.fins); + testReader = Channels.newReader(rbChannel, Charset.forName(CODE_SET).newDecoder(), -1); + assertNotNull(testReader); + assertFalse(testReader.ready()); + readres = testReader.read(charBuf); + fail(); + } catch (NullPointerException e) { + // correct + } + } + + /* + * Test method for + * 'java.nio.channels.Channels.newReader(ReadableByteChannel, String)' + */ + public void testNewReaderReadableByteChannelString() throws IOException { + int bufSize = this.testNum; + int readres = 0; + CharBuffer charBuf = CharBuffer.allocate(bufSize); + this.fins = new FileInputStream(tmpFile); + ReadableByteChannel rbChannel = Channels.newChannel(this.fins); + Reader testReader = Channels.newReader(rbChannel, Charset.forName( + CODE_SET).newDecoder(), //$NON-NLS-1$ + -1); + Reader testReader_s = Channels.newReader(rbChannel, CODE_SET); //$NON-NLS-1$ + + assertEquals(this.fileSize, this.fins.available()); + // not ready... + assertFalse(testReader.ready()); + assertFalse(testReader_s.ready()); + // still reads + readres = testReader.read(charBuf); + assertEquals(bufSize, readres); + assertEquals(0, this.fins.available()); + + try { + readres = testReader.read((CharBuffer) null); + fail(); + } catch (NullPointerException e) { + // correct + } + + readres = testReader_s.read(charBuf); + assertEquals(0, readres); + assertTrue(testReader.ready()); + assertFalse(testReader_s.ready()); + } + + /* + * Zero-Buffer + */ + public void testNewWriterWritableByteChannelString_internalBufZero() + throws IOException { + + String writebuf = ""; //$NON-NLS-1$ + for (int val = 0; val < this.writebufSize / 2; val++) { + writebuf = writebuf + ((char) (val + 64)); + } + // null channel + try { + Writer testWriter = Channels.newWriter(null, Charset.forName(CODE_SET).newEncoder(), -1); + } catch (NullPointerException expected) { + } + + // channel with null input + this.fouts = null; + try { + WritableByteChannel wbChannel = Channels.newChannel(this.fouts); + } catch (NullPointerException expected) { + } + } + + /* + * this test cannot be passed when buffer set to 0! + */ + public void testNewWriterWritableByteChannelString_InputNull() + throws IOException { + this.fouts = new FileOutputStream(tmpFile); + WritableByteChannel wbChannel = Channels.newChannel(this.fouts); + Writer testWriter = Channels.newWriter(wbChannel, Charset.forName( + CODE_SET).newEncoder(), //$NON-NLS-1$ + 1); + + String writebuf = ""; //$NON-NLS-1$ + for (int val = 0; val < this.writebufSize / 2; val++) { + writebuf = writebuf + ((char) (val + 64)); + } + // can write to buffer + testWriter.write(writebuf); + testWriter.flush(); + testWriter.close(); + + } + + /* + * Test method for + * 'java.nio.channels.Channels.newWriter(WritableByteChannel, String)' + */ + public void testNewWriterWritableByteChannelString() throws IOException { + this.fouts = new FileOutputStream(tmpFile); + WritableByteChannel wbChannel = Channels.newChannel(this.fouts); + Writer testWriter = Channels.newWriter(wbChannel, CODE_SET); //$NON-NLS-1$ + Writer testWriter_s = Channels.newWriter(wbChannel, Charset.forName( + CODE_SET).newEncoder(), //$NON-NLS-1$ + -1); + + String writebuf = ""; //$NON-NLS-1$ + for (int val = 0; val < this.writebufSize / 2; val++) { + writebuf = writebuf + ((char) (val + 64)); + } + byte[] bit = new byte[1]; + bit[0] = 80; + this.fouts.write(bit); + this.assertFileSizeSame(tmpFile, 1); + + // writer continues to write after '1',what the fouts write + testWriter.write(writebuf); + testWriter.flush(); + this.assertFileSizeSame(tmpFile, this.writebufSize / 2 + 1); + // testwriter_s does not know if testwrite writes + testWriter_s.write(writebuf); + testWriter.flush(); + this.assertFileSizeSame(tmpFile, this.writebufSize / 2 + 1); + // testwriter_s even does not know if himself writes? + testWriter_s.write(writebuf); + testWriter.flush(); + this.assertFileSizeSame(tmpFile, this.writebufSize / 2 + 1); + + // close the fouts, no longer writable for testWriter + for (int val = 0; val < this.writebufSize; val++) { + writebuf = writebuf + ((char) (val + 64)); + } + this.fouts.close(); + testWriter_s.write(writebuf); + testWriter.flush(); + this.assertFileSizeSame(tmpFile, this.writebufSize / 2 + 1); + } + + /** + * @tests java.nio.channels.Channels#newReader(ReadableByteChannel channel, + * String charsetName) + */ + 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); + + SocketChannel sc = SocketChannel.open(); + sc.connect(localAddr); + sc.configureBlocking(false); + assertFalse(sc.isBlocking()); + + ssc.accept().close(); + ssc.close(); + assertFalse(sc.isBlocking()); + + Reader reader = Channels.newReader(sc, "UTF16"); + try { + int i = reader.read(); + fail("should throw IllegalBlockingModeException"); + } catch (IllegalBlockingModeException expected) { + } + + try { + Channels.newInputStream(sc).read(); + fail("should throw IllegalBlockingModeException"); + } catch (IllegalBlockingModeException expected) { + } + + sc.close(); + } +} 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/nio/tests/java/nio/channels/ClosedByInterruptExceptionTest.java new file mode 100644 index 0000000..aba37ec --- /dev/null +++ b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/ClosedByInterruptExceptionTest.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.nio.tests.java.nio.channels; + +import java.nio.channels.ClosedByInterruptException; + +import junit.framework.TestCase; + +import org.apache.harmony.testframework.serialization.SerializationTest; + +/** + * Tests for ClosedByInterruptException + */ +public class ClosedByInterruptExceptionTest extends TestCase { + + /** + * @tests {@link java.nio.channels.ClosedByInterruptException#ClosedByInterruptException()} + */ + public void test_Constructor() { + ClosedByInterruptException e = new ClosedByInterruptException(); + assertNull(e.getMessage()); + assertNull(e.getLocalizedMessage()); + assertNull(e.getCause()); + } + /** + * @tests serialization/deserialization compatibility. + */ + public void testSerializationSelf() throws Exception { + + SerializationTest.verifySelf(new ClosedByInterruptException()); + } + + /** + * @tests serialization/deserialization compatibility with RI. + */ + public void testSerializationCompatibility() throws Exception { + + SerializationTest.verifyGolden(this, new 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/nio/tests/java/nio/channels/ClosedChannelExceptionTest.java new file mode 100644 index 0000000..3ba322f --- /dev/null +++ b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/ClosedChannelExceptionTest.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.nio.tests.java.nio.channels; + +import java.nio.channels.ClosedChannelException; + +import junit.framework.TestCase; + +import org.apache.harmony.testframework.serialization.SerializationTest; + +/** + * Tests for ClosedChannelException + */ +public class ClosedChannelExceptionTest extends TestCase { + + /** + * @tests {@link java.nio.channels.ClosedChannelException#ClosedChannelException()} + */ + public void test_Constructor() { + ClosedChannelException e = new ClosedChannelException(); + assertNull(e.getMessage()); + assertNull(e.getLocalizedMessage()); + assertNull(e.getCause()); + } + + /** + * @tests serialization/deserialization compatibility. + */ + public void testSerializationSelf() throws Exception { + + SerializationTest.verifySelf(new ClosedChannelException()); + } + + /** + * @tests serialization/deserialization compatibility with RI. + */ + public void testSerializationCompatibility() throws Exception { + + SerializationTest.verifyGolden(this, new 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/nio/tests/java/nio/channels/ClosedSelectorExceptionTest.java new file mode 100644 index 0000000..745d697 --- /dev/null +++ b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/ClosedSelectorExceptionTest.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.nio.tests.java.nio.channels; + +import java.nio.channels.ClosedSelectorException; + +import junit.framework.TestCase; + +import org.apache.harmony.testframework.serialization.SerializationTest; + +/** + * Tests for ClosedSelectorException + */ +public class ClosedSelectorExceptionTest extends TestCase { + + /** + * @tests {@link java.nio.channels.ClosedSelectorException#ClosedSelectorException()} + */ + public void test_Constructor() { + ClosedSelectorException e = new ClosedSelectorException(); + assertNull(e.getMessage()); + assertNull(e.getLocalizedMessage()); + assertNull(e.getCause()); + } + + /** + * @tests serialization/deserialization compatibility. + */ + public void testSerializationSelf() throws Exception { + + SerializationTest.verifySelf(new ClosedSelectorException()); + } + + /** + * @tests serialization/deserialization compatibility with RI. + */ + public void testSerializationCompatibility() throws Exception { + + SerializationTest.verifyGolden(this, new 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/nio/tests/java/nio/channels/ConnectionPendingExceptionTest.java new file mode 100644 index 0000000..0e909ba --- /dev/null +++ b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/ConnectionPendingExceptionTest.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.nio.tests.java.nio.channels; + +import java.nio.channels.ConnectionPendingException; + +import junit.framework.TestCase; + +import org.apache.harmony.testframework.serialization.SerializationTest; + +/** + * Tests for ConnectionPendingException + */ +public class ConnectionPendingExceptionTest extends TestCase { + + /** + * @tests {@link java.nio.channels.ConnectionPendingException#ConnectionPendingException()} + */ + public void test_Constructor() { + ConnectionPendingException e = new ConnectionPendingException(); + assertNull(e.getMessage()); + assertNull(e.getLocalizedMessage()); + assertNull(e.getCause()); + } + + /** + * @tests serialization/deserialization compatibility. + */ + public void testSerializationSelf() throws Exception { + + SerializationTest.verifySelf(new ConnectionPendingException()); + } + + /** + * @tests serialization/deserialization compatibility with RI. + */ + public void testSerializationCompatibility() throws Exception { + + SerializationTest.verifyGolden(this, new 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/nio/tests/java/nio/channels/DatagramChannelTest.java new file mode 100644 index 0000000..cff718e --- /dev/null +++ b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/DatagramChannelTest.java @@ -0,0 +1,2557 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.harmony.nio.tests.java.nio.channels; + +import java.io.IOException; +import java.net.DatagramPacket; +import java.net.DatagramSocket; +import java.net.InetAddress; +import java.net.InetSocketAddress; +import java.net.SocketAddress; +import java.net.SocketException; +import java.nio.ByteBuffer; +import java.nio.channels.AsynchronousCloseException; +import java.nio.channels.ClosedChannelException; +import java.nio.channels.DatagramChannel; +import java.nio.channels.IllegalBlockingModeException; +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; + +/** + * Test for DatagramChannel + * + */ +public class DatagramChannelTest extends TestCase { + + private static final int CAPACITY_NORMAL = 200; + + private static final int CAPACITY_1KB = 1024; + + private static final int CAPACITY_64KB = 65536; + + private static final int CAPACITY_ZERO = 0; + + private static final int CAPACITY_ONE = 1; + + private static final int TIME_UNIT = 500; + + private InetSocketAddress localAddr1; + + private InetSocketAddress localAddr2; + + private DatagramChannel channel1; + + private DatagramChannel channel2; + + private DatagramSocket datagramSocket1; + + private DatagramSocket datagramSocket2; + + // The port to be used in test cases. + private int testPort; + + protected void setUp() throws Exception { + super.setUp(); + this.channel1 = DatagramChannel.open(); + this.channel2 = DatagramChannel.open(); + int[] ports = Support_PortManager.getNextPortsForUDP(5); + this.localAddr1 = new InetSocketAddress("127.0.0.1", ports[0]); + this.localAddr2 = new InetSocketAddress("127.0.0.1", ports[1]); + this.datagramSocket1 = new DatagramSocket(ports[2]); + this.datagramSocket2 = new DatagramSocket(ports[3]); + testPort = ports[4]; + } + + protected void tearDown() throws Exception { + if (null != this.channel1) { + try { + this.channel1.close(); + } catch (Exception e) { + //ignore + } + } + if (null != this.channel2) { + try { + this.channel2.close(); + } catch (Exception e) { + //ignore + } + } + if (null != this.datagramSocket1) { + try { + this.datagramSocket1.close(); + } catch (Exception e) { + //ignore + } + } + if (null != this.datagramSocket2) { + try { + this.datagramSocket2.close(); + } catch (Exception e) { + //ignore + } + } + localAddr1 = null; + localAddr2 = null; + super.tearDown(); + } + + // ------------------------------------------------------------------- + // Test for methods in abstract class. + // ------------------------------------------------------------------- + /* + * Test method for 'java.nio.channels.DatagramChannel.validOps()' + */ + public void testValidOps() { + MockDatagramChannel testMock = new MockDatagramChannel(SelectorProvider + .provider()); + MockDatagramChannel testMocknull = new MockDatagramChannel(null); + int val = this.channel1.validOps(); + assertEquals(5, val); + assertEquals(val, testMock.validOps()); + assertEquals(val, testMocknull.validOps()); + } + + /* + * Test method for 'java.nio.channels.DatagramChannel.open()' + */ + public void testOpen() { + MockDatagramChannel testMock = new MockDatagramChannel(SelectorProvider + .provider()); + MockDatagramChannel testMocknull = new MockDatagramChannel(null); + assertNull(testMocknull.provider()); + assertNotNull(testMock.provider()); + assertEquals(this.channel1.provider(), testMock.provider()); + assertEquals(5, testMock.validOps()); + } + + /* + * Test method for 'java.nio.channels.DatagramChannel.read(ByteBuffer)' + */ + public void testReadByteBufferArray() throws IOException { + final int testNum = 0; + long readres = testNum; + MockDatagramChannel testMock = new MockDatagramChannel(SelectorProvider + .provider()); + MockDatagramChannel testMocknull = new MockDatagramChannel(null); + int bufSize = 10; + ByteBuffer[] readBuf = null; + try { + this.channel1.read(readBuf); + fail("Should throw NPE"); + } catch (NullPointerException e) { + // correct + } + try { + readres = testMock.read(readBuf); + fail("Should throw NPE"); + } catch (NullPointerException e) { + // correct + } + readBuf = new ByteBuffer[bufSize]; + try { + readres = this.channel1.read(readBuf); + fail("Should throw NotYetConnectedException"); + } catch (NotYetConnectedException e) { + // correct + } + readres = testMock.read(readBuf); + assertEquals(testNum, readres); + readres = testMocknull.read(readBuf); + assertEquals(testNum, readres); + } + + /* + * Test method for 'java.nio.channels.DatagramChannel.read(ByteBuffer)' + */ + public void testReadByteBufferArray_BufNull() throws IOException { + MockDatagramChannel testMock = new MockDatagramChannel(SelectorProvider + .provider()); + MockDatagramChannel testMocknull = new MockDatagramChannel(null); + + ByteBuffer[] readBuf = null; + try { + this.channel1.read(readBuf); + fail("Should throw NPE"); + } catch (NullPointerException e) { + // correct + } + try { + testMock.read(readBuf); + fail("Should throw NPE"); + } catch (NullPointerException e) { + // correct + } + try { + testMocknull.read(readBuf); + fail("Should throw NPE"); + } catch (NullPointerException e) { + // correct + } + } + + /* + * Test method for 'java.nio.channels.DatagramChannel.write(ByteBuffer)' + */ + public void testWriteByteBuffer() throws IOException { + MockDatagramChannel testMock = new MockDatagramChannel(SelectorProvider + .provider()); + MockDatagramChannel testMocknull = new MockDatagramChannel(null); + int bufSize = 10; + ByteBuffer[] readBuf = null; + try { + this.channel1.write(readBuf); + fail("Should throw NPE"); + } catch (NullPointerException e) { + // correct + } + try { + testMock.write(readBuf); + fail("Should throw NPE"); + } catch (NullPointerException e) { + // correct + } + readBuf = new ByteBuffer[bufSize]; + try { + this.channel1.write(readBuf); + fail("Should throw NotYetConnectedException"); + } catch (NotYetConnectedException e) { + // correct + } + long writeres = 0; + writeres = testMock.write(readBuf); + + assertEquals(0, writeres); + writeres = testMocknull.write(readBuf); + assertEquals(0, writeres); + } + + /* + * Test method for 'java.nio.channels.DatagramChannel.write(ByteBuffer)' + */ + public void testWriteByteBuffer_Bufnull() throws IOException { + MockDatagramChannel testMock = new MockDatagramChannel(SelectorProvider + .provider()); + MockDatagramChannel testMocknull = new MockDatagramChannel(null); + ByteBuffer[] readBuf = null; + try { + this.channel1.write(readBuf); + fail("Should throw NPE"); + } catch (NullPointerException e) { + // correct + } + try { + testMock.write(readBuf); + fail("Should throw NPE"); + } catch (NullPointerException e) { + // correct + } + try { + testMocknull.write(readBuf); + fail("Should throw NPE"); + } catch (NullPointerException e) { + // correct + } + } + + // ------------------------------------------------------------------- + // Test for socket() + // ------------------------------------------------------------------- + + /** + * 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(); + // same + assertSame(s1, s2); + } + + /** + * 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); + } + + public void testSocket_NonBlock_BasicStatusAfterConnect() + throws IOException { + this.channel1.connect(localAddr1); + this.channel1.configureBlocking(false); + DatagramSocket s1 = this.channel1.socket(); + assertSocketAfterConnect(s1); + DatagramSocket s2 = this.channel1.socket(); + // same + assertSame(s1, s2); + } + + /** + * Test method for 'DatagramChannelImpl.socket()' + * + * @throws IOException + */ + public void testSocket_ActionsBeforeConnect() throws IOException { + assertFalse(this.channel1.isConnected());// not connected + DatagramSocket s = this.channel1.socket(); + assertSocketActionBeforeConnect(s); + } + + /** + * Test method for 'DatagramChannelImpl.socket()' + * + * @throws IOException + */ + 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_ActionsAfterConnect() throws IOException { + this.channel1.connect(localAddr1); + this.channel1.configureBlocking(false); + DatagramSocket s = this.channel1.socket(); + assertSocketActionAfterConnect(s); + } + + private void assertSocketBeforeConnect(DatagramSocket s) + throws SocketException { + assertFalse(s.isBound()); + assertFalse(s.isClosed()); + assertFalse(s.isConnected()); + assertFalse(s.getBroadcast()); + assertFalse(s.getReuseAddress()); + assertNull(s.getInetAddress()); + assertTrue(s.getLocalAddress().isAnyLocalAddress()); + assertEquals(s.getLocalPort(), 0); + assertNull(s.getLocalSocketAddress()); + assertEquals(s.getPort(), -1); + assertTrue(s.getReceiveBufferSize() >= 8192); + assertNull(s.getRemoteSocketAddress()); + assertFalse(s.getReuseAddress()); + assertTrue(s.getSendBufferSize() >= 8192); + assertEquals(s.getSoTimeout(), 0); + assertEquals(s.getTrafficClass(), 0); + } + + private void assertSocketAfterConnect(DatagramSocket s) + throws SocketException { + assertTrue(s.isBound()); + assertFalse(s.isClosed()); + assertTrue(s.isConnected()); + assertFalse(s.getBroadcast()); + assertFalse(s.getReuseAddress()); + assertSame(s.getInetAddress(), localAddr1.getAddress()); + assertEquals(s.getLocalAddress(), localAddr1.getAddress()); + assertNotNull(s.getLocalSocketAddress()); + assertEquals(s.getPort(), localAddr1.getPort()); + assertTrue(s.getReceiveBufferSize() >= 8192); + // not same , but equals + assertNotSame(s.getRemoteSocketAddress(), (SocketAddress) localAddr1); + assertEquals(s.getRemoteSocketAddress(), (SocketAddress) localAddr1); + assertFalse(s.getReuseAddress()); + assertTrue(s.getSendBufferSize() >= 8192); + assertEquals(s.getSoTimeout(), 0); + assertEquals(s.getTrafficClass(), 0); + } + + private void assertSocketActionBeforeConnect(DatagramSocket s) + throws IOException { + s.connect(localAddr2); + assertFalse(this.channel1.isConnected()); + assertFalse(s.isConnected()); + + s.disconnect(); + assertFalse(this.channel1.isConnected()); + assertFalse(s.isConnected()); + + s.close(); + assertTrue(s.isClosed()); + assertFalse(this.channel1.isOpen()); + } + + private void assertSocketActionAfterConnect(DatagramSocket s) + throws IOException { + assertEquals(s.getPort(), localAddr1.getPort()); + s.connect(localAddr2); + assertTrue(this.channel1.isConnected()); + assertTrue(s.isConnected()); + // not changed + assertEquals(s.getPort(), localAddr1.getPort()); + + s.disconnect(); + assertFalse(this.channel1.isConnected()); + assertFalse(s.isConnected()); + + s.close(); + assertTrue(s.isClosed()); + assertFalse(this.channel1.isOpen()); + } + + // ------------------------------------------------------------------- + // Test for configureBlocking() + // ------------------------------------------------------------------- + + 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(); + disconnectAfterConnected(); + this.datagramSocket1.close(); + this.channel1.close(); + assertFalse(this.channel1.isConnected()); + } + + // ------------------------------------------------------------------- + // Test for connect() + // ------------------------------------------------------------------- + + /** + * Test method for 'DatagramChannelImpl.connect(SocketAddress)' + */ + public void testConnect_BlockWithServer() throws IOException { + // blocking mode + assertTrue(this.channel1.isBlocking()); + connectLocalServer(); + datagramSocket1.close(); + disconnectAfterConnected(); + } + + /** + * Test method for 'DatagramChannelImpl.connect(SocketAddress)' + */ + public void testConnect_BlockNoServer() throws IOException { + connectWithoutServer(); + disconnectAfterConnected(); + } + + /** + * Test method for 'DatagramChannelImpl.connect(SocketAddress)' + * + * @throws IOException + */ + public void testConnect_NonBlockWithServer() throws IOException { + // Non blocking mode + this.channel1.configureBlocking(false); + connectLocalServer(); + datagramSocket1.close(); + disconnectAfterConnected(); + } + + /** + * Test method for 'DatagramChannelImpl.connect(SocketAddress)' + * + * @throws IOException + */ + public void testConnect_Null() throws IOException { + assertFalse(this.channel1.isConnected()); + try { + this.channel1.connect(null); + fail("Should throw an IllegalArgumentException here."); //$NON-NLS-1$ + } catch (IllegalArgumentException e) { + // OK. + } + } + + /** + * Test method for 'DatagramChannelImpl.connect(SocketAddress)' + * + * @throws IOException + */ + public void testConnect_UnsupportedType() throws IOException { + assertFalse(this.channel1.isConnected()); + class SubSocketAddress extends SocketAddress { + private static final long serialVersionUID = 1L; + + public SubSocketAddress() { + super(); + } + } + SocketAddress newTypeAddress = new SubSocketAddress(); + try { + this.channel1.connect(newTypeAddress); + fail("Should throw an UnsupportedAddressTypeException here."); + } catch (UnsupportedAddressTypeException e) { + // OK. + } + } + + /** + * Test method for 'DatagramChannelImpl.connect(SocketAddress)' + * + * @throws IOException + */ + public void testConnect_Unresolved() throws IOException { + assertFalse(this.channel1.isConnected()); + InetSocketAddress unresolved = new InetSocketAddress( + "unresolved address", 1080); + try { + this.channel1.connect(unresolved); + fail("Should throw an UnresolvedAddressException here."); //$NON-NLS-1$ + } catch (UnresolvedAddressException e) { + // OK. + } + } + + public void testConnect_EmptyHost() throws Exception { + assertFalse(this.channel1.isConnected()); + + assertEquals(this.channel1, this.channel1 + .connect(new InetSocketAddress("", 1081))); //$NON-NLS-1$ + + } + + /** + * 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); + fail("Should throw ClosedChannelException."); //$NON-NLS-1$ + } catch (ClosedChannelException e) { + // OK. + } + } + + /** + * Test method for 'DatagramChannelImpl.connect(SocketAddress)' + * + * @throws IOException + * + */ + public void testConnect_IllegalStateException() throws IOException { + assertFalse(this.channel1.isConnected()); + this.channel1.connect(localAddr1); + assertTrue(this.channel1.isConnected()); + // connect after connected. + try { + this.channel1.connect(localAddr1); + fail("Should throw IllegalStateException."); //$NON-NLS-1$ + } catch (IllegalStateException e) { + // OK. + } + } + + /** + * Test method for 'DatagramChannelImpl.connect(SocketAddress)' + * + * @throws IOException + * + */ + public void testConnect_CheckOpenBeforeStatus() throws IOException { + assertFalse(this.channel1.isConnected()); + this.channel1.connect(localAddr1); + assertTrue(this.channel1.isConnected()); + // connect after connected. + this.channel1.close(); + assertFalse(this.channel1.isOpen()); + // checking open is before checking status. + try { + this.channel1.connect(localAddr1); + fail("Should throw ClosedChannelException."); //$NON-NLS-1$ + } catch (ClosedChannelException e) { + // OK. + } + } + + private void disconnectAfterConnected() throws IOException { + assertTrue(this.channel1.isConnected()); + this.channel1.disconnect(); + assertFalse(this.channel1.isConnected()); + } + + private void disconnectAfterClosed() throws IOException { + assertFalse(this.channel1.isOpen()); + assertFalse(this.channel1.isConnected()); + this.channel1.disconnect(); + assertFalse(this.channel1.isConnected()); + } + + private void connectLocalServer() throws IOException { + assertFalse(this.channel1.isConnected()); + assertTrue(this.datagramSocket1.isBound()); + assertSame(this.channel1, this.channel1.connect(localAddr1)); + assertTrue(this.channel1.isConnected()); + } + + private void connectWithoutServer() throws IOException { + assertFalse(this.channel1.isConnected()); + this.datagramSocket1.close(); + assertTrue(this.datagramSocket1.isClosed()); + assertSame(this.channel1, this.channel1.connect(localAddr1)); + assertTrue(this.channel1.isConnected()); + } + + // ------------------------------------------------------------------- + // Test for disconnect() + // ------------------------------------------------------------------- + + /** + * Test method for 'DatagramChannelImpl.disconnect()' + * + * @throws IOException + */ + public void testDisconnect_BeforeConnect() throws IOException { + assertFalse(this.channel1.isConnected()); + assertEquals(this.channel1, this.channel1.disconnect()); + assertFalse(this.channel1.isConnected()); + } + + /** + * Test method for 'DatagramChannelImpl.disconnect()' + * + * @throws IOException + */ + public void testDisconnect_UnconnectedClosed() throws IOException { + assertFalse(this.channel1.isConnected()); + this.channel1.close(); + assertFalse(this.channel1.isOpen()); + assertEquals(this.channel1, this.channel1.disconnect()); + assertFalse(this.channel1.isConnected()); + } + + /** + * Test method for 'DatagramChannelImpl.disconnect()' + * + * @throws IOException + */ + public void testDisconnect_BlockWithServerChannelClosed() + throws IOException { + assertTrue(this.channel1.isBlocking()); + connectLocalServer(); + // disconnect after channel close + this.channel1.close(); + disconnectAfterClosed(); + } + + /** + * Test method for 'DatagramChannelImpl.disconnect()' + * + * @throws IOException + */ + public void testDisconnect_NonBlockWithServerChannelClosed() + throws IOException { + this.channel1.configureBlocking(false); + connectLocalServer(); + // disconnect after channel close + this.channel1.close(); + disconnectAfterClosed(); + } + + /** + * Test method for 'DatagramChannelImpl.disconnect()' + * + * @throws IOException + */ + public void testDisconnect_BlockWithServerServerClosed() throws IOException { + assertTrue(this.channel1.isBlocking()); + connectLocalServer(); + // disconnect after server close + this.datagramSocket1.close(); + assertTrue(this.channel1.isOpen()); + assertTrue(this.channel1.isConnected()); + disconnectAfterConnected(); + } + + /** + * Test method for 'DatagramChannelImpl.disconnect()' + * + * @throws IOException + */ + public void testDisconnect_NonBlockWithServerServerClosed() + throws IOException { + this.channel1.configureBlocking(false); + assertFalse(this.channel1.isBlocking()); + connectLocalServer(); + // disconnect after server close + this.datagramSocket1.close(); + assertTrue(this.channel1.isOpen()); + assertTrue(this.channel1.isConnected()); + disconnectAfterConnected(); + } + + // ------------------------------------------------------------------- + // Test for receive(): Behavior Without Server. + // ------------------------------------------------------------------- + + /** + * Test method for 'DatagramChannelImpl.receive(ByteBuffer)' + * + * @throws Exception + */ + public void testReceive_UnconnectedNull() throws Exception { + assertFalse(this.channel1.isConnected()); + try { + this.channel1.receive(null); + fail("Should throw a NPE here."); //$NON-NLS-1$ + } catch (NullPointerException e) { + // OK. + } + } + + /** + * Test method for 'DatagramChannelImpl.receive(ByteBuffer)' + * + * @throws Exception + */ + public void testReceive_UnconnectedReadonly() throws Exception { + assertFalse(this.channel1.isConnected()); + ByteBuffer dst = ByteBuffer.allocateDirect(CAPACITY_NORMAL) + .asReadOnlyBuffer(); + assertTrue(dst.isReadOnly()); + try { + this.channel1.receive(dst); + fail("Should throw an IllegalArgumentException here."); //$NON-NLS-1$ + } catch (IllegalArgumentException e) { + // OK. + } + } + + /** + * Test method for 'DatagramChannelImpl.receive(ByteBuffer)' + * + * @throws Exception + */ + public void testReceive_UnconnectedBufEmpty() throws Exception { + this.channel1.configureBlocking(false); + assertFalse(this.channel1.isConnected()); + ByteBuffer dst = ByteBuffer.allocateDirect(CAPACITY_NORMAL); + assertNull(this.channel1.receive(dst)); + } + + /** + * Test method for 'DatagramChannelImpl.receive(ByteBuffer)' + * + * @throws Exception + */ + public void testReceive_UnconnectedBufZero() throws Exception { + assertFalse(this.channel1.isConnected()); + ByteBuffer dst = ByteBuffer.allocateDirect(CAPACITY_ZERO); + assertNull(this.channel1.receive(dst)); + } + + /** + * Test method for 'DatagramChannelImpl.receive(ByteBuffer)' + * + * @throws Exception + */ + public void testReceive_UnconnectedBufNotEmpty() throws Exception { + assertFalse(this.channel1.isConnected()); + ByteBuffer dst = ByteBuffer.allocateDirect(CAPACITY_NORMAL); + // buf is not empty + dst.put((byte) 88); + assertEquals(dst.position() + CAPACITY_NORMAL - 1, dst.limit()); + assertNull(this.channel1.receive(dst)); + } + + /** + * Test method for 'DatagramChannelImpl.receive(ByteBuffer)' + * + * @throws Exception + */ + public void testReceive_UnconnectedBufFull() throws Exception { + assertFalse(this.channel1.isConnected()); + ByteBuffer dst = ByteBuffer.allocateDirect(CAPACITY_ONE); + // buf is full + dst.put((byte) 88); + assertEquals(dst.position(), dst.limit()); + assertNull(this.channel1.receive(dst)); + } + + /** + * Test method for 'DatagramChannelImpl.receive(ByteBuffer)' + * + * @throws Exception + */ + public void testReceive_UnconnectedClose() throws Exception { + assertFalse(this.channel1.isConnected()); + ByteBuffer dst = ByteBuffer.allocateDirect(CAPACITY_NORMAL); + this.channel1.close(); + assertFalse(this.channel1.isOpen()); + try { + assertNull(this.channel1.receive(dst)); + fail("Should throw a ClosedChannelException here."); //$NON-NLS-1$ + } catch (ClosedChannelException e) { + // OK. + } + } + + /** + * Test method for 'DatagramChannelImpl.receive(ByteBuffer)' + * + * @throws Exception + */ + public void testReceive_UnconnectedCloseNull() throws Exception { + assertFalse(this.channel1.isConnected()); + this.channel1.close(); + assertFalse(this.channel1.isOpen()); + // checking buffer before checking open + try { + this.channel1.receive(null); + fail("Should throw a NPE here."); //$NON-NLS-1$ + } catch (NullPointerException e) { + // OK. + } + } + + /** + * Test method for 'DatagramChannelImpl.receive(ByteBuffer)' + * + * @throws Exception + */ + public void testReceive_UnconnectedCloseReadonly() throws Exception { + assertFalse(this.channel1.isConnected()); + ByteBuffer dst = ByteBuffer.allocateDirect(CAPACITY_NORMAL) + .asReadOnlyBuffer(); + assertTrue(dst.isReadOnly()); + this.channel1.close(); + assertFalse(this.channel1.isOpen()); + try { + this.channel1.receive(dst); + fail("Should throw an IllegalArgumentException here."); //$NON-NLS-1$ + } catch (IllegalArgumentException e) { + // OK. + } + } + + /** + * Test method for 'DatagramChannelImpl.receive(ByteBuffer)' + * + * @throws Exception + */ + public void testReceive_NonBlockNoServerBufEmpty() throws Exception { + this.channel1.configureBlocking(false); + receiveNonBlockNoServer(CAPACITY_NORMAL); + } + + /** + * Test method for 'DatagramChannelImpl.receive(ByteBuffer)' + * + * @throws Exception + */ + public void testReceive_BlockNoServerNull() throws Exception { + assertTrue(this.channel1.isBlocking()); + receiveNoServerNull(); + } + + /** + * Test method for 'DatagramChannelImpl.receive(ByteBuffer)' + * + * @throws Exception + */ + public void testReceive_NonBlockNoServerNull() throws Exception { + this.channel1.configureBlocking(false); + receiveNoServerNull(); + } + + /** + * Test method for 'DatagramChannelImpl.receive(ByteBuffer)' + * + * @throws Exception + */ + public void testReceive_BlockNoServerReadonly() throws Exception { + assertTrue(this.channel1.isBlocking()); + receiveNoServerReadonly(); + } + + /** + * Test method for 'DatagramChannelImpl.receive(ByteBuffer)' + * + * @throws Exception + */ + public void testReceive_NonBlockNoServerReadonly() throws Exception { + this.channel1.configureBlocking(false); + receiveNoServerReadonly(); + } + + /** + * Test method for 'DatagramChannelImpl.receive(ByteBuffer)' + * + * @throws Exception + */ + public void testReceive_NonBlockNoServerBufZero() throws Exception { + this.channel1.configureBlocking(false); + receiveNonBlockNoServer(CAPACITY_ZERO); + } + + /** + * Test method for 'DatagramChannelImpl.receive(ByteBuffer)' + * + * @throws Exception + */ + public void testReceive_NonBlockNoServerBufNotEmpty() throws Exception { + this.channel1.configureBlocking(false); + connectWithoutServer(); + ByteBuffer dst = allocateNonEmptyBuf(); + assertNull(this.channel1.receive(dst)); + } + + + /** + * Test method for 'DatagramChannelImpl.receive(ByteBuffer)' + * + * @throws Exception + */ + public void testReceive_NonBlockNoServerBufFull() throws Exception { + this.channel1.configureBlocking(false); + connectWithoutServer(); + ByteBuffer dst = allocateFullBuf(); + assertNull(this.channel1.receive(dst)); + } + + /** + * Test method for 'DatagramChannelImpl.receive(ByteBuffer)' + * + * @throws Exception + */ + public void testReceive_BlockNoServerChannelClose() throws Exception { + assertTrue(this.channel1.isBlocking()); + receiveNoServerChannelClose(); + } + + /** + * Test method for 'DatagramChannelImpl.receive(ByteBuffer)' + * + * @throws Exception + */ + public void testReceive_NonBlockNoServerChannelClose() throws Exception { + this.channel1.configureBlocking(false); + receiveNoServerChannelClose(); + } + + /** + * Test method for 'DatagramChannelImpl.receive(ByteBuffer)' + * + * @throws Exception + */ + public void testReceive_BlockNoServerCloseNull() throws Exception { + assertTrue(this.channel1.isBlocking()); + receiveNoServerChannelCloseNull(); + } + + /** + * Test method for 'DatagramChannelImpl.receive(ByteBuffer)' + * + * @throws Exception + */ + public void testReceive_NonBlockNoServerCloseNull() throws Exception { + this.channel1.configureBlocking(false); + receiveNoServerChannelCloseNull(); + } + + /** + * Test method for 'DatagramChannelImpl.receive(ByteBuffer)' + * + * @throws Exception + */ + public void testReceive_NonBlockNoServerCloseReadonly() throws Exception { + this.channel1.configureBlocking(false); + receiveNoServerChannelCloseReadonly(); + } + + /** + * Test method for 'DatagramChannelImpl.receive(ByteBuffer)' + * + * @throws Exception + */ + public void testReceive_BlockNoServerCloseReadonly() throws Exception { + assertTrue(this.channel1.isBlocking()); + receiveNoServerChannelCloseReadonly(); + } + + private void receiveNoServerNull() throws IOException { + connectWithoutServer(); + try { + this.channel1.receive(null); + fail("Should throw a NPE here."); //$NON-NLS-1$ + } catch (NullPointerException e) { + // OK. + } + } + + private void receiveNoServerReadonly() throws IOException { + connectWithoutServer(); + ByteBuffer dst = ByteBuffer.allocateDirect(CAPACITY_NORMAL) + .asReadOnlyBuffer(); + assertTrue(dst.isReadOnly()); + try { + this.channel1.receive(dst); + fail("Should throw an IllegalArgumentException here."); //$NON-NLS-1$ + } catch (IllegalArgumentException e) { + // OK. + } + } + + private void receiveNonBlockNoServer(int size) throws IOException { + connectWithoutServer(); + ByteBuffer dst = ByteBuffer.allocateDirect(size); + assertNull(this.channel1.receive(dst)); + } + + private void receiveNoServerChannelClose() throws IOException { + connectWithoutServer(); + ByteBuffer dst = ByteBuffer.allocateDirect(CAPACITY_NORMAL); + this.channel1.close(); + assertFalse(this.channel1.isOpen()); + try { + assertNull(this.channel1.receive(dst)); + fail("Should throw a ClosedChannelException here."); //$NON-NLS-1$ + } catch (ClosedChannelException e) { + // OK. + } + } + + private void receiveNoServerChannelCloseNull() throws IOException { + connectWithoutServer(); + this.channel1.close(); + assertFalse(this.channel1.isOpen()); + try { + this.channel1.receive(null); + fail("Should throw a NPE here."); //$NON-NLS-1$ + } catch (NullPointerException e) { + // OK. + } + } + + private void receiveNoServerChannelCloseReadonly() throws IOException { + connectWithoutServer(); + this.channel1.close(); + assertFalse(this.channel1.isOpen()); + ByteBuffer dst = ByteBuffer.allocateDirect(CAPACITY_NORMAL) + .asReadOnlyBuffer(); + assertTrue(dst.isReadOnly()); + try { + this.channel1.receive(dst); + fail("Should throw an IllegalArgumentException here."); //$NON-NLS-1$ + } catch (IllegalArgumentException e) { + // OK. + } + } + + private ByteBuffer allocateFullBuf() { + ByteBuffer dst = ByteBuffer.allocateDirect(CAPACITY_ONE); + // buf is full + dst.put((byte) 88); + assertEquals(dst.position(), dst.limit()); + return dst; + } + + private ByteBuffer allocateNonEmptyBuf() { + ByteBuffer dst = ByteBuffer.allocateDirect(CAPACITY_NORMAL); + // buf is not empty + dst.put((byte) 88); + dst.put((byte) 99); + assertEquals(dst.position() + CAPACITY_NORMAL - 2, dst.limit()); + return dst; + } + + // ------------------------------------------------------------------- + // Test for send(): Behavior without server. + // ------------------------------------------------------------------- + + private void sendDataBlocking(InetSocketAddress addr, ByteBuffer writeBuf) + throws IOException { + InetSocketAddress ipAddr = addr; + assertEquals(CAPACITY_NORMAL, this.channel1.send(writeBuf, ipAddr)); + assertTrue(this.channel1.isOpen()); + assertTrue(this.channel1.isBlocking()); + this.channel1.connect(ipAddr); + assertTrue(this.channel1.isConnected()); + } + + private void sendDataNonBlocking(InetSocketAddress addr, ByteBuffer writeBuf) + throws IOException { + InetSocketAddress ipAddr = addr; + this.channel1.configureBlocking(false); + assertEquals(CAPACITY_NORMAL, this.channel1.send(writeBuf, ipAddr)); + assertTrue(this.channel1.isOpen()); + assertFalse(this.channel1.isBlocking()); + this.channel1.connect(ipAddr); + assertTrue(this.channel1.isConnected()); + } + + /* + * Test method for 'DatagramChannelImpl.send(ByteBuffer, SocketAddress)' + */ + public void testSend_NoServerBlockingCommon() throws IOException { + ByteBuffer writeBuf = ByteBuffer.allocateDirect(CAPACITY_NORMAL); + sendDataBlocking(localAddr1, writeBuf); + } + + public void testSend_NoServerNonblockingCommon() throws IOException { + ByteBuffer writeBuf = ByteBuffer.allocateDirect(CAPACITY_NORMAL); + sendDataNonBlocking(localAddr1, writeBuf); + } + + public void testSend_NoServerTwice() throws IOException { + ByteBuffer writeBuf = ByteBuffer.allocateDirect(CAPACITY_NORMAL); + sendDataBlocking(localAddr1, writeBuf); + // can not buffer twice! + assertEquals(0, this.channel1.send(writeBuf, localAddr1)); + try { + channel1.send(writeBuf, localAddr2); + fail("Should throw IllegalArgumentException"); + } catch (IllegalArgumentException e) { + // correct + } + } + + public void testSend_NoServerNonBlockingTwice() throws IOException { + ByteBuffer writeBuf = ByteBuffer.allocateDirect(CAPACITY_NORMAL); + sendDataNonBlocking(localAddr1, writeBuf); + // can not buffer twice! + assertEquals(0, this.channel1.send(writeBuf, localAddr1)); + try { + channel1.send(writeBuf, localAddr2); + fail("Should throw IllegalArgumentException"); + } catch (IllegalArgumentException e) { + // correct + } + } + + public void testSend_NoServerBufNull() throws IOException { + try { + sendDataBlocking(localAddr1, null); + fail("Should throw a NPE here."); + } catch (NullPointerException e) { + // correct + } + } + + public void testSend_NoServerBufNullTwice() throws IOException { + ByteBuffer writeBuf = ByteBuffer.allocateDirect(CAPACITY_NORMAL); + try { + sendDataBlocking(localAddr1, null); + fail("Should throw a NPE here."); + } catch (NullPointerException e) { + // correct + } + sendDataBlocking(localAddr1, writeBuf); + try { + channel1.send(null, localAddr2); + fail("Should throw NPE"); + } catch (NullPointerException e) { + // correct + } + } + + public void testSend_NoServerAddrNull() throws IOException { + ByteBuffer writeBuf = ByteBuffer.allocateDirect(CAPACITY_NORMAL); + try { + sendDataBlocking(null, writeBuf); + fail("Should throw a NPE here."); + } catch (NullPointerException e) { + // correct + } + } + + public void testSend_NoServerAddrNullTwice() throws IOException { + ByteBuffer writeBuf = ByteBuffer.allocateDirect(CAPACITY_NORMAL); + try { + sendDataBlocking(null, writeBuf); + fail("Should throw a NPE here."); + } catch (NullPointerException e) { + // correct + } + sendDataBlocking(localAddr1, writeBuf); + try { + channel1.send(writeBuf, null); + fail("Should throw NPE"); + } catch (NullPointerException e) { + // correct + } + } + + // ------------------------------------------------------------------- + // Test for receive()and send(): Send and Receive with Real Data + // ------------------------------------------------------------------- + + public void testReceiveSend_Block_Normal() throws Exception { + this.channel1.socket().bind(localAddr2); + sendByChannel("some normal string in testReceiveSend_Normal", + localAddr2); + receiveByChannel(CAPACITY_NORMAL, localAddr2, + "some normal string in testReceiveSend_Normal"); + } + + 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); + ByteBuffer buf = ByteBuffer.wrap(new byte[CAPACITY_NORMAL]); + assertNull((InetSocketAddress) 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, + "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); + } + + 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); + } + + public void testReceiveSend_Normal_S2S() throws Exception { + String msg = "normal string in testReceiveSend_Normal_S2S"; + this.datagramSocket1 = new DatagramSocket(testPort); + DatagramPacket rdp = new DatagramPacket(msg.getBytes(), msg.length(), + localAddr2); + datagramSocket2 = new DatagramSocket(localAddr2.getPort()); + this.datagramSocket1.send(rdp); + byte[] buf = new byte[CAPACITY_NORMAL]; + this.datagramSocket2.setSoTimeout(TIME_UNIT); + rdp = new DatagramPacket(buf, buf.length); + this.datagramSocket2.receive(rdp); + assertEquals(new String(buf, 0, CAPACITY_NORMAL).trim(), msg); + } + + public void testReceiveSend_Block_Empty() throws Exception { + this.channel1.socket().bind(localAddr2); + sendByChannel("", localAddr2); + receiveByChannel(CAPACITY_NORMAL, localAddr2, ""); + } + + 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, ""); + } + + public void testReceiveSend_Block_Empty_S2C() throws Exception { + this.channel1.socket().bind(localAddr2); + sendByDatagramSocket("", localAddr2); + receiveByChannel(CAPACITY_NORMAL, localAddr2, ""); + } + + 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, ""); + } + + public void testReceiveSend_Block_Empty_C2S() throws Exception { + this.datagramSocket1 = new DatagramSocket(localAddr2.getPort()); + sendByChannel("", localAddr2); + receiveByDatagramSocket(CAPACITY_NORMAL, localAddr2, ""); + } + + 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, ""); + } + + public void testReceiveSend_Empty_S2S() throws Exception { + String msg = ""; + this.datagramSocket1 = new DatagramSocket(testPort); + DatagramPacket rdp = new DatagramPacket(msg.getBytes(), msg.length(), + localAddr2); + datagramSocket2 = new DatagramSocket(localAddr2.getPort()); + this.datagramSocket1.send(rdp); + byte[] buf = new byte[CAPACITY_NORMAL]; + this.datagramSocket2.setSoTimeout(TIME_UNIT); + rdp = new DatagramPacket(buf, buf.length); + this.datagramSocket2.receive(rdp); + assertEquals(new String(buf, 0, CAPACITY_NORMAL).trim(), msg); + } + + public void testReceiveSend_Block_Oversize() throws Exception { + this.channel1.socket().bind(localAddr2); + sendByChannel("0123456789", localAddr2); + receiveByChannel(5, localAddr2, "01234"); + } + + public void testReceiveSend_Block_Oversize_C2S() throws Exception { + this.datagramSocket1 = new DatagramSocket(localAddr2.getPort()); + sendByChannel("0123456789", localAddr2); + receiveByDatagramSocket(5, localAddr2, "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"); + } + + public void testReceiveSend_Block_Oversize_S2C() throws Exception { + this.channel1.socket().bind(localAddr2); + sendByDatagramSocket("0123456789", localAddr2); + receiveByChannel(5, localAddr2, "01234"); + } + + public void testReceiveSend_8K() throws Exception { + StringBuffer str8k = new StringBuffer(); + for (int i = 0; i < 8 * CAPACITY_1KB; i++) { + str8k.append('a'); + } + String str = str8k.toString(); + this.channel1.socket().bind(localAddr2); + sendByChannel(str, localAddr2); + receiveByChannel(8 * CAPACITY_1KB, localAddr2, str); + } + + public void testReceiveSend_64K() throws Exception { + StringBuffer str64k = new StringBuffer(); + for (int i = 0; i < CAPACITY_64KB; i++) { + str64k.append('a'); + } + String str = str64k.toString(); + try { + Thread.sleep(TIME_UNIT); + channel2.send(ByteBuffer.wrap(str.getBytes()), localAddr1); + fail("Should throw SocketException!"); + } catch (SocketException e) { + //expected + } + } + + private void sendByChannel(String data, InetSocketAddress address) + throws Exception { + try { + assertEquals(data.length(), this.channel2.send(ByteBuffer.wrap(data + .getBytes()), address)); + } finally { + this.channel2.close(); + } + } + + private void sendByDatagramSocket(String data, InetSocketAddress address) + throws Exception { + this.datagramSocket1 = new DatagramSocket(testPort); + DatagramPacket rdp = new DatagramPacket(data.getBytes(), data.length(), + address); + this.datagramSocket1.send(rdp); + } + + private void receiveByChannel(int bufSize, InetSocketAddress address, + String expectedString) throws IOException { + try { + ByteBuffer buf = ByteBuffer.wrap(new byte[bufSize]); + InetSocketAddress returnAddr = null; + long startTime = System.currentTimeMillis(); + do { + returnAddr = (InetSocketAddress) this.channel1.receive(buf); + // continue loop when channel1 is non-blocking and no data was + // received. + if (channel1.isBlocking() || null != returnAddr) { + break; + } + // avoid dead loop + assertTimeout(startTime, 10000); + } while (true); + int length = returnAddr.getAddress().getAddress().length; + for (int i = 0; i < length; i++) { + assertEquals(returnAddr.getAddress().getAddress()[i], + InetAddress.getByName("127.0.0.1").getAddress()[i]); + } + // port is NOT equal + assertFalse(returnAddr.getPort() == address.getPort()); + assertEquals(new String(buf.array(), 0, bufSize).trim(), + expectedString); + } finally { + this.channel1.close(); + } + } + + /* + * Fails if the difference between current time and start time is greater + * than timeout. + */ + private void assertTimeout(long startTime, long timeout) { + long currentTime = System.currentTimeMillis(); + if ((currentTime - startTime) > timeout) { + fail("Timeout"); + } + } + + private void receiveByDatagramSocket(int bufSize, + InetSocketAddress address, String expectedString) + throws IOException { + byte[] buf = new byte[bufSize]; + this.datagramSocket1.setSoTimeout(6000); + DatagramPacket rdp = new DatagramPacket(buf, buf.length); + this.datagramSocket1.receive(rdp); + assertEquals(new String(buf, 0, bufSize).trim(), expectedString); + } + + public void testRead_NoSecurity() 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); + 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); + 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()); + assertAscii(buf, strHello); + } + + private static void assertAscii(ByteBuffer b, String s) { + assertEquals(s.length(), b.position()); + for (int i = 0; i < s.length(); ++i) { + assertEquals(s.charAt(i), b.get(i)); + } + } + + // ------------------------------------------------------------------- + // Test for write() + // ------------------------------------------------------------------- + + private void connectWriteBuf(InetSocketAddress ipAddr, ByteBuffer buf) + throws IOException { + this.channel1.connect(ipAddr); + assertTrue(this.channel1.isConnected()); + assertEquals(CAPACITY_NORMAL, this.channel1.write(buf)); + assertEquals(0, this.channel1.write(buf)); + } + + private void noconnectWrite(ByteBuffer buf) throws IOException { + try { + this.channel1.write(buf); + fail("should throw NotYetConnectedException"); + } catch (NotYetConnectedException e) { + // correct + } + } + + /* + * Test method for 'DatagramChannelImpl.write(ByteBuffer)' + */ + public void testWriteByteBuffer_Block() throws IOException { + ByteBuffer writeBuf = ByteBuffer.allocateDirect(CAPACITY_NORMAL); + connectWriteBuf(localAddr1, writeBuf); + } + + public void testWriteByteBuffer_NonBlock() throws IOException { + ByteBuffer writeBuf = ByteBuffer.allocateDirect(CAPACITY_NORMAL); + this.channel1.configureBlocking(false); + connectWriteBuf(localAddr1, writeBuf); + } + + public void testWriteByteBuffer_Block_closed() throws IOException { + ByteBuffer writeBuf = ByteBuffer.allocateDirect(CAPACITY_NORMAL); + InetSocketAddress ipAddr = localAddr1; + noconnectWrite(writeBuf); + this.channel1.connect(ipAddr); + assertTrue(this.channel1.isConnected()); + this.channel1.close(); + try { + channel1.write(writeBuf); + fail("should throw ClosedChannelException"); + } catch (ClosedChannelException e) { + // correct + } + } + + public void testWriteByteBuffer_NonBlock_closed() throws IOException { + ByteBuffer writeBuf = ByteBuffer.allocateDirect(CAPACITY_NORMAL); + InetSocketAddress ipAddr = localAddr1; + // non block mode + this.channel1.configureBlocking(false); + noconnectWrite(writeBuf); + this.channel1.connect(ipAddr); + assertTrue(this.channel1.isConnected()); + this.channel1.close(); + try { + channel1.write(writeBuf); + fail("should throw ClosedChannelException"); + } catch (ClosedChannelException e) { + // correct + } + } + + public void testWriteByteBuffer_Block_BufNull() throws IOException { + ByteBuffer writeBuf = ByteBuffer.allocateDirect(0); + InetSocketAddress ipAddr = localAddr1; + try { + this.channel1.write((ByteBuffer) null); + fail("Should throw NPE."); + } catch (NullPointerException e) { + // correct + } + this.channel1.connect(ipAddr); + assertTrue(this.channel1.isConnected()); + try { + this.channel1.write((ByteBuffer) null); + fail("Should throw NPE."); + } catch (NullPointerException e) { + // correct + } + assertEquals(0, this.channel1.write(writeBuf)); + datagramSocket1.close(); + try { + this.channel1.write((ByteBuffer) null); + fail("Should throw NPE."); + } catch (NullPointerException e) { + // correct + } + } + + public void testWriteByteBuffer_NonBlock_BufNull() throws IOException { + ByteBuffer writeBuf = ByteBuffer.allocateDirect(0); + InetSocketAddress ipAddr = localAddr1; + + // non block mode + this.channel1.configureBlocking(false); + + try { + this.channel1.write((ByteBuffer) null); + fail("Should throw NPE."); + } catch (NullPointerException e) { + // correct + } + this.channel1.connect(ipAddr); + assertTrue(this.channel1.isConnected()); + try { + this.channel1.write((ByteBuffer) null); + fail("Should throw NPE."); + } catch (NullPointerException e) { + // correct + } + assertEquals(0, this.channel1.write(writeBuf)); + datagramSocket1.close(); + try { + this.channel1.write((ByteBuffer) null); + fail("Should throw NPE."); + } catch (NullPointerException e) { + // correct + } + } + + /* + * Test method for 'DatagramChannelImpl.write(ByteBuffer[], int, int)' + */ + public void testWriteByteBufferArrayIntInt_Block() throws IOException { + ByteBuffer[] writeBuf = new ByteBuffer[2]; + writeBuf[0] = ByteBuffer.allocateDirect(CAPACITY_NORMAL); + writeBuf[1] = ByteBuffer.allocateDirect(CAPACITY_NORMAL); + InetSocketAddress ipAddr = localAddr1; + try { + this.channel1.write(writeBuf, 0, 2); + fail("Should throw NotYetConnectedException."); + } catch (NotYetConnectedException e) { + // correct + } + this.channel1.connect(ipAddr); + assertTrue(this.channel1.isConnected()); + assertEquals(CAPACITY_NORMAL * 2, this.channel1.write(writeBuf, 0, 2)); + // cannot be buffered again! + assertEquals(0, this.channel1.write(writeBuf, 0, 1)); + + } + + public void testWriteByteBufferArrayIntInt_NonBlock() throws IOException { + ByteBuffer[] writeBuf = new ByteBuffer[2]; + writeBuf[0] = ByteBuffer.allocateDirect(CAPACITY_NORMAL); + writeBuf[1] = ByteBuffer.allocateDirect(CAPACITY_NORMAL); + InetSocketAddress ipAddr = localAddr1; + // non-block mode + this.channel1.configureBlocking(false); + try { + this.channel1.write(writeBuf, 0, 2); + fail("Should throw NotYetConnectedException."); + } catch (NotYetConnectedException e) { + // correct + } + this.channel1.connect(ipAddr); + assertTrue(this.channel1.isConnected()); + assertEquals(CAPACITY_NORMAL * 2, this.channel1.write(writeBuf, 0, 2)); + // cannot be buffered again! + assertEquals(0, this.channel1.write(writeBuf, 0, 1)); + + } + + public void testWriteByteBufferArrayIntInt_NoConnectIndexBad() + throws IOException { + ByteBuffer[] writeBuf = new ByteBuffer[2]; + writeBuf[0] = ByteBuffer.allocateDirect(CAPACITY_NORMAL); + writeBuf[1] = ByteBuffer.allocateDirect(CAPACITY_NORMAL); + InetSocketAddress ipAddr = localAddr1; + try { + this.channel1.write(writeBuf, -1, 2); + fail("should throw IndexOutOfBoundsException"); + } catch (IndexOutOfBoundsException e) { + // correct + } + try { + this.channel1.write(writeBuf, 0, -1); + fail("should throw IndexOutOfBoundsException"); + } catch (IndexOutOfBoundsException e) { + // correct + } + this.channel1.connect(ipAddr); + assertTrue(this.channel1.isConnected()); + assertEquals(CAPACITY_NORMAL * 2, this.channel1.write(writeBuf, 0, 2)); + // cannot be buffered again! + assertEquals(0, this.channel1.write(writeBuf, 0, 1)); + } + + public void testWriteByteBufferArrayIntInt_ConnectedIndexBad() + throws IOException { + ByteBuffer[] writeBuf = new ByteBuffer[2]; + writeBuf[0] = ByteBuffer.allocateDirect(CAPACITY_NORMAL); + writeBuf[1] = ByteBuffer.allocateDirect(CAPACITY_NORMAL); + InetSocketAddress ipAddr = localAddr1; + this.channel1.connect(ipAddr); + assertTrue(this.channel1.isConnected()); + try { + this.channel1.write(writeBuf, -1, 2); + fail("should throw IndexOutOfBoundsException"); + } catch (IndexOutOfBoundsException e) { + // correct + } + try { + this.channel1.write(writeBuf, 0, -1); + fail("should throw IndexOutOfBoundsException"); + } catch (IndexOutOfBoundsException e) { + // correct + } + } + + public void testWriteByteBufferArrayIntInt_BufNullNoConnect() + throws IOException { + ByteBuffer[] writeBuf = new ByteBuffer[2]; + writeBuf[0] = ByteBuffer.allocateDirect(CAPACITY_NORMAL); + try { + this.channel1.write(null, 0, 2); + fail(); + } catch (NullPointerException expected) { + } + try { + this.channel1.write(writeBuf, -1, 2); + fail(); + } catch (IndexOutOfBoundsException expected) { + } + try { + this.channel1.write(writeBuf, 0, 3); + fail(); + } catch (IndexOutOfBoundsException expected) { + } + } + + public void testWriteByteBufferArrayIntInt_BufNullConnect() + throws IOException { + ByteBuffer[] writeBuf = new ByteBuffer[2]; + writeBuf[0] = ByteBuffer.allocateDirect(CAPACITY_NORMAL); + InetSocketAddress ipAddr = localAddr1; + this.channel1.connect(ipAddr); + assertTrue(this.channel1.isConnected()); + try { + this.channel1.write(null, 0, 2); + fail("should throw NPE"); + } catch (NullPointerException e) { + // correct + } + try { + this.channel1.write(writeBuf, 0, 3); + fail("should throw IndexOutOfBoundsException"); + } catch (IndexOutOfBoundsException e) { + // correct + } + datagramSocket1.close(); + try { + this.channel1.write(null, 0, 2); + fail("should throw NPE"); + } catch (NullPointerException e) { + // correct + } + } + + // ------------------------------------------------------------------- + // Test for read() + // ------------------------------------------------------------------- + + /* + * Test method for 'DatagramChannelImpl.read(ByteBuffer)' + */ + public void testReadByteBuffer() throws IOException { + ByteBuffer readBuf = ByteBuffer.allocateDirect(CAPACITY_NORMAL); + try { + this.channel1.read(readBuf); + fail("should throw NotYetConnectedException"); + } catch (NotYetConnectedException e) { + // correct + } + this.channel1.connect(localAddr1); + assertTrue(this.channel1.isConnected()); + this.channel1.configureBlocking(false); + // note : blocking-mode will make the read process endless! + assertEquals(0, this.channel1.read(readBuf)); + this.channel1.close(); + try { + this.channel1.read(readBuf); + fail("Should throw ClosedChannelException"); + } catch (ClosedChannelException e) { + // OK. + } + } + + public void testReadByteBuffer_bufNull() throws IOException { + ByteBuffer readBuf = ByteBuffer.allocateDirect(0); + InetSocketAddress ipAddr = localAddr1; + try { + this.channel1.read(readBuf); + fail("should throw NotYetConnectedException"); + } catch (NotYetConnectedException e) { + // correct + } + this.channel1.connect(ipAddr); + assertTrue(this.channel1.isConnected()); + try { + channel1.read((ByteBuffer) null); + fail("should throw NPE"); + } catch (NullPointerException e) { + // correct + } + this.channel1.configureBlocking(false); + // note : blocking-mode will make the read process endless! + assertEquals(0, this.channel1.read(readBuf)); + datagramSocket1.close(); + } + + /* + * Test method for 'DatagramChannelImpl.read(ByteBuffer[], int, int)' + */ + public void testReadByteBufferArrayIntInt() throws IOException { + ByteBuffer[] readBuf = new ByteBuffer[2]; + readBuf[0] = ByteBuffer.allocateDirect(CAPACITY_NORMAL); + readBuf[1] = ByteBuffer.allocateDirect(CAPACITY_NORMAL); + InetSocketAddress ipAddr = localAddr1; + try { + this.channel1.read(readBuf, 0, 2); + fail("should throw NotYetConnectedException"); + } catch (NotYetConnectedException e) { + // correct + } + this.channel1.connect(ipAddr); + assertTrue(this.channel1.isConnected()); + this.channel1.configureBlocking(false); + // note : blocking-mode will make the read process endless! + assertEquals(0, this.channel1.read(readBuf, 0, 1)); + assertEquals(0, this.channel1.read(readBuf, 0, 2)); + datagramSocket1.close(); + } + + public void testReadByteBufferArrayIntInt_exceptions() throws IOException { + //regression test for HARMONY-932 + try { + DatagramChannel.open().read(new ByteBuffer[] {}, 2, Integer.MAX_VALUE); + fail(); + } catch (IndexOutOfBoundsException expected) { + } + try { + DatagramChannel.open().read(new ByteBuffer[] {}, -1, 0); + fail(); + } catch (IndexOutOfBoundsException expected) { + } + try { + DatagramChannel.open().read((ByteBuffer[]) null, 0, 0); + fail(); + } catch (NullPointerException expected) { + } + } + + public void testReadByteBufferArrayIntInt_BufNull() throws IOException { + ByteBuffer[] readBuf = new ByteBuffer[2]; + readBuf[0] = ByteBuffer.allocateDirect(CAPACITY_NORMAL); + InetSocketAddress ipAddr = localAddr1; + try { + this.channel1.read(null, 0, 0); + fail("should throw NPE"); + } catch (NullPointerException e) { + // correct + } + this.channel1.connect(ipAddr); + assertTrue(this.channel1.isConnected()); + this.channel1.configureBlocking(false); + // note : blocking-mode will make the read process endless! + try { + this.channel1.read(null, 0, 0); + fail("should throw NPE"); + } catch (NullPointerException e) { + // correct + } + assertEquals(0, this.channel1.read(readBuf, 0, 1)); + try { + this.channel1.read(readBuf, 0, 2); + fail("should throw NPE"); + } catch (NullPointerException e) { + // correct + } + try { + this.channel1.read(readBuf, 0, 3); + fail("should throw IndexOutOfBoundsException"); + } catch (IndexOutOfBoundsException e) { + // correct + } + datagramSocket1.close(); + } + + // ------------------------------------------------------------------- + // test read and write + // ------------------------------------------------------------------- + + public void testReadWrite_configureBlock() throws Exception { + byte[] targetArray = new byte[2]; + // bind and connect + this.channel1.socket().bind(localAddr2); + this.channel1.connect(localAddr1); + this.channel2.socket().bind(localAddr1); + this.channel2.connect(localAddr2); + ByteBuffer targetBuf = ByteBuffer.wrap(targetArray); + + new Thread() { + public void run() { + try { + Thread.sleep(TIME_UNIT); + channel1.configureBlocking(false); + channel1.close(); + } catch (Exception e) { + //ignore + } + } + }.start(); + try { + this.channel1.read(targetBuf); + fail("should throw AsynchronousCloseException"); + } catch (AsynchronousCloseException e) { + // ok + } + } + + public void testReadWrite_Block_Zero() throws Exception { + byte[] sourceArray = new byte[0]; + byte[] targetArray = new byte[0]; + // bind and connect + this.channel1.socket().bind(localAddr2); + this.channel1.connect(localAddr1); + this.channel2.socket().bind(localAddr1); + this.channel2.connect(localAddr2); + + // write + ByteBuffer sourceBuf = ByteBuffer.wrap(sourceArray); + assertEquals(0, this.channel1.write(sourceBuf)); + + // read + ByteBuffer targetBuf = ByteBuffer.wrap(targetArray); + int readCount = this.channel2.read(targetBuf); + + assertEquals(0, readCount); + } + + public void testReadWrite_Block_Normal() throws Exception { + byte[] sourceArray = new byte[CAPACITY_NORMAL]; + byte[] targetArray = new byte[CAPACITY_NORMAL]; + for (int i = 0; i < sourceArray.length; i++) { + sourceArray[i] = (byte) i; + } + + // bind and connect + this.channel1.socket().bind(localAddr2); + this.channel1.connect(localAddr1); + this.channel2.socket().bind(localAddr1); + this.channel2.connect(localAddr2); + + readWriteReadData(this.channel1, sourceArray, this.channel2, + targetArray, CAPACITY_NORMAL, "testReadWrite_Block_Normal"); + } + + public void testReadWrite_Block_Empty() throws Exception { + // empty buf + byte[] sourceArray = "".getBytes(); + byte[] targetArray = new byte[CAPACITY_NORMAL]; + + // bind and connect + + this.channel1.socket().bind(localAddr2); + this.channel1.connect(localAddr1); + this.channel2.socket().bind(localAddr1); + this.channel2.connect(localAddr2); + + // write + ByteBuffer sourceBuf = ByteBuffer.wrap(sourceArray); + assertEquals(0, this.channel1.write(sourceBuf)); + + // read + ByteBuffer targetBuf = ByteBuffer.wrap(targetArray); + // empty message let the reader blocked + closeBlockedReaderChannel2(targetBuf); + } + + public void testReadWrite_changeBlock_Empty() throws Exception { + // empty buf + byte[] sourceArray = "".getBytes(); + byte[] targetArray = new byte[CAPACITY_NORMAL]; + + // bind and connect + + this.channel1.socket().bind(localAddr2); + this.channel1.connect(localAddr1); + this.channel2.socket().bind(localAddr1); + this.channel2.connect(localAddr2); + + // write + ByteBuffer sourceBuf = ByteBuffer.wrap(sourceArray); + assertEquals(0, this.channel1.write(sourceBuf)); + + // read + ByteBuffer targetBuf = ByteBuffer.wrap(targetArray); + // empty message let the reader blocked + new Thread() { + public void run() { + try { + Thread.sleep(TIME_UNIT); + channel2.configureBlocking(false); + Thread.sleep(TIME_UNIT * 5); + channel2.close(); + } catch (Exception e) { + // do nothing + } + } + }.start(); + try { + assertTrue(this.channel2.isBlocking()); + this.channel2.read(targetBuf); + fail("Should throw AsynchronousCloseException"); + } catch (AsynchronousCloseException e) { + assertFalse(this.channel2.isBlocking()); + // OK. + } + } + + public void testReadWrite_Block_8KB() throws Exception { + byte[] sourceArray = new byte[CAPACITY_1KB * 8]; + byte[] targetArray = new byte[CAPACITY_1KB * 8]; + for (int i = 0; i < sourceArray.length; i++) { + sourceArray[i] = (byte) i; + } + + // bind and connect + this.channel1.socket().bind(localAddr2); + this.channel1.connect(localAddr1); + this.channel2.socket().bind(localAddr1); + this.channel2.connect(localAddr2); + + readWriteReadData(this.channel1, sourceArray, this.channel2, + targetArray, 8 * CAPACITY_1KB, "testReadWrite_Block_8KB"); + } + + /* + * sender write the sourceArray whose size is dataSize, and receiver read + * the data into targetArray + */ + private void readWriteReadData(DatagramChannel sender, byte[] sourceArray, + DatagramChannel receiver, byte[] targetArray, int dataSize, + String methodName) throws IOException { + // write + ByteBuffer sourceBuf = ByteBuffer.wrap(sourceArray); + assertEquals(dataSize, sender.write(sourceBuf)); + + // read + ByteBuffer targetBuf = ByteBuffer.wrap(targetArray); + + int count = 0; + int total = 0; + long beginTime = System.currentTimeMillis(); + while (total < dataSize && (count = receiver.read(targetBuf)) != -1) { + total = total + count; + // 3s timeout to avoid dead loop + if (System.currentTimeMillis() - beginTime > 3000){ + break; + } + } + + assertEquals(dataSize, total); + assertEquals(targetBuf.position(), total); + targetBuf.flip(); + targetArray = targetBuf.array(); + for (int i = 0; i < targetArray.length; i++) { + assertEquals(targetArray[i], (byte) i); + } + } + + public void testReadWrite_Block_64K() throws Exception { + byte[] sourceArray = new byte[CAPACITY_64KB]; + for (int i = 0; i < sourceArray.length; i++) { + sourceArray[i] = (byte) i; + } + + // bind and connect + this.channel1.socket().bind(localAddr2); + this.channel1.connect(localAddr1); + this.channel2.socket().bind(localAddr1); + this.channel2.connect(localAddr2); + + // write + ByteBuffer sourceBuf = ByteBuffer.wrap(sourceArray); + try { + channel1.write(sourceBuf); + fail("Should throw IOException"); + } catch (IOException e) { + // too big + } + } + + public void testReadWrite_Block_DifferentAddr() throws Exception { + byte[] sourceArray = new byte[CAPACITY_NORMAL]; + byte[] targetArray = new byte[CAPACITY_NORMAL]; + for (int i = 0; i < sourceArray.length; i++) { + sourceArray[i] = (byte) i; + } + + // bind and connect + this.channel1.socket().bind(localAddr2); + this.channel1.connect(localAddr1); + this.channel2.socket().bind(localAddr1); + this.channel2.connect(localAddr1);// the different addr + + // write + ByteBuffer sourceBuf = ByteBuffer.wrap(sourceArray); + assertEquals(CAPACITY_NORMAL, this.channel1.write(sourceBuf)); + + // read + ByteBuffer targetBuf = ByteBuffer.wrap(targetArray); + // the wrong connected addr will make the read blocked. + // we close the blocked channel + closeBlockedReaderChannel2(targetBuf); + } + + public void testReadWrite_Block_WriterNotBind() throws Exception { + byte[] sourceArray = new byte[CAPACITY_NORMAL]; + byte[] targetArray = new byte[CAPACITY_NORMAL]; + for (int i = 0; i < sourceArray.length; i++) { + sourceArray[i] = (byte) i; + } + + // bind and connect + this.channel1.connect(localAddr1); + this.channel2.socket().bind(localAddr1); + this.channel2.connect(localAddr2); + + // write + ByteBuffer sourceBuf = ByteBuffer.wrap(sourceArray); + assertEquals(CAPACITY_NORMAL, this.channel1.write(sourceBuf)); + + // read + ByteBuffer targetBuf = ByteBuffer.wrap(targetArray); + closeBlockedReaderChannel2(targetBuf); + } + + public void testReadWrite_Block_WriterBindLater() throws Exception { + + byte[] targetArray = new byte[CAPACITY_NORMAL]; + + // bind and connect + // writer channel1 is bound later + this.channel2.socket().bind(localAddr1); + this.channel2.connect(localAddr2); + + // read + ByteBuffer targetBuf = ByteBuffer.wrap(targetArray); + new Thread() { + public void run() { + try { + Thread.sleep(TIME_UNIT); + // bind later + byte[] sourceArray = new byte[CAPACITY_NORMAL]; + for (int i = 0; i < sourceArray.length; i++) { + sourceArray[i] = (byte) i; + } + channel1.socket().bind(localAddr2); + channel1.connect(localAddr1); + // write later + ByteBuffer sourceBuf = ByteBuffer.wrap(sourceArray); + assertEquals(CAPACITY_NORMAL, channel1.write(sourceBuf)); + } catch (Exception e) { + // do nothing + } + } + }.start(); + + int count = 0; + int total = 0; + long beginTime = System.currentTimeMillis(); + while (total < CAPACITY_NORMAL && (count = channel2.read(targetBuf)) != -1) { + total = total + count; + // 3s timeout to avoid dead loop + if (System.currentTimeMillis() - beginTime > 3000){ + break; + } + } + + assertEquals(CAPACITY_NORMAL, total); + assertEquals(targetBuf.position(), total); + targetBuf.flip(); + targetArray = targetBuf.array(); + for (int i = 0; i < targetArray.length; i++) { + assertEquals(targetArray[i], (byte) i); + } + + } + + public void testReadWrite_Block_ReaderNotBind() throws Exception { + byte[] sourceArray = new byte[CAPACITY_NORMAL]; + byte[] targetArray = new byte[CAPACITY_NORMAL]; + for (int i = 0; i < sourceArray.length; i++) { + sourceArray[i] = (byte) i; + } + + // bind and connect + this.channel1.socket().bind(localAddr2); + this.channel1.connect(localAddr1); + // reader channel2 is not bound + this.channel2.connect(localAddr2); + + // write + ByteBuffer sourceBuf = ByteBuffer.wrap(sourceArray); + assertEquals(CAPACITY_NORMAL, this.channel1.write(sourceBuf)); + + // read + ByteBuffer targetBuf = ByteBuffer.wrap(targetArray); + closeBlockedReaderChannel2(targetBuf); + + } + + private void closeBlockedReaderChannel2(ByteBuffer targetBuf) + throws IOException { + new Thread() { + public void run() { + try { + Thread.sleep(TIME_UNIT); + channel2.close(); + } catch (Exception e) { + // do nothing + } + } + }.start(); + try { + assertTrue(this.channel2.isBlocking()); + this.channel2.read(targetBuf); + fail("Should throw AsynchronousCloseException"); + } catch (AsynchronousCloseException e) { + // OK. + } + } + + // ------------------------------------------------------------------- + // Test read and write in non-block mode. + // ------------------------------------------------------------------- + public void testReadWrite_NonBlock_Normal() throws Exception { + byte[] sourceArray = new byte[CAPACITY_NORMAL]; + byte[] targetArray = new byte[CAPACITY_NORMAL]; + for (int i = 0; i < sourceArray.length; i++) { + sourceArray[i] = (byte) i; + } + + this.channel1.configureBlocking(false); + this.channel2.configureBlocking(false); + + // bind and connect + this.channel1.socket().bind(localAddr2); + this.channel1.connect(localAddr1); + this.channel2.socket().bind(localAddr1); + this.channel2.connect(localAddr2); + + readWriteReadData(this.channel1, sourceArray, this.channel2, + targetArray, CAPACITY_NORMAL, "testReadWrite_NonBlock_Normal"); + } + + public void testReadWrite_NonBlock_8KB() throws Exception { + byte[] sourceArray = new byte[CAPACITY_1KB * 8]; + byte[] targetArray = new byte[CAPACITY_1KB * 8]; + for (int i = 0; i < sourceArray.length; i++) { + sourceArray[i] = (byte) i; + } + + this.channel1.configureBlocking(false); + this.channel2.configureBlocking(false); + + // bind and connect + this.channel1.socket().bind(localAddr2); + this.channel1.connect(localAddr1); + this.channel2.socket().bind(localAddr1); + this.channel2.connect(localAddr2); + + readWriteReadData(this.channel1, sourceArray, this.channel2, + targetArray, 8 * CAPACITY_1KB, "testReadWrite_NonBlock_8KB"); + } + + public void testReadWrite_NonBlock_DifferentAddr() throws Exception { + byte[] sourceArray = new byte[CAPACITY_NORMAL]; + byte[] targetArray = new byte[CAPACITY_NORMAL]; + for (int i = 0; i < sourceArray.length; i++) { + sourceArray[i] = (byte) i; + } + + this.channel1.configureBlocking(false); + this.channel2.configureBlocking(false); + + // bind and connect + this.channel1.socket().bind(localAddr2); + this.channel1.connect(localAddr1); + this.channel2.socket().bind(localAddr1); + this.channel2.connect(localAddr1);// the different addr + + // write + ByteBuffer sourceBuf = ByteBuffer.wrap(sourceArray); + assertEquals(CAPACITY_NORMAL, this.channel1.write(sourceBuf)); + + // read + ByteBuffer targetBuf = ByteBuffer.wrap(targetArray); + assertEquals(0, this.channel2.read(targetBuf)); + } + + public void testReadWrite_NonBlock_WriterNotBind() throws Exception { + byte[] sourceArray = new byte[CAPACITY_NORMAL]; + byte[] targetArray = new byte[CAPACITY_NORMAL]; + for (int i = 0; i < sourceArray.length; i++) { + sourceArray[i] = (byte) i; + } + + this.channel1.configureBlocking(false); + this.channel2.configureBlocking(false); + + // bind and connect + this.channel1.connect(localAddr1); + this.channel2.socket().bind(localAddr1); + this.channel2.connect(localAddr2); + + // write + ByteBuffer sourceBuf = ByteBuffer.wrap(sourceArray); + assertEquals(CAPACITY_NORMAL, this.channel1.write(sourceBuf)); + + // read + ByteBuffer targetBuf = ByteBuffer.wrap(targetArray); + assertEquals(0, this.channel2.read(targetBuf)); + } + + public void testReadWrite_NonBlock_ReaderNotBind() throws Exception { + byte[] sourceArray = new byte[CAPACITY_NORMAL]; + byte[] targetArray = new byte[CAPACITY_NORMAL]; + for (int i = 0; i < sourceArray.length; i++) { + sourceArray[i] = (byte) i; + } + + this.channel1.configureBlocking(false); + this.channel2.configureBlocking(false); + + // bind and connect + this.channel1.socket().bind(localAddr2); + this.channel1.connect(localAddr1); + this.channel2.connect(localAddr2); + + // write + ByteBuffer sourceBuf = ByteBuffer.wrap(sourceArray); + assertEquals(CAPACITY_NORMAL, this.channel1.write(sourceBuf)); + + // read + ByteBuffer targetBuf = ByteBuffer.wrap(targetArray); + assertEquals(0, this.channel2.read(targetBuf)); + } + + public void test_write_LBuffer_positioned() throws Exception { + // Regression test for Harmony-683 + int position = 16; + DatagramChannel dc = DatagramChannel.open(); + byte[] sourceArray = new byte[CAPACITY_NORMAL]; + dc.connect(localAddr1); + // write + ByteBuffer sourceBuf = ByteBuffer.wrap(sourceArray); + sourceBuf.position(position); + assertEquals(CAPACITY_NORMAL - position, dc.write(sourceBuf)); + } + + public void test_send_LBuffer_LSocketAddress_PositionNotZero() + throws Exception { + // regression test for Harmony-701 + int CAPACITY_NORMAL = 256; + int position = 16; + DatagramChannel dc = DatagramChannel.open(); + byte[] sourceArray = new byte[CAPACITY_NORMAL]; + // send ByteBuffer whose position is not zero + ByteBuffer sourceBuf = ByteBuffer.wrap(sourceArray); + sourceBuf.position(position); + int ret = dc.send(sourceBuf, localAddr1); + // assert send (256 - 16) bytes + assertEquals(CAPACITY_NORMAL - position, ret); + // assert the position of ByteBuffer has been set + assertEquals(CAPACITY_NORMAL, sourceBuf.position()); + } + + /** + * @tests DatagramChannel#read(ByteBuffer[]) + */ + public void test_read_$LByteBuffer() throws Exception { + // regression test for Harmony-754 + channel2.socket().bind(localAddr1); + channel1.socket().bind(localAddr2); + channel1.connect(localAddr1); + channel2.connect(localAddr2); + channel2.write(ByteBuffer.allocate(CAPACITY_NORMAL)); + + ByteBuffer[] readBuf = new ByteBuffer[2]; + readBuf[0] = ByteBuffer.allocateDirect(CAPACITY_NORMAL); + readBuf[1] = ByteBuffer.allocateDirect(CAPACITY_NORMAL); + + channel1.configureBlocking(true); + assertEquals(CAPACITY_NORMAL, channel1.read(readBuf)); + } + + /** + * @tests DatagramChannel#read(ByteBuffer[],int,int) + */ + public void test_read_$LByteBufferII() throws Exception { + // regression test for Harmony-754 + channel2.socket().bind(localAddr1); + channel1.socket().bind(localAddr2); + channel1.connect(localAddr1); + channel2.connect(localAddr2); + channel2.write(ByteBuffer.allocate(CAPACITY_NORMAL)); + + ByteBuffer[] readBuf = new ByteBuffer[2]; + readBuf[0] = ByteBuffer.allocateDirect(CAPACITY_NORMAL); + readBuf[1] = ByteBuffer.allocateDirect(CAPACITY_NORMAL); + + channel1.configureBlocking(true); + assertEquals(CAPACITY_NORMAL, channel1.read(readBuf,0,2)); + } + + /** + * @tests DatagramChannel#read(ByteBuffer) + */ + public void test_read_LByteBuffer_closed_nullBuf() throws Exception { + // regression test for Harmony-754 + ByteBuffer c = null; + DatagramChannel channel = DatagramChannel.open(); + channel.close(); + try{ + channel.read(c); + fail("Should throw NullPointerException"); + } catch (NullPointerException e){ + // expected + } + } + + /** + * @tests DatagramChannel#read(ByteBuffer) + */ + public void test_read_LByteBuffer_NotConnected_nullBuf() throws Exception { + // regression test for Harmony-754 + ByteBuffer c = null; + DatagramChannel channel = DatagramChannel.open(); + try{ + channel.read(c); + fail("Should throw NullPointerException"); + } catch (NullPointerException e){ + // expected + } + } + + /** + * @tests DatagramChannel#read(ByteBuffer) + */ + public void test_read_LByteBuffer_readOnlyBuf() throws Exception { + // regression test for Harmony-754 + ByteBuffer c = ByteBuffer.allocate(1); + DatagramChannel channel = DatagramChannel.open(); + try{ + channel.read(c.asReadOnlyBuffer()); + fail("Should throw NotYetConnectedException"); + } catch (NotYetConnectedException e){ + } catch (IllegalArgumentException e){ + // expected + } + channel.connect(localAddr1); + try{ + channel.read(c.asReadOnlyBuffer()); + fail("Should throw IllegalArgumentException"); + } catch (IllegalArgumentException e){ + // expected + } + } + + /** + * @tests DatagramChannel#send(ByteBuffer, SocketAddress) + */ + public void test_send_LByteBuffer_LSocketAddress_closed() throws IOException{ + // regression test for Harmony-913 + channel1.close(); + ByteBuffer buf = ByteBuffer.allocate(CAPACITY_NORMAL); + try { + channel1.send(buf, localAddr1); + fail("Should throw ClosedChannelException"); + } catch (ClosedChannelException e) { + //pass + } + try { + channel1.send(null,localAddr1); + fail("Should throw NullPointerException"); + } catch (NullPointerException e) { + //pass + } + try { + channel1.send(buf, null); + fail("Should throw ClosedChannelException"); + } catch (ClosedChannelException e) { + //pass + } + try { + channel1.send(null, null); + fail("Should throw NullPointerException"); + } catch (NullPointerException e) { + //pass + } + } + + /** + * @tests DatagramChannel#socket() + */ + public void test_socket_IllegalBlockingModeException() throws Exception { + // regression test for Harmony-1036 + DatagramChannel channel = DatagramChannel.open(); + channel.configureBlocking(false); + DatagramSocket socket = channel.socket(); + try { + socket.send(null); + fail("should throw IllegalBlockingModeException"); + } catch (IllegalBlockingModeException e) { + // expected + } + try { + socket.receive(null); + fail("should throw IllegalBlockingModeException"); + } catch (IllegalBlockingModeException e) { + // expected + } + } + + public void test_bounded_harmony6493() throws IOException { + DatagramChannel server = DatagramChannel.open(); + InetSocketAddress addr = new InetSocketAddress("localhost", 0); + server.socket().bind(addr); + SocketAddress boundedAddress = server.socket().getLocalSocketAddress(); + + DatagramChannel client = DatagramChannel.open(); + ByteBuffer sent = ByteBuffer.allocate(1024); + sent.put("test".getBytes()); + sent.flip(); + client.send(sent, boundedAddress); + assertTrue(client.socket().isBound()); + + server.close(); + client.close(); + } +} 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/nio/tests/java/nio/channels/FileChannelLockingTest.java new file mode 100644 index 0000000..cb34343 --- /dev/null +++ b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/FileChannelLockingTest.java @@ -0,0 +1,208 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.harmony.nio.tests.java.nio.channels; + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.FileWriter; +import java.io.IOException; +import java.io.RandomAccessFile; +import java.nio.channels.FileChannel; +import java.nio.channels.FileLock; +import java.nio.channels.NonReadableChannelException; +import java.nio.channels.NonWritableChannelException; +import java.nio.channels.OverlappingFileLockException; + +import junit.framework.TestCase; + +/** + * API tests for the NIO FileChannel locking APIs + */ +public class FileChannelLockingTest extends TestCase { + + private FileChannel readOnlyChannel; + + private FileChannel writeOnlyChannel; + + private FileChannel readWriteChannel; + + private final String CONTENT = "The best things in life are nearest: Breath in your nostrils, light in your eyes, " + + "flowers at your feet, duties at your hand, the path of right just before you. Then do not grasp at the stars, " + + "but do life's plain, common work as it comes, certain that daily duties and daily bread are the sweetest " + + " things in life.--Robert Louis Stevenson"; + + protected void setUp() throws Exception { + super.setUp(); + + // Create a three temporary files with content. + File[] tempFiles = new File[3]; + for (int i = 0; i < tempFiles.length; i++) { + tempFiles[i] = File.createTempFile("testing", "tmp"); + tempFiles[i].deleteOnExit(); + FileWriter writer = new FileWriter(tempFiles[i]); + writer.write(CONTENT); + writer.close(); + } + + // Open read, write, and read/write channels on the temp files. + FileInputStream fileInputStream = new FileInputStream(tempFiles[0]); + readOnlyChannel = fileInputStream.getChannel(); + + FileOutputStream fileOutputStream = new FileOutputStream(tempFiles[1]); + writeOnlyChannel = fileOutputStream.getChannel(); + + RandomAccessFile randomAccessFile = new RandomAccessFile(tempFiles[2], + "rw"); + readWriteChannel = randomAccessFile.getChannel(); + } + + protected void tearDown() throws IOException { + if (readOnlyChannel != null) { + readOnlyChannel.close(); + } + if (writeOnlyChannel != null) { + writeOnlyChannel.close(); + } + if (readWriteChannel != null) { + readWriteChannel.close(); + } + } + + public void test_illegalLocks() throws IOException { + // Cannot acquire an exclusive lock on a read-only file channel + try { + readOnlyChannel.lock(); + fail("Acquiring a full exclusive lock on a read only channel should fail."); + } catch (NonWritableChannelException ex) { + // Expected. + } + + // Cannot get a shared lock on a write-only file channel. + try { + writeOnlyChannel.lock(1, 10, true); + fail("Acquiring a shared lock on a write-only channel should fail."); + } catch (NonReadableChannelException ex) { + // expected + } + } + + public void test_lockReadWrite() throws IOException { + // Acquire an exclusive lock across the entire file. + FileLock flock = readWriteChannel.lock(); + if (flock != null) { + flock.release(); + } + } + + public void test_illegalLockParameters() throws IOException { + // Cannot lock negative positions + try { + readOnlyChannel.lock(-1, 10, true); + fail("Passing illegal args to lock should fail."); + } catch (IllegalArgumentException ex) { + // expected + } + try { + writeOnlyChannel.lock(-1, 10, false); + fail("Passing illegal args to lock should fail."); + } catch (IllegalArgumentException ex) { + // expected + } + try { + readWriteChannel.lock(-1, 10, false); + fail("Passing illegal args to lock should fail."); + } catch (IllegalArgumentException ex) { + // expected + } + + // Lock a range at the front, shared. + FileLock flock1 = readWriteChannel.lock(22, 110, true); + + // Try to acquire an overlapping lock. + try { + readWriteChannel.lock(75, 210, true); + } catch (OverlappingFileLockException exception) { + // expected + flock1.release(); + } + } + + public void test_lockLLZ() throws IOException { + // Lock a range at the front, non-shared. + FileLock flock1 = readWriteChannel.lock(0, 10, false); + + // Lock a shared range further in the same file. + FileLock flock2 = readWriteChannel.lock(22, 100, true); + + // The spec allows the impl to refuse shared locks + flock1.release(); + flock2.release(); + } + + public void test_tryLock() throws IOException { + try { + readOnlyChannel.tryLock(); + fail("Acquiring a full exclusive lock on a read channel should have thrown an exception."); + } catch (NonWritableChannelException ex) { + // Expected. + } + } + + public void test_tryLockLLZ() throws IOException { + // It is illegal to request an exclusive lock on a read-only channel + try { + readOnlyChannel.tryLock(0, 99, false); + fail("Acquiring exclusive lock on read-only channel should fail"); + } catch (NonWritableChannelException ex) { + // Expected + } + + // It is invalid to request a lock starting before the file start + try { + readOnlyChannel.tryLock(-99, 0, true); + fail("Acquiring an illegal lock value should fail."); + } catch (IllegalArgumentException ex) { + // expected + } + + // Acquire a valid lock + FileLock tmpLock = readOnlyChannel.tryLock(0, 10, true); + assertTrue(tmpLock.isValid()); + tmpLock.release(); + + // Acquire another valid lock -- and don't release it yet + FileLock lock = readOnlyChannel.tryLock(10, 788, true); + assertTrue(lock.isValid()); + + // Overlapping locks are illegal + try { + readOnlyChannel.tryLock(1, 23, true); + fail("Acquiring an overlapping lock should fail."); + } catch (OverlappingFileLockException ex) { + // Expected + } + + // Adjacent locks are legal + FileLock adjacentLock = readOnlyChannel.tryLock(1, 3, true); + assertTrue(adjacentLock.isValid()); + adjacentLock.release(); + + // Release longer lived lock + lock.release(); + } +} 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/nio/tests/java/nio/channels/FileChannelTest.java new file mode 100644 index 0000000..9a89f7e --- /dev/null +++ b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/FileChannelTest.java @@ -0,0 +1,3121 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.harmony.nio.tests.java.nio.channels; + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.RandomAccessFile; +import java.io.UnsupportedEncodingException; +import java.net.InetAddress; +import java.net.InetSocketAddress; +import java.nio.BufferOverflowException; +import java.nio.ByteBuffer; +import java.nio.MappedByteBuffer; +import java.nio.ReadOnlyBufferException; +import java.nio.channels.ClosedChannelException; +import java.nio.channels.DatagramChannel; +import java.nio.channels.FileChannel; +import java.nio.channels.FileLock; +import java.nio.channels.NonReadableChannelException; +import java.nio.channels.NonWritableChannelException; +import java.nio.channels.OverlappingFileLockException; +import java.nio.channels.Pipe; +import java.nio.channels.ReadableByteChannel; +import java.nio.channels.ServerSocketChannel; +import java.nio.channels.SocketChannel; +import java.nio.channels.WritableByteChannel; +import java.nio.channels.FileChannel.MapMode; +import java.util.Arrays; + +import junit.framework.TestCase; + +public class FileChannelTest extends TestCase { + + private static final int CAPACITY = 100; + + private static final int LIMITED_CAPACITY = 2; + + private static final int TIME_OUT = 10000; + + private static final String CONTENT = "MYTESTSTRING needs to be a little long"; + + private static final byte[] TEST_BYTES; + + private static final byte[] CONTENT_AS_BYTES; + + private static final int CONTENT_AS_BYTES_LENGTH; + + static { + try { + TEST_BYTES = "test".getBytes("iso8859-1"); + CONTENT_AS_BYTES = CONTENT.getBytes("iso8859-1"); + CONTENT_AS_BYTES_LENGTH = CONTENT_AS_BYTES.length; + } catch (UnsupportedEncodingException e) { + throw new Error(e); + } + } + + private static final int CONTENT_LENGTH = CONTENT.length(); + + private FileChannel readOnlyFileChannel; + + private FileChannel writeOnlyFileChannel; + + private FileChannel readWriteFileChannel; + + private File fileOfReadOnlyFileChannel; + + private File fileOfWriteOnlyFileChannel; + + private File fileOfReadWriteFileChannel; + + private ReadableByteChannel readByteChannel; + + private WritableByteChannel writableByteChannel; + + private DatagramChannel datagramChannelSender; + + private DatagramChannel datagramChannelReceiver; + + private ServerSocketChannel serverSocketChannel; + + private SocketChannel socketChannelSender; + + private SocketChannel socketChannelReceiver; + + private Pipe pipe; + + // to read content from FileChannel + private FileInputStream fis; + + private FileLock fileLock; + + protected void setUp() throws Exception { + fileOfReadOnlyFileChannel = File.createTempFile( + "File_of_readOnlyFileChannel", "tmp"); + fileOfReadOnlyFileChannel.deleteOnExit(); + fileOfWriteOnlyFileChannel = File.createTempFile( + "File_of_writeOnlyFileChannel", "tmp"); + fileOfWriteOnlyFileChannel.deleteOnExit(); + fileOfReadWriteFileChannel = File.createTempFile( + "File_of_readWriteFileChannel", "tmp"); + fileOfReadWriteFileChannel.deleteOnExit(); + fis = null; + fileLock = null; + readOnlyFileChannel = new FileInputStream(fileOfReadOnlyFileChannel) + .getChannel(); + writeOnlyFileChannel = new FileOutputStream(fileOfWriteOnlyFileChannel) + .getChannel(); + readWriteFileChannel = new RandomAccessFile(fileOfReadWriteFileChannel, + "rw").getChannel(); + } + + protected void tearDown() { + if (null != readOnlyFileChannel) { + try { + readOnlyFileChannel.close(); + } catch (IOException e) { + // do nothing + } + } + if (null != writeOnlyFileChannel) { + try { + writeOnlyFileChannel.close(); + } catch (IOException e) { + // do nothing + } + } + if (null != readWriteFileChannel) { + try { + readWriteFileChannel.close(); + } catch (IOException e) { + // do nothing + } + } + if (null != fis) { + try { + fis.close(); + } catch (IOException e) { + // do nothing + } + } + + if (null != fileLock) { + try { + fileLock.release(); + } catch (IOException e) { + // do nothing + } + } + + if (null != fileOfReadOnlyFileChannel) { + fileOfReadOnlyFileChannel.delete(); + } + if (null != fileOfWriteOnlyFileChannel) { + fileOfWriteOnlyFileChannel.delete(); + } + if (null != fileOfReadWriteFileChannel) { + fileOfReadWriteFileChannel.delete(); + } + if (null != datagramChannelSender) { + try { + datagramChannelSender.close(); + } catch (IOException e) { + // do nothing + } + } + if (null != datagramChannelReceiver) { + try { + datagramChannelReceiver.close(); + } catch (IOException e) { + // do nothing + } + } + if (null != serverSocketChannel) { + try { + serverSocketChannel.close(); + } catch (IOException e) { + // do nothing + } + } + if (null != socketChannelSender) { + try { + socketChannelSender.close(); + } catch (IOException e) { + // do nothing + } + } + if (null != socketChannelReceiver) { + try { + socketChannelReceiver.close(); + } catch (IOException e) { + // do nothing + } + } + if (null != pipe) { + if (null != pipe.source()) { + try { + pipe.source().close(); + } catch (IOException e) { + // do nothing + } + } + if (null != pipe.sink()) { + try { + pipe.sink().close(); + } catch (IOException e) { + // do nothing + } + } + } + } + + /** + * @tests java.nio.channels.FileChannel#force(boolean) + */ + public void test_forceJ() throws Exception { + ByteBuffer writeBuffer = ByteBuffer.wrap(CONTENT_AS_BYTES); + writeOnlyFileChannel.write(writeBuffer); + writeOnlyFileChannel.force(true); + + byte[] readBuffer = new byte[CONTENT_AS_BYTES_LENGTH]; + fis = new FileInputStream(fileOfWriteOnlyFileChannel); + fis.read(readBuffer); + assertTrue(Arrays.equals(CONTENT_AS_BYTES, readBuffer)); + } + + /** + * @tests java.nio.channels.FileChannel#force(boolean) + */ + public void test_forceJ_closed() throws Exception { + writeOnlyFileChannel.close(); + try { + writeOnlyFileChannel.force(true); + fail(); + } catch (ClosedChannelException expected) { + } + + try { + writeOnlyFileChannel.force(false); + fail(); + } catch (ClosedChannelException expected) { + } + } + + /** + * @tests java.nio.channels.FileChannel#force(boolean) + */ + public void test_forceJ_ReadOnlyChannel() throws Exception { + // force on a read only file channel has no effect. + readOnlyFileChannel.force(true); + readOnlyFileChannel.force(false); + } + + /** + * @tests java.nio.channels.FileChannel#position() + */ + public void test_position_Init() throws Exception { + assertEquals(0, readOnlyFileChannel.position()); + assertEquals(0, writeOnlyFileChannel.position()); + assertEquals(0, readWriteFileChannel.position()); + } + + /** + * @tests java.nio.channels.FileChannel#position() + */ + public void test_position_ReadOnly() throws Exception { + writeDataToFile(fileOfReadOnlyFileChannel); + + assertEquals(0, readOnlyFileChannel.position()); + ByteBuffer readBuffer = ByteBuffer.allocate(CONTENT_LENGTH); + readOnlyFileChannel.read(readBuffer); + assertEquals(CONTENT_LENGTH, readOnlyFileChannel.position()); + } + + /** + * Initializes test file. + * + * @param file + * @throws FileNotFoundException + * @throws IOException + */ + private void writeDataToFile(File file) throws FileNotFoundException, + IOException { + FileOutputStream fos = new FileOutputStream(file); + try { + fos.write(CONTENT_AS_BYTES); + } finally { + fos.close(); + } + } + + /** + * Initializes large test file. + * + * @param file the file to be written + * @param size the content size to be written + * @throws FileNotFoundException + * @throws IOException + */ + private void writeLargeDataToFile(File file, int size) throws FileNotFoundException, + IOException { + FileOutputStream fos = new FileOutputStream(file); + byte[] buf = new byte[size]; + + try { + // we don't care about content - just need a particular file size + fos.write(buf); + } finally { + fos.close(); + } + } + + /** + * @tests java.nio.channels.FileChannel#position() + */ + public void test_position_WriteOnly() throws Exception { + ByteBuffer writeBuffer = ByteBuffer.wrap(CONTENT_AS_BYTES); + writeOnlyFileChannel.write(writeBuffer); + assertEquals(CONTENT_LENGTH, writeOnlyFileChannel.position()); + } + + /** + * @tests java.nio.channels.FileChannel#position() + */ + public void test_position_ReadWrite() throws Exception { + writeDataToFile(fileOfReadWriteFileChannel); + + assertEquals(0, readWriteFileChannel.position()); + ByteBuffer readBuffer = ByteBuffer.allocate(CONTENT_LENGTH); + readWriteFileChannel.read(readBuffer); + assertEquals(CONTENT_LENGTH, readWriteFileChannel.position()); + + ByteBuffer writeBuffer = ByteBuffer.wrap(CONTENT_AS_BYTES); + readWriteFileChannel.write(writeBuffer); + assertEquals(CONTENT_LENGTH * 2, readWriteFileChannel.position()); + } + + /** + * @tests java.nio.channels.FileChannel#position() + */ + public void test_position_Closed() throws Exception { + readOnlyFileChannel.close(); + try { + readOnlyFileChannel.position(); + fail("should throw ClosedChannelException"); + } catch (ClosedChannelException expected) { + } + + writeOnlyFileChannel.close(); + try { + writeOnlyFileChannel.position(); + fail("should throw ClosedChannelException"); + } catch (ClosedChannelException expected) { + } + + readWriteFileChannel.close(); + try { + readWriteFileChannel.position(); + fail("should throw ClosedChannelException"); + } catch (ClosedChannelException expected) { + } + } + + /** + * @tests java.nio.channels.FileChannel#position(long) + */ + public void test_positionJ_Closed() throws Exception { + final long POSITION = 100; + + readOnlyFileChannel.close(); + try { + readOnlyFileChannel.position(POSITION); + fail(); + } catch (ClosedChannelException expected) { + } + + writeOnlyFileChannel.close(); + try { + writeOnlyFileChannel.position(POSITION); + fail(); + } catch (ClosedChannelException expected) { + } + + readWriteFileChannel.close(); + try { + readWriteFileChannel.position(POSITION); + fail(); + } catch (ClosedChannelException expected) { + } + } + + /** + * @tests java.nio.channels.FileChannel#position(long) + */ + public void test_positionJ_Negative() throws Exception { + final long NEGATIVE_POSITION = -1; + try { + readOnlyFileChannel.position(NEGATIVE_POSITION); + fail("should throw IllegalArgumentException"); + } catch (IllegalArgumentException e) { + // expected + } + + try { + writeOnlyFileChannel.position(NEGATIVE_POSITION); + fail("should throw IllegalArgumentException"); + } catch (IllegalArgumentException e) { + // expected + } + + try { + readWriteFileChannel.position(NEGATIVE_POSITION); + fail("should throw IllegalArgumentException"); + } catch (IllegalArgumentException e) { + // expected + } + } + + /** + * @tests java.nio.channels.FileChannel#position(long) + */ + public void test_positionJ_ReadOnly() throws Exception { + writeDataToFile(fileOfReadOnlyFileChannel); + + // set the position of the read only file channel to POSITION + final int POSITION = 4; + readOnlyFileChannel.position(POSITION); + + // reads the content left to readBuffer through read only file channel + ByteBuffer readBuffer = ByteBuffer.allocate(CONTENT_LENGTH); + int count = readOnlyFileChannel.read(readBuffer); + assertEquals(CONTENT_LENGTH - POSITION, count); + + // asserts the content read is the part which stays beyond the POSITION + readBuffer.flip(); + int i = POSITION; + while (readBuffer.hasRemaining()) { + assertEquals(CONTENT_AS_BYTES[i], readBuffer.get()); + i++; + } + } + + /** + * @tests java.nio.channels.FileChannel#position(long) + */ + public void test_positionJ_WriteOnly() throws Exception { + writeDataToFile(fileOfWriteOnlyFileChannel); + + // init data to write + ByteBuffer writeBuffer = ByteBuffer.wrap(CONTENT_AS_BYTES); + + // set the position of the write only file channel to POSITION + final int POSITION = 4; + writeOnlyFileChannel.position(POSITION); + + // writes to the write only file channel + writeOnlyFileChannel.write(writeBuffer); + // force to write out. + writeOnlyFileChannel.close(); + + // gets the result of the write only file channel + byte[] result = new byte[POSITION + CONTENT_LENGTH]; + fis = new FileInputStream(fileOfWriteOnlyFileChannel); + fis.read(result); + + // constructs the expected result which has content[0... POSITION] plus + // content[0...length()] + byte[] expectedResult = new byte[POSITION + CONTENT_LENGTH]; + System.arraycopy(CONTENT_AS_BYTES, 0, expectedResult, 0, POSITION); + System.arraycopy(CONTENT_AS_BYTES, 0, expectedResult, POSITION, + CONTENT_LENGTH); + + // asserts result of the write only file channel same as expected + assertTrue(Arrays.equals(expectedResult, result)); + } + + /** + * @tests java.nio.channels.FileChannel#size() + */ + public void test_size_Init() throws Exception { + assertEquals(0, readOnlyFileChannel.size()); + assertEquals(0, writeOnlyFileChannel.size()); + assertEquals(0, readWriteFileChannel.size()); + } + + /** + * @tests java.nio.channels.FileChannel#size() + */ + public void test_size() throws Exception { + writeDataToFile(fileOfReadOnlyFileChannel); + assertEquals(fileOfReadOnlyFileChannel.length(), readOnlyFileChannel + .size()); + + + // REGRESSION test for read(ByteBuffer[], int, int) on special files + try { + FileChannel specialFile = + new FileInputStream("/dev/zero").getChannel(); + assertEquals(0, specialFile.size()); + ByteBuffer buf = ByteBuffer.allocate(8); + assertEquals(8, specialFile.read(buf)); + ByteBuffer[] bufs = { ByteBuffer.allocate(8) }; + assertEquals(8, specialFile.read(bufs, 0, 1)); + specialFile.close(); + } catch (FileNotFoundException e) { + // skip test if special file doesn't exist + } + } + + /** + * @tests java.nio.channels.FileChannel#size() + */ + public void test_size_Closed() throws Exception { + readOnlyFileChannel.close(); + try { + readOnlyFileChannel.size(); + fail("should throw ClosedChannelException"); + } catch (ClosedChannelException e) { + // expected + } + + writeOnlyFileChannel.close(); + try { + writeOnlyFileChannel.size(); + fail("should throw ClosedChannelException"); + } catch (ClosedChannelException e) { + // expected + } + + readWriteFileChannel.close(); + try { + readWriteFileChannel.size(); + fail("should throw ClosedChannelException"); + } catch (ClosedChannelException e) { + // expected + } + } + + /** + * @tests java.nio.channels.FileChannel#truncate(long) + */ + public void test_truncateJ_Closed() throws Exception { + readOnlyFileChannel.close(); + try { + readOnlyFileChannel.truncate(0); + fail("should throw ClosedChannelException"); + } catch (ClosedChannelException e) { + // expected + } + + writeOnlyFileChannel.close(); + try { + writeOnlyFileChannel.truncate(0); + fail("should throw ClosedChannelException"); + } catch (ClosedChannelException e) { + // expected + } + + readWriteFileChannel.close(); + try { + readWriteFileChannel.truncate(-1); + fail("should throw ClosedChannelException"); + } catch (ClosedChannelException e) { + // expected + } + } + + /** + * @tests java.nio.channels.FileChannel#truncate(long) + */ + public void test_truncateJ_IllegalArgument() throws Exception { + // regression test for Harmony-941 + try { + readOnlyFileChannel.truncate(-1); + fail("should throw IllegalArgumentException"); + } catch (IllegalArgumentException e) { + // expected + } + + try { + writeOnlyFileChannel.truncate(-1); + fail("should throw IllegalArgumentException"); + } catch (IllegalArgumentException e) { + // expected + } + + try { + readWriteFileChannel.truncate(-1); + fail("should throw IllegalArgumentException"); + } catch (IllegalArgumentException e) { + // expected + } + } + + /** + * @tests java.nio.channels.FileChannel#truncate(long) + */ + public void test_truncateJ_ReadOnly() throws Exception { + writeDataToFile(fileOfReadOnlyFileChannel); + try { + readOnlyFileChannel.truncate(readOnlyFileChannel.size()); + fail("should throw NonWritableChannelException."); + } catch (NonWritableChannelException e) { + // expected + } + + try { + readOnlyFileChannel.truncate(0); + fail("should throw NonWritableChannelException."); + } catch (NonWritableChannelException e) { + // expected + } + } + + /** + * @tests java.nio.channels.FileChannel#truncate(long) + */ + public void test_truncateJ() throws Exception { + writeDataToFile(fileOfReadWriteFileChannel); + + int truncateLength = CONTENT_LENGTH + 2; + assertEquals(readWriteFileChannel, readWriteFileChannel + .truncate(truncateLength)); + assertEquals(CONTENT_LENGTH, fileOfReadWriteFileChannel.length()); + + truncateLength = CONTENT_LENGTH; + assertEquals(readWriteFileChannel, readWriteFileChannel + .truncate(truncateLength)); + assertEquals(CONTENT_LENGTH, fileOfReadWriteFileChannel.length()); + + truncateLength = CONTENT_LENGTH / 2; + assertEquals(readWriteFileChannel, readWriteFileChannel + .truncate(truncateLength)); + assertEquals(truncateLength, fileOfReadWriteFileChannel.length()); + } + + /** + * @tests java.nio.channels.FileChannel#lock() + */ + public void test_lock() throws Exception { + MockFileChannel mockFileChannel = new MockFileChannel(); + // Verify that calling lock() leads to the method + // lock(long, long, boolean) being called with a 0 for the + // first parameter, Long.MAX_VALUE as the second parameter and false + // as the third parameter. + mockFileChannel.lock(); + assertTrue(mockFileChannel.isLockCalled); + } + + /** + * @tests java.nio.channels.FileChannel#lock(long, long, boolean) + */ + public void test_lockJJZ_Closed() throws Exception { + readOnlyFileChannel.close(); + try { + readOnlyFileChannel.lock(0, 10, false); + fail("should throw ClosedChannelException"); + } catch (ClosedChannelException e) { + // expected + } + + writeOnlyFileChannel.close(); + try { + writeOnlyFileChannel.lock(0, 10, false); + fail("should throw ClosedChannelException"); + } catch (ClosedChannelException e) { + // expected + } + + readWriteFileChannel.close(); + try { + readWriteFileChannel.lock(0, 10, false); + fail("should throw ClosedChannelException"); + } catch (ClosedChannelException e) { + // expected + } + + // throws ClosedChannelException before IllegalArgumentException + try { + readWriteFileChannel.lock(-1, 0, false); + fail("should throw ClosedChannelException"); + } catch (ClosedChannelException e) { + // expected + } + } + + /** + * @tests java.nio.channels.FileChannel#lock(long, long, boolean) + */ + public void test_lockJJZ_IllegalArgument() throws Exception { + try { + writeOnlyFileChannel.lock(0, -1, false); + fail("should throw IllegalArgumentException"); + } catch (IllegalArgumentException e) { + // expected + } + + try { + writeOnlyFileChannel.lock(-1, 0, false); + fail("should throw IllegalArgumentException"); + } catch (IllegalArgumentException e) { + // expected + } + + try { + readWriteFileChannel.lock(-1, -1, false); + fail("should throw IllegalArgumentException"); + } catch (IllegalArgumentException e) { + // expected + } + + try { + readWriteFileChannel.lock(Long.MAX_VALUE, 1, false); + fail("should throw IllegalArgumentException"); + } catch (IllegalArgumentException e) { + // expected + } + } + + /** + * @tests java.nio.channels.FileChannel#lock(long, long, boolean) + */ + public void test_lockJJZ_NonWritable() throws Exception { + try { + readOnlyFileChannel.lock(0, 10, false); + fail("should throw NonWritableChannelException"); + } catch (NonWritableChannelException e) { + // expected + } + + // throws NonWritableChannelException before IllegalArgumentException + try { + readOnlyFileChannel.lock(-1, 0, false); + fail("should throw NonWritableChannelException"); + } catch (NonWritableChannelException e) { + // expected + } + } + + /** + * @tests java.nio.channels.FileChannel#lock(long, long, boolean) + */ + public void test_lockJJZ_NonReadable() throws Exception { + try { + writeOnlyFileChannel.lock(0, 10, true); + fail("should throw NonReadableChannelException"); + } catch (NonReadableChannelException e) { + // expected + } + + // throws NonReadableChannelException before IllegalArgumentException + try { + writeOnlyFileChannel.lock(-1, 0, true); + fail("should throw NonReadableChannelException"); + } catch (NonReadableChannelException e) { + // expected + } + } + + /** + * @tests java.nio.channels.FileChannel#lock(long, long, boolean) + */ + public void test_lockJJZ_Shared() throws Exception { + final long POSITION = 100; + final long SIZE = 200; + fileLock = readOnlyFileChannel.lock(POSITION, SIZE, true); + assertTrue(fileLock.isValid()); + // fileLock.isShared depends on whether the underlying platform support + // shared lock, but it works on Windows & Linux. + assertTrue(fileLock.isShared()); + assertSame(readOnlyFileChannel, fileLock.channel()); + assertEquals(POSITION, fileLock.position()); + assertEquals(SIZE, fileLock.size()); + } + + /** + * @tests java.nio.channels.FileChannel#lock(long, long, boolean) + */ + public void test_lockJJZ_NotShared() throws Exception { + final long POSITION = 100; + final long SIZE = 200; + fileLock = writeOnlyFileChannel.lock(POSITION, SIZE, false); + assertTrue(fileLock.isValid()); + assertFalse(fileLock.isShared()); + assertSame(writeOnlyFileChannel, fileLock.channel()); + assertEquals(POSITION, fileLock.position()); + assertEquals(SIZE, fileLock.size()); + } + + /** + * @tests java.nio.channels.FileChannel#lock(long, long, boolean) + */ + public void test_lockJJZ_Long_MAX_VALUE() throws Exception { + final long POSITION = 0; + final long SIZE = Long.MAX_VALUE; + fileLock = readOnlyFileChannel.lock(POSITION, SIZE, true); + assertTrue(fileLock.isValid()); + assertTrue(fileLock.isShared()); + assertEquals(POSITION, fileLock.position()); + assertEquals(SIZE, fileLock.size()); + assertSame(readOnlyFileChannel, fileLock.channel()); + } + + /** + * @tests java.nio.channels.FileChannel#lock(long, long, boolean) + */ + public void test_lockJJZ_Overlapping() throws Exception { + final long POSITION = 100; + final long SIZE = 200; + fileLock = writeOnlyFileChannel.lock(POSITION, SIZE, false); + assertTrue(fileLock.isValid()); + + try { + writeOnlyFileChannel.lock(POSITION + 1, SIZE, false); + fail("should throw OverlappingFileLockException"); + } catch (OverlappingFileLockException e) { + // expected + } + } + + /** + * @tests java.nio.channels.FileChannel#lock(long, long, boolean) + */ + public void test_lockJJZ_NotOverlapping() throws Exception { + final long POSITION = 100; + final long SIZE = 200; + FileLock fileLock1 = writeOnlyFileChannel.lock(POSITION, SIZE, false); + assertTrue(fileLock1.isValid()); + FileLock fileLock2 = writeOnlyFileChannel.lock(POSITION + SIZE, SIZE, + false); + assertTrue(fileLock2.isValid()); + } + + /** + * @tests java.nio.channels.FileChannel#lock(long,long,boolean) + */ + public void test_lockJJZ_After_Release() throws Exception { + fileLock = writeOnlyFileChannel.lock(0, 10, false); + fileLock.release(); + // after release file lock can be obtained again. + fileLock = writeOnlyFileChannel.lock(0, 10, false); + assertTrue(fileLock.isValid()); + } + + /** + * @tests java.nio.channels.FileChannel#tryLock() + */ + public void test_tryLock() throws Exception { + MockFileChannel mockFileChannel = new MockFileChannel(); + // Verify that calling tryLock() leads to the method + // tryLock(long, long, boolean) being called with a 0 for the + // first parameter, Long.MAX_VALUE as the second parameter and false + // as the third parameter. + mockFileChannel.tryLock(); + assertTrue(mockFileChannel.isTryLockCalled); + } + + /** + * @tests java.nio.channels.FileChannel#tryLock(long, long, boolean) + */ + public void test_tryLockJJZ_Closed() throws Exception { + readOnlyFileChannel.close(); + try { + readOnlyFileChannel.tryLock(0, 10, false); + fail("should throw ClosedChannelException"); + } catch (ClosedChannelException e) { + // expected + } + + writeOnlyFileChannel.close(); + try { + writeOnlyFileChannel.tryLock(0, 10, false); + fail("should throw ClosedChannelException"); + } catch (ClosedChannelException e) { + // expected + } + + readWriteFileChannel.close(); + try { + readWriteFileChannel.tryLock(0, 10, false); + fail("should throw ClosedChannelException"); + } catch (ClosedChannelException e) { + // expected + } + + // throws ClosedChannelException before IllegalArgumentException + try { + readWriteFileChannel.tryLock(-1, 0, false); + fail("should throw ClosedChannelException"); + } catch (ClosedChannelException e) { + // expected + } + } + + /** + * @tests java.nio.channels.FileChannel#tryLock(long, long, boolean) + */ + public void test_tryLockJJZ_IllegalArgument() throws Exception { + try { + writeOnlyFileChannel.tryLock(0, -1, false); + fail("should throw IllegalArgumentException"); + } catch (IllegalArgumentException e) { + // expected + } + + try { + writeOnlyFileChannel.tryLock(-1, 0, false); + fail("should throw IllegalArgumentException"); + } catch (IllegalArgumentException e) { + // expected + } + + try { + readWriteFileChannel.tryLock(-1, -1, false); + fail("should throw IllegalArgumentException"); + } catch (IllegalArgumentException e) { + // expected + } + + try { + readWriteFileChannel.tryLock(Long.MAX_VALUE, 1, false); + fail("should throw IllegalArgumentException"); + } catch (IllegalArgumentException e) { + // expected + } + } + + /** + * @tests java.nio.channels.FileChannel#tryLock(long, long, boolean) + */ + public void test_tryLockJJZ_NonWritable() throws Exception { + try { + readOnlyFileChannel.tryLock(0, 10, false); + fail("should throw NonWritableChannelException"); + } catch (NonWritableChannelException e) { + // expected + } + + // throws NonWritableChannelException before IllegalArgumentException + try { + readOnlyFileChannel.tryLock(-1, 0, false); + fail("should throw NonWritableChannelException"); + } catch (NonWritableChannelException e) { + // expected + } + } + + /** + * @tests java.nio.channels.FileChannel#tryLock(long, long, boolean) + */ + public void test_tryLockJJZ_NonReadable() throws Exception { + try { + writeOnlyFileChannel.tryLock(0, 10, true); + fail("should throw NonReadableChannelException"); + } catch (NonReadableChannelException e) { + // expected + } + + // throws NonReadableChannelException before IllegalArgumentException + try { + writeOnlyFileChannel.tryLock(-1, 0, true); + fail("should throw NonReadableChannelException"); + } catch (NonReadableChannelException e) { + // expected + } + } + + /** + * @tests java.nio.channels.FileChannel#tryLock(long, long, boolean) + */ + public void test_tryLockJJZ_Shared() throws Exception { + final long POSITION = 100; + final long SIZE = 200; + fileLock = readOnlyFileChannel.tryLock(POSITION, SIZE, true); + assertTrue(fileLock.isValid()); + // fileLock.isShared depends on whether the underlying platform support + // shared lock, but it works on Windows & Linux. + assertTrue(fileLock.isShared()); + assertSame(readOnlyFileChannel, fileLock.channel()); + assertEquals(POSITION, fileLock.position()); + assertEquals(SIZE, fileLock.size()); + } + + /** + * @tests java.nio.channels.FileChannel#tryLock(long, long, boolean) + */ + public void test_tryLockJJZ_NotShared() throws Exception { + final long POSITION = 100; + final long SIZE = 200; + fileLock = writeOnlyFileChannel.tryLock(POSITION, SIZE, false); + assertTrue(fileLock.isValid()); + assertFalse(fileLock.isShared()); + assertSame(writeOnlyFileChannel, fileLock.channel()); + assertEquals(POSITION, fileLock.position()); + assertEquals(SIZE, fileLock.size()); + } + + /** + * @tests java.nio.channels.FileChannel#tryLock(long, long, boolean) + */ + public void test_tryLockJJZ_Long_MAX_VALUE() throws Exception { + final long POSITION = 0; + final long SIZE = Long.MAX_VALUE; + fileLock = readOnlyFileChannel.tryLock(POSITION, SIZE, true); + assertTrue(fileLock.isValid()); + assertTrue(fileLock.isShared()); + assertEquals(POSITION, fileLock.position()); + assertEquals(SIZE, fileLock.size()); + assertSame(readOnlyFileChannel, fileLock.channel()); + } + + /** + * @tests java.nio.channels.FileChannel#tryLock(long, long, boolean) + */ + public void test_tryLockJJZ_Overlapping() throws Exception { + final long POSITION = 100; + final long SIZE = 200; + fileLock = writeOnlyFileChannel.lock(POSITION, SIZE, false); + assertTrue(fileLock.isValid()); + + try { + writeOnlyFileChannel.lock(POSITION + 1, SIZE, false); + fail("should throw OverlappingFileLockException"); + } catch (OverlappingFileLockException e) { + // expected + } + } + + /** + * @tests java.nio.channels.FileChannel#tryLock(long, long, boolean) + */ + public void test_tryLockJJZ_NotOverlapping() throws Exception { + final long POSITION = 100; + final long SIZE = 200; + FileLock fileLock1 = writeOnlyFileChannel + .tryLock(POSITION, SIZE, false); + assertTrue(fileLock1.isValid()); + + FileLock fileLock2 = writeOnlyFileChannel.tryLock(POSITION + SIZE, + SIZE, false); + assertTrue(fileLock2.isValid()); + } + + /** + * @tests java.nio.channels.FileChannel#tryLock(long,long,boolean) + */ + public void test_tryLockJJZ_After_Release() throws Exception { + fileLock = writeOnlyFileChannel.tryLock(0, 10, false); + fileLock.release(); + + // after release file lock can be obtained again. + fileLock = writeOnlyFileChannel.tryLock(0, 10, false); + assertTrue(fileLock.isValid()); + } + + /** + * @tests java.nio.channels.FileChannel#read(ByteBuffer) + */ + public void test_readLByteBuffer_Null() throws Exception { + ByteBuffer readBuffer = null; + + try { + readOnlyFileChannel.read(readBuffer); + fail("should throw NullPointerException"); + } catch (NullPointerException e) { + // expected + } + + try { + readWriteFileChannel.read(readBuffer); + fail("should throw NullPointerException"); + } catch (NullPointerException e) { + // expected + } + } + + /** + * @tests java.nio.channels.FileChannel#read(ByteBuffer) + */ + public void test_readLByteBuffer_Closed() throws Exception { + ByteBuffer readBuffer = ByteBuffer.allocate(CAPACITY); + + readOnlyFileChannel.close(); + try { + readOnlyFileChannel.read(readBuffer); + fail("should throw ClosedChannelException"); + } catch (ClosedChannelException e) { + // expected + } + + writeOnlyFileChannel.close(); + try { + writeOnlyFileChannel.read(readBuffer); + fail("should throw ClosedChannelException"); + } catch (ClosedChannelException e) { + // expected + } + + readWriteFileChannel.close(); + try { + readWriteFileChannel.read(readBuffer); + fail("should throw ClosedChannelException"); + } catch (ClosedChannelException e) { + // expected + } + + // should throw ClosedChannelException first + readBuffer = null; + try { + readWriteFileChannel.read(readBuffer); + fail(); + } catch (ClosedChannelException expected) { + } catch (NullPointerException expected) { + } + } + + public void test_readLByteBuffer_WriteOnly() throws Exception { + ByteBuffer readBuffer = ByteBuffer.allocate(CAPACITY); + + try { + writeOnlyFileChannel.read(readBuffer); + fail(); + } catch (NonReadableChannelException expected) { + } + + readBuffer = null; + try { + writeOnlyFileChannel.read(readBuffer); + fail(); + } catch (NonReadableChannelException expected) { + } catch (NullPointerException expected) { + } + } + + public void test_readLByteBuffer_EmptyFile() throws Exception { + ByteBuffer readBuffer = ByteBuffer.allocate(CAPACITY); + int result = readOnlyFileChannel.read(readBuffer); + assertEquals(-1, result); + assertEquals(0, readBuffer.position()); + } + + /** + * @tests java.nio.channels.FileChannel#read(ByteBuffer) + */ + public void test_readLByteBuffer_LimitedCapacity() throws Exception { + writeDataToFile(fileOfReadOnlyFileChannel); + + ByteBuffer readBuffer = ByteBuffer.allocate(LIMITED_CAPACITY); + int result = readOnlyFileChannel.read(readBuffer); + assertEquals(LIMITED_CAPACITY, result); + assertEquals(LIMITED_CAPACITY, readBuffer.position()); + readBuffer.flip(); + for (int i = 0; i < LIMITED_CAPACITY; i++) { + assertEquals(CONTENT_AS_BYTES[i], readBuffer.get()); + } + } + + public void test_readLByteBuffer() throws Exception { + writeDataToFile(fileOfReadOnlyFileChannel); + + ByteBuffer readBuffer = ByteBuffer.allocate(CONTENT_AS_BYTES_LENGTH); + int result = readOnlyFileChannel.read(readBuffer); + assertEquals(CONTENT_AS_BYTES_LENGTH, result); + assertEquals(CONTENT_AS_BYTES_LENGTH, readBuffer.position()); + readBuffer.flip(); + for (int i = 0; i < CONTENT_AS_BYTES_LENGTH; i++) { + assertEquals(CONTENT_AS_BYTES[i], readBuffer.get()); + } + } + + public void test_readLByteBufferJ_Null() throws Exception { + try { + readOnlyFileChannel.read(null, 0); + fail(); + } catch (NullPointerException expected) { + } + + try { + readWriteFileChannel.read(null, 0); + fail(); + } catch (NullPointerException expected) { + } + } + + public void test_readLByteBufferJ_Closed() throws Exception { + ByteBuffer readBuffer = ByteBuffer.allocate(CAPACITY); + + readOnlyFileChannel.close(); + try { + readOnlyFileChannel.read(readBuffer, 0); + fail(); + } catch (ClosedChannelException expected) { + } + + readWriteFileChannel.close(); + try { + readWriteFileChannel.read(readBuffer, 0); + fail(); + } catch (ClosedChannelException expected) { + } + } + + public void test_readLByteBufferJ_IllegalArgument() throws Exception { + ByteBuffer readBuffer = ByteBuffer.allocate(CAPACITY); + + try { + readOnlyFileChannel.read(readBuffer, -1); + fail(); + } catch (IllegalArgumentException expected) { + } + + try { + writeOnlyFileChannel.read(readBuffer, -1); + fail(); + } catch (IllegalArgumentException expected) { + } + + try { + readWriteFileChannel.read(readBuffer, -1); + fail(); + } catch (IllegalArgumentException expected) { + } + } + + public void test_readLByteBufferJ_WriteOnly() throws Exception { + ByteBuffer readBuffer = ByteBuffer.allocate(CAPACITY); + + try { + writeOnlyFileChannel.read(readBuffer, 0); + fail(); + } catch (NonReadableChannelException expected) { + } + } + + public void test_readLByteBufferJ_Emptyfile() throws Exception { + ByteBuffer readBuffer = ByteBuffer.allocate(CAPACITY); + int result = readOnlyFileChannel.read(readBuffer, 0); + assertEquals(-1, result); + assertEquals(0, readBuffer.position()); + } + + public void test_readLByteBufferJ_Position_BeyondFileLimit() throws Exception { + writeDataToFile(fileOfReadOnlyFileChannel); + + ByteBuffer readBuffer = ByteBuffer.allocate(CAPACITY); + int result = readOnlyFileChannel.read(readBuffer, + CONTENT_AS_BYTES.length); + assertEquals(-1, result); + assertEquals(0, readBuffer.position()); + } + + public void test_readLByteBufferJ_Position_As_Long() throws Exception { + ByteBuffer readBuffer = ByteBuffer.allocate(CAPACITY); + try { + readOnlyFileChannel.read(readBuffer, Long.MAX_VALUE); + } catch (IOException expected) { + } + } + + public void test_readLByteBufferJ() throws Exception { + writeDataToFile(fileOfReadOnlyFileChannel); + ByteBuffer readBuffer = ByteBuffer.allocate(CAPACITY); + + final int BUFFER_POSITION = 1; + readBuffer.position(BUFFER_POSITION); + + final int POSITION = 2; + int result = readOnlyFileChannel.read(readBuffer, POSITION); + assertEquals(CONTENT_AS_BYTES_LENGTH - POSITION, result); + assertEquals(BUFFER_POSITION + result, readBuffer.position()); + + readBuffer.flip(); + readBuffer.position(BUFFER_POSITION); + for (int i = POSITION; i < CONTENT_AS_BYTES_LENGTH; i++) { + assertEquals(CONTENT_AS_BYTES[i], readBuffer.get()); + } + } + + /** + * @tests java.nio.channels.FileChannel#read(ByteBuffer[]) + */ + public void test_read$LByteBuffer() throws Exception { + // regression test for Harmony-849 + writeDataToFile(fileOfReadOnlyFileChannel); + ByteBuffer[] readBuffers = new ByteBuffer[2]; + readBuffers[0] = ByteBuffer.allocate(CAPACITY); + readBuffers[1] = ByteBuffer.allocate(CAPACITY); + + long readCount = readOnlyFileChannel.read(readBuffers); + assertEquals(CONTENT_AS_BYTES_LENGTH, readCount); + assertEquals(CONTENT_AS_BYTES_LENGTH, readBuffers[0].position()); + assertEquals(0, readBuffers[1].position()); + readBuffers[0].flip(); + for (int i = 0; i < CONTENT_AS_BYTES_LENGTH; i++) { + assertEquals(CONTENT_AS_BYTES[i], readBuffers[0].get()); + } + } + + /** + * @tests java.nio.channels.FileChannel#read(ByteBuffer[]) + */ + public void test_read$LByteBuffer_mock() throws Exception { + FileChannel mockChannel = new MockFileChannel(); + ByteBuffer[] buffers = new ByteBuffer[2]; + mockChannel.read(buffers); + // Verify that calling read(ByteBuffer[] dsts) leads to the method + // read(dsts, 0, dsts.length) + assertTrue(((MockFileChannel)mockChannel).isReadCalled); + } + + /** + * @tests java.nio.channels.FileChannel#read(ByteBuffer[], int, int) + */ + public void test_read$LByteBufferII_Null() throws Exception { + ByteBuffer[] readBuffers = null; + + try { + readOnlyFileChannel.read(readBuffers, 0, 1); + fail("should throw NullPointerException"); + } catch (NullPointerException e) { + // expected + } + + try { + readOnlyFileChannel.read(readBuffers, 1, 11); + fail("should throw NullPointerException"); + } catch (NullPointerException e) { + // expected + } + + try { + writeOnlyFileChannel.read(readBuffers, 0, 1); + fail("should throw NullPointerException"); + } catch (NullPointerException e) { + // expected + } + + try { + readWriteFileChannel.read(readBuffers, 0, 1); + fail("should throw NullPointerException"); + } catch (NullPointerException e) { + // expected + } + + // first throws NullPointerException + writeOnlyFileChannel.close(); + try { + writeOnlyFileChannel.read(readBuffers, 0, 1); + fail("should throw NullPointerException"); + } catch (NullPointerException e) { + // expected + } + } + + /** + * @tests java.nio.channels.FileChannel#read(ByteBuffer[], int, int) + */ + public void test_read$LByteBufferII_Closed() throws Exception { + ByteBuffer[] readBuffers = new ByteBuffer[2]; + readBuffers[0] = ByteBuffer.allocate(CAPACITY); + + readOnlyFileChannel.close(); + try { + readOnlyFileChannel.read(readBuffers, 0, 1); + fail("should throw ClosedChannelException"); + } catch (ClosedChannelException e) { + // expected + } + + writeOnlyFileChannel.close(); + try { + writeOnlyFileChannel.read(readBuffers, 0, 1); + fail("should throw ClosedChannelException"); + } catch (ClosedChannelException e) { + // expected + } + + readWriteFileChannel.close(); + try { + readWriteFileChannel.read(readBuffers, 0, 1); + fail("should throw ClosedChannelException"); + } catch (ClosedChannelException e) { + // expected + } + + // regression test for Harmony-902 + readBuffers[0] = null; + try { + readOnlyFileChannel.read(readBuffers, 0, 1); + fail("should throw ClosedChannelException"); + } catch (ClosedChannelException e) { + // expected + } + try { + writeOnlyFileChannel.read(readBuffers, 0, 1); + fail("should throw ClosedChannelException"); + } catch (ClosedChannelException e) { + // expected + } + try { + readWriteFileChannel.read(readBuffers, 0, 1); + fail("should throw ClosedChannelException"); + } catch (ClosedChannelException e) { + // expected + } + } + + /** + * @tests java.nio.channels.FileChannel#read(ByteBuffer[], int, int) + */ + public void test_read$LByteBufferII_WriteOnly() throws Exception { + ByteBuffer[] readBuffers = new ByteBuffer[2]; + readBuffers[0] = ByteBuffer.allocate(CAPACITY); + + try { + writeOnlyFileChannel.read(readBuffers, 0, 1); + fail("should throw NonReadableChannelException"); + } catch (NonReadableChannelException e) { + // expected + } + + // first throws NonReadableChannelException. + readBuffers[0] = null; + try { + writeOnlyFileChannel.read(readBuffers, 0, 1); + fail("should throw NonReadableChannelException"); + } catch (NonReadableChannelException e) { + // expected + } + } + + /** + * @tests java.nio.channels.FileChannel#read(ByteBuffer[], int, int) + */ + public void test_read$LByteBufferII_IndexOutOfBound() throws Exception { + ByteBuffer[] readBuffers = new ByteBuffer[2]; + readBuffers[0] = ByteBuffer.allocate(CAPACITY); + readBuffers[1] = ByteBuffer.allocate(CAPACITY); + + try { + readOnlyFileChannel.read(readBuffers, 2, 1); + fail(); + } catch (IndexOutOfBoundsException expected) { + } + + try { + readWriteFileChannel.read(null, -1, 0); + fail(); + } catch (IndexOutOfBoundsException expected) { + } catch (NullPointerException expected) { + } + + try { + writeOnlyFileChannel.read(readBuffers, 0, 3); + fail(); + } catch (IndexOutOfBoundsException expected) { + } + + try { + readWriteFileChannel.read(readBuffers, -1, 0); + fail(); + } catch (IndexOutOfBoundsException expected) { + } + + readWriteFileChannel.close(); + try { + readWriteFileChannel.read(readBuffers, 0, 3); + fail(); + } catch (IndexOutOfBoundsException expected) { + } + } + + /** + * @tests java.nio.channels.FileChannel#read(ByteBuffer[], int, int) + */ + public void test_read$LByteBufferII_EmptyFile() throws Exception { + ByteBuffer[] readBuffers = new ByteBuffer[2]; + readBuffers[0] = ByteBuffer.allocate(CAPACITY); + readBuffers[1] = ByteBuffer.allocate(CAPACITY); + long result = readOnlyFileChannel.read(readBuffers, 0, 2); + assertEquals(-1, result); + assertEquals(0, readBuffers[0].position()); + assertEquals(0, readBuffers[1].position()); + } + + /** + * @tests java.nio.channels.FileChannel#read(ByteBuffer[], int, int) + */ + public void test_read$LByteBufferII_EmptyBuffers() throws Exception { + ByteBuffer[] readBuffers = new ByteBuffer[2]; + try { + readOnlyFileChannel.read(readBuffers, 0, 2); + } catch (NullPointerException e) { + // expected + } + + writeDataToFile(fileOfReadOnlyFileChannel); + readBuffers[0] = ByteBuffer.allocate(CAPACITY); + try { + readOnlyFileChannel.read(readBuffers, 0, 2); + } catch (NullPointerException e) { + // expected + } + + long result = readOnlyFileChannel.read(readBuffers, 0, 1); + assertEquals(CONTENT_AS_BYTES_LENGTH, result); + } + + /** + * @tests java.nio.channels.FileChannel#read(ByteBuffer[], int, int) + */ + public void test_read$LByteBufferII_EmptyFile_EmptyBuffers() + throws Exception { + ByteBuffer[] readBuffers = new ByteBuffer[2]; + // will not throw NullPointerException + long result = readOnlyFileChannel.read(readBuffers, 0, 0); + assertEquals(0, result); + } + + /** + * @tests java.nio.channels.FileChannel#read(ByteBuffer[], int, int) + */ + public void test_read$LByteBufferII_Length_Zero() throws Exception { + writeDataToFile(fileOfReadOnlyFileChannel); + ByteBuffer[] readBuffers = new ByteBuffer[2]; + readBuffers[0] = ByteBuffer.allocate(LIMITED_CAPACITY); + readBuffers[1] = ByteBuffer.allocate(LIMITED_CAPACITY); + long result = readOnlyFileChannel.read(readBuffers, 1, 0); + assertEquals(0, result); + } + + /** + * @tests java.nio.channels.FileChannel#read(ByteBuffer[], int, int) + */ + public void test_read$LByteBufferII_LimitedCapacity() throws Exception { + writeDataToFile(fileOfReadOnlyFileChannel); + ByteBuffer[] readBuffers = new ByteBuffer[2]; + readBuffers[0] = ByteBuffer.allocate(LIMITED_CAPACITY); + readBuffers[1] = ByteBuffer.allocate(LIMITED_CAPACITY); + + // reads to the second buffer + long result = readOnlyFileChannel.read(readBuffers, 1, 1); + assertEquals(LIMITED_CAPACITY, result); + assertEquals(0, readBuffers[0].position()); + assertEquals(LIMITED_CAPACITY, readBuffers[1].position()); + + readBuffers[1].flip(); + for (int i = 0; i < LIMITED_CAPACITY; i++) { + assertEquals(CONTENT_AS_BYTES[i], readBuffers[1].get()); + } + } + + /** + * @tests java.nio.channels.FileChannel#read(ByteBuffer[], int, int) + */ + public void test_read$LByteBufferII() throws Exception { + writeDataToFile(fileOfReadOnlyFileChannel); + ByteBuffer[] readBuffers = new ByteBuffer[2]; + readBuffers[0] = ByteBuffer.allocate(CAPACITY); + readBuffers[1] = ByteBuffer.allocate(CAPACITY); + + // writes to the second buffer + assertEquals(CONTENT_AS_BYTES_LENGTH, readOnlyFileChannel.read( + readBuffers, 1, 1)); + assertEquals(0, readBuffers[0].position()); + assertEquals(CONTENT_AS_BYTES_LENGTH, readBuffers[1].position()); + + readBuffers[1].flip(); + for (int i = 0; i < CONTENT_AS_BYTES_LENGTH; i++) { + assertEquals(CONTENT_AS_BYTES[i], readBuffers[1].get()); + } + } + + /** + * @tests java.nio.channels.FileChannel#isOpen() + */ + public void test_isOpen() throws Exception { + // Regression for HARMONY-40 + File logFile = File.createTempFile("out", "tmp"); + logFile.deleteOnExit(); + FileOutputStream out = new FileOutputStream(logFile, true); + FileChannel channel = out.getChannel(); + out.write(1); + out.close(); + assertFalse("Assert 0: Channel is still open", channel.isOpen()); + } + + /** + * @tests java.nio.channels.FileChannel#position() + */ + public void test_position_append() throws Exception { + // Regression test for Harmony-508 + File tmpfile = File.createTempFile("FileOutputStream", "tmp"); + tmpfile.deleteOnExit(); + FileOutputStream fos = new FileOutputStream(tmpfile); + byte[] b = new byte[10]; + for (int i = 0; i < b.length; i++) { + b[i] = (byte) i; + } + fos.write(b); + 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()); + } + + + /** + * @tests java.nio.channels.FileChannel#map(MapMode,long,long) + */ + public void test_map_AbnormalMode() throws IOException { + try { + writeOnlyFileChannel.map(MapMode.READ_ONLY, 0, CONTENT_LENGTH); + fail("should throw NonReadableChannelException."); + } catch (NonReadableChannelException ex) { + // expected; + } + try { + writeOnlyFileChannel.map(MapMode.READ_WRITE, 0, CONTENT_LENGTH); + fail("should throw NonReadableChannelException."); + } catch (NonReadableChannelException ex) { + // expected; + } + try { + writeOnlyFileChannel.map(MapMode.PRIVATE, 0, CONTENT_LENGTH); + fail("should throw NonReadableChannelException."); + } catch (NonReadableChannelException ex) { + // expected; + } + writeOnlyFileChannel.close(); + try { + writeOnlyFileChannel.map(MapMode.READ_WRITE, 0, -1); + fail("should throw ClosedChannelException."); + } catch (ClosedChannelException ex) { + // expected; + } + + try { + readOnlyFileChannel.map(MapMode.READ_WRITE, 0, CONTENT_LENGTH); + fail("should throw NonWritableChannelException ."); + } catch (NonWritableChannelException ex) { + // expected; + } + try { + readOnlyFileChannel.map(MapMode.PRIVATE, 0, CONTENT_LENGTH); + fail("should throw NonWritableChannelException ."); + } catch (NonWritableChannelException ex) { + // expected; + } + try { + readOnlyFileChannel.map(MapMode.READ_WRITE, -1, CONTENT_LENGTH); + fail("should throw IAE."); + } catch (IllegalArgumentException ex) { + // expected; + } + try { + readOnlyFileChannel.map(MapMode.READ_WRITE, 0, -1); + fail("should throw IAE."); + } catch (IllegalArgumentException ex) { + // expected; + } + + try { + readOnlyFileChannel.map(MapMode.READ_ONLY, 0, CONTENT_LENGTH + 1); + fail(); + } catch (NonWritableChannelException expected) { + } catch (IOException expected) { + } + try { + readOnlyFileChannel.map(MapMode.READ_ONLY, 2, CONTENT_LENGTH - 1); + fail(); + } catch (NonWritableChannelException expected) { + } catch (IOException expected) { + } + + readOnlyFileChannel.close(); + try { + readOnlyFileChannel.map(MapMode.READ_WRITE, 0, -1); + fail("should throw ClosedChannelException."); + } catch (ClosedChannelException ex) { + // expected; + } + try { + readOnlyFileChannel.map(MapMode.READ_ONLY, 2, CONTENT_LENGTH - 1); + fail("should throw IOException."); + } catch (IOException ex) { + // expected; + } + + readWriteFileChannel.close(); + try { + readWriteFileChannel.map(MapMode.READ_WRITE, 0, -1); + fail("should throw ClosedChannelException."); + } catch (ClosedChannelException ex) { + // expected; + } + } + + /** + * @tests java.nio.channels.FileChannel#map(MapMode,long,long) + */ + public void test_map_ReadOnly_CloseChannel() throws IOException { + // close channel has no effect on map if mapped + assertEquals(0, readWriteFileChannel.size()); + MappedByteBuffer mapped = readWriteFileChannel.map(MapMode.READ_ONLY, + 0, CONTENT_LENGTH); + assertEquals(CONTENT_LENGTH, readWriteFileChannel.size()); + readOnlyFileChannel.close(); + assertEquals(CONTENT_LENGTH, mapped.limit()); + } + + /** + * @tests java.nio.channels.FileChannel#map(MapMode,long,long) + */ + public void test_map_Private_CloseChannel() throws IOException { + MappedByteBuffer mapped = readWriteFileChannel.map(MapMode.PRIVATE, 0, + CONTENT_LENGTH); + readWriteFileChannel.close(); + mapped.put(TEST_BYTES); + assertEquals(CONTENT_LENGTH, mapped.limit()); + assertEquals("test".length(), mapped.position()); + } + + /** + * @tests java.nio.channels.FileChannel#map(MapMode,long,long) + */ + public void test_map_ReadOnly() throws IOException { + MappedByteBuffer mapped = null; + // try put something to readonly map + writeDataToFile(fileOfReadOnlyFileChannel); + mapped = readOnlyFileChannel.map(MapMode.READ_ONLY, 0, CONTENT_LENGTH); + try { + mapped.put(TEST_BYTES); + fail("should throw ReadOnlyBufferException."); + } catch (ReadOnlyBufferException ex) { + // expected; + } + assertEquals(CONTENT_LENGTH, mapped.limit()); + assertEquals(CONTENT_LENGTH, mapped.capacity()); + assertEquals(0, mapped.position()); + + // try to get a readonly map from read/write channel + writeDataToFile(fileOfReadWriteFileChannel); + mapped = readWriteFileChannel.map(MapMode.READ_ONLY, 0, CONTENT + .length()); + assertEquals(CONTENT_LENGTH, mapped.limit()); + assertEquals(CONTENT_LENGTH, mapped.capacity()); + assertEquals(0, mapped.position()); + + // map not change channel's position + assertEquals(0, readOnlyFileChannel.position()); + assertEquals(0, readWriteFileChannel.position()); + } + + /** + * @tests java.nio.channels.FileChannel#map(MapMode,long,long) + */ + public void test_map_ReadOnly_NonZeroPosition() throws IOException { + this.writeDataToFile(fileOfReadOnlyFileChannel); + MappedByteBuffer mapped = readOnlyFileChannel.map(MapMode.READ_ONLY, + 10, CONTENT_LENGTH - 10); + assertEquals(CONTENT_LENGTH - 10, mapped.limit()); + assertEquals(CONTENT_LENGTH - 10, mapped.capacity()); + assertEquals(0, mapped.position()); + } + + /** + * @tests java.nio.channels.FileChannel#map(MapMode,long,long) + */ + public void test_map_Private() throws IOException { + this.writeDataToFile(fileOfReadWriteFileChannel); + MappedByteBuffer mapped = readWriteFileChannel.map(MapMode.PRIVATE, 0, + CONTENT_LENGTH); + assertEquals(CONTENT_LENGTH, mapped.limit()); + // test copy on write if private + ByteBuffer returnByPut = mapped.put(TEST_BYTES); + assertSame(returnByPut, mapped); + ByteBuffer checkBuffer = ByteBuffer.allocate(CONTENT_LENGTH); + mapped.force(); + readWriteFileChannel.read(checkBuffer); + assertEquals(CONTENT, new String(checkBuffer.array(), "iso8859-1")); + + // test overflow + try { + mapped.put(("test" + CONTENT).getBytes("iso8859-1")); + fail("should throw BufferOverflowException."); + } catch (BufferOverflowException ex) { + // expected; + } + } + + /** + * @tests java.nio.channels.FileChannel#map(MapMode,long,long) + */ + public void test_map_Private_NonZeroPosition() throws IOException { + MappedByteBuffer mapped = readWriteFileChannel.map(MapMode.PRIVATE, 10, + CONTENT_LENGTH - 10); + assertEquals(CONTENT_LENGTH - 10, mapped.limit()); + assertEquals(CONTENT_LENGTH - 10, mapped.capacity()); + assertEquals(0, mapped.position()); + } + + /** + * @tests java.nio.channels.FileChannel#map(MapMode,long,long) + */ + public void test_map_ReadWrite() throws IOException { + MappedByteBuffer mapped = null; + writeDataToFile(fileOfReadWriteFileChannel); + mapped = readWriteFileChannel.map(MapMode.READ_WRITE, 0, CONTENT + .length()); + + // put something will change its channel + ByteBuffer returnByPut = mapped.put(TEST_BYTES); + assertSame(returnByPut, mapped); + String checkString = "test" + CONTENT.substring(4); + ByteBuffer checkBuffer = ByteBuffer.allocate(CONTENT_LENGTH); + mapped.force(); + readWriteFileChannel.position(0); + readWriteFileChannel.read(checkBuffer); + assertEquals(checkString, new String(checkBuffer.array(), "iso8859-1")); + + try { + mapped.put(("test" + CONTENT).getBytes("iso8859-1")); + fail("should throw BufferOverflowException."); + } catch (BufferOverflowException ex) { + // expected; + } + } + + /** + * @tests java.nio.channels.FileChannel#map(MapMode,long,long) + */ + public void test_map_ReadWrite_NonZeroPosition() throws IOException { + // test position non-zero + writeDataToFile(fileOfReadWriteFileChannel); + MappedByteBuffer mapped = readWriteFileChannel.map(MapMode.READ_WRITE, + 10, CONTENT_LENGTH - 10); + assertEquals(CONTENT_LENGTH - 10, mapped.limit()); + assertEquals(CONTENT.length() - 10, mapped.capacity()); + assertEquals(0, mapped.position()); + mapped.put(TEST_BYTES); + ByteBuffer checkBuffer = ByteBuffer.allocate(CONTENT_LENGTH); + readWriteFileChannel.read(checkBuffer); + String expected = CONTENT.substring(0, 10) + "test" + + CONTENT.substring(10 + "test".length()); + assertEquals(expected, new String(checkBuffer.array(), "iso8859-1")); + } + + /** + * Tests map() method for the value of positions exceeding memory + * page size and allocation granularity size. + * + * @tests java.nio.channels.FileChannel#map(MapMode,long,long) + */ + public void test_map_LargePosition() throws IOException { + // Regression test for HARMONY-3085 + int[] sizes = { + 4096, // 4K size (normal page size for Linux & Windows) + 65536, // 64K size (alocation granularity size for Windows) + }; + final int CONTENT_LEN = 10; + + for (int i = 0; i < sizes.length; ++i) { + // reset the file and the channel for the iterations + // (for the first iteration it was done by setUp() + if (i > 0 ) { + fileOfReadOnlyFileChannel = File.createTempFile( + "File_of_readOnlyFileChannel", "tmp"); + fileOfReadOnlyFileChannel.deleteOnExit(); + readOnlyFileChannel = new FileInputStream(fileOfReadOnlyFileChannel) + .getChannel(); + } + + writeLargeDataToFile(fileOfReadOnlyFileChannel, sizes[i] + 2 * CONTENT_LEN); + MappedByteBuffer mapped = readOnlyFileChannel.map(MapMode.READ_ONLY, + sizes[i], CONTENT_LEN); + assertEquals("Incorrectly mapped file channel for " + sizes[i] + + " position (capacity)", CONTENT_LEN, mapped.capacity()); + assertEquals("Incorrectly mapped file channel for " + sizes[i] + + " position (limit)", CONTENT_LEN, mapped.limit()); + assertEquals("Incorrectly mapped file channel for " + sizes[i] + + " position (position)", 0, mapped.position()); + + // map not change channel's position + assertEquals(0, readOnlyFileChannel.position()); + + // Close the file and the channel before the next iteration + readOnlyFileChannel.close(); + fileOfReadOnlyFileChannel.delete(); + } + } + + /** + * @tests java.nio.channels.FileChannel#write(ByteBuffer) + */ + public void test_writeLByteBuffer_Null() throws Exception { + ByteBuffer writeBuffer = null; + + try { + writeOnlyFileChannel.write(writeBuffer); + fail("should throw NullPointerException"); + } catch (NullPointerException e) { + // expected + } + + try { + readWriteFileChannel.write(writeBuffer); + fail("should throw NullPointerException"); + } catch (NullPointerException e) { + // expected + } + } + + /** + * @tests java.nio.channels.FileChannel#write(ByteBuffer) + */ + public void test_writeLByteBuffer_Closed() throws Exception { + ByteBuffer writeBuffer = ByteBuffer.allocate(CAPACITY); + + readOnlyFileChannel.close(); + try { + readOnlyFileChannel.write(writeBuffer); + fail("should throw ClosedChannelException"); + } catch (ClosedChannelException e) { + // expected + } + + writeOnlyFileChannel.close(); + try { + writeOnlyFileChannel.write(writeBuffer); + fail("should throw ClosedChannelException"); + } catch (ClosedChannelException e) { + // expected + } + + readWriteFileChannel.close(); + try { + readWriteFileChannel.write(writeBuffer); + fail(); + } catch (ClosedChannelException expected) { + } + + writeBuffer = null; + try { + readWriteFileChannel.read(writeBuffer); + fail(); + } catch (NullPointerException expected) { + } catch (ClosedChannelException expected) { + } + } + + /** + * @tests java.nio.channels.FileChannel#write(ByteBuffer) + */ + public void test_writeLByteBuffer_ReadOnly() throws Exception { + ByteBuffer writeBuffer = ByteBuffer.allocate(CAPACITY); + + try { + readOnlyFileChannel.write(writeBuffer); + fail("should throw NonWritableChannelException"); + } catch (NonWritableChannelException e) { + // expected + } + + // first throws NonWriteableChannelException + writeBuffer = null; + try { + readOnlyFileChannel.write(writeBuffer); + fail("should throw NonWritableChannelException"); + } catch (NonWritableChannelException e) { + // expected + } + } + + /** + * @tests java.nio.channels.FileChannel#write(ByteBuffer) + */ + public void test_writeLByteBuffer() throws Exception { + ByteBuffer writeBuffer = ByteBuffer.wrap(CONTENT_AS_BYTES); + + int result = writeOnlyFileChannel.write(writeBuffer); + assertEquals(CONTENT_AS_BYTES_LENGTH, result); + assertEquals(CONTENT_AS_BYTES_LENGTH, writeBuffer.position()); + writeOnlyFileChannel.close(); + + assertEquals(CONTENT_AS_BYTES_LENGTH, fileOfWriteOnlyFileChannel + .length()); + + fis = new FileInputStream(fileOfWriteOnlyFileChannel); + byte[] inputBuffer = new byte[CONTENT_AS_BYTES_LENGTH]; + fis.read(inputBuffer); + assertTrue(Arrays.equals(CONTENT_AS_BYTES, inputBuffer)); + } + + /** + * @tests java.nio.channels.FileChannel#write(ByteBuffer) + */ + public void test_writeLByteBuffer_positioned() throws Exception { + final int pos = 5; + ByteBuffer writeBuffer = ByteBuffer.wrap(CONTENT_AS_BYTES); + writeBuffer.position(pos); + int result = writeOnlyFileChannel.write(writeBuffer); + assertEquals(CONTENT_AS_BYTES_LENGTH - pos, result); + assertEquals(CONTENT_AS_BYTES_LENGTH, writeBuffer.position()); + writeOnlyFileChannel.close(); + + assertEquals(CONTENT_AS_BYTES_LENGTH - pos, fileOfWriteOnlyFileChannel + .length()); + + fis = new FileInputStream(fileOfWriteOnlyFileChannel); + byte[] inputBuffer = new byte[CONTENT_AS_BYTES_LENGTH - pos]; + fis.read(inputBuffer); + String test = CONTENT.substring(pos); + assertTrue(Arrays.equals(test.getBytes("iso8859-1"), inputBuffer)); + } + + public void test_writeLByteBufferJ_Null() throws Exception { + try { + readWriteFileChannel.write(null, 0); + fail(); + } catch (NullPointerException expected) { + } catch (NonWritableChannelException expected) { + } + + try { + writeOnlyFileChannel.write(null, 0); + fail(); + } catch (NullPointerException expected) { + } + + try { + readWriteFileChannel.write(null, 0); + fail(); + } catch (NullPointerException expected) { + } + } + + public void test_writeLByteBufferJ_Closed() throws Exception { + ByteBuffer writeBuffer = ByteBuffer.allocate(CAPACITY); + + writeOnlyFileChannel.close(); + try { + writeOnlyFileChannel.write(writeBuffer, 0); + fail(); + } catch (ClosedChannelException expected) { + } + + readWriteFileChannel.close(); + try { + readWriteFileChannel.write(writeBuffer, 0); + fail(); + } catch (ClosedChannelException expected) { + } + } + + public void test_writeLByteBufferJ_ReadOnly() throws Exception { + ByteBuffer writeBuffer = ByteBuffer.allocate(CAPACITY); + try { + readOnlyFileChannel.write(writeBuffer, 10); + fail(); + } catch (NonWritableChannelException expected) { + } + } + + public void test_writeLByteBufferJ_IllegalArgument() throws Exception { + ByteBuffer writeBuffer = ByteBuffer.allocate(CAPACITY); + + try { + readOnlyFileChannel.write(writeBuffer, -1); + fail(); + } catch (IllegalArgumentException expected) { + } + + try { + writeOnlyFileChannel.write(writeBuffer, -1); + fail(); + } catch (IllegalArgumentException expected) { + } + + try { + readWriteFileChannel.write(writeBuffer, -1); + fail(); + } catch (IllegalArgumentException expected) { + } + } + + /** + * @tests java.nio.channels.FileChannel#write(ByteBuffer,long) + */ + public void test_writeLByteBufferJ() throws Exception { + writeDataToFile(fileOfWriteOnlyFileChannel); + + final int POSITION = 4; + ByteBuffer writeBuffer = ByteBuffer.wrap(CONTENT_AS_BYTES); + int result = writeOnlyFileChannel.write(writeBuffer, POSITION); + assertEquals(CONTENT_AS_BYTES_LENGTH, result); + assertEquals(CONTENT_AS_BYTES_LENGTH, writeBuffer.position()); + writeOnlyFileChannel.close(); + + assertEquals(POSITION + CONTENT_AS_BYTES_LENGTH, + fileOfWriteOnlyFileChannel.length()); + + fis = new FileInputStream(fileOfWriteOnlyFileChannel); + byte[] inputBuffer = new byte[POSITION + CONTENT_AS_BYTES_LENGTH]; + fis.read(inputBuffer); + byte[] expectedResult = new byte[POSITION + CONTENT_AS_BYTES_LENGTH]; + System.arraycopy(CONTENT_AS_BYTES, 0, expectedResult, 0, POSITION); + System.arraycopy(CONTENT_AS_BYTES, 0, expectedResult, POSITION, + CONTENT_AS_BYTES_LENGTH); + assertTrue(Arrays.equals(expectedResult, inputBuffer)); + } + + /** + * @tests java.nio.channels.FileChannel#write(ByteBuffer[]) + */ + public void test_write$LByteBuffer() throws Exception { + ByteBuffer[] writeBuffers = new ByteBuffer[2]; + MockFileChannel mockFileChannel = new MockFileChannel(); + mockFileChannel.write(writeBuffers); + // verify that calling write(ByteBuffer[] srcs) leads to the method + // write(srcs, 0, srcs.length) + assertTrue(mockFileChannel.isWriteCalled); + } + + /** + * @tests java.nio.channels.FileChannel#write(ByteBuffer[],int,int) + */ + public void test_write$LByteBufferII_Null() throws Exception { + ByteBuffer[] writeBuffers = null; + + try { + readOnlyFileChannel.write(writeBuffers, 1, 2); + fail("should throw NullPointerException"); + } catch (NullPointerException e) { + // expected + } + + try { + writeOnlyFileChannel.write(writeBuffers, 1, 2); + fail("should throw NullPointerException"); + } catch (NullPointerException e) { + // expected + } + + try { + readWriteFileChannel.write(writeBuffers, 1, 2); + fail("should throw NullPointerException"); + } catch (NullPointerException e) { + // expected + } + + // first throws NullPointerException + readWriteFileChannel.close(); + try { + readWriteFileChannel.write(writeBuffers, 0, 0); + fail("should throw NullPointerException"); + } catch (NullPointerException e) { + // expected + } + } + + /** + * @tests java.nio.channels.FileChannel#write(ByteBuffer[],int,int) + */ + public void test_write$LByteBufferII_Closed() throws Exception { + ByteBuffer[] writeBuffers = new ByteBuffer[2]; + writeBuffers[0] = ByteBuffer.allocate(CAPACITY); + writeBuffers[1] = ByteBuffer.allocate(CAPACITY); + + readOnlyFileChannel.close(); + try { + readOnlyFileChannel.write(writeBuffers, 0, 2); + fail("should throw ClosedChannelException"); + } catch (ClosedChannelException e) { + // expected + } + + writeOnlyFileChannel.close(); + try { + writeOnlyFileChannel.write(writeBuffers, 0, 2); + fail("should throw ClosedChannelException"); + } catch (ClosedChannelException e) { + // expected + } + + readWriteFileChannel.close(); + try { + readWriteFileChannel.write(writeBuffers, 0, 2); + fail("should throw ClosedChannelException"); + } catch (ClosedChannelException e) { + // expected + } + + // throws ClosedChannelException first + writeBuffers[0] = null; + try { + readWriteFileChannel.write(writeBuffers, 0, 2); + fail("should throw ClosedChannelException"); + } catch (ClosedChannelException e) { + // expected + } + } + + /** + * @tests java.nio.channels.FileChannel#write(ByteBuffer[],int,int) + */ + public void test_write$LByteBufferII_ReadOnly() throws Exception { + ByteBuffer[] writeBuffers = new ByteBuffer[2]; + writeBuffers[0] = ByteBuffer.allocate(CAPACITY); + writeBuffers[1] = ByteBuffer.allocate(CAPACITY); + + try { + readOnlyFileChannel.write(writeBuffers, 0, 2); + fail(); + } catch (NonWritableChannelException e) { + } + + try { + readOnlyFileChannel.write(writeBuffers, 0, -1); + fail(); + } catch (IndexOutOfBoundsException expected) { + } + + writeBuffers = null; + try { + readOnlyFileChannel.write(writeBuffers, 0, 1); + fail(); + } catch (NullPointerException expected) { + } + + readOnlyFileChannel.close(); + } + + /** + * @tests java.nio.channels.FileChannel#write(ByteBuffer[],int,int) + */ + public void test_write$LByteBufferII_EmptyBuffers() throws Exception { + ByteBuffer[] writeBuffers = new ByteBuffer[2]; + try { + writeOnlyFileChannel.write(writeBuffers, 0, 2); + fail("should throw NullPointerException"); + } catch (NullPointerException e) { + // expected + } + + try { + readWriteFileChannel.write(writeBuffers, 0, 2); + fail("should throw NullPointerException"); + } catch (NullPointerException e) { + // expected + } + } + + /** + * @tests java.nio.channels.FileChannel#write(ByteBuffer[],int,int) + */ + public void test_write$LByteBufferII() throws Exception { + ByteBuffer[] writeBuffers = new ByteBuffer[2]; + writeBuffers[0] = ByteBuffer.wrap(CONTENT_AS_BYTES); + writeBuffers[1] = ByteBuffer.wrap(CONTENT_AS_BYTES); + + long result = writeOnlyFileChannel.write(writeBuffers, 0, 2); + assertEquals(CONTENT_AS_BYTES_LENGTH * 2, result); + assertEquals(CONTENT_AS_BYTES_LENGTH, writeBuffers[0].position()); + assertEquals(CONTENT_AS_BYTES_LENGTH, writeBuffers[1].position()); + writeOnlyFileChannel.close(); + + assertEquals(CONTENT_AS_BYTES_LENGTH * 2, fileOfWriteOnlyFileChannel + .length()); + + fis = new FileInputStream(fileOfWriteOnlyFileChannel); + byte[] inputBuffer = new byte[CONTENT_AS_BYTES_LENGTH]; + fis.read(inputBuffer); + byte[] expectedResult = new byte[CONTENT_AS_BYTES_LENGTH * 2]; + System.arraycopy(CONTENT_AS_BYTES, 0, expectedResult, 0, + CONTENT_AS_BYTES_LENGTH); + System.arraycopy(CONTENT_AS_BYTES, 0, expectedResult, + CONTENT_AS_BYTES_LENGTH, CONTENT_AS_BYTES_LENGTH); + assertTrue(Arrays.equals(CONTENT_AS_BYTES, inputBuffer)); + } + + /** + * @tests java.nio.channels.FileChannel#transferFrom(ReadableByteChannel,long,long) + */ + public void test_transferFromLReadableByteChannelJJ_Closed() + throws Exception { + readByteChannel = DatagramChannel.open(); + readOnlyFileChannel.close(); + try { + readOnlyFileChannel.transferFrom(readByteChannel, 0, 0); + fail("should throw ClosedChannelException."); + } catch (ClosedChannelException e) { + // expected + } + + writeOnlyFileChannel.close(); + try { + writeOnlyFileChannel.transferFrom(readByteChannel, 0, 10); + fail("should throw ClosedChannelException."); + } catch (ClosedChannelException e) { + // expected + } + + readWriteFileChannel.close(); + try { + readWriteFileChannel.transferFrom(readByteChannel, 0, 0); + fail("should throw ClosedChannelException."); + } catch (ClosedChannelException e) { + // expected + } + + // should throw ClosedChannelException first. + try { + readWriteFileChannel.transferFrom(readByteChannel, 0, -1); + fail("should throw ClosedChannelException."); + } catch (ClosedChannelException e) { + // expected + } + } + + /** + * @tests java.nio.channels.FileChannel#transferFrom(ReadableByteChannel,long,long) + */ + public void test_transferFromLReadableByteChannelJJ_SourceClosed() + throws Exception { + readByteChannel = DatagramChannel.open(); + readByteChannel.close(); + + try { + readOnlyFileChannel.transferFrom(readByteChannel, 0, 10); + fail("should throw ClosedChannelException."); + } catch (ClosedChannelException e) { + // expected + } + + try { + writeOnlyFileChannel.transferFrom(readByteChannel, 0, 10); + fail("should throw ClosedChannelException."); + } catch (ClosedChannelException e) { + // expected + } + + try { + readWriteFileChannel.transferFrom(readByteChannel, 0, 10); + fail("should throw ClosedChannelException."); + } catch (ClosedChannelException e) { + // expected + } + + // should throw ClosedChannelException first. + try { + readWriteFileChannel.transferFrom(readByteChannel, 0, -1); + fail("should throw ClosedChannelException."); + } catch (ClosedChannelException e) { + // expected + } + } + + /** + * @tests java.nio.channels.FileChannel#transferFrom(ReadableByteChannel,long,long) + */ + public void test_transferFromLReadableByteChannelJJ_IllegalArgument() + throws Exception { + readByteChannel = DatagramChannel.open(); + try { + writeOnlyFileChannel.transferFrom(readByteChannel, 10, -1); + fail("should throw IllegalArgumentException."); + } catch (IllegalArgumentException e) { + // expected + } + + try { + readWriteFileChannel.transferFrom(readByteChannel, -1, -10); + fail("should throw IllegalArgumentException."); + } catch (IllegalArgumentException e) { + // expected + } + } + + /** + * @tests java.nio.channels.FileChannel#transferFrom(ReadableByteChannel,long,long) + */ + public void test_transferFromLReadableByteChannelJJ_NonWritable() + throws Exception { + readByteChannel = DatagramChannel.open(); + try { + readOnlyFileChannel.transferFrom(readByteChannel, 0, 0); + fail("should throw NonWritableChannelException."); + } catch (NonWritableChannelException e) { + // expected + } + } + + /** + * @tests java.nio.channels.FileChannel#transferFrom(ReadableByteChannel,long,long) + */ + public void test_transferFromLReadableByteChannelJJ_SourceNonReadable() + throws Exception { + try { + readWriteFileChannel.transferFrom(writeOnlyFileChannel, 0, 0); + fail("should throw NonReadableChannelException."); + } catch (NonReadableChannelException e) { + // expected + } + + // not throws NonReadableChannelException first if position beyond file + // size. + readWriteFileChannel.transferFrom(writeOnlyFileChannel, 10, 10); + } + + /** + * @tests java.nio.channels.FileChannel#transferFrom(ReadableByteChannel,long,long) + */ + public void test_transferFromLReadableByteChannelJJ_PositionBeyondSize() + throws Exception { + // init data to file. + writeDataToFile(fileOfReadOnlyFileChannel); + writeDataToFile(fileOfWriteOnlyFileChannel); + + final int READONLYFILECHANNELPOSITION = 2; + readOnlyFileChannel.position(READONLYFILECHANNELPOSITION); + + final int POSITION = CONTENT_AS_BYTES_LENGTH * 2; + final int LENGTH = 5; + long result = writeOnlyFileChannel.transferFrom(readOnlyFileChannel, + POSITION, LENGTH); + assertEquals(0, result); + assertEquals(0, writeOnlyFileChannel.position()); + assertEquals(READONLYFILECHANNELPOSITION, readOnlyFileChannel + .position()); + } + + /** + * @tests java.nio.channels.FileChannel#transferFrom(ReadableByteChannel,long,long) + */ + public void test_transferFromLReadableByteChannelJJ_FileChannel() + throws Exception { + // init data to file. + writeDataToFile(fileOfReadOnlyFileChannel); + writeDataToFile(fileOfWriteOnlyFileChannel); + + final int READONLYFILECHANNELPOSITION = 2; + final int WRITEONLYFILECHANNELPOSITION = 4; + readOnlyFileChannel.position(READONLYFILECHANNELPOSITION); + writeOnlyFileChannel.position(WRITEONLYFILECHANNELPOSITION); + + final int POSITION = 3; + final int LENGTH = 5; + long result = writeOnlyFileChannel.transferFrom(readOnlyFileChannel, + POSITION, LENGTH); + assertEquals(LENGTH, result); + assertEquals(WRITEONLYFILECHANNELPOSITION, writeOnlyFileChannel + .position()); + assertEquals(READONLYFILECHANNELPOSITION + LENGTH, readOnlyFileChannel + .position()); + writeOnlyFileChannel.close(); + + final int EXPECTED_LENGTH = POSITION + LENGTH; + fis = new FileInputStream(fileOfWriteOnlyFileChannel); + byte[] resultContent = new byte[EXPECTED_LENGTH]; + fis.read(resultContent); + + byte[] expectedContent = new byte[EXPECTED_LENGTH]; + System.arraycopy(CONTENT_AS_BYTES, 0, expectedContent, 0, POSITION); + System.arraycopy(CONTENT_AS_BYTES, READONLYFILECHANNELPOSITION, + expectedContent, POSITION, LENGTH); + assertTrue(Arrays.equals(expectedContent, resultContent)); + } + + /** + * @tests java.nio.channels.FileChannel#transferFrom(ReadableByteChannel,long,long) + */ + public void test_transferFromLReadableByteChannelJJ_DatagramChannel() + throws Exception { + // connects two datagramChannels. + datagramChannelReceiver = DatagramChannel.open(); + datagramChannelReceiver.socket().bind( + new InetSocketAddress(InetAddress.getLocalHost(), 0)); + datagramChannelSender = DatagramChannel.open(); + datagramChannelSender.socket().bind( + new InetSocketAddress(InetAddress.getLocalHost(), 0)); + datagramChannelReceiver.socket().setSoTimeout(TIME_OUT); + datagramChannelReceiver.connect(datagramChannelSender.socket() + .getLocalSocketAddress()); + datagramChannelSender.socket().setSoTimeout(TIME_OUT); + ByteBuffer writeBuffer = ByteBuffer.wrap(CONTENT_AS_BYTES); + datagramChannelSender.socket().setSoTimeout(TIME_OUT); + // sends data from datagramChannelSender to datagramChannelReceiver. + datagramChannelSender.send(writeBuffer, datagramChannelReceiver + .socket().getLocalSocketAddress()); + datagramChannelReceiver.socket().setSoTimeout(TIME_OUT); + + // transfers data from datagramChannelReceiver to fileChannel. + long result = writeOnlyFileChannel.transferFrom( + datagramChannelReceiver, 0, CONTENT_AS_BYTES_LENGTH); + assertEquals(CONTENT_AS_BYTES_LENGTH, result); + assertEquals(0, writeOnlyFileChannel.position()); + writeOnlyFileChannel.close(); + + // gets content from file. + fis = new FileInputStream(fileOfWriteOnlyFileChannel); + assertEquals(CONTENT_AS_BYTES_LENGTH, fileOfWriteOnlyFileChannel + .length()); + byte[] resultContent = new byte[CONTENT_AS_BYTES_LENGTH]; + fis.read(resultContent); + + // compares contents. + assertTrue(Arrays.equals(CONTENT_AS_BYTES, resultContent)); + } + + /** + * @tests java.nio.channels.FileChannel#transferFrom(ReadableByteChannel,long,long) + */ + public void test_transferFromLReadableByteChannelJJ_SocketChannel() + throws Exception { + // connects two socketChannels. + socketChannelReceiver = SocketChannel.open(); + serverSocketChannel = ServerSocketChannel.open(); + serverSocketChannel.socket().bind( + new InetSocketAddress(InetAddress.getLocalHost(), 0)); + socketChannelReceiver.socket().setSoTimeout(TIME_OUT); + socketChannelReceiver.connect(serverSocketChannel.socket() + .getLocalSocketAddress()); + serverSocketChannel.socket().setSoTimeout(TIME_OUT); + socketChannelSender = serverSocketChannel.accept(); + socketChannelSender.socket().setSoTimeout(TIME_OUT); + + // sends data from socketChannelSender to socketChannelReceiver. + ByteBuffer writeBuffer = ByteBuffer.wrap(CONTENT_AS_BYTES); + socketChannelSender.write(writeBuffer); + + // transfers data from socketChannelReceiver to fileChannel. + long result = readWriteFileChannel.transferFrom(socketChannelReceiver, + 0, CONTENT_AS_BYTES_LENGTH); + assertEquals(CONTENT_AS_BYTES_LENGTH, result); + assertEquals(0, readWriteFileChannel.position()); + readWriteFileChannel.close(); + + // gets content from file. + fis = new FileInputStream(fileOfReadWriteFileChannel); + assertEquals(CONTENT_AS_BYTES_LENGTH, fileOfReadWriteFileChannel + .length()); + byte[] resultContent = new byte[CONTENT_AS_BYTES_LENGTH]; + fis.read(resultContent); + + // compares content. + assertTrue(Arrays.equals(CONTENT_AS_BYTES, resultContent)); + } + + /** + * @tests java.nio.channels.FileChannel#transferFrom(ReadableByteChannel,long,long) + */ + public void test_transferFromLReadableByteChannelJJ_Pipe() throws Exception { + // inits data in file. + writeDataToFile(fileOfWriteOnlyFileChannel); + + // inits pipe. + pipe = Pipe.open(); + + // writes content to pipe. + ByteBuffer writeBuffer = ByteBuffer.wrap(CONTENT_AS_BYTES); + pipe.sink().write(writeBuffer); + + // transfers data from pipe to fileChannel. + final int OFFSET = 2; + final int LENGTH = 4; + long result = writeOnlyFileChannel.transferFrom(pipe.source(), OFFSET, + LENGTH); + assertEquals(LENGTH, result); + writeOnlyFileChannel.close(); + + // gets content from file. + fis = new FileInputStream(fileOfWriteOnlyFileChannel); + byte[] resultBytes = new byte[OFFSET + LENGTH]; + fis.read(resultBytes); + + // compares content. + byte[] expectedBytes = new byte[OFFSET + LENGTH]; + System.arraycopy(CONTENT_AS_BYTES, 0, expectedBytes, 0, OFFSET); + System.arraycopy(CONTENT_AS_BYTES, 0, expectedBytes, OFFSET, LENGTH); + + assertTrue(Arrays.equals(expectedBytes, resultBytes)); + } + + /** + * @tests java.nio.channels.FileChannel#transferTo(long,long,WritableByteChannel) + */ + public void test_transferToJJLWritableByteChannel_Null() throws Exception { + writableByteChannel = null; + try { + readOnlyFileChannel.transferTo(0, 10, writableByteChannel); + fail(); + } catch (NullPointerException expected) { + } + + try { + writeOnlyFileChannel.transferTo(0, 10, writableByteChannel); + fail(); + } catch (NullPointerException expected) { + } catch (NonReadableChannelException expected) { + } + + try { + readWriteFileChannel.transferTo(0, 10, writableByteChannel); + fail(); + } catch (NullPointerException expected) { + } + + readOnlyFileChannel.close(); + try { + writeOnlyFileChannel.transferTo(-1, 0, writableByteChannel); + fail(); + } catch (NullPointerException expected) { + } catch (NonReadableChannelException expected) { + } + } + + /** + * @tests java.nio.channels.FileChannel#transferTo(long,long,WritableByteChannel) + */ + public void test_transferToJJLWritableByteChannel_Closed() throws Exception { + writableByteChannel = DatagramChannel.open(); + readOnlyFileChannel.close(); + try { + readOnlyFileChannel.transferTo(0, 10, writableByteChannel); + fail("should throw ClosedChannelException."); + } catch (ClosedChannelException e) { + // expected + } + + writeOnlyFileChannel.close(); + try { + writeOnlyFileChannel.transferTo(0, 10, writableByteChannel); + fail("should throw ClosedChannelException."); + } catch (ClosedChannelException e) { + // expected + } + + readWriteFileChannel.close(); + try { + readWriteFileChannel.transferTo(0, 10, writableByteChannel); + fail("should throw ClosedChannelException."); + } catch (ClosedChannelException e) { + // expected + } + + // should throw ClosedChannelException first. + try { + readWriteFileChannel.transferTo(0, -1, writableByteChannel); + fail("should throw ClosedChannelException."); + } catch (ClosedChannelException e) { + // expected + } + } + + public void test_transferToJJLWritableByteChannel_SourceClosed() throws Exception { + writableByteChannel = DatagramChannel.open(); + writableByteChannel.close(); + + try { + readOnlyFileChannel.transferTo(0, 10, writableByteChannel); + fail(); + } catch (ClosedChannelException expected) { + } + + try { + writeOnlyFileChannel.transferTo(0, 10, writableByteChannel); + fail(); + } catch (ClosedChannelException expected) { + } catch (NonReadableChannelException expected) { + } + + try { + readWriteFileChannel.transferTo(0, 10, writableByteChannel); + fail(); + } catch (ClosedChannelException expected) { + } + + try { + readWriteFileChannel.transferTo(0, -1, writableByteChannel); + fail(); + } catch (ClosedChannelException expected) { + } + } + + /** + * @tests java.nio.channels.FileChannel#transferTo(long,long,WritableByteChannel) + */ + public void test_transferToJJLWritableByteChannel_IllegalArgument() + throws Exception { + writableByteChannel = DatagramChannel.open(); + try { + readOnlyFileChannel.transferTo(10, -1, writableByteChannel); + fail("should throw IllegalArgumentException."); + } catch (IllegalArgumentException e) { + // expected + } + + try { + readWriteFileChannel.transferTo(-1, -10, writableByteChannel); + fail("should throw IllegalArgumentException."); + } catch (IllegalArgumentException e) { + // expected + } + } + + public void test_transferToJJLWritableByteChannel_NonReadable() throws Exception { + writableByteChannel = DatagramChannel.open(); + try { + writeOnlyFileChannel.transferTo(0, 10, writableByteChannel); + fail(); + } catch (NonReadableChannelException expected) { + } + } + + /** + * @tests java.nio.channels.FileChannel#transferTo(long,long,WritableByteChannel) + */ + public void test_transferToJJLWritableByteChannel_TargetNonWritable() + throws Exception { + try { + readWriteFileChannel.transferTo(0, 0, readOnlyFileChannel); + fail("should throw NonWritableChannelException."); + } catch (NonWritableChannelException e) { + // expected + } + + // first throws NonWritableChannelException even position out of file + // size. + try { + readWriteFileChannel.transferTo(10, 10, readOnlyFileChannel); + fail("should throw NonWritableChannelException."); + } catch (NonWritableChannelException e) { + // expected + } + + // regression test for Harmony-941 + // first throws NonWritableChannelException even arguments are illegal. + try { + readWriteFileChannel.transferTo(-1, 10, readOnlyFileChannel); + fail("should throw NonWritableChannelException."); + } catch (NonWritableChannelException e) { + // expected + } + + try { + readWriteFileChannel.transferTo(0, -1, readOnlyFileChannel); + fail("should throw NonWritableChannelException."); + } catch (NonWritableChannelException e) { + // expected + } + } + + /** + * @tests java.nio.channels.FileChannel#transferTo(long,long,WritableByteChannel) + */ + public void test_transferToJJLWritableByteChannel_PositionBeyondSize() + throws Exception { + // init data to file. + writeDataToFile(fileOfReadOnlyFileChannel); + writeDataToFile(fileOfWriteOnlyFileChannel); + + final int WRITEONLYFILECHANNELPOSITION = 2; + writeOnlyFileChannel.position(WRITEONLYFILECHANNELPOSITION); + + final int POSITION = CONTENT_AS_BYTES_LENGTH * 2; + final int LENGTH = 5; + long result = readOnlyFileChannel.transferTo(POSITION, LENGTH, + writeOnlyFileChannel); + assertEquals(0, result); + assertEquals(0, readOnlyFileChannel.position()); + assertEquals(WRITEONLYFILECHANNELPOSITION, writeOnlyFileChannel + .position()); + } + + /** + * @tests java.nio.channels.FileChannel#transferTo(long,long,WritableByteChannel) + */ + public void test_transferToJJLWritableByteChannel_FileChannel() + throws Exception { + // init data to file. + writeDataToFile(fileOfReadOnlyFileChannel); + writeDataToFile(fileOfWriteOnlyFileChannel); + + final int READONLYFILECHANNELPOSITION = 2; + final int WRITEONLYFILECHANNELPOSITION = 4; + readOnlyFileChannel.position(READONLYFILECHANNELPOSITION); + writeOnlyFileChannel.position(WRITEONLYFILECHANNELPOSITION); + + final int POSITION = 3; + final int LENGTH = 5; + long result = readOnlyFileChannel.transferTo(POSITION, LENGTH, + writeOnlyFileChannel); + assertEquals(LENGTH, result); + assertEquals(READONLYFILECHANNELPOSITION, readOnlyFileChannel + .position()); + assertEquals(WRITEONLYFILECHANNELPOSITION + LENGTH, + writeOnlyFileChannel.position()); + writeOnlyFileChannel.close(); + + final int EXPECTED_LENGTH = WRITEONLYFILECHANNELPOSITION + LENGTH; + fis = new FileInputStream(fileOfWriteOnlyFileChannel); + byte[] resultContent = new byte[EXPECTED_LENGTH]; + fis.read(resultContent); + + byte[] expectedContent = new byte[EXPECTED_LENGTH]; + System.arraycopy(CONTENT_AS_BYTES, 0, expectedContent, 0, + WRITEONLYFILECHANNELPOSITION); + System.arraycopy(CONTENT_AS_BYTES, POSITION, expectedContent, + WRITEONLYFILECHANNELPOSITION, LENGTH); + assertTrue(Arrays.equals(expectedContent, resultContent)); + } + + /** + * @tests java.nio.channels.FileChannel#transferTo(long,long,WritableByteChannel) + */ + public void test_transferToJJLWritableByteChannel_SocketChannel() + throws Exception { + // inits data into file. + writeDataToFile(fileOfReadOnlyFileChannel); + + // connects two socketChannels. + socketChannelReceiver = SocketChannel.open(); + socketChannelReceiver.socket().bind( + new InetSocketAddress(InetAddress.getLocalHost(), 0)); + serverSocketChannel = ServerSocketChannel.open(); + serverSocketChannel.socket().bind( + new InetSocketAddress(InetAddress.getLocalHost(), 0)); + socketChannelReceiver.socket().setSoTimeout(TIME_OUT); + socketChannelReceiver.connect(serverSocketChannel.socket() + .getLocalSocketAddress()); + serverSocketChannel.socket().setSoTimeout(TIME_OUT); + socketChannelSender = serverSocketChannel.accept(); + socketChannelSender.socket().setSoTimeout(TIME_OUT); + + // position here should have no effect on transferTo since it uses + // offset from file_begin + final int POSITION = 10; + readOnlyFileChannel.position(POSITION); + + // transfers data from file to socketChannelSender. + final int OFFSET = 2; + long result = readOnlyFileChannel.transferTo(OFFSET, + CONTENT_AS_BYTES_LENGTH * 2, socketChannelSender); + final int LENGTH = CONTENT_AS_BYTES_LENGTH - OFFSET; + assertEquals(LENGTH, result); + assertEquals(POSITION, readOnlyFileChannel.position()); + readOnlyFileChannel.close(); + socketChannelSender.close(); + + // gets contents from socketChannelReceiver. + ByteBuffer readBuffer = ByteBuffer.allocate(LENGTH + 1); + int totalRead = 0; + int countRead = 0; + long beginTime = System.currentTimeMillis(); + while ((countRead = socketChannelReceiver.read(readBuffer)) != -1) { + totalRead += countRead; + // TIMEOUT + if (System.currentTimeMillis() - beginTime > TIME_OUT) { + break; + } + } + assertEquals(LENGTH, totalRead); + + // compares contents. + readBuffer.flip(); + for (int i = OFFSET; i < CONTENT_AS_BYTES_LENGTH; i++) { + assertEquals(CONTENT_AS_BYTES[i], readBuffer.get()); + } + } + + /** + * @tests java.nio.channels.FileChannel#transferTo(long,long,WritableByteChannel) + */ + public void test_transferToJJLWritableByteChannel_DatagramChannel() + throws Exception { + // inits data to file. + writeDataToFile(fileOfReadOnlyFileChannel); + + // connects two datagramChannel + datagramChannelReceiver = DatagramChannel.open(); + datagramChannelReceiver.socket().bind( + new InetSocketAddress(InetAddress.getLocalHost(), 0)); + datagramChannelSender = DatagramChannel.open(); + datagramChannelSender.socket().bind( + new InetSocketAddress(InetAddress.getLocalHost(), 0)); + datagramChannelSender.socket().setSoTimeout(TIME_OUT); + datagramChannelSender.connect(datagramChannelReceiver.socket() + .getLocalSocketAddress()); + datagramChannelReceiver.socket().setSoTimeout(TIME_OUT); + datagramChannelReceiver.connect(datagramChannelSender.socket() + .getLocalSocketAddress()); + + // transfers data from fileChannel to datagramChannelSender + long result = readOnlyFileChannel.transferTo(0, + CONTENT_AS_BYTES_LENGTH, datagramChannelSender); + assertEquals(CONTENT_AS_BYTES_LENGTH, result); + assertEquals(0, readOnlyFileChannel.position()); + readOnlyFileChannel.close(); + datagramChannelSender.close(); + + // gets contents from datagramChannelReceiver + ByteBuffer readBuffer = ByteBuffer.allocate(CONTENT_AS_BYTES_LENGTH); + long beginTime = System.currentTimeMillis(); + int totalRead = 0; + while (totalRead < CONTENT_AS_BYTES_LENGTH) { + totalRead += datagramChannelReceiver.read(readBuffer); + if (System.currentTimeMillis() - beginTime > TIME_OUT) { + break; + } + } + assertEquals(CONTENT_AS_BYTES_LENGTH, totalRead); + + // compares contents. + readBuffer.flip(); + for (int i = 0; i < CONTENT_AS_BYTES_LENGTH; i++) { + assertEquals(CONTENT_AS_BYTES[i], readBuffer.get()); + } + } + + /** + * @tests java.nio.channels.FileChannel#transferTo(long,long,WritableByteChannel) + */ + public void test_transferToJJLWritableByteChannel_Pipe() throws Exception { + // inits data in file. + writeDataToFile(fileOfReadOnlyFileChannel); + + // inits pipe. + pipe = Pipe.open(); + + // transfers data from fileChannel to pipe. + final int OFFSET = 2; + final int LENGTH = 4; + long result = readOnlyFileChannel.transferTo(OFFSET, LENGTH, pipe + .sink()); + assertEquals(LENGTH, result); + assertEquals(0, readOnlyFileChannel.position()); + readOnlyFileChannel.close(); + + // gets content from pipe. + ByteBuffer readBuffer = ByteBuffer.allocate(LENGTH); + result = pipe.source().read(readBuffer); + assertEquals(LENGTH, result); + + // compares content. + readBuffer.flip(); + for (int i = OFFSET; i < OFFSET + LENGTH; i++) { + assertEquals(CONTENT_AS_BYTES[i], readBuffer.get()); + } + } + + /** + * Regression test for Harmony-3324 + * Make sure we could delete the file after we called transferTo() method. + */ + public void test_transferTo_couldDelete() throws Exception { + // init data in files + writeDataToFile(fileOfReadOnlyFileChannel); + writeDataToFile(fileOfWriteOnlyFileChannel); + + // call transferTo() method + readOnlyFileChannel.transferTo(0 , 2, writeOnlyFileChannel); + + // delete both files + readOnlyFileChannel.close(); + writeOnlyFileChannel.close(); + boolean rDel = fileOfReadOnlyFileChannel.delete(); + boolean wDel = fileOfWriteOnlyFileChannel.delete(); + + // make sure both files were deleted + assertTrue("File " + readOnlyFileChannel + " exists", rDel); + assertTrue("File " + writeOnlyFileChannel + " exists", wDel); + } + + /** + * Regression test for Harmony-3324 + * Make sure we could delete the file after we called transferFrom() method. + */ + public void test_transferFrom_couldDelete() throws Exception { + // init data in files + writeDataToFile(fileOfReadOnlyFileChannel); + writeDataToFile(fileOfWriteOnlyFileChannel); + + // call transferTo() method + writeOnlyFileChannel.transferFrom(readOnlyFileChannel, 0 , 2); + + // delete both files + readOnlyFileChannel.close(); + writeOnlyFileChannel.close(); + boolean rDel = fileOfReadOnlyFileChannel.delete(); + boolean wDel = fileOfWriteOnlyFileChannel.delete(); + + // make sure both files were deleted + assertTrue("File " + readOnlyFileChannel + " exists", rDel); + assertTrue("File " + writeOnlyFileChannel + " exists", wDel); + } + + private class MockFileChannel extends FileChannel { + + private boolean isLockCalled = false; + + private boolean isTryLockCalled = false; + + private boolean isReadCalled = false; + + private boolean isWriteCalled = false; + + public void force(boolean arg0) throws IOException { + // do nothing + } + + public FileLock lock(long position, long size, boolean shared) + throws IOException { + // verify that calling lock() leads to the method + // lock(0, Long.MAX_VALUE, false). + if (0 == position && Long.MAX_VALUE == size && false == shared) { + isLockCalled = true; + } + return null; + } + + public MappedByteBuffer map(MapMode arg0, long arg1, long arg2) + throws IOException { + return null; + } + + public long position() throws IOException { + return 0; + } + + public FileChannel position(long arg0) throws IOException { + return null; + } + + public int read(ByteBuffer arg0) throws IOException { + return 0; + } + + public int read(ByteBuffer arg0, long arg1) throws IOException { + return 0; + } + + public long read(ByteBuffer[] srcs, int offset, int length) + throws IOException { + // verify that calling read(ByteBuffer[] srcs) leads to the method + // read(srcs, 0, srcs.length) + if (0 == offset && length == srcs.length) { + isReadCalled = true; + } + return 0; + } + + public long size() throws IOException { + return 0; + } + + public long transferFrom(ReadableByteChannel arg0, long arg1, long arg2) + throws IOException { + return 0; + } + + public long transferTo(long arg0, long arg1, WritableByteChannel arg2) + throws IOException { + return 0; + } + + public FileChannel truncate(long arg0) throws IOException { + return null; + } + + public FileLock tryLock(long position, long size, boolean shared) + throws IOException { + // verify that calling tryLock() leads to the method + // tryLock(0, Long.MAX_VALUE, false). + if (0 == position && Long.MAX_VALUE == size && false == shared) { + isTryLockCalled = true; + } + return null; + } + + public int write(ByteBuffer arg0) throws IOException { + return 0; + } + + public int write(ByteBuffer arg0, long arg1) throws IOException { + return 0; + } + + public long write(ByteBuffer[] srcs, int offset, int length) + throws IOException { + // verify that calling write(ByteBuffer[] srcs) leads to the method + // write(srcs, 0, srcs.length) + if(0 == offset && length == srcs.length){ + isWriteCalled = true; + } + return 0; + } + + protected void implCloseChannel() throws IOException { + + } + } +} 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/nio/tests/java/nio/channels/FileLockInterruptionExceptionTest.java new file mode 100644 index 0000000..b60096c --- /dev/null +++ b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/FileLockInterruptionExceptionTest.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.nio.tests.java.nio.channels; + +import java.nio.channels.FileLockInterruptionException; + +import junit.framework.TestCase; + +import org.apache.harmony.testframework.serialization.SerializationTest; + +/** + * Tests for FileLockInterruptionException + */ +public class FileLockInterruptionExceptionTest extends TestCase { + + /** + * @tests {@link java.nio.channels.FileLockInterruptionException#FileLockInterruptionException()} + */ + public void test_Constructor() { + FileLockInterruptionException e = new FileLockInterruptionException(); + assertNull(e.getMessage()); + assertNull(e.getLocalizedMessage()); + assertNull(e.getCause()); + } + + /** + * @tests serialization/deserialization compatibility. + */ + public void testSerializationSelf() throws Exception { + + SerializationTest.verifySelf(new FileLockInterruptionException()); + } + + /** + * @tests serialization/deserialization compatibility with RI. + */ + public void testSerializationCompatibility() throws Exception { + + SerializationTest.verifyGolden(this, + new 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/nio/tests/java/nio/channels/FileLockTest.java new file mode 100644 index 0000000..12142e8 --- /dev/null +++ b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/FileLockTest.java @@ -0,0 +1,199 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.harmony.nio.tests.java.nio.channels; + +import java.io.File; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.RandomAccessFile; +import java.nio.channels.ClosedChannelException; +import java.nio.channels.FileChannel; +import java.nio.channels.FileLock; + +import junit.framework.TestCase; + +/** + * Tests class FileLock. + */ +public class FileLockTest extends TestCase { + + private FileChannel readWriteChannel; + + private MockFileLock mockLock; + + class MockFileLock extends FileLock { + + boolean isValid = true; + + protected MockFileLock(FileChannel channel, long position, long size, + boolean shared) { + super(channel, position, size, shared); + } + + public boolean isValid() { + return isValid; + } + + public void release() throws IOException { + isValid = false; + } + } + + protected void setUp() throws Exception { + super.setUp(); + File tempFile = File.createTempFile("testing", "tmp"); + tempFile.deleteOnExit(); + RandomAccessFile randomAccessFile = new RandomAccessFile(tempFile, "rw"); + readWriteChannel = randomAccessFile.getChannel(); + mockLock = new MockFileLock(readWriteChannel, 10, 100, false); + } + + protected void tearDown() throws IOException { + if (readWriteChannel != null) { + readWriteChannel.close(); + } + } + + /** + * @tests java.nio.channels.FileLock#FileLock(FileChannel, long, long, + * boolean) + */ + public void test_Constructor_Ljava_nio_channels_FileChannelJJZ() { + FileLock fileLock1 = new MockFileLock(null, 0, 0, false); + assertNull(fileLock1.channel()); + + try { + new MockFileLock(readWriteChannel, -1, 0, false); + fail("should throw IllegalArgumentException."); + } catch (IllegalArgumentException ex) { + // expected + } + try { + new MockFileLock(readWriteChannel, 0, -1, false); + fail("should throw IllegalArgumentException."); + } catch (IllegalArgumentException ex) { + // expected + } + // Harmony-682 regression test + try { + new MockFileLock(readWriteChannel, Long.MAX_VALUE, 1, false); + fail("should throw IllegalArgumentException."); + } catch (IllegalArgumentException ex) { + // expected + } + } + + /** + * @tests java.nio.channels.FileLock#channel() + */ + public void test_channel() { + assertSame(readWriteChannel, mockLock.channel()); + FileLock lock = new MockFileLock(null, 0, 10, true); + assertNull(lock.channel()); + } + + /** + * @tests java.nio.channels.FileLock#position() + */ + public void test_position() { + FileLock fileLock1 = new MockFileLock(readWriteChannel, 20, 100, true); + assertEquals(20, fileLock1.position()); + + final long position = ((long) Integer.MAX_VALUE + 1); + FileLock fileLock2 = new MockFileLock(readWriteChannel, position, 100, + true); + assertEquals(position, fileLock2.position()); + } + + /** + * @tests java.nio.channels.FileLock#size() + */ + public void test_size() { + FileLock fileLock1 = new MockFileLock(readWriteChannel, 20, 100, true); + assertEquals(100, fileLock1.size()); + + final long position = 0x0FFFFFFFFFFFFFFFL; + final long size = ((long) Integer.MAX_VALUE + 1); + FileLock fileLock2 = new MockFileLock(readWriteChannel, position, size, + true); + assertEquals(size, fileLock2.size()); + } + + /** + * @tests java.nio.channels.FileLock#isShared() + */ + public void test_isShared() { + assertFalse(mockLock.isShared()); + FileLock lock = new MockFileLock(null, 0, 10, true); + assertTrue(lock.isShared()); + } + + /** + * @tests java.nio.channels.FileLock#overlaps(long, long) + */ + public void test_overlaps_JJ() { + assertTrue(mockLock.overlaps(0, 11)); + assertFalse(mockLock.overlaps(0, 10)); + assertTrue(mockLock.overlaps(100, 110)); + assertTrue(mockLock.overlaps(99, 110)); + assertFalse(mockLock.overlaps(-1, 10)); + //Harmony-671 regression test + assertTrue(mockLock.overlaps(1, 120)); + assertTrue(mockLock.overlaps(20, 50)); + } + + /** + * @tests java.nio.channels.FileLock#isValid() + */ + public void test_isValid() throws IOException { + FileLock fileLock = readWriteChannel.lock(); + assertTrue(fileLock.isValid()); + fileLock.release(); + assertFalse(fileLock.isValid()); + } + + /** + * @tests java.nio.channels.FileLock#release() + */ + public void test_release() throws Exception { + File file = File.createTempFile("test", "tmp"); + file.deleteOnExit(); + FileOutputStream fout = new FileOutputStream(file); + FileChannel fileChannel = fout.getChannel(); + FileLock fileLock = fileChannel.lock(); + fileChannel.close(); + try { + fileLock.release(); + fail("should throw ClosedChannelException"); + } catch (ClosedChannelException e) { + // expected + } + + // release after release + fout = new FileOutputStream(file); + fileChannel = fout.getChannel(); + fileLock = fileChannel.lock(); + fileLock.release(); + fileChannel.close(); + try { + fileLock.release(); + fail("should throw ClosedChannelException"); + } catch (ClosedChannelException e) { + //expected + } + } +} 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/nio/tests/java/nio/channels/IllegalBlockingModeExceptionTest.java new file mode 100644 index 0000000..a8cdf83 --- /dev/null +++ b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/IllegalBlockingModeExceptionTest.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.nio.tests.java.nio.channels; + +import java.nio.channels.IllegalBlockingModeException; + +import junit.framework.TestCase; + +import org.apache.harmony.testframework.serialization.SerializationTest; + +/** + * Tests for IllegalBlockingModeException + */ +public class IllegalBlockingModeExceptionTest extends TestCase { + + /** + * @tests {@link java.nio.channels.IllegalBlockingModeException#IllegalBlockingModeException()} + */ + public void test_Constructor() { + IllegalBlockingModeException e = new IllegalBlockingModeException(); + assertNull(e.getMessage()); + assertNull(e.getLocalizedMessage()); + assertNull(e.getCause()); + } + + /** + * @tests serialization/deserialization compatibility. + */ + public void testSerializationSelf() throws Exception { + + SerializationTest.verifySelf(new IllegalBlockingModeException()); + } + + /** + * @tests serialization/deserialization compatibility with RI. + */ + public void testSerializationCompatibility() throws Exception { + + SerializationTest + .verifyGolden(this, new 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/nio/tests/java/nio/channels/IllegalSelectorExceptionTest.java new file mode 100644 index 0000000..2fa3171 --- /dev/null +++ b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/IllegalSelectorExceptionTest.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.nio.tests.java.nio.channels; + +import java.nio.channels.IllegalSelectorException; + +import junit.framework.TestCase; + +import org.apache.harmony.testframework.serialization.SerializationTest; + +/** + * Tests for IllegalSelectorException + */ +public class IllegalSelectorExceptionTest extends TestCase { + + /** + * @tests {@link java.nio.channels.IllegalSelectorException#IllegalSelectorException()} + */ + public void test_Constructor() { + IllegalSelectorException e = new IllegalSelectorException(); + assertNull(e.getMessage()); + assertNull(e.getLocalizedMessage()); + assertNull(e.getCause()); + } + + /** + * @tests serialization/deserialization compatibility. + */ + public void testSerializationSelf() throws Exception { + + SerializationTest.verifySelf(new IllegalSelectorException()); + } + + /** + * @tests serialization/deserialization compatibility with RI. + */ + public void testSerializationCompatibility() throws Exception { + + SerializationTest.verifyGolden(this, new 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/nio/tests/java/nio/channels/MapModeTest.java new file mode 100644 index 0000000..33234eb --- /dev/null +++ b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/MapModeTest.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.nio.tests.java.nio.channels; + +import java.nio.channels.FileChannel; + +import junit.framework.TestCase; + +/** + * Tests for FileChannel.MapMode + */ +public class MapModeTest extends TestCase { + + /** + * java.nio.channels.FileChannel.MapMode#PRIVATE,READONLY,READWRITE + */ + public void test_PRIVATE_READONLY_READWRITE() { + assertNotNull(FileChannel.MapMode.PRIVATE); + assertNotNull(FileChannel.MapMode.READ_ONLY); + assertNotNull(FileChannel.MapMode.READ_WRITE); + + assertFalse(FileChannel.MapMode.PRIVATE + .equals(FileChannel.MapMode.READ_ONLY)); + assertFalse(FileChannel.MapMode.PRIVATE + .equals(FileChannel.MapMode.READ_WRITE)); + assertFalse(FileChannel.MapMode.READ_ONLY + .equals(FileChannel.MapMode.READ_WRITE)); + } + + /** + * java.nio.channels.FileChannel.MapMode#toString() + */ + public void test_toString() { + assertNotNull(FileChannel.MapMode.PRIVATE.toString()); + assertNotNull(FileChannel.MapMode.READ_ONLY.toString()); + assertNotNull(FileChannel.MapMode.READ_WRITE.toString()); + } +} 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/nio/tests/java/nio/channels/MockDatagramChannel.java new file mode 100644 index 0000000..c8dc2af --- /dev/null +++ b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/MockDatagramChannel.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.nio.tests.java.nio.channels; + +import java.io.IOException; +import java.net.DatagramSocket; +import java.net.SocketAddress; +import java.nio.ByteBuffer; +import java.nio.channels.DatagramChannel; +import java.nio.channels.spi.SelectorProvider; + +class MockDatagramChannel extends DatagramChannel { + + public MockDatagramChannel(SelectorProvider arg0) { + super(arg0); + } + + public DatagramSocket socket() { + return null; + } + + public boolean isConnected() { + return false; + } + + public DatagramChannel connect(SocketAddress arg0) throws IOException { + return null; + } + + public DatagramChannel disconnect() throws IOException { + return null; + } + + public SocketAddress receive(ByteBuffer arg0) throws IOException { + return null; + } + + public int send(ByteBuffer arg0, SocketAddress arg1) throws IOException { + return 0; + } + + public int read(ByteBuffer arg0) throws IOException { + return 0; + } + + public long read(ByteBuffer[] arg0, int arg1, int arg2) throws IOException { + return 0; + } + + public int write(ByteBuffer arg0) throws IOException { + return 0; + } + + public long write(ByteBuffer[] arg0, int arg1, int arg2) throws IOException { + return 0; + } + + protected void implCloseSelectableChannel() throws IOException { + // empty + } + + protected void implConfigureBlocking(boolean arg0) throws IOException { + // empty + } + +} diff --git a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/MockServerSocketChannel.java b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/MockServerSocketChannel.java new file mode 100644 index 0000000..2058a7a --- /dev/null +++ b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/MockServerSocketChannel.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.nio.tests.java.nio.channels; + +import java.io.IOException; +import java.net.ServerSocket; +import java.nio.channels.ServerSocketChannel; +import java.nio.channels.SocketChannel; +import java.nio.channels.spi.SelectorProvider; + +class MockServerSocketChannel extends ServerSocketChannel { + + protected MockServerSocketChannel(SelectorProvider arg0) { + super(arg0); + } + + public ServerSocket socket() { + return null; + } + + public SocketChannel accept() throws IOException { + return null; + } + + protected void implCloseSelectableChannel() throws IOException { + } + + protected void implConfigureBlocking(boolean arg0) throws IOException { + } + +} diff --git a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/MockSocketChannel.java b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/MockSocketChannel.java new file mode 100644 index 0000000..9d130ca --- /dev/null +++ b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/MockSocketChannel.java @@ -0,0 +1,75 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.harmony.nio.tests.java.nio.channels; + +import java.io.IOException; +import java.net.Socket; +import java.net.SocketAddress; +import java.nio.ByteBuffer; +import java.nio.channels.SocketChannel; +import java.nio.channels.spi.SelectorProvider; + +class MockSocketChannel extends SocketChannel { + + protected MockSocketChannel(SelectorProvider arg0) { + super(arg0); + } + + public Socket socket() { + return null; + } + + public boolean isConnected() { + return false; + } + + public boolean isConnectionPending() { + return false; + } + + public boolean connect(SocketAddress arg0) throws IOException { + return false; + } + + public boolean finishConnect() throws IOException { + return false; + } + + public int read(ByteBuffer arg0) throws IOException { + return 0; + } + + public long read(ByteBuffer[] arg0, int arg1, int arg2) throws IOException { + return 0; + } + + public int write(ByteBuffer arg0) throws IOException { + return 0; + } + + public long write(ByteBuffer[] arg0, int arg1, int arg2) throws IOException { + return 0; + } + + protected void implCloseSelectableChannel() throws IOException { + } + + protected void implConfigureBlocking(boolean arg0) throws IOException { + } + +} diff --git a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/NoConnectionPendingExceptionTest.java b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/NoConnectionPendingExceptionTest.java new file mode 100644 index 0000000..2ba7ba6 --- /dev/null +++ b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/NoConnectionPendingExceptionTest.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.nio.tests.java.nio.channels; + +import java.nio.channels.NoConnectionPendingException; + +import junit.framework.TestCase; + +import org.apache.harmony.testframework.serialization.SerializationTest; + +/** + * Tests for NoConnectionPendingException + */ +public class NoConnectionPendingExceptionTest extends TestCase { + + /** + * @tests {@link java.nio.channels.NoConnectionPendingException#NoConnectionPendingException()} + */ + public void test_Constructor() { + NoConnectionPendingException e = new NoConnectionPendingException(); + assertNull(e.getMessage()); + assertNull(e.getLocalizedMessage()); + assertNull(e.getCause()); + } + + /** + * @tests serialization/deserialization compatibility. + */ + public void testSerializationSelf() throws Exception { + + SerializationTest.verifySelf(new NoConnectionPendingException()); + } + + /** + * @tests serialization/deserialization compatibility with RI. + */ + public void testSerializationCompatibility() throws Exception { + + SerializationTest + .verifyGolden(this, new 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/nio/tests/java/nio/channels/NonReadableChannelExceptionTest.java new file mode 100644 index 0000000..8c44f17 --- /dev/null +++ b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/NonReadableChannelExceptionTest.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.nio.tests.java.nio.channels; + +import java.nio.channels.NonReadableChannelException; + +import junit.framework.TestCase; + +import org.apache.harmony.testframework.serialization.SerializationTest; + +/** + * Tests for NonReadableChannelException + */ +public class NonReadableChannelExceptionTest extends TestCase { + + /** + * @tests {@link java.nio.channels.NonReadableChannelException#NonReadableChannelException()} + */ + public void test_Constructor() { + NonReadableChannelException e = new NonReadableChannelException(); + assertNull(e.getMessage()); + assertNull(e.getLocalizedMessage()); + assertNull(e.getCause()); + } + + /** + * @tests serialization/deserialization compatibility. + */ + public void testSerializationSelf() throws Exception { + + SerializationTest.verifySelf(new NonReadableChannelException()); + } + + /** + * @tests serialization/deserialization compatibility with RI. + */ + public void testSerializationCompatibility() throws Exception { + + SerializationTest.verifyGolden(this, new 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/nio/tests/java/nio/channels/NonWritableChannelExceptionTest.java new file mode 100644 index 0000000..459d85a --- /dev/null +++ b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/NonWritableChannelExceptionTest.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.nio.tests.java.nio.channels; + +import java.nio.channels.NonWritableChannelException; + +import junit.framework.TestCase; + +import org.apache.harmony.testframework.serialization.SerializationTest; + +/** + * Tests for NonWritableChannelException + */ +public class NonWritableChannelExceptionTest extends TestCase { + + /** + * @tests {@link java.nio.channels.NonWritableChannelException#NonWritableChannelException()} + */ + public void test_Constructor() { + NonWritableChannelException e = new NonWritableChannelException(); + assertNull(e.getMessage()); + assertNull(e.getLocalizedMessage()); + assertNull(e.getCause()); + } + + /** + * @tests serialization/deserialization compatibility. + */ + public void testSerializationSelf() throws Exception { + + SerializationTest.verifySelf(new NonWritableChannelException()); + } + + /** + * @tests serialization/deserialization compatibility with RI. + */ + public void testSerializationCompatibility() throws Exception { + + SerializationTest.verifyGolden(this, new 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/nio/tests/java/nio/channels/NotYetBoundExceptionTest.java new file mode 100644 index 0000000..d1c2d86 --- /dev/null +++ b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/NotYetBoundExceptionTest.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.nio.tests.java.nio.channels; + +import java.nio.channels.NotYetBoundException; + +import junit.framework.TestCase; + +import org.apache.harmony.testframework.serialization.SerializationTest; + +/** + * Tests for NotYetBoundException + */ +public class NotYetBoundExceptionTest extends TestCase { + + /** + * @tests {@link java.nio.channels.NotYetBoundException#NotYetBoundException()} + */ + public void test_Constructor() { + NotYetBoundException e = new NotYetBoundException(); + assertNull(e.getMessage()); + assertNull(e.getLocalizedMessage()); + assertNull(e.getCause()); + } + + /** + * @tests serialization/deserialization compatibility. + */ + public void testSerializationSelf() throws Exception { + + SerializationTest.verifySelf(new NotYetBoundException()); + } + + /** + * @tests serialization/deserialization compatibility with RI. + */ + public void testSerializationCompatibility() throws Exception { + + SerializationTest.verifyGolden(this, new 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/nio/tests/java/nio/channels/NotYetConnectedExceptionTest.java new file mode 100644 index 0000000..09e4c1c --- /dev/null +++ b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/NotYetConnectedExceptionTest.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.nio.tests.java.nio.channels; + +import java.nio.channels.NotYetConnectedException; + +import junit.framework.TestCase; + +import org.apache.harmony.testframework.serialization.SerializationTest; + +/** + * Tests for NotYetConnectedException + */ +public class NotYetConnectedExceptionTest extends TestCase { + + /** + * @tests {@link java.nio.channels.NotYetConnectedException#NotYetConnectedException()} + */ + public void test_Constructor() { + NotYetConnectedException e = new NotYetConnectedException(); + assertNull(e.getMessage()); + assertNull(e.getLocalizedMessage()); + assertNull(e.getCause()); + } + + /** + * @tests serialization/deserialization compatibility. + */ + public void testSerializationSelf() throws Exception { + + SerializationTest.verifySelf(new NotYetConnectedException()); + } + + /** + * @tests serialization/deserialization compatibility with RI. + */ + public void testSerializationCompatibility() throws Exception { + + SerializationTest.verifyGolden(this, new 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/nio/tests/java/nio/channels/OverlappingFileLockExceptionTest.java new file mode 100644 index 0000000..d06f807 --- /dev/null +++ b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/OverlappingFileLockExceptionTest.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.nio.tests.java.nio.channels; + +import java.nio.channels.OverlappingFileLockException; + +import junit.framework.TestCase; + +import org.apache.harmony.testframework.serialization.SerializationTest; + +/** + * Tests for OverlappingFileLockException + */ +public class OverlappingFileLockExceptionTest extends TestCase { + + /** + * @tests {@link java.nio.channels.OverlappingFileLockException#OverlappingFileLockException()} + */ + public void test_Constructor() { + OverlappingFileLockException e = new OverlappingFileLockException(); + assertNull(e.getMessage()); + assertNull(e.getLocalizedMessage()); + assertNull(e.getCause()); + } + + /** + * @tests serialization/deserialization compatibility. + */ + public void testSerializationSelf() throws Exception { + + SerializationTest.verifySelf(new OverlappingFileLockException()); + } + + /** + * @tests serialization/deserialization compatibility with RI. + */ + public void testSerializationCompatibility() throws Exception { + + SerializationTest + .verifyGolden(this, new 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/nio/tests/java/nio/channels/PipeTest.java new file mode 100644 index 0000000..53f19c4 --- /dev/null +++ b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/PipeTest.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.nio.tests.java.nio.channels; + +import java.io.IOException; +import java.net.NetPermission; +import java.nio.channels.Pipe; +import java.nio.channels.Pipe.SinkChannel; +import java.nio.channels.Pipe.SourceChannel; +import java.security.Permission; + +import junit.framework.TestCase; + +/* + * Tests for Pipe and its default implementation + */ +public class PipeTest extends TestCase { + + /** + * @tests java.nio.channels.Pipe#open() + */ + public void test_open() throws IOException{ + Pipe pipe = Pipe.open(); + assertNotNull(pipe); + } + + /** + * @tests java.nio.channels.Pipe#sink() + */ + public void test_sink() throws IOException { + Pipe pipe = Pipe.open(); + SinkChannel sink = pipe.sink(); + assertTrue(sink.isBlocking()); + } + + /** + * @tests java.nio.channels.Pipe#source() + */ + public void test_source() throws IOException { + Pipe pipe = Pipe.open(); + SourceChannel source = pipe.source(); + assertTrue(source.isBlocking()); + } + +} 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/nio/tests/java/nio/channels/SelectableChannelTest.java new file mode 100644 index 0000000..25b5f00 --- /dev/null +++ b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/SelectableChannelTest.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.nio.tests.java.nio.channels; + +import java.io.IOException; +import java.nio.channels.ClosedChannelException; +import java.nio.channels.SelectableChannel; +import java.nio.channels.SelectionKey; +import java.nio.channels.Selector; +import java.nio.channels.spi.SelectorProvider; +import junit.framework.TestCase; + +/* + * Tests for SelectableChannel + */ +public class SelectableChannelTest extends TestCase { + + /** + * @tests SelectableChannel#register(Selector, int) + */ + public void test_register_LSelectorI() throws IOException { + MockSelectableChannel msc = new MockSelectableChannel(); + // Verify that calling register(Selector, int) leads to the method + // register(Selector, int, Object) being called with a null value + // for the third argument. + msc.register(Selector.open(), SelectionKey.OP_ACCEPT); + assertTrue(msc.isCalled); + } + + private class MockSelectableChannel extends SelectableChannel { + + private boolean isCalled = false; + + public Object blockingLock() { + return null; + } + + public SelectableChannel configureBlocking(boolean block) + throws IOException { + return null; + } + + public boolean isBlocking() { + return false; + } + + public boolean isRegistered() { + return false; + } + + public SelectionKey keyFor(Selector sel) { + return null; + } + + public SelectorProvider provider() { + return null; + } + + public SelectionKey register(Selector sel, int ops, Object att) + throws ClosedChannelException { + if (null == att) { + isCalled = true; + } + return null; + } + + public int validOps() { + return 0; + } + + protected void implCloseChannel() throws IOException { + // empty + } + } +} diff --git a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/SelectionKeyTest.java b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/SelectionKeyTest.java new file mode 100644 index 0000000..ed33752 --- /dev/null +++ b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/SelectionKeyTest.java @@ -0,0 +1,321 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.harmony.nio.tests.java.nio.channels; + +import java.io.IOException; +import java.net.InetSocketAddress; +import java.net.ServerSocket; +import java.nio.channels.CancelledKeyException; +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 + */ +public class SelectionKeyTest extends TestCase { + + Selector selector; + + SocketChannel sc; + + SelectionKey selectionKey; + + private static String LOCAL_ADDR = "127.0.0.1"; + + protected void setUp() throws Exception { + super.setUp(); + selector = Selector.open(); + sc = SocketChannel.open(); + sc.configureBlocking(false); + selectionKey = sc.register(selector, SelectionKey.OP_CONNECT); + } + + protected void tearDown() throws Exception { + selectionKey.cancel(); + selectionKey = null; + selector.close(); + selector = null; + super.tearDown(); + } + + static class MockSelectionKey extends SelectionKey { + private int interestOps; + + MockSelectionKey(int ops) { + interestOps = ops; + } + + public void cancel() { + // do nothing + } + + public SelectableChannel channel() { + return null; + } + + public int interestOps() { + return 0; + } + + public SelectionKey interestOps(int operations) { + return null; + } + + public boolean isValid() { + return true; + } + + public int readyOps() { + return interestOps; + } + + public Selector selector() { + return null; + } + } + + /** + * @tests java.nio.channels.SelectionKey#attach(Object) + */ + public void test_attach() { + MockSelectionKey mockSelectionKey = new MockSelectionKey(SelectionKey.OP_ACCEPT); + // no previous, return null + Object o = new Object(); + Object check = mockSelectionKey.attach(o); + assertNull(check); + + // null parameter is ok + check = mockSelectionKey.attach(null); + assertSame(o, check); + + check = mockSelectionKey.attach(o); + assertNull(check); + } + + /** + * @tests java.nio.channels.SelectionKey#attachment() + */ + public void test_attachment() { + MockSelectionKey mockSelectionKey = new MockSelectionKey(SelectionKey.OP_ACCEPT); + assertNull(mockSelectionKey.attachment()); + Object o = new Object(); + mockSelectionKey.attach(o); + assertSame(o, mockSelectionKey.attachment()); + } + + /** + * @tests java.nio.channels.SelectionKey#channel() + */ + public void test_channel() { + assertSame(sc, selectionKey.channel()); + // can be invoked even canceled + selectionKey.cancel(); + assertSame(sc, selectionKey.channel()); + } + + /** + * @tests java.nio.channels.SelectionKey#interestOps() + */ + public void test_interestOps() { + assertEquals(SelectionKey.OP_CONNECT, selectionKey.interestOps()); + } + + /** + * @tests java.nio.channels.SelectionKey#interestOps(int) + */ + public void test_interestOpsI() { + selectionKey.interestOps(SelectionKey.OP_WRITE); + assertEquals(SelectionKey.OP_WRITE, selectionKey.interestOps()); + + try { + selectionKey.interestOps(SelectionKey.OP_ACCEPT); + fail("should throw IAE."); + } catch (IllegalArgumentException ex) { + // expected; + } + + try { + selectionKey.interestOps(~sc.validOps()); + fail("should throw IAE."); + } catch (IllegalArgumentException ex) { + // expected; + } + try { + selectionKey.interestOps(-1); + fail("should throw IAE."); + } catch (IllegalArgumentException ex) { + // expected; + } + + } + + /** + * @tests java.nio.channels.SelectionKey#isValid() + */ + public void test_isValid() { + assertTrue(selectionKey.isValid()); + } + + /** + * @tests java.nio.channels.SelectionKey#isValid() + */ + public void test_isValid_KeyCancelled() { + selectionKey.cancel(); + assertFalse(selectionKey.isValid()); + } + + /** + * @tests java.nio.channels.SelectionKey#isValid() + */ + public void test_isValid_ChannelColsed() throws IOException { + sc.close(); + assertFalse(selectionKey.isValid()); + } + + /** + * @tests java.nio.channels.SelectionKey#isValid() + */ + public void test_isValid_SelectorClosed() throws IOException { + selector.close(); + assertFalse(selectionKey.isValid()); + } + + /** + * @tests java.nio.channels.SelectionKey#isAcceptable() + */ + public void test_isAcceptable() throws IOException { + MockSelectionKey mockSelectionKey1 = new MockSelectionKey(SelectionKey.OP_ACCEPT); + assertTrue(mockSelectionKey1.isAcceptable()); + MockSelectionKey mockSelectionKey2 = new MockSelectionKey(SelectionKey.OP_CONNECT); + assertFalse(mockSelectionKey2.isAcceptable()); + } + + /** + * @tests java.nio.channels.SelectionKey#isConnectable() + */ + public void test_isConnectable() { + MockSelectionKey mockSelectionKey1 = new MockSelectionKey(SelectionKey.OP_CONNECT); + assertTrue(mockSelectionKey1.isConnectable()); + MockSelectionKey mockSelectionKey2 = new MockSelectionKey(SelectionKey.OP_ACCEPT); + assertFalse(mockSelectionKey2.isConnectable()); + } + + /** + * @tests java.nio.channels.SelectionKey#isReadable() + */ + public void test_isReadable() { + MockSelectionKey mockSelectionKey1 = new MockSelectionKey(SelectionKey.OP_READ); + assertTrue(mockSelectionKey1.isReadable()); + MockSelectionKey mockSelectionKey2 = new MockSelectionKey(SelectionKey.OP_ACCEPT); + assertFalse(mockSelectionKey2.isReadable()); + } + + /** + * @tests java.nio.channels.SelectionKey#isWritable() + */ + public void test_isWritable() { + MockSelectionKey mockSelectionKey1 = new MockSelectionKey(SelectionKey.OP_WRITE); + assertTrue(mockSelectionKey1.isWritable()); + MockSelectionKey mockSelectionKey2 = new MockSelectionKey(SelectionKey.OP_ACCEPT); + assertFalse(mockSelectionKey2.isWritable()); + } + + /** + * @tests java.nio.channels.SelectionKey#cancel() + */ + public void test_cancel() { + selectionKey.cancel(); + try { + selectionKey.isAcceptable(); + fail("should throw CancelledKeyException."); + } catch (CancelledKeyException ex) { + // expected + } + try { + selectionKey.isConnectable(); + fail("should throw CancelledKeyException."); + } catch (CancelledKeyException ex) { + // expected + } + try { + selectionKey.isReadable(); + fail("should throw CancelledKeyException."); + } catch (CancelledKeyException ex) { + // expected + } + try { + selectionKey.isWritable(); + fail("should throw CancelledKeyException."); + } catch (CancelledKeyException ex) { + // expected + } + + try { + selectionKey.readyOps(); + fail("should throw CancelledKeyException."); + } catch (CancelledKeyException ex) { + // expected + } + + try { + selectionKey.interestOps(SelectionKey.OP_CONNECT); + fail("should throw CancelledKeyException."); + } catch (CancelledKeyException ex) { + // expected + } + + try { + selectionKey.interestOps(); + fail("should throw CancelledKeyException."); + } catch (CancelledKeyException ex) { + // expected + } + } + + /** + * @tests java.nio.channels.SelectionKey#readyOps() + */ + public void test_readyOps() throws IOException { + int port = Support_PortManager.getNextPort(); + ServerSocket ss = new ServerSocket(port); + try { + sc.connect(new InetSocketAddress(LOCAL_ADDR, port)); + assertEquals(0, selectionKey.readyOps()); + assertFalse(selectionKey.isConnectable()); + selector.select(); + assertEquals(SelectionKey.OP_CONNECT, selectionKey.readyOps()); + } finally { + ss.close(); + ss = null; + } + + } + + /** + * @tests java.nio.channels.SelectionKey#selector() + */ + public void test_selector() { + assertSame(selector, selectionKey.selector()); + selectionKey.cancel(); + assertSame(selector, selectionKey.selector()); + } +} 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/nio/tests/java/nio/channels/SelectorTest.java new file mode 100644 index 0000000..fd29ac8 --- /dev/null +++ b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/SelectorTest.java @@ -0,0 +1,689 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.harmony.nio.tests.java.nio.channels; + +import java.io.IOException; +import java.net.InetSocketAddress; +import java.net.ServerSocket; +import java.nio.ByteBuffer; +import java.nio.channels.ClosedChannelException; +import java.nio.channels.ClosedSelectorException; +import java.nio.channels.Pipe; +import java.nio.channels.SelectionKey; +import java.nio.channels.Selector; +import java.nio.channels.ServerSocketChannel; +import java.nio.channels.SocketChannel; +import java.nio.channels.spi.SelectorProvider; +import java.util.Set; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicReference; + +import junit.framework.TestCase; +import tests.support.Support_PortManager; + +/* + * Tests for Selector and its default implementation + */ +public class SelectorTest extends TestCase { + + private static final int WAIT_TIME = 100; + + private static final int PORT = Support_PortManager.getNextPort(); + + private static final InetSocketAddress LOCAL_ADDRESS = new InetSocketAddress( + "127.0.0.1", PORT); + + Selector selector; + + ServerSocketChannel ssc; + + enum SelectType { + NULL, TIMEOUT, NOW + }; + + protected void setUp() throws Exception { + super.setUp(); + ssc = ServerSocketChannel.open(); + ssc.configureBlocking(false); + ServerSocket ss = ssc.socket(); + InetSocketAddress address = new InetSocketAddress(PORT); + ss.bind(address); + selector = Selector.open(); + } + + protected void tearDown() throws Exception { + try { + ssc.close(); + } catch (Exception e) { + // do nothing + } + try { + selector.close(); + } catch (Exception e) { + // do nothing + } + super.tearDown(); + } + + /** + * @tests java.nio.channels.Selector#open() + */ + public void test_open() throws IOException { + assertNotNull(selector); + } + + /** + * @tests Selector#isOpen() + */ + public void test_isOpen() throws IOException { + assertTrue(selector.isOpen()); + selector.close(); + assertFalse(selector.isOpen()); + } + + /** + * @tests java.nio.channels.Selector#provider() + */ + public void test_provider() throws IOException { + // should be system default provider + assertNotNull(selector.provider()); + assertSame(SelectorProvider.provider(), selector.provider()); + } + + /** + * @tests java.nio.channels.Selector#keys() + */ + public void test_keys() throws IOException { + SelectionKey key = ssc.register(selector, SelectionKey.OP_ACCEPT); + + Set<SelectionKey> keySet = selector.keys(); + Set<SelectionKey> keySet2 = selector.keys(); + + assertSame(keySet, keySet2); + assertEquals(1,keySet.size()); + SelectionKey key2 = keySet.iterator().next(); + assertEquals(key,key2); + + // Any attempt to modify keys will cause UnsupportedOperationException + SocketChannel sc = SocketChannel.open(); + sc.configureBlocking(false); + SelectionKey key3 = sc.register(selector, SelectionKey.OP_READ); + try { + keySet2.add(key3); + fail("should throw UnsupportedOperationException"); + } catch (UnsupportedOperationException e) { + // expected + } + try { + keySet2.remove(key3); + fail("should throw UnsupportedOperationException"); + } catch (UnsupportedOperationException e) { + // expected + } + try { + keySet2.clear(); + fail("should throw UnsupportedOperationException"); + } catch (UnsupportedOperationException e) { + // expected + } + + selector.close(); + try { + selector.keys(); + fail("should throw ClosedSelectorException"); + } catch (ClosedSelectorException e) { + // expected + } + } + + /** + * @tests java.nio.channels.Selector#keys() + */ + public void test_selectedKeys() throws IOException { + SocketChannel sc = SocketChannel.open(); + ssc.register(selector, SelectionKey.OP_ACCEPT); + try { + int count = 0; + sc.connect(LOCAL_ADDRESS); + count = blockingSelect(SelectType.NULL, 0); + assertEquals(1, count); + Set<SelectionKey> selectedKeys = selector.selectedKeys(); + Set<SelectionKey> selectedKeys2 = selector.selectedKeys(); + assertSame(selectedKeys, selectedKeys2); + + assertEquals(1, selectedKeys.size()); + assertEquals(ssc.keyFor(selector), selectedKeys.iterator().next()); + // add one key into selectedKeys + try { + selectedKeys.add(ssc.keyFor(selector)); + fail("Should throw UnsupportedOperationException"); + } catch (UnsupportedOperationException e) { + // expected + } + + // no exception should be thrown + selectedKeys.clear(); + + Set<SelectionKey> selectedKeys3 = selector.selectedKeys(); + assertSame(selectedKeys, selectedKeys3); + + ssc.keyFor(selector).cancel(); + assertEquals(0, selectedKeys.size()); + selector.close(); + try { + selector.selectedKeys(); + fail("should throw ClosedSelectorException"); + } catch (ClosedSelectorException e) { + // expected + } + } finally { + sc.close(); + } + } + + /** + * @tests java.nio.channel.Selector#selectNow() + */ + public void test_selectNow() throws IOException { + assert_select_OP_ACCEPT(SelectType.NOW, 0); + assert_select_OP_CONNECT(SelectType.NOW, 0); + assert_select_OP_READ(SelectType.NOW, 0); + assert_select_OP_WRITE(SelectType.NOW, 0); + } + + /** + * @tests java.nio.channel.Selector#selectNow() + */ + public void test_selectNow_SelectorClosed() throws IOException { + 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(); + } + + /** + * @tests java.nio.channel.Selector#select() + */ + public void test_select() throws IOException { + assert_select_OP_ACCEPT(SelectType.NULL, 0); + assert_select_OP_CONNECT(SelectType.NULL, 0); + assert_select_OP_READ(SelectType.NULL, 0); + assert_select_OP_WRITE(SelectType.NULL, 0); + } + + /** + * @tests java.nio.channel.Selector#select() + */ + public void test_select_SelectorClosed() throws IOException { + assert_select_SelectorClosed(SelectType.NULL, 0); + } + + /** + * @tests java.nio.channel.Selector#select(long) + */ + public void test_selectJ() throws IOException { + assert_select_OP_ACCEPT(SelectType.TIMEOUT, 0); + assert_select_OP_CONNECT(SelectType.TIMEOUT, 0); + assert_select_OP_READ(SelectType.TIMEOUT, 0); + assert_select_OP_WRITE(SelectType.TIMEOUT, 0); + + assert_select_OP_ACCEPT(SelectType.TIMEOUT, WAIT_TIME); + assert_select_OP_CONNECT(SelectType.TIMEOUT, WAIT_TIME); + assert_select_OP_READ(SelectType.TIMEOUT, WAIT_TIME); + assert_select_OP_WRITE(SelectType.TIMEOUT, WAIT_TIME); + } + + /** + * @tests java.nio.channel.Selector#select(long) + */ + public void test_selectJ_SelectorClosed() throws IOException { + assert_select_SelectorClosed(SelectType.TIMEOUT, 0); + selector = Selector.open(); + assert_select_SelectorClosed(SelectType.TIMEOUT, WAIT_TIME); + } + + /** + * @tests java.nio.channel.Selector#select(long) + */ + public void test_selectJ_Exception() throws IOException { + try { + selector.select(-1); + } catch (IllegalArgumentException e) { + // expected + } + } + + /** + * @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 + // time if keys.size() == 0 (initial state of selector). + + final long SELECT_TIMEOUT = 2000; + + long time1 = System.currentTimeMillis(); + selector.select(SELECT_TIMEOUT); + long time2 = System.currentTimeMillis(); + assertEquals("elapsed time", SELECT_TIMEOUT, (time2 - time1), + SELECT_TIMEOUT * 0.05); // 5% accuracy + } + + /** + * @tests java.nio.channels.Selector#wakeup() + */ + public void test_wakeup() throws IOException { + /* + * make sure the test does not block on select + */ + selector.wakeup(); + selectOnce(SelectType.NULL, 0); + selector.wakeup(); + selectOnce(SelectType.TIMEOUT, 0); + + // try to wakeup select. The invocation sequence of wakeup and select + // doesn't affect test result. + new Thread() { + public void run() { + + try { + Thread.sleep(WAIT_TIME); + } catch (InterruptedException e) { + // ignore + } + selector.wakeup(); + } + }.start(); + selectOnce(SelectType.NULL, 0); + + // try to wakeup select. The invocation sequence of wakeup and select + // doesn't affect test result. + new Thread() { + public void run() { + + try { + Thread.sleep(WAIT_TIME); + } catch (InterruptedException e) { + // ignore + } + selector.wakeup(); + } + }.start(); + selectOnce(SelectType.TIMEOUT, 0); + } + + public void test_keySetViewsModifications() throws IOException { + Set<SelectionKey> keys = selector.keys(); + + SelectionKey key1 = ssc.register(selector, SelectionKey.OP_ACCEPT); + + assertTrue(keys.contains(key1)); + + SocketChannel sc = SocketChannel.open(); + sc.configureBlocking(false); + SelectionKey key2 = sc.register(selector, SelectionKey.OP_READ); + + assertTrue(keys.contains(key1)); + assertTrue(keys.contains(key2)); + + key1.cancel(); + assertTrue(keys.contains(key1)); + + selector.selectNow(); + assertFalse(keys.contains(key1)); + assertTrue(keys.contains(key2)); + } + + /** + * This test cancels a key while selecting to verify that the cancelled + * key set is processed both before and after the call to the underlying + * operating system. + */ + public void test_cancelledKeys() throws Exception { + final AtomicReference<Throwable> failure = new AtomicReference<Throwable>(); + final AtomicBoolean complete = new AtomicBoolean(); + + final Pipe pipe = Pipe.open(); + pipe.source().configureBlocking(false); + final SelectionKey key = pipe.source().register(selector, SelectionKey.OP_READ); + + Thread thread = new Thread() { + public void run() { + try { + // make sure to call key.cancel() while the main thread is selecting + Thread.sleep(500); + key.cancel(); + assertFalse(key.isValid()); + pipe.sink().write(ByteBuffer.allocate(4)); // unblock select() + } catch (Throwable e) { + failure.set(e); + } finally { + complete.set(true); + } + } + }; + assertTrue(key.isValid()); + + thread.start(); + do { + assertEquals(0, selector.select(5000)); // blocks + assertEquals(0, selector.selectedKeys().size()); + } while (!complete.get()); // avoid spurious interrupts + assertFalse(key.isValid()); + + thread.join(); + assertNull(failure.get()); + } + + public void testOpChange() throws Exception { + SocketChannel sc = SocketChannel.open(); + sc.configureBlocking(false); + sc.register(selector, SelectionKey.OP_CONNECT); + try { + sc.connect(LOCAL_ADDRESS); + int count = blockingSelect(SelectType.TIMEOUT, 100); + assertEquals(1, count); + Set<SelectionKey> selectedKeys = selector.selectedKeys(); + assertEquals(1, selectedKeys.size()); + SelectionKey key = selectedKeys.iterator().next(); + assertEquals(sc.keyFor(selector), key); + assertEquals(SelectionKey.OP_CONNECT, key.readyOps()); + // select again, it should return 0 + count = selectOnce(SelectType.TIMEOUT, 100); + assertEquals(0, count); + // but selectedKeys remains the same as previous + assertSame(selectedKeys, selector.selectedKeys()); + sc.finishConnect(); + + // same selector, but op is changed + SelectionKey key1 = sc.register(selector, SelectionKey.OP_WRITE); + assertEquals(key, key1); + count = blockingSelect(SelectType.TIMEOUT, 100); + assertEquals(1, count); + selectedKeys = selector.selectedKeys(); + assertEquals(1, selectedKeys.size()); + key = selectedKeys.iterator().next(); + assertEquals(key, key1); + assertEquals(SelectionKey.OP_WRITE, key.readyOps()); + + selectedKeys.clear(); + } finally { + try { + ssc.accept().close(); + } catch (Exception e) { + // do nothing + } + try { + sc.close(); + } catch (IOException e) { + // do nothing + } + } + } + + public void test_nonBlockingConnect() throws IOException { + SocketChannel channel = null; + try { + channel = SocketChannel.open(); + channel.configureBlocking(false); + Selector selector = Selector.open(); + channel.register(selector, SelectionKey.OP_CONNECT); + channel.connect(LOCAL_ADDRESS); + channel.finishConnect(); + selector.select(); + assertEquals(1, selector.selectedKeys().size()); + } finally { + channel.close(); + } + } + + private void assert_select_SelectorClosed(SelectType type, int timeout) + throws IOException { + // selector is closed + selector.close(); + try { + selectOnce(type, timeout); + fail("should throw ClosedSelectorException"); + } catch (ClosedSelectorException e) { + // expected + } + } + + private void assert_select_OP_ACCEPT(SelectType type, int timeout) + throws IOException, ClosedChannelException { + SocketChannel sc = SocketChannel.open(); + SocketChannel client = null; + try { + ssc.register(selector, SelectionKey.OP_ACCEPT); + sc.connect(LOCAL_ADDRESS); + int count = blockingSelect(type, timeout); + assertEquals(1, count); + Set<SelectionKey> selectedKeys = selector.selectedKeys(); + assertEquals(1, selectedKeys.size()); + SelectionKey key = selectedKeys.iterator().next(); + assertEquals(ssc.keyFor(selector), key); + assertEquals(SelectionKey.OP_ACCEPT, key.readyOps()); + // select again, it should return 0 + count = selectOnce(type, timeout); + assertEquals(0,count); + // but selectedKeys remains the same as previous + assertSame(selectedKeys, selector.selectedKeys()); + client = ssc.accept(); + selectedKeys.clear(); + } finally { + try { + sc.close(); + } catch (IOException e) { + // do nothing + } + if (null != client) { + client.close(); + } + } + ssc.keyFor(selector).cancel(); + } + + private void assert_select_OP_CONNECT(SelectType type, int timeout) + throws IOException, ClosedChannelException { + SocketChannel sc = SocketChannel.open(); + sc.configureBlocking(false); + sc.register(selector, SelectionKey.OP_CONNECT); + try { + sc.connect(LOCAL_ADDRESS); + int count = blockingSelect(type, timeout); + assertEquals(1, count); + Set<SelectionKey> selectedKeys = selector.selectedKeys(); + assertEquals(1, selectedKeys.size()); + SelectionKey key = selectedKeys.iterator().next(); + assertEquals(sc.keyFor(selector), key); + assertEquals(SelectionKey.OP_CONNECT, key.readyOps()); + // select again, it should return 0 + count = selectOnce(type, timeout); + assertEquals(0, count); + // but selectedKeys remains the same as previous + assertSame(selectedKeys, selector.selectedKeys()); + sc.finishConnect(); + selectedKeys.clear(); + } finally { + try { + ssc.accept().close(); + } catch (Exception e) { + // do nothing + } + + try { + sc.close(); + } catch (IOException e) { + // do nothing + } + } + } + + private void assert_select_OP_READ(SelectType type, int timeout) + throws IOException { + SocketChannel sc = SocketChannel.open(); + SocketChannel client = null; + SocketChannel sc2 = SocketChannel.open(); + SocketChannel client2 = null; + try { + ssc.configureBlocking(true); + sc.connect(LOCAL_ADDRESS); + client = ssc.accept(); + sc.configureBlocking(false); + sc.register(selector, SelectionKey.OP_READ); + client.configureBlocking(true); + + sc2.connect(LOCAL_ADDRESS); + client2 = ssc.accept(); + sc2.configureBlocking(false); + sc2.register(selector, SelectionKey.OP_READ); + client2.configureBlocking(true); + + client.write(ByteBuffer.wrap("a".getBytes())); + int count = blockingSelect(type, timeout); + assertEquals(1, count); + Set<SelectionKey> selectedKeys = selector.selectedKeys(); + assertEquals(1, selectedKeys.size()); + SelectionKey key = selectedKeys.iterator().next(); + assertEquals(sc.keyFor(selector), key); + assertEquals(SelectionKey.OP_READ, key.readyOps()); + // select again, it should return 0 + count = selectOnce(type, timeout); + assertEquals(0, count); + // but selectedKeys remains the same as previous + assertSame(selectedKeys, selector.selectedKeys()); + + sc.read(ByteBuffer.allocate(8)); + + // the second SocketChannel should be selected this time + client2.write(ByteBuffer.wrap("a".getBytes())); + count = blockingSelect(type, timeout); + assertEquals(1, count); + // selectedKeys still includes the key of sc, because the key of sc + // is not removed last time. + selectedKeys = selector.selectedKeys(); + assertEquals(2, selectedKeys.size()); + } finally { + if (null != client) { + try { + client.close(); + } catch (Exception e) { + // ignore + } + } + if (null != client2) { + try { + client2.close(); + } catch (Exception e) { + // ignore + } + } + try { + sc.close(); + } catch (Exception e) { + // ignore + } + try { + sc2.close(); + } catch (Exception e) { + // ignore + } + ssc.configureBlocking(false); + } + } + + private void assert_select_OP_WRITE(SelectType type, int timeout) + throws IOException { + SocketChannel sc = SocketChannel.open(); + SocketChannel client = null; + try { + sc.connect(LOCAL_ADDRESS); + ssc.configureBlocking(true); + client = ssc.accept(); + sc.configureBlocking(false); + sc.register(selector, SelectionKey.OP_WRITE); + int count = blockingSelect(type, timeout); + assertEquals(1, count); + Set<SelectionKey> selectedKeys = selector.selectedKeys(); + assertEquals(1, selectedKeys.size()); + SelectionKey key = selectedKeys.iterator().next(); + assertEquals(sc.keyFor(selector), key); + assertEquals(SelectionKey.OP_WRITE, key.readyOps()); + // select again, it should return 0 + count = selectOnce(type, timeout); + assertEquals(0, count); + // but selectedKeys remains the same as previous + assertSame(selectedKeys, selector.selectedKeys()); + } finally { + if (null != client) { + client.close(); + } + try { + sc.close(); + } catch (IOException e) { + // do nothing + } + ssc.configureBlocking(false); + } + } + + private int blockingSelect(SelectType type, int timeout) throws IOException { + int ret = 0; + do { + ret = selectOnce(type, timeout); + if (ret > 0) { + return ret; + } + try { + Thread.sleep(100); + } catch (InterruptedException e) { + // ignore + } + } while (true); + } + + private int selectOnce(SelectType type, int timeout) throws IOException { + int ret = 0; + switch (type) { + case NULL: + ret = selector.select(); + break; + case TIMEOUT: + ret = selector.select(timeout); + break; + case NOW: + ret = selector.selectNow(); + break; + } + return ret; + } + +} diff --git a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/ServerSocketChannelTest.java b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/ServerSocketChannelTest.java new file mode 100644 index 0000000..fdbbc48 --- /dev/null +++ b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/ServerSocketChannelTest.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.nio.tests.java.nio.channels; + +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.net.InetSocketAddress; +import java.net.ServerSocket; +import java.net.Socket; +import java.nio.ByteBuffer; +import java.nio.channels.AsynchronousCloseException; +import java.nio.channels.ClosedChannelException; +import java.nio.channels.IllegalBlockingModeException; +import java.nio.channels.NotYetBoundException; +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 + */ +public class ServerSocketChannelTest extends TestCase { + + private static final int CAPACITY_NORMAL = 200; + + private static final int CAPACITY_64KB = 65536; + + 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(); + } + + protected void tearDown() throws Exception { + if (null != this.serverChannel) { + try { + this.serverChannel.close(); + } catch (Exception e) { + //ignore + } + + } + if (null != this.clientChannel) { + try { + this.clientChannel.close(); + } catch (Exception e) { + //ignore + } + } + super.tearDown(); + } + + // ------------------------------------------------------------------- + // Test for methods in abstract class. + // ------------------------------------------------------------------- + + /* + * Test method for 'java.nio.channels.ServerSocketChannel.validOps()' + */ + public void testValidOps() { + MockServerSocketChannel testMSChnlnull = new MockServerSocketChannel( + null); + MockServerSocketChannel testMSChnl = new MockServerSocketChannel( + SelectorProvider.provider()); + assertEquals(SelectionKey.OP_ACCEPT, this.serverChannel.validOps()); + assertEquals(SelectionKey.OP_ACCEPT, testMSChnl.validOps()); + assertEquals(SelectionKey.OP_ACCEPT, testMSChnlnull.validOps()); + + } + + /* + * Test method for 'java.nio.channels.ServerSocketChannel.open()' + */ + public void testOpen() { + MockServerSocketChannel testMSChnl = new MockServerSocketChannel(null); + MockServerSocketChannel testMSChnlnotnull = new MockServerSocketChannel( + SelectorProvider.provider()); + assertEquals(SelectionKey.OP_ACCEPT, testMSChnlnotnull.validOps()); + assertNull(testMSChnl.provider()); + assertNotNull(testMSChnlnotnull.provider()); + assertNotNull(this.serverChannel.provider()); + assertEquals(testMSChnlnotnull.provider(), this.serverChannel + .provider()); + } + + // ------------------------------------------------------------------- + // Test for socket() + // ------------------------------------------------------------------- + + /* + * Test method for 'java.nio.channels.ServerSocketChannel.socket()' + */ + public void testSocket_Block_BeforeClose() throws Exception { + assertTrue(this.serverChannel.isOpen()); + assertTrue(this.serverChannel.isBlocking()); + ServerSocket s1 = this.serverChannel.socket(); + assertFalse(s1.isClosed()); + assertSocketNotAccepted(s1); + ServerSocket s2 = this.serverChannel.socket(); + // same + assertSame(s1, s2); + + // socket close makes the channel close + s1.close(); + assertFalse(this.serverChannel.isOpen()); + + } + + public void testSocket_NonBlock_BeforeClose() throws Exception { + assertTrue(this.serverChannel.isOpen()); + this.serverChannel.configureBlocking(false); + ServerSocket s1 = this.serverChannel.socket(); + assertFalse(s1.isClosed()); + assertSocketNotAccepted(s1); + ServerSocket s2 = this.serverChannel.socket(); + // same + assertSame(s1, s2); + + // socket close makes the channel close + s1.close(); + assertFalse(this.serverChannel.isOpen()); + + } + + public void testSocket_Block_Closed() throws Exception { + this.serverChannel.close(); + assertFalse(this.serverChannel.isOpen()); + assertTrue(this.serverChannel.isBlocking()); + ServerSocket s1 = this.serverChannel.socket(); + assertTrue(s1.isClosed()); + assertSocketNotAccepted(s1); + ServerSocket s2 = this.serverChannel.socket(); + // same + assertSame(s1, s2); + } + + public void testSocket_NonBlock_Closed() throws Exception { + this.serverChannel.configureBlocking(false); + this.serverChannel.close(); + assertFalse(this.serverChannel.isBlocking()); + assertFalse(this.serverChannel.isOpen()); + ServerSocket s1 = this.serverChannel.socket(); + assertTrue(s1.isClosed()); + assertSocketNotAccepted(s1); + ServerSocket s2 = this.serverChannel.socket(); + // same + assertSame(s1, s2); + } + + private void assertSocketNotAccepted(ServerSocket s) throws IOException { + assertFalse(s.isBound()); + assertNull(s.getInetAddress()); + assertEquals(-1, s.getLocalPort()); + assertNull(s.getLocalSocketAddress()); + try { + assertEquals(0, s.getSoTimeout()); + } catch (IOException expected) { + // Android doesn't cache the timeout, so the getsockopt(2) fails and throws. + } + } + + public void testChannelBasicStatus() { + ServerSocket gotSocket = this.serverChannel.socket(); + assertFalse(gotSocket.isClosed()); + assertTrue(this.serverChannel.isBlocking()); + assertFalse(this.serverChannel.isRegistered()); + assertEquals(SelectionKey.OP_ACCEPT, this.serverChannel.validOps()); + assertEquals(SelectorProvider.provider(), this.serverChannel.provider()); + } + + // ------------------------------------------------------------------- + // Test for accept() + // ------------------------------------------------------------------- + + /* + * Test method for 'java.nio.channels.ServerSocketChannel.accept()' + */ + + public void testAccept_Block_NotYetBound() throws IOException { + assertTrue(this.serverChannel.isOpen()); + assertTrue(this.serverChannel.isBlocking()); + try { + this.serverChannel.accept(); + fail("Should throw NotYetBoundException"); + } catch (NotYetBoundException e) { + // correct + } + } + + public void testAccept_NonBlock_NotYetBound() throws IOException { + assertTrue(this.serverChannel.isOpen()); + this.serverChannel.configureBlocking(false); + try { + this.serverChannel.accept(); + fail("Should throw NotYetBoundException"); + } catch (NotYetBoundException e) { + // correct + } + } + + public void testAccept_ClosedChannel() throws Exception { + this.serverChannel.close(); + assertFalse(this.serverChannel.isOpen()); + try { + this.serverChannel.accept(); + fail("Should throw ClosedChannelException"); + } catch (ClosedChannelException e) { + // OK. + } + } + + public void testAccept_Block_NoConnect() throws IOException { + assertTrue(this.serverChannel.isBlocking()); + ServerSocket gotSocket = this.serverChannel.socket(); + gotSocket.bind(localAddr1); + // blocking mode , will block and wait for ever... + // so must close the server channel with another thread. + new Thread() { + public void run() { + try { + Thread.sleep(TIME_UNIT); + ServerSocketChannelTest.this.serverChannel.close(); + } catch (Exception e) { + fail("Fail to close the server channel because of" + + e.getClass().getName()); + } + } + }.start(); + try { + this.serverChannel.accept(); + fail("Should throw a AsynchronousCloseException"); + } catch (AsynchronousCloseException e) { + // OK. + } + } + + public void testAccept_NonBlock_NoConnect() throws IOException { + ServerSocket gotSocket = this.serverChannel.socket(); + gotSocket.bind(localAddr1); + this.serverChannel.configureBlocking(false); + // non-blocking mode , will immediately return + assertNull(this.serverChannel.accept()); + } + + /** + * @tests ServerSocketChannel#accept().socket() + */ + public void test_read_Blocking_RealData() throws IOException { + serverChannel.socket().bind(localAddr1); + ByteBuffer buf = ByteBuffer.allocate(CAPACITY_NORMAL); + + for (int i = 0; i < CAPACITY_NORMAL; i++) { + buf.put((byte) i); + } + clientChannel.connect(localAddr1); + Socket serverSocket = serverChannel.accept().socket(); + InputStream in = serverSocket.getInputStream(); + buf.flip(); + clientChannel.write(buf); + clientChannel.close(); + assertReadResult(in,CAPACITY_NORMAL); + } + + /** + * Asserts read content. The read content should contain <code>size</code> + * bytes, and the value should be a sequence from 0 to size-1 + * ([0,1,...size-1]). Otherwise, the method throws Exception. + * + */ + private void assertReadResult(InputStream in, int size) throws IOException{ + byte[] readContent = new byte[size + 1]; + int count = 0; + int total = 0; + while ((count = in.read(readContent, total, size + 1 - total)) != -1) { + total = total + count; + } + assertEquals(size, total); + for (int i = 0; i < size; i++) { + assertEquals((byte) i, readContent[i]); + } + } + + /** + * @tests ServerSocketChannel#accept().socket() + */ + public void test_read_NonBlocking_RealData() throws Exception { + serverChannel.configureBlocking(false); + serverChannel.socket().bind(localAddr1); + ByteBuffer buf = ByteBuffer.allocate(CAPACITY_NORMAL); + for (int i = 0; i < CAPACITY_NORMAL; i++) { + buf.put((byte) i); + } + buf.flip(); + clientChannel.connect(localAddr1); + Socket serverSocket = serverChannel.accept().socket(); + InputStream in = serverSocket.getInputStream(); + clientChannel.write(buf); + clientChannel.close(); + assertReadResult(in,CAPACITY_NORMAL); + } + + /** + * @tests ServerSocketChannel#accept().socket() + */ + public void test_write_Blocking_RealData() throws IOException { + assertTrue(serverChannel.isBlocking()); + ServerSocket serverSocket = serverChannel.socket(); + serverSocket.bind(localAddr1); + + byte[] writeContent = new byte[CAPACITY_NORMAL]; + for (int i = 0; i < writeContent.length; i++) { + writeContent[i] = (byte) i; + } + clientChannel.connect(localAddr1); + Socket socket = serverChannel.accept().socket(); + OutputStream out = socket.getOutputStream(); + out.write(writeContent); + out.flush(); + socket.close(); + assertWriteResult(CAPACITY_NORMAL); + } + + + /** + * @tests ServerSocketChannel#accept().socket() + */ + public void test_write_NonBlocking_RealData() throws Exception { + serverChannel.configureBlocking(false); + ServerSocket serverSocket = serverChannel.socket(); + serverSocket.bind(localAddr1); + + byte[] writeContent = new byte[CAPACITY_NORMAL]; + for (int i = 0; i < CAPACITY_NORMAL; i++) { + writeContent[i] = (byte) i; + } + clientChannel.connect(localAddr1); + Socket clientSocket = serverChannel.accept().socket(); + OutputStream out = clientSocket.getOutputStream(); + out.write(writeContent); + clientSocket.close(); + assertWriteResult(CAPACITY_NORMAL); + } + + /** + * @throws InterruptedException + * @tests ServerSocketChannel#accept().socket() + */ + public void test_read_LByteBuffer_Blocking_ReadWriteRealLargeData() + throws IOException, InterruptedException { + serverChannel.socket().bind(localAddr1); + ByteBuffer buf = ByteBuffer.allocate(CAPACITY_64KB); + for (int i = 0; i < CAPACITY_64KB; i++) { + buf.put((byte) i); + } + buf.flip(); + clientChannel.connect(localAddr1); + WriteChannelThread writeThread = new WriteChannelThread(clientChannel, buf); + writeThread.start(); + Socket socket = serverChannel.accept().socket(); + InputStream in = socket.getInputStream(); + assertReadResult(in,CAPACITY_64KB); + writeThread.join(); + // check if the thread threw any exceptions + if (writeThread.exception != null) { + throw writeThread.exception; + } + } + + class WriteChannelThread extends Thread { + SocketChannel channel; + ByteBuffer buffer; + IOException exception; + + public WriteChannelThread(SocketChannel channel, ByteBuffer buffer) { + this.channel = channel; + this.buffer = buffer; + } + + public void run() { + try { + channel.write(buffer); + channel.close(); + } catch (IOException e) { + exception = e; + } + } + } + + /** + * @tests ServerSocketChannel#accept().socket() + */ + public void test_read_LByteBuffer_NonBlocking_ReadWriteRealLargeData() + throws Exception { + serverChannel.configureBlocking(false); + serverChannel.socket().bind(localAddr1); + ByteBuffer buf = ByteBuffer.allocate(CAPACITY_64KB); + for (int i = 0; i < CAPACITY_64KB; i++) { + buf.put((byte) i); + } + buf.flip(); + clientChannel.connect(localAddr1); + WriteChannelThread writeThread = new WriteChannelThread(clientChannel, buf); + writeThread.start(); + Socket socket = serverChannel.accept().socket(); + InputStream in = socket.getInputStream(); + assertReadResult(in,CAPACITY_64KB); + writeThread.join(); + // check if the thread threw any exceptions + if (writeThread.exception != null) { + throw writeThread.exception; + } + } + + /** + * @tests ServerSocketChannel#accept().socket() + */ + public void test_write_LByteBuffer_NonBlocking_ReadWriteRealLargeData() + throws Exception { + serverChannel.configureBlocking(false); + serverChannel.socket().bind(localAddr1); + byte[] writeContent = new byte[CAPACITY_64KB]; + for (int i = 0; i < writeContent.length; i++) { + writeContent[i] = (byte) i; + } + clientChannel.connect(localAddr1); + Socket socket = serverChannel.accept().socket(); + WriteSocketThread writeThread = new WriteSocketThread(socket, writeContent); + writeThread.start(); + assertWriteResult(CAPACITY_64KB); + writeThread.join(); + // check if the thread threw any exceptions + if (writeThread.exception != null) { + throw writeThread.exception; + } + } + + class WriteSocketThread extends Thread { + Socket socket; + byte[] buffer; + IOException exception; + + public WriteSocketThread(Socket socket, byte[] buffer) { + this.socket = socket; + this.buffer = buffer; + } + + public void run() { + try { + OutputStream out = socket.getOutputStream(); + out.write(buffer); + socket.close(); + } catch (IOException e) { + exception = e; + } + } + } + + /** + * @tests ServerSocketChannel#accept().socket() + */ + public void test_write_LByteBuffer_Blocking_ReadWriteRealLargeData() + throws Exception { + serverChannel.socket().bind(localAddr1); + byte[] writeContent = new byte[CAPACITY_64KB]; + for (int i = 0; i < writeContent.length; i++) { + writeContent[i] = (byte) i; + } + clientChannel.connect(localAddr1); + Socket socket = serverChannel.accept().socket(); + WriteSocketThread writeThread = new WriteSocketThread(socket, writeContent); + writeThread.start(); + assertWriteResult(CAPACITY_64KB); + writeThread.join(); + // check if the thread threw any exceptions + if (writeThread.exception != null) { + throw writeThread.exception; + } + } + + /** + * Uses SocketChannel.read(ByteBuffer) to verify write result. + */ + private void assertWriteResult(int size) throws IOException{ + ByteBuffer buf = ByteBuffer.allocate(size + 1); + int count = 0; + int total = 0; + long beginTime = System.currentTimeMillis(); + while ((count = clientChannel.read(buf)) != -1) { + total = total + count; + // 10s timeout to avoid dead loop + if (System.currentTimeMillis() - beginTime > 10000){ + break; + } + } + assertEquals(total, size); + buf.flip(); + for (int i = 0; i < count; i++) { + assertEquals((byte) i, buf.get(i)); + } + } + + /** + * @tests ServerSocketChannel#socket().getSoTimeout() + */ + public void test_accept_SOTIMEOUT() throws IOException { + // regression test for Harmony-707 + final int SO_TIMEOUT = 10; + ServerSocketChannel sc = ServerSocketChannel.open(); + try { + ServerSocket ss = sc.socket(); + ss.bind(localAddr1); + sc.configureBlocking(false); + ss.setSoTimeout(SO_TIMEOUT); + 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); + } finally { + sc.close(); + } + } + + /** + * @tests ServerSocket#socket().accept() + */ + public void test_socket_accept_Blocking_NotBound() throws IOException { + // regression test for Harmony-748 + ServerSocket gotSocket = serverChannel.socket(); + serverChannel.configureBlocking(true); + try { + gotSocket.accept(); + fail("Should throw an IllegalBlockingModeException"); + } catch (IllegalBlockingModeException e) { + // expected + } + serverChannel.close(); + try { + gotSocket.accept(); + fail("Should throw an IllegalBlockingModeException"); + } catch (IllegalBlockingModeException e) { + // expected + } + } + + /** + * @tests ServerSocket#socket().accept() + */ + public void test_socket_accept_Nonblocking_NotBound() throws IOException { + // regression test for Harmony-748 + ServerSocket gotSocket = serverChannel.socket(); + serverChannel.configureBlocking(false); + try { + gotSocket.accept(); + fail("Should throw an IllegalBlockingModeException"); + } catch (IllegalBlockingModeException e) { + // expected + } + serverChannel.close(); + try { + gotSocket.accept(); + fail("Should throw an IllegalBlockingModeException"); + } catch (IllegalBlockingModeException e) { + // expected + } + } + + /** + * @tests ServerSocket#socket().accept() + */ + public void test_socket_accept_Nonblocking_Bound() throws IOException { + // regression test for Harmony-748 + serverChannel.configureBlocking(false); + ServerSocket gotSocket = serverChannel.socket(); + gotSocket.bind(localAddr1); + try { + gotSocket.accept(); + fail("Should throw an IllegalBlockingModeException"); + } catch (IllegalBlockingModeException e) { + // expected + } + serverChannel.close(); + try { + gotSocket.accept(); + fail("Should throw a ClosedChannelException"); + } catch (ClosedChannelException e) { + // expected + } + } + + /** + * @tests ServerSocket#socket().accept() + */ + 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.close(); + try { + gotSocket.accept(); + fail("Should throw a ClosedChannelException"); + } catch (ClosedChannelException e) { + // expected + } + } + /** + * Regression test for HARMONY-4961 + */ + public void test_socket_getLocalPort() throws IOException { + serverChannel.socket().bind(localAddr1); + clientChannel.connect(localAddr1); + SocketChannel myChannel = serverChannel.accept(); + int port = myChannel.socket().getLocalPort(); + assertEquals(localAddr1.getPort(), port); + myChannel.close(); + clientChannel.close(); + serverChannel.close(); + } + + /** + * Regression test for HARMONY-6375 + */ + public void test_accept_configureBlocking() throws Exception { + InetSocketAddress localAddr = new InetSocketAddress("localhost", 0); + serverChannel.socket().bind(localAddr); + + // configure the channel non-blocking + // when it is accepting in main thread + new Thread() { + public void run() { + try { + Thread.sleep(TIME_UNIT); + serverChannel.configureBlocking(false); + serverChannel.close(); + } catch (Exception e) { + e.printStackTrace(); + } + } + }.start(); + + try { + serverChannel.accept(); + fail("should throw AsynchronousCloseException"); + } catch (AsynchronousCloseException e) { + // 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/nio/tests/java/nio/channels/SinkChannelTest.java new file mode 100644 index 0000000..9e96fad --- /dev/null +++ b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/SinkChannelTest.java @@ -0,0 +1,505 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.harmony.nio.tests.java.nio.channels; + +import java.io.IOException; +import java.net.InetAddress; +import java.net.InetSocketAddress; +import java.nio.ByteBuffer; +import java.nio.channels.ClosedChannelException; +import java.nio.channels.Pipe; +import java.nio.channels.SelectionKey; +import java.nio.channels.ServerSocketChannel; +import java.nio.channels.SocketChannel; + +import junit.framework.TestCase; + +/** + * Tests for Pipe.SinkChannel class + */ +public class SinkChannelTest extends TestCase { + + private static final int BUFFER_SIZE = 5; + + private static final String ISO8859_1 = "ISO8859-1"; + + private Pipe pipe; + + private Pipe.SinkChannel sink; + + private Pipe.SourceChannel source; + + private ByteBuffer buffer; + + private ByteBuffer positionedBuffer; + + protected void setUp() throws Exception { + super.setUp(); + pipe = Pipe.open(); + sink = pipe.sink(); + source = pipe.source(); + buffer = ByteBuffer.wrap("bytes".getBytes(ISO8859_1)); + positionedBuffer = ByteBuffer.wrap("12345bytes".getBytes(ISO8859_1)); + positionedBuffer.position(BUFFER_SIZE); + } + + /** + * @tests java.nio.channels.Pipe.SinkChannel#validOps() + */ + public void test_validOps() { + assertEquals(SelectionKey.OP_WRITE, sink.validOps()); + } + + /** + * @tests java.nio.channels.Pipe.SinkChannel#write(ByteBuffer) + */ + public void test_write_LByteBuffer() throws IOException { + ByteBuffer[] bufArray = { buffer, positionedBuffer }; + boolean[] sinkBlockingMode = { true, true, false, false }; + boolean[] sourceBlockingMode = { true, false, true, false }; + int oldPosition; + int currentPosition; + for (int i = 0; i < sinkBlockingMode.length; ++i) { + sink.configureBlocking(sinkBlockingMode[i]); + source.configureBlocking(sourceBlockingMode[i]); + // if sink and source both are blocking mode, source only needs read + // once to get what sink write. + boolean isBlocking = sinkBlockingMode[i] && sourceBlockingMode[i]; + for (ByteBuffer buf : bufArray) { + buf.mark(); + oldPosition = buf.position(); + sink.write(buf); + ByteBuffer readBuf = ByteBuffer.allocate(BUFFER_SIZE); + int totalCount = 0; + do { + int count = source.read(readBuf); + if (count > 0) { + totalCount += count; + } + } while (totalCount != BUFFER_SIZE && !isBlocking); + currentPosition = buf.position(); + assertEquals(BUFFER_SIZE, currentPosition - oldPosition); + assertEquals("bytes", new String(readBuf.array(), ISO8859_1)); + buf.reset(); + } + } + } + + /** + * @tests java.nio.channels.Pipe.SinkChannel#write(ByteBuffer) + */ + public void test_write_LByteBuffer_mutliThread() throws IOException, + InterruptedException { + final int THREAD_NUM = 20; + final byte[] strbytes = "bytes".getBytes(ISO8859_1); + Thread[] thread = new Thread[THREAD_NUM]; + for (int i = 0; i < THREAD_NUM; i++) { + thread[i] = new Thread() { + public void run() { + try { + sink.write(ByteBuffer.wrap(strbytes)); + } catch (IOException e) { + throw new RuntimeException(e); + } + } + }; + } + for (int i = 0; i < THREAD_NUM; i++) { + thread[i].start(); + } + for (int i = 0; i < THREAD_NUM; i++) { + thread[i].join(); + } + ByteBuffer readBuf = ByteBuffer.allocate(THREAD_NUM * BUFFER_SIZE); + + long totalCount = 0; + do { + long count = source.read(readBuf); + if (count < 0) { + break; + } + totalCount += count; + } while (totalCount != (THREAD_NUM * BUFFER_SIZE)); + + StringBuffer buf = new StringBuffer(); + for (int i = 0; i < THREAD_NUM; i++) { + buf.append("bytes"); + } + String readString = buf.toString(); + assertEquals(readString, new String(readBuf.array(), ISO8859_1)); + } + + /** + * @tests java.nio.channels.Pipe.SinkChannel#write(ByteBuffer) + */ + public void test_write_LByteBuffer_Exception() throws IOException { + // write null ByteBuffer + ByteBuffer nullBuf = null; + try { + sink.write(nullBuf); + fail("should throw NullPointerException"); + } catch (NullPointerException e) { + // expected + } + } + + public void test_write_LByteBuffer_SourceClosed() throws IOException { + source.close(); + try { + int written = sink.write(buffer); + fail(); + } catch (IOException expected) { + } + } + + public void test_write_LByteBuffer_SinkClosed() throws IOException { + sink.close(); + try { + sink.write(buffer); + fail("should throw ClosedChannelException"); + } catch (ClosedChannelException expected) { + } + } + + /** + * @tests java.nio.channels.Pipe.SinkChannel#write(ByteBuffer[]) + */ + public void test_write_$LByteBuffer() throws IOException { + ByteBuffer[] bufArray = { buffer, positionedBuffer }; + boolean[] sinkBlockingMode = { true, true, false, false }; + boolean[] sourceBlockingMode = { true, false, true, false }; + for (int i = 0; i < sinkBlockingMode.length; ++i) { + sink.configureBlocking(sinkBlockingMode[i]); + source.configureBlocking(sourceBlockingMode[i]); + buffer.position(0); + positionedBuffer.position(BUFFER_SIZE); + sink.write(bufArray); + // if sink and source both are blocking mode, source only needs read + // once to get what sink write. + boolean isBlocking = sinkBlockingMode[i] && sourceBlockingMode[i]; + for (int j = 0; j < bufArray.length; ++j) { + ByteBuffer readBuf = ByteBuffer.allocate(BUFFER_SIZE); + int totalCount = 0; + do { + int count = source.read(readBuf); + if (count < 0) { + break; + } + totalCount += count; + } while (totalCount != BUFFER_SIZE && !isBlocking); + assertEquals("bytes", new String(readBuf.array(), ISO8859_1)); + } + assertEquals(BUFFER_SIZE, buffer.position()); + assertEquals(10, positionedBuffer.position()); + } + } + + /** + * @tests java.nio.channels.Pipe.SinkChannel#write(ByteBuffer[]) + */ + public void test_write_$LByteBuffer_Exception() throws IOException { + // write null ByteBuffer[] + ByteBuffer[] nullBufArrayRef = null; + try { + sink.write(nullBufArrayRef); + fail("should throw NullPointerException"); + } catch (NullPointerException e) { + // expected + } + + // write ByteBuffer[] contains null element + ByteBuffer nullBuf = null; + ByteBuffer[] nullBufArray = { buffer, nullBuf }; + try { + sink.write(nullBufArray); + fail("should throw NullPointerException"); + } catch (NullPointerException e) { + // expected + } + } + + public void test_write_$LByteBuffer_SourceClosed() throws IOException { + ByteBuffer[] bufArray = { buffer }; + source.close(); + try { + long written = sink.write(bufArray); + fail(); + } catch (IOException expected) { + } + } + + /** + * @tests java.nio.channels.Pipe.SinkChannel#write(ByteBuffer[]) + */ + public void test_write_$LByteBuffer_SinkClosed() throws IOException { + ByteBuffer[] bufArray = { buffer }; + sink.close(); + try { + sink.write(bufArray); + fail("should throw ClosedChannelException"); + } catch (ClosedChannelException e) { + // expected + } + + ByteBuffer[] nullBufArrayRef = null; + try { + sink.write(nullBufArrayRef); + fail("should throw NullPointerException"); + } catch (NullPointerException e) { + // expected + } + + ByteBuffer nullBuf = null; + ByteBuffer[] nullBufArray = { nullBuf }; + // write ByteBuffer[] contains null element + try { + sink.write(nullBufArray); + fail("should throw ClosedChannelException"); + } catch (ClosedChannelException e) { + // expected + } + } + + /** + * @tests java.nio.channels.Pipe.SinkChannel#write(ByteBuffer[], int, int) + */ + public void test_write_$LByteBufferII() throws IOException { + ByteBuffer[] bufArray = { buffer, positionedBuffer }; + boolean[] sinkBlockingMode = { true, true, false, false }; + boolean[] sourceBlockingMode = { true, false, true, false }; + for (int i = 0; i < sinkBlockingMode.length; ++i) { + sink.configureBlocking(sinkBlockingMode[i]); + source.configureBlocking(sourceBlockingMode[i]); + positionedBuffer.position(BUFFER_SIZE); + sink.write(bufArray, 1, 1); + // if sink and source both are blocking mode, source only needs read + // once to get what sink write. + boolean isBlocking = sinkBlockingMode[i] && sourceBlockingMode[i]; + ByteBuffer readBuf = ByteBuffer.allocate(BUFFER_SIZE); + int totalCount = 0; + do { + int count = source.read(readBuf); + if (count < 0) { + break; + } + totalCount += count; + } while (totalCount != BUFFER_SIZE && !isBlocking); + assertEquals("bytes", new String(readBuf.array(), ISO8859_1)); + assertEquals(10, positionedBuffer.position()); + } + } + + public void test_write_$LByteBufferII_Exception() throws IOException { + try { + sink.write(null, 0, 1); + fail(); + } catch (NullPointerException expected) { + } + + try { + sink.write(new ByteBuffer[2], 0, -1); + fail(); + } catch (IndexOutOfBoundsException expected) { + } + + // write ByteBuffer[] contains null element + ByteBuffer nullBuf = null; + ByteBuffer[] nullBufArray = { nullBuf }; + try { + sink.write(nullBufArray, 0, 1); + fail("should throw NullPointerException"); + } catch (NullPointerException e) { + // expected + } + + try { + sink.write(nullBufArray, 0, -1); + fail("should throw IndexOutOfBoundsException"); + } catch (IndexOutOfBoundsException e) { + // expected + } + + ByteBuffer[] bufArray = { buffer, nullBuf }; + try { + sink.write(bufArray, 0, -1); + fail("should throw IndexOutOfBoundsException"); + } catch (IndexOutOfBoundsException e) { + // expected + } + + try { + sink.write(bufArray, -1, 0); + fail("should throw IndexOutOfBoundsException"); + } catch (IndexOutOfBoundsException e) { + // expected + } + + try { + sink.write(bufArray, -1, 1); + fail("should throw IndexOutOfBoundsException"); + } catch (IndexOutOfBoundsException e) { + // expected + } + + try { + sink.write(bufArray, 0, 3); + fail("should throw IndexOutOfBoundsException"); + } catch (IndexOutOfBoundsException e) { + // expected + } + + try { + sink.write(bufArray, 0, 2); + fail("should throw NullPointerException"); + } catch (NullPointerException e) { + // expected + } + } + + public void test_write_$LByteBufferII_SourceClosed() throws IOException { + ByteBuffer[] bufArray = { buffer }; + source.close(); + + try { + long written = sink.write(bufArray, 0, 1); + fail(); + } catch (IOException expected) { + } + } + + public void test_write_$LByteBufferII_SinkClosed() throws IOException { + ByteBuffer[] bufArray = { buffer }; + sink.close(); + try { + sink.write(bufArray, 0, 1); + fail(); + } catch (ClosedChannelException expected) { + } + + try { + sink.write(null, 0, 1); + fail(); + } catch (NullPointerException expected) { + } + try { + sink.write(new ByteBuffer[2], 0, -1); + fail(); + } catch (IndexOutOfBoundsException expected) { + } + + // write ByteBuffer[] contains null element + ByteBuffer nullBuf = null; + ByteBuffer[] nullBufArray = { nullBuf }; + try { + sink.write(nullBufArray, 0, 1); + fail("should throw ClosedChannelException"); + } catch (ClosedChannelException e) { + // expected + } + // illegal array index + try { + sink.write(nullBufArray, 0, -1); + fail("should throw IndexOutOfBoundsException"); + } catch (IndexOutOfBoundsException e) { + // expected + } + + ByteBuffer[] bufArray2 = { buffer, nullBuf }; + // illegal array index + try { + sink.write(bufArray2, 0, -1); + fail("should throw IndexOutOfBoundsException"); + } catch (IndexOutOfBoundsException e) { + // expected + } + + try { + sink.write(bufArray2, -1, 0); + fail("should throw IndexOutOfBoundsException"); + } catch (IndexOutOfBoundsException e) { + // expected + } + + try { + sink.write(bufArray2, -1, 1); + fail("should throw IndexOutOfBoundsException"); + } catch (IndexOutOfBoundsException e) { + // expected + } + + try { + sink.write(bufArray2, 0, 3); + fail("should throw IndexOutOfBoundsException"); + } catch (IndexOutOfBoundsException e) { + // expected + } + + try { + sink.write(bufArray2, 0, 2); + fail("should throw ClosedChannelException"); + } catch (ClosedChannelException e) { + // expected + } + } + + public void test_close() throws IOException { + sink.close(); + assertFalse(sink.isOpen()); + } + + public void test_socketChannel_read_close() throws Exception { + ServerSocketChannel ssc = ServerSocketChannel.open(); + ssc.socket().bind(new InetSocketAddress(InetAddress.getLocalHost(),49999)); + SocketChannel sc = SocketChannel.open(); + ByteBuffer buf = null; + try{ + sc.write(buf); + fail("should throw NPE"); + }catch (NullPointerException e){ + // expected + } + sc.connect(new InetSocketAddress(InetAddress.getLocalHost(),49999)); + SocketChannel sock = ssc.accept(); + ssc.close(); + sc.close(); + try{ + sc.write(buf); + fail("should throw NPE"); + }catch (NullPointerException e){ + // expected + } + sock.close(); + } + + public void test_socketChannel_read_write() throws Exception { + ServerSocketChannel ssc = ServerSocketChannel.open(); + ssc.socket().bind(new InetSocketAddress(InetAddress.getLocalHost(),49999)); + SocketChannel sc = SocketChannel.open(); + sc.connect(new InetSocketAddress(InetAddress.getLocalHost(),49999)); + SocketChannel sock = ssc.accept(); + ByteBuffer[] buf = {ByteBuffer.allocate(10),null}; + try { + sc.write(buf,0,2); + fail("should throw NPE"); + } catch (NullPointerException expected) { + } + ssc.close(); + sc.close(); + ByteBuffer target = ByteBuffer.allocate(10); + assertEquals(-1, sock.read(target)); + } +} 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/nio/tests/java/nio/channels/SocketChannelTest.java new file mode 100644 index 0000000..7325ba1 --- /dev/null +++ b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/SocketChannelTest.java @@ -0,0 +1,3628 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.harmony.nio.tests.java.nio.channels; + +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.net.BindException; +import java.net.ConnectException; +import java.net.InetAddress; +import java.net.InetSocketAddress; +import java.net.ServerSocket; +import java.net.Socket; +import java.net.SocketAddress; +import java.net.SocketException; +import java.nio.Buffer; +import java.nio.ByteBuffer; +import java.nio.channels.AlreadyConnectedException; +import java.nio.channels.ClosedChannelException; +import java.nio.channels.ConnectionPendingException; +import java.nio.channels.IllegalBlockingModeException; +import java.nio.channels.NoConnectionPendingException; +import java.nio.channels.NotYetConnectedException; +import java.nio.channels.ServerSocketChannel; +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. + */ +public class SocketChannelTest extends TestCase { + + private static final int CAPACITY_NORMAL = 200; + + private InetSocketAddress localAddr1; + + private InetSocketAddress localAddr2; + + private SocketChannel channel1; + + private SocketChannel channel2; + + private ServerSocket server1; + + private ServerSocket server2; + + private final static int TIMEOUT = 60000; + + private final static int EOF = -1; + + 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()); + } + + protected void tearDown() throws Exception { + super.tearDown(); + 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.server1) { + try { + this.server1.close(); + } catch (Exception e) { + //ignore + } + } + if (null != this.server2) { + try { + this.server2.close(); + } catch (Exception e) { + //ignore + } + } + } + + // ------------------------------------------------------------------- + // Test for methods in abstract class. + // ------------------------------------------------------------------- + /* + * Test method for 'java.nio.channels.SocketChannel.validOps()' + */ + public void testValidOps() { + MockSocketChannel testMSChannel = new MockSocketChannel(null); + assertEquals(13, this.channel1.validOps()); + assertEquals(13, testMSChannel.validOps()); + } + + /* + * Test method for 'java.nio.channels.SocketChannel.open()' + */ + public void testOpen() throws IOException { + java.nio.ByteBuffer[] buf = new java.nio.ByteBuffer[1]; + buf[0] = java.nio.ByteBuffer.allocateDirect(CAPACITY_NORMAL); + MockSocketChannel testMSChannel = new MockSocketChannel(null); + MockSocketChannel testMSChannelnotnull = new MockSocketChannel( + SelectorProvider.provider()); + assertNull(testMSChannel.provider()); + assertNotNull(testMSChannelnotnull.provider()); + assertNotNull(this.channel1); + assertEquals(this.channel1.provider(), testMSChannelnotnull.provider()); + try { + this.channel1.write(buf); + fail("Should throw NotYetConnectedException"); + } catch (NotYetConnectedException e) { + // correct + } + } + + /* + * Test method for 'java.nio.channels.SocketChannel.open(SocketAddress)' + */ + public void testOpenSocketAddress_Null() throws IOException { + SocketChannel channel1IP = null; + try { + channel1IP = SocketChannel.open(null); + fail("Should throw an IllegalArgumentException"); + } catch (IllegalArgumentException e) { + // correct + } + assertNull(channel1IP); + } + + /* + * Test method for 'java.nio.channels.SocketChannel.read(ByteBuffer[])' + */ + public void testReadByteBufferArray() throws IOException { + java.nio.ByteBuffer[] byteBuf = null; + MockSocketChannel testMSChannelnull = new MockSocketChannel(null); + MockSocketChannel testMSChannel = new MockSocketChannel( + SelectorProvider.provider()); + ServerSocket testServer = new ServerSocket(Support_PortManager + .getNextPort()); + try { + try { + this.channel1.read(byteBuf); + fail("Should throw NPE"); + } catch (NullPointerException e) { + // correct + } + byteBuf = new java.nio.ByteBuffer[CAPACITY_NORMAL]; + try { + this.channel1.read(byteBuf); + fail("Should throw NotYetConnectedException"); + } catch (NotYetConnectedException e) { + // correct + } + long readNum = CAPACITY_NORMAL; + readNum = testMSChannel.read(byteBuf); + assertEquals(0, readNum); + readNum = CAPACITY_NORMAL; + readNum = testMSChannelnull.read(byteBuf); + assertEquals(0, readNum); + } finally { + testServer.close(); + } + } + + /* + * Test method for 'java.nio.channels.SocketChannel.read(ByteBuffer[])' + */ + public void testReadByteBufferArray_BufNull() throws IOException { + java.nio.ByteBuffer[] byteBuf = null; + MockSocketChannel testMSChannelnull = new MockSocketChannel(null); + MockSocketChannel testMSChannel = new MockSocketChannel( + SelectorProvider.provider()); + try { + this.channel1.read(byteBuf); + fail("Should throw NPE"); + } catch (NullPointerException e) { + // correct + } + try { + testMSChannel.read(byteBuf); + fail("Should throw NPE"); + } catch (NullPointerException e) { + // correct + } + try { + testMSChannelnull.read(byteBuf); + fail("Should throw NPE"); + } catch (NullPointerException e) { + // correct + } + } + + /* + * Test method for 'java.nio.channels.SocketChannel.write(ByteBuffer[])' + */ + public void testWriteByteBufferArray() throws IOException { + java.nio.ByteBuffer[] byteBuf = null; + MockSocketChannel testMSChannelnull = new MockSocketChannel(null); + MockSocketChannel testMSChannel = new MockSocketChannel( + SelectorProvider.provider()); + try { + this.channel1.write(byteBuf); + fail("Should throw NPE"); + } catch (NullPointerException e) { + // correct + } + byteBuf = new java.nio.ByteBuffer[CAPACITY_NORMAL]; + try { + this.channel1.write(byteBuf); + fail("Should throw NotYetConnectedException"); + } catch (NotYetConnectedException e) { + // correct + } + testMSChannel.write(byteBuf); + testMSChannelnull.write(byteBuf); + } + + /* + * Test method for 'java.nio.channels.SocketChannel.write(ByteBuffer[])' + */ + public void testWriteByteBufferArray_BufNull() throws IOException { + java.nio.ByteBuffer[] byteBuf = null; + MockSocketChannel testMSChannelnull = new MockSocketChannel(null); + MockSocketChannel testMSChannel = new MockSocketChannel( + SelectorProvider.provider()); + try { + this.channel1.write(byteBuf); + fail("Should throw NPE"); + } catch (NullPointerException e) { + // correct + } + try { + testMSChannel.write(byteBuf); + fail("Should throw NPE"); + } catch (NullPointerException e) { + // correct + } + try { + testMSChannelnull.write(byteBuf); + fail("Should throw NPE"); + } catch (NullPointerException e) { + // correct + } + } + + public void testSocket_BasicStatusBeforeConnect() throws IOException { + assertFalse(this.channel1.isConnected());// not connected + Socket s1 = this.channel1.socket(); + assertSocketBeforeConnect(s1); + Socket s2 = this.channel1.socket(); + // same + assertSame(s1, s2); + } + + public void testSocket_Block_BasicStatusAfterConnect() throws IOException { + assertFalse(this.channel1.isConnected());// not connected + assertTrue(this.channel1.connect(localAddr1)); + + assertTrue(this.channel1.isConnected()); + Socket s1 = this.channel1.socket(); + + assertSocketAfterConnect(s1, localAddr1); + Socket s2 = this.channel1.socket(); + // same + assertSame(s1, s2); + } + + public void testSocket_NonBlock_BasicStatusAfterConnect() throws Exception { + assertFalse(this.channel1.isConnected());// not connected + this.channel1.configureBlocking(false); + boolean connected = channel1.connect(localAddr1); + Socket s1 = null; + Socket s2 = null; + if (!connected) { + assertFalse(this.channel1.isConnected()); + assertTrue(this.channel1.isConnectionPending()); + s1 = this.channel1.socket(); + // status of not connected + assertSocketBeforeConnect(s1); + s2 = this.channel1.socket(); + // same + assertSame(s1, s2); + } + + if (tryFinish()) { + assertTrue(this.channel1.isConnected()); + s1 = this.channel1.socket(); + assertSocketAfterConnect(s1, localAddr1); + s2 = this.channel1.socket(); + // same + assertSame(s1, s2); + } + } + + public void testSocket_Block_ActionsBeforeConnect() throws IOException { + assertFalse(this.channel1.isConnected());// not connected + Socket s = this.channel1.socket(); + assertSocketAction_Block_BeforeConnect(s); + } + + public void testSocket_Block_ActionsAfterConnect() throws IOException { + assertFalse(this.channel1.isConnected());// not connected + assertTrue(this.channel1.connect(localAddr1)); + assertTrue(this.channel1.isConnected()); + Socket s = this.channel1.socket(); + assertSocketAction_Block_AfterConnect(s); + + } + + public void testSocket_NonBlock_ActionsAfterConnectBeforeFinish() + throws IOException { + assertFalse(this.channel1.isConnected());// not connected + this.channel1.configureBlocking(false); + boolean connected = channel1.connect(localAddr1); + if (!connected) { + assertFalse(this.channel1.isConnected()); + assertTrue(this.channel1.isConnectionPending()); + Socket s1 = this.channel1.socket(); + // Action of not connected + assertSocketAction_NonBlock_BeforeConnect(s1); + Socket s2 = this.channel1.socket(); + // same + assertSame(s1, s2); + } + } + + public void testSocket_NonBlock_ActionsAfterConnectAfterFinish() + throws Exception { + assertFalse(this.channel1.isConnected());// not connected + this.channel1.configureBlocking(false); + channel1.connect(localAddr1); + if (tryFinish()) { + Socket s1 = this.channel1.socket(); + assertSocketAction_NonBlock_AfterConnect(s1); + Socket s2 = this.channel1.socket(); + // same + assertSame(s1, s2); + } + } + + public void testSocket_getInetAddress() throws Exception { + Socket socket = channel1.socket(); + assertNull(socket.getInetAddress()); + + channel1.connect(localAddr1); + + assertNotNull(socket.getInetAddress()); + assertEquals(localAddr1.getAddress(), socket.getInetAddress()); + } + + public void testSocket_getRemoteSocketAddress() throws Exception { + Socket socket = channel1.socket(); + assertNull(socket.getRemoteSocketAddress()); + + channel1.connect(localAddr1); + + assertNotNull(socket.getRemoteSocketAddress()); + assertEquals(localAddr1, socket.getRemoteSocketAddress()); + } + + public void testSocket_getPort() throws Exception { + Socket socket = channel1.socket(); + assertEquals(0, socket.getPort()); + + channel1.connect(localAddr1); + + assertEquals(localAddr1.getPort(), socket.getPort()); + } + + public void testSocket_getLocalAddress() throws Exception { + Socket socket = channel1.socket(); + assertNotNull(socket.getLocalAddress()); + + channel1.connect(localAddr1); + + assertNotNull(socket.getLocalAddress()); + } + + public void testSocket_getLocalSocketAddress() throws Exception { + Socket socket = channel1.socket(); + assertNull(socket.getLocalSocketAddress()); + + channel1.connect(localAddr1); + + assertNotNull(socket.getLocalSocketAddress()); + } + + public void testSocket_getLocalPort() throws Exception { + Socket socket = channel1.socket(); + assertEquals(-1, socket.getLocalPort()); + + channel1.connect(localAddr1); + + assertTrue(-1 != socket.getLocalPort()); + assertTrue(0 != socket.getLocalPort()); + } + + public void testSocket_bind() throws Exception { + Socket socket = channel1.socket(); + socket.bind(new InetSocketAddress("127.0.0.1", 0)); + assertEquals("127.0.0.1", socket.getLocalAddress().getHostAddress()); + assertTrue(socket.getLocalPort() != -1); + } + + private void assertSocketBeforeConnect(Socket s) throws IOException { + assertFalse(s.isBound()); + assertFalse(s.isClosed()); + assertFalse(s.isConnected()); + assertFalse(s.getKeepAlive()); + try { + s.getInputStream(); + fail("Should throw SocketException."); + } catch (SocketException e) { + // OK. + } + assertFalse(s.getOOBInline()); + try { + s.getOutputStream(); + fail("Should throw SocketException."); + } catch (SocketException e) { + // OK. + } + assertEquals(-1, s.getSoLinger()); + assertFalse(s.getTcpNoDelay()); + + assertFalse(s.isInputShutdown()); + 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()); + assertTrue(s.getReceiveBufferSize() >= 8192); + assertNull(s.getRemoteSocketAddress()); + assertTrue(s.getSendBufferSize() >= 8192); + assertEquals(0, s.getSoTimeout()); + assertEquals(0, s.getTrafficClass()); + + } + + private void assertSocketAfterConnect(Socket s, InetSocketAddress address) + throws IOException { + assertTrue(s.isBound()); + assertFalse(s.isClosed()); + assertTrue(s.isConnected()); + assertFalse(s.getKeepAlive()); + + assertNotNull(s.getInputStream()); + assertNotNull(s.getOutputStream()); + + assertFalse(s.getOOBInline()); + assertEquals(-1, s.getSoLinger()); + assertFalse(s.getTcpNoDelay()); + + assertFalse(s.isInputShutdown()); + assertFalse(s.isOutputShutdown()); + + assertSame(s.getInetAddress(), address.getAddress()); + + assertEquals(s.getLocalAddress(), this.localAddr1.getAddress()); + assertEquals(s.getPort(), address.getPort()); + assertNotNull(s.getLocalSocketAddress()); + assertTrue(s.getReceiveBufferSize() >= 8192); + assertEquals(s.getRemoteSocketAddress(), (SocketAddress) address); + // assertFalse(s.getReuseAddress()); + assertTrue(s.getSendBufferSize() >= 8192); + assertEquals(0, s.getSoTimeout()); + assertEquals(0, s.getTrafficClass()); + } + + 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()); + + assertSocketAfterConnect(s, localAddr2); + + try { + s.bind(localAddr2); + fail("Should throw AlreadyConnectedException"); + } catch (AlreadyConnectedException e) { + // OK. + } + + s.close(); + assertTrue(s.isClosed()); + assertFalse(this.channel1.isOpen()); + } + + 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"); + } catch (IllegalBlockingModeException e1) { + // OK. + } + + if (this.channel1.isConnectionPending()) { + try { + s.bind(localAddr2); + fail("Should throw ConnectionPendingException"); + } catch (ConnectionPendingException e1) { + // OK. + } + } else { + try { + s.bind(localAddr2); + fail("Should throw BindException"); + } catch (BindException e1) { + // OK. + } + } + + assertFalse(this.channel1.isConnected()); + assertFalse(s.isConnected()); + + s.close(); + assertTrue(s.isClosed()); + assertFalse(this.channel1.isOpen()); + } + + private void assertSocketAction_Block_AfterConnect(Socket s) + throws IOException { + assertEquals(s.getPort(), localAddr1.getPort()); + assertTrue(this.channel1.isConnected()); + assertTrue(s.isConnected()); + try { + s.connect(localAddr2); + fail("Should throw AlreadyConnectedException"); + } catch (AlreadyConnectedException e) { + // OK. + } + + try { + s.bind(localAddr2); + fail("Should throw AlreadyConnectedException"); + } catch (AlreadyConnectedException e) { + // OK. + } + + s.close(); + assertTrue(s.isClosed()); + assertFalse(this.channel1.isOpen()); + } + + private void assertSocketAction_NonBlock_AfterConnect(Socket s) + throws IOException { + assertEquals(s.getPort(), localAddr1.getPort()); + assertTrue(this.channel1.isConnected()); + assertTrue(s.isConnected()); + + if (this.channel1.isConnectionPending()) { + try { + s.connect(localAddr2); + fail("Should throw AlreadyConnectedException"); + } catch (AlreadyConnectedException e) { + // OK. + } + } else { + try { + s.connect(localAddr2); + fail("Should throw IllegalBlockingModeException"); + } catch (IllegalBlockingModeException e) { + // OK. + } + } + + try { + s.bind(localAddr2); + fail("Should throw AlreadyConnectedException"); + } catch (AlreadyConnectedException e) { + // OK. + } + + s.close(); + assertTrue(s.isClosed()); + assertFalse(this.channel1.isOpen()); + } + + // ------------------------------------------------------------------- + // Tests for connect(), finishConnect(),isConnected(),isConnectionPending() + // These methods are very close, so we test them together, call them "CFII". + // ------------------------------------------------------------------- + /** + * connect-->finish-->close + */ + public void testCFII_Norml_NoServer_Block() throws Exception { + // ensure + ensureServerClosed(); + assertTrue(this.channel1.isBlocking()); + statusNotConnected_NotPending(); + // connect + try { + this.channel1.connect(localAddr1); + fail("Should throw a ConnectException here."); + } catch (ConnectException e) { + // OK. + } + statusChannelClosed(); + try { + this.channel1.finishConnect(); + fail("Should throw a ClosedChannelException here."); + } catch (ClosedChannelException e) { + // OK. + } + } + + /** + * connect-->finish-->close + */ + public void testCFII_Norml_NoServer_NonBlock() throws Exception { + connectNoServerNonBlock(); + + this.channel1.close(); + statusChannelClosed(); + } + + /** + * connect-->finish-->close + */ + public void testCFII_Norml_Server_Block() throws Exception { + connectServerBlock(); + + this.channel1.close(); + statusChannelClosed(); + + } + + /** + * connect-->finish-->close + */ + public void testCFII_Norml_Server_NonBlock() throws Exception { + connectServerNonBlock(); + + this.channel1.close(); + statusChannelClosed(); + } + + /** + * connect-->server closed-->finish-->close + */ + public void testCFII_ServerClosed_Block() throws Exception { + // ensure + ensureServerOpen(); + assertTrue(this.channel1.isBlocking()); + statusNotConnected_NotPending(); + // connect + assertTrue(this.channel1.connect(localAddr1)); + statusConnected_NotPending(); + + ensureServerClosed(); + + tryFinish(); + + this.channel1.close(); + statusChannelClosed(); + + } + + /** + * connect-->server closed-->finish-->close + */ + public void testCFII_ServerClosed_NonBlock() throws Exception { + // ensure + ensureServerOpen(); + this.channel1.configureBlocking(false); + statusNotConnected_NotPending(); + // connect + boolean connected = channel1.connect(localAddr1); + if (!connected) { + statusNotConnected_Pending(); + } + ensureServerClosed(); + + tryFinish(); + + this.channel1.close(); + statusChannelClosed(); + } + + /** + * connect-->finish-->server closed-->close + */ + public void testCFII_ServerClosedAfterFinish_Block() throws Exception { + connectServerBlock(); + + ensureServerClosed(); + assertTrue(this.channel1.isOpen()); + this.channel1.close(); + statusChannelClosed(); + + } + + /** + * connect-->finish-->server closed-->close + */ + public void testCFII_ServerClosedAfterFinish_NonBlock() throws Exception { + connectServerNonBlock(); + + ensureServerClosed(); + assertTrue(this.channel1.isOpen()); + this.channel1.close(); + statusChannelClosed(); + } + + /** + * no server-->connect-->server open-->finish-->close + */ + public void testCFII_ServerStartLater_Block() throws Exception { + // ensure + ensureServerClosed(); + assertTrue(this.channel1.isBlocking()); + statusNotConnected_NotPending(); + // connect + try { + this.channel1.connect(localAddr1); + fail("Should throw a ConnectException here."); + } catch (ConnectException e) { + // OK. + } + statusChannelClosed(); + ensureServerOpen(); + try { + this.channel1.finishConnect(); + fail("Should throw a ClosedChannelException here."); + } catch (ClosedChannelException e) { + // OK. + } + } + + /** + * no server-->connect-->server open-->finish-->close + */ + public void testCFII_ServerStartLater_NonBlock() throws Exception { + // ensure + ensureServerClosed(); + this.channel1.configureBlocking(false); + statusNotConnected_NotPending(); + // connect + assertFalse(this.channel1.connect(localAddr1)); + statusNotConnected_Pending(); + + ensureServerOpen(); + + try { + assertFalse(this.channel1.finishConnect()); + statusNotConnected_Pending(); + this.channel1.close(); + } catch (ConnectException e) { + // FIXME: assertEquals(e.getMessage(), "Connection refused"); + } + } + + /** + * connect-->finish-->finish-->close + */ + public void testCFII_FinishTwice_NoServer_NonBlock() throws Exception { + // ensure + ensureServerClosed(); + this.channel1.configureBlocking(false); + statusNotConnected_NotPending(); + // connect + assertFalse(this.channel1.connect(localAddr1)); + statusNotConnected_Pending(); + try { + assertFalse(this.channel1.finishConnect()); + statusNotConnected_Pending(); + assertFalse(this.channel1.finishConnect()); + statusNotConnected_Pending(); + this.channel1.close(); + } catch (ConnectException e) { + // FIXME: assertEquals(e.getMessage(), "Connection refused"); + } + statusChannelClosed(); + } + + /** + * connect-->finish-->finish-->close + */ + public void testCFII_FinishTwice_Server_Block() throws Exception { + connectServerBlock(); + tryFinish(); + this.channel1.close(); + statusChannelClosed(); + + } + + /** + * connect-->finish-->finish-->close + */ + public void testCFII_FinishTwice_Server_NonBlock() throws Exception { + connectServerNonBlock(); + tryFinish(); + this.channel1.close(); + statusChannelClosed(); + } + + /** + * connect-->finish-->connect-->close + */ + public void testCFII_ConnectAfterFinish_NoServer_Block() throws Exception { + // ensure + ensureServerClosed(); + assertTrue(this.channel1.isBlocking()); + statusNotConnected_NotPending(); + // connect + try { + this.channel1.connect(localAddr1); + fail("Should throw a ConnectException here."); + } catch (ConnectException e) { + // OK. + } + statusChannelClosed(); + try { + this.channel1.finishConnect(); + fail("Should throw a ClosedChannelException here."); + } catch (ClosedChannelException e) { + // OK. + } + statusChannelClosed(); + try { + this.channel1.connect(localAddr1); + fail("Should throw a ClosedChannelException here."); + } catch (ClosedChannelException e) { + // OK. + } + statusChannelClosed(); + } + + /** + * connect-->finish-->connect-->close + */ + public void testCFII_ConnectAfterFinish_NoServer_NonBlock() + throws Exception { + // ensure + ensureServerClosed(); + this.channel1.configureBlocking(false); + statusNotConnected_NotPending(); + // connect + assertFalse(this.channel1.connect(localAddr1)); + statusNotConnected_Pending(); + try { + assertFalse(this.channel1.finishConnect()); + statusNotConnected_Pending(); + } catch (ConnectException e) { + // FIXME: assertEquals(e.getMessage(), "Connection refused"); + } + + if (this.channel1.isOpen()) { + + try { + this.channel1.connect(localAddr1); + fail("Should throw a ConnectionPendingException here."); + } catch (ConnectionPendingException e) { + // OK. + } + statusNotConnected_Pending(); + + // connect another addr + try { + this.channel1.connect(localAddr2); + fail("Should throw a ConnectionPendingException here."); + } catch (ConnectionPendingException e) { + // OK. + } + statusNotConnected_Pending(); + + // connect if server closed + ensureServerClosed(); + + try { + this.channel1.connect(localAddr1); + fail("Should throw a ConnectionPendingException here."); + } catch (ConnectionPendingException e) { + // OK. + } + statusNotConnected_Pending(); + + this.channel1.close(); + } + statusChannelClosed(); + } + + /** + * connect-->finish-->connect-->close + */ + public void testCFII_ConnectAfterFinish_Server_Block() throws Exception { + connectServerBlock(); + + if (!this.channel1.isConnected()) { + System.err + .println("Connection fail, testCFII_ConnectAfterFinish_Server_Block is not finished."); + return; + } + + try { + this.channel1.connect(localAddr1); + fail("Should throw an AlreadyConnectedException here."); + } catch (AlreadyConnectedException e) { + // OK. + } + statusConnected_NotPending(); + + // connect another addr + try { + this.channel1.connect(localAddr2); + fail("Should throw an AlreadyConnectedException here."); + } catch (AlreadyConnectedException e) { + // OK. + } + statusConnected_NotPending(); + + // connect if server closed + ensureServerClosed(); + + try { + this.channel1.connect(localAddr1); + fail("Should throw an AlreadyConnectedException here."); + } catch (AlreadyConnectedException e) { + // OK. + } + statusConnected_NotPending(); + + this.channel1.close(); + statusChannelClosed(); + + } + + /** + * connect-->finish-->connect-->close + */ + public void testCFII_ConnectAfterFinish_Server_NonBlock() throws Exception { + connectServerNonBlock(); + + if (!this.channel1.isConnected()) { + System.err + .println("Connection fail, testCFII_ConnectAfterFinish_Server_Block is not finished."); + return; + } + try { + this.channel1.connect(localAddr1); + fail("Should throw an AlreadyConnectedException or a ConnectionPendingException here."); + } catch (AlreadyConnectedException e) { + // OK. + } + + statusConnected_NotPending(); + + // connect another addr + try { + this.channel1.connect(localAddr2); + fail("Should throw an AlreadyConnectedException here."); + } catch (AlreadyConnectedException e) { + // OK. + } + statusConnected_NotPending(); + + // connect if server closed + ensureServerClosed(); + + try { + this.channel1.connect(localAddr1); + fail("Should throw an AlreadyConnectedException here."); + } catch (AlreadyConnectedException e) { + // OK. + } + statusConnected_NotPending(); + + this.channel1.close(); + statusChannelClosed(); + } + + /** + * connect-->connect-->finish-->close + */ + public void testCFII_ConnectTwice_NoServer_NonBlock() throws Exception { + // ensure + ensureServerClosed(); + this.channel1.configureBlocking(false); + statusNotConnected_NotPending(); + // connect + assertFalse(this.channel1.connect(localAddr1)); + statusNotConnected_Pending(); + + try { + this.channel1.connect(localAddr1); + fail("Should throw a ConnectionPendingException here."); + } catch (ConnectionPendingException e) { + // OK. + } + statusNotConnected_Pending(); + + // connect another addr + try { + this.channel1.connect(localAddr2); + fail("Should throw a ConnectionPendingException here."); + } catch (ConnectionPendingException e) { + // OK. + } + statusNotConnected_Pending(); + + // connect if server closed + ensureServerClosed(); + + try { + this.channel1.connect(localAddr1); + fail("Should throw a ConnectionPendingException here."); + } catch (ConnectionPendingException e) { + // OK. + } + statusNotConnected_Pending(); + + try { + assertFalse(this.channel1.finishConnect()); + statusNotConnected_Pending(); + this.channel1.close(); + } catch (ConnectException e) { + // FIXME: assertEquals(e.getMessage(), "Connection refused"); + } + + statusChannelClosed(); + } + + /** + * connect-->connect-->finish-->close + */ + public void testCFII_ConnectTwice_Server_Block() throws Exception { + // ensure + ensureServerOpen(); + assertTrue(this.channel1.isBlocking()); + statusNotConnected_NotPending(); + // connect + assertTrue(this.channel1.connect(localAddr1)); + statusConnected_NotPending(); + + try { + this.channel1.connect(localAddr1); + fail("Should throw an AlreadyConnectedException here."); + } catch (AlreadyConnectedException e) { + // OK. + } + statusConnected_NotPending(); + + // connect another addr + try { + this.channel1.connect(localAddr2); + fail("Should throw an AlreadyConnectedException here."); + } catch (AlreadyConnectedException e) { + // OK. + } + statusConnected_NotPending(); + + // connect if server closed + ensureServerClosed(); + + try { + this.channel1.connect(localAddr1); + fail("Should throw an AlreadyConnectedException here."); + } catch (AlreadyConnectedException e) { + // OK. + } + statusConnected_NotPending(); + + tryFinish(); + + this.channel1.close(); + statusChannelClosed(); + + } + + /** + * connect-->connect-->finish-->close + */ + public void testCFII_ConnectTwice_Server_NonBlock() throws Exception { + // ensure + ensureServerOpen(); + this.channel1.configureBlocking(false); + statusNotConnected_NotPending(); + // connect + boolean connected = channel1.connect(localAddr1); + if (!connected) { + statusNotConnected_Pending(); + + try { + this.channel1.connect(localAddr1); + fail("Should throw a ConnectionPendingException here."); + } catch (ConnectionPendingException e) { + // OK. + } + statusNotConnected_Pending(); + + // connect another addr + try { + this.channel1.connect(localAddr2); + fail("Should throw a ConnectionPendingException here."); + } catch (ConnectionPendingException e) { + // OK. + } + statusNotConnected_Pending(); + + // connect if server closed + ensureServerClosed(); + + try { + this.channel1.connect(localAddr1); + fail("Should throw a ConnectionPendingException here."); + } catch (ConnectionPendingException e) { + // OK. + } + statusNotConnected_Pending(); + } + tryFinish(); + + this.channel1.close(); + statusChannelClosed(); + } + + /** + * finish-->connect-->finish-->close + */ + public void testCFII_FinishFirst_NoServer_Block() throws Exception { + // ensure + ensureServerClosed(); + assertTrue(this.channel1.isBlocking()); + statusNotConnected_NotPending(); + // finish + try { + this.channel1.finishConnect(); + fail("Should throw NoConnectionPendingException"); + } catch (NoConnectionPendingException e) { + // OK. + } + statusNotConnected_NotPending(); + // connect + try { + this.channel1.connect(localAddr1); + fail("Should throw a ConnectException here."); + } catch (ConnectException e) { + // OK. + } + statusChannelClosed(); + try { + this.channel1.finishConnect(); + fail("Should throw a ClosedChannelException here."); + } catch (ClosedChannelException e) { + // OK. + } + statusChannelClosed(); + } + + /** + * finish-->connect-->finish-->close + */ + public void testCFII_FinishFirst_NoServer_NonBlock() throws Exception { + // ensure + ensureServerClosed(); + this.channel1.configureBlocking(false); + statusNotConnected_NotPending(); + // finish + try { + this.channel1.finishConnect(); + fail("Should throw NoConnectionPendingException"); + } catch (NoConnectionPendingException e) { + // OK. + } + statusNotConnected_NotPending(); + // connect + assertFalse(this.channel1.connect(localAddr1)); + statusNotConnected_Pending(); + + try { + assertFalse(this.channel1.finishConnect()); + statusNotConnected_Pending(); + this.channel1.close(); + } catch (ConnectException e) { + // FIXME: assertEquals(e.getMessage(), "Connection refused"); + } + + statusChannelClosed(); + } + + /** + * finish-->connect-->finish-->close + */ + public void testCFII_FinishFirst_Server_Block() throws Exception { + // ensure + ensureServerOpen(); + assertTrue(this.channel1.isBlocking()); + statusNotConnected_NotPending(); + // finish + try { + this.channel1.finishConnect(); + fail("Should throw NoConnectionPendingException"); + } catch (NoConnectionPendingException e) { + // OK. + } + statusNotConnected_NotPending(); + // connect + assertTrue(this.channel1.connect(localAddr1)); + statusConnected_NotPending(); + + tryFinish(); + + this.channel1.close(); + statusChannelClosed(); + + } + + /** + * finish-->connect-->finish-->close + */ + public void testCFII_FinishFirst_Server_NonBlock() throws Exception { + // ensure + ensureServerOpen(); + this.channel1.configureBlocking(false); + statusNotConnected_NotPending(); + // finish + try { + this.channel1.finishConnect(); + fail("Should throw NoConnectionPendingException"); + } catch (NoConnectionPendingException e) { + // OK. + } + statusNotConnected_NotPending(); + // connect + boolean connected = channel1.connect(localAddr1); + if (!connected) { + statusNotConnected_Pending(); + } + tryFinish(); + + this.channel1.close(); + statusChannelClosed(); + } + + public void testCFII_Null() throws Exception { + statusNotConnected_NotPending(); + try { + this.channel1.connect(null); + fail("Should throw an IllegalArgumentException here."); + } catch (IllegalArgumentException e) { + // OK. + } + } + + public void testCFII_UnsupportedType() throws Exception { + class SubSocketAddress extends SocketAddress { + private static final long serialVersionUID = 1L; + + //empty + public SubSocketAddress() { + super(); + } + } + statusNotConnected_NotPending(); + SocketAddress newTypeAddress = new SubSocketAddress(); + try { + this.channel1.connect(newTypeAddress); + fail("Should throw an UnsupportedAddressTypeException here."); + } catch (UnsupportedAddressTypeException e) { + // OK. + } + } + + public void testCFII_Unresolved() throws IOException { + statusNotConnected_NotPending(); + InetSocketAddress unresolved = new InetSocketAddress( + "unresolved address", 1080); + try { + this.channel1.connect(unresolved); + fail("Should throw an UnresolvedAddressException here."); + } catch (UnresolvedAddressException e) { + // OK. + } + } + + public void testCFII_EmptyHost() throws Exception { + statusNotConnected_NotPending(); + ServerSocket server = new ServerSocket(0); + int port = server.getLocalPort(); + server.close(); + try { + this.channel1.connect(new InetSocketAddress("", port)); + fail("Should throw ConnectException"); + } catch (ConnectException e) { + // correct + } + } + + public void testCFII_CloseFirst() throws Exception { + this.channel1.close(); + statusChannelClosed(); + ensureServerOpen(); + try { + this.channel1.connect(localAddr1); + fail("Should throw ClosedChannelException."); + } catch (ClosedChannelException e) { + // OK. + } + statusChannelClosed(); + try { + this.channel1.finishConnect(); + fail("Should throw ClosedChannelException."); + } catch (ClosedChannelException e) { + // OK. + } + statusChannelClosed(); + try { + this.channel1.configureBlocking(false); + fail("Should throw ClosedChannelException."); + } catch (ClosedChannelException e) { + // OK. + } + statusChannelClosed(); + } + + public void testCFII_StatusAfterFinish() throws Exception { + // 1. close server, finish must return false, check the status + ensureServerClosed(); + + // 1.1 block mode + assertTrue(this.channel1.isBlocking()); + try { + channel1.connect(localAddr1); + fail("Should throw ConnectException"); + } catch (ConnectException e) { + // OK. + } + assertFalse(this.channel1.isOpen()); + + assertFalse(this.channel1.isOpen()); + assertTrue(this.channel1.isBlocking()); + assertFalse(this.channel1.isConnectionPending()); + + // 1.2 non block mode + this.channel1 = SocketChannel.open(); + this.channel1.configureBlocking(false); + assertFalse(this.channel1.connect(localAddr1)); + try { + assertFalse(this.channel1.finishConnect()); + statusNotConnected_Pending(); + this.channel1.close(); + } catch (ConnectException e) { + System.out.println(e.getMessage()); + } + + // 2. start server, finish usually return true, check the status + ensureServerOpen(); + + // 2.1 block mode + this.channel1 = SocketChannel.open(); + assertTrue(this.channel1.isBlocking()); + assertTrue(this.channel1.connect(localAddr1)); + assertTrue(this.channel1.finishConnect()); + statusConnected_NotPending(); + this.channel1.close(); + + // 2.2 non block mode + this.channel1 = SocketChannel.open(); + this.channel1.configureBlocking(false); + assertFalse(this.channel1.connect(localAddr1)); + tryFinish(); + this.channel1.close(); + } + + private void ensureServerClosed() throws IOException { + if (null != this.server1) { + this.server1.close(); + assertTrue(this.server1.isClosed()); + } + if (null != this.server2) { + this.server2.close(); + assertTrue(this.server2.isClosed()); + } + } + + private void ensureServerOpen() throws IOException { + ensureServerClosed(); + this.server1 = new ServerSocket(localAddr1.getPort()); + this.server2 = new ServerSocket(localAddr2.getPort()); + assertTrue(this.server1.isBound()); + assertTrue(this.server2.isBound()); + } + + private void connectNoServerNonBlock() throws Exception { + // ensure + ensureServerClosed(); + this.channel1.configureBlocking(false); + statusNotConnected_NotPending(); + // connect + assertFalse(this.channel1.connect(localAddr1)); + statusNotConnected_Pending(); + try { + assertFalse(this.channel1.finishConnect()); + statusNotConnected_Pending(); + } catch (ConnectException e) { + // FIXME: assertEquals(e.getMessage(), "Connection refused"); + } + } + + private void connectServerNonBlock() throws Exception { + // ensure + ensureServerOpen(); + this.channel1.configureBlocking(false); + statusNotConnected_NotPending(); + // connect + boolean connected = channel1.connect(localAddr1); + if (!connected) { + statusNotConnected_Pending(); + } + tryFinish(); + } + + private void connectServerBlock() throws Exception { + // ensure + ensureServerOpen(); + assertTrue(this.channel1.isBlocking()); + statusNotConnected_NotPending(); + // connect + assertTrue(this.channel1.connect(localAddr1)); + statusConnected_NotPending(); + tryFinish(); + } + + private void statusChannelClosed() { + assertFalse(this.channel1.isConnected()); + assertFalse(this.channel1.isConnectionPending()); + assertFalse(this.channel1.isOpen()); + } + + private void statusNotConnected_NotPending() { + assertFalse(this.channel1.isConnected()); + assertFalse(this.channel1.isConnectionPending()); + assertTrue(this.channel1.isOpen()); + } + + private void statusNotConnected_Pending() { + assertFalse(this.channel1.isConnected()); + assertTrue(this.channel1.isConnectionPending()); + assertTrue(this.channel1.isOpen()); + } + + private void statusConnected_NotPending() { + assertTrue(this.channel1.isConnected()); + assertFalse(this.channel1.isConnectionPending()); + assertTrue(this.channel1.isOpen()); + } + + private boolean tryFinish() throws IOException { + /* + * the result of finish will be asserted in multi-thread tests. + */ + boolean connected = false; + assertTrue(this.channel1.isOpen()); + try { + connected = this.channel1.finishConnect(); + } catch (SocketException e) { + // Finish connection failed, probably due to reset by peer error. + } + if (connected) { + statusConnected_NotPending(); + } + return connected; + } + + // ------------------------------------------------------------------- + // Original tests. Test method for CFII with real data. + // ------------------------------------------------------------------- + + /** + * + * 'SocketChannelImpl.connect(SocketAddress)' + */ + public void testCFII_Data_ConnectWithServer() throws Exception { + ensureServerOpen(); + java.nio.ByteBuffer writeBuf = java.nio.ByteBuffer + .allocate(CAPACITY_NORMAL); + java.nio.ByteBuffer[] writeBufArr = new java.nio.ByteBuffer[1]; + writeBufArr[0] = java.nio.ByteBuffer.allocate(CAPACITY_NORMAL); + assertFalse(this.channel1.isRegistered()); + assertTrue(this.channel1.isBlocking()); + + this.channel1.connect(localAddr1); + + assertTrue(this.channel1.isBlocking()); + assertTrue(this.channel1.isConnected()); + assertFalse(this.channel1.isConnectionPending()); + assertTrue(this.channel1.isOpen()); + assertEquals(CAPACITY_NORMAL, this.channel1.write(writeBuf)); + assertEquals(CAPACITY_NORMAL, this.channel1.write(writeBufArr, 0, 1)); + + this.channel1.configureBlocking(false); + try { + this.channel1.connect(localAddr1); + fail("Should throw AlreadyConnectedException"); + } catch (AlreadyConnectedException e) { + // correct + } + + assertFalse(this.channel1.isRegistered()); + tryFinish(); + } + + /* + * Test method for 'SocketChannelImpl.connect(SocketAddress)' + */ + public void testCFII_Data_ConnectWithServer_nonBlocking() throws Exception { + ensureServerOpen(); + java.nio.ByteBuffer writeBuf = java.nio.ByteBuffer + .allocate(CAPACITY_NORMAL); + java.nio.ByteBuffer[] writeBufArr = new java.nio.ByteBuffer[1]; + writeBufArr[0] = java.nio.ByteBuffer.allocate(CAPACITY_NORMAL); + assertFalse(this.channel1.isRegistered()); + assertTrue(this.channel1.isBlocking()); + this.channel1.configureBlocking(false); + this.channel1.connect(localAddr1); + + assertFalse(this.channel1.isBlocking()); + boolean connected = channel1.isConnected(); + if (!connected) { + assertTrue(this.channel1.isConnectionPending()); + assertTrue(this.channel1.isOpen()); + } + if (tryFinish()) { + assertEquals(CAPACITY_NORMAL, this.channel1.write(writeBuf)); + assertEquals(CAPACITY_NORMAL, this.channel1.write(writeBufArr, 0, 1)); + + this.channel1.configureBlocking(false); + try { + this.channel1.connect(localAddr1); + fail("Should throw AlreadyConnectedException"); + } catch (AlreadyConnectedException e) { + // correct + } + } + + assertFalse(this.channel1.isRegistered()); + tryFinish(); + } + + /* + * Test method for 'SocketChannelImpl.finishConnect()' + */ + public void testCFII_Data_FinishConnect_nonBlocking() throws IOException { + ensureServerOpen(); + + java.nio.ByteBuffer writeBuf = java.nio.ByteBuffer + .allocate(CAPACITY_NORMAL); + java.nio.ByteBuffer[] writeBufArr = new java.nio.ByteBuffer[1]; + writeBufArr[0] = java.nio.ByteBuffer.allocate(CAPACITY_NORMAL); + + this.channel1.configureBlocking(false); + try { + this.channel1.finishConnect(); + fail("Should throw NoConnectionPendingException"); + } catch (NoConnectionPendingException e) { + // correct + } + boolean connected = channel1.connect(localAddr1); + if (!connected) { + assertFalse(this.channel1.isBlocking()); + assertFalse(this.channel1.isConnected()); + assertTrue(this.channel1.isConnectionPending()); + assertTrue(this.channel1.isOpen()); + } + this.server1.accept(); + if (tryFinish()) { + assertEquals(CAPACITY_NORMAL, this.channel1.write(writeBuf)); + assertEquals(CAPACITY_NORMAL, this.channel1.write(writeBufArr, 0, 1)); + try { + this.channel1.connect(localAddr1); + fail("Should throw AlreadyConnectedException"); + } catch (AlreadyConnectedException e) { + // correct + } + } + assertFalse(this.channel1.isRegistered()); + tryFinish(); + } + + 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); + fail("Should throw ConnectException"); + } catch (ConnectException e) { + // correct + } + assertTrue(this.channel1.isOpen()); + assertFalse(this.channel1.isBlocking()); + assertFalse(this.channel1.isConnectionPending()); + this.channel1.configureBlocking(true); + try { + this.channel1.finishConnect(); + fail("Should throw NoConnectionPendingException"); + } catch (NoConnectionPendingException e) { + // correct + } + try { + this.channel1.connect(localAddr2); + fail("Should throw ConnectException"); + } catch (ConnectException e) { + // correct + } + + assertTrue(this.channel1.isBlocking()); + try { + this.channel1.finishConnect(); + fail("Should throw ClosedChannelException"); + } catch (ClosedChannelException e) { + // correct + } + assertFalse(this.channel1.isConnected()); + // finish after finish OK + assertFalse(this.channel1.isConnectionPending()); + this.channel1 = SocketChannel.open(); + this.channel1.configureBlocking(false); + this.channel1.connect(localAddr1); + assertFalse(this.channel1.isConnected()); + ensureServerOpen(); + // cannot connect? + try { + assertFalse(this.channel1.finishConnect()); + assertFalse(this.channel1.isBlocking()); + assertFalse(this.channel1.isConnected()); + assertTrue(this.channel1.isConnectionPending()); + assertTrue(this.channel1.isOpen()); + try { + this.channel1.connect(localAddr1); + fail("Should throw ConnectionPendingException"); + } catch (ConnectionPendingException e) { + // correct + } + this.channel1.configureBlocking(true); + try { + this.channel1.connect(localAddr1); + fail("Should throw ConnectionPendingException"); + } catch (ConnectionPendingException e) { + // correct + } + tryFinish(); + } catch (ConnectException e) { + // FIXME: assertEquals(e.getMessage(), "Connection refused"); + } + } + + 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(); + fail("Should throw NoConnectionPendingException"); + } catch (NoConnectionPendingException e) { + // correct + } + try { + this.channel1.connect(localAddr1); + fail("Should throw ConnectException"); + } catch (ConnectException e) { + // correct + } + + try { + this.channel1.finishConnect(); + fail("Should throw ClosedChannelException"); + } catch (ClosedChannelException e) { + // correct + } + assertFalse(this.channel1.isConnected()); + // finish after finish OK + assertFalse(this.channel1.isConnectionPending()); + this.channel1 = SocketChannel.open(); + this.channel1.configureBlocking(false); + this.channel1.connect(localAddr1); + assertFalse(this.channel1.isConnected()); + ensureServerOpen(); + // cannot connect? + try { + assertFalse(this.channel1.finishConnect()); + assertFalse(this.channel1.isBlocking()); + assertFalse(this.channel1.isConnected()); + assertTrue(this.channel1.isConnectionPending()); + assertTrue(this.channel1.isOpen()); + try { + this.channel1.connect(localAddr1); + fail("Should throw ConnectionPendingException"); + } catch (ConnectionPendingException e) { + // correct + } + this.channel1.configureBlocking(true); + try { + this.channel1.connect(localAddr1); + fail("Should throw ConnectionPendingException"); + } catch (ConnectionPendingException e) { + // correct + } + tryFinish(); + } catch (ConnectException e) { + // FIXME: assertEquals(e.getMessage(), "Connection refused"); + } + } + + public void testCFII_Data_FinishConnect_Blocking() throws IOException { + ensureServerOpen(); + java.nio.ByteBuffer writeBuf = java.nio.ByteBuffer + .allocate(CAPACITY_NORMAL); + 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(); + fail("Should throw NoConnectionPendingException"); + } catch (NoConnectionPendingException e) { + // correct + } + + this.channel1.connect(localAddr1); + + assertTrue(this.channel1.isConnected()); + assertFalse(this.channel1.isConnectionPending()); + assertTrue(this.channel1.isOpen()); + if (tryFinish()) { + assertEquals(CAPACITY_NORMAL, this.channel1.write(writeBuf)); + assertEquals(CAPACITY_NORMAL, this.channel1.write(writeBufArr, 0, 1)); + + try { + this.channel1.connect(localAddr1); + fail("Should throw AlreadyConnectedException"); + } catch (AlreadyConnectedException e) { + // correct + } + } + assertFalse(this.channel1.isRegistered()); + tryFinish(); + } + + /** + * Regression test for Harmony-1947. + */ + public void test_finishConnect() throws Exception { + SocketAddress address = new InetSocketAddress("localhost", 0); + + ServerSocketChannel theServerChannel = ServerSocketChannel.open(); + ServerSocket serversocket = theServerChannel.socket(); + serversocket.setReuseAddress(true); + // Bind the socket + serversocket.bind(address); + + boolean doneNonBlockingConnect = false; + // Loop so that we make sure we're definitely testing finishConnect() + while (!doneNonBlockingConnect) { + channel1 = SocketChannel.open(); + + // Set the SocketChannel to non-blocking so that connect(..) does + // not block + channel1.configureBlocking(false); + boolean connected = channel1.connect(new InetSocketAddress("localhost",serversocket.getLocalPort())); + if (!connected) { + // Now set the SocketChannel back to blocking so that + // finishConnect() blocks. + channel1.configureBlocking(true); + doneNonBlockingConnect = channel1.finishConnect(); + } + if (doneNonBlockingConnect) { + tryFinish(); + } + channel1.close(); + } + if (!serversocket.isClosed()) { + serversocket.close(); + } + } + + // ------------------------------------------------------------------- + // End of original tests. Test method for CFII with real data. + // ------------------------------------------------------------------- + + /** + * @tests java.nio.channels.SocketChannel#read(ByteBuffer) + */ + public void test_readLjava_nio_ByteBuffer_Blocking() throws IOException { + // initialize write content + byte[] writeContent = new byte[CAPACITY_NORMAL]; + for (int i = 0; i < writeContent.length; i++) { + writeContent[i] = (byte) i; + } + // establish connection + channel1.connect(localAddr1); + Socket acceptedSocket = server1.accept(); + + // use OutputStream.write to send CAPACITY_NORMAL bytes data + OutputStream out = acceptedSocket.getOutputStream(); + out.write(writeContent); + // use close to guarantee all data is sent + acceptedSocket.close(); + + ByteBuffer readContent = ByteBuffer.allocate(CAPACITY_NORMAL + 1); + int totalCount = 0; + int count = 0; + long startTime = System.currentTimeMillis(); + // use SocketChannel.read to read data + while (totalCount <= CAPACITY_NORMAL) { + count = channel1.read(readContent); + if (EOF == count) { + break; + } + totalCount += 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. For + // blocking read, it possibly returns 0 in some cases. + assertTimeout(startTime, TIMEOUT); + } + assertEquals(CAPACITY_NORMAL, totalCount); + readContent.flip(); + for (int i = 0; i < CAPACITY_NORMAL; i++) { + assertEquals(writeContent[i], readContent.get()); + } + } + + /** + * @tests java.nio.channels.SocketChannel#read(ByteBuffer) + */ + public void test_readLjava_nio_ByteBuffer_Nonblocking() throws IOException { + // initialize write content + byte[] writeContent = new byte[CAPACITY_NORMAL]; + for (int i = 0; i < writeContent.length; i++) { + writeContent[i] = (byte) i; + } + + // establish connection + channel1.connect(localAddr1); + Socket acceptedSocket = server1.accept(); + // use OutputStream.write to write CAPACITY_NORMAL bytes data. + OutputStream out = acceptedSocket.getOutputStream(); + out.write(writeContent); + // use close to guarantee all data is sent + acceptedSocket.close(); + + channel1.configureBlocking(false); + ByteBuffer readContent = ByteBuffer.allocate(CAPACITY_NORMAL + 1); + int totalCount = 0; + int count = 0; + long startTime = System.currentTimeMillis(); + // use SocketChannel.read to read data + while (totalCount <= CAPACITY_NORMAL) { + count = channel1.read(readContent); + if (EOF == count) { + break; + } + totalCount += 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. + assertTimeout(startTime, TIMEOUT); + } + + // assert read content + assertEquals(CAPACITY_NORMAL, totalCount); + assertEquals(CAPACITY_NORMAL, readContent.position()); + readContent.flip(); + for (int i = 0; i < CAPACITY_NORMAL; i++) { + assertEquals(writeContent[i], readContent.get()); + } + } + + /** + * @tests java.nio.channels.SocketChannel#write(ByteBuffer) + */ + public void test_writeLjava_nio_ByteBuffer_Blocking() throws IOException { + // initialize write content + ByteBuffer writeContent = ByteBuffer.allocate(CAPACITY_NORMAL); + for (int i = 0; i < CAPACITY_NORMAL; i++) { + writeContent.put((byte) i); + } + writeContent.flip(); + // establish connection + channel1.connect(localAddr1); + Socket acceptedSocket = server1.accept(); + + // use SocketChannel.write(ByteBuffer) to write CAPACITY_NORMAL bytes + // data + int writtenCount = channel1.write(writeContent); + // assert written count and ByteBuffer position + assertEquals(CAPACITY_NORMAL, writtenCount); + assertEquals(CAPACITY_NORMAL, writeContent.position()); + // use close to guarantee all data is sent + channel1.close(); + + InputStream in = acceptedSocket.getInputStream(); + int totalCount = 0; + int count = 0; + byte[] readContent = new byte[CAPACITY_NORMAL + 1]; + // 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. + acceptedSocket.setSoTimeout(TIMEOUT); + + // use InputStream.read to read data. + while (totalCount <= CAPACITY_NORMAL) { + count = in.read(readContent, totalCount, readContent.length + - totalCount); + if (EOF == count) { + break; + } + totalCount += count; + } + + // assert read content + assertEquals(CAPACITY_NORMAL, totalCount); + writeContent.flip(); + for (int i = 0; i < CAPACITY_NORMAL; i++) { + assertEquals(writeContent.get(), readContent[i]); + } + } + + /** + * @tests java.nio.channels.SocketChannel#write(ByteBuffer) + */ + public void test_writeLjava_nio_ByteBuffer_NonBlocking() throws Exception { + // initialize write content + ByteBuffer writeContent = ByteBuffer.allocate(CAPACITY_NORMAL); + for (int i = 0; i < CAPACITY_NORMAL; i++) { + writeContent.put((byte) i); + } + writeContent.flip(); + + // establish connection + channel1.connect(localAddr1); + Socket acceptedSocket = server1.accept(); + + channel1.configureBlocking(false); + int writtenTotalCount = 0; + int writtenCount = 0; + long startTime = System.currentTimeMillis(); + // use SocketChannel.write(ByteBuffer) to write CAPACITY_NORMAL bytes + while (writtenTotalCount < CAPACITY_NORMAL) { + writtenCount = channel1.write(writeContent); + writtenTotalCount += writtenCount; + // if the channel could not finish writing in TIMEOUT ms, the + // test fails. It is used to guarantee the test never hangs even + // if there are bugs of SocketChannel implementation. + assertTimeout(startTime, TIMEOUT); + } + // assert written count and ByteBuffer position + assertEquals(CAPACITY_NORMAL, writtenTotalCount); + assertEquals(CAPACITY_NORMAL, writeContent.position()); + // use close to guarantee all data is sent + channel1.close(); + + InputStream in = acceptedSocket.getInputStream(); + byte[] readContent = new byte[CAPACITY_NORMAL + 1]; + int totalCount = 0; + int count = 0; + // 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. + acceptedSocket.setSoTimeout(TIMEOUT); + // use InputStream.read to read data. + while (totalCount <= CAPACITY_NORMAL) { + count = in.read(readContent, totalCount, readContent.length + - totalCount); + if (EOF == count) { + break; + } + totalCount += count; + } + // assert read content + assertEquals(CAPACITY_NORMAL, totalCount); + writeContent.flip(); + for (int i = 0; i < CAPACITY_NORMAL; i++) { + assertEquals(writeContent.get(), readContent[i]); + } + } + + /* + * Fails if the difference between current time and start time is greater + * than timeout. + */ + private void assertTimeout(long startTime, long timeout) { + long currentTime = System.currentTimeMillis(); + if ((currentTime - startTime) > timeout) { + fail("Timeout"); + } + } + + // ------------------------------------------------- + // Test for read/write but no real data expressed + // ------------------------------------------------- + + public void testReadByteBuffer() throws Exception { + assertTrue(this.server1.isBound()); + java.nio.ByteBuffer readBuf = java.nio.ByteBuffer + .allocate(CAPACITY_NORMAL); + assertFalse(this.channel1.isRegistered()); + assertTrue(this.channel1.isBlocking()); + assertFalse(this.channel1.isConnected()); + assertFalse(this.channel1.isConnectionPending()); + assertTrue(this.channel1.isOpen()); + // note: blocking-mode will make the read process endless! + this.channel1.configureBlocking(false); + try { + channel1.read(readBuf); + fail("Should throw NotYetConnectedException"); + } catch (NotYetConnectedException e) { + // correct + } + boolean connected = this.channel1.connect(localAddr1); + if (!connected) { + assertFalse(this.channel1.isBlocking()); + assertTrue(this.channel1.isConnectionPending()); + assertFalse(this.channel1.isConnected()); + } + if (tryFinish()) { + assertEquals(0, this.channel1.read(readBuf)); + } + + this.channel1.close(); + try { + channel1.read(readBuf); + fail("Should throw ClosedChannelException"); + } catch (ClosedChannelException e) { + // correct + } + } + + public void testReadByteBuffer_Direct() throws Exception { + assertTrue(this.server1.isBound()); + java.nio.ByteBuffer readBuf = java.nio.ByteBuffer + .allocateDirect(CAPACITY_NORMAL); + assertFalse(this.channel1.isRegistered()); + assertTrue(this.channel1.isBlocking()); + assertFalse(this.channel1.isConnected()); + assertFalse(this.channel1.isConnectionPending()); + assertTrue(this.channel1.isOpen()); + // note: blocking-mode will make the read process endless! + this.channel1.configureBlocking(false); + try { + channel1.read(readBuf); + fail("Should throw NotYetConnectedException"); + } catch (NotYetConnectedException e) { + // correct + } + boolean connected = this.channel1.connect(localAddr1); + if (!connected) { + assertFalse(this.channel1.isBlocking()); + assertTrue(this.channel1.isConnectionPending()); + assertFalse(this.channel1.isConnected()); + } + if (tryFinish()) { + assertEquals(0, this.channel1.read(readBuf)); + } + + this.channel1.close(); + try { + channel1.read(readBuf); + fail("Should throw ClosedChannelException"); + } catch (ClosedChannelException e) { + // correct + } + } + + public void testReadByteBuffer_Direct2() throws IOException { + byte[] request = new byte[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; + ByteBuffer buffer = ByteBuffer.allocateDirect(128); + + ServerSocketChannel server = ServerSocketChannel.open(); + server.socket().bind( + new InetSocketAddress(InetAddress.getLocalHost(), 0), 5); + Socket client = new Socket(InetAddress.getLocalHost(), server.socket() + .getLocalPort()); + client.setTcpNoDelay(false); + Socket worker = server.socket().accept(); + SocketChannel workerChannel = worker.getChannel(); + + OutputStream out = client.getOutputStream(); + out.write(request); + out.close(); + + buffer.limit(5); + int bytesRead = workerChannel.read(buffer); + assertEquals(5, bytesRead); + assertEquals(5, buffer.position()); + + buffer.limit(request.length); + bytesRead = workerChannel.read(buffer); + assertEquals(6, bytesRead); + + buffer.flip(); + assertEquals(request.length, buffer.limit()); + + assertEquals(ByteBuffer.wrap(request), buffer); + + client.close(); + worker.close(); + server.close(); + } + + public void testReadByteBuffer_BufNull() throws Exception { + assertTrue(this.server1.isBound()); + java.nio.ByteBuffer readBuf = java.nio.ByteBuffer.allocate(0); + // note: blocking-mode will make the read process endless! + this.channel1.configureBlocking(false); + try { + channel1.read((java.nio.ByteBuffer) null); + fail("Should throw NPE"); + } catch (NullPointerException e) { + // correct + } + this.channel1.connect(localAddr1); + if (tryFinish()) { + try { + this.channel1.read((java.nio.ByteBuffer) null); + fail("Should throw NPE"); + } catch (NullPointerException e) { + // correct + } + assertEquals(0, this.channel1.read(readBuf)); + } + this.server1.close(); + try { + channel1.read((java.nio.ByteBuffer) null); + fail("Should throw NPE"); + } catch (NullPointerException e) { + // correct + } + } + + /* + * SocketChannelImpl.read(ByteBuffer[], int, int)' + */ + public void testReadByteBufferArrayIntInt() throws Exception { + assertTrue(this.server1.isBound()); + java.nio.ByteBuffer[] readBuf = new java.nio.ByteBuffer[2]; + readBuf[0] = java.nio.ByteBuffer.allocate(CAPACITY_NORMAL); + readBuf[1] = java.nio.ByteBuffer.allocate(CAPACITY_NORMAL); + assertFalse(this.channel1.isRegistered()); + assertTrue(this.channel1.isBlocking()); + assertFalse(this.channel1.isConnected()); + assertFalse(this.channel1.isConnectionPending()); + assertTrue(this.channel1.isOpen()); + // note: blocking-mode will make the read process endless! + this.channel1.configureBlocking(false); + try { + channel1.read(readBuf, 0, 1); + fail("Should throw NotYetConnectedException"); + } catch (NotYetConnectedException e) { + // correct + } + boolean connected = this.channel1.connect(localAddr1); + if (!connected) { + assertFalse(this.channel1.isBlocking()); + assertTrue(this.channel1.isConnectionPending()); + assertFalse(this.channel1.isConnected()); + } + if (tryFinish()) { + assertEquals(0, this.channel1.read(readBuf, 0, 1)); + assertEquals(0, this.channel1.read(readBuf, 0, 2)); + } + + this.channel1.close(); + try { + channel1.read(readBuf, 0, 1); + fail("Should throw ClosedChannelException"); + } catch (ClosedChannelException e) { + // correct + } + } + + /* + * SocketChannelImpl.read(ByteBuffer[], int, int)' + */ + public void testReadByteBufferArrayIntInt_Direct() throws Exception { + assertTrue(this.server1.isBound()); + java.nio.ByteBuffer[] readBuf = new java.nio.ByteBuffer[2]; + readBuf[0] = java.nio.ByteBuffer.allocateDirect(CAPACITY_NORMAL); + readBuf[1] = java.nio.ByteBuffer.allocateDirect(CAPACITY_NORMAL); + assertFalse(this.channel1.isRegistered()); + assertTrue(this.channel1.isBlocking()); + assertFalse(this.channel1.isConnected()); + assertFalse(this.channel1.isConnectionPending()); + assertTrue(this.channel1.isOpen()); + // note: blocking-mode will make the read process endless! + this.channel1.configureBlocking(false); + try { + channel1.read(readBuf, 0, 1); + fail("Should throw NotYetConnectedException"); + } catch (NotYetConnectedException e) { + // correct + } + boolean connected = this.channel1.connect(localAddr1); + if (!connected) { + assertFalse(this.channel1.isBlocking()); + assertTrue(this.channel1.isConnectionPending()); + assertFalse(this.channel1.isConnected()); + } + if (tryFinish()) { + assertEquals(0, this.channel1.read(readBuf, 0, 1)); + assertEquals(0, this.channel1.read(readBuf, 0, 2)); + } + + this.channel1.close(); + try { + channel1.read(readBuf, 0, 1); + fail("Should throw ClosedChannelException"); + } catch (ClosedChannelException e) { + // correct + } + } + + public void testReadByteBufferArrayIntInt_BufNull() throws Exception { + assertTrue(this.server1.isBound()); + java.nio.ByteBuffer[] readBuf = new java.nio.ByteBuffer[2]; + readBuf[0] = java.nio.ByteBuffer.allocate(CAPACITY_NORMAL); + assertFalse(this.channel1.isRegistered()); + assertTrue(this.channel1.isBlocking()); + assertFalse(this.channel1.isConnected()); + assertFalse(this.channel1.isConnectionPending()); + assertTrue(this.channel1.isOpen()); + // note: blocking-mode will make the read process endless! + this.channel1.configureBlocking(false); + try { + channel1.read(null, 0, 0); + fail("Should throw NPE"); + } catch (NullPointerException e) { + // correct + } + this.channel1.connect(localAddr1); + if (tryFinish()) { + + try { + channel1.read(null, 0, 0); + fail("Should throw NPE"); + } catch (NullPointerException e) { + // correct + } + try { + channel1.read(readBuf, 0, 2); + fail("Should throw NPE"); + } catch (NullPointerException e) { + // correct + } + + assertEquals(0, this.channel1.read(readBuf, 0, 1)); + } + this.channel1.close(); + try { + channel1.read(null, 0, 1); + fail("Should throw NPE"); + } catch (NullPointerException e) { + // correct + } + } + + public void testWriteByteBuffer() throws IOException { + assertTrue(this.server1.isBound()); + java.nio.ByteBuffer writeBuf = java.nio.ByteBuffer + .allocate(CAPACITY_NORMAL); + assertFalse(this.channel1.isRegistered()); + assertTrue(this.channel1.isBlocking()); + assertFalse(this.channel1.isConnected()); + assertFalse(this.channel1.isConnectionPending()); + assertTrue(this.channel1.isOpen()); + try { + channel1.write(writeBuf); + fail("Should throw NotYetConnectedException"); + } catch (NotYetConnectedException e) { + // correct + } + this.channel1.connect(localAddr1); + assertTrue(this.channel1.isBlocking()); + assertTrue(this.channel1.isConnected()); + assertFalse(this.channel1.isConnectionPending()); + assertTrue(this.channel1.isOpen()); + assertEquals(CAPACITY_NORMAL, this.channel1.write(writeBuf)); + + this.channel1.close(); + try { + channel1.write(writeBuf); + fail("Should throw ClosedChannelException"); + } catch (ClosedChannelException e) { + // correct + } + } + + public void testWriteByteBuffer_Direct() throws IOException { + assertTrue(this.server1.isBound()); + java.nio.ByteBuffer writeBuf = java.nio.ByteBuffer + .allocateDirect(CAPACITY_NORMAL); + assertFalse(this.channel1.isRegistered()); + assertTrue(this.channel1.isBlocking()); + assertFalse(this.channel1.isConnected()); + assertFalse(this.channel1.isConnectionPending()); + assertTrue(this.channel1.isOpen()); + try { + channel1.write(writeBuf); + fail("Should throw NotYetConnectedException"); + } catch (NotYetConnectedException e) { + // correct + } + this.channel1.connect(localAddr1); + assertTrue(this.channel1.isBlocking()); + assertTrue(this.channel1.isConnected()); + assertFalse(this.channel1.isConnectionPending()); + assertTrue(this.channel1.isOpen()); + assertEquals(CAPACITY_NORMAL, this.channel1.write(writeBuf)); + + this.channel1.close(); + try { + channel1.write(writeBuf); + fail("Should throw ClosedChannelException"); + } catch (ClosedChannelException e) { + // correct + } + } + + public void testWriteByteBuffer_BufNull() throws IOException { + assertTrue(this.server1.isBound()); + java.nio.ByteBuffer writeBuf = java.nio.ByteBuffer.allocate(0); + this.channel1.connect(localAddr1); + assertEquals(this.channel1.write(writeBuf), 0); + try { + this.channel1.write((java.nio.ByteBuffer) null); + fail("Should throw NPE"); + } catch (NullPointerException e) { + // correct + } + } + + /* + * SocketChannelImpl.write(ByteBuffer[], int, int)' + */ + public void testWriteByteBufferArrayIntInt() throws IOException { + java.nio.ByteBuffer[] writeBuf = new java.nio.ByteBuffer[2]; + writeBuf[0] = java.nio.ByteBuffer.allocate(CAPACITY_NORMAL); + writeBuf[1] = java.nio.ByteBuffer.allocate(CAPACITY_NORMAL); + assertFalse(this.channel1.isRegistered()); + assertTrue(this.channel1.isBlocking()); + assertFalse(this.channel1.isConnected()); + assertFalse(this.channel1.isConnectionPending()); + assertTrue(this.channel1.isOpen()); + try { + channel1.write(writeBuf, 0, 1); + fail("Should throw NotYetConnectedException"); + } catch (NotYetConnectedException e) { + // correct + } + this.channel1.connect(localAddr1); + assertTrue(this.channel1.isBlocking()); + assertTrue(this.channel1.isConnected()); + assertFalse(this.channel1.isConnectionPending()); + assertTrue(this.channel1.isOpen()); + assertEquals(CAPACITY_NORMAL, this.channel1.write(writeBuf, 0, 1)); + // still writes the same size as above + assertEquals(CAPACITY_NORMAL, this.channel1.write(writeBuf, 0, 2)); + writeBuf[0].flip(); + writeBuf[1].flip(); + assertEquals(CAPACITY_NORMAL * 2, this.channel1.write(writeBuf, 0, 2)); + this.channel1.close(); + try { + channel1.write(writeBuf); + fail("Should throw ClosedChannelException"); + } catch (ClosedChannelException e) { + // correct + } + } + + /* + * SocketChannelImpl.write(ByteBuffer[], int, int)' + */ + public void testWriteByteBufferArrayIntInt_Direct() throws IOException { + java.nio.ByteBuffer[] writeBuf = new java.nio.ByteBuffer[2]; + writeBuf[0] = java.nio.ByteBuffer.allocateDirect(CAPACITY_NORMAL); + writeBuf[1] = java.nio.ByteBuffer.allocateDirect(CAPACITY_NORMAL); + assertFalse(this.channel1.isRegistered()); + assertTrue(this.channel1.isBlocking()); + assertFalse(this.channel1.isConnected()); + assertFalse(this.channel1.isConnectionPending()); + assertTrue(this.channel1.isOpen()); + try { + channel1.write(writeBuf, 0, 1); + fail("Should throw NotYetConnectedException"); + } catch (NotYetConnectedException e) { + // correct + } + this.channel1.connect(localAddr1); + assertTrue(this.channel1.isBlocking()); + assertTrue(this.channel1.isConnected()); + assertFalse(this.channel1.isConnectionPending()); + assertTrue(this.channel1.isOpen()); + assertEquals(CAPACITY_NORMAL, this.channel1.write(writeBuf, 0, 1)); + // still writes the same size as above + assertEquals(CAPACITY_NORMAL, this.channel1.write(writeBuf, 0, 2)); + writeBuf[0].flip(); + writeBuf[1].flip(); + assertEquals(CAPACITY_NORMAL * 2, this.channel1.write(writeBuf, 0, 2)); + this.channel1.close(); + try { + channel1.write(writeBuf); + fail("Should throw ClosedChannelException"); + } catch (ClosedChannelException e) { + // correct + } + } + + public void testWriteByteBufferArrayIntInt_BufNull() throws IOException { + java.nio.ByteBuffer[] writeBuf = new java.nio.ByteBuffer[0]; + + this.channel1.connect(localAddr1); + try { + this.channel1.write(null, 0, 1); + fail("Should throw NPE"); + } catch (NullPointerException e) { + // correct + } + assertEquals(0, this.channel1.write(writeBuf, 0, 0)); + try { + this.channel1.write(writeBuf, 0, 1); + fail("Should throw IndexOutOfBoundsException"); + } catch (IndexOutOfBoundsException e) { + // correct + } + writeBuf = new java.nio.ByteBuffer[1]; + try { + this.channel1.write(writeBuf, 0, 1); + fail("Should throw NPE"); + } catch (NullPointerException e) { + // correct + } + try { + this.channel1.write(writeBuf, 0, 2); + fail("Should throw IndexOutOfBoundsException"); + } catch (IndexOutOfBoundsException e) { + // correct + } + this.server1.close(); + try { + channel1.read(null, 0, 1); + fail("Should throw NPE"); + } catch (NullPointerException e) { + // correct + } + } + + public void testWriteByteBufferArrayIntInt_SizeError() throws IOException { + java.nio.ByteBuffer[] buf = new java.nio.ByteBuffer[1]; + this.channel1.connect(localAddr1); + assertEquals(0, this.channel1.write(buf, 0, 0)); + try { + this.channel1.write(buf, -1, 1); + fail(); + } catch (IndexOutOfBoundsException expected) { + } + try { + this.channel1.write(buf, 0, -1); + fail(); + } catch (IndexOutOfBoundsException expected) { + } + try { + this.channel1.write(buf, 0, 2); + fail(); + } catch (IndexOutOfBoundsException expected) { + } + try { + this.channel1.write(buf, 2, 0); + fail(); + } catch (IndexOutOfBoundsException expected) { + } + try { + this.channel1.write(null, 0, 0); + fail(); + } catch (NullPointerException expected) { + } + this.server1.close(); + } + + public void testReadByteBufferArrayIntInt_SizeError() throws IOException { + java.nio.ByteBuffer[] buf = new java.nio.ByteBuffer[1]; + this.channel1.connect(localAddr1); + assertEquals(0, this.channel1.read(buf, 0, 0)); + try { + this.channel1.read(buf, -1, 1); + fail(); + } catch (IndexOutOfBoundsException expected) { + } + try { + this.channel1.read(buf, 0, -1); + fail(); + } catch (IndexOutOfBoundsException expected) { + } + try { + this.channel1.read(buf, 0, 2); + fail(); + } catch (IndexOutOfBoundsException expected) { + } + try { + this.channel1.read(buf, 2, 0); + fail(); + } catch (IndexOutOfBoundsException expected) { + } + try { + this.channel1.read(null, 0, 0); + fail(); + } catch (NullPointerException expected) { + } + this.server1.close(); + } + + /* + * ========================================================================== + * Tests for read/write real data + * ========================================================================== + */ + + + /** + * @tests java.nio.channels.SocketChannel#read(ByteBuffer[]) + */ + public void test_read$LByteBuffer() throws IOException { + MockSocketChannel sc = new MockSocketChannel(null); + ByteBuffer [] byteBufferArray = { ByteBuffer.allocate(1), ByteBuffer.allocate(1)}; + // Verify that calling read(ByteBuffer[]) leads to the method + // read(ByteBuffer[], int, int) being called with a 0 for the + // second parameter and targets.length as the third parameter. + sc.read(byteBufferArray); + assertTrue(sc.isReadCalled); + } + /** + * @tests java.nio.channels.SocketChannel#read(ByteBuffer[],int,int) + */ + public void test_read$LByteBufferII_blocking() throws Exception { + assert_read$LByteBuffer(true); + } + + /** + * @tests java.nio.channels.SocketChannel#read(ByteBuffer[],int,int) + */ + public void test_read$LByteBufferII_nonblocking() throws Exception { + assert_read$LByteBuffer(false); + } + + private void assert_read$LByteBuffer(boolean isBlocking) throws IOException { + // initialize write content + byte[] writeContent = new byte[CAPACITY_NORMAL * 2]; + for (int i = 0; i < CAPACITY_NORMAL * 2; i++) { + writeContent[i] = (byte) i; + } + ByteBuffer[] readContents = new ByteBuffer[2]; + readContents[0] = ByteBuffer.allocate(CAPACITY_NORMAL); + readContents[1] = ByteBuffer.allocate(CAPACITY_NORMAL + 1); + // establish connection + channel1.connect(localAddr1); + Socket acceptedSocket = server1.accept(); + // use OutputStream.write to send CAPACITY_NORMAL * 2 bytes data + OutputStream out = acceptedSocket.getOutputStream(); + out.write(writeContent); + // use close to guarantee all data is sent + acceptedSocket.close(); + // configure block/nonblock mode + channel1.configureBlocking(isBlocking); + long startTime = System.currentTimeMillis(); + long totalRead = 0; + long countRead = 0; + + while (totalRead <= CAPACITY_NORMAL * 2) { + countRead = channel1.read(readContents, 0, 2); + if (0 == countRead && !readContents[1].hasRemaining()) { + // read returns 0 because readContents is full + break; + } + if (EOF == countRead) { + break; + } + totalRead += countRead; + // 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. For + // blocking read, it possibly returns 0 in some cases. + assertTimeout(startTime, TIMEOUT); + } + + // assert total bytes read and the position of ByteBuffers + assertEquals(CAPACITY_NORMAL * 2, totalRead); + assertEquals(CAPACITY_NORMAL, readContents[0].position()); + assertEquals(CAPACITY_NORMAL, readContents[1].position()); + // assert read content + readContents[0].flip(); + readContents[1].flip(); + for (int i = 0; i < CAPACITY_NORMAL; i++) { + assertEquals(writeContent[i], readContents[0].get()); + } + for (int i = CAPACITY_NORMAL; i < CAPACITY_NORMAL * 2; i++) { + assertEquals(writeContent[i], readContents[1].get()); + } + } + + /** + * @tests java.nio.channels.SocketChannel#write(ByteBuffer[],int,int) + */ + public void test_write$LByteBufferII_blocking() throws Exception { + assert_write$LByteBuffer(true); + } + + /** + * @tests java.nio.channels.SocketChannel#write(ByteBuffer[],int,int) + */ + public void test_write$LByteBufferII_nonblocking() + throws Exception { + assert_write$LByteBuffer(false); + } + + private void assert_write$LByteBuffer(boolean isBlocking) + throws IOException { + // initialize write contents + ByteBuffer writeContents[] = new ByteBuffer[2]; + writeContents[0] = ByteBuffer.allocate(CAPACITY_NORMAL); + writeContents[1] = ByteBuffer.allocate(CAPACITY_NORMAL); + for (int i = 0; i < CAPACITY_NORMAL; i++) { + writeContents[0].put((byte) i); + } + for (int i = CAPACITY_NORMAL; i < CAPACITY_NORMAL * 2; i++) { + writeContents[1].put((byte) i); + } + writeContents[0].flip(); + writeContents[1].flip(); + // establish connection + channel1.connect(localAddr1); + Socket acceptedSocket = server1.accept(); + // set blocking/nonblocking mode + channel1.configureBlocking(isBlocking); + + assertEquals(CAPACITY_NORMAL, channel1.write(writeContents, 0, 1)); + assertEquals(CAPACITY_NORMAL, channel1.write(writeContents, 1, 1)); + + // assert written count and ByteBuffer position + assertEquals(CAPACITY_NORMAL, writeContents[0].position()); + assertEquals(CAPACITY_NORMAL, writeContents[1].position()); + // use close to guarantee all data is sent + channel1.close(); + InputStream in = acceptedSocket.getInputStream(); + byte[] readContent = new byte[CAPACITY_NORMAL * 2 + 1]; + int totalCount = 0; + int count = 0; + // 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. + acceptedSocket.setSoTimeout(TIMEOUT); + // use InputStream.read to read data. + while (totalCount <= CAPACITY_NORMAL) { + count = in.read(readContent, totalCount, readContent.length + - totalCount); + if (EOF == count) { + break; + } + totalCount += count; + } + // assert read content + assertEquals(CAPACITY_NORMAL * 2, totalCount); + writeContents[0].flip(); + writeContents[1].flip(); + for (int i = 0; i < CAPACITY_NORMAL; i++) { + assertEquals(writeContents[0].get(), readContent[i]); + } + for (int i = CAPACITY_NORMAL; i < CAPACITY_NORMAL * 2; i++) { + assertEquals(writeContents[1].get(), readContent[i]); + } + } + + /** + * @tests java.nio.channels.SocketChannel#write(ByteBuffer[]) + */ + public void test_write$LByteBuffer() throws IOException { + MockSocketChannel sc = new MockSocketChannel(null); + ByteBuffer [] byteBufferArray = { ByteBuffer.allocate(1), ByteBuffer.allocate(1)}; + // Verify that calling write(ByteBuffer[]) leads to the method + // write(ByteBuffer[], int, int) being called with a 0 for the + // second parameter and sources.length as the third parameter. + sc.write(byteBufferArray); + assertTrue(sc.isWriteCalled); + } + + /** + * @tests java.nio.channels.SocketChannel#write(ByteBuffer[]) + */ + public void test_writev() throws Exception { + ServerSocketChannel ssc = ServerSocketChannel.open(); + ssc.socket().bind(localAddr2); + SocketChannel sc = SocketChannel.open(); + sc.connect(localAddr2); + SocketChannel sock = ssc.accept(); + ByteBuffer[] buf = { ByteBuffer.allocate(10), ByteBuffer.allocateDirect(20) }; + + while (buf[0].remaining() != 0 && buf[1].remaining() !=0) { + assertTrue(sc.write(buf, 0, 2) >= 0); + } + + ByteBuffer target = ByteBuffer.allocate(30); + + while (target.remaining() != 0) { + assertTrue(sock.read(target) >=0); + } + + ssc.close(); + sc.close(); + sock.close(); + } + + /** + * @tests java.nio.channels.SocketChannel#write(ByteBuffer[]) + */ + public void test_writev2() throws Exception { + ServerSocketChannel ssc = ServerSocketChannel.open(); + ssc.configureBlocking(false); + ssc.socket().bind(null); + SocketChannel sc = SocketChannel.open(); + sc.configureBlocking(false); + boolean connected = sc.connect(ssc.socket().getLocalSocketAddress()); + SocketChannel sock = ssc.accept(); + if (!connected) { + sc.finishConnect(); + } + + ByteBuffer buf1 = ByteBuffer.allocate(10); + sc.socket().setSendBufferSize(512); + int bufSize = sc.socket().getSendBufferSize(); + ByteBuffer buf2 = ByteBuffer.allocate(bufSize * 10); + + ByteBuffer[] sent = new ByteBuffer[2]; + sent[0] = buf1; + sent[1] = buf2; + + long whole = buf1.remaining() + buf2.remaining(); + + long write = sc.write(sent); + ssc.close(); + sc.close(); + sock.close(); + + assertTrue(whole == (write + buf1.remaining() + buf2.remaining())); + } + + /** + * @tests java.nio.channels.SocketChannel#write(ByteBuffer[]) + * + * In non-blocking mode, the native system call will return EAGAIN/EWOULDBLOCK error + * code on Linux/Unix and return WSATRY_AGAIN/WSAEWOULDBLOCK error code on Windows. + * These error code means try again but not fatal error, so we should not throw exception. + */ + public void test_write$NonBlockingException() throws Exception { + ServerSocketChannel ssc = ServerSocketChannel.open(); + ssc.configureBlocking(false); + ssc.socket().bind(null); + SocketChannel sc = SocketChannel.open(); + sc.configureBlocking(false); + boolean connected = sc.connect(ssc.socket().getLocalSocketAddress()); + SocketChannel sock = ssc.accept(); + if (!connected) { + sc.finishConnect(); + } + + try { + for (int i = 0; i < 100; i++) { + ByteBuffer buf1 = ByteBuffer.allocate(10); + sc.socket().setSendBufferSize(512); + int bufSize = sc.socket().getSendBufferSize(); + ByteBuffer buf2 = ByteBuffer.allocate(bufSize * 10); + + ByteBuffer[] sent = new ByteBuffer[2]; + sent[0] = buf1; + sent[1] = buf2; + + sc.write(sent); + } + } finally { + ssc.close(); + sc.close(); + sock.close(); + } + + } + + /** + * @tests java.nio.channels.SocketChannel#write(ByteBuffer[]) + */ + public void test_write$LByteBuffer2() throws IOException { + // Set-up + ServerSocketChannel server = ServerSocketChannel.open(); + server.socket().bind(null); + SocketChannel client = SocketChannel.open(); + client.connect(server.socket().getLocalSocketAddress()); + SocketChannel worker = server.accept(); + + // Test overlapping buffers + byte[] data = "Hello world!".getBytes("UTF-8"); + ByteBuffer[] buffers = new ByteBuffer[3]; + buffers[0] = ByteBuffer.wrap(data, 0, 6); + buffers[1] = ByteBuffer.wrap(data, 6, data.length - 6); + buffers[2] = ByteBuffer.wrap(data); + + // Write them out, read what we wrote and check it + client.write(buffers); + client.close(); + ByteBuffer readBuffer = ByteBuffer.allocate(1024); + while (EOF != worker.read(readBuffer)) {}; + readBuffer.flip(); + Buffer expected = ByteBuffer.allocate(1024).put(data).put(data).flip(); + assertEquals(expected, readBuffer); + + // Tidy-up + worker.close(); + server.close(); + } + + /** + * @tests java.nio.channels.SocketChannel#write(ByteBuffer[]) + */ + public void test_write$LByteBuffer_buffers() throws IOException { + // Set-up + ServerSocketChannel server = ServerSocketChannel.open(); + server.socket().bind(null); + SocketChannel client = SocketChannel.open(); + client.connect(server.socket().getLocalSocketAddress()); + SocketChannel worker = server.accept(); + + // A variety of buffer types to write + byte[] data = "Hello world!".getBytes("UTF-8"); + ByteBuffer[] buffers = new ByteBuffer[3]; + buffers[0] = ByteBuffer.wrap(data, 0, 2); + assertFalse(buffers[0].isDirect()); + assertTrue(buffers[0].hasArray()); + + buffers[1] = ByteBuffer.wrap(data, 2, 4).asReadOnlyBuffer(); + assertFalse(buffers[1].isDirect()); + assertFalse(buffers[1].hasArray()); + + buffers[2] = ByteBuffer.allocateDirect(42); + buffers[2].put(data, 6, data.length - 6); + buffers[2].flip(); + assertTrue(buffers[2].isDirect()); + // Android's direct buffers do have a backing array. + assertTrue(buffers[2].hasArray()); + + // Write them out, read what we wrote and check it + client.write(buffers); + client.close(); + ByteBuffer readBuffer = ByteBuffer.allocate(1024); + while (EOF != worker.read(readBuffer)) {}; + readBuffer.flip(); + assertEquals(ByteBuffer.wrap(data), readBuffer); + + // Tidy-up + worker.close(); + server.close(); + } + + /** + * @tests java.nio.channels.SocketChannel#write(ByteBuffer[]) + */ + public void test_write$LByteBuffer_writes() throws IOException { + // Set-up + ServerSocketChannel server = ServerSocketChannel.open(); + server.socket().bind(null); + SocketChannel client = SocketChannel.open(); + client.connect(server.socket().getLocalSocketAddress()); + SocketChannel worker = server.accept(); + + // Data to write + byte[] data = "Hello world!".getBytes("UTF-8"); + ByteBuffer[] buffers = new ByteBuffer[3]; + buffers[0] = ByteBuffer.wrap(data, 0, 6); + buffers[1] = ByteBuffer.wrap("world!".getBytes("UTF-8")); + buffers[2] = buffers[0]; + assertTrue(buffers[0].hasArray()); + + // Test a sequence of write calls + client.write(buffers, 0, 0); // write nothing + client.write(buffers, 1, 0); // write nothing + client.write(buffers, 0, 1); // write "Hello " + assertEquals("Failed to drain buffer 0", 0, buffers[0].remaining()); + assertEquals("Shouldn't touch buffer 1", buffers[1].limit(), buffers[1] + .remaining()); + client.write(buffers, 0, 2); // writes "world!" + assertEquals("Failed to drain buffer 1", 0, buffers[1].remaining()); + client.write(buffers, 0, 3); // write nothing + client.close(); + + // Read what we wrote and check it + ByteBuffer readBuffer = ByteBuffer.allocate(1024); + while (EOF != worker.read(readBuffer)) {}; + readBuffer.flip(); + assertEquals(ByteBuffer.wrap(data), readBuffer); + + // Tidy-up + worker.close(); + server.close(); + } + + /** + * @tests java.nio.channels.SocketChannel#write(ByteBuffer[]) + */ + public void test_write$LByteBuffer_invalid() throws IOException { + // Set-up + ServerSocketChannel server = ServerSocketChannel.open(); + server.socket().bind(null); + + SocketChannel client = SocketChannel.open(); + client.connect(server.socket().getLocalSocketAddress()); + + SocketChannel worker = server.accept(); + + // Do some stuff + try { + client.write((ByteBuffer[]) null); + fail("Should throw a NPE"); + } catch (NullPointerException e) { + // expected + } + try { + client.write((ByteBuffer[]) null, 0, 0); + fail("Should throw a NPE"); + } catch (NullPointerException e) { + // expected + } + try { + client.write((ByteBuffer[]) null, 1, 0); + fail("Should throw a NPE"); + } catch (NullPointerException e) { + // expected + } + try { + client.write((ByteBuffer[]) null, 0, 1); + fail("Should throw a NPE"); + } catch (NullPointerException e) { + // expected + } + try { + client.write((ByteBuffer[]) null, 1, 1); + fail("Should throw a NPE"); + } catch (NullPointerException e) { + // expected + } + + ByteBuffer[] buffers = new ByteBuffer[1]; + buffers[0] = ByteBuffer.wrap("Hello ".getBytes("UTF-8")); + + try { + client.write(buffers, -1, 1); + fail(); + } catch (IndexOutOfBoundsException expected) { + } + try { + client.write(buffers, 0, -1); + fail(); + } catch (IndexOutOfBoundsException expected) { + } + try { + client.write(buffers, 0, 2); + fail(); + } catch (IndexOutOfBoundsException expected) { + } + try { + client.write(buffers, 2, 0); + fail(); + } catch (IndexOutOfBoundsException expected) { + } + try { + client.write(null, 0, 0); + fail(); + } catch (NullPointerException expected) { + } + + // Tidy-up + worker.close(); + client.close(); + server.close(); + } + + public void testSocket_configureblocking() throws IOException { + byte[] serverWBuf = new byte[CAPACITY_NORMAL]; + for (int i = 0; i < serverWBuf.length; i++) { + serverWBuf[i] = (byte) i; + } + java.nio.ByteBuffer buf = java.nio.ByteBuffer + .allocate(CAPACITY_NORMAL + 1); + channel1.connect(localAddr1); + server1.accept(); + Socket sock = this.channel1.socket(); + channel1.configureBlocking(false); + assertFalse(channel1.isBlocking()); + OutputStream channelSocketOut = sock.getOutputStream(); + try { + // write operation is not allowed in non-blocking mode + channelSocketOut.write(buf.array()); + fail("Non-Blocking mode should cause IllegalBlockingModeException"); + } catch (IllegalBlockingModeException e) { + // correct + } + channel1.configureBlocking(true); + assertTrue(channel1.isBlocking()); + // write operation is allowed in blocking mode + channelSocketOut.write(buf.array()); + } + + /** + * @tests SocketChannel#read(ByteBuffer[], int, int) when remote server + * closed + */ + public void test_socketChannel_read_ByteBufferII_remoteClosed() + throws Exception { + // regression 1 for HARMONY-549 + ServerSocketChannel ssc = ServerSocketChannel.open(); + ssc.socket().bind(localAddr2); + SocketChannel sc = SocketChannel.open(); + sc.connect(localAddr2); + ssc.accept().close(); + ByteBuffer[] buf = { ByteBuffer.allocate(10) }; + assertEquals(-1, sc.read(buf, 0, 1)); + ssc.close(); + sc.close(); + } + + /** + * @tests SocketChannel#write(ByteBuffer[], int, int) + */ + public void test_socketChannel_write_ByteBufferII() throws Exception { + // regression 2 for HARMONY-549 + ServerSocketChannel ssc = ServerSocketChannel.open(); + ssc.socket().bind(localAddr2); + SocketChannel sc = SocketChannel.open(); + sc.connect(localAddr2); + SocketChannel sock = ssc.accept(); + ByteBuffer[] buf = { ByteBuffer.allocate(10), null }; + try { + sc.write(buf, 0, 2); + fail("should throw NPE"); + } catch (NullPointerException e) { + // expected + } + ssc.close(); + sc.close(); + ByteBuffer target = ByteBuffer.allocate(10); + assertEquals(-1, sock.read(target)); + } + + /** + * @tests SocketChannel#read(ByteBuffer[], int, int) with a null ByteBuffer + */ + public void test_socketChannel_read_ByteBufferII_bufNULL() throws Exception { + // regression 3 for HARMONY-549 + ServerSocketChannel ssc = ServerSocketChannel.open(); + ssc.socket().bind(localAddr2); + SocketChannel sc = SocketChannel.open(); + sc.connect(localAddr2); + ssc.accept(); + ByteBuffer[] buf = new ByteBuffer[2]; + buf[0] = ByteBuffer.allocate(1); + // let buf[1] be null + try { + sc.read(buf, 0, 2); + fail("should throw NullPointerException"); + } catch (NullPointerException e) { + // expected + } + ssc.close(); + sc.close(); + } + + /** + * @tests SocketChannel#write(ByteBuffer) after close + */ + public void test_socketChannel_write_close() throws Exception { + // regression 4 for HARMONY-549 + ServerSocketChannel ssc = ServerSocketChannel.open(); + ssc.socket().bind(localAddr2); + SocketChannel sc = SocketChannel.open(); + sc.connect(localAddr2); + SocketChannel sock = ssc.accept(); + ByteBuffer buf = null; + ssc.close(); + sc.close(); + try { + sc.write(buf); + fail("should throw NPE"); + } catch (NullPointerException e) { + // expected + } + sock.close(); + } + + /** + * @tests SocketChannel#write(ByteBuffer) if position is not zero + */ + public void test_socketChannel_write_ByteBuffer_posNotZero() + throws Exception { + // regression 5 for HARMONY-549 + final String testStr = "Hello World"; + ByteBuffer readBuf = ByteBuffer.allocate(11); + ByteBuffer buf = ByteBuffer.wrap(testStr.getBytes()); + ServerSocketChannel ssc = ServerSocketChannel.open(); + ssc.socket().bind(localAddr2); + SocketChannel sc = SocketChannel.open(); + sc.connect(localAddr2); + buf.position(2); + ssc.accept().write(buf); + assertEquals(9, sc.read(readBuf)); + buf.flip(); + readBuf.flip(); + byte[] read = new byte[9]; + byte[] write = new byte[11]; + buf.get(write); + readBuf.get(read); + for (int i = 0; i < 9; i++) { + assertEquals(read[i], write[i + 2]); + } + } + + /** + * @tests SocketChannelImpl#read(ByteBuffer[]) + */ + public void test_read_$ByteBuffer_Blocking() throws IOException { + // regression test for Harmony-728 + byte[] data = new byte[CAPACITY_NORMAL]; + for (int i = 0; i < CAPACITY_NORMAL; i++) { + data[i] = (byte) i; + } + ByteBuffer[] buf = new ByteBuffer[2]; + buf[0] = ByteBuffer.allocate(CAPACITY_NORMAL); + buf[1] = ByteBuffer.allocate(CAPACITY_NORMAL); + channel1.connect(localAddr1); + Socket socket = null; + try { + socket = server1.accept(); + OutputStream out = socket.getOutputStream(); + out.write(data); + // should not block here + channel1.read(buf); + } finally { + if (null != socket) { + socket.close(); + } + } + } + + public void test_socket_getOutputStream_nonBlocking_read_Exception() throws IOException { + byte[] buf = new byte[1]; + channel1.connect(this.localAddr1); + InputStream is = channel1.socket().getInputStream(); + channel1.configureBlocking(false); + try { + is.read(); + fail(); + } catch (IllegalBlockingModeException expected) { + } + try { + is.read(null); + fail(); + } catch (NullPointerException expected) { + } + try { + is.read(buf, -1, 1); + fail(); + } catch (IndexOutOfBoundsException expected) { + } + try { + is.read(buf, 0, -1); + fail(); + } catch (IndexOutOfBoundsException expected) { + } + try { + is.read(buf, 0, 2); + fail(); + } catch (IndexOutOfBoundsException expected) { + } + try { + is.read(buf, 2, 0); + fail(); + } catch (IndexOutOfBoundsException expected) { + } + try { + is.read(null, 0, 0); + fail(); + } catch (NullPointerException expected) { + } + + is.close(); + + try { + is.read(); + fail(); + } catch (IllegalBlockingModeException expected) { + } + try { + is.read(null); + fail(); + } catch (NullPointerException expected) { + } + try { + is.read(buf, -1, 1); + fail(); + } catch (IndexOutOfBoundsException expected) { + } + try { + is.read(buf, 0, -1); + fail(); + } catch (IndexOutOfBoundsException expected) { + } + try { + is.read(buf, 0, 2); + fail(); + } catch (IndexOutOfBoundsException expected) { + } + try { + is.read(buf, 2, 0); + fail(); + } catch (IndexOutOfBoundsException expected) { + } + try { + is.read(null, 0, 0); + fail(); + } catch (NullPointerException expected) { + } + } + + public void test_socket_getOutputStream_blocking_read_Exception() throws IOException { + byte[] buf = new byte[1]; + channel1.connect(this.localAddr1); + InputStream is = channel1.socket().getInputStream(); + try { + is.read(null); + fail(); + } catch (NullPointerException expected) { + } + try { + is.read(buf, -1, 1); + fail(); + } catch (IndexOutOfBoundsException expected) { + } + try { + is.read(buf, 0, -1); + fail(); + } catch (IndexOutOfBoundsException expected) { + } + try { + is.read(buf, 0, 2); + fail(); + } catch (IndexOutOfBoundsException expected) { + } + try { + is.read(buf, 2, 0); + fail(); + } catch (IndexOutOfBoundsException expected) { + } + try { + is.read(null, 0, 0); + fail(); + } catch (NullPointerException expected) { + } + + is.close(); + + try { + is.read(null); + fail(); + } catch (NullPointerException expected) { + } + try { + is.read(buf, -1, 1); + fail(); + } catch (IndexOutOfBoundsException expected) { + } + try { + is.read(buf, 0, -1); + fail(); + } catch (IndexOutOfBoundsException expected) { + } + try { + is.read(buf, 0, 2); + fail(); + } catch (IndexOutOfBoundsException expected) { + } + try { + is.read(buf, 2, 0); + fail(); + } catch (IndexOutOfBoundsException expected) { + } + try { + is.read(null, 0, 0); + fail(); + } catch (NullPointerException expected) { + } + } + + public void test_socket_getOutputStream_nonBlocking_write_Exception() throws IOException { + byte[] buf = new byte[1]; + channel1.connect(this.localAddr1); + OutputStream os = channel1.socket().getOutputStream(); + channel1.configureBlocking(false); + + try { + os.write(1); + fail(); + } catch (IllegalBlockingModeException expected) { + } + try { + os.write(null); + fail(); + } catch (NullPointerException expected) { + } + try { + os.write(buf, -1, 1); + fail(); + } catch (IndexOutOfBoundsException expected) { + } + try { + os.write(buf, 0, -1); + fail(); + } catch (IndexOutOfBoundsException expected) { + } + try { + os.write(buf, 0, 2); + fail(); + } catch (IndexOutOfBoundsException expected) { + } + try { + os.write(buf, 2, 0); + fail(); + } catch (IndexOutOfBoundsException expected) { + } + try { + os.write(null, 0, 0); + fail(); + } catch (NullPointerException expected) { + } + + os.close(); + + try { + os.write(1); + fail(); + } catch (IllegalBlockingModeException expected) { + } + try { + os.write(null); + fail(); + } catch (NullPointerException expected) { + } + try { + os.write(buf, -1, 1); + fail(); + } catch (IndexOutOfBoundsException expected) { + } + try { + os.write(buf, 0, -1); + fail(); + } catch (IndexOutOfBoundsException expected) { + } + try { + os.write(buf, 0, 2); + fail(); + } catch (IndexOutOfBoundsException expected) { + } + try { + os.write(buf, 2, 0); + fail(); + } catch (IndexOutOfBoundsException expected) { + } + try { + os.write(null, 0, 0); + fail(); + } catch (NullPointerException expected) { + } + } + + public void test_socket_getOutputStream_blocking_write_Exception() throws IOException { + byte[] buf = new byte[1]; + channel1.connect(this.localAddr1); + OutputStream os = channel1.socket().getOutputStream(); + try { + os.write(null); + fail(); + } catch (NullPointerException expected) { + } + try { + os.write(buf, -1, 1); + fail(); + } catch (IndexOutOfBoundsException expected) { + } + try { + os.write(buf, 0, -1); + fail(); + } catch (IndexOutOfBoundsException expected) { + } + try { + os.write(buf, 0, 2); + fail(); + } catch (IndexOutOfBoundsException expected) { + } + try { + os.write(buf, 2, 0); + fail(); + } catch (IndexOutOfBoundsException expected) { + } + try { + os.write(null, 0, 0); + fail(); + } catch (NullPointerException expected) { + } + + os.close(); + + try { + os.write(null); + fail(); + } catch (NullPointerException expected) { + } + try { + os.write(buf, -1, 1); + fail(); + } catch (IndexOutOfBoundsException expected) { + } + try { + os.write(buf, 0, -1); + fail(); + } catch (IndexOutOfBoundsException expected) { + } + try { + os.write(buf, 0, 2); + fail(); + } catch (IndexOutOfBoundsException expected) { + } + try { + os.write(buf, 2, 0); + fail(); + } catch (IndexOutOfBoundsException expected) { + } + try { + os.write(null, 0, 0); + fail(); + } catch (NullPointerException expected) { + } + } + + /** + * @tests SocketChannelImpl#socket().getOutputStream().write(int) + */ + public void test_socket_getOutputStream_write_oneByte() + throws IOException { + + // Regression test for Harmony-3475 + + int MAGIC = 123; + + channel1.connect(this.localAddr1); + + OutputStream os = channel1.socket().getOutputStream(); + + Socket acceptedSocket = server1.accept(); + + InputStream in = acceptedSocket.getInputStream(); + + os.write(MAGIC); + channel1.close(); + + int lastByte = in.read(); + if (lastByte == -1) { + fail("Server received nothing. Expected 1 byte."); + } else if (lastByte != MAGIC) { + fail("Server received wrong single byte: " + lastByte + + ", expected: " + MAGIC); + } + + lastByte = in.read(); + if (lastByte != -1) { + fail("Server received too long sequence. Expected 1 byte."); + } + } + + public void testSocket_setOptions() throws IOException { + channel1.connect(localAddr1); + Socket socket = channel1.socket(); + + ByteBuffer buffer = ByteBuffer.wrap(new byte[] {1, 2, 3}); + socket.setKeepAlive(true); + channel1.write(buffer); + + socket.setOOBInline(true); + channel1.write(buffer); + + socket.setReceiveBufferSize(100); + channel1.write(buffer); + + socket.setReuseAddress(true); + channel1.write(buffer); + + socket.setSendBufferSize(100); + channel1.write(buffer); + + socket.setSoLinger(true, 100); + channel1.write(buffer); + + socket.setSoTimeout(1000); + channel1.write(buffer); + + socket.setTcpNoDelay(true); + channel1.write(buffer); + + socket.setTrafficClass(10); + channel1.write(buffer); + } + + class MockSocketChannel extends SocketChannel{ + + private boolean isWriteCalled = false; + + private boolean isReadCalled = false; + + public MockSocketChannel(SelectorProvider provider){ + super(provider); + } + + public Socket socket() { + return null; + } + + public boolean isConnected() { + return false; + } + + public boolean isConnectionPending() { + return false; + } + + public boolean connect(SocketAddress address) throws IOException { + return false; + } + + public boolean finishConnect() throws IOException { + return false; + } + + public int read(ByteBuffer target) throws IOException { + return 0; + } + + 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 + // second parameter and targets.length as the third parameter. + if(0 == offset && length == targets.length){ + isReadCalled = true; + } + return 0; + } + + public int write(ByteBuffer source) throws IOException { + return 0; + } + + 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 + // second parameter and sources.length as the third parameter. + if(0 == offset && length == sources.length){ + isWriteCalled = true; + } + return 0; + } + + protected void implCloseSelectableChannel() throws IOException { + // empty + } + + 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/nio/tests/java/nio/channels/SourceChannelTest.java new file mode 100644 index 0000000..53fdae4 --- /dev/null +++ b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/SourceChannelTest.java @@ -0,0 +1,554 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.harmony.nio.tests.java.nio.channels; + +import java.io.IOException; +import java.nio.ByteBuffer; +import java.nio.channels.ClosedChannelException; +import java.nio.channels.Pipe; +import java.nio.channels.SelectionKey; + +import junit.framework.TestCase; + +/** + * Tests for java.nio.channels.Pipe.SourceChannel + */ +public class SourceChannelTest extends TestCase { + + private static final int BUFFER_SIZE = 5; + + private static final String ISO8859_1 = "ISO8859-1"; + + private Pipe pipe; + + private Pipe.SinkChannel sink; + + private Pipe.SourceChannel source; + + private ByteBuffer buffer; + + private ByteBuffer positionedBuffer; + + protected void setUp() throws Exception { + super.setUp(); + pipe = Pipe.open(); + sink = pipe.sink(); + source = pipe.source(); + buffer = ByteBuffer.wrap("bytes".getBytes(ISO8859_1)); + positionedBuffer = ByteBuffer.wrap("12345bytes".getBytes(ISO8859_1)); + positionedBuffer.position(BUFFER_SIZE); + } + + /** + * @tests java.nio.channels.Pipe.SourceChannel#validOps() + */ + public void test_validOps() { + assertEquals(SelectionKey.OP_READ, source.validOps()); + } + + /** + * @tests java.nio.channels.Pipe.SourceChannel#read(ByteBuffer) + */ + public void test_read_LByteBuffer_DataAvailable() throws IOException { + // if anything can read, read method will not block + sink.write(ByteBuffer.allocate(1)); + int count = source.read(ByteBuffer.allocate(10)); + assertEquals(1, count); + } + + /** + * @tests java.nio.channels.Pipe.SourceChannel#read(ByteBuffer) + */ + public void test_read_LByteBuffer_Exception() throws IOException { + ByteBuffer nullBuf = null; + try { + source.read(nullBuf); + fail("should throw NullPointerException"); + } catch (NullPointerException e) { + // expected + } + } + + /** + * @tests java.nio.channels.Pipe.SourceChannel#read(ByteBuffer) + */ + public void test_read_LByteBuffer_SinkClosed() throws IOException { + ByteBuffer readBuf = ByteBuffer.allocate(BUFFER_SIZE); + sink.write(buffer); + sink.close(); + long count = source.read(readBuf); + assertEquals(BUFFER_SIZE, count); + // readBuf is full, read 0 byte expected + count = source.read(readBuf); + assertEquals(0, count); + // readBuf is not null, -1 is expected + readBuf.position(0); + count = source.read(readBuf); + assertEquals(-1, count); + } + + /** + * @tests java.nio.channels.Pipe.SourceChannel#read(ByteBuffer) + */ + public void test_read_LByteBuffer_SourceClosed() throws IOException { + ByteBuffer readBuf = ByteBuffer.allocate(BUFFER_SIZE); + source.close(); + try { + source.read(readBuf); + fail("should throw ClosedChannelException"); + } catch (ClosedChannelException e) { + // expected + } + readBuf.position(BUFFER_SIZE); + try { + // readBuf is full + source.read(readBuf); + fail("should throw ClosedChannelException"); + } catch (ClosedChannelException e) { + // expected + } + + ByteBuffer nullBuf = null; + try { + source.read(nullBuf); + fail("should throw NullPointerException"); + } catch (NullPointerException e) { + // expected + } + + ByteBuffer[] bufArray = null; + try { + source.read(bufArray); + fail("should throw NullPointerException"); + } catch (NullPointerException e) { + // expected + } + + ByteBuffer[] nullBufArray = {nullBuf}; + try { + source.read(nullBufArray); + fail("should throw ClosedChannelException"); + } catch (ClosedChannelException e) { + // expected + } + } + + /** + * @tests java.nio.channels.Pipe.SourceChannel#read(ByteBuffer[]) + */ + public void test_read_$LByteBuffer() throws IOException { + ByteBuffer[] bufArray = { buffer, positionedBuffer }; + boolean[] sinkBlockingMode = { true, true, false, false }; + boolean[] sourceBlockingMode = { true, false, true, false }; + for (int i = 0; i < sinkBlockingMode.length; ++i) { + // open new pipe everytime, will be closed in finally block + pipe = Pipe.open(); + sink = pipe.sink(); + source = pipe.source(); + sink.configureBlocking(sinkBlockingMode[i]); + source.configureBlocking(sourceBlockingMode[i]); + buffer.position(0); + positionedBuffer.position(BUFFER_SIZE); + try { + long writeCount = sink.write(bufArray); + assertEquals(10, writeCount); + // invoke close to ensure all data will be sent out + sink.close(); + // read until EOF is meet or readBufArray is full. + ByteBuffer[] readBufArray = { ByteBuffer.allocate(BUFFER_SIZE), + ByteBuffer.allocate(BUFFER_SIZE) }; + long totalCount = 0; + do { + long count = source.read(readBufArray); + if (count < 0) { + break; + } + if (0 == count && BUFFER_SIZE == readBufArray[1].position()) { + // source.read returns 0 because readBufArray is full + break; + } + totalCount += count; + } while (totalCount <= 10); + // assert read result + for (ByteBuffer readBuf : readBufArray) { + // RI may fail because of its bug implementation + assertEquals(BUFFER_SIZE, readBuf.position()); + assertEquals("bytes", + new String(readBuf.array(), ISO8859_1)); + } + } finally { + // close pipe everytime + sink.close(); + source.close(); + } + } + } + + /** + * @tests java.nio.channels.Pipe.SourceChannel#read(ByteBuffer) + */ + public void test_read_$LByteBuffer_Exception() throws IOException { + ByteBuffer[] nullBufArrayRef = null; + try { + source.read(nullBufArrayRef); + fail("should throw NullPointerException"); + } catch (NullPointerException e) { + // expected + } + + // ByteBuffer array contains null element + ByteBuffer nullBuf = null; + ByteBuffer[] nullBufArray1 = { nullBuf }; + try { + source.read(nullBufArray1); + fail("should throw NullPointerException"); + } catch (NullPointerException e) { + // expected + } + + ByteBuffer[] nullBufArray2 = { buffer, nullBuf }; + try { + source.read(nullBufArray2); + fail("should throw NullPointerException"); + } catch (NullPointerException e) { + // expected + } + } + + /** + * @tests java.nio.channels.Pipe.SourceChannel#read(ByteBuffer) + */ + public void test_read_$LByteBuffer_SinkClosed() throws IOException { + ByteBuffer readBuf = ByteBuffer.allocate(BUFFER_SIZE); + ByteBuffer[] readBufArray = { readBuf }; + sink.write(buffer); + sink.close(); + long count = source.read(readBufArray); + assertEquals(BUFFER_SIZE, count); + // readBuf is full, read 0 byte expected + count = source.read(readBufArray); + assertEquals(0, count); + // readBuf is not null, -1 is expected + readBuf.position(0); + assertTrue(readBuf.hasRemaining()); + count = source.read(readBufArray); + assertEquals(-1, count); + } + + /** + * @tests java.nio.channels.Pipe.SourceChannel#read(ByteBuffer) + */ + public void test_read_$LByteBuffer_SourceClosed() throws IOException { + ByteBuffer readBuf = ByteBuffer.allocate(BUFFER_SIZE); + ByteBuffer[] readBufArray = { readBuf }; + source.close(); + try { + source.read(readBufArray); + fail("should throw ClosedChannelException"); + } catch (ClosedChannelException e) { + // expected + } + readBuf.position(BUFFER_SIZE); + try { + // readBuf is full + source.read(readBufArray); + fail("should throw ClosedChannelException"); + } catch (ClosedChannelException e) { + // expected + } + + ByteBuffer[] nullBufArrayRef = null; + try { + source.read(nullBufArrayRef); + fail("should throw NullPointerException"); + } catch (NullPointerException e) { + // expected + } + + // ByteBuffer array contains null element + ByteBuffer nullBuf = null; + ByteBuffer[] nullBufArray1 = { nullBuf }; + try { + source.read(nullBufArray1); + fail("should throw ClosedChannelException"); + } catch (ClosedChannelException e) { + // expected + } + } + + /** + * @tests java.nio.channels.Pipe.SourceChannel#read(ByteBuffer[], int, int) + */ + public void test_read_$LByteBufferII() throws IOException { + ByteBuffer[] bufArray = { buffer, positionedBuffer }; + boolean[] sinkBlockingMode = { true, true, false, false }; + boolean[] sourceBlockingMode = { true, false, true, false }; + for (int i = 0; i < sinkBlockingMode.length; ++i) { + Pipe pipe = Pipe.open(); + sink = pipe.sink(); + source = pipe.source(); + + sink.configureBlocking(sinkBlockingMode[i]); + source.configureBlocking(sourceBlockingMode[i]); + + buffer.position(0); + positionedBuffer.position(BUFFER_SIZE); + try { + sink.write(bufArray); + // invoke close to ensure all data will be sent out + sink.close(); + // read until EOF is meet or readBufArray is full. + ByteBuffer[] readBufArray = { ByteBuffer.allocate(BUFFER_SIZE), + ByteBuffer.allocate(BUFFER_SIZE) }; + long totalCount = 0; + do { + long count = source.read(readBufArray, 0, 2); + if (count < 0) { + break; + } + if (0 == count && BUFFER_SIZE == readBufArray[1].position()) { + // source.read returns 0 because readBufArray is full + break; + } + totalCount += count; + } while (totalCount != 10); + + // assert read result + for (ByteBuffer readBuf : readBufArray) { + // RI may fail because of its bug implementation + assertEquals(BUFFER_SIZE, readBuf.position()); + assertEquals("bytes", + new String(readBuf.array(), ISO8859_1)); + } + } finally { + sink.close(); + source.close(); + } + } + } + + /** + * @tests java.nio.channels.Pipe.SourceChannel#read(ByteBuffer) + */ + public void test_read_$LByteBufferII_Exception() throws IOException { + + ByteBuffer[] nullBufArrayRef = null; + try { + source.read(nullBufArrayRef, 0, 1); + fail(); + } catch (NullPointerException expected) { + } + + try { + source.read(nullBufArrayRef, 0, -1); + fail(); + } catch (NullPointerException expected) { + } catch (IndexOutOfBoundsException expected) { + } + + try { + source.read(new ByteBuffer[0], 0, -1); + fail(); + } catch (IndexOutOfBoundsException expected) { + } + + try { + source.read(new ByteBuffer[0], -1, 0); + fail(); + } catch (IndexOutOfBoundsException expected) { + } + + // ByteBuffer array contains null element + ByteBuffer nullBuf = null; + ByteBuffer[] nullBufArray1 = { nullBuf }; + try { + source.read(nullBufArray1, 0, 1); + fail("should throw NullPointerException"); + } catch (NullPointerException e) { + // expected + } + try { + source.read(nullBufArray1, 0, -1); + fail("should throw IndexOutOfBoundsException"); + } catch (IndexOutOfBoundsException e) { + // expected + } + try { + source.read(nullBufArray1, -1, 0); + fail("should throw IndexOutOfBoundsException"); + } catch (IndexOutOfBoundsException e) { + // expected + } + try { + source.read(nullBufArray1, -1, 1); + fail("should throw IndexOutOfBoundsException"); + } catch (IndexOutOfBoundsException e) { + // expected + } + + ByteBuffer[] nullBufArray2 = { buffer, nullBuf }; + + try { + source.read(nullBufArray1, 1, -1); + fail("should throw IndexOutOfBoundsException"); + } catch (IndexOutOfBoundsException e) { + // expected + } + + try { + source.read(nullBufArray2, 0, 3); + fail("should throw IndexOutOfBoundsException"); + } catch (IndexOutOfBoundsException e) { + // expected + } + + try { + source.read(nullBufArray2, 0, 2); + fail("should throw NullPointerException"); + } catch (NullPointerException e) { + // expected + } + } + + /** + * @tests java.nio.channels.Pipe.SourceChannel#read(ByteBuffer) + */ + public void test_read_$LByteBufferII_SinkClosed() throws IOException { + ByteBuffer readBuf = ByteBuffer.allocate(BUFFER_SIZE); + ByteBuffer[] readBufArray = { readBuf }; + sink.write(buffer); + sink.close(); + long count = source.read(readBufArray, 0, 1); + assertEquals(BUFFER_SIZE, count); + // readBuf is full, read 0 byte expected + count = source.read(readBufArray); + assertEquals(0, count); + // readBuf is not null, -1 is expected + readBuf.position(0); + count = source.read(readBufArray, 0, 1); + assertEquals(-1, count); + } + + /** + * @tests java.nio.channels.Pipe.SourceChannel#read(ByteBuffer) + */ + public void test_read_$LByteBufferII_SourceClosed() throws IOException { + ByteBuffer readBuf = ByteBuffer.allocate(BUFFER_SIZE); + ByteBuffer[] readBufArray = { readBuf }; + source.close(); + try { + source.read(readBufArray, 0, 1); + fail("should throw ClosedChannelException"); + } catch (ClosedChannelException e) { + // expected + } + readBuf.position(BUFFER_SIZE); + try { + // readBuf is full + source.read(readBufArray, 0, 1); + fail("should throw ClosedChannelException"); + } catch (ClosedChannelException e) { + // expected + } + + ByteBuffer[] nullBufArrayRef = null; + try { + source.read(nullBufArrayRef, 0, 1); + fail(); + } catch (NullPointerException expected) { + } + + try { + source.read(nullBufArrayRef, 0, -1); + fail(); + } catch (NullPointerException expected) { + } catch (IndexOutOfBoundsException expected) { + } + + try { + source.read(new ByteBuffer[0], 0, -1); + fail(); + } catch (IndexOutOfBoundsException expected) { + } + + try { + source.read(new ByteBuffer[0], -1, 1); + fail(); + } catch (IndexOutOfBoundsException expected) { + } + + // ByteBuffer array contains null element + ByteBuffer nullBuf = null; + ByteBuffer[] nullBufArray1 = { nullBuf }; + try { + source.read(nullBufArray1, 0, 1); + fail("should throw ClosedChannelException"); + } catch (ClosedChannelException e) { + // expected + } + try { + source.read(nullBufArray1, 0, -1); + fail("should throw IndexOutOfBoundsException"); + } catch (IndexOutOfBoundsException e) { + // expected + } + try { + source.read(nullBufArray1, -1, 0); + fail("should throw IndexOutOfBoundsException"); + } catch (IndexOutOfBoundsException e) { + // expected + } + try { + source.read(nullBufArray1, -1, 1); + fail("should throw IndexOutOfBoundsException"); + } catch (IndexOutOfBoundsException e) { + // expected + } + + ByteBuffer[] nullBufArray2 = { buffer, nullBuf }; + + try { + source.read(nullBufArray1, 1, -1); + fail("should throw IndexOutOfBoundsException"); + } catch (IndexOutOfBoundsException e) { + // expected + } + + try { + source.read(nullBufArray2, 0, 3); + fail("should throw IndexOutOfBoundsException"); + } catch (IndexOutOfBoundsException e) { + // expected + } + + try { + source.read(nullBufArray2, 0, 2); + fail("should throw ClosedChannelException"); + } catch (ClosedChannelException e) { + // expected + } + } + + /** + * @tests java.nio.channels.Pipe.SourceChannel#close() + */ + public void test_close() throws IOException { + sink.close(); + assertFalse(sink.isOpen()); + } + +} 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/nio/tests/java/nio/channels/UnixSelectorTest.java new file mode 100644 index 0000000..95fbbd6 --- /dev/null +++ b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/UnixSelectorTest.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.nio.tests.java.nio.channels; + +import java.net.InetSocketAddress; +import java.net.ServerSocket; +import java.nio.channels.SelectableChannel; +import java.nio.channels.SelectionKey; +import java.nio.channels.Selector; +import java.nio.channels.ServerSocketChannel; +import java.nio.channels.SocketChannel; + +import junit.framework.TestCase; + +public class UnixSelectorTest extends TestCase { + static class Server { + private ServerSocketChannel serverChannel = ServerSocketChannel.open(); + private ServerSocket socket = null; + + Server() throws Exception { + serverChannel.configureBlocking(false); + } + + public void initialize() throws Exception { + this.socket = serverChannel.socket(); + socket.bind(new InetSocketAddress("localhost", 0)); + } + + public int getPort() { + return socket.getLocalPort(); + } + + public boolean isOpen() { + return !socket.isClosed(); + } + + public ServerSocketChannel getServerChannel() { + return serverChannel; + } + + public void accept() { + Thread serverThread = new Thread(new Runnable() { + public void run() { + try { + while (serverChannel.accept() == null) { + Thread.sleep(1000); + } + } catch (Exception e) {} + } + }); + serverThread.start(); + } + + public void close() throws Exception{ + serverChannel.close(); + } + } + + public void testSelectorAcceptAndRead() throws Exception { + Selector sel0 = Selector.open(); + Selector sel1 = Selector.open(); + Server server = new Server(); + SelectableChannel serverChannel = server.getServerChannel(); + SelectionKey mkey0 = serverChannel.register(sel0, SelectionKey.OP_ACCEPT); + serverChannel.register(sel1, SelectionKey.OP_ACCEPT); + + // HUP is treating as acceptable + assertEquals(1, sel0.select(100)); + assertEquals(true, sel0.selectedKeys().contains(mkey0)); + server.initialize(); + // after bind can not accept + assertEquals(0, sel1.select(100)); + server.accept(); + Thread.sleep(1000); + int port = server.getPort(); + SocketChannel socketChannel = SocketChannel.open(); + socketChannel.configureBlocking(false); + Selector sel2 = Selector.open(); + socketChannel.register(sel2, SelectionKey.OP_WRITE); + boolean isConnected = socketChannel.connect(new InetSocketAddress("localhost", port)); + if (!isConnected) { + socketChannel.finishConnect(); + } + + assertEquals(true, socketChannel.isConnected()); + server.close(); + Thread.sleep(3000); + assertEquals(true, socketChannel.isConnected()); + assertEquals(1, sel2.select(100)); + } + + public void testSelectUnConnectedChannel() throws Exception { + SocketChannel socketChannel2 = SocketChannel.open(); + socketChannel2.configureBlocking(false); + Selector sel3 = Selector.open(); + SelectionKey mkey3 = socketChannel2.register(sel3, SelectionKey.OP_WRITE); + // HUP is also treating as writable + assertEquals(1, sel3.select(100)); + assertEquals(false, mkey3.isConnectable()); + // even the channel is not connected, the selector could be writable + assertEquals(false, socketChannel2.isConnected()); + assertEquals(true, mkey3.isWritable()); + + Selector sel4 = Selector.open(); + SelectionKey mkey4 = socketChannel2.register(sel4, SelectionKey.OP_CONNECT); + assertEquals(1, sel4.select(100)); + assertEquals(false, mkey4.isWritable()); + assertEquals(true, mkey4.isConnectable()); + + Selector sel5 = Selector.open(); + SelectionKey mkey5 = socketChannel2.register(sel5, SelectionKey.OP_CONNECT | SelectionKey.OP_WRITE); + assertEquals(1, sel5.select(100)); + assertEquals(true, mkey5.isWritable()); + assertEquals(true, mkey5.isConnectable()); + } +} 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/nio/tests/java/nio/channels/UnresolvedAddressExceptionTest.java new file mode 100644 index 0000000..827dcd7 --- /dev/null +++ b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/UnresolvedAddressExceptionTest.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.nio.tests.java.nio.channels; + +import java.nio.channels.UnresolvedAddressException; + +import junit.framework.TestCase; + +import org.apache.harmony.testframework.serialization.SerializationTest; + +/** + * Tests for UnresolvedAddressException + */ +public class UnresolvedAddressExceptionTest extends TestCase { + + /** + * @tests {@link java.nio.channels.UnresolvedAddressException#UnresolvedAddressException()} + */ + public void test_Constructor() { + UnresolvedAddressException e = new UnresolvedAddressException(); + assertNull(e.getMessage()); + assertNull(e.getLocalizedMessage()); + assertNull(e.getCause()); + } + + /** + * @tests serialization/deserialization compatibility. + */ + public void testSerializationSelf() throws Exception { + + SerializationTest.verifySelf(new UnresolvedAddressException()); + } + + /** + * @tests serialization/deserialization compatibility with RI. + */ + public void testSerializationCompatibility() throws Exception { + + SerializationTest.verifyGolden(this, new 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/nio/tests/java/nio/channels/UnsupportedAddressTypeExceptionTest.java new file mode 100644 index 0000000..e032ea4 --- /dev/null +++ b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/UnsupportedAddressTypeExceptionTest.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.nio.tests.java.nio.channels; + +import java.nio.channels.UnsupportedAddressTypeException; + +import junit.framework.TestCase; + +import org.apache.harmony.testframework.serialization.SerializationTest; + +/** + * Tests for UnsupportedAddressTypeException + */ +public class UnsupportedAddressTypeExceptionTest extends TestCase { + + /** + * @tests {@link java.nio.channels.UnsupportedAddressTypeException#UnsupportedAddressTypeException()} + */ + public void test_Constructor() { + UnsupportedAddressTypeException e = new UnsupportedAddressTypeException(); + assertNull(e.getMessage()); + assertNull(e.getLocalizedMessage()); + assertNull(e.getCause()); + } + + /** + * @tests serialization/deserialization compatibility. + */ + public void testSerializationSelf() throws Exception { + + SerializationTest.verifySelf(new UnsupportedAddressTypeException()); + } + + /** + * @tests serialization/deserialization compatibility with RI. + */ + public void testSerializationCompatibility() throws Exception { + + SerializationTest.verifyGolden(this, + new 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/nio/tests/java/nio/channels/spi/AbstractInterruptibleChannelTest.java new file mode 100644 index 0000000..5072dc9 --- /dev/null +++ b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/spi/AbstractInterruptibleChannelTest.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.nio.tests.java.nio.channels.spi; + +import java.io.IOException; +import java.nio.channels.AsynchronousCloseException; +import java.nio.channels.spi.AbstractInterruptibleChannel; + +import junit.framework.TestCase; + +public class AbstractInterruptibleChannelTest extends TestCase { + + /** + * @tests AbstractInterruptibleChannel#close() + */ + public void test_close() throws IOException { + MockInterruptibleChannel testMiChannel = new MockInterruptibleChannel(); + assertTrue(testMiChannel.isOpen()); + testMiChannel.isImplCloseCalled = false; + testMiChannel.close(); + assertTrue(testMiChannel.isImplCloseCalled); + assertFalse(testMiChannel.isOpen()); + } + + /** + * @tests AbstractInterruptibleChannel#begin/end() + */ + public void test_begin_end() throws IOException { + boolean complete = false; + MockInterruptibleChannel testChannel = new MockInterruptibleChannel(); + try { + testChannel.superBegin(); + complete = true; + } finally { + testChannel.superEnd(complete); + } + + try { + testChannel.superBegin(); + complete = false; + } finally { + testChannel.superEnd(complete); + } + + try { + testChannel.superBegin(); + complete = true; + } finally { + testChannel.superEnd(complete); + } + + testChannel.superBegin(); + try { + testChannel.superBegin(); + complete = true; + } finally { + testChannel.superEnd(complete); + } + assertTrue(testChannel.isOpen()); + testChannel.close(); + } + + /** + * @tests AbstractInterruptibleChannel#close/begin/end() + */ + public void test_close_begin_end() throws IOException { + boolean complete = false; + MockInterruptibleChannel testChannel = new MockInterruptibleChannel(); + assertTrue(testChannel.isOpen()); + try { + testChannel.superBegin(); + complete = true; + } finally { + testChannel.superEnd(complete); + } + assertTrue(testChannel.isOpen()); + testChannel.close(); + try { + testChannel.superBegin(); + complete = false; + } finally { + try { + testChannel.superEnd(complete); + fail("should throw AsynchronousCloseException"); + } catch (AsynchronousCloseException e) { + // expected + } + } + assertFalse(testChannel.isOpen()); + try { + testChannel.superBegin(); + complete = true; + } finally { + testChannel.superEnd(complete); + } + assertFalse(testChannel.isOpen()); + } + + private class MockInterruptibleChannel extends AbstractInterruptibleChannel { + + private boolean isImplCloseCalled = false; + + public MockInterruptibleChannel() { + super(); + } + + protected void implCloseChannel() throws IOException { + isImplCloseCalled = true; + } + + // call super.begin() for test + void superBegin() { + super.begin(); + } + + // call super.end() for test + void superEnd(boolean completed) throws AsynchronousCloseException { + super.end(completed); + } + } +} diff --git a/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/nio/tests/java/nio/channels/spi/AbstractSelectableChannelTest.java new file mode 100644 index 0000000..b396264 --- /dev/null +++ b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/spi/AbstractSelectableChannelTest.java @@ -0,0 +1,313 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.harmony.nio.tests.java.nio.channels.spi; + +import java.io.IOException; +import java.nio.channels.ClosedChannelException; +import java.nio.channels.IllegalBlockingModeException; +import java.nio.channels.IllegalSelectorException; +import java.nio.channels.SelectableChannel; +import java.nio.channels.SelectionKey; +import java.nio.channels.Selector; +import java.nio.channels.SocketChannel; +import java.nio.channels.spi.AbstractSelectableChannel; +import java.nio.channels.spi.SelectorProvider; + +import junit.framework.TestCase; + +/** + * Tests for AbstractSelectableChannel + */ +public class AbstractSelectableChannelTest extends TestCase { + + private MockSelectableChannel testChannel; + + protected void setUp() throws Exception { + super.setUp(); + testChannel = new MockSelectableChannel(SelectorProvider.provider()); + } + + protected void tearDown() throws Exception { + if (testChannel.isOpen()) { + testChannel.close(); + } + } + + /** + * @tests AbstractSelectableChannel#implCloseChannel() + */ + public void test_implClose() throws IOException { + testChannel.isImplCloseSelectableChannelCalled = false; + testChannel.implCloseSelectableChannelCount = 0; + testChannel.close(); + assertFalse(testChannel.isOpen()); + assertTrue(testChannel.isImplCloseSelectableChannelCalled); + assertEquals(1, testChannel.implCloseSelectableChannelCount); + + testChannel = new MockSelectableChannel(SelectorProvider.provider()); + testChannel.isImplCloseSelectableChannelCalled = false; + testChannel.implCloseSelectableChannelCount = 0; + // close twice. + // make sure implCloseSelectableChannelCount is called only once. + testChannel.close(); + testChannel.close(); + assertFalse(testChannel.isOpen()); + assertTrue(testChannel.isImplCloseSelectableChannelCalled); + assertEquals(1, testChannel.implCloseSelectableChannelCount); + } + + /** + * @tests AbstractSelectableChannel#provider() + */ + public void test_provider() { + SelectorProvider provider = testChannel.provider(); + assertSame(SelectorProvider.provider(), provider); + testChannel = new MockSelectableChannel(null); + provider = testChannel.provider(); + assertNull(provider); + } + + /** + * @tests AbstractSelectableChannel#isBlocking() + */ + public void test_isBlocking() throws IOException { + assertTrue(testChannel.isBlocking()); + testChannel.configureBlocking(false); + assertFalse(testChannel.isBlocking()); + testChannel.configureBlocking(true); + assertTrue(testChannel.isBlocking()); + } + + /** + * + * @tests AbstractSelectableChannel#blockingLock() + */ + public void test_blockingLock() { + Object gotObj = testChannel.blockingLock(); + assertNotNull(gotObj); + } + + /** + * @tests AbstractSelectableChannel#register(Selector, int, Object) + */ + public void test_register_LSelectorILObject() throws IOException { + assertFalse(testChannel.isRegistered()); + Selector acceptSelector1 = SelectorProvider.provider().openSelector(); + Selector acceptSelector2 = new MockAbstractSelector(SelectorProvider + .provider()); + SocketChannel sc = SocketChannel.open(); + sc.configureBlocking(false); + SelectionKey acceptKey = sc.register(acceptSelector1, + SelectionKey.OP_READ, null); + assertNotNull(acceptKey); + assertTrue(acceptKey.isValid()); + assertSame(sc, acceptKey.channel()); + + //test that sc.register invokes Selector.register() + acceptKey = sc.register(acceptSelector2, SelectionKey.OP_READ, null); + assertNull(acceptKey); + + // Regression test to ensure acceptance of a selector with empty + // interest set. + SocketChannel channel = SocketChannel.open(); + channel.configureBlocking(false); + Selector selector = Selector.open(); + channel.register(selector, 0); + selector.close(); + channel.close(); + } + + /** + * @tests AbstractSelectableChannel#register(Selector, int, Object) + */ + public void test_register_LSelectorILObject_IllegalArgument() + throws IOException { + Selector acceptSelector = SelectorProvider.provider().openSelector(); + assertTrue(acceptSelector.isOpen()); + MockSelectableChannel msc = new MockSelectableChannel(SelectorProvider + .provider()); + msc.configureBlocking(false); + // in nonblocking mode + try { + //different SelectionKey with validOps + msc.register(acceptSelector, SelectionKey.OP_READ, null); + fail("Should throw IllegalArgumentException"); + } catch (IllegalArgumentException e) { + // expected + } + try { + msc.register(null, 0, null); + fail("Should throw NullPointerException"); + } catch (NullPointerException e) { + // expected + } + // in nonblocking mode, if selector closed + acceptSelector.close(); + try { + msc.register(acceptSelector, SelectionKey.OP_READ, null); + fail("Should throw IllegalArgumentException"); + } catch (IllegalArgumentException e) { + // expected + } + try { + msc.register(null, 0, null); + fail("Should throw NullPointerException"); + } catch (NullPointerException e) { + // expected + } + try { + msc.register(acceptSelector, 0, null); + fail("Should throw IllegalSelectorException"); + } catch (IllegalSelectorException e) { + // expected + } + + acceptSelector = SelectorProvider.provider().openSelector(); + // test in blocking mode + msc.configureBlocking(true); + try { + msc.register(acceptSelector, SelectionKey.OP_READ, null); + fail("Should throw IllegalArgumentException"); + } catch (IllegalArgumentException e) { + // expected + } + try { + msc.register(null, 0, null); + fail("Should throw IllegalBlockingModeException"); + } catch (IllegalBlockingModeException e) { + // expected + } + acceptSelector.close(); + // in blocking mode, if selector closed + try { + msc.register(acceptSelector, SelectionKey.OP_READ, null); + fail("Should throw IllegalArgumentException"); + } catch (IllegalArgumentException e) { + // expected + } + try { + msc.register(null, 0, null); + fail("Should throw IllegalBlockingModeException"); + } catch (IllegalBlockingModeException e) { + // expected + } + + // register with an object + Object argObj = new Object(); + SocketChannel sc = SocketChannel.open(); + sc.configureBlocking(false); + try { + sc.register(null, SelectionKey.OP_READ, argObj); + fail("Should throw NullPointerException"); + } catch (NullPointerException e) { + // expected + } + + // if channel closed + msc.close(); + try { + msc.register(acceptSelector, SelectionKey.OP_READ, null); + fail("Should throw ClosedChannelException"); + } catch (ClosedChannelException e) { + // expected + } + + } + + /** + * @tests AbstractSelectableChannel#keyFor(Selector) + */ + public void test_keyfor_LSelector() throws Exception { + SocketChannel sc = SocketChannel.open(); + Object argObj = new Object(); + sc.configureBlocking(false); + Selector acceptSelector = SelectorProvider.provider().openSelector(); + Selector acceptSelectorOther = SelectorProvider.provider() + .openSelector(); + SelectionKey acceptKey = sc.register(acceptSelector, + SelectionKey.OP_READ, argObj); + assertEquals(sc.keyFor(acceptSelector), acceptKey); + SelectionKey acceptKeyObjNull = sc.register(acceptSelector, + SelectionKey.OP_READ, null); + assertSame(sc.keyFor(acceptSelector), acceptKeyObjNull); + assertSame(acceptKeyObjNull, acceptKey); + SelectionKey acceptKeyOther = sc.register(acceptSelectorOther, + SelectionKey.OP_READ, null); + assertSame(sc.keyFor(acceptSelectorOther), acceptKeyOther); + } + + /** + * @tests AbstractSelectableChannel#configureBlocking(boolean) + */ + public void test_configureBlocking_Z_IllegalBlockingMode() throws Exception { + SocketChannel sc = SocketChannel.open(); + sc.configureBlocking(false); + Selector acceptSelector = SelectorProvider.provider().openSelector(); + SelectionKey acceptKey = sc.register(acceptSelector, + SelectionKey.OP_READ, null); + assertEquals(sc.keyFor(acceptSelector), acceptKey); + SelectableChannel getChannel = sc.configureBlocking(false); + assertEquals(getChannel, sc); + try { + sc.configureBlocking(true); + fail("Should throw IllegalBlockingModeException"); + } catch (IllegalBlockingModeException e) { + // expected + } + } + + /** + * @tests AbstractSelectableChannel#configureBlocking(boolean) + */ + public void test_configureBlocking_Z() throws Exception { + MockSelectableChannel mock = new MockSelectableChannel(SelectorProvider + .provider()); + //default blocking mode is true + //the implConfigureBlocking is only invoked if the given mode is different with current one + mock.configureBlocking(true); + assertFalse(mock.implConfigureBlockingCalled); + mock.configureBlocking(false); + assertTrue(mock.implConfigureBlockingCalled); + } + + private class MockSelectableChannel extends AbstractSelectableChannel { + + private boolean isImplCloseSelectableChannelCalled = false; + + private int implCloseSelectableChannelCount = 0; + + private boolean implConfigureBlockingCalled = false; + + public MockSelectableChannel(SelectorProvider arg0) { + super(arg0); + } + + protected void implCloseSelectableChannel() throws IOException { + isImplCloseSelectableChannelCalled = true; + ++implCloseSelectableChannelCount; + } + + protected void implConfigureBlocking(boolean arg0) throws IOException { + implConfigureBlockingCalled = true; + } + + public int validOps() { + return SelectionKey.OP_ACCEPT; + } + + } +} diff --git a/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/nio/tests/java/nio/channels/spi/AbstractSelectionKeyTest.java new file mode 100644 index 0000000..1404fc1 --- /dev/null +++ b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/spi/AbstractSelectionKeyTest.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.nio.tests.java.nio.channels.spi; + +import java.nio.channels.SelectableChannel; +import java.nio.channels.SelectionKey; +import java.nio.channels.Selector; +import java.nio.channels.spi.AbstractSelectionKey; + +import junit.framework.TestCase; + +public class AbstractSelectionKeyTest extends TestCase { + + /** + * @tests AbstractSelectionKey#isValid() without selector + */ + public void test_isValid() throws Exception { + MockSelectionKey testKey = new MockSelectionKey(); + assertTrue(testKey.isValid()); + } + + /** + * @tests AbstractSelectionKey#cancel + */ + public void test_cancel() throws Exception { + MockSelectionKey testKey = new MockSelectionKey(); + try { + testKey.cancel(); + fail("should throw NullPointerException"); + } catch (NullPointerException e) { + // expected: no selector available + } + assertFalse(testKey.isValid()); + } + + private class MockSelectionKey extends AbstractSelectionKey { + + MockSelectionKey() { + super(); + } + + public SelectableChannel channel() { + return null; + } + + public Selector selector() { + return null; + } + + public int interestOps() { + return 0; + } + + public SelectionKey interestOps(int arg0) { + return null; + } + + public int readyOps() { + return 0; + } + } +} diff --git a/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/nio/tests/java/nio/channels/spi/AbstractSelectorTest.java new file mode 100644 index 0000000..4b39001 --- /dev/null +++ b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/spi/AbstractSelectorTest.java @@ -0,0 +1,160 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.harmony.nio.tests.java.nio.channels.spi; + +import java.io.IOException; +import java.nio.channels.IllegalBlockingModeException; +import java.nio.channels.SelectionKey; +import java.nio.channels.Selector; +import java.nio.channels.ServerSocketChannel; +import java.nio.channels.spi.SelectorProvider; + +import junit.framework.TestCase; + +/** + * Tests for AbstractSelector and register of its default implementation + */ +public class AbstractSelectorTest extends TestCase { + + /** + * @tests AbstractSelector#provider() + */ + public void test_provider() throws IOException { + Selector mockSelector = new MockAbstractSelector(SelectorProvider + .provider()); + assertTrue(mockSelector.isOpen()); + assertSame(SelectorProvider.provider(), mockSelector.provider()); + mockSelector = new MockAbstractSelector(null); + assertNull(mockSelector.provider()); + } + + /** + * @tests AbstractSelector#close() + */ + public void test_close() throws IOException { + MockAbstractSelector mockSelector = new MockAbstractSelector( + SelectorProvider.provider()); + mockSelector.close(); + assertTrue(mockSelector.isImplCloseSelectorCalled); + } + + /** + * + * @tests AbstractSelector#begin/end() + */ + public void test_begin_end() throws IOException { + MockAbstractSelector mockSelector = new MockAbstractSelector( + SelectorProvider.provider()); + try { + mockSelector.superBegin(); + } finally { + mockSelector.superEnd(); + } + + mockSelector = new MockAbstractSelector(SelectorProvider.provider()); + try { + mockSelector.superBegin(); + mockSelector.close(); + } finally { + mockSelector.superEnd(); + } + + try { + // begin twice + mockSelector.superBegin(); + mockSelector.superBegin(); + } finally { + mockSelector.superEnd(); + } + + try { + mockSelector.superBegin(); + } finally { + // end twice + mockSelector.superEnd(); + mockSelector.superEnd(); + } + + mockSelector.close(); + try { + mockSelector.superBegin(); + } finally { + mockSelector.superEnd(); + } + } + + /** + * @tests AbstractSelector#isOpen() + */ + public void test_isOpen() throws Exception { + Selector acceptSelector = SelectorProvider.provider().openSelector(); + assertTrue(acceptSelector.isOpen()); + acceptSelector.close(); + assertFalse(acceptSelector.isOpen()); + } + + /** + * @tests AbstractSelector#register(Selector,int) + */ + public void test_register_LSelectorI() throws Exception { + Selector acceptSelector = SelectorProvider.provider().openSelector(); + ServerSocketChannel ssc = ServerSocketChannel.open(); + ssc.configureBlocking(false); + + assertFalse(ssc.isRegistered()); + SelectionKey acceptKey = ssc.register(acceptSelector, + SelectionKey.OP_ACCEPT); + assertTrue(ssc.isRegistered()); + assertNotNull(acceptKey); + assertTrue(acceptSelector.keys().contains(acceptKey)); + } + + /** + * @tests AbstractSelector#register(Selector,int) + */ + public void test_register_LSelectorI_error() throws IOException { + Selector acceptSelector = SelectorProvider.provider().openSelector(); + ServerSocketChannel ssc = ServerSocketChannel.open(); + ssc.configureBlocking(false); + acceptSelector.close(); + + assertFalse(acceptSelector.isOpen()); + try { + ssc.register(acceptSelector, SelectionKey.OP_ACCEPT); + fail("should throw NullPointerException"); + } catch (NullPointerException e) { + // expected + } + assertFalse(ssc.isRegistered()); + + acceptSelector = Selector.open(); + ssc.configureBlocking(true); + try { + ssc.register(acceptSelector, SelectionKey.OP_ACCEPT); + fail("should throw IllegalBlockingModeException"); + } catch (IllegalBlockingModeException e) { + // expected + } + assertFalse(ssc.isRegistered()); + ssc.configureBlocking(false); + SelectionKey acceptKey = ssc.register(acceptSelector, + SelectionKey.OP_ACCEPT); + assertNotNull(acceptKey); + assertTrue(acceptSelector.keys().contains(acceptKey)); + assertTrue(ssc.isRegistered()); + } +} 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/nio/tests/java/nio/channels/spi/MockAbstractSelector.java new file mode 100644 index 0000000..6e016b0 --- /dev/null +++ b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/spi/MockAbstractSelector.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.nio.tests.java.nio.channels.spi; + +import java.io.IOException; +import java.nio.channels.SelectionKey; +import java.nio.channels.Selector; +import java.nio.channels.spi.AbstractSelectableChannel; +import java.nio.channels.spi.AbstractSelectionKey; +import java.nio.channels.spi.AbstractSelector; +import java.nio.channels.spi.SelectorProvider; +import java.util.Set; + +public class MockAbstractSelector extends AbstractSelector { + + public boolean isImplCloseSelectorCalled = false; + + public MockAbstractSelector(SelectorProvider arg0) { + super(arg0); + } + + public static MockAbstractSelector openSelector() { + return new MockAbstractSelector(SelectorProvider.provider()); + } + + public Set getCancelledKeys() { + return super.cancelledKeys(); + } + + protected void implCloseSelector() throws IOException { + isImplCloseSelectorCalled = true; + } + + protected SelectionKey register(AbstractSelectableChannel arg0, int arg1, + Object arg2) { + return null; + } + + public void superBegin() { + super.begin(); + } + + public void superEnd() { + super.end(); + } + + protected void mockDeregister(AbstractSelectionKey key) { + super.deregister(key); + } + + public Set<SelectionKey> keys() { + return null; + } + + public Set<SelectionKey> selectedKeys() { + return null; + } + + public int selectNow() throws IOException { + return 0; + } + + public int select(long arg0) throws IOException { + return 0; + } + + public int select() throws IOException { + return 0; + } + + public Selector wakeup() { + return null; + } + +} diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/math/BigDecimalArithmeticTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/math/BigDecimalArithmeticTest.java new file mode 100644 index 0000000..ba71e2c --- /dev/null +++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/math/BigDecimalArithmeticTest.java @@ -0,0 +1,1623 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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.BigInteger; +import java.math.MathContext; +import java.math.RoundingMode; + +import junit.framework.TestCase; + +/** + * Class: java.math.BigDecimal + * Methods: add, subtract, multiply, divide + */ +public class BigDecimalArithmeticTest extends TestCase { + /** + * Add two numbers of equal positive scales + */ + public void testAddEqualScalePosPos() { + String a = "1231212478987482988429808779810457634781384756794987"; + int aScale = 10; + String b = "747233429293018787918347987234564568"; + int bScale = 10; + String c = "123121247898748373566323807282924555312937.1991359555"; + int cScale = 10; + BigDecimal aNumber = new BigDecimal(new BigInteger(a), aScale); + BigDecimal bNumber = new BigDecimal(new BigInteger(b), bScale); + BigDecimal result = aNumber.add(bNumber); + assertEquals("incorrect value", c, result.toString()); + assertEquals("incorrect scale", cScale, result.scale()); + } + + /** + * Add two numbers of equal positive scales using MathContext + */ + public void testAddMathContextEqualScalePosPos() { + String a = "1231212478987482988429808779810457634781384756794987"; + int aScale = 10; + String b = "747233429293018787918347987234564568"; + int bScale = 10; + String c = "1.2313E+41"; + int cScale = -37; + BigDecimal aNumber = new BigDecimal(new BigInteger(a), aScale); + BigDecimal bNumber = new BigDecimal(new BigInteger(b), bScale); + MathContext mc = new MathContext(5, RoundingMode.UP); + BigDecimal result = aNumber.add(bNumber, mc); + assertEquals("incorrect value", c, result.toString()); + assertEquals("incorrect scale", cScale, result.scale()); + } + + /** + * Add two numbers of equal negative scales + */ + public void testAddEqualScaleNegNeg() { + String a = "1231212478987482988429808779810457634781384756794987"; + int aScale = -10; + String b = "747233429293018787918347987234564568"; + int bScale = -10; + String c = "1.231212478987483735663238072829245553129371991359555E+61"; + int cScale = -10; + BigDecimal aNumber = new BigDecimal(new BigInteger(a), aScale); + BigDecimal bNumber = new BigDecimal(new BigInteger(b), bScale); + BigDecimal result = aNumber.add(bNumber); + assertEquals("incorrect value", c, result.toString()); + assertEquals("incorrect scale", cScale, result.scale()); + } + + /** + * Add two numbers of equal negative scales using MathContext + */ + public void testAddMathContextEqualScaleNegNeg() { + String a = "1231212478987482988429808779810457634781384756794987"; + int aScale = -10; + String b = "747233429293018787918347987234564568"; + int bScale = -10; + String c = "1.2312E+61"; + int cScale = -57; + BigDecimal aNumber = new BigDecimal(new BigInteger(a), aScale); + BigDecimal bNumber = new BigDecimal(new BigInteger(b), bScale); + MathContext mc = new MathContext(5, RoundingMode.FLOOR); + BigDecimal result = aNumber.add(bNumber, mc); + assertEquals("incorrect value ", c, result.toString()); + assertEquals("incorrect scale", cScale, result.scale()); + } + + /** + * Add two numbers of different scales; the first is positive + */ + public void testAddDiffScalePosNeg() { + String a = "1231212478987482988429808779810457634781384756794987"; + int aScale = 15; + String b = "747233429293018787918347987234564568"; + int bScale = -10; + String c = "7472334294161400358170962860775454459810457634.781384756794987"; + int cScale = 15; + BigDecimal aNumber = new BigDecimal(new BigInteger(a), aScale); + BigDecimal bNumber = new BigDecimal(new BigInteger(b), bScale); + BigDecimal result = aNumber.add(bNumber); + assertEquals("incorrect value", c, result.toString()); + assertEquals("incorrect scale", cScale, result.scale()); + } + + /** + * Add two numbers of different scales using MathContext; the first is positive + */ + public void testAddMathContextDiffScalePosNeg() { + String a = "1231212478987482988429808779810457634781384756794987"; + int aScale = 15; + String b = "747233429293018787918347987234564568"; + int bScale = -10; + String c = "7.47233429416141E+45"; + int cScale = -31; + BigDecimal aNumber = new BigDecimal(new BigInteger(a), aScale); + BigDecimal bNumber = new BigDecimal(new BigInteger(b), bScale); + MathContext mc = new MathContext(15, RoundingMode.CEILING); + BigDecimal result = aNumber.add(bNumber, mc); + assertEquals("incorrect value", c, c.toString()); + assertEquals("incorrect scale", cScale, result.scale()); + } + + /** + * Add two numbers of different scales; the first is negative + */ + public void testAddDiffScaleNegPos() { + String a = "1231212478987482988429808779810457634781384756794987"; + int aScale = -15; + String b = "747233429293018787918347987234564568"; + int bScale = 10; + String c = "1231212478987482988429808779810457634781459480137916301878791834798.7234564568"; + int cScale = 10; + BigDecimal aNumber = new BigDecimal(new BigInteger(a), aScale); + BigDecimal bNumber = new BigDecimal(new BigInteger(b), bScale); + BigDecimal result = aNumber.add(bNumber); + assertEquals("incorrect value", c, result.toString()); + assertEquals("incorrect scale", cScale, result.scale()); + } + + /** + * Add two zeroes of different scales; the first is negative + */ + public void testAddDiffScaleZeroZero() { + String a = "0"; + int aScale = -15; + String b = "0"; + int bScale = 10; + String c = "0E-10"; + int cScale = 10; + BigDecimal aNumber = new BigDecimal(new BigInteger(a), aScale); + BigDecimal bNumber = new BigDecimal(new BigInteger(b), bScale); + BigDecimal result = aNumber.add(bNumber); + assertEquals("incorrect value", c, result.toString()); + assertEquals("incorrect scale", cScale, result.scale()); + } + + /** + * Subtract two numbers of equal positive scales + */ + public void testSubtractEqualScalePosPos() { + String a = "1231212478987482988429808779810457634781384756794987"; + int aScale = 10; + String b = "747233429293018787918347987234564568"; + int bScale = 10; + String c = "123121247898748224119637948679166971643339.7522230419"; + int cScale = 10; + BigDecimal aNumber = new BigDecimal(new BigInteger(a), aScale); + BigDecimal bNumber = new BigDecimal(new BigInteger(b), bScale); + BigDecimal result = aNumber.subtract(bNumber); + assertEquals("incorrect value", c, result.toString()); + assertEquals("incorrect scale", cScale, result.scale()); + } + + /** + * Subtract two numbers of equal positive scales using MathContext + */ + public void testSubtractMathContextEqualScalePosPos() { + String a = "1231212478987482988429808779810457634781384756794987"; + int aScale = 10; + String b = "747233429293018787918347987234564568"; + int bScale = 10; + String c = "1.23121247898749E+41"; + int cScale = -27; + BigDecimal aNumber = new BigDecimal(new BigInteger(a), aScale); + BigDecimal bNumber = new BigDecimal(new BigInteger(b), bScale); + MathContext mc = new MathContext(15, RoundingMode.CEILING); + BigDecimal result = aNumber.subtract(bNumber, mc); + assertEquals("incorrect value", c, result.toString()); + assertEquals("incorrect scale", cScale, result.scale()); + } + + /** + * Subtract two numbers of equal negative scales + */ + public void testSubtractEqualScaleNegNeg() { + String a = "1231212478987482988429808779810457634781384756794987"; + int aScale = -10; + String b = "747233429293018787918347987234564568"; + int bScale = -10; + String c = "1.231212478987482241196379486791669716433397522230419E+61"; + int cScale = -10; + BigDecimal aNumber = new BigDecimal(new BigInteger(a), aScale); + BigDecimal bNumber = new BigDecimal(new BigInteger(b), bScale); + BigDecimal result = aNumber.subtract(bNumber); + assertEquals("incorrect value", c, result.toString()); + assertEquals("incorrect scale", cScale, result.scale()); + } + + /** + * Subtract two numbers of different scales; the first is positive + */ + public void testSubtractDiffScalePosNeg() { + String a = "1231212478987482988429808779810457634781384756794987"; + int aScale = 15; + String b = "747233429293018787918347987234564568"; + int bScale = -10; + String c = "-7472334291698975400195996883915836900189542365.218615243205013"; + int cScale = 15; + BigDecimal aNumber = new BigDecimal(new BigInteger(a), aScale); + BigDecimal bNumber = new BigDecimal(new BigInteger(b), bScale); + BigDecimal result = aNumber.subtract(bNumber); + assertEquals("incorrect value", c, result.toString()); + assertEquals("incorrect scale", cScale, result.scale()); + } + + /** + * Subtract two numbers of different scales using MathContext; + * the first is positive + */ + public void testSubtractMathContextDiffScalePosNeg() { + String a = "1231212478987482988429808779810457634781384756794987"; + int aScale = 15; + String b = "747233429293018787918347987234564568"; + int bScale = -10; + String c = "-7.4723342916989754E+45"; + int cScale = -29; + BigDecimal aNumber = new BigDecimal(new BigInteger(a), aScale); + BigDecimal bNumber = new BigDecimal(new BigInteger(b), bScale); + MathContext mc = new MathContext(17, RoundingMode.DOWN); + BigDecimal result = aNumber.subtract(bNumber, mc); + assertEquals("incorrect value", c, result.toString()); + assertEquals("incorrect scale", cScale, result.scale()); + } + + /** + * Subtract two numbers of different scales; the first is negative + */ + public void testSubtractDiffScaleNegPos() { + String a = "1231212478987482988429808779810457634781384756794987"; + int aScale = -15; + String b = "747233429293018787918347987234564568"; + int bScale = 10; + String c = "1231212478987482988429808779810457634781310033452057698121208165201.2765435432"; + int cScale = 10; + BigDecimal aNumber = new BigDecimal(new BigInteger(a), aScale); + BigDecimal bNumber = new BigDecimal(new BigInteger(b), bScale); + BigDecimal result = aNumber.subtract(bNumber); + assertEquals("incorrect value", c, result.toString()); + assertEquals("incorrect scale", cScale, result.scale()); + } + + /** + * Subtract two numbers of different scales using MathContext; + * the first is negative + */ + public void testSubtractMathContextDiffScaleNegPos() { + String a = "986798656676789766678767876078779810457634781384756794987"; + int aScale = -15; + String b = "747233429293018787918347987234564568"; + int bScale = 40; + String c = "9.867986566767897666787678760787798104576347813847567949870000000000000E+71"; + int cScale = -2; + BigDecimal aNumber = new BigDecimal(new BigInteger(a), aScale); + BigDecimal bNumber = new BigDecimal(new BigInteger(b), bScale); + MathContext mc = new MathContext(70, RoundingMode.HALF_DOWN); + BigDecimal result = aNumber.subtract(bNumber, mc); + assertEquals("incorrect value", c, result.toString()); + assertEquals("incorrect scale", cScale, result.scale()); + } + + /** + * Multiply two numbers of positive scales + */ + public void testMultiplyScalePosPos() { + String a = "1231212478987482988429808779810457634781384756794987"; + int aScale = 15; + String b = "747233429293018787918347987234564568"; + int bScale = 10; + String c = "92000312286217574978643009574114545567010139156902666284589309.1880727173060570190220616"; + int cScale = 25; + BigDecimal aNumber = new BigDecimal(new BigInteger(a), aScale); + BigDecimal bNumber = new BigDecimal(new BigInteger(b), bScale); + BigDecimal result = aNumber.multiply(bNumber); + assertEquals("incorrect value", c, result.toString()); + assertEquals("incorrect scale", cScale, result.scale()); + } + + /** + * Multiply two numbers of positive scales using MathContext + */ + public void testMultiplyMathContextScalePosPos() { + String a = "97665696756578755423325476545428779810457634781384756794987"; + int aScale = -25; + String b = "87656965586786097685674786576598865"; + int bScale = 10; + String c = "8.561078619600910561431314228543672720908E+108"; + int cScale = -69; + BigDecimal aNumber = new BigDecimal(new BigInteger(a), aScale); + BigDecimal bNumber = new BigDecimal(new BigInteger(b), bScale); + MathContext mc = new MathContext(40, RoundingMode.HALF_DOWN); + BigDecimal result = aNumber.multiply(bNumber, mc); + assertEquals("incorrect value", c, result.toString()); + assertEquals("incorrect scale", cScale, result.scale()); + } + + /** + * Multiply two numbers of negative scales + */ + public void testMultiplyEqualScaleNegNeg() { + String a = "1231212478987482988429808779810457634781384756794987"; + int aScale = -15; + String b = "747233429293018787918347987234564568"; + int bScale = -10; + String c = "9.20003122862175749786430095741145455670101391569026662845893091880727173060570190220616E+111"; + int cScale = -25; + BigDecimal aNumber = new BigDecimal(new BigInteger(a), aScale); + BigDecimal bNumber = new BigDecimal(new BigInteger(b), bScale); + BigDecimal result = aNumber.multiply(bNumber); + assertEquals("incorrect value", c, result.toString()); + assertEquals("incorrect scale", cScale, result.scale()); + } + + /** + * Multiply two numbers of different scales + */ + public void testMultiplyDiffScalePosNeg() { + String a = "1231212478987482988429808779810457634781384756794987"; + int aScale = 10; + String b = "747233429293018787918347987234564568"; + int bScale = -10; + String c = "920003122862175749786430095741145455670101391569026662845893091880727173060570190220616"; + int cScale = 0; + BigDecimal aNumber = new BigDecimal(new BigInteger(a), aScale); + BigDecimal bNumber = new BigDecimal(new BigInteger(b), bScale); + BigDecimal result = aNumber.multiply(bNumber); + assertEquals("incorrect value", c, result.toString()); + assertEquals("incorrect scale", cScale, result.scale()); + } + + /** + * Multiply two numbers of different scales using MathContext + */ + public void testMultiplyMathContextDiffScalePosNeg() { + String a = "987667796597975765768768767866756808779810457634781384756794987"; + int aScale = 100; + String b = "747233429293018787918347987234564568"; + int bScale = -70; + String c = "7.3801839465418518653942222612429081498248509257207477E+68"; + int cScale = -16; + BigDecimal aNumber = new BigDecimal(new BigInteger(a), aScale); + BigDecimal bNumber = new BigDecimal(new BigInteger(b), bScale); + MathContext mc = new MathContext(53, RoundingMode.HALF_UP); + BigDecimal result = aNumber.multiply(bNumber, mc); + assertEquals("incorrect value", c, result.toString()); + assertEquals("incorrect scale", cScale, result.scale()); + } + + /** + * Multiply two numbers of different scales + */ + public void testMultiplyDiffScaleNegPos() { + String a = "1231212478987482988429808779810457634781384756794987"; + int aScale = -15; + String b = "747233429293018787918347987234564568"; + int bScale = 10; + String c = "9.20003122862175749786430095741145455670101391569026662845893091880727173060570190220616E+91"; + int cScale = -5; + BigDecimal aNumber = new BigDecimal(new BigInteger(a), aScale); + BigDecimal bNumber = new BigDecimal(new BigInteger(b), bScale); + BigDecimal result = aNumber.multiply(bNumber); + assertEquals("incorrect value", c, result.toString()); + assertEquals("incorrect scale", cScale, result.scale()); + } + + /** + * Multiply two numbers of different scales using MathContext + */ + public void testMultiplyMathContextDiffScaleNegPos() { + String a = "488757458676796558668876576576579097029810457634781384756794987"; + int aScale = -63; + String b = "747233429293018787918347987234564568"; + int bScale = 63; + String c = "3.6521591193960361339707130098174381429788164316E+98"; + int cScale = -52; + BigDecimal aNumber = new BigDecimal(new BigInteger(a), aScale); + BigDecimal bNumber = new BigDecimal(new BigInteger(b), bScale); + MathContext mc = new MathContext(47, RoundingMode.HALF_UP); + BigDecimal result = aNumber.multiply(bNumber, mc); + assertEquals("incorrect value", c, result.toString()); + assertEquals("incorrect scale", cScale, result.scale()); + } + + /** + * pow(int) + */ + public void testPow() { + String a = "123121247898748298842980"; + int aScale = 10; + int exp = 10; + String c = "8004424019039195734129783677098845174704975003788210729597" + + "4875206425711159855030832837132149513512555214958035390490" + + "798520842025826.594316163502809818340013610490541783276343" + + "6514490899700151256484355936102754469438371850240000000000"; + int cScale = 100; + BigDecimal aNumber = new BigDecimal(new BigInteger(a), aScale); + BigDecimal result = aNumber.pow(exp); + assertEquals("incorrect value", c, result.toString()); + assertEquals("incorrect scale", cScale, result.scale()); + } + + /** + * pow(0) + */ + public void testPow0() { + String a = "123121247898748298842980"; + int aScale = 10; + int exp = 0; + String c = "1"; + int cScale = 0; + BigDecimal aNumber = new BigDecimal(new BigInteger(a), aScale); + BigDecimal result = aNumber.pow(exp); + assertEquals("incorrect value", c, result.toString()); + assertEquals("incorrect scale", cScale, result.scale()); + } + + /** + * ZERO.pow(0) + */ + public void testZeroPow0() { + String c = "1"; + int cScale = 0; + BigDecimal result = BigDecimal.ZERO.pow(0); + assertEquals("incorrect value", c, result.toString()); + assertEquals("incorrect scale", cScale, result.scale()); + } + + /** + * pow(int, MathContext) + */ + public void testPowMathContext() { + String a = "123121247898748298842980"; + int aScale = 10; + int exp = 10; + String c = "8.0044E+130"; + int cScale = -126; + BigDecimal aNumber = new BigDecimal(new BigInteger(a), aScale); + MathContext mc = new MathContext(5, RoundingMode.HALF_UP); + BigDecimal result = aNumber.pow(exp, mc); + assertEquals("incorrect value", c, result.toString()); + assertEquals("incorrect scale", cScale, result.scale()); + } + + /** + * Divide by zero + */ + public void testDivideByZero() { + String a = "1231212478987482988429808779810457634781384756794987"; + int aScale = 15; + BigDecimal aNumber = new BigDecimal(new BigInteger(a), aScale); + BigDecimal bNumber = BigDecimal.valueOf(0L); + try { + aNumber.divide(bNumber); + fail("ArithmeticException has not been caught"); + } catch (ArithmeticException e) { + assertEquals("Improper exception message", "Division by zero", e.getMessage()); + } + } + + /** + * Divide with ROUND_UNNECESSARY + */ + public void testDivideExceptionRM() { + String a = "1231212478987482988429808779810457634781384756794987"; + int aScale = 15; + String b = "747233429293018787918347987234564568"; + int bScale = 10; + BigDecimal aNumber = new BigDecimal(new BigInteger(a), aScale); + BigDecimal bNumber = new BigDecimal(new BigInteger(b), bScale); + try { + aNumber.divide(bNumber, BigDecimal.ROUND_UNNECESSARY); + fail("ArithmeticException has not been caught"); + } catch (ArithmeticException e) { + assertEquals("Improper exception message", "Rounding necessary", e.getMessage()); + } + } + + /** + * Divide with invalid rounding mode + */ + public void testDivideExceptionInvalidRM() { + String a = "1231212478987482988429808779810457634781384756794987"; + int aScale = 15; + String b = "747233429293018787918347987234564568"; + int bScale = 10; + BigDecimal aNumber = new BigDecimal(new BigInteger(a), aScale); + BigDecimal bNumber = new BigDecimal(new BigInteger(b), bScale); + try { + aNumber.divide(bNumber, 100); + fail("IllegalArgumentException has not been caught"); + } catch (IllegalArgumentException e) { + assertEquals("Improper exception message", "Invalid rounding mode", e.getMessage()); + } + } + + /** + * Divide: local variable exponent is less than zero + */ + public void testDivideExpLessZero() { + String a = "1231212478987482988429808779810457634781384756794987"; + int aScale = 15; + String b = "747233429293018787918347987234564568"; + int bScale = 10; + String c = "1.64770E+10"; + int resScale = -5; + BigDecimal aNumber = new BigDecimal(new BigInteger(a), aScale); + BigDecimal bNumber = new BigDecimal(new BigInteger(b), bScale); + BigDecimal result = aNumber.divide(bNumber, resScale, BigDecimal.ROUND_CEILING); + assertEquals("incorrect value", c, result.toString()); + assertEquals("incorrect scale", resScale, result.scale()); + } + + /** + * Divide: local variable exponent is equal to zero + */ + public void testDivideExpEqualsZero() { + String a = "1231212478987482988429808779810457634781384756794987"; + int aScale = -15; + String b = "747233429293018787918347987234564568"; + int bScale = 10; + String c = "1.64769459009933764189139568605273529E+40"; + int resScale = -5; + BigDecimal aNumber = new BigDecimal(new BigInteger(a), aScale); + BigDecimal bNumber = new BigDecimal(new BigInteger(b), bScale); + BigDecimal result = aNumber.divide(bNumber, resScale, BigDecimal.ROUND_CEILING); + assertEquals("incorrect value", c, result.toString()); + assertEquals("incorrect scale", resScale, result.scale()); + } + + /** + * Divide: local variable exponent is greater than zero + */ + public void testDivideExpGreaterZero() { + String a = "1231212478987482988429808779810457634781384756794987"; + int aScale = -15; + String b = "747233429293018787918347987234564568"; + int bScale = 20; + String c = "1.647694590099337641891395686052735285121058381E+50"; + int resScale = -5; + BigDecimal aNumber = new BigDecimal(new BigInteger(a), aScale); + BigDecimal bNumber = new BigDecimal(new BigInteger(b), bScale); + BigDecimal result = aNumber.divide(bNumber, resScale, BigDecimal.ROUND_CEILING); + assertEquals("incorrect value", c, result.toString()); + assertEquals("incorrect scale", resScale, result.scale()); + } + + /** + * Divide: remainder is zero + */ + public void testDivideRemainderIsZero() { + String a = "8311389578904553209874735431110"; + int aScale = -15; + String b = "237468273682987234567849583746"; + int bScale = 20; + String c = "3.5000000000000000000000000000000E+36"; + int resScale = -5; + BigDecimal aNumber = new BigDecimal(new BigInteger(a), aScale); + BigDecimal bNumber = new BigDecimal(new BigInteger(b), bScale); + BigDecimal result = aNumber.divide(bNumber, resScale, BigDecimal.ROUND_CEILING); + assertEquals("incorrect value", c, result.toString()); + assertEquals("incorrect scale", resScale, result.scale()); + } + + /** + * Divide: rounding mode is ROUND_UP, result is negative + */ + public void testDivideRoundUpNeg() { + String a = "-92948782094488478231212478987482988429808779810457634781384756794987"; + int aScale = -24; + String b = "7472334223847623782375469293018787918347987234564568"; + int bScale = 13; + String c = "-1.24390557635720517122423359799284E+53"; + int resScale = -21; + BigDecimal aNumber = new BigDecimal(new BigInteger(a), aScale); + BigDecimal bNumber = new BigDecimal(new BigInteger(b), bScale); + BigDecimal result = aNumber.divide(bNumber, resScale, BigDecimal.ROUND_UP); + assertEquals("incorrect value", c, result.toString()); + assertEquals("incorrect scale", resScale, result.scale()); + } + + /** + * Divide: rounding mode is ROUND_UP, result is positive + */ + public void testDivideRoundUpPos() { + String a = "92948782094488478231212478987482988429808779810457634781384756794987"; + int aScale = -24; + String b = "7472334223847623782375469293018787918347987234564568"; + int bScale = 13; + String c = "1.24390557635720517122423359799284E+53"; + int resScale = -21; + BigDecimal aNumber = new BigDecimal(new BigInteger(a), aScale); + BigDecimal bNumber = new BigDecimal(new BigInteger(b), bScale); + BigDecimal result = aNumber.divide(bNumber, resScale, BigDecimal.ROUND_UP); + assertEquals("incorrect value", c, result.toString()); + assertEquals("incorrect scale", resScale, result.scale()); + } + + /** + * Divide: rounding mode is ROUND_DOWN, result is negative + */ + public void testDivideRoundDownNeg() { + String a = "-92948782094488478231212478987482988429808779810457634781384756794987"; + int aScale = -24; + String b = "7472334223847623782375469293018787918347987234564568"; + int bScale = 13; + String c = "-1.24390557635720517122423359799283E+53"; + int resScale = -21; + BigDecimal aNumber = new BigDecimal(new BigInteger(a), aScale); + BigDecimal bNumber = new BigDecimal(new BigInteger(b), bScale); + BigDecimal result = aNumber.divide(bNumber, resScale, BigDecimal.ROUND_DOWN); + assertEquals("incorrect value", c, result.toString()); + assertEquals("incorrect scale", resScale, result.scale()); + } + + /** + * Divide: rounding mode is ROUND_DOWN, result is positive + */ + public void testDivideRoundDownPos() { + String a = "92948782094488478231212478987482988429808779810457634781384756794987"; + int aScale = -24; + String b = "7472334223847623782375469293018787918347987234564568"; + int bScale = 13; + String c = "1.24390557635720517122423359799283E+53"; + int resScale = -21; + BigDecimal aNumber = new BigDecimal(new BigInteger(a), aScale); + BigDecimal bNumber = new BigDecimal(new BigInteger(b), bScale); + BigDecimal result = aNumber.divide(bNumber, resScale, BigDecimal.ROUND_DOWN); + assertEquals("incorrect value", c, result.toString()); + assertEquals("incorrect scale", resScale, result.scale()); + } + + /** + * Divide: rounding mode is ROUND_FLOOR, result is positive + */ + public void testDivideRoundFloorPos() { + String a = "92948782094488478231212478987482988429808779810457634781384756794987"; + int aScale = -24; + String b = "7472334223847623782375469293018787918347987234564568"; + int bScale = 13; + String c = "1.24390557635720517122423359799283E+53"; + int resScale = -21; + BigDecimal aNumber = new BigDecimal(new BigInteger(a), aScale); + BigDecimal bNumber = new BigDecimal(new BigInteger(b), bScale); + BigDecimal result = aNumber.divide(bNumber, resScale, BigDecimal.ROUND_FLOOR); + assertEquals("incorrect value", c, result.toString()); + assertEquals("incorrect scale", resScale, result.scale()); + } + + /** + * Divide: rounding mode is ROUND_FLOOR, result is negative + */ + public void testDivideRoundFloorNeg() { + String a = "-92948782094488478231212478987482988429808779810457634781384756794987"; + int aScale = -24; + String b = "7472334223847623782375469293018787918347987234564568"; + int bScale = 13; + String c = "-1.24390557635720517122423359799284E+53"; + int resScale = -21; + BigDecimal aNumber = new BigDecimal(new BigInteger(a), aScale); + BigDecimal bNumber = new BigDecimal(new BigInteger(b), bScale); + BigDecimal result = aNumber.divide(bNumber, resScale, BigDecimal.ROUND_FLOOR); + assertEquals("incorrect value", c, result.toString()); + assertEquals("incorrect scale", resScale, result.scale()); + } + + /** + * Divide: rounding mode is ROUND_CEILING, result is positive + */ + public void testDivideRoundCeilingPos() { + String a = "92948782094488478231212478987482988429808779810457634781384756794987"; + int aScale = -24; + String b = "7472334223847623782375469293018787918347987234564568"; + int bScale = 13; + String c = "1.24390557635720517122423359799284E+53"; + int resScale = -21; + BigDecimal aNumber = new BigDecimal(new BigInteger(a), aScale); + BigDecimal bNumber = new BigDecimal(new BigInteger(b), bScale); + BigDecimal result = aNumber.divide(bNumber, resScale, BigDecimal.ROUND_CEILING); + assertEquals("incorrect value", c, result.toString()); + assertEquals("incorrect scale", resScale, result.scale()); + } + + /** + * Divide: rounding mode is ROUND_CEILING, result is negative + */ + public void testDivideRoundCeilingNeg() { + String a = "-92948782094488478231212478987482988429808779810457634781384756794987"; + int aScale = -24; + String b = "7472334223847623782375469293018787918347987234564568"; + int bScale = 13; + String c = "-1.24390557635720517122423359799283E+53"; + int resScale = -21; + BigDecimal aNumber = new BigDecimal(new BigInteger(a), aScale); + BigDecimal bNumber = new BigDecimal(new BigInteger(b), bScale); + BigDecimal result = aNumber.divide(bNumber, resScale, BigDecimal.ROUND_CEILING); + assertEquals("incorrect value", c, result.toString()); + assertEquals("incorrect scale", resScale, result.scale()); + } + + /** + * Divide: rounding mode is ROUND_HALF_UP, result is positive; distance = -1 + */ + public void testDivideRoundHalfUpPos() { + String a = "92948782094488478231212478987482988429808779810457634781384756794987"; + int aScale = -24; + String b = "7472334223847623782375469293018787918347987234564568"; + int bScale = 13; + String c = "1.24390557635720517122423359799284E+53"; + int resScale = -21; + BigDecimal aNumber = new BigDecimal(new BigInteger(a), aScale); + BigDecimal bNumber = new BigDecimal(new BigInteger(b), bScale); + BigDecimal result = aNumber.divide(bNumber, resScale, BigDecimal.ROUND_HALF_UP); + assertEquals("incorrect value", c, result.toString()); + assertEquals("incorrect scale", resScale, result.scale()); + } + + /** + * Divide: rounding mode is ROUND_HALF_UP, result is negative; distance = -1 + */ + public void testDivideRoundHalfUpNeg() { + String a = "-92948782094488478231212478987482988429808779810457634781384756794987"; + int aScale = -24; + String b = "7472334223847623782375469293018787918347987234564568"; + int bScale = 13; + String c = "-1.24390557635720517122423359799284E+53"; + int resScale = -21; + BigDecimal aNumber = new BigDecimal(new BigInteger(a), aScale); + BigDecimal bNumber = new BigDecimal(new BigInteger(b), bScale); + BigDecimal result = aNumber.divide(bNumber, resScale, BigDecimal.ROUND_HALF_UP); + assertEquals("incorrect value", c, result.toString()); + assertEquals("incorrect scale", resScale, result.scale()); + } + + /** + * Divide: rounding mode is ROUND_HALF_UP, result is positive; distance = 1 + */ + public void testDivideRoundHalfUpPos1() { + String a = "92948782094488478231212478987482988798104576347813847567949855464535634534563456"; + int aScale = -24; + String b = "74723342238476237823754692930187879183479"; + int bScale = 13; + String c = "1.2439055763572051712242335979928354832010167729111113605E+76"; + int resScale = -21; + BigDecimal aNumber = new BigDecimal(new BigInteger(a), aScale); + BigDecimal bNumber = new BigDecimal(new BigInteger(b), bScale); + BigDecimal result = aNumber.divide(bNumber, resScale, BigDecimal.ROUND_HALF_UP); + assertEquals("incorrect value", c, result.toString()); + assertEquals("incorrect scale", resScale, result.scale()); + } + + /** + * Divide: rounding mode is ROUND_HALF_UP, result is negative; distance = 1 + */ + public void testDivideRoundHalfUpNeg1() { + String a = "-92948782094488478231212478987482988798104576347813847567949855464535634534563456"; + int aScale = -24; + String b = "74723342238476237823754692930187879183479"; + int bScale = 13; + String c = "-1.2439055763572051712242335979928354832010167729111113605E+76"; + int resScale = -21; + BigDecimal aNumber = new BigDecimal(new BigInteger(a), aScale); + BigDecimal bNumber = new BigDecimal(new BigInteger(b), bScale); + BigDecimal result = aNumber.divide(bNumber, resScale, BigDecimal.ROUND_HALF_UP); + assertEquals("incorrect value", c, result.toString()); + assertEquals("incorrect scale", resScale, result.scale()); + } + + /** + * Divide: rounding mode is ROUND_HALF_UP, result is negative; equidistant + */ + public void testDivideRoundHalfUpNeg2() { + String a = "-37361671119238118911893939591735"; + int aScale = 10; + String b = "74723342238476237823787879183470"; + int bScale = 15; + String c = "-1E+5"; + int resScale = -5; + BigDecimal aNumber = new BigDecimal(new BigInteger(a), aScale); + BigDecimal bNumber = new BigDecimal(new BigInteger(b), bScale); + BigDecimal result = aNumber.divide(bNumber, resScale, BigDecimal.ROUND_HALF_UP); + assertEquals("incorrect value", c, result.toString()); + assertEquals("incorrect scale", resScale, result.scale()); + } + + /** + * Divide: rounding mode is ROUND_HALF_DOWN, result is positive; distance = -1 + */ + public void testDivideRoundHalfDownPos() { + String a = "92948782094488478231212478987482988429808779810457634781384756794987"; + int aScale = -24; + String b = "7472334223847623782375469293018787918347987234564568"; + int bScale = 13; + String c = "1.24390557635720517122423359799284E+53"; + int resScale = -21; + BigDecimal aNumber = new BigDecimal(new BigInteger(a), aScale); + BigDecimal bNumber = new BigDecimal(new BigInteger(b), bScale); + BigDecimal result = aNumber.divide(bNumber, resScale, BigDecimal.ROUND_HALF_DOWN); + assertEquals("incorrect value", c, result.toString()); + assertEquals("incorrect scale", resScale, result.scale()); + } + + /** + * Divide: rounding mode is ROUND_HALF_DOWN, result is negative; distance = -1 + */ + public void testDivideRoundHalfDownNeg() { + String a = "-92948782094488478231212478987482988429808779810457634781384756794987"; + int aScale = -24; + String b = "7472334223847623782375469293018787918347987234564568"; + int bScale = 13; + String c = "-1.24390557635720517122423359799284E+53"; + int resScale = -21; + BigDecimal aNumber = new BigDecimal(new BigInteger(a), aScale); + BigDecimal bNumber = new BigDecimal(new BigInteger(b), bScale); + BigDecimal result = aNumber.divide(bNumber, resScale, BigDecimal.ROUND_HALF_DOWN); + assertEquals("incorrect value", c, result.toString()); + assertEquals("incorrect scale", resScale, result.scale()); + } + + /** + * Divide: rounding mode is ROUND_HALF_DOWN, result is positive; distance = 1 + */ + public void testDivideRoundHalfDownPos1() { + String a = "92948782094488478231212478987482988798104576347813847567949855464535634534563456"; + int aScale = -24; + String b = "74723342238476237823754692930187879183479"; + int bScale = 13; + String c = "1.2439055763572051712242335979928354832010167729111113605E+76"; + int resScale = -21; + BigDecimal aNumber = new BigDecimal(new BigInteger(a), aScale); + BigDecimal bNumber = new BigDecimal(new BigInteger(b), bScale); + BigDecimal result = aNumber.divide(bNumber, resScale, BigDecimal.ROUND_HALF_DOWN); + assertEquals("incorrect value", c, result.toString()); + assertEquals("incorrect scale", resScale, result.scale()); + } + + /** + * Divide: rounding mode is ROUND_HALF_DOWN, result is negative; distance = 1 + */ + public void testDivideRoundHalfDownNeg1() { + String a = "-92948782094488478231212478987482988798104576347813847567949855464535634534563456"; + int aScale = -24; + String b = "74723342238476237823754692930187879183479"; + int bScale = 13; + String c = "-1.2439055763572051712242335979928354832010167729111113605E+76"; + int resScale = -21; + BigDecimal aNumber = new BigDecimal(new BigInteger(a), aScale); + BigDecimal bNumber = new BigDecimal(new BigInteger(b), bScale); + BigDecimal result = aNumber.divide(bNumber, resScale, BigDecimal.ROUND_HALF_DOWN); + assertEquals("incorrect value", c, result.toString()); + assertEquals("incorrect scale", resScale, result.scale()); + } + + /** + * Divide: rounding mode is ROUND_HALF_UP, result is negative; equidistant + */ + public void testDivideRoundHalfDownNeg2() { + String a = "-37361671119238118911893939591735"; + int aScale = 10; + String b = "74723342238476237823787879183470"; + int bScale = 15; + String c = "0E+5"; + int resScale = -5; + BigDecimal aNumber = new BigDecimal(new BigInteger(a), aScale); + BigDecimal bNumber = new BigDecimal(new BigInteger(b), bScale); + BigDecimal result = aNumber.divide(bNumber, resScale, BigDecimal.ROUND_HALF_DOWN); + assertEquals("incorrect value", c, result.toString()); + assertEquals("incorrect scale", resScale, result.scale()); + } + + /** + * Divide: rounding mode is ROUND_HALF_EVEN, result is positive; distance = -1 + */ + public void testDivideRoundHalfEvenPos() { + String a = "92948782094488478231212478987482988429808779810457634781384756794987"; + int aScale = -24; + String b = "7472334223847623782375469293018787918347987234564568"; + int bScale = 13; + String c = "1.24390557635720517122423359799284E+53"; + int resScale = -21; + BigDecimal aNumber = new BigDecimal(new BigInteger(a), aScale); + BigDecimal bNumber = new BigDecimal(new BigInteger(b), bScale); + BigDecimal result = aNumber.divide(bNumber, resScale, BigDecimal.ROUND_HALF_EVEN); + assertEquals("incorrect value", c, result.toString()); + assertEquals("incorrect scale", resScale, result.scale()); + } + + /** + * Divide: rounding mode is ROUND_HALF_EVEN, result is negative; distance = -1 + */ + public void testDivideRoundHalfEvenNeg() { + String a = "-92948782094488478231212478987482988429808779810457634781384756794987"; + int aScale = -24; + String b = "7472334223847623782375469293018787918347987234564568"; + int bScale = 13; + String c = "-1.24390557635720517122423359799284E+53"; + int resScale = -21; + BigDecimal aNumber = new BigDecimal(new BigInteger(a), aScale); + BigDecimal bNumber = new BigDecimal(new BigInteger(b), bScale); + BigDecimal result = aNumber.divide(bNumber, resScale, BigDecimal.ROUND_HALF_EVEN); + assertEquals("incorrect value", c, result.toString()); + assertEquals("incorrect scale", resScale, result.scale()); + } + + /** + * Divide: rounding mode is ROUND_HALF_EVEN, result is positive; distance = 1 + */ + public void testDivideRoundHalfEvenPos1() { + String a = "92948782094488478231212478987482988798104576347813847567949855464535634534563456"; + int aScale = -24; + String b = "74723342238476237823754692930187879183479"; + int bScale = 13; + String c = "1.2439055763572051712242335979928354832010167729111113605E+76"; + int resScale = -21; + BigDecimal aNumber = new BigDecimal(new BigInteger(a), aScale); + BigDecimal bNumber = new BigDecimal(new BigInteger(b), bScale); + BigDecimal result = aNumber.divide(bNumber, resScale, BigDecimal.ROUND_HALF_EVEN); + assertEquals("incorrect value", c, result.toString()); + assertEquals("incorrect scale", resScale, result.scale()); + } + + /** + * Divide: rounding mode is ROUND_HALF_EVEN, result is negative; distance = 1 + */ + public void testDivideRoundHalfEvenNeg1() { + String a = "-92948782094488478231212478987482988798104576347813847567949855464535634534563456"; + int aScale = -24; + String b = "74723342238476237823754692930187879183479"; + int bScale = 13; + String c = "-1.2439055763572051712242335979928354832010167729111113605E+76"; + int resScale = -21; + BigDecimal aNumber = new BigDecimal(new BigInteger(a), aScale); + BigDecimal bNumber = new BigDecimal(new BigInteger(b), bScale); + BigDecimal result = aNumber.divide(bNumber, resScale, BigDecimal.ROUND_HALF_EVEN); + assertEquals("incorrect value", c, result.toString()); + assertEquals("incorrect scale", resScale, result.scale()); + } + + /** + * Divide: rounding mode is ROUND_HALF_EVEN, result is negative; equidistant + */ + public void testDivideRoundHalfEvenNeg2() { + String a = "-37361671119238118911893939591735"; + int aScale = 10; + String b = "74723342238476237823787879183470"; + int bScale = 15; + String c = "0E+5"; + int resScale = -5; + BigDecimal aNumber = new BigDecimal(new BigInteger(a), aScale); + BigDecimal bNumber = new BigDecimal(new BigInteger(b), bScale); + BigDecimal result = aNumber.divide(bNumber, resScale, BigDecimal.ROUND_HALF_EVEN); + assertEquals("incorrect value", c, result.toString()); + assertEquals("incorrect scale", resScale, result.scale()); + } + + /** + * Divide to BigDecimal + */ + public void testDivideBigDecimal1() { + String a = "-37361671119238118911893939591735"; + int aScale = 10; + String b = "74723342238476237823787879183470"; + int bScale = 15; + String c = "-5E+4"; + int resScale = -4; + BigDecimal aNumber = new BigDecimal(new BigInteger(a), aScale); + BigDecimal bNumber = new BigDecimal(new BigInteger(b), bScale); + BigDecimal result = aNumber.divide(bNumber); + assertEquals("incorrect value", c, result.toString()); + assertEquals("incorrect scale", resScale, result.scale()); + } + + /** + * Divide to BigDecimal + */ + public void testDivideBigDecimal2() { + String a = "-37361671119238118911893939591735"; + int aScale = 10; + String b = "74723342238476237823787879183470"; + int bScale = -15; + String c = "-5E-26"; + int resScale = 26; + BigDecimal aNumber = new BigDecimal(new BigInteger(a), aScale); + BigDecimal bNumber = new BigDecimal(new BigInteger(b), bScale); + BigDecimal result = aNumber.divide(bNumber); + assertEquals("incorrect value", c, result.toString()); + assertEquals("incorrect scale", resScale, result.scale()); + } + + /** + * divide(BigDecimal, scale, RoundingMode) + */ + public void testDivideBigDecimalScaleRoundingModeUP() { + String a = "-37361671119238118911893939591735"; + int aScale = 10; + String b = "74723342238476237823787879183470"; + int bScale = -15; + int newScale = 31; + RoundingMode rm = RoundingMode.UP; + String c = "-5.00000E-26"; + BigDecimal aNumber = new BigDecimal(new BigInteger(a), aScale); + BigDecimal bNumber = new BigDecimal(new BigInteger(b), bScale); + BigDecimal result = aNumber.divide(bNumber, newScale, rm); + assertEquals("incorrect value", c, result.toString()); + assertEquals("incorrect scale", newScale, result.scale()); + } + + /** + * divide(BigDecimal, scale, RoundingMode) + */ + public void testDivideBigDecimalScaleRoundingModeDOWN() { + String a = "-37361671119238118911893939591735"; + int aScale = 10; + String b = "74723342238476237823787879183470"; + int bScale = 15; + int newScale = 31; + RoundingMode rm = RoundingMode.DOWN; + String c = "-50000.0000000000000000000000000000000"; + BigDecimal aNumber = new BigDecimal(new BigInteger(a), aScale); + BigDecimal bNumber = new BigDecimal(new BigInteger(b), bScale); + BigDecimal result = aNumber.divide(bNumber, newScale, rm); + assertEquals("incorrect value", c, result.toString()); + assertEquals("incorrect scale", newScale, result.scale()); + } + + /** + * divide(BigDecimal, scale, RoundingMode) + */ + public void testDivideBigDecimalScaleRoundingModeCEILING() { + String a = "3736186567876876578956958765675671119238118911893939591735"; + int aScale = 100; + String b = "74723342238476237823787879183470"; + int bScale = 15; + int newScale = 45; + RoundingMode rm = RoundingMode.CEILING; + String c = "1E-45"; + BigDecimal aNumber = new BigDecimal(new BigInteger(a), aScale); + BigDecimal bNumber = new BigDecimal(new BigInteger(b), bScale); + BigDecimal result = aNumber.divide(bNumber, newScale, rm); + assertEquals("incorrect value", c, result.toString()); + assertEquals("incorrect scale", newScale, result.scale()); + } + + /** + * divide(BigDecimal, scale, RoundingMode) + */ + public void testDivideBigDecimalScaleRoundingModeFLOOR() { + String a = "3736186567876876578956958765675671119238118911893939591735"; + int aScale = 100; + String b = "74723342238476237823787879183470"; + int bScale = 15; + int newScale = 45; + RoundingMode rm = RoundingMode.FLOOR; + String c = "0E-45"; + BigDecimal aNumber = new BigDecimal(new BigInteger(a), aScale); + BigDecimal bNumber = new BigDecimal(new BigInteger(b), bScale); + BigDecimal result = aNumber.divide(bNumber, newScale, rm); + assertEquals("incorrect value", c, result.toString()); + assertEquals("incorrect scale", newScale, result.scale()); + } + + /** + * divide(BigDecimal, scale, RoundingMode) + */ + public void testDivideBigDecimalScaleRoundingModeHALF_UP() { + String a = "3736186567876876578956958765675671119238118911893939591735"; + int aScale = -51; + String b = "74723342238476237823787879183470"; + int bScale = 45; + int newScale = 3; + RoundingMode rm = RoundingMode.HALF_UP; + String c = "50000260373164286401361913262100972218038099522752460421" + + "05959924024355721031761947728703598332749334086415670525" + + "3761096961.670"; + BigDecimal aNumber = new BigDecimal(new BigInteger(a), aScale); + BigDecimal bNumber = new BigDecimal(new BigInteger(b), bScale); + BigDecimal result = aNumber.divide(bNumber, newScale, rm); + assertEquals("incorrect value", c, result.toString()); + assertEquals("incorrect scale", newScale, result.scale()); + } + + /** + * divide(BigDecimal, scale, RoundingMode) + */ + public void testDivideBigDecimalScaleRoundingModeHALF_DOWN() { + String a = "3736186567876876578956958765675671119238118911893939591735"; + int aScale = 5; + String b = "74723342238476237823787879183470"; + int bScale = 15; + int newScale = 7; + RoundingMode rm = RoundingMode.HALF_DOWN; + String c = "500002603731642864013619132621009722.1803810"; + BigDecimal aNumber = new BigDecimal(new BigInteger(a), aScale); + BigDecimal bNumber = new BigDecimal(new BigInteger(b), bScale); + BigDecimal result = aNumber.divide(bNumber, newScale, rm); + assertEquals("incorrect value", c, result.toString()); + assertEquals("incorrect scale", newScale, result.scale()); + } + + /** + * divide(BigDecimal, scale, RoundingMode) + */ + public void testDivideBigDecimalScaleRoundingModeHALF_EVEN() { + String a = "3736186567876876578956958765675671119238118911893939591735"; + int aScale = 5; + String b = "74723342238476237823787879183470"; + int bScale = 15; + int newScale = 7; + RoundingMode rm = RoundingMode.HALF_EVEN; + String c = "500002603731642864013619132621009722.1803810"; + BigDecimal aNumber = new BigDecimal(new BigInteger(a), aScale); + BigDecimal bNumber = new BigDecimal(new BigInteger(b), bScale); + BigDecimal result = aNumber.divide(bNumber, newScale, rm); + assertEquals("incorrect value", c, result.toString()); + assertEquals("incorrect scale", newScale, result.scale()); + } + + /** + * divide(BigDecimal, MathContext) + */ + public void testDivideBigDecimalScaleMathContextUP() { + String a = "3736186567876876578956958765675671119238118911893939591735"; + int aScale = 15; + String b = "748766876876723342238476237823787879183470"; + int bScale = 10; + int precision = 21; + RoundingMode rm = RoundingMode.UP; + MathContext mc = new MathContext(precision, rm); + String c = "49897861180.2562512996"; + int resScale = 10; + BigDecimal aNumber = new BigDecimal(new BigInteger(a), aScale); + BigDecimal bNumber = new BigDecimal(new BigInteger(b), bScale); + BigDecimal result = aNumber.divide(bNumber, mc); + assertEquals("incorrect value", c, result.toString()); + assertEquals("incorrect scale", resScale, result.scale()); + } + + /** + * divide(BigDecimal, MathContext) + */ + public void testDivideBigDecimalScaleMathContextDOWN() { + String a = "3736186567876876578956958765675671119238118911893939591735"; + int aScale = 15; + String b = "748766876876723342238476237823787879183470"; + int bScale = 70; + int precision = 21; + RoundingMode rm = RoundingMode.DOWN; + MathContext mc = new MathContext(precision, rm); + String c = "4.98978611802562512995E+70"; + int resScale = -50; + BigDecimal aNumber = new BigDecimal(new BigInteger(a), aScale); + BigDecimal bNumber = new BigDecimal(new BigInteger(b), bScale); + BigDecimal result = aNumber.divide(bNumber, mc); + assertEquals("incorrect value", c, result.toString()); + assertEquals("incorrect scale", resScale, result.scale()); + } + + /** + * divide(BigDecimal, MathContext) + */ + public void testDivideBigDecimalScaleMathContextCEILING() { + String a = "3736186567876876578956958765675671119238118911893939591735"; + int aScale = 15; + String b = "748766876876723342238476237823787879183470"; + int bScale = 70; + int precision = 21; + RoundingMode rm = RoundingMode.CEILING; + MathContext mc = new MathContext(precision, rm); + String c = "4.98978611802562512996E+70"; + int resScale = -50; + BigDecimal aNumber = new BigDecimal(new BigInteger(a), aScale); + BigDecimal bNumber = new BigDecimal(new BigInteger(b), bScale); + BigDecimal result = aNumber.divide(bNumber, mc); + assertEquals("incorrect value", c, result.toString()); + assertEquals("incorrect scale", resScale, result.scale()); + } + + /** + * divide(BigDecimal, MathContext) + */ + public void testDivideBigDecimalScaleMathContextFLOOR() { + String a = "3736186567876876578956958765675671119238118911893939591735"; + int aScale = 15; + String b = "748766876876723342238476237823787879183470"; + int bScale = 70; + int precision = 21; + RoundingMode rm = RoundingMode.FLOOR; + MathContext mc = new MathContext(precision, rm); + String c = "4.98978611802562512995E+70"; + int resScale = -50; + BigDecimal aNumber = new BigDecimal(new BigInteger(a), aScale); + BigDecimal bNumber = new BigDecimal(new BigInteger(b), bScale); + BigDecimal result = aNumber.divide(bNumber, mc); + assertEquals("incorrect value", c, result.toString()); + assertEquals("incorrect scale", resScale, result.scale()); + } + + /** + * divide(BigDecimal, MathContext) + */ + public void testDivideBigDecimalScaleMathContextHALF_UP() { + String a = "3736186567876876578956958765675671119238118911893939591735"; + int aScale = 45; + String b = "134432345432345748766876876723342238476237823787879183470"; + int bScale = 70; + int precision = 21; + RoundingMode rm = RoundingMode.HALF_UP; + MathContext mc = new MathContext(precision, rm); + String c = "2.77923185514690367475E+26"; + int resScale = -6; + BigDecimal aNumber = new BigDecimal(new BigInteger(a), aScale); + BigDecimal bNumber = new BigDecimal(new BigInteger(b), bScale); + BigDecimal result = aNumber.divide(bNumber, mc); + assertEquals("incorrect value", c, result.toString()); + assertEquals("incorrect scale", resScale, result.scale()); + } + + /** + * divide(BigDecimal, MathContext) + */ + public void testDivideBigDecimalScaleMathContextHALF_DOWN() { + String a = "3736186567876876578956958765675671119238118911893939591735"; + int aScale = 45; + String b = "134432345432345748766876876723342238476237823787879183470"; + int bScale = 70; + int precision = 21; + RoundingMode rm = RoundingMode.HALF_DOWN; + MathContext mc = new MathContext(precision, rm); + String c = "2.77923185514690367475E+26"; + int resScale = -6; + BigDecimal aNumber = new BigDecimal(new BigInteger(a), aScale); + BigDecimal bNumber = new BigDecimal(new BigInteger(b), bScale); + BigDecimal result = aNumber.divide(bNumber, mc); + assertEquals("incorrect value", c, result.toString()); + assertEquals("incorrect scale", resScale, result.scale()); + } + + /** + * divide(BigDecimal, MathContext) + */ + public void testDivideBigDecimalScaleMathContextHALF_EVEN() { + String a = "3736186567876876578956958765675671119238118911893939591735"; + int aScale = 45; + String b = "134432345432345748766876876723342238476237823787879183470"; + int bScale = 70; + int precision = 21; + RoundingMode rm = RoundingMode.HALF_EVEN; + MathContext mc = new MathContext(precision, rm); + String c = "2.77923185514690367475E+26"; + int resScale = -6; + BigDecimal aNumber = new BigDecimal(new BigInteger(a), aScale); + BigDecimal bNumber = new BigDecimal(new BigInteger(b), bScale); + BigDecimal result = aNumber.divide(bNumber, mc); + assertEquals("incorrect value", c, result.toString()); + assertEquals("incorrect scale", resScale, result.scale()); + } + + + /** + * BigDecimal.divide with a scale that's too large + * + * Regression test for HARMONY-6271 + */ + public void testDivideLargeScale() { + BigDecimal arg1 = new BigDecimal("320.0E+2147483647"); + BigDecimal arg2 = new BigDecimal("6E-2147483647"); + try { + BigDecimal result = arg1.divide(arg2, Integer.MAX_VALUE, + java.math.RoundingMode.CEILING); + fail("Expected ArithmeticException when dividing with a scale that's too large"); + } catch (ArithmeticException e) { + // expected behaviour + } + } + + /** + * divideToIntegralValue(BigDecimal) + */ + public void testDivideToIntegralValue() { + String a = "3736186567876876578956958765675671119238118911893939591735"; + int aScale = 45; + String b = "134432345432345748766876876723342238476237823787879183470"; + int bScale = 70; + String c = "277923185514690367474770683"; + int resScale = 0; + BigDecimal aNumber = new BigDecimal(new BigInteger(a), aScale); + BigDecimal bNumber = new BigDecimal(new BigInteger(b), bScale); + BigDecimal result = aNumber.divideToIntegralValue(bNumber); + assertEquals("incorrect value", c, result.toString()); + assertEquals("incorrect scale", resScale, result.scale()); + } + + /** + * divideToIntegralValue(BigDecimal, MathContext) + */ + public void testDivideToIntegralValueMathContextUP() { + String a = "3736186567876876578956958765675671119238118911893939591735"; + int aScale = 45; + String b = "134432345432345748766876876723342238476237823787879183470"; + int bScale = 70; + int precision = 32; + RoundingMode rm = RoundingMode.UP; + MathContext mc = new MathContext(precision, rm); + String c = "277923185514690367474770683"; + int resScale = 0; + BigDecimal aNumber = new BigDecimal(new BigInteger(a), aScale); + BigDecimal bNumber = new BigDecimal(new BigInteger(b), bScale); + BigDecimal result = aNumber.divideToIntegralValue(bNumber, mc); + assertEquals("incorrect value", c, result.toString()); + assertEquals("incorrect scale", resScale, result.scale()); + } + + /** + * divideToIntegralValue(BigDecimal, MathContext) + */ + public void testDivideToIntegralValueMathContextDOWN() { + String a = "3736186567876876578956958769675785435673453453653543654354365435675671119238118911893939591735"; + int aScale = 45; + String b = "134432345432345748766876876723342238476237823787879183470"; + int bScale = 70; + int precision = 75; + RoundingMode rm = RoundingMode.DOWN; + MathContext mc = new MathContext(precision, rm); + String c = "2.7792318551469036747477068339450205874992634417590178670822889E+62"; + int resScale = -1; + BigDecimal aNumber = new BigDecimal(new BigInteger(a), aScale); + BigDecimal bNumber = new BigDecimal(new BigInteger(b), bScale); + BigDecimal result = aNumber.divideToIntegralValue(bNumber, mc); + assertEquals("incorrect value", c, result.toString()); + assertEquals("incorrect scale", resScale, result.scale()); + } + + /** + * divideAndRemainder(BigDecimal) + */ + public void testDivideAndRemainder1() { + String a = "3736186567876876578956958765675671119238118911893939591735"; + int aScale = 45; + String b = "134432345432345748766876876723342238476237823787879183470"; + int bScale = 70; + String res = "277923185514690367474770683"; + int resScale = 0; + String rem = "1.3032693871288309587558885943391070087960319452465789990E-15"; + int remScale = 70; + BigDecimal aNumber = new BigDecimal(new BigInteger(a), aScale); + BigDecimal bNumber = new BigDecimal(new BigInteger(b), bScale); + BigDecimal result[] = aNumber.divideAndRemainder(bNumber); + assertEquals("incorrect quotient value", res, result[0].toString()); + assertEquals("incorrect quotient scale", resScale, result[0].scale()); + assertEquals("incorrect remainder value", rem, result[1].toString()); + assertEquals("incorrect remainder scale", remScale, result[1].scale()); + } + + /** + * divideAndRemainder(BigDecimal) + */ + public void testDivideAndRemainder2() { + String a = "3736186567876876578956958765675671119238118911893939591735"; + int aScale = -45; + String b = "134432345432345748766876876723342238476237823787879183470"; + int bScale = 70; + String res = "2779231855146903674747706830969461168692256919247547952" + + "2608549363170374005512836303475980101168105698072946555" + + "6862849"; + int resScale = 0; + String rem = "3.4935796954060524114470681810486417234751682675102093970E-15"; + int remScale = 70; + BigDecimal aNumber = new BigDecimal(new BigInteger(a), aScale); + BigDecimal bNumber = new BigDecimal(new BigInteger(b), bScale); + BigDecimal result[] = aNumber.divideAndRemainder(bNumber); + assertEquals("incorrect quotient value", res, result[0].toString()); + assertEquals("incorrect quotient scale", resScale, result[0].scale()); + assertEquals("incorrect remainder value", rem, result[1].toString()); + assertEquals("incorrect remainder scale", remScale, result[1].scale()); + } + + /** + * divideAndRemainder(BigDecimal, MathContext) + */ + public void testDivideAndRemainderMathContextUP() { + String a = "3736186567876876578956958765675671119238118911893939591735"; + int aScale = 45; + String b = "134432345432345748766876876723342238476237823787879183470"; + int bScale = 70; + int precision = 75; + RoundingMode rm = RoundingMode.UP; + MathContext mc = new MathContext(precision, rm); + String res = "277923185514690367474770683"; + int resScale = 0; + String rem = "1.3032693871288309587558885943391070087960319452465789990E-15"; + int remScale = 70; + BigDecimal aNumber = new BigDecimal(new BigInteger(a), aScale); + BigDecimal bNumber = new BigDecimal(new BigInteger(b), bScale); + BigDecimal result[] = aNumber.divideAndRemainder(bNumber, mc); + assertEquals("incorrect quotient value", res, result[0].toString()); + assertEquals("incorrect quotient scale", resScale, result[0].scale()); + assertEquals("incorrect remainder value", rem, result[1].toString()); + assertEquals("incorrect remainder scale", remScale, result[1].scale()); + } + + /** + * divideAndRemainder(BigDecimal, MathContext) + */ + public void testDivideAndRemainderMathContextDOWN() { + String a = "3736186567876876578956958765675671119238118911893939591735"; + int aScale = 45; + String b = "134432345432345748766876876723342238476237823787879183470"; + int bScale = 20; + int precision = 15; + RoundingMode rm = RoundingMode.DOWN; + MathContext mc = new MathContext(precision, rm); + String res = "0E-25"; + int resScale = 25; + String rem = "3736186567876.876578956958765675671119238118911893939591735"; + int remScale = 45; + BigDecimal aNumber = new BigDecimal(new BigInteger(a), aScale); + BigDecimal bNumber = new BigDecimal(new BigInteger(b), bScale); + BigDecimal result[] = aNumber.divideAndRemainder(bNumber, mc); + assertEquals("incorrect quotient value", res, result[0].toString()); + assertEquals("incorrect quotient scale", resScale, result[0].scale()); + assertEquals("incorrect remainder value", rem, result[1].toString()); + assertEquals("incorrect remainder scale", remScale, result[1].scale()); + } + + /** + * remainder(BigDecimal) + */ + public void testRemainder1() { + String a = "3736186567876876578956958765675671119238118911893939591735"; + int aScale = 45; + String b = "134432345432345748766876876723342238476237823787879183470"; + int bScale = 10; + String res = "3736186567876.876578956958765675671119238118911893939591735"; + int resScale = 45; + BigDecimal aNumber = new BigDecimal(new BigInteger(a), aScale); + BigDecimal bNumber = new BigDecimal(new BigInteger(b), bScale); + BigDecimal result = aNumber.remainder(bNumber); + assertEquals("incorrect quotient value", res, result.toString()); + assertEquals("incorrect quotient scale", resScale, result.scale()); + } + + /** + * remainder(BigDecimal) + */ + public void testRemainder2() { + String a = "3736186567876876578956958765675671119238118911893939591735"; + int aScale = -45; + String b = "134432345432345748766876876723342238476237823787879183470"; + int bScale = 10; + String res = "1149310942946292909508821656680979993738625937.2065885780"; + int resScale = 10; + BigDecimal aNumber = new BigDecimal(new BigInteger(a), aScale); + BigDecimal bNumber = new BigDecimal(new BigInteger(b), bScale); + BigDecimal result = aNumber.remainder(bNumber); + assertEquals("incorrect quotient value", res, result.toString()); + assertEquals("incorrect quotient scale", resScale, result.scale()); + } + + /** + * remainder(BigDecimal, MathContext) + */ + public void testRemainderMathContextHALF_UP() { + String a = "3736186567876876578956958765675671119238118911893939591735"; + int aScale = 45; + String b = "134432345432345748766876876723342238476237823787879183470"; + int bScale = 10; + int precision = 15; + RoundingMode rm = RoundingMode.HALF_UP; + MathContext mc = new MathContext(precision, rm); + String res = "3736186567876.876578956958765675671119238118911893939591735"; + int resScale = 45; + BigDecimal aNumber = new BigDecimal(new BigInteger(a), aScale); + BigDecimal bNumber = new BigDecimal(new BigInteger(b), bScale); + BigDecimal result = aNumber.remainder(bNumber, mc); + assertEquals("incorrect quotient value", res, result.toString()); + assertEquals("incorrect quotient scale", resScale, result.scale()); + } + + /** + * remainder(BigDecimal, MathContext) + */ + public void testRemainderMathContextHALF_DOWN() { + String a = "3736186567876876578956958765675671119238118911893939591735"; + int aScale = -45; + String b = "134432345432345748766876876723342238476237823787879183470"; + int bScale = 10; + int precision = 75; + RoundingMode rm = RoundingMode.HALF_DOWN; + MathContext mc = new MathContext(precision, rm); + String res = "1149310942946292909508821656680979993738625937.2065885780"; + int resScale = 10; + BigDecimal aNumber = new BigDecimal(new BigInteger(a), aScale); + BigDecimal bNumber = new BigDecimal(new BigInteger(b), bScale); + BigDecimal result = aNumber.remainder(bNumber, mc); + assertEquals("incorrect quotient value", res, result.toString()); + assertEquals("incorrect quotient scale", resScale, result.scale()); + } + + /** + * round(BigDecimal, MathContext) + */ + public void testRoundMathContextHALF_DOWN() { + String a = "3736186567876876578956958765675671119238118911893939591735"; + int aScale = -45; + int precision = 75; + RoundingMode rm = RoundingMode.HALF_DOWN; + MathContext mc = new MathContext(precision, rm); + String res = "3.736186567876876578956958765675671119238118911893939591735E+102"; + int resScale = -45; + BigDecimal aNumber = new BigDecimal(new BigInteger(a), aScale); + BigDecimal result = aNumber.round(mc); + assertEquals("incorrect quotient value", res, result.toString()); + assertEquals("incorrect quotient scale", resScale, result.scale()); + } + + /** + * round(BigDecimal, MathContext) + */ + public void testRoundMathContextHALF_UP() { + String a = "3736186567876876578956958765675671119238118911893939591735"; + int aScale = 45; + int precision = 15; + RoundingMode rm = RoundingMode.HALF_UP; + MathContext mc = new MathContext(precision, rm); + String res = "3736186567876.88"; + int resScale = 2; + BigDecimal aNumber = new BigDecimal(new BigInteger(a), aScale); + BigDecimal result = aNumber.round(mc); + assertEquals("incorrect quotient value", res, result.toString()); + assertEquals("incorrect quotient scale", resScale, result.scale()); + } + + /** + * round(BigDecimal, MathContext) when precision = 0 + */ + public void testRoundMathContextPrecision0() { + String a = "3736186567876876578956958765675671119238118911893939591735"; + int aScale = 45; + int precision = 0; + RoundingMode rm = RoundingMode.HALF_UP; + MathContext mc = new MathContext(precision, rm); + String res = "3736186567876.876578956958765675671119238118911893939591735"; + BigDecimal aNumber = new BigDecimal(new BigInteger(a), aScale); + BigDecimal result = aNumber.round(mc); + assertEquals("incorrect quotient value", res, result.toString()); + assertEquals("incorrect quotient scale", aScale, result.scale()); + } + + + /** + * ulp() of a positive BigDecimal + */ + public void testUlpPos() { + String a = "3736186567876876578956958765675671119238118911893939591735"; + int aScale = -45; + BigDecimal aNumber = new BigDecimal(new BigInteger(a), aScale); + BigDecimal result = aNumber.ulp(); + String res = "1E+45"; + int resScale = -45; + assertEquals("incorrect value", res, result.toString()); + assertEquals("incorrect scale", resScale, result.scale()); + } + + /** + * ulp() of a negative BigDecimal + */ + public void testUlpNeg() { + String a = "-3736186567876876578956958765675671119238118911893939591735"; + int aScale = 45; + BigDecimal aNumber = new BigDecimal(new BigInteger(a), aScale); + BigDecimal result = aNumber.ulp(); + String res = "1E-45"; + int resScale = 45; + assertEquals("incorrect value", res, result.toString()); + assertEquals("incorrect scale", resScale, result.scale()); + } + + /** + * ulp() of a negative BigDecimal + */ + public void testUlpZero() { + String a = "0"; + int aScale = 2; + BigDecimal aNumber = new BigDecimal(new BigInteger(a), aScale); + BigDecimal result = aNumber.ulp(); + String res = "0.01"; + int resScale = 2; + assertEquals("incorrect value", res, result.toString()); + assertEquals("incorrect scale", resScale, result.scale()); + } +} diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/math/BigDecimalCompareTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/math/BigDecimalCompareTest.java new file mode 100644 index 0000000..df756a1 --- /dev/null +++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/math/BigDecimalCompareTest.java @@ -0,0 +1,512 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 Elena Semukhina + */ + +package org.apache.harmony.tests.java.math; + +import java.math.BigDecimal; +import java.math.BigInteger; +import java.math.MathContext; +import java.math.RoundingMode; + +import junit.framework.TestCase; + +/** + * Class: java.math.BigDecimal + * Methods: abs, compareTo, equals, hashCode, + * max, min, negate, signum + */ +public class BigDecimalCompareTest extends TestCase { + /** + * Abs() of a negative BigDecimal + */ + public void testAbsNeg() { + String a = "-123809648392384754573567356745735.63567890295784902768787678287E+21"; + BigDecimal aNumber = new BigDecimal(a); + String result = "123809648392384754573567356745735635678902957849027687.87678287"; + assertEquals("incorrect value", result, aNumber.abs().toString()); + } + + /** + * Abs() of a positive BigDecimal + */ + public void testAbsPos() { + String a = "123809648392384754573567356745735.63567890295784902768787678287E+21"; + BigDecimal aNumber = new BigDecimal(a); + String result = "123809648392384754573567356745735635678902957849027687.87678287"; + assertEquals("incorrect value", result, aNumber.abs().toString()); + } + + /** + * Abs(MathContext) of a negative BigDecimal + */ + public void testAbsMathContextNeg() { + String a = "-123809648392384754573567356745735.63567890295784902768787678287E+21"; + BigDecimal aNumber = new BigDecimal(a); + int precision = 15; + RoundingMode rm = RoundingMode.HALF_DOWN; + MathContext mc = new MathContext(precision, rm); + String result = "1.23809648392385E+53"; + int resScale = -39; + BigDecimal res = aNumber.abs(mc); + assertEquals("incorrect value", result, res.toString()); + assertEquals("incorrect scale", resScale, res.scale()); + } + + /** + * Abs(MathContext) of a positive BigDecimal + */ + public void testAbsMathContextPos() { + String a = "123809648392384754573567356745735.63567890295784902768787678287E+21"; + BigDecimal aNumber = new BigDecimal(a); + int precision = 41; + RoundingMode rm = RoundingMode.HALF_EVEN; + MathContext mc = new MathContext(precision, rm); + String result = "1.2380964839238475457356735674573563567890E+53"; + int resScale = -13; + BigDecimal res = aNumber.abs(mc); + assertEquals("incorrect value", result, res.toString()); + assertEquals("incorrect scale", resScale, res.scale()); + } + + /** + * Compare to a number of an equal scale + */ + public void testCompareEqualScale1() { + String a = "12380964839238475457356735674573563567890295784902768787678287"; + int aScale = 18; + String b = "4573563567890295784902768787678287"; + int bScale = 18; + BigDecimal aNumber = new BigDecimal(new BigInteger(a), aScale); + BigDecimal bNumber = new BigDecimal(new BigInteger(b), bScale); + int result = 1; + assertEquals("incorrect result", result, aNumber.compareTo(bNumber)); + } + + /** + * Compare to a number of an equal scale + */ + public void testCompareEqualScale2() { + String a = "12380964839238475457356735674573563567890295784902768787678287"; + int aScale = 18; + String b = "4573563923487289357829759278282992758247567890295784902768787678287"; + int bScale = 18; + BigDecimal aNumber = new BigDecimal(new BigInteger(a), aScale); + BigDecimal bNumber = new BigDecimal(new BigInteger(b), bScale); + int result = -1; + assertEquals("incorrect result", result, aNumber.compareTo(bNumber)); + } + + /** + * Compare to a number of an greater scale + */ + public void testCompareGreaterScale1() { + String a = "12380964839238475457356735674573563567890295784902768787678287"; + int aScale = 28; + String b = "4573563567890295784902768787678287"; + int bScale = 18; + BigDecimal aNumber = new BigDecimal(new BigInteger(a), aScale); + BigDecimal bNumber = new BigDecimal(new BigInteger(b), bScale); + int result = 1; + assertEquals("incorrect result", result, aNumber.compareTo(bNumber)); + } + + /** + * Compare to a number of an greater scale + */ + public void testCompareGreaterScale2() { + String a = "12380964839238475457356735674573563567890295784902768787678287"; + int aScale = 48; + String b = "4573563567890295784902768787678287"; + int bScale = 2; + BigDecimal aNumber = new BigDecimal(new BigInteger(a), aScale); + BigDecimal bNumber = new BigDecimal(new BigInteger(b), bScale); + int result = -1; + assertEquals("incorrect result", result, aNumber.compareTo(bNumber)); + } + + /** + * Compare to a number of an less scale + */ + public void testCompareLessScale1() { + String a = "12380964839238475457356735674573563567890295784902768787678287"; + int aScale = 18; + String b = "4573563567890295784902768787678287"; + int bScale = 28; + BigDecimal aNumber = new BigDecimal(new BigInteger(a), aScale); + BigDecimal bNumber = new BigDecimal(new BigInteger(b), bScale); + int result = 1; + assertEquals("incorrect result", result, aNumber.compareTo(bNumber)); + } + + /** + * Compare to a number of an less scale + */ + public void testCompareLessScale2() { + String a = "12380964839238475457356735674573"; + int aScale = 36; + String b = "45735635948573894578349572001798379183767890295784902768787678287"; + int bScale = 48; + BigDecimal aNumber = new BigDecimal(new BigInteger(a), aScale); + BigDecimal bNumber = new BigDecimal(new BigInteger(b), bScale); + int result = -1; + assertEquals("incorrect result", result, aNumber.compareTo(bNumber)); + } + + /** + * Equals() for unequal BigDecimals + */ + public void testEqualsUnequal1() { + String a = "92948782094488478231212478987482988429808779810457634781384756794987"; + int aScale = -24; + String b = "7472334223847623782375469293018787918347987234564568"; + int bScale = 13; + BigDecimal aNumber = new BigDecimal(new BigInteger(a), aScale); + BigDecimal bNumber = new BigDecimal(new BigInteger(b), bScale); + assertFalse(aNumber.equals(bNumber)); + } + + /** + * Equals() for unequal BigDecimals + */ + public void testEqualsUnequal2() { + String a = "92948782094488478231212478987482988429808779810457634781384756794987"; + int aScale = -24; + String b = "92948782094488478231212478987482988429808779810457634781384756794987"; + int bScale = 13; + BigDecimal aNumber = new BigDecimal(new BigInteger(a), aScale); + BigDecimal bNumber = new BigDecimal(new BigInteger(b), bScale); + assertFalse(aNumber.equals(bNumber)); + } + + /** + * Equals() for unequal BigDecimals + */ + public void testEqualsUnequal3() { + String a = "92948782094488478231212478987482988429808779810457634781384756794987"; + int aScale = -24; + String b = "92948782094488478231212478987482988429808779810457634781384756794987"; + BigDecimal aNumber = new BigDecimal(new BigInteger(a), aScale); + assertFalse(aNumber.equals(b)); + } + + /** + * equals() for equal BigDecimals + */ + public void testEqualsEqual() { + String a = "92948782094488478231212478987482988429808779810457634781384756794987"; + int aScale = -24; + String b = "92948782094488478231212478987482988429808779810457634781384756794987"; + int bScale = -24; + BigDecimal aNumber = new BigDecimal(new BigInteger(a), aScale); + BigDecimal bNumber = new BigDecimal(new BigInteger(b), bScale); + assertEquals(aNumber, bNumber); + } + + /** + * equals() for equal BigDecimals + */ + public void testEqualsNull() { + String a = "92948782094488478231212478987482988429808779810457634781384756794987"; + int aScale = -24; + BigDecimal aNumber = new BigDecimal(new BigInteger(a), aScale); + assertFalse(aNumber.equals(null)); + } + + /** + * hashCode() for equal BigDecimals + */ + public void testHashCodeEqual() { + String a = "92948782094488478231212478987482988429808779810457634781384756794987"; + int aScale = -24; + String b = "92948782094488478231212478987482988429808779810457634781384756794987"; + int bScale = -24; + BigDecimal aNumber = new BigDecimal(new BigInteger(a), aScale); + BigDecimal bNumber = new BigDecimal(new BigInteger(b), bScale); + assertEquals("incorrect value", aNumber.hashCode(), bNumber.hashCode()); + } + + /** + * hashCode() for unequal BigDecimals + */ + public void testHashCodeUnequal() { + String a = "8478231212478987482988429808779810457634781384756794987"; + int aScale = 41; + String b = "92948782094488478231212478987482988429808779810457634781384756794987"; + int bScale = -24; + BigDecimal aNumber = new BigDecimal(new BigInteger(a), aScale); + BigDecimal bNumber = new BigDecimal(new BigInteger(b), bScale); + assertTrue("incorrect value", aNumber.hashCode() != bNumber.hashCode()); + } + + /** + * max() for equal BigDecimals + */ + public void testMaxEqual() { + String a = "8478231212478987482988429808779810457634781384756794987"; + int aScale = 41; + String b = "8478231212478987482988429808779810457634781384756794987"; + int bScale = 41; + String c = "8478231212478987482988429808779810457634781384756794987"; + int cScale = 41; + BigDecimal aNumber = new BigDecimal(new BigInteger(a), aScale); + BigDecimal bNumber = new BigDecimal(new BigInteger(b), bScale); + BigDecimal cNumber = new BigDecimal(new BigInteger(c), cScale); + assertEquals("incorrect value", cNumber, aNumber.max(bNumber)); + } + + /** + * max() for unequal BigDecimals + */ + public void testMaxUnequal1() { + String a = "92948782094488478231212478987482988429808779810457634781384756794987"; + int aScale = 24; + String b = "92948782094488478231212478987482988429808779810457634781384756794987"; + int bScale = 41; + String c = "92948782094488478231212478987482988429808779810457634781384756794987"; + int cScale = 24; + BigDecimal aNumber = new BigDecimal(new BigInteger(a), aScale); + BigDecimal bNumber = new BigDecimal(new BigInteger(b), bScale); + BigDecimal cNumber = new BigDecimal(new BigInteger(c), cScale); + assertEquals("incorrect value", cNumber, aNumber.max(bNumber)); + } + + /** + * max() for unequal BigDecimals + */ + public void testMaxUnequal2() { + String a = "92948782094488478231212478987482988429808779810457634781384756794987"; + int aScale = 41; + String b = "94488478231212478987482988429808779810457634781384756794987"; + int bScale = 41; + String c = "92948782094488478231212478987482988429808779810457634781384756794987"; + int cScale = 41; + BigDecimal aNumber = new BigDecimal(new BigInteger(a), aScale); + BigDecimal bNumber = new BigDecimal(new BigInteger(b), bScale); + BigDecimal cNumber = new BigDecimal(new BigInteger(c), cScale); + assertEquals("incorrect value", cNumber, aNumber.max(bNumber)); + } + + /** + * min() for equal BigDecimals + */ + public void testMinEqual() { + String a = "8478231212478987482988429808779810457634781384756794987"; + int aScale = 41; + String b = "8478231212478987482988429808779810457634781384756794987"; + int bScale = 41; + String c = "8478231212478987482988429808779810457634781384756794987"; + int cScale = 41; + BigDecimal aNumber = new BigDecimal(new BigInteger(a), aScale); + BigDecimal bNumber = new BigDecimal(new BigInteger(b), bScale); + BigDecimal cNumber = new BigDecimal(new BigInteger(c), cScale); + assertEquals("incorrect value", cNumber, aNumber.min(bNumber)); + } + + /** + * min() for unequal BigDecimals + */ + public void testMinUnequal1() { + String a = "92948782094488478231212478987482988429808779810457634781384756794987"; + int aScale = 24; + String b = "92948782094488478231212478987482988429808779810457634781384756794987"; + int bScale = 41; + String c = "92948782094488478231212478987482988429808779810457634781384756794987"; + int cScale = 41; + BigDecimal aNumber = new BigDecimal(new BigInteger(a), aScale); + BigDecimal bNumber = new BigDecimal(new BigInteger(b), bScale); + BigDecimal cNumber = new BigDecimal(new BigInteger(c), cScale); + assertEquals("incorrect value", cNumber, aNumber.min(bNumber)); + } + + /** + * min() for unequal BigDecimals + */ + public void testMinUnequal2() { + String a = "92948782094488478231212478987482988429808779810457634781384756794987"; + int aScale = 41; + String b = "94488478231212478987482988429808779810457634781384756794987"; + int bScale = 41; + String c = "94488478231212478987482988429808779810457634781384756794987"; + int cScale = 41; + BigDecimal aNumber = new BigDecimal(new BigInteger(a), aScale); + BigDecimal bNumber = new BigDecimal(new BigInteger(b), bScale); + BigDecimal cNumber = new BigDecimal(new BigInteger(c), cScale); + assertEquals("incorrect value", cNumber, aNumber.min(bNumber)); + } + + /** + * plus() for a positive BigDecimal + */ + public void testPlusPositive() { + String a = "92948782094488478231212478987482988429808779810457634781384756794987"; + int aScale = 41; + String c = "92948782094488478231212478987482988429808779810457634781384756794987"; + int cScale = 41; + BigDecimal aNumber = new BigDecimal(new BigInteger(a), aScale); + BigDecimal cNumber = new BigDecimal(new BigInteger(c), cScale); + assertEquals("incorrect value", cNumber, aNumber.plus()); + } + + /** + * plus(MathContext) for a positive BigDecimal + */ + public void testPlusMathContextPositive() { + String a = "92948782094488478231212478987482988429808779810457634781384756794987"; + int aScale = 41; + int precision = 37; + RoundingMode rm = RoundingMode.FLOOR; + MathContext mc = new MathContext(precision, rm); + String c = "929487820944884782312124789.8748298842"; + int cScale = 10; + BigDecimal aNumber = new BigDecimal(new BigInteger(a), aScale); + BigDecimal res = aNumber.plus(mc); + assertEquals("incorrect value", c, res.toString()); + assertEquals("incorrect scale", cScale, res.scale()); + } + + /** + * plus() for a negative BigDecimal + */ + public void testPlusNegative() { + String a = "-92948782094488478231212478987482988429808779810457634781384756794987"; + int aScale = 41; + String c = "-92948782094488478231212478987482988429808779810457634781384756794987"; + int cScale = 41; + BigDecimal aNumber = new BigDecimal(new BigInteger(a), aScale); + BigDecimal cNumber = new BigDecimal(new BigInteger(c), cScale); + assertEquals("incorrect value", cNumber, aNumber.plus()); + } + + /** + * plus(MathContext) for a negative BigDecimal + */ + public void testPlusMathContextNegative() { + String a = "-92948782094488478231212478987482988429808779810457634781384756794987"; + int aScale = 49; + int precision = 46; + RoundingMode rm = RoundingMode.CEILING; + MathContext mc = new MathContext(precision, rm); + String c = "-9294878209448847823.121247898748298842980877981"; + int cScale = 27; + BigDecimal aNumber = new BigDecimal(new BigInteger(a), aScale); + BigDecimal res = aNumber.plus(mc); + assertEquals("incorrect value", c, res.toString()); + assertEquals("incorrect scale", cScale, res.scale()); + } + + /** + * negate() for a positive BigDecimal + */ + public void testNegatePositive() { + String a = "92948782094488478231212478987482988429808779810457634781384756794987"; + int aScale = 41; + String c = "-92948782094488478231212478987482988429808779810457634781384756794987"; + int cScale = 41; + BigDecimal aNumber = new BigDecimal(new BigInteger(a), aScale); + BigDecimal cNumber = new BigDecimal(new BigInteger(c), cScale); + assertEquals("incorrect value", cNumber, aNumber.negate()); + } + + /** + * negate(MathContext) for a positive BigDecimal + */ + public void testNegateMathContextPositive() { + String a = "92948782094488478231212478987482988429808779810457634781384756794987"; + int aScale = 41; + int precision = 37; + RoundingMode rm = RoundingMode.FLOOR; + MathContext mc = new MathContext(precision, rm); + String c = "-929487820944884782312124789.8748298843"; + int cScale = 10; + BigDecimal aNumber = new BigDecimal(new BigInteger(a), aScale); + BigDecimal res = aNumber.negate(mc); + assertEquals("incorrect value", c, res.toString()); + assertEquals("incorrect scale", cScale, res.scale()); + } + + /** + * negate() for a negative BigDecimal + */ + public void testNegateNegative() { + String a = "-92948782094488478231212478987482988429808779810457634781384756794987"; + int aScale = 41; + String c = "92948782094488478231212478987482988429808779810457634781384756794987"; + int cScale = 41; + BigDecimal aNumber = new BigDecimal(new BigInteger(a), aScale); + BigDecimal cNumber = new BigDecimal(new BigInteger(c), cScale); + assertEquals("incorrect value", cNumber, aNumber.negate()); + } + + /** + * negate(MathContext) for a negative BigDecimal + */ + public void testNegateMathContextNegative() { + String a = "-92948782094488478231212478987482988429808779810457634781384756794987"; + int aScale = 49; + int precision = 46; + RoundingMode rm = RoundingMode.CEILING; + MathContext mc = new MathContext(precision, rm); + String c = "9294878209448847823.121247898748298842980877982"; + int cScale = 27; + BigDecimal aNumber = new BigDecimal(new BigInteger(a), aScale); + BigDecimal res = aNumber.negate(mc); + assertEquals("incorrect value", c, res.toString()); + assertEquals("incorrect scale", cScale, res.scale()); + } + + /** + * signum() for a positive BigDecimal + */ + public void testSignumPositive() { + String a = "92948782094488478231212478987482988429808779810457634781384756794987"; + int aScale = 41; + BigDecimal aNumber = new BigDecimal(new BigInteger(a), aScale); + assertEquals("incorrect value", 1, aNumber.signum()); + } + + /** + * signum() for a negative BigDecimal + */ + public void testSignumNegative() { + String a = "-92948782094488478231212478987482988429808779810457634781384756794987"; + int aScale = 41; + BigDecimal aNumber = new BigDecimal(new BigInteger(a), aScale); + assertEquals("incorrect value", -1, aNumber.signum()); + } + + /** + * signum() for zero + */ + public void testSignumZero() { + String a = "0"; + int aScale = 41; + BigDecimal aNumber = new BigDecimal(new BigInteger(a), aScale); + assertEquals("incorrect value", 0, aNumber.signum()); + } + + /* + * Regression test for HARMONY-6406 + */ + public void testApproxPrecision() { + BigDecimal testInstance = BigDecimal.TEN.multiply(new BigDecimal("0.1")); + int result = testInstance.compareTo(new BigDecimal("1.00")); + assertEquals(0, result); + } +} diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/math/BigDecimalConstructorsTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/math/BigDecimalConstructorsTest.java new file mode 100644 index 0000000..3838991 --- /dev/null +++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/math/BigDecimalConstructorsTest.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. + */ +/** + * @author Elena Semukhina + */ + +package org.apache.harmony.tests.java.math; + +import java.math.BigDecimal; +import java.math.BigInteger; +import java.math.MathContext; +import java.math.RoundingMode; + +import junit.framework.TestCase; + +/** + * Class: java.math.BigDecimal + * Methods: constructors and fields + */ +public class BigDecimalConstructorsTest extends TestCase { + /** + * check ONE + */ + public void testFieldONE() { + String oneS = "1"; + double oneD = 1.0; + assertEquals("incorrect string value", oneS, BigDecimal.ONE.toString()); + assertEquals("incorrect double value", oneD, BigDecimal.ONE.doubleValue(), 0); + } + + /** + * check TEN + */ + public void testFieldTEN() { + String oneS = "10"; + double oneD = 10.0; + assertEquals("incorrect string value", oneS, BigDecimal.TEN.toString()); + assertEquals("incorrect double value", oneD, BigDecimal.TEN.doubleValue(), 0); + } + + /** + * check ZERO + */ + public void testFieldZERO() { + String oneS = "0"; + double oneD = 0.0; + assertEquals("incorrect string value", oneS, BigDecimal.ZERO.toString()); + assertEquals("incorrect double value", oneD, BigDecimal.ZERO.doubleValue(), 0); + } + + /** + * new BigDecimal(BigInteger value) + */ + public void testConstrBI() { + String a = "1231212478987482988429808779810457634781384756794987"; + BigInteger bA = new BigInteger(a); + BigDecimal aNumber = new BigDecimal(bA); + assertEquals("incorrect value", bA, aNumber.unscaledValue()); + assertEquals("incorrect scale", 0, aNumber.scale()); + + try { + new BigDecimal((BigInteger) null); + fail("No NullPointerException"); + } catch (NullPointerException e) { + //expected + } + } + + /** + * new BigDecimal(BigInteger value, int scale) + */ + public void testConstrBIScale() { + String a = "1231212478987482988429808779810457634781384756794987"; + BigInteger bA = new BigInteger(a); + int aScale = 10; + BigDecimal aNumber = new BigDecimal(bA, aScale); + assertEquals("incorrect value", bA, aNumber.unscaledValue()); + assertEquals("incorrect scale", aScale, aNumber.scale()); + } + + /** + * new BigDecimal(BigInteger value, MathContext) + */ + public void testConstrBigIntegerMathContext() { + String a = "1231212478987482988429808779810457634781384756794987"; + BigInteger bA = new BigInteger(a); + int precision = 46; + RoundingMode rm = RoundingMode.CEILING; + MathContext mc = new MathContext(precision, rm); + String res = "1231212478987482988429808779810457634781384757"; + int resScale = -6; + BigDecimal result = new BigDecimal(bA, mc); + assertEquals("incorrect value", res, result.unscaledValue().toString()); + assertEquals("incorrect scale", resScale, result.scale()); + } + + /** + * new BigDecimal(BigInteger value, int scale, MathContext) + */ + public void testConstrBigIntegerScaleMathContext() { + String a = "1231212478987482988429808779810457634781384756794987"; + BigInteger bA = new BigInteger(a); + int aScale = 10; + int precision = 46; + RoundingMode rm = RoundingMode.CEILING; + MathContext mc = new MathContext(precision, rm); + String res = "1231212478987482988429808779810457634781384757"; + int resScale = 4; + BigDecimal result = new BigDecimal(bA, aScale, mc); + assertEquals("incorrect value", res, result.unscaledValue().toString()); + assertEquals("incorrect scale", resScale, result.scale()); + } + + /** + * new BigDecimal(char[] value); + */ + public void testConstrChar() { + char value[] = {'-', '1', '2', '3', '8', '0', '.', '4', '7', '3', '8', 'E', '-', '4', '2', '3'}; + BigDecimal result = new BigDecimal(value); + String res = "-1.23804738E-419"; + int resScale = 427; + assertEquals("incorrect value", res, result.toString()); + assertEquals("incorrect scale", resScale, result.scale()); + + try { + // Regression for HARMONY-783 + new BigDecimal(new char[] {}); + fail("NumberFormatException has not been thrown"); + } catch (NumberFormatException e) { + } + } + + /** + * new BigDecimal(char[] value, int offset, int len); + */ + public void testConstrCharIntInt() { + char value[] = {'-', '1', '2', '3', '8', '0', '.', '4', '7', '3', '8', 'E', '-', '4', '2', '3'}; + int offset = 3; + int len = 12; + BigDecimal result = new BigDecimal(value, offset, len); + String res = "3.804738E-40"; + int resScale = 46; + assertEquals("incorrect value", res, result.toString()); + assertEquals("incorrect scale", resScale, result.scale()); + + try { + // Regression for HARMONY-783 + new BigDecimal(new char[] {}, 0, 0); + fail("NumberFormatException has not been thrown"); + } catch (NumberFormatException e) { + } + } + + /** + * new BigDecimal(char[] value, int offset, int len, MathContext mc); + */ + public void testConstrCharIntIntMathContext() { + char value[] = {'-', '1', '2', '3', '8', '0', '.', '4', '7', '3', '8', 'E', '-', '4', '2', '3'}; + int offset = 3; + int len = 12; + int precision = 4; + RoundingMode rm = RoundingMode.CEILING; + MathContext mc = new MathContext(precision, rm); + BigDecimal result = new BigDecimal(value, offset, len, mc); + String res = "3.805E-40"; + int resScale = 43; + assertEquals("incorrect value", res, result.toString()); + assertEquals("incorrect scale", resScale, result.scale()); + + try { + // Regression for HARMONY-783 + new BigDecimal(new char[] {}, 0, 0, MathContext.DECIMAL32); + fail("NumberFormatException has not been thrown"); + } catch (NumberFormatException e) { + } + } + + /** + * new BigDecimal(char[] value, int offset, int len, MathContext mc); + */ + public void testConstrCharIntIntMathContextException1() { + char value[] = {'-', '1', '2', '3', '8', '0', '.', '4', '7', '3', '8', 'E', '-', '4', '2', '3'}; + int offset = 3; + int len = 120; + int precision = 4; + RoundingMode rm = RoundingMode.CEILING; + MathContext mc = new MathContext(precision, rm); + try { + new BigDecimal(value, offset, len, mc); + fail("NumberFormatException has not been thrown"); + } catch (NumberFormatException e) { + } + } + + /** + * new BigDecimal(char[] value, int offset, int len, MathContext mc); + */ + public void testConstrCharIntIntMathContextException2() { + char value[] = {'-', '1', '2', '3', '8', '0', ',', '4', '7', '3', '8', 'E', '-', '4', '2', '3'}; + int offset = 3; + int len = 120; + int precision = 4; + RoundingMode rm = RoundingMode.CEILING; + MathContext mc = new MathContext(precision, rm); + try { + new BigDecimal(value, offset, len, mc); + fail("NumberFormatException has not been thrown"); + } catch (NumberFormatException e) { + } + } + + /** + * new BigDecimal(char[] value, MathContext mc); + */ + public void testConstrCharMathContext() { + try { + // Regression for HARMONY-783 + new BigDecimal(new char[] {}, MathContext.DECIMAL32); + fail("NumberFormatException has not been thrown"); + } catch (NumberFormatException e) { + } + } + + /** + * new BigDecimal(double value) when value is NaN + */ + public void testConstrDoubleNaN() { + double a = Double.NaN; + try { + new BigDecimal(a); + fail("NumberFormatException has not been caught"); + } catch (NumberFormatException e) { + } + } + + /** + * new BigDecimal(double value) when value is positive infinity + */ + public void testConstrDoublePosInfinity() { + double a = Double.POSITIVE_INFINITY; + try { + new BigDecimal(a); + fail("NumberFormatException has not been caught"); + } catch (NumberFormatException e) { + } + } + + /** + * new BigDecimal(double value) when value is positive infinity + */ + public void testConstrDoubleNegInfinity() { + double a = Double.NEGATIVE_INFINITY; + try { + new BigDecimal(a); + fail("NumberFormatException has not been caught"); + } catch (NumberFormatException e) { + } + } + + /** + * new BigDecimal(double value) + */ + public void testConstrDouble() { + double a = 732546982374982347892379283571094797.287346782359284756; + int aScale = 0; + BigInteger bA = new BigInteger("732546982374982285073458350476230656"); + BigDecimal aNumber = new BigDecimal(a); + assertEquals("incorrect value", bA, aNumber.unscaledValue()); + assertEquals("incorrect scale", aScale, aNumber.scale()); + } + + /** + * new BigDecimal(double, MathContext) + */ + public void testConstrDoubleMathContext() { + double a = 732546982374982347892379283571094797.287346782359284756; + int precision = 21; + RoundingMode rm = RoundingMode.CEILING; + MathContext mc = new MathContext(precision, rm); + String res = "732546982374982285074"; + int resScale = -15; + BigDecimal result = new BigDecimal(a, mc); + assertEquals("incorrect value", res, result.unscaledValue().toString()); + assertEquals("incorrect scale", resScale, result.scale()); + } + + /** + * new BigDecimal(0.1) + */ + public void testConstrDouble01() { + double a = 1.E-1; + int aScale = 55; + BigInteger bA = new BigInteger("1000000000000000055511151231257827021181583404541015625"); + BigDecimal aNumber = new BigDecimal(a); + assertEquals("incorrect value", bA, aNumber.unscaledValue()); + assertEquals("incorrect scale", aScale, aNumber.scale()); + } + + /** + * new BigDecimal(0.555) + */ + public void testConstrDouble02() { + double a = 0.555; + int aScale = 53; + BigInteger bA = new BigInteger("55500000000000004884981308350688777863979339599609375"); + BigDecimal aNumber = new BigDecimal(a); + assertEquals("incorrect value", bA, aNumber.unscaledValue()); + assertEquals("incorrect scale", aScale, aNumber.scale()); + } + + /** + * new BigDecimal(-0.1) + */ + public void testConstrDoubleMinus01() { + double a = -1.E-1; + int aScale = 55; + BigInteger bA = new BigInteger("-1000000000000000055511151231257827021181583404541015625"); + BigDecimal aNumber = new BigDecimal(a); + assertEquals("incorrect value", bA, aNumber.unscaledValue()); + assertEquals("incorrect scale", aScale, aNumber.scale()); + } + + /** + * new BigDecimal(int value) + */ + public void testConstrInt() { + int a = 732546982; + String res = "732546982"; + int resScale = 0; + BigDecimal result = new BigDecimal(a); + assertEquals("incorrect value", res, result.unscaledValue().toString()); + assertEquals("incorrect scale", resScale, result.scale()); + } + + /** + * new BigDecimal(int, MathContext) + */ + public void testConstrIntMathContext() { + int a = 732546982; + int precision = 21; + RoundingMode rm = RoundingMode.CEILING; + MathContext mc = new MathContext(precision, rm); + String res = "732546982"; + int resScale = 0; + BigDecimal result = new BigDecimal(a, mc); + assertEquals("incorrect value", res, result.unscaledValue().toString()); + assertEquals("incorrect scale", resScale, result.scale()); + } + + /** + * new BigDecimal(long value) + */ + public void testConstrLong() { + long a = 4576578677732546982L; + String res = "4576578677732546982"; + int resScale = 0; + BigDecimal result = new BigDecimal(a); + assertEquals("incorrect value", res, result.unscaledValue().toString()); + assertEquals("incorrect scale", resScale, result.scale()); + } + + /** + * new BigDecimal(long, MathContext) + */ + public void testConstrLongMathContext() { + long a = 4576578677732546982L; + int precision = 5; + RoundingMode rm = RoundingMode.CEILING; + MathContext mc = new MathContext(precision, rm); + String res = "45766"; + int resScale = -14; + BigDecimal result = new BigDecimal(a, mc); + assertEquals("incorrect value", res, result.unscaledValue().toString()); + assertEquals("incorrect scale", resScale, result.scale()); + } + + /** + * new BigDecimal(double value) when value is denormalized + */ + public void testConstrDoubleDenormalized() { + double a = 2.274341322658976E-309; + int aScale = 1073; + BigInteger bA = new BigInteger("227434132265897633950269241702666687639731047124115603942986140264569528085692462493371029187342478828091760934014851133733918639492582043963243759464684978401240614084312038547315281016804838374623558434472007664427140169018817050565150914041833284370702366055678057809362286455237716100382057360123091641959140448783514464639706721250400288267372238950016114583259228262046633530468551311769574111763316146065958042194569102063373243372766692713192728878701004405568459288708477607744497502929764155046100964958011009313090462293046650352146796805866786767887226278836423536035611825593567576424943331337401071583562754098901412372708947790843318760718495117047155597276492717187936854356663665005157041552436478744491526494952982062613955349661409854888916015625"); + BigDecimal aNumber = new BigDecimal(a); + assertEquals("incorrect value", bA, aNumber.unscaledValue()); + assertEquals("incorrect scale", aScale, aNumber.scale()); + } + + /** + * new BigDecimal(String value) + * when value is not a valid representation of BigDecimal. + */ + public void testConstrStringException() { + String a = "-238768.787678287a+10"; + try { + new BigDecimal(a); + fail("NumberFormatException has not been caught"); + } catch (NumberFormatException e) {} + } + + /** + * new BigDecimal(String value) when exponent is empty. + */ + public void testConstrStringExceptionEmptyExponent1() { + String a = "-238768.787678287e"; + try { + new BigDecimal(a); + fail("NumberFormatException has not been caught"); + } catch (NumberFormatException e) { + } + } + + /** + * new BigDecimal(String value) when exponent is empty. + */ + public void testConstrStringExceptionEmptyExponent2() { + String a = "-238768.787678287e-"; + try { + new BigDecimal(a); + fail("NumberFormatException has not been caught"); + } catch (NumberFormatException e) { + } + } + + /** + * new BigDecimal(String value) when exponent is greater than + * Integer.MAX_VALUE. + */ + public void testConstrStringExceptionExponentGreaterIntegerMax() { + String a = "-238768.787678287e214748364767876"; + try { + new BigDecimal(a); + fail("NumberFormatException has not been caught"); + } catch (NumberFormatException e) { + } + } + + /** + * new BigDecimal(String value) when exponent is less than + * Integer.MIN_VALUE. + */ + public void testConstrStringExceptionExponentLessIntegerMin() { + String a = "-238768.787678287e-214748364767876"; + try { + new BigDecimal(a); + fail("NumberFormatException has not been caught"); + } catch (NumberFormatException e) { + } + } + + /** + * new BigDecimal(String value) + * when exponent is Integer.MAX_VALUE. + */ + public void testConstrStringExponentIntegerMax() { + String a = "-238768.787678287e2147483647"; + int aScale = -2147483638; + BigInteger bA = new BigInteger("-238768787678287"); + BigDecimal aNumber = new BigDecimal(a); + assertEquals("incorrect value", bA, aNumber.unscaledValue()); + assertEquals("incorrect scale", aScale, aNumber.scale()); + } + + /** + * new BigDecimal(String value) + * when exponent is Integer.MIN_VALUE. + */ + public void testConstrStringExponentIntegerMin() { + String a = ".238768e-2147483648"; + try { + new BigDecimal(a); + fail("NumberFormatException expected"); + } catch (NumberFormatException e) { + } + } + + /** + * new BigDecimal(String value); value does not contain exponent + */ + public void testConstrStringWithoutExpPos1() { + String a = "732546982374982347892379283571094797.287346782359284756"; + int aScale = 18; + BigInteger bA = new BigInteger("732546982374982347892379283571094797287346782359284756"); + BigDecimal aNumber = new BigDecimal(a); + assertEquals("incorrect value", bA, aNumber.unscaledValue()); + assertEquals("incorrect scale", aScale, aNumber.scale()); + } + + /** + * new BigDecimal(String value); value does not contain exponent + */ + public void testConstrStringWithoutExpPos2() { + String a = "+732546982374982347892379283571094797.287346782359284756"; + int aScale = 18; + BigInteger bA = new BigInteger("732546982374982347892379283571094797287346782359284756"); + BigDecimal aNumber = new BigDecimal(a); + assertEquals("incorrect value", bA, aNumber.unscaledValue()); + assertEquals("incorrect scale", aScale, aNumber.scale()); + } + + /** + * new BigDecimal(String value); value does not contain exponent + */ + public void testConstrStringWithoutExpNeg() { + String a = "-732546982374982347892379283571094797.287346782359284756"; + int aScale = 18; + BigInteger bA = new BigInteger("-732546982374982347892379283571094797287346782359284756"); + BigDecimal aNumber = new BigDecimal(a); + assertEquals("incorrect value", bA, aNumber.unscaledValue()); + assertEquals("incorrect scale", aScale, aNumber.scale()); + } + + /** + * new BigDecimal(String value); value does not contain exponent + * and decimal point + */ + public void testConstrStringWithoutExpWithoutPoint() { + String a = "-732546982374982347892379283571094797287346782359284756"; + int aScale = 0; + BigInteger bA = new BigInteger("-732546982374982347892379283571094797287346782359284756"); + BigDecimal aNumber = new BigDecimal(a); + assertEquals("incorrect value", bA, aNumber.unscaledValue()); + assertEquals("incorrect scale", aScale, aNumber.scale()); + } + + /** + * new BigDecimal(String value); value contains exponent + * and does not contain decimal point + */ + public void testConstrStringWithExponentWithoutPoint1() { + String a = "-238768787678287e214"; + int aScale = -214; + BigInteger bA = new BigInteger("-238768787678287"); + BigDecimal aNumber = new BigDecimal(a); + assertEquals("incorrect value", bA, aNumber.unscaledValue()); + assertEquals("incorrect scale", aScale, aNumber.scale()); + } + + /** + * new BigDecimal(String value); value contains exponent + * and does not contain decimal point + */ + public void testConstrStringWithExponentWithoutPoint2() { + String a = "-238768787678287e-214"; + int aScale = 214; + BigInteger bA = new BigInteger("-238768787678287"); + BigDecimal aNumber = new BigDecimal(a); + assertEquals("incorrect value", bA, aNumber.unscaledValue()); + assertEquals("incorrect scale", aScale, aNumber.scale()); + } + + /** + * new BigDecimal(String value); value contains exponent + * and does not contain decimal point + */ + public void testConstrStringWithExponentWithoutPoint3() { + String a = "238768787678287e-214"; + int aScale = 214; + BigInteger bA = new BigInteger("238768787678287"); + BigDecimal aNumber = new BigDecimal(a); + assertEquals("incorrect value", bA, aNumber.unscaledValue()); + assertEquals("incorrect scale", aScale, aNumber.scale()); + } + + /** + * new BigDecimal(String value); value contains exponent + * and does not contain decimal point + */ + public void testConstrStringWithExponentWithoutPoint4() { + String a = "238768787678287e+214"; + int aScale = -214; + BigInteger bA = new BigInteger("238768787678287"); + BigDecimal aNumber = new BigDecimal(a); + assertEquals("incorrect value", bA, aNumber.unscaledValue()); + assertEquals("incorrect scale", aScale, aNumber.scale()); + } + + /** + * new BigDecimal(String value); value contains exponent + * and does not contain decimal point + */ + public void testConstrStringWithExponentWithoutPoint5() { + String a = "238768787678287E214"; + int aScale = -214; + BigInteger bA = new BigInteger("238768787678287"); + BigDecimal aNumber = new BigDecimal(a); + assertEquals("incorrect value", bA, aNumber.unscaledValue()); + assertEquals("incorrect scale", aScale, aNumber.scale()); + } + + /** + * new BigDecimal(String value); + * value contains both exponent and decimal point + */ + public void testConstrStringWithExponentWithPoint1() { + String a = "23985439837984782435652424523876878.7678287e+214"; + int aScale = -207; + BigInteger bA = new BigInteger("239854398379847824356524245238768787678287"); + BigDecimal aNumber = new BigDecimal(a); + assertEquals("incorrect value", bA, aNumber.unscaledValue()); + assertEquals("incorrect scale", aScale, aNumber.scale()); + } + + /** + * new BigDecimal(String value); + * value contains both exponent and decimal point + */ + public void testConstrStringWithExponentWithPoint2() { + String a = "238096483923847545735673567457356356789029578490276878.7678287e-214"; + int aScale = 221; + BigInteger bA = new BigInteger("2380964839238475457356735674573563567890295784902768787678287"); + BigDecimal aNumber = new BigDecimal(a); + assertEquals("incorrect value", bA, aNumber.unscaledValue()); + assertEquals("incorrect scale", aScale, aNumber.scale()); + } + + /** + * new BigDecimal(String value); + * value contains both exponent and decimal point + */ + public void testConstrStringWithExponentWithPoint3() { + String a = "2380964839238475457356735674573563567890.295784902768787678287E+21"; + int aScale = 0; + BigInteger bA = new BigInteger("2380964839238475457356735674573563567890295784902768787678287"); + BigDecimal aNumber = new BigDecimal(a); + assertEquals("incorrect value", bA, aNumber.unscaledValue()); + assertEquals("incorrect scale", aScale, aNumber.scale()); + } + + /** + * new BigDecimal(String value); + * value contains both exponent and decimal point + */ + public void testConstrStringWithExponentWithPoint4() { + String a = "23809648392384754573567356745735635678.90295784902768787678287E+21"; + int aScale = 2; + BigInteger bA = new BigInteger("2380964839238475457356735674573563567890295784902768787678287"); + BigDecimal aNumber = new BigDecimal(a); + assertEquals("incorrect value", bA, aNumber.unscaledValue()); + assertEquals("incorrect scale", aScale, aNumber.scale()); + } + + /** + * new BigDecimal(String value); + * value contains both exponent and decimal point + */ + public void testConstrStringWithExponentWithPoint5() { + String a = "238096483923847545735673567457356356789029.5784902768787678287E+21"; + int aScale = -2; + BigInteger bA = new BigInteger("2380964839238475457356735674573563567890295784902768787678287"); + BigDecimal aNumber = new BigDecimal(a); + assertEquals("incorrect value", bA, aNumber.unscaledValue()); + assertEquals("incorrect scale", aScale, aNumber.scale()); + } + + /** + * new BigDecimal(String value, MathContext) + */ + public void testConstrStringMathContext() { + String a = "-238768787678287e214"; + int precision = 5; + RoundingMode rm = RoundingMode.CEILING; + MathContext mc = new MathContext(precision, rm); + String res = "-23876"; + int resScale = -224; + BigDecimal result = new BigDecimal(a, mc); + assertEquals("incorrect value", res, result.unscaledValue().toString()); + assertEquals("incorrect scale", resScale, result.scale()); + } +} diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/math/BigDecimalConvertTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/math/BigDecimalConvertTest.java new file mode 100644 index 0000000..67fd8b4 --- /dev/null +++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/math/BigDecimalConvertTest.java @@ -0,0 +1,569 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 Elena Semukhina + */ + +package org.apache.harmony.tests.java.math; + +import junit.framework.TestCase; +import java.math.BigDecimal; +import java.math.BigInteger; + +/** + * Class: java.math.BigDecimal + * Methods: doubleValue, floatValue, intValue, longValue, + * valueOf, toString, toBigInteger + */ +public class BigDecimalConvertTest extends TestCase { + /** + * Double value of a negative BigDecimal + */ + public void testDoubleValueNeg() { + String a = "-123809648392384754573567356745735.63567890295784902768787678287E+21"; + BigDecimal aNumber = new BigDecimal(a); + double result = -1.2380964839238476E53; + assertEquals("incorrect value", result, aNumber.doubleValue(), 0); + } + + /** + * Double value of a positive BigDecimal + */ + public void testDoubleValuePos() { + String a = "123809648392384754573567356745735.63567890295784902768787678287E+21"; + BigDecimal aNumber = new BigDecimal(a); + double result = 1.2380964839238476E53; + assertEquals("incorrect value", result, aNumber.doubleValue(), 0); + } + + /** + * Double value of a large positive BigDecimal + */ + public void testDoubleValuePosInfinity() { + String a = "123809648392384754573567356745735.63567890295784902768787678287E+400"; + BigDecimal aNumber = new BigDecimal(a); + double result = Double.POSITIVE_INFINITY; + assertEquals("incorrect value", result, aNumber.doubleValue(), 0); + } + + /** + * Double value of a large negative BigDecimal + */ + public void testDoubleValueNegInfinity() { + String a = "-123809648392384754573567356745735.63567890295784902768787678287E+400"; + BigDecimal aNumber = new BigDecimal(a); + double result = Double.NEGATIVE_INFINITY; + assertEquals("incorrect value", result, aNumber.doubleValue(), 0); + } + + /** + * Double value of a small negative BigDecimal + */ + public void testDoubleValueMinusZero() { + String a = "-123809648392384754573567356745735.63567890295784902768787678287E-400"; + BigDecimal aNumber = new BigDecimal(a); + long minusZero = -9223372036854775808L; + double result = aNumber.doubleValue(); + assertTrue("incorrect value", Double.doubleToLongBits(result) == minusZero); + } + + /** + * Double value of a small positive BigDecimal + */ + public void testDoubleValuePlusZero() { + String a = "123809648392384754573567356745735.63567890295784902768787678287E-400"; + BigDecimal aNumber = new BigDecimal(a); + long zero = 0; + double result = aNumber.doubleValue(); + assertTrue("incorrect value", Double.doubleToLongBits(result) == zero); + } + + /** + * Float value of a negative BigDecimal + */ + public void testFloatValueNeg() { + String a = "-1238096483923847.6356789029578E+21"; + BigDecimal aNumber = new BigDecimal(a); + float result = -1.2380965E36F; + assertTrue("incorrect value", aNumber.floatValue() == result); + } + + /** + * Float value of a positive BigDecimal + */ + public void testFloatValuePos() { + String a = "1238096483923847.6356789029578E+21"; + BigDecimal aNumber = new BigDecimal(a); + float result = 1.2380965E36F; + assertTrue("incorrect value", aNumber.floatValue() == result); + } + + /** + * Float value of a large positive BigDecimal + */ + public void testFloatValuePosInfinity() { + String a = "123809648373567356745735.6356789787678287E+200"; + BigDecimal aNumber = new BigDecimal(a); + float result = Float.POSITIVE_INFINITY; + assertTrue("incorrect value", aNumber.floatValue() == result); + } + + /** + * Float value of a large negative BigDecimal + */ + public void testFloatValueNegInfinity() { + String a = "-123809648392384755735.63567887678287E+200"; + BigDecimal aNumber = new BigDecimal(a); + float result = Float.NEGATIVE_INFINITY; + assertTrue("incorrect value", aNumber.floatValue() == result); + } + + /** + * Float value of a small negative BigDecimal + */ + public void testFloatValueMinusZero() { + String a = "-123809648392384754573567356745735.63567890295784902768787678287E-400"; + BigDecimal aNumber = new BigDecimal(a); + int minusZero = -2147483648; + float result = aNumber.floatValue(); + assertTrue("incorrect value", Float.floatToIntBits(result) == minusZero); + } + + /** + * Float value of a small positive BigDecimal + */ + public void testFloatValuePlusZero() { + String a = "123809648392384754573567356745735.63567890295784902768787678287E-400"; + BigDecimal aNumber = new BigDecimal(a); + int zero = 0; + float result = aNumber.floatValue(); + assertTrue("incorrect value", Float.floatToIntBits(result) == zero); + } + + /** + * Integer value of a negative BigDecimal + */ + public void testIntValueNeg() { + String a = "-123809648392384754573567356745735.63567890295784902768787678287E+21"; + BigDecimal aNumber = new BigDecimal(a); + int result = 218520473; + assertTrue("incorrect value", aNumber.intValue() == result); + } + + /** + * Integer value of a positive BigDecimal + */ + public void testIntValuePos() { + String a = "123809648392384754573567356745735.63567890295784902768787678287E+21"; + BigDecimal aNumber = new BigDecimal(a); + int result = -218520473; + assertTrue("incorrect value", aNumber.intValue() == result); + } + + /** + * Long value of a negative BigDecimal + */ + public void testLongValueNeg() { + String a = "-123809648392384754573567356745735.63567890295784902768787678287E+21"; + BigDecimal aNumber = new BigDecimal(a); + long result = -1246043477766677607L; + assertTrue("incorrect value", aNumber.longValue() == result); + } + + /** + * Long value of a positive BigDecimal + */ + public void testLongValuePos() { + String a = "123809648392384754573567356745735.63567890295784902768787678287E+21"; + BigDecimal aNumber = new BigDecimal(a); + long result = 1246043477766677607L; + assertTrue("incorrect value", aNumber.longValue() == result); + } + + /** + * scaleByPowerOfTen(int n) + */ + public void testScaleByPowerOfTen1() { + String a = "1231212478987482988429808779810457634781384756794987"; + int aScale = 13; + BigDecimal aNumber = new BigDecimal(new BigInteger(a), aScale); + BigDecimal result = aNumber.scaleByPowerOfTen(10); + String res = "1231212478987482988429808779810457634781384756794.987"; + int resScale = 3; + assertEquals("incorrect value", res, result.toString()); + assertEquals("incorrect scale", resScale, result.scale()); + } + + /** + * scaleByPowerOfTen(int n) + */ + public void testScaleByPowerOfTen2() { + String a = "1231212478987482988429808779810457634781384756794987"; + int aScale = -13; + BigDecimal aNumber = new BigDecimal(new BigInteger(a), aScale); + BigDecimal result = aNumber.scaleByPowerOfTen(10); + String res = "1.231212478987482988429808779810457634781384756794987E+74"; + int resScale = -23; + assertEquals("incorrect value", res, result.toString()); + assertEquals("incorrect scale", resScale, result.scale()); + } + + /** + * Convert a positive BigDecimal to BigInteger + */ + public void testToBigIntegerPos1() { + String a = "123809648392384754573567356745735.63567890295784902768787678287E+21"; + BigInteger bNumber = new BigInteger("123809648392384754573567356745735635678902957849027687"); + BigDecimal aNumber = new BigDecimal(a); + BigInteger result = aNumber.toBigInteger(); + assertTrue("incorrect value", result.equals(bNumber)); + } + + /** + * Convert a positive BigDecimal to BigInteger + */ + public void testToBigIntegerPos2() { + String a = "123809648392384754573567356745735.63567890295784902768787678287E+15"; + BigInteger bNumber = new BigInteger("123809648392384754573567356745735635678902957849"); + BigDecimal aNumber = new BigDecimal(a); + BigInteger result = aNumber.toBigInteger(); + assertTrue("incorrect value", result.equals(bNumber)); + } + + /** + * Convert a positive BigDecimal to BigInteger + */ + public void testToBigIntegerPos3() { + String a = "123809648392384754573567356745735.63567890295784902768787678287E+45"; + BigInteger bNumber = new BigInteger("123809648392384754573567356745735635678902957849027687876782870000000000000000"); + BigDecimal aNumber = new BigDecimal(a); + BigInteger result = aNumber.toBigInteger(); + assertTrue("incorrect value", result.equals(bNumber)); + } + + /** + * Convert a negative BigDecimal to BigInteger + */ + public void testToBigIntegerNeg1() { + String a = "-123809648392384754573567356745735.63567890295784902768787678287E+21"; + BigInteger bNumber = new BigInteger("-123809648392384754573567356745735635678902957849027687"); + BigDecimal aNumber = new BigDecimal(a); + BigInteger result = aNumber.toBigInteger(); + assertTrue("incorrect value", result.equals(bNumber)); + } + + /** + * Convert a negative BigDecimal to BigInteger + */ + public void testToBigIntegerNeg2() { + String a = "-123809648392384754573567356745735.63567890295784902768787678287E+15"; + BigInteger bNumber = new BigInteger("-123809648392384754573567356745735635678902957849"); + BigDecimal aNumber = new BigDecimal(a); + BigInteger result = aNumber.toBigInteger(); + assertTrue("incorrect value", result.equals(bNumber)); + } + + /** + * Convert a negative BigDecimal to BigInteger + */ + public void testToBigIntegerNeg3() { + String a = "-123809648392384754573567356745735.63567890295784902768787678287E+45"; + BigInteger bNumber = new BigInteger("-123809648392384754573567356745735635678902957849027687876782870000000000000000"); + BigDecimal aNumber = new BigDecimal(a); + BigInteger result = aNumber.toBigInteger(); + assertTrue("incorrect value", result.equals(bNumber)); + } + + /** + * Convert a small BigDecimal to BigInteger + */ + public void testToBigIntegerZero() { + String a = "-123809648392384754573567356745735.63567890295784902768787678287E-500"; + BigInteger bNumber = new BigInteger("0"); + BigDecimal aNumber = new BigDecimal(a); + BigInteger result = aNumber.toBigInteger(); + assertTrue("incorrect value", result.equals(bNumber)); + } + + /** + * toBigIntegerExact() + */ + public void testToBigIntegerExact1() { + String a = "-123809648392384754573567356745735.63567890295784902768787678287E+45"; + BigDecimal aNumber = new BigDecimal(a); + String res = "-123809648392384754573567356745735635678902957849027687876782870000000000000000"; + BigInteger result = aNumber.toBigIntegerExact(); + assertEquals("incorrect value", res, result.toString()); + } + + /** + * toBigIntegerExact() + */ + public void testToBigIntegerExactException() { + String a = "-123809648392384754573567356745735.63567890295784902768787678287E-10"; + BigDecimal aNumber = new BigDecimal(a); + try { + aNumber.toBigIntegerExact(); + fail("java.lang.ArithmeticException has not been thrown"); + } catch (java.lang.ArithmeticException e) { + return; + } + } + + /** + * Convert a positive BigDecimal to an engineering string representation + */ + public void testToEngineeringStringPos() { + String a = "123809648392384754573567356745735.63567890295784902768787678287E-501"; + BigDecimal aNumber = new BigDecimal(a); + String result = "123.80964839238475457356735674573563567890295784902768787678287E-471"; + assertEquals("incorrect value", result, aNumber.toEngineeringString()); + } + + /** + * Convert a negative BigDecimal to an engineering string representation + */ + public void testToEngineeringStringNeg() { + String a = "-123809648392384754573567356745735.63567890295784902768787678287E-501"; + BigDecimal aNumber = new BigDecimal(a); + String result = "-123.80964839238475457356735674573563567890295784902768787678287E-471"; + assertEquals("incorrect value", result, aNumber.toEngineeringString()); + } + + /** + * Convert a negative BigDecimal to an engineering string representation + */ + public void testToEngineeringStringZeroPosExponent() { + String a = "0.0E+16"; + BigDecimal aNumber = new BigDecimal(a); + String result = "0E+15"; + assertEquals("incorrect value", result, aNumber.toEngineeringString()); + } + + /** + * Convert a negative BigDecimal to an engineering string representation + */ + public void testToEngineeringStringZeroNegExponent() { + String a = "0.0E-16"; + BigDecimal aNumber = new BigDecimal(a); + String result = "0.00E-15"; + assertEquals("incorrect value", result, aNumber.toEngineeringString()); + } + + /** + * Convert a negative BigDecimal with a negative exponent to a plain string + * representation; scale == 0. + */ + public void testToPlainStringNegNegExp() { + String a = "-123809648392384754573567356745735.63567890295784902768787678287E-100"; + BigDecimal aNumber = new BigDecimal(a); + String result = "-0.000000000000000000000000000000000000000000000000000000000000000000012380964839238475457356735674573563567890295784902768787678287"; + assertTrue("incorrect value", aNumber.toPlainString().equals(result)); + } + + /** + * Convert a negative BigDecimal with a positive exponent + * to a plain string representation; + * scale == 0. + */ + public void testToPlainStringNegPosExp() { + String a = "-123809648392384754573567356745735.63567890295784902768787678287E100"; + BigDecimal aNumber = new BigDecimal(a); + String result = "-1238096483923847545735673567457356356789029578490276878767828700000000000000000000000000000000000000000000000000000000000000000000000"; + assertTrue("incorrect value", aNumber.toPlainString().equals(result)); + } + + /** + * Convert a positive BigDecimal with a negative exponent + * to a plain string representation; + * scale == 0. + */ + public void testToPlainStringPosNegExp() { + String a = "123809648392384754573567356745735.63567890295784902768787678287E-100"; + BigDecimal aNumber = new BigDecimal(a); + String result = "0.000000000000000000000000000000000000000000000000000000000000000000012380964839238475457356735674573563567890295784902768787678287"; + assertTrue("incorrect value", aNumber.toPlainString().equals(result)); + } + + /** + * Convert a negative BigDecimal with a negative exponent + * to a plain string representation; + * scale == 0. + */ + public void testToPlainStringPosPosExp() { + String a = "123809648392384754573567356745735.63567890295784902768787678287E+100"; + BigDecimal aNumber = new BigDecimal(a); + String result = "1238096483923847545735673567457356356789029578490276878767828700000000000000000000000000000000000000000000000000000000000000000000000"; + assertTrue("incorrect value", aNumber.toPlainString().equals(result)); + } + + /** + * Convert a BigDecimal to a string representation; + * scale == 0. + */ + public void testToStringZeroScale() { + String a = "-123809648392384754573567356745735635678902957849027687876782870"; + BigDecimal aNumber = new BigDecimal(new BigInteger(a)); + String result = "-123809648392384754573567356745735635678902957849027687876782870"; + assertTrue("incorrect value", aNumber.toString().equals(result)); + } + + /** + * Convert a positive BigDecimal to a string representation + */ + public void testToStringPos() { + String a = "123809648392384754573567356745735.63567890295784902768787678287E-500"; + BigDecimal aNumber = new BigDecimal(a); + String result = "1.2380964839238475457356735674573563567890295784902768787678287E-468"; + assertTrue("incorrect value", aNumber.toString().equals(result)); + } + + /** + * Convert a negative BigDecimal to a string representation + */ + public void testToStringNeg() { + String a = "-123.4564563673567380964839238475457356735674573563567890295784902768787678287E-5"; + BigDecimal aNumber = new BigDecimal(a); + String result = "-0.001234564563673567380964839238475457356735674573563567890295784902768787678287"; + assertTrue("incorrect value", aNumber.toString().equals(result)); + } + + /** + * Create a BigDecimal from a positive long value; scale == 0 + */ + public void testValueOfPosZeroScale() { + long a = 98374823947823578L; + BigDecimal aNumber = BigDecimal.valueOf(a); + String result = "98374823947823578"; + assertTrue("incorrect value", aNumber.toString().equals(result)); + } + + /** + * Create a BigDecimal from a negative long value; scale is 0 + */ + public void testValueOfNegZeroScale() { + long a = -98374823947823578L; + BigDecimal aNumber = BigDecimal.valueOf(a); + String result = "-98374823947823578"; + assertTrue("incorrect value", aNumber.toString().equals(result)); + } + + /** + * Create a BigDecimal from a negative long value; scale is positive + */ + public void testValueOfNegScalePos() { + long a = -98374823947823578L; + int scale = 12; + BigDecimal aNumber = BigDecimal.valueOf(a, scale); + String result = "-98374.823947823578"; + assertTrue("incorrect value", aNumber.toString().equals(result)); + } + + /** + * Create a BigDecimal from a negative long value; scale is negative + */ + public void testValueOfNegScaleNeg() { + long a = -98374823947823578L; + int scale = -12; + BigDecimal aNumber = BigDecimal.valueOf(a, scale); + String result = "-9.8374823947823578E+28"; + assertTrue("incorrect value", aNumber.toString().equals(result)); + } + + /** + * Create a BigDecimal from a negative long value; scale is positive + */ + public void testValueOfPosScalePos() { + long a = 98374823947823578L; + int scale = 12; + BigDecimal aNumber = BigDecimal.valueOf(a, scale); + String result = "98374.823947823578"; + assertTrue("incorrect value", aNumber.toString().equals(result)); + } + + /** + * Create a BigDecimal from a negative long value; scale is negative + */ + public void testValueOfPosScaleNeg() { + long a = 98374823947823578L; + int scale = -12; + BigDecimal aNumber = BigDecimal.valueOf(a, scale); + String result = "9.8374823947823578E+28"; + assertTrue("incorrect value", aNumber.toString().equals(result)); + } + + /** + * Create a BigDecimal from a negative double value + */ + public void testValueOfDoubleNeg() { + double a = -65678765876567576.98788767; + BigDecimal result = BigDecimal.valueOf(a); + String res = "-65678765876567576"; + int resScale = 0; + assertEquals("incorrect value", res, result.toString()); + assertEquals("incorrect scale", resScale, result.scale()); + } + + /** + * Create a BigDecimal from a positive double value + */ + public void testValueOfDoublePos1() { + double a = 65678765876567576.98788767; + BigDecimal result = BigDecimal.valueOf(a); + String res = "65678765876567576"; + int resScale = 0; + assertEquals("incorrect value", res, result.toString()); + assertEquals("incorrect scale", resScale, result.scale()); + } + + /** + * Create a BigDecimal from a positive double value + */ + public void testValueOfDoublePos2() { + double a = 12321237576.98788767; + BigDecimal result = BigDecimal.valueOf(a); + String res = "12321237576.987888"; + int resScale = 6; + assertEquals("incorrect value", res, result.toString()); + assertEquals("incorrect scale", resScale, result.scale()); + } + + /** + * Create a BigDecimal from a positive double value + */ + public void testValueOfDoublePos3() { + double a = 12321237576.9878838; + BigDecimal result = BigDecimal.valueOf(a); + String res = "12321237576.987885"; + int resScale = 6; + assertEquals("incorrect value", res, result.toString()); + assertEquals("incorrect scale", resScale, result.scale()); + } + + /** + * valueOf(Double.NaN) + */ + public void testValueOfDoubleNaN() { + double a = Double.NaN; + try { + BigDecimal.valueOf(a); + fail("NumberFormatException has not been thrown for Double.NaN"); + } catch (NumberFormatException e) { + return; + } + } +} diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/math/BigDecimalScaleOperationsTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/math/BigDecimalScaleOperationsTest.java new file mode 100644 index 0000000..6c74dee --- /dev/null +++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/math/BigDecimalScaleOperationsTest.java @@ -0,0 +1,348 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 Elena Semukhina + */ + +package org.apache.harmony.tests.java.math; + +import junit.framework.TestCase; +import java.math.*; + +/** + * Class: java.math.BigDecimal + * Methods: movePointLeft, movePointRight, scale, setScale, unscaledValue * + */ +public class BigDecimalScaleOperationsTest extends TestCase { + /** + * Check the default scale + */ + public void testScaleDefault() { + String a = "1231212478987482988429808779810457634781384756794987"; + int cScale = 0; + BigDecimal aNumber = new BigDecimal(new BigInteger(a)); + assertTrue("incorrect scale", aNumber.scale() == cScale); + } + + /** + * Check a negative scale + */ + public void testScaleNeg() { + String a = "1231212478987482988429808779810457634781384756794987"; + int aScale = -10; + int cScale = -10; + BigDecimal aNumber = new BigDecimal(new BigInteger(a), aScale); + assertTrue("incorrect scale", aNumber.scale() == cScale); + } + + /** + * Check a positive scale + */ + public void testScalePos() { + String a = "1231212478987482988429808779810457634781384756794987"; + int aScale = 10; + int cScale = 10; + BigDecimal aNumber = new BigDecimal(new BigInteger(a), aScale); + assertTrue("incorrect scale", aNumber.scale() == cScale); + } + + /** + * Check the zero scale + */ + public void testScaleZero() { + String a = "1231212478987482988429808779810457634781384756794987"; + int aScale = 0; + int cScale = 0; + BigDecimal aNumber = new BigDecimal(new BigInteger(a), aScale); + assertTrue("incorrect scale", aNumber.scale() == cScale); + } + + /** + * Check the unscaled value + */ + public void testUnscaledValue() { + String a = "1231212478987482988429808779810457634781384756794987"; + int aScale = 100; + BigInteger bNumber = new BigInteger(a); + BigDecimal aNumber = new BigDecimal(bNumber, aScale); + assertTrue("incorrect unscaled value", aNumber.unscaledValue().equals(bNumber)); + } + + /** + * Set a greater new scale + */ + public void testSetScaleGreater() { + String a = "1231212478987482988429808779810457634781384756794987"; + int aScale = 18; + int newScale = 28; + BigDecimal aNumber = new BigDecimal(new BigInteger(a), aScale); + BigDecimal bNumber = aNumber.setScale(newScale); + assertTrue("incorrect scale", bNumber.scale() == newScale); + assertEquals("incorrect value", 0, bNumber.compareTo(aNumber)); + } + + /** + * Set a less new scale; this.scale == 8; newScale == 5. + */ + public void testSetScaleLess() { + String a = "2.345726458768760000E+10"; + int newScale = 5; + BigDecimal aNumber = new BigDecimal(a); + BigDecimal bNumber = aNumber.setScale(newScale); + assertTrue("incorrect scale", bNumber.scale() == newScale); + assertEquals("incorrect value", 0, bNumber.compareTo(aNumber)); + } + + /** + * Verify an exception when setting a new scale + */ + public void testSetScaleException() { + String a = "1231212478987482988429808779810457634781384756794987"; + int aScale = 28; + int newScale = 18; + BigDecimal aNumber = new BigDecimal(new BigInteger(a), aScale); + try { + aNumber.setScale(newScale); + fail("ArithmeticException has not been caught"); + } catch (ArithmeticException e) { + assertEquals("Improper exception message", "Rounding necessary", e.getMessage()); + } + } + + /** + * Set the same new scale + */ + public void testSetScaleSame() { + String a = "1231212478987482988429808779810457634781384756794987"; + int aScale = 18; + int newScale = 18; + BigDecimal aNumber = new BigDecimal(new BigInteger(a), aScale); + BigDecimal bNumber = aNumber.setScale(newScale); + assertTrue("incorrect scale", bNumber.scale() == newScale); + assertTrue("incorrect value", bNumber.equals(aNumber)); + } + + /** + * Set a new scale + */ + public void testSetScaleRoundUp() { + String a = "1231212478987482988429808779810457634781384756794987"; + String b = "123121247898748298842980877981045763478139"; + int aScale = 28; + int newScale = 18; + BigDecimal aNumber = new BigDecimal(new BigInteger(a), aScale); + BigDecimal bNumber = aNumber.setScale(newScale, BigDecimal.ROUND_UP); + assertTrue("incorrect scale", bNumber.scale() == newScale); + assertTrue("incorrect value", bNumber.unscaledValue().toString().equals(b)); + } + + /** + * Set a new scale + */ + public void testSetScaleRoundDown() { + String a = "1231212478987482988429808779810457634781384756794987"; + String b = "123121247898748298842980877981045763478138"; + int aScale = 28; + int newScale = 18; + BigDecimal aNumber = new BigDecimal(new BigInteger(a), aScale); + BigDecimal bNumber = aNumber.setScale(newScale, BigDecimal.ROUND_DOWN); + assertTrue("incorrect scale", bNumber.scale() == newScale); + assertTrue("incorrect value", bNumber.unscaledValue().toString().equals(b)); + } + + /** + * Set a new scale + */ + public void testSetScaleRoundCeiling() { + String a = "1231212478987482988429808779810457634781384756794987"; + String b = "123121247898748298842980877981045763478139"; + int aScale = 28; + int newScale = 18; + BigDecimal aNumber = new BigDecimal(new BigInteger(a), aScale); + BigDecimal bNumber = aNumber.setScale(newScale, BigDecimal.ROUND_CEILING); + assertTrue("incorrect scale", bNumber.scale() == newScale); + assertTrue("incorrect value", bNumber.unscaledValue().toString().equals(b)); + } + + /** + * Set a new scale + */ + public void testSetScaleRoundFloor() { + String a = "1231212478987482988429808779810457634781384756794987"; + String b = "123121247898748298842980877981045763478138"; + int aScale = 28; + int newScale = 18; + BigDecimal aNumber = new BigDecimal(new BigInteger(a), aScale); + BigDecimal bNumber = aNumber.setScale(newScale, BigDecimal.ROUND_FLOOR); + assertTrue("incorrect scale", bNumber.scale() == newScale); + assertTrue("incorrect value", bNumber.unscaledValue().toString().equals(b)); + } + + /** + * Set a new scale + */ + public void testSetScaleRoundHalfUp() { + String a = "1231212478987482988429808779810457634781384756794987"; + String b = "123121247898748298842980877981045763478138"; + int aScale = 28; + int newScale = 18; + BigDecimal aNumber = new BigDecimal(new BigInteger(a), aScale); + BigDecimal bNumber = aNumber.setScale(newScale, BigDecimal.ROUND_HALF_UP); + assertTrue("incorrect scale", bNumber.scale() == newScale); + assertTrue("incorrect value", bNumber.unscaledValue().toString().equals(b)); + } + + /** + * Set a new scale + */ + public void testSetScaleRoundHalfDown() { + String a = "1231212478987482988429808779810457634781384756794987"; + String b = "123121247898748298842980877981045763478138"; + int aScale = 28; + int newScale = 18; + BigDecimal aNumber = new BigDecimal(new BigInteger(a), aScale); + BigDecimal bNumber = aNumber.setScale(newScale, BigDecimal.ROUND_HALF_DOWN); + assertTrue("incorrect scale", bNumber.scale() == newScale); + assertTrue("incorrect value", bNumber.unscaledValue().toString().equals(b)); + } + + /** + * Set a new scale + */ + public void testSetScaleRoundHalfEven() { + String a = "1231212478987482988429808779810457634781384756794987"; + String b = "123121247898748298842980877981045763478138"; + int aScale = 28; + int newScale = 18; + BigDecimal aNumber = new BigDecimal(new BigInteger(a), aScale); + BigDecimal bNumber = aNumber.setScale(newScale, BigDecimal.ROUND_HALF_EVEN); + assertTrue("incorrect scale", bNumber.scale() == newScale); + assertTrue("incorrect value", bNumber.unscaledValue().toString().equals(b)); + } + + /** + * SetScale(int, RoundingMode) + */ + public void testSetScaleIntRoundingMode() { + String a = "1231212478987482988429808779810457634781384756794987"; + int aScale = 28; + int newScale = 18; + BigDecimal aNumber = new BigDecimal(new BigInteger(a), aScale); + BigDecimal result = aNumber.setScale(newScale, RoundingMode.HALF_EVEN); + String res = "123121247898748298842980.877981045763478138"; + int resScale = 18; + assertEquals("incorrect value", res, result.toString()); + assertEquals("incorrect scale", resScale, result.scale()); + } + + /** + * Move the decimal point to the left; the shift value is positive + */ + public void testMovePointLeftPos() { + String a = "1231212478987482988429808779810457634781384756794987"; + int aScale = 28; + int shift = 18; + int resScale = 46; + BigDecimal aNumber = new BigDecimal(new BigInteger(a), aScale); + BigDecimal bNumber = aNumber.movePointLeft(shift); + assertTrue("incorrect scale", bNumber.scale() == resScale); + assertTrue("incorrect value", bNumber.unscaledValue().toString().equals(a)); + } + + /** + * Move the decimal point to the left; the shift value is positive + */ + public void testMovePointLeftNeg() { + String a = "1231212478987482988429808779810457634781384756794987"; + int aScale = 28; + int shift = -18; + int resScale = 10; + BigDecimal aNumber = new BigDecimal(new BigInteger(a), aScale); + BigDecimal bNumber = aNumber.movePointLeft(shift); + assertTrue("incorrect scale", bNumber.scale() == resScale); + assertTrue("incorrect value", bNumber.unscaledValue().toString().equals(a)); + } + + /** + * Move the decimal point to the right; the shift value is positive + */ + public void testMovePointRightPosGreater() { + String a = "1231212478987482988429808779810457634781384756794987"; + int aScale = 28; + int shift = 18; + int resScale = 10; + BigDecimal aNumber = new BigDecimal(new BigInteger(a), aScale); + BigDecimal bNumber = aNumber.movePointRight(shift); + assertTrue("incorrect scale", bNumber.scale() == resScale); + assertTrue("incorrect value", bNumber.unscaledValue().toString().equals(a)); + } + + /** + * Move the decimal point to the right; the shift value is positive + */ + public void testMovePointRightPosLess() { + String a = "1231212478987482988429808779810457634781384756794987"; + String b = "123121247898748298842980877981045763478138475679498700"; + int aScale = 28; + int shift = 30; + int resScale = 0; + BigDecimal aNumber = new BigDecimal(new BigInteger(a), aScale); + BigDecimal bNumber = aNumber.movePointRight(shift); + assertTrue("incorrect scale", bNumber.scale() == resScale); + assertTrue("incorrect value", bNumber.unscaledValue().toString().equals(b)); + } + + /** + * Move the decimal point to the right; the shift value is positive + */ + public void testMovePointRightNeg() { + String a = "1231212478987482988429808779810457634781384756794987"; + int aScale = 28; + int shift = -18; + int resScale = 46; + BigDecimal aNumber = new BigDecimal(new BigInteger(a), aScale); + BigDecimal bNumber = aNumber.movePointRight(shift); + assertTrue("incorrect scale", bNumber.scale() == resScale); + assertTrue("incorrect value", bNumber.unscaledValue().toString().equals(a)); + } + + /** + * Move the decimal point to the right when the scale overflows + */ + public void testMovePointRightException() { + String a = "12312124789874829887348723648726347429808779810457634781384756794987"; + int aScale = Integer.MAX_VALUE; //2147483647 + int shift = -18; + BigDecimal aNumber = new BigDecimal(new BigInteger(a), aScale); + try { + aNumber.movePointRight(shift); + fail("ArithmeticException has not been caught"); + } catch (ArithmeticException e) { + } + } + + /** + * precision() + */ + public void testPrecision() { + String a = "12312124789874829887348723648726347429808779810457634781384756794987"; + int aScale = 14; + BigDecimal aNumber = new BigDecimal(new BigInteger(a), aScale); + int prec = aNumber.precision(); + assertEquals(68, prec); + } +} diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/math/BigIntegerAddTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/math/BigIntegerAddTest.java new file mode 100644 index 0000000..913eb8a --- /dev/null +++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/math/BigIntegerAddTest.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. + */ +/** + * @author Elena Semukhina + */ + +package org.apache.harmony.tests.java.math; + +import junit.framework.TestCase; +import java.math.BigInteger; + +/** + * Class: java.math.BigInteger + * Method: add + */ +public class BigIntegerAddTest extends TestCase { + /** + * Add two positive numbers of the same length + */ + public void testCase1() { + byte aBytes[] = {1, 2, 3, 4, 5, 6, 7, 1, 2, 3}; + byte bBytes[] = {10, 20, 30, 40, 50, 60, 70, 10, 20, 30}; + int aSign = 1; + int bSign = 1; + byte rBytes[] = {11, 22, 33, 44, 55, 66, 77, 11, 22, 33}; + BigInteger aNumber = new BigInteger(aSign, aBytes); + BigInteger bNumber = new BigInteger(bSign, bBytes); + BigInteger result = aNumber.add(bNumber); + byte resBytes[] = new byte[rBytes.length]; + resBytes = result.toByteArray(); + for(int i = 0; i < resBytes.length; i++) { + assertTrue(resBytes[i] == rBytes[i]); + } + assertEquals("incorrect sign", 1, result.signum()); + } + + /** + * Add two negative numbers of the same length + */ + public void testCase2() { + byte aBytes[] = {1, 2, 3, 4, 5, 6, 7, 1, 2, 3}; + byte bBytes[] = {10, 20, 30, 40, 50, 60, 70, 10, 20, 30}; + int aSign = -1; + int bSign = -1; + byte rBytes[] = {-12, -23, -34, -45, -56, -67, -78, -12, -23, -33}; + BigInteger aNumber = new BigInteger(aSign, aBytes); + BigInteger bNumber = new BigInteger(bSign, bBytes); + BigInteger result = aNumber.add(bNumber); + byte resBytes[] = new byte[rBytes.length]; + resBytes = result.toByteArray(); + for(int i = 0; i < resBytes.length; i++) { + assertTrue(resBytes[i] == rBytes[i]); + } + assertEquals("incorrect sign", -1, result.signum()); + } + + /** + * Add two numbers of the same length. + * The first one is positive and the second is negative. + * The first one is greater in absolute value. + */ + public void testCase3() { + byte aBytes[] = {3, 4, 5, 6, 7, 8, 9}; + byte bBytes[] = {1, 2, 3, 4, 5, 6, 7}; + byte rBytes[] = {2, 2, 2, 2, 2, 2, 2}; + int aSign = 1; + int bSign = -1; + BigInteger aNumber = new BigInteger(aSign, aBytes); + BigInteger bNumber = new BigInteger(bSign, bBytes); + BigInteger result = aNumber.add(bNumber); + byte resBytes[] = new byte[rBytes.length]; + resBytes = result.toByteArray(); + for(int i = 0; i < resBytes.length; i++) { + assertTrue(resBytes[i] == rBytes[i]); + } + assertEquals("incorrect sign", 1, result.signum()); + } + + /** + * Add two numbers of the same length. + * The first one is negative and the second is positive. + * The first one is greater in absolute value. + */ + public void testCase4() { + byte aBytes[] = {3, 4, 5, 6, 7, 8, 9}; + byte bBytes[] = {1, 2, 3, 4, 5, 6, 7}; + byte rBytes[] = {-3, -3, -3, -3, -3, -3, -2}; + int aSign = -1; + int bSign = 1; + BigInteger aNumber = new BigInteger(aSign, aBytes); + BigInteger bNumber = new BigInteger(bSign, bBytes); + BigInteger result = aNumber.add(bNumber); + byte resBytes[] = new byte[rBytes.length]; + resBytes = result.toByteArray(); + for(int i = 0; i < resBytes.length; i++) { + assertTrue(resBytes[i] == rBytes[i]); + } + assertEquals("incorrect sign", -1, result.signum()); + } + + /** + * Add two numbers of the same length. + * The first is positive and the second is negative. + * The first is less in absolute value. + */ + public void testCase5() { + byte aBytes[] = {1, 2, 3, 4, 5, 6, 7}; + byte bBytes[] = {3, 4, 5, 6, 7, 8, 9}; + byte rBytes[] = {-3, -3, -3, -3, -3, -3, -2}; + int aSign = 1; + int bSign = -1; + BigInteger aNumber = new BigInteger(aSign, aBytes); + BigInteger bNumber = new BigInteger(bSign, bBytes); + BigInteger result = aNumber.add(bNumber); + byte resBytes[] = new byte[rBytes.length]; + resBytes = result.toByteArray(); + for(int i = 0; i < resBytes.length; i++) { + assertTrue(resBytes[i] == rBytes[i]); + } + assertEquals("incorrect sign", -1, result.signum()); + } + + /** + * Add two numbers of the same length. + * The first one is negative and the second is positive. + * The first one is less in absolute value. + */ + public void testCase6() { + byte aBytes[] = {1, 2, 3, 4, 5, 6, 7}; + byte bBytes[] = {3, 4, 5, 6, 7, 8, 9}; + byte rBytes[] = {2, 2, 2, 2, 2, 2, 2}; + int aSign = -1; + int bSign = 1; + BigInteger aNumber = new BigInteger(aSign, aBytes); + BigInteger bNumber = new BigInteger(bSign, bBytes); + BigInteger result = aNumber.add(bNumber); + byte resBytes[] = new byte[rBytes.length]; + resBytes = result.toByteArray(); + for(int i = 0; i < resBytes.length; i++) { + assertTrue(resBytes[i] == rBytes[i]); + } + assertEquals("incorrect sign", 1, result.signum()); + } + + /** + * Add two positive numbers of different length. + * The first is longer. + */ + public void testCase7() { + byte aBytes[] = {1, 2, 3, 4, 5, 6, 7, 1, 2, 3, 4, 5, 6, 7}; + byte bBytes[] = {10, 20, 30, 40, 50, 60, 70, 10, 20, 30}; + int aSign = 1; + int bSign = 1; + byte rBytes[] = {1, 2, 3, 4, 15, 26, 37, 41, 52, 63, 74, 15, 26, 37}; + BigInteger aNumber = new BigInteger(aSign, aBytes); + BigInteger bNumber = new BigInteger(bSign, bBytes); + BigInteger result = aNumber.add(bNumber); + byte resBytes[] = new byte[rBytes.length]; + resBytes = result.toByteArray(); + for(int i = 0; i < resBytes.length; i++) { + assertTrue(resBytes[i] == rBytes[i]); + } + assertEquals("incorrect sign", 1, result.signum()); + } + + /** + * Add two positive numbers of different length. + * The second is longer. + */ + public void testCase8() { + byte aBytes[] = {10, 20, 30, 40, 50, 60, 70, 10, 20, 30}; + byte bBytes[] = {1, 2, 3, 4, 5, 6, 7, 1, 2, 3, 4, 5, 6, 7}; + byte rBytes[] = {1, 2, 3, 4, 15, 26, 37, 41, 52, 63, 74, 15, 26, 37}; + BigInteger aNumber = new BigInteger(aBytes); + BigInteger bNumber = new BigInteger(bBytes); + BigInteger result = aNumber.add(bNumber); + byte resBytes[] = new byte[rBytes.length]; + resBytes = result.toByteArray(); + for(int i = 0; i < resBytes.length; i++) { + assertTrue(resBytes[i] == rBytes[i]); + } + assertEquals("incorrect sign", 1, result.signum()); + } + + /** + * Add two negative numbers of different length. + * The first is longer. + */ + public void testCase9() { + byte aBytes[] = {1, 2, 3, 4, 5, 6, 7, 1, 2, 3, 4, 5, 6, 7}; + byte bBytes[] = {10, 20, 30, 40, 50, 60, 70, 10, 20, 30}; + int aSign = -1; + int bSign = -1; + byte rBytes[] = {-2, -3, -4, -5, -16, -27, -38, -42, -53, -64, -75, -16, -27, -37}; + BigInteger aNumber = new BigInteger(aSign, aBytes); + BigInteger bNumber = new BigInteger(bSign, bBytes); + BigInteger result = aNumber.add(bNumber); + byte resBytes[] = new byte[rBytes.length]; + resBytes = result.toByteArray(); + for(int i = 0; i < resBytes.length; i++) { + assertTrue(resBytes[i] == rBytes[i]); + } + assertEquals("incorrect sign", -1, result.signum()); + } + + /** + * Add two negative numbers of different length. + * The second is longer. + */ + public void testCase10() { + byte aBytes[] = {10, 20, 30, 40, 50, 60, 70, 10, 20, 30}; + byte bBytes[] = {1, 2, 3, 4, 5, 6, 7, 1, 2, 3, 4, 5, 6, 7}; + int aSign = -1; + int bSign = -1; + byte rBytes[] = {-2, -3, -4, -5, -16, -27, -38, -42, -53, -64, -75, -16, -27, -37}; + BigInteger aNumber = new BigInteger(aSign, aBytes); + BigInteger bNumber = new BigInteger(bSign, bBytes); + BigInteger result = aNumber.add(bNumber); + byte resBytes[] = new byte[rBytes.length]; + resBytes = result.toByteArray(); + for(int i = 0; i < resBytes.length; i++) { + assertTrue(resBytes[i] == rBytes[i]); + } + assertEquals("incorrect sign", -1, result.signum()); + } + + /** + * Add two numbers of different length and sign. + * The first is positive. + * The first is longer. + */ + public void testCase11() { + byte aBytes[] = {1, 2, 3, 4, 5, 6, 7, 1, 2, 3, 4, 5, 6, 7}; + byte bBytes[] = {10, 20, 30, 40, 50, 60, 70, 10, 20, 30}; + int aSign = 1; + int bSign = -1; + byte rBytes[] = {1, 2, 3, 3, -6, -15, -24, -40, -49, -58, -67, -6, -15, -23}; + BigInteger aNumber = new BigInteger(aSign, aBytes); + BigInteger bNumber = new BigInteger(bSign, bBytes); + BigInteger result = aNumber.add(bNumber); + byte resBytes[] = new byte[rBytes.length]; + resBytes = result.toByteArray(); + for(int i = 0; i < resBytes.length; i++) { + assertTrue(resBytes[i] == rBytes[i]); + } + assertEquals("incorrect sign", 1, result.signum()); + } + + /** + * Add two numbers of different length and sign. + * The first is positive. + * The second is longer. + */ + public void testCase12() { + byte aBytes[] = {10, 20, 30, 40, 50, 60, 70, 10, 20, 30}; + byte bBytes[] = {1, 2, 3, 4, 5, 6, 7, 1, 2, 3, 4, 5, 6, 7}; + int aSign = 1; + int bSign = -1; + byte rBytes[] = {-2, -3, -4, -4, 5, 14, 23, 39, 48, 57, 66, 5, 14, 23}; + BigInteger aNumber = new BigInteger(aSign, aBytes); + BigInteger bNumber = new BigInteger(bSign, bBytes); + BigInteger result = aNumber.add(bNumber); + byte resBytes[] = new byte[rBytes.length]; + resBytes = result.toByteArray(); + for(int i = 0; i < resBytes.length; i++) { + assertTrue(resBytes[i] == rBytes[i]); + } + assertEquals("incorrect sign", -1, result.signum()); + } + + /** + * Add two numbers of different length and sign. + * The first is negative. + * The first is longer. + */ + public void testCase13() { + byte aBytes[] = {1, 2, 3, 4, 5, 6, 7, 1, 2, 3, 4, 5, 6, 7}; + byte bBytes[] = {10, 20, 30, 40, 50, 60, 70, 10, 20, 30}; + int aSign = -1; + int bSign = 1; + byte rBytes[] = {-2, -3, -4, -4, 5, 14, 23, 39, 48, 57, 66, 5, 14, 23}; + BigInteger aNumber = new BigInteger(aSign, aBytes); + BigInteger bNumber = new BigInteger(bSign, bBytes); + BigInteger result = aNumber.add(bNumber); + byte resBytes[] = new byte[rBytes.length]; + resBytes = result.toByteArray(); + for(int i = 0; i < resBytes.length; i++) { + assertTrue(resBytes[i] == rBytes[i]); + } + assertEquals("incorrect sign", -1, result.signum()); + } + + /** + * Add two numbers of different length and sign. + * The first is negative. + * The second is longer. + */ + public void testCase14() { + byte aBytes[] = {10, 20, 30, 40, 50, 60, 70, 10, 20, 30}; + byte bBytes[] = {1, 2, 3, 4, 5, 6, 7, 1, 2, 3, 4, 5, 6, 7}; + int aSign = -1; + int bSign = 1; + byte rBytes[] = {1, 2, 3, 3, -6, -15, -24, -40, -49, -58, -67, -6, -15, -23}; + BigInteger aNumber = new BigInteger(aSign, aBytes); + BigInteger bNumber = new BigInteger(bSign, bBytes); + BigInteger result = aNumber.add(bNumber); + byte resBytes[] = new byte[rBytes.length]; + resBytes = result.toByteArray(); + for(int i = 0; i < resBytes.length; i++) { + assertTrue(resBytes[i] == rBytes[i]); + } + assertEquals("incorrect sign", 1, result.signum()); + } + + /** + * Add two equal numbers of different signs + */ + public void testCase15() { + byte aBytes[] = {1, 2, 3, 4, 5, 6, 7}; + byte bBytes[] = {1, 2, 3, 4, 5, 6, 7}; + byte rBytes[] = {0}; + int aSign = -1; + int bSign = 1; + BigInteger aNumber = new BigInteger(aSign, aBytes); + BigInteger bNumber = new BigInteger(bSign, bBytes); + BigInteger result = aNumber.add(bNumber); + byte resBytes[] = new byte[rBytes.length]; + for(int i = 0; i < resBytes.length; i++) { + assertTrue(resBytes[i] == rBytes[i]); + } + assertEquals("incorrect sign", 0, result.signum()); + } + + /** + * Add zero to a number + */ + public void testCase16() { + byte aBytes[] = {1, 2, 3, 4, 5, 6, 7}; + byte bBytes[] = {0}; + byte rBytes[] = {1, 2, 3, 4, 5, 6, 7}; + int aSign = 1; + int bSign = 1; + BigInteger aNumber = new BigInteger(aSign, aBytes); + BigInteger bNumber = new BigInteger(bSign, bBytes); + BigInteger result = aNumber.add(bNumber); + byte resBytes[] = new byte[rBytes.length]; + resBytes = result.toByteArray(); + for(int i = 0; i < resBytes.length; i++) { + assertTrue(resBytes[i] == rBytes[i]); + } + assertEquals("incorrect sign", 1, result.signum()); + } + + /** + * Add a number to zero + */ + public void testCase17() { + byte aBytes[] = {0}; + byte bBytes[] = {1, 2, 3, 4, 5, 6, 7}; + byte rBytes[] = {1, 2, 3, 4, 5, 6, 7}; + int aSign = 1; + int bSign = 1; + BigInteger aNumber = new BigInteger(aSign, aBytes); + BigInteger bNumber = new BigInteger(bSign, bBytes); + BigInteger result = aNumber.add(bNumber); + byte resBytes[] = new byte[rBytes.length]; + resBytes = result.toByteArray(); + for(int i = 0; i < resBytes.length; i++) { + assertTrue(resBytes[i] == rBytes[i]); + } + assertEquals("incorrect sign", 1, result.signum()); + } + + /** + * Add zero to zero + */ + public void testCase18() { + byte aBytes[] = {0}; + byte bBytes[] = {0}; + byte rBytes[] = {0}; + int aSign = 1; + int bSign = 1; + BigInteger aNumber = new BigInteger(aSign, aBytes); + BigInteger bNumber = new BigInteger(bSign, bBytes); + BigInteger result = aNumber.add(bNumber); + byte resBytes[] = new byte[rBytes.length]; + resBytes = result.toByteArray(); + for(int i = 0; i < resBytes.length; i++) { + assertTrue(resBytes[i] == rBytes[i]); + } + assertEquals("incorrect sign", 0, result.signum()); + } + + /** + * Add ZERO to a number + */ + public void testCase19() { + byte aBytes[] = {1, 2, 3, 4, 5, 6, 7}; + byte rBytes[] = {1, 2, 3, 4, 5, 6, 7}; + int aSign = 1; + BigInteger aNumber = new BigInteger(aSign, aBytes); + BigInteger bNumber = BigInteger.ZERO; + BigInteger result = aNumber.add(bNumber); + byte resBytes[] = new byte[rBytes.length]; + resBytes = result.toByteArray(); + for(int i = 0; i < resBytes.length; i++) { + assertTrue(resBytes[i] == rBytes[i]); + } + assertEquals("incorrect sign", 1, result.signum()); + } + + /** + * Add a number to zero + */ + public void testCase20() { + byte bBytes[] = {1, 2, 3, 4, 5, 6, 7}; + byte rBytes[] = {1, 2, 3, 4, 5, 6, 7}; + int bSign = 1; + BigInteger aNumber = BigInteger.ZERO; + BigInteger bNumber = new BigInteger(bSign, bBytes); + BigInteger result = aNumber.add(bNumber); + byte resBytes[] = new byte[rBytes.length]; + resBytes = result.toByteArray(); + for(int i = 0; i < resBytes.length; i++) { + assertTrue(resBytes[i] == rBytes[i]); + } + assertEquals("incorrect sign", 1, result.signum()); + } + + /** + * Add ZERO to ZERO + */ + public void testCase21() { + byte rBytes[] = {0}; + BigInteger aNumber = BigInteger.ZERO; + BigInteger bNumber = BigInteger.ZERO; + BigInteger result = aNumber.add(bNumber); + byte resBytes[] = new byte[rBytes.length]; + resBytes = result.toByteArray(); + for(int i = 0; i < resBytes.length; i++) { + assertTrue(resBytes[i] == rBytes[i]); + } + assertEquals("incorrect sign", 0, result.signum()); + } + + /** + * Add ONE to ONE + */ + public void testCase22() { + byte rBytes[] = {2}; + BigInteger aNumber = BigInteger.ONE; + BigInteger bNumber = BigInteger.ONE; + BigInteger result = aNumber.add(bNumber); + byte resBytes[] = new byte[rBytes.length]; + resBytes = result.toByteArray(); + for(int i = 0; i < resBytes.length; i++) { + assertTrue(resBytes[i] == rBytes[i]); + } + assertEquals("incorrect sign", 1, result.signum()); + } + + /** + * Add two numbers so that carry is 1 + */ + public void testCase23() { + byte aBytes[] = {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}; + byte bBytes[] = {-1, -1, -1, -1, -1, -1, -1, -1}; + int aSign = 1; + int bSign = 1; + byte rBytes[] = {1, 0, 0, 0, 0, 0, 0, -1, -1, -1, -1, -1, -1, -1, -2}; + BigInteger aNumber = new BigInteger(aSign, aBytes); + BigInteger bNumber = new BigInteger(bSign, bBytes); + BigInteger result = aNumber.add(bNumber); + byte resBytes[] = new byte[rBytes.length]; + resBytes = result.toByteArray(); + for(int i = 0; i < resBytes.length; i++) { + assertTrue(resBytes[i] == rBytes[i]); + } + assertEquals("incorrect sign", 1, result.signum()); + } +} diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/math/BigIntegerAndTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/math/BigIntegerAndTest.java new file mode 100644 index 0000000..d057bfa --- /dev/null +++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/math/BigIntegerAndTest.java @@ -0,0 +1,432 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 Elena Semukhina + */ + +package org.apache.harmony.tests.java.math; + +import junit.framework.TestCase; +import java.math.BigInteger; + +/** + * Class: java.math.BigInteger + * Method: and + */ +public class BigIntegerAndTest extends TestCase { + /** + * And for zero and a positive number + */ + public void testZeroPos() { + byte aBytes[] = {0}; + byte bBytes[] = {-2, -3, -4, -4, 5, 14, 23, 39, 48, 57, 66, 5, 14, 23}; + int aSign = 0; + int bSign = 1; + byte rBytes[] = {0}; + BigInteger aNumber = new BigInteger(aSign, aBytes); + BigInteger bNumber = new BigInteger(bSign, bBytes); + BigInteger result = aNumber.and(bNumber); + byte resBytes[] = new byte[rBytes.length]; + resBytes = result.toByteArray(); + for(int i = 0; i < resBytes.length; i++) { + assertTrue(resBytes[i] == rBytes[i]); + } + assertEquals("incorrect sign", 0, result.signum()); + } + + /** + * And for zero and a negative number + */ + public void testZeroNeg() { + byte aBytes[] = {0}; + byte bBytes[] = {-2, -3, -4, -4, 5, 14, 23, 39, 48, 57, 66, 5, 14, 23}; + int aSign = 0; + int bSign = -1; + byte rBytes[] = {0}; + BigInteger aNumber = new BigInteger(aSign, aBytes); + BigInteger bNumber = new BigInteger(bSign, bBytes); + BigInteger result = aNumber.and(bNumber); + byte resBytes[] = new byte[rBytes.length]; + resBytes = result.toByteArray(); + for(int i = 0; i < resBytes.length; i++) { + assertTrue(resBytes[i] == rBytes[i]); + } + assertEquals("incorrect sign", 0, result.signum()); + } + + /** + * And for a positive number and zero + */ + public void testPosZero() { + byte aBytes[] = {-2, -3, -4, -4, 5, 14, 23, 39, 48, 57, 66, 5, 14, 23}; + byte bBytes[] = {0}; + int aSign = 1; + int bSign = 0; + byte rBytes[] = {0}; + BigInteger aNumber = new BigInteger(aSign, aBytes); + BigInteger bNumber = new BigInteger(bSign, bBytes); + BigInteger result = aNumber.and(bNumber); + byte resBytes[] = new byte[rBytes.length]; + resBytes = result.toByteArray(); + for(int i = 0; i < resBytes.length; i++) { + assertTrue(resBytes[i] == rBytes[i]); + } + assertEquals("incorrect sign", 0, result.signum()); + } + + /** + * And for a negative number and zero + */ + public void testNegPos() { + byte aBytes[] = {-2, -3, -4, -4, 5, 14, 23, 39, 48, 57, 66, 5, 14, 23}; + byte bBytes[] = {0}; + int aSign = -1; + int bSign = 0; + byte rBytes[] = {0}; + BigInteger aNumber = new BigInteger(aSign, aBytes); + BigInteger bNumber = new BigInteger(bSign, bBytes); + BigInteger result = aNumber.and(bNumber); + byte resBytes[] = new byte[rBytes.length]; + resBytes = result.toByteArray(); + for(int i = 0; i < resBytes.length; i++) { + assertTrue(resBytes[i] == rBytes[i]); + } + assertEquals("incorrect sign", 0, result.signum()); + } + + /** + * And for zero and zero + */ + public void testZeroZero() { + byte aBytes[] = {0}; + byte bBytes[] = {0}; + int aSign = 0; + int bSign = 0; + byte rBytes[] = {0}; + BigInteger aNumber = new BigInteger(aSign, aBytes); + BigInteger bNumber = new BigInteger(bSign, bBytes); + BigInteger result = aNumber.and(bNumber); + byte resBytes[] = new byte[rBytes.length]; + resBytes = result.toByteArray(); + for(int i = 0; i < resBytes.length; i++) { + assertTrue(resBytes[i] == rBytes[i]); + } + assertEquals("incorrect sign", 0, result.signum()); + } + + /** + * And for zero and one + */ + public void testZeroOne() { + BigInteger aNumber = BigInteger.ZERO; + BigInteger bNumber = BigInteger.ONE; + BigInteger result = aNumber.and(bNumber); + assertTrue(result.equals(BigInteger.ZERO)); + assertEquals("incorrect sign", 0, result.signum()); + } + + /** + * And for one and one + */ + public void testOneOne() { + BigInteger aNumber = BigInteger.ONE; + BigInteger bNumber = BigInteger.ONE; + BigInteger result = aNumber.and(bNumber); + assertTrue(result.equals(BigInteger.ONE)); + assertEquals("incorrect sign", 1, result.signum()); + } + + /** + * And for two positive numbers of the same length + */ + public void testPosPosSameLength() { + byte aBytes[] = {-128, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26, -117}; + byte bBytes[] = {-2, -3, -4, -4, 5, 14, 23, 39, 48, 57, 66, 5, 14, 23}; + int aSign = 1; + int bSign = 1; + byte rBytes[] = {0, -128, 56, 100, 4, 4, 17, 37, 16, 1, 64, 1, 10, 3}; + BigInteger aNumber = new BigInteger(aSign, aBytes); + BigInteger bNumber = new BigInteger(bSign, bBytes); + BigInteger result = aNumber.and(bNumber); + byte resBytes[] = new byte[rBytes.length]; + resBytes = result.toByteArray(); + for(int i = 0; i < resBytes.length; i++) { + assertTrue(resBytes[i] == rBytes[i]); + } + assertEquals("incorrect sign", 1, result.signum()); + } + + /** + * And for two positive numbers; the first is longer + */ + public void testPosPosFirstLonger() { + byte aBytes[] = {-128, 9, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26, -117, 23, 87, -25, -75}; + byte bBytes[] = {-2, -3, -4, -4, 5, 14, 23, 39, 48, 57, 66, 5, 14, 23}; + int aSign = 1; + int bSign = 1; + byte rBytes[] = {0, -2, -76, 88, 44, 1, 2, 17, 35, 16, 9, 2, 5, 6, 21}; + BigInteger aNumber = new BigInteger(aSign, aBytes); + BigInteger bNumber = new BigInteger(bSign, bBytes); + BigInteger result = aNumber.and(bNumber); + byte resBytes[] = new byte[rBytes.length]; + resBytes = result.toByteArray(); + for(int i = 0; i < resBytes.length; i++) { + assertTrue(resBytes[i] == rBytes[i]); + } + assertEquals("incorrect sign", 1, result.signum()); + } + + /** + * And for two positive numbers; the first is shorter + */ + public void testPosPosFirstShorter() { + byte aBytes[] = {-2, -3, -4, -4, 5, 14, 23, 39, 48, 57, 66, 5, 14, 23}; + byte bBytes[] = {-128, 9, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26, -117, 23, 87, -25, -75}; + int aSign = 1; + int bSign = 1; + byte rBytes[] = {0, -2, -76, 88, 44, 1, 2, 17, 35, 16, 9, 2, 5, 6, 21}; + BigInteger aNumber = new BigInteger(aSign, aBytes); + BigInteger bNumber = new BigInteger(bSign, bBytes); + BigInteger result = aNumber.and(bNumber); + byte resBytes[] = new byte[rBytes.length]; + resBytes = result.toByteArray(); + for(int i = 0; i < resBytes.length; i++) { + assertTrue(resBytes[i] == rBytes[i]); + } + assertEquals("incorrect sign", 1, result.signum()); + } + + /** + * And for two negative numbers of the same length + */ + public void testNegNegSameLength() { + byte aBytes[] = {-128, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26, -117}; + byte bBytes[] = {-2, -3, -4, -4, 5, 14, 23, 39, 48, 57, 66, 5, 14, 23}; + int aSign = -1; + int bSign = -1; + byte rBytes[] = {-1, 1, 2, 3, 3, 0, 65, -96, -48, -124, -60, 12, -40, -31, 97}; + BigInteger aNumber = new BigInteger(aSign, aBytes); + BigInteger bNumber = new BigInteger(bSign, bBytes); + BigInteger result = aNumber.and(bNumber); + byte resBytes[] = new byte[rBytes.length]; + resBytes = result.toByteArray(); + for(int i = 0; i < resBytes.length; i++) { + assertTrue(resBytes[i] == rBytes[i]); + } + assertEquals("incorrect sign", -1, result.signum()); + } + + /** + * And for two negative numbers; the first is longer + */ + public void testNegNegFirstLonger() { + byte aBytes[] = {-128, 9, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26, -117, 23, 87, -25, -75}; + byte bBytes[] = {-2, -3, -4, -4, 5, 14, 23, 39, 48, 57, 66, 5, 14, 23}; + int aSign = -1; + int bSign = -1; + byte rBytes[] = {-1, 127, -10, -57, -101, 1, 2, 2, 2, -96, -16, 8, -40, -59, 68, -88, -88, 16, 73}; + BigInteger aNumber = new BigInteger(aSign, aBytes); + BigInteger bNumber = new BigInteger(bSign, bBytes); + BigInteger result = aNumber.and(bNumber); + byte resBytes[] = new byte[rBytes.length]; + resBytes = result.toByteArray(); + for(int i = 0; i < resBytes.length; i++) { + assertTrue(resBytes[i] == rBytes[i]); + } + assertEquals("incorrect sign", -1, result.signum()); + } + + /** + * And for two negative numbers; the first is shorter + */ + public void testNegNegFirstShorter() { + byte aBytes[] = {-2, -3, -4, -4, 5, 14, 23, 39, 48, 57, 66, 5, 14, 23}; + byte bBytes[] = {-128, 9, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26, -117, 23, 87, -25, -75}; + int aSign = -1; + int bSign = -1; + byte rBytes[] = {-1, 127, -10, -57, -101, 1, 2, 2, 2, -96, -16, 8, -40, -59, 68, -88, -88, 16, 73}; + BigInteger aNumber = new BigInteger(aSign, aBytes); + BigInteger bNumber = new BigInteger(bSign, bBytes); + BigInteger result = aNumber.and(bNumber); + byte resBytes[] = new byte[rBytes.length]; + resBytes = result.toByteArray(); + for(int i = 0; i < resBytes.length; i++) { + assertTrue(resBytes[i] == rBytes[i]); + } + assertEquals("incorrect sign", -1, result.signum()); + } + + /** + * And for two numbers of different signs and the same length + */ + public void testPosNegSameLength() { + byte aBytes[] = {-128, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26, -117}; + byte bBytes[] = {-2, -3, -4, -4, 5, 14, 23, 39, 48, 57, 66, 5, 14, 23}; + int aSign = 1; + int bSign = -1; + byte rBytes[] = {0, -6, -80, 72, 8, 75, 2, -79, 34, 16, -119}; + BigInteger aNumber = new BigInteger(aSign, aBytes); + BigInteger bNumber = new BigInteger(bSign, bBytes); + BigInteger result = aNumber.and(bNumber); + byte resBytes[] = new byte[rBytes.length]; + resBytes = result.toByteArray(); + for(int i = 0; i < resBytes.length; i++) { + assertTrue(resBytes[i] == rBytes[i]); + } + assertEquals("incorrect sign", 1, result.signum()); + } + + /** + * And for two numbers of different signs and the same length + */ + public void testNegPosSameLength() { + byte aBytes[] = {-128, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26, -117}; + byte bBytes[] = {-2, -3, -4, -4, 5, 14, 23, 39, 48, 57, 66, 5, 14, 23}; + int aSign = -1; + int bSign = 1; + byte rBytes[] = {0, -2, 125, -60, -104, 1, 10, 6, 2, 32, 56, 2, 4, 4, 21}; + BigInteger aNumber = new BigInteger(aSign, aBytes); + BigInteger bNumber = new BigInteger(bSign, bBytes); + BigInteger result = aNumber.and(bNumber); + byte resBytes[] = new byte[rBytes.length]; + resBytes = result.toByteArray(); + for(int i = 0; i < resBytes.length; i++) { + assertTrue(resBytes[i] == rBytes[i]); + } + assertEquals("incorrect sign", 1, result.signum()); + } + + /** + * And for a negative and a positive numbers; the first is longer + */ + public void testNegPosFirstLonger() { + byte aBytes[] = {-128, 9, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26, -117, 23, 87, -25, -75}; + byte bBytes[] = {-2, -3, -4, -4, 5, 14, 23, 39, 48, 57, 66, 5, 14, 23}; + int aSign = -1; + int bSign = 1; + byte rBytes[] = {73, -92, -48, 4, 12, 6, 4, 32, 48, 64, 0, 8, 3}; + BigInteger aNumber = new BigInteger(aSign, aBytes); + BigInteger bNumber = new BigInteger(bSign, bBytes); + BigInteger result = aNumber.and(bNumber); + byte resBytes[] = new byte[rBytes.length]; + resBytes = result.toByteArray(); + for(int i = 0; i < resBytes.length; i++) { + assertTrue(resBytes[i] == rBytes[i]); + } + assertEquals("incorrect sign", 1, result.signum()); + } + + /** + * And for a negative and a positive numbers; the first is shorter + */ + public void testNegPosFirstShorter() { + byte aBytes[] = {-2, -3, -4, -4, 5, 14, 23, 39, 48, 57, 66, 5, 14, 23}; + byte bBytes[] = {-128, 9, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26, -117, 23, 87, -25, -75}; + int aSign = -1; + int bSign = 1; + byte rBytes[] = {0, -128, 9, 56, 100, 0, 0, 1, 1, 90, 1, -32, 0, 10, -126, 21, 82, -31, -95}; + BigInteger aNumber = new BigInteger(aSign, aBytes); + BigInteger bNumber = new BigInteger(bSign, bBytes); + BigInteger result = aNumber.and(bNumber); + byte resBytes[] = new byte[rBytes.length]; + resBytes = result.toByteArray(); + for(int i = 0; i < resBytes.length; i++) { + assertTrue(resBytes[i] == rBytes[i]); + } + assertEquals("incorrect sign", 1, result.signum()); + } + + /** + * And for a positive and a negative numbers; the first is longer + */ + public void testPosNegFirstLonger() { + byte aBytes[] = {-128, 9, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26, -117, 23, 87, -25, -75}; + byte bBytes[] = {-2, -3, -4, -4, 5, 14, 23, 39, 48, 57, 66, 5, 14, 23}; + int aSign = 1; + int bSign = -1; + byte rBytes[] = {0, -128, 9, 56, 100, 0, 0, 1, 1, 90, 1, -32, 0, 10, -126, 21, 82, -31, -95}; + BigInteger aNumber = new BigInteger(aSign, aBytes); + BigInteger bNumber = new BigInteger(bSign, bBytes); + BigInteger result = aNumber.and(bNumber); + byte resBytes[] = new byte[rBytes.length]; + resBytes = result.toByteArray(); + for(int i = 0; i < resBytes.length; i++) { + assertTrue(resBytes[i] == rBytes[i]); + } + assertEquals("incorrect sign", 1, result.signum()); + } + + /** + * And for a positive and a negative numbers; the first is shorter + */ + public void testPosNegFirstShorter() { + byte aBytes[] = {-2, -3, -4, -4, 5, 14, 23, 39, 48, 57, 66, 5, 14, 23}; + byte bBytes[] = {-128, 9, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26, -117, 23, 87, -25, -75}; + int aSign = 1; + int bSign = -1; + byte rBytes[] = {73, -92, -48, 4, 12, 6, 4, 32, 48, 64, 0, 8, 3}; + BigInteger aNumber = new BigInteger(aSign, aBytes); + BigInteger bNumber = new BigInteger(bSign, bBytes); + BigInteger result = aNumber.and(bNumber); + byte resBytes[] = new byte[rBytes.length]; + resBytes = result.toByteArray(); + for(int i = 0; i < resBytes.length; i++) { + assertTrue(resBytes[i] == rBytes[i]); + } + assertEquals("incorrect sign", 1, result.signum()); + } + + /** + * Test for a special case + */ + public void testSpecialCase1() { + byte aBytes[] = {-1, -1, -1, -1}; + byte bBytes[] = {5, -4, -3, -2}; + int aSign = -1; + int bSign = -1; + byte rBytes[] = {-1, 0, 0, 0, 0}; + BigInteger aNumber = new BigInteger(aSign, aBytes); + BigInteger bNumber = new BigInteger(bSign, bBytes); + BigInteger result = aNumber.and(bNumber); + byte resBytes[] = new byte[rBytes.length]; + resBytes = result.toByteArray(); + for(int i = 0; i < resBytes.length; i++) { + assertTrue(resBytes[i] == rBytes[i]); + } + assertEquals("incorrect sign", -1, result.signum()); + } + + /** + * Test for a special case + */ + public void testSpecialCase2() { + byte aBytes[] = {-51}; + byte bBytes[] = {-52, -51, -50, -49, -48}; + int aSign = -1; + int bSign = 1; + byte rBytes[] = {0, -52, -51, -50, -49, 16}; + BigInteger aNumber = new BigInteger(aSign, aBytes); + BigInteger bNumber = new BigInteger(bSign, bBytes); + BigInteger result = aNumber.and(bNumber); + byte resBytes[] = new byte[rBytes.length]; + resBytes = result.toByteArray(); + for(int i = 0; i < resBytes.length; i++) { + assertTrue(resBytes[i] == rBytes[i]); + } + assertEquals("incorrect sign", 1, result.signum()); + } +} diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/math/BigIntegerCompareTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/math/BigIntegerCompareTest.java new file mode 100644 index 0000000..a65c77e --- /dev/null +++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/math/BigIntegerCompareTest.java @@ -0,0 +1,533 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 Elena Semukhina + */ + +package org.apache.harmony.tests.java.math; + +import junit.framework.TestCase; +import java.math.BigInteger; + +/** + * Class: java.math.BigInteger + * Methods: abs, compareTo, equals, max, min, negate, signum + */ +public class BigIntegerCompareTest extends TestCase { + /** + * abs() for a positive number + */ + public void testAbsPositive() { + byte aBytes[] = {1, 2, 3, 4, 5, 6, 7}; + int aSign = 1; + byte rBytes[] = {1, 2, 3, 4, 5, 6, 7}; + BigInteger aNumber = new BigInteger(aSign, aBytes); + BigInteger result = aNumber.abs(); + byte resBytes[] = new byte[rBytes.length]; + resBytes = result.toByteArray(); + for(int i = 0; i < resBytes.length; i++) { + assertTrue(resBytes[i] == rBytes[i]); + } + assertEquals("incorrect sign", 1, result.signum()); + } + + /** + * abs() for a negative number + */ + public void testAbsNegative() { + byte aBytes[] = {1, 2, 3, 4, 5, 6, 7}; + int aSign = -1; + byte rBytes[] = {1, 2, 3, 4, 5, 6, 7}; + BigInteger aNumber = new BigInteger(aSign, aBytes); + BigInteger result = aNumber.abs(); + byte resBytes[] = new byte[rBytes.length]; + resBytes = result.toByteArray(); + for(int i = 0; i < resBytes.length; i++) { + assertTrue(resBytes[i] == rBytes[i]); + } + assertEquals("incorrect sign", 1, result.signum()); + } + + /** + * compareTo(BigInteger a). + * Compare two positive numbers. + * The first is greater. + */ + public void testCompareToPosPos1() { + byte aBytes[] = {12, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26, 3, 91}; + byte bBytes[] = {10, 20, 30, 40, 50, 60, 70, 10, 20, 30}; + int aSign = 1; + int bSign = 1; + BigInteger aNumber = new BigInteger(aSign, aBytes); + BigInteger bNumber = new BigInteger(bSign, bBytes); + assertEquals(1, aNumber.compareTo(bNumber)); + } + + /** + * compareTo(BigInteger a). + * Compare two positive numbers. + * The first is less. + */ + public void testCompareToPosPos2() { + byte aBytes[] = {10, 20, 30, 40, 50, 60, 70, 10, 20, 30}; + byte bBytes[] = {12, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26, 3, 91}; + int aSign = 1; + int bSign = 1; + BigInteger aNumber = new BigInteger(aSign, aBytes); + BigInteger bNumber = new BigInteger(bSign, bBytes); + assertEquals(-1, aNumber.compareTo(bNumber)); + } + + /** + * compareTo(BigInteger a). + * Compare two equal positive numbers. + */ + public void testCompareToEqualPos() { + byte aBytes[] = {12, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26, 3, 91}; + byte bBytes[] = {12, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26, 3, 91}; + int aSign = 1; + int bSign = 1; + BigInteger aNumber = new BigInteger(aSign, aBytes); + BigInteger bNumber = new BigInteger(bSign, bBytes); + assertEquals(0, aNumber.compareTo(bNumber)); + } + + /** + * compareTo(BigInteger a). + * Compare two negative numbers. + * The first is greater in absolute value. + */ + public void testCompareToNegNeg1() { + byte aBytes[] = {12, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26, 3, 91}; + byte bBytes[] = {10, 20, 30, 40, 50, 60, 70, 10, 20, 30}; + int aSign = -1; + int bSign = -1; + BigInteger aNumber = new BigInteger(aSign, aBytes); + BigInteger bNumber = new BigInteger(bSign, bBytes); + assertEquals(-1, aNumber.compareTo(bNumber)); + } + + /** + * compareTo(BigInteger a). + * Compare two negative numbers. + * The first is less in absolute value. + */ + public void testCompareNegNeg2() { + byte aBytes[] = {10, 20, 30, 40, 50, 60, 70, 10, 20, 30}; + byte bBytes[] = {12, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26, 3, 91}; + int aSign = -1; + int bSign = -1; + BigInteger aNumber = new BigInteger(aSign, aBytes); + BigInteger bNumber = new BigInteger(bSign, bBytes); + assertEquals(1, aNumber.compareTo(bNumber)); + } + + /** + * compareTo(BigInteger a). + * Compare two equal negative numbers. + */ + public void testCompareToEqualNeg() { + byte aBytes[] = {12, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26, 3, 91}; + byte bBytes[] = {12, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26, 3, 91}; + int aSign = -1; + int bSign = -1; + BigInteger aNumber = new BigInteger(aSign, aBytes); + BigInteger bNumber = new BigInteger(bSign, bBytes); + assertEquals(0, aNumber.compareTo(bNumber)); + } + + /** + * compareTo(BigInteger a). + * Compare two numbers of different signs. + * The first is positive. + */ + public void testCompareToDiffSigns1() { + byte aBytes[] = {12, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26, 3, 91}; + byte bBytes[] = {10, 20, 30, 40, 50, 60, 70, 10, 20, 30}; + int aSign = 1; + int bSign = -1; + BigInteger aNumber = new BigInteger(aSign, aBytes); + BigInteger bNumber = new BigInteger(bSign, bBytes); + assertEquals(1, aNumber.compareTo(bNumber)); + } + + /** + * compareTo(BigInteger a). + * Compare two numbers of different signs. + * The first is negative. + */ + public void testCompareToDiffSigns2() { + byte aBytes[] = {12, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26, 3, 91}; + byte bBytes[] = {10, 20, 30, 40, 50, 60, 70, 10, 20, 30}; + int aSign = -1; + int bSign = 1; + BigInteger aNumber = new BigInteger(aSign, aBytes); + BigInteger bNumber = new BigInteger(bSign, bBytes); + assertEquals(-1, aNumber.compareTo(bNumber)); + } + + /** + * compareTo(BigInteger a). + * Compare a positive number to ZERO. + */ + public void testCompareToPosZero() { + byte aBytes[] = {12, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26, 3, 91}; + int aSign = 1; + BigInteger aNumber = new BigInteger(aSign, aBytes); + BigInteger bNumber = BigInteger.ZERO; + assertEquals(1, aNumber.compareTo(bNumber)); + } + + /** + * compareTo(BigInteger a). + * Compare ZERO to a positive number. + */ + public void testCompareToZeroPos() { + byte bBytes[] = {12, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26, 3, 91}; + int bSign = 1; + BigInteger aNumber = BigInteger.ZERO; + BigInteger bNumber = new BigInteger(bSign, bBytes); + assertEquals(-1, aNumber.compareTo(bNumber)); + } + + /** + * compareTo(BigInteger a). + * Compare a negative number to ZERO. + */ + public void testCompareToNegZero() { + byte aBytes[] = {12, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26, 3, 91}; + int aSign = -1; + BigInteger aNumber = new BigInteger(aSign, aBytes); + BigInteger bNumber = BigInteger.ZERO; + assertEquals(-1, aNumber.compareTo(bNumber)); + } + + /** + * compareTo(BigInteger a). + * Compare ZERO to a negative number. + */ + public void testCompareToZeroNeg() { + byte bBytes[] = {12, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26, 3, 91}; + int bSign = -1; + BigInteger aNumber = BigInteger.ZERO; + BigInteger bNumber = new BigInteger(bSign, bBytes); + assertEquals(1, aNumber.compareTo(bNumber)); + } + + /** + * compareTo(BigInteger a). + * Compare ZERO to ZERO. + */ + public void testCompareToZeroZero() { + BigInteger aNumber = BigInteger.ZERO; + BigInteger bNumber = BigInteger.ZERO; + assertEquals(0, aNumber.compareTo(bNumber)); + } + + /** + * equals(Object obj). + * obj is not a BigInteger + */ + public void testEqualsObject() { + byte aBytes[] = {12, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26, 3, 91}; + int aSign = 1; + BigInteger aNumber = new BigInteger(aSign, aBytes); + Object obj = new Object(); + assertFalse(aNumber.equals(obj)); + } + + /** + * equals(null). + */ + public void testEqualsNull() { + byte aBytes[] = {12, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26, 3, 91}; + int aSign = 1; + BigInteger aNumber = new BigInteger(aSign, aBytes); + assertFalse(aNumber.equals(null)); + } + + /** + * equals(Object obj). + * obj is a BigInteger. + * numbers are equal. + */ + public void testEqualsBigIntegerTrue() { + byte aBytes[] = {12, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26, 3, 91}; + byte bBytes[] = {12, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26, 3, 91}; + int aSign = 1; + int bSign = 1; + BigInteger aNumber = new BigInteger(aSign, aBytes); + Object bNumber = new BigInteger(bSign, bBytes); + assertTrue(aNumber.equals(bNumber)); + } + + /** + * equals(Object obj). + * obj is a BigInteger. + * numbers are not equal. + */ + public void testEqualsBigIntegerFalse() { + byte aBytes[] = {12, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26, 3, 91}; + byte bBytes[] = {45, 91, 3, -15, 35, 26, 3, 91}; + int aSign = 1; + int bSign = 1; + BigInteger aNumber = new BigInteger(aSign, aBytes); + Object bNumber = new BigInteger(bSign, bBytes); + assertFalse(aNumber.equals(bNumber)); + } + + /** + * max(BigInteger val). + * the first is greater. + */ + public void testMaxGreater() { + byte aBytes[] = {12, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26, 3, 91}; + byte bBytes[] = {45, 91, 3, -15, 35, 26, 3, 91}; + int aSign = 1; + int bSign = 1; + byte rBytes[] = {12, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26, 3, 91}; + BigInteger aNumber = new BigInteger(aSign, aBytes); + BigInteger bNumber = new BigInteger(bSign, bBytes); + BigInteger result = aNumber.max(bNumber); + byte resBytes[] = new byte[rBytes.length]; + resBytes = result.toByteArray(); + for(int i = 0; i < resBytes.length; i++) { + assertTrue(resBytes[i] == rBytes[i]); + } + assertTrue("incorrect sign", result.signum() == 1); + } + + /** + * max(BigInteger val). + * the first is less. + */ + public void testMaxLess() { + byte aBytes[] = {45, 91, 3, -15, 35, 26, 3, 91}; + byte bBytes[] = {12, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26, 3, 91}; + int aSign = 1; + int bSign = 1; + byte rBytes[] = {12, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26, 3, 91}; + BigInteger aNumber = new BigInteger(aSign, aBytes); + BigInteger bNumber = new BigInteger(bSign, bBytes); + BigInteger result = aNumber.max(bNumber); + byte resBytes[] = new byte[rBytes.length]; + resBytes = result.toByteArray(); + for(int i = 0; i < resBytes.length; i++) { + assertTrue(resBytes[i] == rBytes[i]); + } + assertTrue("incorrect sign", result.signum() == 1); + } + + /** + * max(BigInteger val). + * numbers are equal. + */ + public void testMaxEqual() { + byte aBytes[] = {45, 91, 3, -15, 35, 26, 3, 91}; + byte bBytes[] = {45, 91, 3, -15, 35, 26, 3, 91}; + int aSign = 1; + int bSign = 1; + byte rBytes[] = {45, 91, 3, -15, 35, 26, 3, 91}; + BigInteger aNumber = new BigInteger(aSign, aBytes); + BigInteger bNumber = new BigInteger(bSign, bBytes); + BigInteger result = aNumber.max(bNumber); + byte resBytes[] = new byte[rBytes.length]; + resBytes = result.toByteArray(); + for(int i = 0; i < resBytes.length; i++) { + assertTrue(resBytes[i] == rBytes[i]); + } + assertEquals("incorrect sign", 1, result.signum()); + } + + /** + * max(BigInteger val). + * max of negative and ZERO. + */ + public void testMaxNegZero() { + byte aBytes[] = {45, 91, 3, -15, 35, 26, 3, 91}; + int aSign = -1; + byte rBytes[] = {0}; + BigInteger aNumber = new BigInteger(aSign, aBytes); + BigInteger bNumber = BigInteger.ZERO; + BigInteger result = aNumber.max(bNumber); + byte resBytes[] = new byte[rBytes.length]; + resBytes = result.toByteArray(); + for(int i = 0; i < resBytes.length; i++) { + assertTrue(resBytes[i] == rBytes[i]); + } + assertTrue("incorrect sign", result.signum() == 0); + } + + /** + * min(BigInteger val). + * the first is greater. + */ + public void testMinGreater() { + byte aBytes[] = {12, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26, 3, 91}; + byte bBytes[] = {45, 91, 3, -15, 35, 26, 3, 91}; + int aSign = 1; + int bSign = 1; + byte rBytes[] = {45, 91, 3, -15, 35, 26, 3, 91}; + BigInteger aNumber = new BigInteger(aSign, aBytes); + BigInteger bNumber = new BigInteger(bSign, bBytes); + BigInteger result = aNumber.min(bNumber); + byte resBytes[] = new byte[rBytes.length]; + resBytes = result.toByteArray(); + for(int i = 0; i < resBytes.length; i++) { + assertTrue(resBytes[i] == rBytes[i]); + } + assertEquals("incorrect sign", 1, result.signum()); + } + + /** + * min(BigInteger val). + * the first is less. + */ + public void testMinLess() { + byte aBytes[] = {45, 91, 3, -15, 35, 26, 3, 91}; + byte bBytes[] = {12, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26, 3, 91}; + int aSign = 1; + int bSign = 1; + byte rBytes[] = {45, 91, 3, -15, 35, 26, 3, 91}; + BigInteger aNumber = new BigInteger(aSign, aBytes); + BigInteger bNumber = new BigInteger(bSign, bBytes); + BigInteger result = aNumber.min(bNumber); + byte resBytes[] = new byte[rBytes.length]; + resBytes = result.toByteArray(); + for(int i = 0; i < resBytes.length; i++) { + assertTrue(resBytes[i] == rBytes[i]); + } + assertEquals("incorrect sign", 1, result.signum()); + } + + /** + * min(BigInteger val). + * numbers are equal. + */ + public void testMinEqual() { + byte aBytes[] = {45, 91, 3, -15, 35, 26, 3, 91}; + byte bBytes[] = {45, 91, 3, -15, 35, 26, 3, 91}; + int aSign = 1; + int bSign = 1; + byte rBytes[] = {45, 91, 3, -15, 35, 26, 3, 91}; + BigInteger aNumber = new BigInteger(aSign, aBytes); + BigInteger bNumber = new BigInteger(bSign, bBytes); + BigInteger result = aNumber.min(bNumber); + byte resBytes[] = new byte[rBytes.length]; + resBytes = result.toByteArray(); + for(int i = 0; i < resBytes.length; i++) { + assertTrue(resBytes[i] == rBytes[i]); + } + assertTrue("incorrect sign", result.signum() == 1); + } + + /** + * max(BigInteger val). + * min of positive and ZERO. + */ + public void testMinPosZero() { + byte aBytes[] = {45, 91, 3, -15, 35, 26, 3, 91}; + int aSign = 1; + byte rBytes[] = {0}; + BigInteger aNumber = new BigInteger(aSign, aBytes); + BigInteger bNumber = BigInteger.ZERO; + BigInteger result = aNumber.min(bNumber); + byte resBytes[] = new byte[rBytes.length]; + resBytes = result.toByteArray(); + for(int i = 0; i < resBytes.length; i++) { + assertTrue(resBytes[i] == rBytes[i]); + } + assertTrue("incorrect sign", result.signum() == 0); + } + + /** + * negate() a positive number. + */ + public void testNegatePositive() { + byte aBytes[] = {12, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26, 3, 91}; + int aSign = 1; + byte rBytes[] = {-13, -57, -101, 1, 75, -90, -46, -92, -4, 14, -36, -27, -4, -91}; + BigInteger aNumber = new BigInteger(aSign, aBytes); + BigInteger result = aNumber.negate(); + byte resBytes[] = new byte[rBytes.length]; + resBytes = result.toByteArray(); + for(int i = 0; i < resBytes.length; i++) { + assertTrue(resBytes[i] == rBytes[i]); + } + assertTrue("incorrect sign", result.signum() == -1); + } + + /** + * negate() a negative number. + */ + public void testNegateNegative() { + byte aBytes[] = {12, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26, 3, 91}; + int aSign = -1; + byte rBytes[] = {12, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26, 3, 91}; + BigInteger aNumber = new BigInteger(aSign, aBytes); + BigInteger result = aNumber.negate(); + byte resBytes[] = new byte[rBytes.length]; + resBytes = result.toByteArray(); + for(int i = 0; i < resBytes.length; i++) { + assertTrue(resBytes[i] == rBytes[i]); + } + assertTrue("incorrect sign", result.signum() == 1); + } + + /** + * negate() ZERO. + */ + public void testNegateZero() { + byte rBytes[] = {0}; + BigInteger aNumber = BigInteger.ZERO; + BigInteger result = aNumber.negate(); + byte resBytes[] = new byte[rBytes.length]; + resBytes = result.toByteArray(); + for(int i = 0; i < resBytes.length; i++) { + assertTrue(resBytes[i] == rBytes[i]); + } + assertEquals("incorrect sign", 0, result.signum()); + } + + /** + * signum() of a positive number. + */ + public void testSignumPositive() { + byte aBytes[] = {12, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26, 3, 91}; + int aSign = 1; + BigInteger aNumber = new BigInteger(aSign, aBytes); + assertEquals("incorrect sign", 1, aNumber.signum()); + } + + /** + * signum() of a negative number. + */ + public void testSignumNegative() { + byte aBytes[] = {12, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26, 3, 91}; + int aSign = -1; + BigInteger aNumber = new BigInteger(aSign, aBytes); + assertEquals("incorrect sign", -1, aNumber.signum()); + } + + /** + * signum() of ZERO. + */ + public void testSignumZero() { + BigInteger aNumber = BigInteger.ZERO; + assertEquals("incorrect sign", 0, aNumber.signum()); + } +} diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/math/BigIntegerConstructorsTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/math/BigIntegerConstructorsTest.java new file mode 100644 index 0000000..1e0e4a1 --- /dev/null +++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/math/BigIntegerConstructorsTest.java @@ -0,0 +1,786 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 Elena Semukhina + */ + +package org.apache.harmony.tests.java.math; + +import junit.framework.TestCase; +import java.math.BigInteger; +import java.util.Random; + +/** + * Class: java.math.BigInteger + * Constructors: BigInteger(byte[] a), BigInteger(int sign, byte[] a), + * BigInteger(String val, int radix) + */ +public class BigIntegerConstructorsTest extends TestCase { + /** + * Create a number from an array of bytes. + * Verify an exception thrown if an array is zero bytes long + */ + public void testConstructorBytesException() { + byte aBytes[] = {}; + try { + new BigInteger(aBytes); + fail("NumberFormatException has not been caught"); + } catch (NumberFormatException e) { + } + } + + /** + * Create a positive number from an array of bytes. + * The number fits in an array of integers. + */ + public void testConstructorBytesPositive1() { + byte aBytes[] = {12, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26, 3, 91}; + byte rBytes[] = {12, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26, 3, 91}; + BigInteger aNumber = new BigInteger(aBytes); + byte resBytes[] = new byte[rBytes.length]; + resBytes = aNumber.toByteArray(); + for(int i = 0; i < resBytes.length; i++) { + assertTrue(resBytes[i] == rBytes[i]); + } + assertEquals("incorrect sign", 1, aNumber.signum()); + } + + /** + * Create a positive number from an array of bytes. + * The number fits in an integer. + */ + public void testConstructorBytesPositive2() { + byte aBytes[] = {12, 56, 100}; + byte rBytes[] = {12, 56, 100}; + BigInteger aNumber = new BigInteger(aBytes); + byte resBytes[] = new byte[rBytes.length]; + resBytes = aNumber.toByteArray(); + for(int i = 0; i < resBytes.length; i++) { + assertTrue(resBytes[i] == rBytes[i]); + } + assertEquals("incorrect sign", 1, aNumber.signum()); + } + + /** + * Create a positive number from an array of bytes. + * The number of bytes is 4. + */ + public void testConstructorBytesPositive3() { + byte aBytes[] = {127, 56, 100, -1}; + byte rBytes[] = {127, 56, 100, -1}; + BigInteger aNumber = new BigInteger(aBytes); + byte resBytes[] = new byte[rBytes.length]; + resBytes = aNumber.toByteArray(); + for(int i = 0; i < resBytes.length; i++) { + assertTrue(resBytes[i] == rBytes[i]); + } + assertEquals("incorrect sign", 1, aNumber.signum()); + } + + /** + * Create a positive number from an array of bytes. + * The number of bytes is multiple of 4. + */ + public void testConstructorBytesPositive() { + byte aBytes[] = {127, 56, 100, -1, 14, 75, -24, -100}; + byte rBytes[] = {127, 56, 100, -1, 14, 75, -24, -100}; + BigInteger aNumber = new BigInteger(aBytes); + byte resBytes[] = new byte[rBytes.length]; + resBytes = aNumber.toByteArray(); + for(int i = 0; i < resBytes.length; i++) { + assertTrue(resBytes[i] == rBytes[i]); + } + assertEquals("incorrect sign", 1, aNumber.signum()); + } + + /** + * Create a negative number from an array of bytes. + * The number fits in an array of integers. + */ + public void testConstructorBytesNegative1() { + byte aBytes[] = {-12, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26, 3, 91}; + byte rBytes[] = {-12, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26, 3, 91}; + BigInteger aNumber = new BigInteger(aBytes); + byte resBytes[] = new byte[rBytes.length]; + resBytes = aNumber.toByteArray(); + for(int i = 0; i < resBytes.length; i++) { + assertTrue(resBytes[i] == rBytes[i]); + } + assertEquals("incorrect sign", -1, aNumber.signum()); + } + + /** + * Create a negative number from an array of bytes. + * The number fits in an integer. + */ + public void testConstructorBytesNegative2() { + byte aBytes[] = {-12, 56, 100}; + byte rBytes[] = {-12, 56, 100}; + BigInteger aNumber = new BigInteger(aBytes); + byte resBytes[] = new byte[rBytes.length]; + resBytes = aNumber.toByteArray(); + for(int i = 0; i < resBytes.length; i++) { + assertTrue(resBytes[i] == rBytes[i]); + } + assertEquals("incorrect sign", -1, aNumber.signum()); + } + + /** + * Create a negative number from an array of bytes. + * The number of bytes is 4. + */ + public void testConstructorBytesNegative3() { + byte aBytes[] = {-128, -12, 56, 100}; + byte rBytes[] = {-128, -12, 56, 100}; + BigInteger aNumber = new BigInteger(aBytes); + byte resBytes[] = new byte[rBytes.length]; + resBytes = aNumber.toByteArray(); + for(int i = 0; i < resBytes.length; i++) { + assertTrue(resBytes[i] == rBytes[i]); + } + assertEquals("incorrect sign", -1, aNumber.signum()); + } + + /** + * Create a negative number from an array of bytes. + * The number of bytes is multiple of 4. + */ + public void testConstructorBytesNegative4() { + byte aBytes[] = {-128, -12, 56, 100, -13, 56, 93, -78}; + byte rBytes[] = {-128, -12, 56, 100, -13, 56, 93, -78}; + BigInteger aNumber = new BigInteger(aBytes); + byte resBytes[] = new byte[rBytes.length]; + resBytes = aNumber.toByteArray(); + for(int i = 0; i < resBytes.length; i++) { + assertTrue(resBytes[i] == rBytes[i]); + } + assertEquals("incorrect sign", -1, aNumber.signum()); + } + + /** + * Create a zero number from an array of zero bytes. + */ + public void testConstructorBytesZero() { + byte aBytes[] = {0, 0, 0, -0, +0, 0, -0}; + byte rBytes[] = {0}; + BigInteger aNumber = new BigInteger(aBytes); + byte resBytes[] = new byte[rBytes.length]; + resBytes = aNumber.toByteArray(); + for(int i = 0; i < resBytes.length; i++) { + assertTrue(resBytes[i] == rBytes[i]); + } + assertEquals("incorrect sign", 0, aNumber.signum()); + } + + /** + * Create a number from a sign and an array of bytes. + * Verify an exception thrown if a sign has improper value. + */ + public void testConstructorSignBytesException1() { + byte aBytes[] = {123, 45, -3, -76}; + int aSign = 3; + try { + new BigInteger(aSign, aBytes); + fail("NumberFormatException has not been caught"); + } catch (NumberFormatException e) { + } + } + + /** + * Create a number from a sign and an array of bytes. + * Verify an exception thrown if the array contains non-zero bytes while the sign is 0. + */ + public void testConstructorSignBytesException2() { + byte aBytes[] = {123, 45, -3, -76}; + int aSign = 0; + try { + new BigInteger(aSign, aBytes); + fail("NumberFormatException has not been caught"); + } catch (NumberFormatException e) { + assertEquals("Improper exception message", "signum-magnitude mismatch", e.getMessage()); + } + } + + /** + * Create a positive number from a sign and an array of bytes. + * The number fits in an array of integers. + * The most significant byte is positive. + */ + public void testConstructorSignBytesPositive1() { + byte aBytes[] = {12, 56, 100, -2, -76, 89, 45, 91, 3, -15}; + int aSign = 1; + byte rBytes[] = {12, 56, 100, -2, -76, 89, 45, 91, 3, -15}; + BigInteger aNumber = new BigInteger(aSign, aBytes); + byte resBytes[] = new byte[rBytes.length]; + resBytes = aNumber.toByteArray(); + for(int i = 0; i < resBytes.length; i++) { + assertTrue(resBytes[i] == rBytes[i]); + } + assertEquals("incorrect sign", 1, aNumber.signum()); + } + + /** + * Create a positive number from a sign and an array of bytes. + * The number fits in an array of integers. + * The most significant byte is negative. + */ + public void testConstructorSignBytesPositive2() { + byte aBytes[] = {-12, 56, 100, -2, -76, 89, 45, 91, 3, -15}; + int aSign = 1; + byte rBytes[] = {0, -12, 56, 100, -2, -76, 89, 45, 91, 3, -15}; + BigInteger aNumber = new BigInteger(aSign, aBytes); + byte resBytes[] = new byte[rBytes.length]; + resBytes = aNumber.toByteArray(); + for(int i = 0; i < resBytes.length; i++) { + assertTrue(resBytes[i] == rBytes[i]); + } + assertEquals("incorrect sign", 1, aNumber.signum()); + } + + /** + * Create a positive number from a sign and an array of bytes. + * The number fits in an integer. + */ + public void testConstructorSignBytesPositive3() { + byte aBytes[] = {-12, 56, 100}; + int aSign = 1; + byte rBytes[] = {0, -12, 56, 100}; + BigInteger aNumber = new BigInteger(aSign, aBytes); + byte resBytes[] = new byte[rBytes.length]; + resBytes = aNumber.toByteArray(); + for(int i = 0; i < resBytes.length; i++) { + assertTrue(resBytes[i] == rBytes[i]); + } + assertEquals("incorrect sign", 1, aNumber.signum()); + } + + /** + * Create a positive number from a sign and an array of bytes. + * The number of bytes is 4. + * The most significant byte is positive. + */ + public void testConstructorSignBytesPositive4() { + byte aBytes[] = {127, 56, 100, -2}; + int aSign = 1; + byte rBytes[] = {127, 56, 100, -2}; + BigInteger aNumber = new BigInteger(aSign, aBytes); + byte resBytes[] = new byte[rBytes.length]; + resBytes = aNumber.toByteArray(); + for(int i = 0; i < resBytes.length; i++) { + assertTrue(resBytes[i] == rBytes[i]); + } + assertEquals("incorrect sign", 1, aNumber.signum()); + } + + /** + * Create a positive number from a sign and an array of bytes. + * The number of bytes is 4. + * The most significant byte is negative. + */ + public void testConstructorSignBytesPositive5() { + byte aBytes[] = {-127, 56, 100, -2}; + int aSign = 1; + byte rBytes[] = {0, -127, 56, 100, -2}; + BigInteger aNumber = new BigInteger(aSign, aBytes); + byte resBytes[] = new byte[rBytes.length]; + resBytes = aNumber.toByteArray(); + for(int i = 0; i < resBytes.length; i++) { + assertTrue(resBytes[i] == rBytes[i]); + } + assertEquals("incorrect sign", 1, aNumber.signum()); + } + + /** + * Create a positive number from a sign and an array of bytes. + * The number of bytes is multiple of 4. + * The most significant byte is positive. + */ + public void testConstructorSignBytesPositive6() { + byte aBytes[] = {12, 56, 100, -2, -76, 89, 45, 91, 3, -15, 23, -101}; + int aSign = 1; + byte rBytes[] = {12, 56, 100, -2, -76, 89, 45, 91, 3, -15, 23, -101}; + BigInteger aNumber = new BigInteger(aSign, aBytes); + byte resBytes[] = new byte[rBytes.length]; + resBytes = aNumber.toByteArray(); + for(int i = 0; i < resBytes.length; i++) { + assertTrue(resBytes[i] == rBytes[i]); + } + assertEquals("incorrect sign", 1, aNumber.signum()); + } + + /** + * Create a positive number from a sign and an array of bytes. + * The number of bytes is multiple of 4. + * The most significant byte is negative. + */ + public void testConstructorSignBytesPositive7() { + byte aBytes[] = {-12, 56, 100, -2, -76, 89, 45, 91, 3, -15, 23, -101}; + int aSign = 1; + byte rBytes[] = {0, -12, 56, 100, -2, -76, 89, 45, 91, 3, -15, 23, -101}; + BigInteger aNumber = new BigInteger(aSign, aBytes); + byte resBytes[] = new byte[rBytes.length]; + resBytes = aNumber.toByteArray(); + for(int i = 0; i < resBytes.length; i++) { + assertTrue(resBytes[i] == rBytes[i]); + } + assertEquals("incorrect sign", 1, aNumber.signum()); + } + + /** + * Create a negative number from a sign and an array of bytes. + * The number fits in an array of integers. + * The most significant byte is positive. + */ + public void testConstructorSignBytesNegative1() { + byte aBytes[] = {12, 56, 100, -2, -76, 89, 45, 91, 3, -15}; + int aSign = -1; + byte rBytes[] = {-13, -57, -101, 1, 75, -90, -46, -92, -4, 15}; + BigInteger aNumber = new BigInteger(aSign, aBytes); + byte resBytes[] = new byte[rBytes.length]; + resBytes = aNumber.toByteArray(); + for(int i = 0; i < resBytes.length; i++) { + assertTrue(resBytes[i] == rBytes[i]); + } + assertEquals("incorrect sign", -1, aNumber.signum()); + } + + /** + * Create a negative number from a sign and an array of bytes. + * The number fits in an array of integers. + * The most significant byte is negative. + */ + public void testConstructorSignBytesNegative2() { + byte aBytes[] = {-12, 56, 100, -2, -76, 89, 45, 91, 3, -15}; + int aSign = -1; + byte rBytes[] = {-1, 11, -57, -101, 1, 75, -90, -46, -92, -4, 15}; + BigInteger aNumber = new BigInteger(aSign, aBytes); + byte resBytes[] = new byte[rBytes.length]; + resBytes = aNumber.toByteArray(); + for(int i = 0; i < resBytes.length; i++) { + assertTrue(resBytes[i] == rBytes[i]); + } + assertEquals("incorrect sign", -1, aNumber.signum()); + } + + /** + * Create a negative number from a sign and an array of bytes. + * The number fits in an integer. + */ + public void testConstructorSignBytesNegative3() { + byte aBytes[] = {-12, 56, 100}; + int aSign = -1; + byte rBytes[] = {-1, 11, -57, -100}; + BigInteger aNumber = new BigInteger(aSign, aBytes); + byte resBytes[] = new byte[rBytes.length]; + resBytes = aNumber.toByteArray(); + for(int i = 0; i < resBytes.length; i++) { + assertTrue(resBytes[i] == rBytes[i]); + } + assertEquals("incorrect sign", -1, aNumber.signum()); + } + + /** + * Create a negative number from a sign and an array of bytes. + * The number of bytes is 4. + * The most significant byte is positive. + */ + public void testConstructorSignBytesNegative4() { + byte aBytes[] = {127, 56, 100, -2}; + int aSign = -1; + byte rBytes[] = {-128, -57, -101, 2}; + BigInteger aNumber = new BigInteger(aSign, aBytes); + byte resBytes[] = new byte[rBytes.length]; + resBytes = aNumber.toByteArray(); + for(int i = 0; i < resBytes.length; i++) { + assertTrue(resBytes[i] == rBytes[i]); + } + assertEquals("incorrect sign", -1, aNumber.signum()); + } + + /** + * Create a negative number from a sign and an array of bytes. + * The number of bytes is 4. + * The most significant byte is negative. + */ + public void testConstructorSignBytesNegative5() { + byte aBytes[] = {-127, 56, 100, -2}; + int aSign = -1; + byte rBytes[] = {-1, 126, -57, -101, 2}; + BigInteger aNumber = new BigInteger(aSign, aBytes); + byte resBytes[] = new byte[rBytes.length]; + resBytes = aNumber.toByteArray(); + for(int i = 0; i < resBytes.length; i++) { + assertTrue(resBytes[i] == rBytes[i]); + } + assertEquals("incorrect sign", -1, aNumber.signum()); + } + + /** + * Create a negative number from a sign and an array of bytes. + * The number of bytes is multiple of 4. + * The most significant byte is positive. + */ + public void testConstructorSignBytesNegative6() { + byte aBytes[] = {12, 56, 100, -2, -76, 89, 45, 91, 3, -15, 23, -101}; + int aSign = -1; + byte rBytes[] = {-13, -57, -101, 1, 75, -90, -46, -92, -4, 14, -24, 101}; + BigInteger aNumber = new BigInteger(aSign, aBytes); + byte resBytes[] = new byte[rBytes.length]; + resBytes = aNumber.toByteArray(); + for(int i = 0; i < resBytes.length; i++) { + assertTrue(resBytes[i] == rBytes[i]); + } + assertEquals("incorrect sign", -1, aNumber.signum()); + } + + /** + * Create a negative number from a sign and an array of bytes. + * The number of bytes is multiple of 4. + * The most significant byte is negative. + */ + public void testConstructorSignBytesNegative7() { + byte aBytes[] = {-12, 56, 100, -2, -76, 89, 45, 91, 3, -15, 23, -101}; + int aSign = -1; + byte rBytes[] = {-1, 11, -57, -101, 1, 75, -90, -46, -92, -4, 14, -24, 101}; + BigInteger aNumber = new BigInteger(aSign, aBytes); + byte resBytes[] = new byte[rBytes.length]; + resBytes = aNumber.toByteArray(); + for(int i = 0; i < resBytes.length; i++) { + assertTrue(resBytes[i] == rBytes[i]); + } + assertEquals("incorrect sign", -1, aNumber.signum()); + } + + /** + * Create a zero number from a sign and an array of zero bytes. + * The sign is -1. + */ + public void testConstructorSignBytesZero1() { + byte aBytes[] = {-0, 0, +0, 0, 0, 00, 000}; + int aSign = -1; + byte rBytes[] = {0}; + BigInteger aNumber = new BigInteger(aSign, aBytes); + byte resBytes[] = new byte[rBytes.length]; + resBytes = aNumber.toByteArray(); + for(int i = 0; i < resBytes.length; i++) { + assertTrue(resBytes[i] == rBytes[i]); + } + assertEquals("incorrect sign", 0, aNumber.signum()); + } + + /** + * Create a zero number from a sign and an array of zero bytes. + * The sign is 0. + */ + public void testConstructorSignBytesZero2() { + byte aBytes[] = {-0, 0, +0, 0, 0, 00, 000}; + int aSign = 0; + byte rBytes[] = {0}; + BigInteger aNumber = new BigInteger(aSign, aBytes); + byte resBytes[] = new byte[rBytes.length]; + resBytes = aNumber.toByteArray(); + for(int i = 0; i < resBytes.length; i++) { + assertTrue(resBytes[i] == rBytes[i]); + } + assertEquals("incorrect sign", 0, aNumber.signum()); + } + + /** + * Create a zero number from a sign and an array of zero bytes. + * The sign is 1. + */ + public void testConstructorSignBytesZero3() { + byte aBytes[] = {-0, 0, +0, 0, 0, 00, 000}; + int aSign = 1; + byte rBytes[] = {0}; + BigInteger aNumber = new BigInteger(aSign, aBytes); + byte resBytes[] = new byte[rBytes.length]; + resBytes = aNumber.toByteArray(); + for(int i = 0; i < resBytes.length; i++) { + assertTrue(resBytes[i] == rBytes[i]); + } + assertEquals("incorrect sign", 0, aNumber.signum()); + } + + /** + * Create a zero number from a sign and an array of zero length. + * The sign is -1. + */ + public void testConstructorSignBytesZeroNull1() { + byte aBytes[] = {}; + int aSign = -1; + byte rBytes[] = {0}; + BigInteger aNumber = new BigInteger(aSign, aBytes); + byte resBytes[] = new byte[rBytes.length]; + resBytes = aNumber.toByteArray(); + for(int i = 0; i < resBytes.length; i++) { + assertTrue(resBytes[i] == rBytes[i]); + } + assertEquals("incorrect sign", 0, aNumber.signum()); + } + + /** + * Create a zero number from a sign and an array of zero length. + * The sign is 0. + */ + public void testConstructorSignBytesZeroNull2() { + byte aBytes[] = {}; + int aSign = 0; + byte rBytes[] = {0}; + BigInteger aNumber = new BigInteger(aSign, aBytes); + byte resBytes[] = new byte[rBytes.length]; + resBytes = aNumber.toByteArray(); + for(int i = 0; i < resBytes.length; i++) { + assertTrue(resBytes[i] == rBytes[i]); + } + assertEquals("incorrect sign", 0, aNumber.signum()); + } + + /** + * Create a zero number from a sign and an array of zero length. + * The sign is 1. + */ + public void testConstructorSignBytesZeroNull3() { + byte aBytes[] = {}; + int aSign = 1; + byte rBytes[] = {0}; + BigInteger aNumber = new BigInteger(aSign, aBytes); + byte resBytes[] = new byte[rBytes.length]; + resBytes = aNumber.toByteArray(); + for(int i = 0; i < resBytes.length; i++) { + assertTrue(resBytes[i] == rBytes[i]); + } + assertEquals("incorrect sign", 0, aNumber.signum()); + } + + /** + * Create a number from a string value and radix. + * Verify an exception thrown if a radix is out of range + */ + public void testConstructorStringException1() { + String value = "9234853876401"; + int radix = 45; + try { + new BigInteger(value, radix); + fail("NumberFormatException has not been caught"); + } catch (NumberFormatException e) { + } + } + + /** + * Create a number from a string value and radix. + * Verify an exception thrown if the string starts with a space. + */ + public void testConstructorStringException2() { + String value = " 9234853876401"; + int radix = 10; + try { + new BigInteger(value, radix); + fail("NumberFormatException has not been caught"); + } catch (NumberFormatException e) { + } + } + + /** + * Create a number from a string value and radix. + * Verify an exception thrown if the string contains improper characters. + */ + public void testConstructorStringException3() { + String value = "92348$*#78987"; + int radix = 34; + try { + new BigInteger(value, radix); + fail("NumberFormatException has not been caught"); + } catch (NumberFormatException e) { + } + } + + /** + * Create a number from a string value and radix. + * Verify an exception thrown if some digits are greater than radix. + */ + public void testConstructorStringException4() { + String value = "98zv765hdsaiy"; + int radix = 20; + try { + new BigInteger(value, radix); + fail("NumberFormatException has not been caught"); + } catch (NumberFormatException e) { + } + } + + /** + * Create a positive number from a string value and radix 2. + */ + public void testConstructorStringRadix2() { + String value = "10101010101010101"; + int radix = 2; + byte rBytes[] = {1, 85, 85}; + BigInteger aNumber = new BigInteger(value, radix); + byte resBytes[] = new byte[rBytes.length]; + resBytes = aNumber.toByteArray(); + for(int i = 0; i < resBytes.length; i++) { + assertTrue(resBytes[i] == rBytes[i]); + } + assertEquals("incorrect sign", 1, aNumber.signum()); + } + + /** + * Create a positive number from a string value and radix 8. + */ + public void testConstructorStringRadix8() { + String value = "76356237071623450"; + int radix = 8; + byte rBytes[] = {7, -50, -28, -8, -25, 39, 40}; + BigInteger aNumber = new BigInteger(value, radix); + byte resBytes[] = new byte[rBytes.length]; + resBytes = aNumber.toByteArray(); + for(int i = 0; i < resBytes.length; i++) { + assertTrue(resBytes[i] == rBytes[i]); + } + assertEquals("incorrect sign", 1, aNumber.signum()); + } + + /** + * Create a positive number from a string value and radix 10. + */ + public void testConstructorStringRadix10() { + String value = "987328901348934898"; + int radix = 10; + byte rBytes[] = {13, -77, -78, 103, -103, 97, 68, -14}; + BigInteger aNumber = new BigInteger(value, radix); + byte resBytes[] = new byte[rBytes.length]; + resBytes = aNumber.toByteArray(); + for(int i = 0; i < resBytes.length; i++) { + assertTrue(resBytes[i] == rBytes[i]); + } + assertEquals("incorrect sign", 1, aNumber.signum()); + } + + /** + * Create a positive number from a string value and radix 16. + */ + public void testConstructorStringRadix16() { + String value = "fe2340a8b5ce790"; + int radix = 16; + byte rBytes[] = {15, -30, 52, 10, -117, 92, -25, -112}; + BigInteger aNumber = new BigInteger(value, radix); + byte resBytes[] = new byte[rBytes.length]; + resBytes = aNumber.toByteArray(); + for(int i = 0; i < resBytes.length; i++) { + assertTrue(resBytes[i] == rBytes[i]); + } + assertEquals("incorrect sign", 1, aNumber.signum()); + } + + /** + * Create a positive number from a string value and radix 36. + */ + public void testConstructorStringRadix36() { + String value = "skdjgocvhdjfkl20jndjkf347ejg457"; + int radix = 36; + byte rBytes[] = {0, -12, -116, 112, -105, 12, -36, 66, 108, 66, -20, -37, -15, 108, -7, 52, -99, -109, -8, -45, -5}; + BigInteger aNumber = new BigInteger(value, radix); + byte resBytes[] = new byte[rBytes.length]; + resBytes = aNumber.toByteArray(); + for(int i = 0; i < resBytes.length; i++) { + assertTrue(resBytes[i] == rBytes[i]); + } + assertEquals("incorrect sign", 1, aNumber.signum()); + } + + /** + * Create a negative number from a string value and radix 10. + */ + public void testConstructorStringRadix10Negative() { + String value = "-234871376037"; + int radix = 36; + byte rBytes[] = {-4, 48, 71, 62, -76, 93, -105, 13}; + BigInteger aNumber = new BigInteger(value, radix); + byte resBytes[] = new byte[rBytes.length]; + resBytes = aNumber.toByteArray(); + for(int i = 0; i < resBytes.length; i++) { + assertTrue(resBytes[i] == rBytes[i]); + } + assertEquals("incorrect sign", -1, aNumber.signum()); + } + + /** + * Create a zero number from a string value and radix 36. + */ + public void testConstructorStringRadix10Zero() { + String value = "-00000000000000"; + int radix = 10; + byte rBytes[] = {0}; + BigInteger aNumber = new BigInteger(value, radix); + byte resBytes[] = new byte[rBytes.length]; + resBytes = aNumber.toByteArray(); + for(int i = 0; i < resBytes.length; i++) { + assertTrue(resBytes[i] == rBytes[i]); + } + assertEquals("incorrect sign", 0, aNumber.signum()); + } + + /** + * Create a random number of 75 bits length. + */ + public void testConstructorRandom() { + int bitLen = 75; + Random rnd = new Random(); + BigInteger aNumber = new BigInteger(bitLen, rnd); + assertTrue("incorrect bitLength", aNumber.bitLength() <= bitLen); + } + + public void testConstructorPrime() { + for (int rep = 0; rep < 2048; ++rep) { + Random rnd = new Random(); + BigInteger b; + int bits; + + // Create a 128-bit prime number. + bits = 128; + b = new BigInteger(bits, 10, rnd); + assertEquals(b.toString(), bits, b.bitLength()); + + // Create a prime number of 25 bits length. + bits = 25; + b = new BigInteger(bits, 10, rnd); + assertEquals(b.toString(), bits, b.bitLength()); + + // Create a prime number of 18 bits length. + bits = 18; + b = new BigInteger(bits, 10, rnd); + assertEquals(b.toString(), bits, b.bitLength()); + + // On Android, anything less than 16 bits used to be at least 16 bits + // because that's how OpenSSL behaves, but we recently fixed this... + bits = 2; + b = new BigInteger(bits, 10, rnd); + assertEquals(b.toString(), bits, b.bitLength()); + + // The 2-arg constructor has never used OpenSSL. + bits = 2; + b = new BigInteger(bits, rnd); + assertTrue(b.toString(), b.bitLength() <= bits); + assertTrue(b.toString(), b.intValue() <= 3); + + bits = 16; + b = new BigInteger(bits, rnd); + assertTrue(b.toString(), b.bitLength() <= bits); + } + } +} diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/math/BigIntegerConvertTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/math/BigIntegerConvertTest.java new file mode 100644 index 0000000..d72923d --- /dev/null +++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/math/BigIntegerConvertTest.java @@ -0,0 +1,792 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 Elena Semukhina + */ + +package org.apache.harmony.tests.java.math; + +import junit.framework.TestCase; +import java.math.BigInteger; + +/** + * Class: java.math.BigInteger + * Methods: intValue, longValue, toByteArray(), valueOf(long val), + * floatValue(), doubleValue() + */ +public class BigIntegerConvertTest extends TestCase { + /** + * Return the double value of ZERO. + */ + public void testDoubleValueZero() { + String a = "0"; + double result = 0.0; + double aNumber = new BigInteger(a).doubleValue(); + assertTrue(aNumber == result); + } + + /** + * Convert a positive number to a double value. + * The number's length is less than 64 bits. + */ + public void testDoubleValuePositive1() { + String a = "27467238945"; + double result = 2.7467238945E10; + double aNumber = new BigInteger(a).doubleValue(); + assertTrue(aNumber == result); + } + + /** + * Convert a positive number to a double value. + * The number's bit length is inside [63, 1024]. + */ + public void testDoubleValuePositive2() { + String a = "2746723894572364578265426346273456972"; + double result = 2.7467238945723645E36; + double aNumber = new BigInteger(a).doubleValue(); + assertTrue(aNumber == result); + } + + /** + * Convert a negative number to a double value. + * The number's bit length is less than 64 bits. + */ + public void testDoubleValueNegative1() { + String a = "-27467238945"; + double result = -2.7467238945E10; + double aNumber = new BigInteger(a).doubleValue(); + assertTrue(aNumber == result); + } + + /** + * Convert a negative number to a double value. + * The number's bit length is inside [63, 1024]. + */ + public void testDoubleValueNegative2() { + String a = "-2746723894572364578265426346273456972"; + double result = -2.7467238945723645E36; + double aNumber = new BigInteger(a).doubleValue(); + assertTrue(aNumber == result); + } + + /** + * Convert a positive number to a double value. + * Rounding is needed. + * The rounding bit is 1 and the next bit to the left is 1. + */ + public void testDoubleValuePosRounded1() { + byte[] a = {-128, 1, 2, 3, 4, 5, 60, 23, 1, -3, -5}; + int aSign = 1; + double result = 1.54747264387948E26; + double aNumber = new BigInteger(aSign, a).doubleValue(); + assertTrue(aNumber == result); + } + + /** + * Convert a positive number to a double value. + * Rounding is needed. + * The rounding bit is 1 and the next bit to the left is 0 + * but some of dropped bits are 1s. + */ + public void testDoubleValuePosRounded2() { + byte[] a = {-128, 1, 2, 3, 4, 5, 36, 23, 1, -3, -5}; + int aSign = 1; + double result = 1.547472643879479E26; + double aNumber = new BigInteger(aSign, a).doubleValue(); + assertTrue(aNumber == result); + } + /** + * Convert a positive number to a double value. + * Rounding is NOT needed. + */ + public void testDoubleValuePosNotRounded() { + byte[] a = {-128, 1, 2, 3, 4, 5, -128, 23, 1, -3, -5}; + int aSign = 1; + double result = 1.5474726438794828E26; + double aNumber = new BigInteger(aSign, a).doubleValue(); + assertTrue(aNumber == result); + } + + /** + * Convert a positive number to a double value. + * Rounding is needed. + */ + public void testDoubleValueNegRounded1() { + byte[] a = {-128, 1, 2, 3, 4, 5, 60, 23, 1, -3, -5}; + int aSign = -1; + double result = -1.54747264387948E26; + double aNumber = new BigInteger(aSign, a).doubleValue(); + assertTrue(aNumber == result); + } + + /** + * Convert a positive number to a double value. + * Rounding is needed. + * The rounding bit is 1 and the next bit to the left is 0 + * but some of dropped bits are 1s. + */ + public void testDoubleValueNegRounded2() { + byte[] a = {-128, 1, 2, 3, 4, 5, 36, 23, 1, -3, -5}; + int aSign = -1; + double result = -1.547472643879479E26; + double aNumber = new BigInteger(aSign, a).doubleValue(); + assertTrue(aNumber == result); + } + + /** + * Convert a positive number to a double value. + * Rounding is NOT needed. + */ + public void testDoubleValueNegNotRounded() { + byte[] a = {-128, 1, 2, 3, 4, 5, -128, 23, 1, -3, -5}; + int aSign = -1; + double result = -1.5474726438794828E26; + double aNumber = new BigInteger(aSign, a).doubleValue(); + assertTrue(aNumber == result); + } + + /** + * Convert a positive number to a double value. + * The exponent is 1023 and the mantissa is all 1s. + * The rounding bit is 0. + * The result is Double.MAX_VALUE. + */ + public void testDoubleValuePosMaxValue() { + byte[] a = {0, -1, -1, -1, -1, -1, -1, -8, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 + }; + int aSign = 1; + double aNumber = new BigInteger(aSign, a).doubleValue(); + assertTrue(aNumber == Double.MAX_VALUE); + } + + /** + * Convert a negative number to a double value. + * The exponent is 1023 and the mantissa is all 1s. + * The result is -Double.MAX_VALUE. + */ + public void testDoubleValueNegMaxValue() { + byte[] a = {0, -1, -1, -1, -1, -1, -1, -8, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 + }; + int aSign = -1; + double aNumber = new BigInteger(aSign, a).doubleValue(); + assertTrue(aNumber == -Double.MAX_VALUE); + } + + /** + * Convert a positive number to a double value. + * The exponent is 1023 and the mantissa is all 1s. + * The rounding bit is 1. + * The result is Double.POSITIVE_INFINITY. + */ + public void testDoubleValuePositiveInfinity1() { + byte[] a = {-1, -1, -1, -1, -1, -1, -1, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 + }; + int aSign = 1; + double aNumber = new BigInteger(aSign, a).doubleValue(); + assertTrue(aNumber == Double.POSITIVE_INFINITY); + } + + /** + * Convert a positive number to a double value. + * The number's bit length is greater than 1024. + */ + public void testDoubleValuePositiveInfinity2() { + String a = "2746723894572364578265426346273456972283746872364768676747462342342342342342342342323423423423423423426767456345745293762384756238475634563456845634568934568347586346578648576478568456457634875673845678456786587345873645767456834756745763457863485768475678465783456702897830296720476846578634576384567845678346573465786457863"; + double aNumber = new BigInteger(a).doubleValue(); + assertTrue(aNumber == Double.POSITIVE_INFINITY); + } + + /** + * Convert a negative number to a double value. + * The number's bit length is greater than 1024. + */ + public void testDoubleValueNegativeInfinity1() { + String a = "-2746723894572364578265426346273456972283746872364768676747462342342342342342342342323423423423423423426767456345745293762384756238475634563456845634568934568347586346578648576478568456457634875673845678456786587345873645767456834756745763457863485768475678465783456702897830296720476846578634576384567845678346573465786457863"; + double aNumber = new BigInteger(a).doubleValue(); + assertTrue(aNumber == Double.NEGATIVE_INFINITY); + } + + /** + * Convert a negative number to a double value. + * The exponent is 1023 and the mantissa is all 0s. + * The rounding bit is 0. + * The result is Double.NEGATIVE_INFINITY. + */ + public void testDoubleValueNegativeInfinity2() { + byte[] a = {-1, -1, -1, -1, -1, -1, -1, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 + }; + int aSign = -1; + double aNumber = new BigInteger(aSign, a).doubleValue(); + assertTrue(aNumber == Double.NEGATIVE_INFINITY); + } + + /** + * Convert a positive number to a double value. + * The exponent is 1023 and the mantissa is all 0s + * but the 54th bit (implicit) is 1. + */ + public void testDoubleValuePosMantissaIsZero() { + byte[] a = {-128, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 + }; + int aSign = 1; + double result = 8.98846567431158E307; + double aNumber = new BigInteger(aSign, a).doubleValue(); + assertTrue(aNumber == result); + } + + /** + * Convert a positive number to a double value. + * The exponent is 1023 and the mantissa is all 0s + * but the 54th bit (implicit) is 1. + */ + public void testDoubleValueNegMantissaIsZero() { + byte[] a = {-128, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 + }; + int aSign = -1; + double aNumber = new BigInteger(aSign, a).doubleValue(); + assertTrue(aNumber == -8.98846567431158E307); + } + + /** + * Return the float value of ZERO. + */ + public void testFloatValueZero() { + String a = "0"; + float result = 0.0f; + float aNumber = new BigInteger(a).floatValue(); + assertTrue(aNumber == result); + } + + /** + * Convert a positive number to a float value. + * The number's length is less than 32 bits. + */ + public void testFloatValuePositive1() { + String a = "27467238"; + float result = 2.7467238E7f; + float aNumber = new BigInteger(a).floatValue(); + assertTrue(aNumber == result); + } + + /** + * Convert a positive number to a float value. + * The number's bit length is inside [32, 127]. + */ + public void testFloatValuePositive2() { + String a = "27467238945723645782"; + float result = 2.7467239E19f; + float aNumber = new BigInteger(a).floatValue(); + assertTrue(aNumber == result); + } + + /** + * Convert a negative number to a float value. + * The number's bit length is less than 32 bits. + */ + public void testFloatValueNegative1() { + String a = "-27467238"; + float result = -2.7467238E7f; + float aNumber = new BigInteger(a).floatValue(); + assertTrue(aNumber == result); + } + + /** + * Convert a negative number to a doufloatble value. + * The number's bit length is inside [63, 1024]. + */ + public void testFloatValueNegative2() { + String a = "-27467238945723645782"; + float result = -2.7467239E19f; + float aNumber = new BigInteger(a).floatValue(); + assertTrue(aNumber == result); + } + + /** + * Convert a positive number to a float value. + * Rounding is needed. + * The rounding bit is 1 and the next bit to the left is 1. + */ + public void testFloatValuePosRounded1() { + byte[] a = {-128, 1, -1, -4, 4, 5, 60, 23, 1, -3, -5}; + int aSign = 1; + float result = 1.5475195E26f; + float aNumber = new BigInteger(aSign, a).floatValue(); + assertTrue(aNumber == result); + } + + /** + * Convert a positive number to a float value. + * Rounding is needed. + * The rounding bit is 1 and the next bit to the left is 0 + * but some of dropped bits are 1s. + */ + public void testFloatValuePosRounded2() { + byte[] a = {-128, 1, 2, -128, 4, 5, 60, 23, 1, -3, -5}; + int aSign = 1; + float result = 1.5474728E26f; + float aNumber = new BigInteger(aSign, a).floatValue(); + assertTrue(aNumber == result); + } + /** + * Convert a positive number to a float value. + * Rounding is NOT needed. + */ + public void testFloatValuePosNotRounded() { + byte[] a = {-128, 1, 2, 3, 4, 5, 60, 23, 1, -3, -5}; + int aSign = 1; + float result = 1.5474726E26f; + float aNumber = new BigInteger(aSign, a).floatValue(); + assertTrue(aNumber == result); + } + + /** + * Convert a positive number to a float value. + * Rounding is needed. + */ + public void testFloatValueNegRounded1() { + byte[] a = {-128, 1, -1, -4, 4, 5, 60, 23, 1, -3, -5}; + int aSign = -1; + float result = -1.5475195E26f; + float aNumber = new BigInteger(aSign, a).floatValue(); + assertTrue(aNumber == result); + } + + /** + * Convert a positive number to a float value. + * Rounding is needed. + * The rounding bit is 1 and the next bit to the left is 0 + * but some of dropped bits are 1s. + */ + public void testFloatValueNegRounded2() { + byte[] a = {-128, 1, 2, -128, 4, 5, 60, 23, 1, -3, -5}; + int aSign = -1; + float result = -1.5474728E26f; + float aNumber = new BigInteger(aSign, a).floatValue(); + assertTrue(aNumber == result); + } + + /** + * Convert a positive number to a float value. + * Rounding is NOT needed. + */ + public void testFloatValueNegNotRounded() { + byte[] a = {-128, 1, 2, 3, 4, 5, 60, 23, 1, -3, -5}; + int aSign = -1; + float result = -1.5474726E26f; + float aNumber = new BigInteger(aSign, a).floatValue(); + assertTrue(aNumber == result); + } + + /** + * Convert a positive number to a float value. + * The exponent is 1023 and the mantissa is all 1s. + * The rounding bit is 0. + * The result is Float.MAX_VALUE. + */ + public void testFloatValuePosMaxValue() { + byte[] a = {0, -1, -1, -1, 0, -1, -1, -8, -1, -1, -1, -1, -1, -1, -1, -1, -1}; + int aSign = 1; + float aNumber = new BigInteger(aSign, a).floatValue(); + assertTrue(aNumber == Float.MAX_VALUE); + } + + /** + * Convert a negative number to a float value. + * The exponent is 1023 and the mantissa is all 1s. + * The rounding bit is 0. + * The result is -Float.MAX_VALUE. + */ + public void testFloatValueNegMaxValue() { + byte[] a = {0, -1, -1, -1, 0, -1, -1, -8, -1, -1, -1, -1, -1, -1, -1, -1, -1}; + int aSign = -1; + float aNumber = new BigInteger(aSign, a).floatValue(); + assertTrue(aNumber == -Float.MAX_VALUE); + } + + /** + * Convert a positive number to a float value. + * The exponent is 1023 and the mantissa is all 1s. + * The rounding bit is 1. + * The result is Float.POSITIVE_INFINITY. + */ + public void testFloatValuePositiveInfinity1() { + byte[] a = {0, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}; + int aSign = 1; + float aNumber = new BigInteger(aSign, a).floatValue(); + assertTrue(aNumber == Float.POSITIVE_INFINITY); + } + + /** + * Convert a positive number to a float value. + * The number's bit length is greater than 127. + */ + public void testFloatValuePositiveInfinity2() { + String a = "2746723894572364578265426346273456972283746872364768676747462342342342342342342342323423423423423423426767456345745293762384756238475634563456845634568934568347586346578648576478568456457634875673845678456786587345873645767456834756745763457863485768475678465783456702897830296720476846578634576384567845678346573465786457863"; + float aNumber = new BigInteger(a).floatValue(); + assertTrue(aNumber == Float.POSITIVE_INFINITY); + } + + /** + * Convert a negative number to a float value. + * The number's bit length is greater than 127. + */ + public void testFloatValueNegativeInfinity1() { + String a = "-2746723894572364578265426346273456972283746872364768676747462342342342342342342342323423423423423423426767456345745293762384756238475634563456845634568934568347586346578648576478568456457634875673845678456786587345873645767456834756745763457863485768475678465783456702897830296720476846578634576384567845678346573465786457863"; + float aNumber = new BigInteger(a).floatValue(); + assertTrue(aNumber == Float.NEGATIVE_INFINITY); + } + + /** + * Convert a negative number to a float value. + * The exponent is 1023 and the mantissa is all 0s. + * The rounding bit is 0. + * The result is Float.NEGATIVE_INFINITY. + */ + public void testFloatValueNegativeInfinity2() { + byte[] a = {0, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}; + int aSign = -1; + float aNumber = new BigInteger(aSign, a).floatValue(); + assertTrue(aNumber == Float.NEGATIVE_INFINITY); + } + + /** + * Convert a positive number to a float value. + * The exponent is 1023 and the mantissa is all 0s + * but the 54th bit (implicit) is 1. + */ + public void testFloatValuePosMantissaIsZero() { + byte[] a = {-128, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; + int aSign = 1; + float result = 1.7014118E38f; + float aNumber = new BigInteger(aSign, a).floatValue(); + assertTrue(aNumber == result); + } + + /** + * Convert a positive number to a double value. + * The exponent is 1023 and the mantissa is all 0s + * but the 54th bit (implicit) is 1. + */ + public void testFloatValueNegMantissaIsZero() { + byte[] a = {1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; + int aSign = -1; + float aNumber = new BigInteger(aSign, a).floatValue(); + assertTrue(aNumber == Float.NEGATIVE_INFINITY); + } + + /** + * Convert a negative number to a float value. + * The number's bit length is less than 32 bits. + */ + public void testFloatValueBug2482() { + String a = "2147483649"; + float result = 2.14748365E9f; + float aNumber = new BigInteger(a).floatValue(); + assertTrue(aNumber == result); + } + + /** + * Convert a positive BigInteger to an integer value. + * The low digit is positive + */ + public void testIntValuePositive1() { + byte aBytes[] = {12, 56, 100, -2, -76, 89, 45, 91, 3}; + int resInt = 1496144643; + int aNumber = new BigInteger(aBytes).intValue(); + assertTrue(aNumber == resInt); + } + + /** + * Convert a positive BigInteger to an integer value. + * The low digit is positive + */ + public void testIntValuePositive2() { + byte aBytes[] = {12, 56, 100}; + int resInt = 800868; + int aNumber = new BigInteger(aBytes).intValue(); + assertTrue(aNumber == resInt); + } + + /** + * Convert a positive BigInteger to an integer value. + * The low digit is negative. + */ + public void testIntValuePositive3() { + byte aBytes[] = {56, 13, 78, -12, -5, 56, 100}; + int sign = 1; + int resInt = -184862620; + int aNumber = new BigInteger(sign, aBytes).intValue(); + assertTrue(aNumber == resInt); + } + + /** + * Convert a negative BigInteger to an integer value. + * The low digit is negative. + */ + public void testIntValueNegative1() { + byte aBytes[] = {12, 56, 100, -2, -76, -128, 45, 91, 3}; + int sign = -1; + int resInt = 2144511229; + int aNumber = new BigInteger(sign, aBytes).intValue(); + assertTrue(aNumber == resInt); + } + + /** + * Convert a negative BigInteger to an integer value. + * The low digit is negative. + */ + public void testIntValueNegative2() { + byte aBytes[] = {-12, 56, 100}; + int result = -771996; + int aNumber = new BigInteger(aBytes).intValue(); + assertTrue(aNumber == result); + } + + /** + * Convert a negative BigInteger to an integer value. + * The low digit is positive. + */ + public void testIntValueNegative3() { + byte aBytes[] = {12, 56, 100, -2, -76, 127, 45, 91, 3}; + int sign = -1; + int resInt = -2133678851; + int aNumber = new BigInteger(sign, aBytes).intValue(); + assertTrue(aNumber == resInt); + } + + /** + * Convert a BigInteger to a positive long value + * The BigInteger is longer than int. + */ + public void testLongValuePositive1() { + byte aBytes[] = {12, 56, 100, -2, -76, 89, 45, 91, 3, 120, -34, -12, 45, 98}; + long result = 3268209772258930018L; + long aNumber = new BigInteger(aBytes).longValue(); + assertTrue(aNumber == result); + } + + /** + * Convert a number to a positive long value + * The number fits in a long. + */ + public void testLongValuePositive2() { + byte aBytes[] = {12, 56, 100, 18, -105, 34, -18, 45}; + long result = 880563758158769709L; + long aNumber = new BigInteger(aBytes).longValue(); + assertTrue(aNumber == result); + } + + /** + * Convert a number to a negative long value + * The BigInteger is longer than int. + */ + public void testLongValueNegative1() { + byte aBytes[] = {12, -1, 100, -2, -76, -128, 45, 91, 3}; + long result = -43630045168837885L; + long aNumber = new BigInteger(aBytes).longValue(); + assertTrue(aNumber == result); + } + + /** + * Convert a number to a negative long value + * The number fits in a long. + */ + public void testLongValueNegative2() { + byte aBytes[] = {-12, 56, 100, 45, -101, 45, 98}; + long result = -3315696807498398L; + long aNumber = new BigInteger(aBytes).longValue(); + assertTrue(aNumber == result); + } + + /** + * valueOf (long val): convert Integer.MAX_VALUE to a BigInteger. + */ + public void testValueOfIntegerMax() { + long longVal = Integer.MAX_VALUE; + BigInteger aNumber = BigInteger.valueOf(longVal); + byte rBytes[] = {127, -1, -1, -1}; + byte resBytes[] = new byte[rBytes.length]; + resBytes = aNumber.toByteArray(); + for(int i = 0; i < resBytes.length; i++) { + assertTrue(resBytes[i] == rBytes[i]); + } + assertEquals("incorrect sign", 1, aNumber.signum()); + } + + /** + * valueOf (long val): convert Integer.MIN_VALUE to a BigInteger. + */ + public void testValueOfIntegerMin() { + long longVal = Integer.MIN_VALUE; + BigInteger aNumber = BigInteger.valueOf(longVal); + byte rBytes[] = {-128, 0, 0, 0}; + byte resBytes[] = new byte[rBytes.length]; + resBytes = aNumber.toByteArray(); + for(int i = 0; i < resBytes.length; i++) { + assertTrue(resBytes[i] == rBytes[i]); + } + assertEquals("incorrect sign", -1, aNumber.signum()); + } + + /** + * valueOf (long val): convert Long.MAX_VALUE to a BigInteger. + */ + public void testValueOfLongMax() { + long longVal = Long.MAX_VALUE; + BigInteger aNumber = BigInteger.valueOf(longVal); + byte rBytes[] = {127, -1, -1, -1, -1, -1, -1, -1}; + byte resBytes[] = new byte[rBytes.length]; + resBytes = aNumber.toByteArray(); + for(int i = 0; i < resBytes.length; i++) { + assertTrue(resBytes[i] == rBytes[i]); + } + assertEquals("incorrect sign", 1, aNumber.signum()); + } + + /** + * valueOf (long val): convert Long.MIN_VALUE to a BigInteger. + */ + public void testValueOfLongMin() { + long longVal = Long.MIN_VALUE; + BigInteger aNumber = BigInteger.valueOf(longVal); + byte rBytes[] = {-128, 0, 0, 0, 0, 0, 0, 0}; + byte resBytes[] = new byte[rBytes.length]; + resBytes = aNumber.toByteArray(); + for(int i = 0; i < resBytes.length; i++) { + assertTrue(resBytes[i] == rBytes[i]); + } + assertEquals("incorrect sign", -1, aNumber.signum()); + } + + /** + * valueOf (long val): convert a positive long value to a BigInteger. + */ + public void testValueOfLongPositive1() { + long longVal = 268209772258930018L; + BigInteger aNumber = BigInteger.valueOf(longVal); + byte rBytes[] = {3, -72, -33, 93, -24, -56, 45, 98}; + byte resBytes[] = new byte[rBytes.length]; + resBytes = aNumber.toByteArray(); + for(int i = 0; i < resBytes.length; i++) { + assertTrue(resBytes[i] == rBytes[i]); + } + assertEquals("incorrect sign", 1, aNumber.signum()); + } + + /** + * valueOf (long val): convert a positive long value to a BigInteger. + * The long value fits in integer. + */ + public void testValueOfLongPositive2() { + long longVal = 58930018L; + BigInteger aNumber = BigInteger.valueOf(longVal); + byte rBytes[] = {3, -125, 51, 98}; + byte resBytes[] = new byte[rBytes.length]; + resBytes = aNumber.toByteArray(); + for(int i = 0; i < resBytes.length; i++) { + assertTrue(resBytes[i] == rBytes[i]); + } + assertEquals("incorrect sign", 1, aNumber.signum()); + } + + /** + * valueOf (long val): convert a negative long value to a BigInteger. + */ + public void testValueOfLongNegative1() { + long longVal = -268209772258930018L; + BigInteger aNumber = BigInteger.valueOf(longVal); + byte rBytes[] = {-4, 71, 32, -94, 23, 55, -46, -98}; + byte resBytes[] = new byte[rBytes.length]; + resBytes = aNumber.toByteArray(); + for(int i = 0; i < resBytes.length; i++) { + assertTrue(resBytes[i] == rBytes[i]); + } + assertEquals("incorrect sign", -1, aNumber.signum()); + } + + /** + * valueOf (long val): convert a negative long value to a BigInteger. + * The long value fits in integer. + */ + public void testValueOfLongNegative2() { + long longVal = -58930018L; + BigInteger aNumber = BigInteger.valueOf(longVal); + byte rBytes[] = {-4, 124, -52, -98}; + byte resBytes[] = new byte[rBytes.length]; + resBytes = aNumber.toByteArray(); + for(int i = 0; i < resBytes.length; i++) { + assertTrue(resBytes[i] == rBytes[i]); + } + assertEquals("incorrect sign", -1, aNumber.signum()); + } + /** + * valueOf (long val): convert a zero long value to a BigInteger. + */ + public void testValueOfLongZero() { + long longVal = 0L; + BigInteger aNumber = BigInteger.valueOf(longVal); + byte rBytes[] = {0}; + byte resBytes[] = new byte[rBytes.length]; + resBytes = aNumber.toByteArray(); + for(int i = 0; i < resBytes.length; i++) { + assertTrue(resBytes[i] == rBytes[i]); + } + assertEquals("incorrect sign", 0, aNumber.signum()); + } +} diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/math/BigIntegerDivideTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/math/BigIntegerDivideTest.java new file mode 100644 index 0000000..3f2ab51 --- /dev/null +++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/math/BigIntegerDivideTest.java @@ -0,0 +1,666 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 Elena Semukhina + */ + +package org.apache.harmony.tests.java.math; + +import junit.framework.TestCase; +import java.math.BigInteger; + +/** + * Class: java.math.BigInteger + * Methods: divide, remainder, mod, and divideAndRemainder + */ +public class BigIntegerDivideTest extends TestCase { + /** + * Divide by zero + */ + public void testCase1() { + byte aBytes[] = {1, 2, 3, 4, 5, 6, 7}; + byte bBytes[] = {0}; + int aSign = 1; + int bSign = 0; + BigInteger aNumber = new BigInteger(aSign, aBytes); + BigInteger bNumber = new BigInteger(bSign, bBytes); + try { + aNumber.divide(bNumber); + fail("ArithmeticException has not been caught"); + } catch (ArithmeticException e) { + } + } + + /** + * Divide by ZERO + */ + public void testCase2() { + byte aBytes[] = {1, 2, 3, 4, 5, 6, 7}; + int aSign = 1; + BigInteger aNumber = new BigInteger(aSign, aBytes); + BigInteger bNumber = BigInteger.ZERO; + try { + aNumber.divide(bNumber); + fail("ArithmeticException has not been caught"); + } catch (ArithmeticException e) { + } + } + + /** + * Divide two equal positive numbers + */ + public void testCase3() { + byte aBytes[] = {-127, 100, 56, 7, 98, -1, 39, -128, 127}; + byte bBytes[] = {-127, 100, 56, 7, 98, -1, 39, -128, 127}; + int aSign = 1; + int bSign = 1; + byte rBytes[] = {1}; + BigInteger aNumber = new BigInteger(aSign, aBytes); + BigInteger bNumber = new BigInteger(bSign, bBytes); + BigInteger result = aNumber.divide(bNumber); + byte resBytes[] = new byte[rBytes.length]; + resBytes = result.toByteArray(); + for(int i = 0; i < resBytes.length; i++) { + assertTrue(resBytes[i] == rBytes[i]); + } + assertEquals("incorrect sign", 1, result.signum()); + } + + /** + * Divide two equal in absolute value numbers of different signs. + */ + public void testCase4() { + byte aBytes[] = {-127, 100, 56, 7, 98, -1, 39, -128, 127}; + byte bBytes[] = {-127, 100, 56, 7, 98, -1, 39, -128, 127}; + int aSign = -1; + int bSign = 1; + byte rBytes[] = {-1}; + BigInteger aNumber = new BigInteger(aSign, aBytes); + BigInteger bNumber = new BigInteger(bSign, bBytes); + BigInteger result = aNumber.divide(bNumber); + byte resBytes[] = new byte[rBytes.length]; + resBytes = result.toByteArray(); + for(int i = 0; i < resBytes.length; i++) { + assertTrue(resBytes[i] == rBytes[i]); + } + assertEquals("incorrect sign", -1, result.signum()); + } + + /** + * Divide two numbers of different length and different signs. + * The second is longer. + */ + public void testCase5() { + byte aBytes[] = {-127, 100, 56, 7, 98, -1, 39, -128, 127}; + byte bBytes[] = {-127, 100, 56, 7, 98, -1, 39, -128, 127, 1, 2, 3, 4, 5}; + int aSign = -1; + int bSign = 1; + byte rBytes[] = {0}; + BigInteger aNumber = new BigInteger(aSign, aBytes); + BigInteger bNumber = new BigInteger(bSign, bBytes); + BigInteger result = aNumber.divide(bNumber); + byte resBytes[] = new byte[rBytes.length]; + resBytes = result.toByteArray(); + for(int i = 0; i < resBytes.length; i++) { + assertTrue(resBytes[i] == rBytes[i]); + } + assertEquals("incorrect sign", 0, result.signum()); + } + + /** + * Divide two positive numbers of the same length. + * The second is greater. + */ + public void testCase6() { + byte aBytes[] = {1, 100, 56, 7, 98, -1, 39, -128, 127}; + byte bBytes[] = {15, 100, 56, 7, 98, -1, 39, -128, 127}; + int aSign = 1; + int bSign = 1; + byte rBytes[] = {0}; + BigInteger aNumber = new BigInteger(aSign, aBytes); + BigInteger bNumber = new BigInteger(bSign, bBytes); + BigInteger result = aNumber.divide(bNumber); + byte resBytes[] = new byte[rBytes.length]; + resBytes = result.toByteArray(); + for(int i = 0; i < resBytes.length; i++) { + assertTrue(resBytes[i] == rBytes[i]); + } + assertEquals("incorrect sign", 0, result.signum()); + } + + /** + * Divide two positive numbers. + */ + public void testCase7() { + byte aBytes[] = {1, 100, 56, 7, 98, -1, 39, -128, 127, 5, 6, 7, 8, 9}; + byte bBytes[] = {15, 48, -29, 7, 98, -1, 39, -128}; + int aSign = 1; + int bSign = 1; + byte rBytes[] = {23, 115, 11, 78, 35, -11}; + BigInteger aNumber = new BigInteger(aSign, aBytes); + BigInteger bNumber = new BigInteger(bSign, bBytes); + BigInteger result = aNumber.divide(bNumber); + byte resBytes[] = new byte[rBytes.length]; + resBytes = result.toByteArray(); + for(int i = 0; i < resBytes.length; i++) { + assertTrue(resBytes[i] == rBytes[i]); + } + assertEquals("incorrect sign", 1, result.signum()); + } + + /** + * Divide a positive number by a negative one. + */ + public void testCase8() { + byte aBytes[] = {1, 100, 56, 7, 98, -1, 39, -128, 127, 5, 6, 7, 8, 9}; + byte bBytes[] = {15, 48, -29, 7, 98, -1, 39, -128}; + int aSign = 1; + int bSign = -1; + byte rBytes[] = {-24, -116, -12, -79, -36, 11}; + BigInteger aNumber = new BigInteger(aSign, aBytes); + BigInteger bNumber = new BigInteger(bSign, bBytes); + BigInteger result = aNumber.divide(bNumber); + byte resBytes[] = new byte[rBytes.length]; + resBytes = result.toByteArray(); + for(int i = 0; i < resBytes.length; i++) { + assertTrue(resBytes[i] == rBytes[i]); + } + assertEquals("incorrect sign", -1, result.signum()); + } + + /** + * Divide a negative number by a positive one. + */ + public void testCase9() { + byte aBytes[] = {1, 100, 56, 7, 98, -1, 39, -128, 127, 5, 6, 7, 8, 9}; + byte bBytes[] = {15, 48, -29, 7, 98, -1, 39, -128}; + int aSign = -1; + int bSign = 1; + byte rBytes[] = {-24, -116, -12, -79, -36, 11}; + BigInteger aNumber = new BigInteger(aSign, aBytes); + BigInteger bNumber = new BigInteger(bSign, bBytes); + BigInteger result = aNumber.divide(bNumber); + byte resBytes[] = new byte[rBytes.length]; + resBytes = result.toByteArray(); + for(int i = 0; i < resBytes.length; i++) { + assertTrue(resBytes[i] == rBytes[i]); + } + assertEquals("incorrect sign", -1, result.signum()); + } + + /** + * Divide two negative numbers. + */ + public void testCase10() { + byte aBytes[] = {1, 100, 56, 7, 98, -1, 39, -128, 127, 5, 6, 7, 8, 9}; + byte bBytes[] = {15, 48, -29, 7, 98, -1, 39, -128}; + int aSign = -1; + int bSign = -1; + byte rBytes[] = {23, 115, 11, 78, 35, -11}; + BigInteger aNumber = new BigInteger(aSign, aBytes); + BigInteger bNumber = new BigInteger(bSign, bBytes); + BigInteger result = aNumber.divide(bNumber); + byte resBytes[] = new byte[rBytes.length]; + resBytes = result.toByteArray(); + for(int i = 0; i < resBytes.length; i++) { + assertTrue(resBytes[i] == rBytes[i]); + } + assertEquals("incorrect sign", 1, result.signum()); + } + + /** + * Divide zero by a negative number. + */ + public void testCase11() { + byte aBytes[] = {0}; + byte bBytes[] = {15, 48, -29, 7, 98, -1, 39, -128}; + int aSign = 0; + int bSign = -1; + byte rBytes[] = {0}; + BigInteger aNumber = new BigInteger(aSign, aBytes); + BigInteger bNumber = new BigInteger(bSign, bBytes); + BigInteger result = aNumber.divide(bNumber); + byte resBytes[] = new byte[rBytes.length]; + resBytes = result.toByteArray(); + for(int i = 0; i < resBytes.length; i++) { + assertTrue(resBytes[i] == rBytes[i]); + } + assertEquals("incorrect sign", 0, result.signum()); + } + + /** + * Divide ZERO by a negative number. + */ + public void testCase12() { + byte bBytes[] = {15, 48, -29, 7, 98, -1, 39, -128}; + int bSign = -1; + byte rBytes[] = {0}; + BigInteger aNumber = BigInteger.ZERO; + BigInteger bNumber = new BigInteger(bSign, bBytes); + BigInteger result = aNumber.divide(bNumber); + byte resBytes[] = new byte[rBytes.length]; + resBytes = result.toByteArray(); + for(int i = 0; i < resBytes.length; i++) { + assertTrue(resBytes[i] == rBytes[i]); + } + assertEquals("incorrect sign", 0, result.signum()); + } + + /** + * Divide a positive number by ONE. + */ + public void testCase13() { + byte aBytes[] = {15, 48, -29, 7, 98, -1, 39, -128}; + int aSign = 1; + byte rBytes[] = {15, 48, -29, 7, 98, -1, 39, -128}; + BigInteger aNumber = new BigInteger(aSign, aBytes); + BigInteger bNumber = BigInteger.ONE; + BigInteger result = aNumber.divide(bNumber); + byte resBytes[] = new byte[rBytes.length]; + resBytes = result.toByteArray(); + for(int i = 0; i < resBytes.length; i++) { + assertTrue(resBytes[i] == rBytes[i]); + } + assertEquals("incorrect sign", 1, result.signum()); + } + + /** + * Divide ONE by ONE. + */ + public void testCase14() { + byte rBytes[] = {1}; + BigInteger aNumber = BigInteger.ONE; + BigInteger bNumber = BigInteger.ONE; + BigInteger result = aNumber.divide(bNumber); + byte resBytes[] = new byte[rBytes.length]; + resBytes = result.toByteArray(); + for(int i = 0; i < resBytes.length; i++) { + assertTrue(resBytes[i] == rBytes[i]); + } + assertEquals("incorrect sign", 1, result.signum()); + } + + /** + * Verifies the case when borrow != 0 in the private divide method. + */ + public void testDivisionKnuth1() { + byte aBytes[] = {-7, -6, -5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7}; + byte bBytes[] = {-3, -3, -3, -3}; + int aSign = 1; + int bSign = 1; + byte rBytes[] = {0, -5, -12, -33, -96, -36, -105, -56, 92, 15, 48, -109}; + BigInteger aNumber = new BigInteger(aSign, aBytes); + BigInteger bNumber = new BigInteger(bSign, bBytes); + BigInteger result = aNumber.divide(bNumber); + byte resBytes[] = new byte[rBytes.length]; + resBytes = result.toByteArray(); + for(int i = 0; i < resBytes.length; i++) { + assertTrue(resBytes[i] == rBytes[i]); + } + assertEquals("incorrect sign", 1, result.signum()); + } + + /** + * Verifies the case when the divisor is already normalized. + */ + public void testDivisionKnuthIsNormalized() { + byte aBytes[] = {-9, -8, -7, -6, -5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5}; + byte bBytes[] = {-1, -1, -1, -1, -1, -1, -1, -1}; + int aSign = -1; + int bSign = -1; + byte rBytes[] = {0, -9, -8, -7, -6, -5, -4, -3}; + BigInteger aNumber = new BigInteger(aSign, aBytes); + BigInteger bNumber = new BigInteger(bSign, bBytes); + BigInteger result = aNumber.divide(bNumber); + byte resBytes[] = new byte[rBytes.length]; + resBytes = result.toByteArray(); + for(int i = 0; i < resBytes.length; i++) { + assertTrue(resBytes[i] == rBytes[i]); + } + assertEquals("incorrect sign", 1, result.signum()); + } + + /** + * Verifies the case when the first digits of the dividend + * and divisor equal. + */ + public void testDivisionKnuthFirstDigitsEqual() { + byte aBytes[] = {2, -3, -4, -5, -1, -5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5}; + byte bBytes[] = {2, -3, -4, -5, -1, -1, -1, -1}; + int aSign = -1; + int bSign = -1; + byte rBytes[] = {0, -1, -1, -1, -1, -2, -88, -60, 41}; + BigInteger aNumber = new BigInteger(aSign, aBytes); + BigInteger bNumber = new BigInteger(bSign, bBytes); + BigInteger result = aNumber.divide(bNumber); + byte resBytes[] = new byte[rBytes.length]; + resBytes = result.toByteArray(); + for(int i = 0; i < resBytes.length; i++) { + assertTrue(resBytes[i] == rBytes[i]); + } + assertEquals("incorrect sign", 1, result.signum()); + } + + /** + * Divide the number of one digit by the number of one digit + */ + public void testDivisionKnuthOneDigitByOneDigit() { + byte aBytes[] = {113, -83, 123, -5}; + byte bBytes[] = {2, -3, -4, -5}; + int aSign = 1; + int bSign = -1; + byte rBytes[] = {-37}; + BigInteger aNumber = new BigInteger(aSign, aBytes); + BigInteger bNumber = new BigInteger(bSign, bBytes); + BigInteger result = aNumber.divide(bNumber); + byte resBytes[] = new byte[rBytes.length]; + resBytes = result.toByteArray(); + for(int i = 0; i < resBytes.length; i++) { + assertTrue(resBytes[i] == rBytes[i]); + } + assertEquals("incorrect sign", -1, result.signum()); + } + + /** + * Divide the number of multi digits by the number of one digit + */ + public void testDivisionKnuthMultiDigitsByOneDigit() { + byte aBytes[] = {113, -83, 123, -5, 18, -34, 67, 39, -29}; + byte bBytes[] = {2, -3, -4, -5}; + int aSign = 1; + int bSign = -1; + byte rBytes[] = {-38, 2, 7, 30, 109, -43}; + BigInteger aNumber = new BigInteger(aSign, aBytes); + BigInteger bNumber = new BigInteger(bSign, bBytes); + BigInteger result = aNumber.divide(bNumber); + byte resBytes[] = new byte[rBytes.length]; + resBytes = result.toByteArray(); + for(int i = 0; i < resBytes.length; i++) { + assertTrue(resBytes[i] == rBytes[i]); + } + assertEquals("incorrect sign", -1, result.signum()); + } + + /** + * Remainder of division by zero + */ + public void testCase15() { + byte aBytes[] = {1, 2, 3, 4, 5, 6, 7}; + byte bBytes[] = {0}; + int aSign = 1; + int bSign = 0; + BigInteger aNumber = new BigInteger(aSign, aBytes); + BigInteger bNumber = new BigInteger(bSign, bBytes); + try { + aNumber.remainder(bNumber); + fail("ArithmeticException has not been caught"); + } catch (ArithmeticException e) { + } + } + + /** + * Remainder of division of equal numbers + */ + public void testCase16() { + byte aBytes[] = {-127, 100, 56, 7, 98, -1, 39, -128, 127}; + byte bBytes[] = {-127, 100, 56, 7, 98, -1, 39, -128, 127}; + int aSign = 1; + int bSign = 1; + byte rBytes[] = {0}; + BigInteger aNumber = new BigInteger(aSign, aBytes); + BigInteger bNumber = new BigInteger(bSign, bBytes); + BigInteger result = aNumber.remainder(bNumber); + byte resBytes[] = new byte[rBytes.length]; + resBytes = result.toByteArray(); + for(int i = 0; i < resBytes.length; i++) { + assertTrue(resBytes[i] == rBytes[i]); + } + assertEquals("incorrect sign", 0, result.signum()); + } + + /** + * Remainder of division of two positive numbers + */ + public void testCase17() { + byte aBytes[] = {-127, 100, 56, 7, 98, -1, 39, -128, 127, 75}; + byte bBytes[] = {27, -15, 65, 39, 100}; + int aSign = 1; + int bSign = 1; + byte rBytes[] = {12, -21, 73, 56, 27}; + BigInteger aNumber = new BigInteger(aSign, aBytes); + BigInteger bNumber = new BigInteger(bSign, bBytes); + BigInteger result = aNumber.remainder(bNumber); + byte resBytes[] = new byte[rBytes.length]; + resBytes = result.toByteArray(); + for(int i = 0; i < resBytes.length; i++) { + assertTrue(resBytes[i] == rBytes[i]); + } + assertEquals("incorrect sign", 1, result.signum()); + } + + /** + * Remainder of division of two negative numbers + */ + public void testCase18() { + byte aBytes[] = {-127, 100, 56, 7, 98, -1, 39, -128, 127, 75}; + byte bBytes[] = {27, -15, 65, 39, 100}; + int aSign = -1; + int bSign = -1; + byte rBytes[] = {-13, 20, -74, -57, -27}; + BigInteger aNumber = new BigInteger(aSign, aBytes); + BigInteger bNumber = new BigInteger(bSign, bBytes); + BigInteger result = aNumber.remainder(bNumber); + byte resBytes[] = new byte[rBytes.length]; + resBytes = result.toByteArray(); + for(int i = 0; i < resBytes.length; i++) { + assertTrue(resBytes[i] == rBytes[i]); + } + assertEquals("incorrect sign", -1, result.signum()); + } + + /** + * Remainder of division of two numbers of different signs. + * The first is positive. + */ + public void testCase19() { + byte aBytes[] = {-127, 100, 56, 7, 98, -1, 39, -128, 127, 75}; + byte bBytes[] = {27, -15, 65, 39, 100}; + int aSign = 1; + int bSign = -1; + byte rBytes[] = {12, -21, 73, 56, 27}; + BigInteger aNumber = new BigInteger(aSign, aBytes); + BigInteger bNumber = new BigInteger(bSign, bBytes); + BigInteger result = aNumber.remainder(bNumber); + byte resBytes[] = new byte[rBytes.length]; + resBytes = result.toByteArray(); + for(int i = 0; i < resBytes.length; i++) { + assertTrue(resBytes[i] == rBytes[i]); + } + assertEquals("incorrect sign", 1, result.signum()); + } + + /** + * Remainder of division of two numbers of different signs. + * The first is negative. + */ + public void testCase20() { + byte aBytes[] = {-127, 100, 56, 7, 98, -1, 39, -128, 127, 75}; + byte bBytes[] = {27, -15, 65, 39, 100}; + int aSign = -1; + int bSign = 1; + byte rBytes[] = {-13, 20, -74, -57, -27}; + BigInteger aNumber = new BigInteger(aSign, aBytes); + BigInteger bNumber = new BigInteger(bSign, bBytes); + BigInteger result = aNumber.remainder(bNumber); + byte resBytes[] = new byte[rBytes.length]; + resBytes = result.toByteArray(); + for(int i = 0; i < resBytes.length; i++) { + assertTrue(resBytes[i] == rBytes[i]); + } + assertEquals("incorrect sign", -1, result.signum()); + } + + /** + * Tests the step D6 from the Knuth algorithm + */ + public void testRemainderKnuth1() { + byte aBytes[] = {-9, -8, -7, -6, -5, -4, -3, -2, -1, 0, 1}; + byte bBytes[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; + int aSign = 1; + int bSign = 1; + byte rBytes[] = {1, 2, 3, 4, 5, 6, 7, 7, 18, -89}; + BigInteger aNumber = new BigInteger(aSign, aBytes); + BigInteger bNumber = new BigInteger(bSign, bBytes); + BigInteger result = aNumber.remainder(bNumber); + byte resBytes[] = new byte[rBytes.length]; + resBytes = result.toByteArray(); + for(int i = 0; i < resBytes.length; i++) { + assertTrue(resBytes[i] == rBytes[i]); + } + assertEquals("incorrect sign", 1, result.signum()); + } + + /** + * Divide the number of one digit by the number of one digit + */ + public void testRemainderKnuthOneDigitByOneDigit() { + byte aBytes[] = {113, -83, 123, -5}; + byte bBytes[] = {2, -3, -4, -50}; + int aSign = 1; + int bSign = -1; + byte rBytes[] = {2, -9, -14, 53}; + BigInteger aNumber = new BigInteger(aSign, aBytes); + BigInteger bNumber = new BigInteger(bSign, bBytes); + BigInteger result = aNumber.remainder(bNumber); + byte resBytes[] = new byte[rBytes.length]; + resBytes = result.toByteArray(); + for(int i = 0; i < resBytes.length; i++) { + assertTrue(resBytes[i] == rBytes[i]); + } + assertEquals("incorrect sign", 1, result.signum()); + } + + /** + * Divide the number of multi digits by the number of one digit + */ + public void testRemainderKnuthMultiDigitsByOneDigit() { + byte aBytes[] = {113, -83, 123, -5, 18, -34, 67, 39, -29}; + byte bBytes[] = {2, -3, -4, -50}; + int aSign = 1; + int bSign = -1; + byte rBytes[] = {2, -37, -60, 59}; + BigInteger aNumber = new BigInteger(aSign, aBytes); + BigInteger bNumber = new BigInteger(bSign, bBytes); + BigInteger result = aNumber.remainder(bNumber); + byte resBytes[] = new byte[rBytes.length]; + resBytes = result.toByteArray(); + for(int i = 0; i < resBytes.length; i++) { + assertTrue(resBytes[i] == rBytes[i]); + } + assertEquals("incorrect sign", 1, result.signum()); + } + + /** + * divideAndRemainder of two numbers of different signs. + * The first is negative. + */ + public void testCase21() { + byte aBytes[] = {-127, 100, 56, 7, 98, -1, 39, -128, 127, 75}; + byte bBytes[] = {27, -15, 65, 39, 100}; + int aSign = -1; + int bSign = 1; + byte rBytes[][] = { + {-5, 94, -115, -74, -85, 84}, + {-13, 20, -74, -57, -27} + }; + BigInteger aNumber = new BigInteger(aSign, aBytes); + BigInteger bNumber = new BigInteger(bSign, bBytes); + BigInteger result[] = aNumber.divideAndRemainder(bNumber); + byte resBytes[] = new byte[rBytes.length]; + resBytes = result[0].toByteArray(); + for(int i = 0; i < resBytes.length; i++) { + if (resBytes[i] != rBytes[0][i]) { + fail("Incorrect quotation"); + } + } + assertEquals(-1, result[0].signum()); + resBytes = result[1].toByteArray(); + for(int i = 0; i < resBytes.length; i++) { + if (resBytes[i] != rBytes[1][i]) { + fail("Incorrect remainder"); + } + assertEquals(-1, result[1].signum()); + } + } + + /** + * mod when modulus is negative + */ + public void testCase22() { + byte aBytes[] = {1, 2, 3, 4, 5, 6, 7}; + byte bBytes[] = {1, 30, 40, 56, -1, 45}; + int aSign = 1; + int bSign = -1; + BigInteger aNumber = new BigInteger(aSign, aBytes); + BigInteger bNumber = new BigInteger(bSign, bBytes); + try { + aNumber.mod(bNumber); + fail("ArithmeticException has not been caught"); + } catch (ArithmeticException e) { + } + } + + /** + * mod when a divisor is positive + */ + public void testCase23() { + byte aBytes[] = {-127, 100, 56, 7, 98, -1, 39, -128, 127, 75}; + byte bBytes[] = {27, -15, 65, 39, 100}; + int aSign = 1; + int bSign = 1; + byte rBytes[] = {12, -21, 73, 56, 27}; + BigInteger aNumber = new BigInteger(aSign, aBytes); + BigInteger bNumber = new BigInteger(bSign, bBytes); + BigInteger result = aNumber.mod(bNumber); + byte resBytes[] = new byte[rBytes.length]; + resBytes = result.toByteArray(); + for(int i = 0; i < resBytes.length; i++) { + assertTrue(resBytes[i] == rBytes[i]); + } + assertEquals("incorrect sign", 1, result.signum()); + } + + /** + * mod when a divisor is negative + */ + public void testCase24() { + byte aBytes[] = {-127, 100, 56, 7, 98, -1, 39, -128, 127, 75}; + byte bBytes[] = {27, -15, 65, 39, 100}; + int aSign = -1; + int bSign = 1; + byte rBytes[] = {15, 5, -9, -17, 73}; + BigInteger aNumber = new BigInteger(aSign, aBytes); + BigInteger bNumber = new BigInteger(bSign, bBytes); + BigInteger result = aNumber.mod(bNumber); + byte resBytes[] = new byte[rBytes.length]; + resBytes = result.toByteArray(); + for(int i = 0; i < resBytes.length; i++) { + assertTrue(resBytes[i] == rBytes[i]); + } + assertEquals("incorrect sign", 1, result.signum()); + } +} diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/math/BigIntegerHashCodeTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/math/BigIntegerHashCodeTest.java new file mode 100644 index 0000000..52bf56f --- /dev/null +++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/math/BigIntegerHashCodeTest.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 Elena Semukhina + */ + +package org.apache.harmony.tests.java.math; + +import java.math.BigInteger; + +import junit.framework.TestCase; + +/** + * Class: java.math.BigInteger + * Method: hashCode() + */ +public class BigIntegerHashCodeTest extends TestCase { + /** + * Test hash codes for the same object + */ + public void testSameObject() { + String value1 = "12378246728727834290276457386374882976782849"; + String value2 = "-5634562095872038262928728727834290276457386374882976782849"; + BigInteger aNumber1 = new BigInteger(value1); + BigInteger aNumber2 = new BigInteger(value2); + int code1 = aNumber1.hashCode(); + aNumber1.add(aNumber2).shiftLeft(125); + aNumber1.subtract(aNumber2).shiftRight(125); + aNumber1.multiply(aNumber2).toByteArray(); + aNumber1.divide(aNumber2).bitLength(); + aNumber1.gcd(aNumber2).pow(7); + int code2 = aNumber1.hashCode(); + assertTrue("hash codes for the same object differ", code1 == code2); + } + + /** + * Test hash codes for equal objects. + */ + public void testEqualObjects() { + String value1 = "12378246728727834290276457386374882976782849"; + String value2 = "12378246728727834290276457386374882976782849"; + BigInteger aNumber1 = new BigInteger(value1); + BigInteger aNumber2 = new BigInteger(value2); + int code1 = aNumber1.hashCode(); + int code2 = aNumber2.hashCode(); + if (aNumber1.equals(aNumber2)) { + assertTrue("hash codes for equal objects are unequal", code1 == code2); + } + } + + /** + * Test hash codes for unequal objects. + * The codes are unequal. + */ + public void testUnequalObjectsUnequal() { + String value1 = "12378246728727834290276457386374882976782849"; + String value2 = "-5634562095872038262928728727834290276457386374882976782849"; + BigInteger aNumber1 = new BigInteger(value1); + BigInteger aNumber2 = new BigInteger(value2); + int code1 = aNumber1.hashCode(); + int code2 = aNumber2.hashCode(); + if (!aNumber1.equals(aNumber2)) { + assertTrue("hash codes for unequal objects are equal", code1 != code2); + } + } +} diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/math/BigIntegerModPowTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/math/BigIntegerModPowTest.java new file mode 100644 index 0000000..4af4d9d --- /dev/null +++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/math/BigIntegerModPowTest.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. + */ +/** + * @author Elena Semukhina + */ + +package org.apache.harmony.tests.java.math; + +import junit.framework.TestCase; +import java.math.BigInteger; + +/** + * Class: java.math.BigInteger + * Methods: modPow, modInverse, and gcd + */ +public class BigIntegerModPowTest extends TestCase { + /** + * modPow: non-positive modulus + */ + public void testModPowException() { + byte aBytes[] = {1, 2, 3, 4, 5, 6, 7}; + byte eBytes[] = {1, 2, 3, 4, 5}; + byte mBytes[] = {1, 2, 3}; + int aSign = 1; + int eSign = 1; + int mSign = -1; + BigInteger aNumber = new BigInteger(aSign, aBytes); + BigInteger exp = new BigInteger(eSign, eBytes); + BigInteger modulus = new BigInteger(mSign, mBytes); + try { + aNumber.modPow(exp, modulus); + fail("ArithmeticException has not been caught"); + } catch (ArithmeticException e) { + } + + try { + BigInteger.ZERO.modPow(new BigInteger("-1"), new BigInteger("10")); + fail("ArithmeticException has not been caught"); + } catch (ArithmeticException e) { + // expected + } + } + + /** + * modPow: positive exponent + */ + public void testModPowPosExp() { + byte aBytes[] = {-127, 100, 56, 7, 98, -1, 39, -128, 127, 75, 48, -7}; + byte eBytes[] = {27, -15, 65, 39}; + byte mBytes[] = {-128, 2, 3, 4, 5}; + int aSign = 1; + int eSign = 1; + int mSign = 1; + byte rBytes[] = {113, 100, -84, -28, -85}; + BigInteger aNumber = new BigInteger(aSign, aBytes); + BigInteger exp = new BigInteger(eSign, eBytes); + BigInteger modulus = new BigInteger(mSign, mBytes); + BigInteger result = aNumber.modPow(exp, modulus); + byte resBytes[] = new byte[rBytes.length]; + resBytes = result.toByteArray(); + for(int i = 0; i < resBytes.length; i++) { + assertTrue(resBytes[i] == rBytes[i]); + } + assertEquals("incorrect sign", 1, result.signum()); + } + + /** + * modPow: negative exponent + */ + public void testModPowNegExp() { + byte aBytes[] = {-127, 100, 56, 7, 98, -1, 39, -128, 127, 75, 48, -7}; + byte eBytes[] = {27, -15, 65, 39}; + byte mBytes[] = {-128, 2, 3, 4, 5}; + int aSign = 1; + int eSign = -1; + int mSign = 1; + byte rBytes[] = {12, 118, 46, 86, 92}; + BigInteger aNumber = new BigInteger(aSign, aBytes); + BigInteger exp = new BigInteger(eSign, eBytes); + BigInteger modulus = new BigInteger(mSign, mBytes); + BigInteger result = aNumber.modPow(exp, modulus); + byte resBytes[] = new byte[rBytes.length]; + resBytes = result.toByteArray(); + for(int i = 0; i < resBytes.length; i++) { + assertTrue(resBytes[i] == rBytes[i]); + } + assertEquals("incorrect sign", 1, result.signum()); + } + + public void testModPowZeroExp() { + BigInteger exp = new BigInteger("0"); + BigInteger[] base = new BigInteger[] {new BigInteger("-1"), new BigInteger("0"), new BigInteger("1")}; + BigInteger[] mod = new BigInteger[] {new BigInteger("2"), new BigInteger("10"), new BigInteger("2147483648")}; + + for (int i = 0; i < base.length; ++i) { + for (int j = 0; j < mod.length; ++j) { + assertEquals(base[i] + " modePow(" + exp + ", " + mod[j] + + ") should be " + BigInteger.ONE, BigInteger.ONE, + base[i].modPow(exp, mod[j])); + } + } + + mod = new BigInteger[] {new BigInteger("1")}; + for (int i = 0; i < base.length; ++i) { + for (int j = 0; j < mod.length; ++j) { + assertEquals(base[i] + " modePow(" + exp + ", " + mod[j] + + ") should be " + BigInteger.ZERO, BigInteger.ZERO, + base[i].modPow(exp, mod[j])); + } + } + } + + /** + * modInverse: non-positive modulus + */ + public void testmodInverseException() { + byte aBytes[] = {1, 2, 3, 4, 5, 6, 7}; + byte mBytes[] = {1, 2, 3}; + int aSign = 1; + int mSign = -1; + BigInteger aNumber = new BigInteger(aSign, aBytes); + BigInteger modulus = new BigInteger(mSign, mBytes); + try { + aNumber.modInverse(modulus); + fail("ArithmeticException has not been caught"); + } catch (ArithmeticException e) { + } + } + + /** + * modInverse: non-invertible number + */ + public void testmodInverseNonInvertible() { + byte aBytes[] = {-15, 24, 123, 56, -11, -112, -34, -98, 8, 10, 12, 14, 25, 125, -15, 28, -127}; + byte mBytes[] = {-12, 1, 0, 0, 0, 23, 44, 55, 66}; + int aSign = 1; + int mSign = 1; + BigInteger aNumber = new BigInteger(aSign, aBytes); + BigInteger modulus = new BigInteger(mSign, mBytes); + try { + aNumber.modInverse(modulus); + fail("ArithmeticException has not been caught"); + } catch (ArithmeticException e) { + } + } + + /** + * modInverse: positive number + */ + public void testmodInversePos1() { + byte aBytes[] = {24, 123, 56, -11, -112, -34, -98, 8, 10, 12, 14, 25, 125, -15, 28, -127}; + byte mBytes[] = {122, 45, 36, 100, 122, 45}; + int aSign = 1; + int mSign = 1; + byte rBytes[] = {47, 3, 96, 62, 87, 19}; + BigInteger aNumber = new BigInteger(aSign, aBytes); + BigInteger modulus = new BigInteger(mSign, mBytes); + BigInteger result = aNumber.modInverse(modulus); + byte resBytes[] = new byte[rBytes.length]; + resBytes = result.toByteArray(); + for(int i = 0; i < resBytes.length; i++) { + assertTrue(resBytes[i] == rBytes[i]); + } + assertEquals("incorrect sign", 1, result.signum()); + } + + /** + * modInverse: positive number (another case: a < 0) + */ + public void testmodInversePos2() { + byte aBytes[] = {15, 24, 123, 56, -11, -112, -34, -98, 8, 10, 12, 14, 25, 125, -15, 28, -127}; + byte mBytes[] = {2, 122, 45, 36, 100}; + int aSign = 1; + int mSign = 1; + byte rBytes[] = {1, -93, 40, 127, 73}; + BigInteger aNumber = new BigInteger(aSign, aBytes); + BigInteger modulus = new BigInteger(mSign, mBytes); + BigInteger result = aNumber.modInverse(modulus); + byte resBytes[] = new byte[rBytes.length]; + resBytes = result.toByteArray(); + for(int i = 0; i < resBytes.length; i++) { + assertTrue(resBytes[i] == rBytes[i]); + } + assertEquals("incorrect sign", 1, result.signum()); + } + + /** + * modInverse: negative number + */ + public void testmodInverseNeg1() { + byte aBytes[] = {15, 24, 123, 56, -11, -112, -34, -98, 8, 10, 12, 14, 25, 125, -15, 28, -127}; + byte mBytes[] = {2, 122, 45, 36, 100}; + int aSign = -1; + int mSign = 1; + byte rBytes[] = {0, -41, 4, -91, 27}; + BigInteger aNumber = new BigInteger(aSign, aBytes); + BigInteger modulus = new BigInteger(mSign, mBytes); + BigInteger result = aNumber.modInverse(modulus); + byte resBytes[] = new byte[rBytes.length]; + resBytes = result.toByteArray(); + for(int i = 0; i < resBytes.length; i++) { + assertTrue(resBytes[i] == rBytes[i]); + } + assertEquals("incorrect sign", 1, result.signum()); + } + + /** + * modInverse: negative number (another case: x < 0) + */ + public void testmodInverseNeg2() { + byte aBytes[] = {-15, 24, 123, 57, -15, 24, 123, 57, -15, 24, 123, 57}; + byte mBytes[] = {122, 2, 4, 122, 2, 4}; + byte rBytes[] = {85, 47, 127, 4, -128, 45}; + BigInteger aNumber = new BigInteger(aBytes); + BigInteger modulus = new BigInteger(mBytes); + BigInteger result = aNumber.modInverse(modulus); + byte resBytes[] = new byte[rBytes.length]; + resBytes = result.toByteArray(); + for(int i = 0; i < resBytes.length; i++) { + assertTrue(resBytes[i] == rBytes[i]); + } + assertEquals("incorrect sign", 1, result.signum()); + } + + /** + * gcd: the second number is zero + */ + public void testGcdSecondZero() { + byte aBytes[] = {15, 24, 123, 57, -15, 24, 123, 57, -15, 24, 123, 57}; + byte bBytes[] = {0}; + int aSign = 1; + int bSign = 1; + byte rBytes[] = {15, 24, 123, 57, -15, 24, 123, 57, -15, 24, 123, 57}; + BigInteger aNumber = new BigInteger(aSign, aBytes); + BigInteger bNumber = new BigInteger(bSign, bBytes); + BigInteger result = aNumber.gcd(bNumber); + byte resBytes[] = new byte[rBytes.length]; + resBytes = result.toByteArray(); + for(int i = 0; i < resBytes.length; i++) { + assertTrue(resBytes[i] == rBytes[i]); + } + assertEquals("incorrect sign", 1, result.signum()); + } + + /** + * gcd: the first number is zero + */ + public void testGcdFirstZero() { + byte aBytes[] = {0}; + byte bBytes[] = {15, 24, 123, 57, -15, 24, 123, 57, -15, 24, 123, 57}; + int aSign = 1; + int bSign = 1; + byte rBytes[] = {15, 24, 123, 57, -15, 24, 123, 57, -15, 24, 123, 57}; + BigInteger aNumber = new BigInteger(aSign, aBytes); + BigInteger bNumber = new BigInteger(bSign, bBytes); + BigInteger result = aNumber.gcd(bNumber); + byte resBytes[] = new byte[rBytes.length]; + resBytes = result.toByteArray(); + for(int i = 0; i < resBytes.length; i++) { + assertTrue(resBytes[i] == rBytes[i]); + } + assertEquals("incorrect sign", 1, result.signum()); + } + + /** + * gcd: the first number is ZERO + */ + public void testGcdFirstZERO() { + byte bBytes[] = {15, 24, 123, 57, -15, 24, 123, 57, -15, 24, 123, 57}; + int bSign = 1; + byte rBytes[] = {15, 24, 123, 57, -15, 24, 123, 57, -15, 24, 123, 57}; + BigInteger aNumber = BigInteger.ZERO; + BigInteger bNumber = new BigInteger(bSign, bBytes); + BigInteger result = aNumber.gcd(bNumber); + byte resBytes[] = new byte[rBytes.length]; + resBytes = result.toByteArray(); + for(int i = 0; i < resBytes.length; i++) { + assertTrue(resBytes[i] == rBytes[i]); + } + assertEquals("incorrect sign", 1, result.signum()); + } + + /** + * gcd: both numbers are zeros + */ + public void testGcdBothZeros() { + byte rBytes[] = {0}; + BigInteger aNumber = new BigInteger("0"); + BigInteger bNumber = BigInteger.valueOf(0L); + BigInteger result = aNumber.gcd(bNumber); + byte resBytes[] = result.toByteArray(); + for(int i = 0; i < resBytes.length; i++) { + assertTrue(resBytes[i] == rBytes[i]); + } + assertEquals("incorrect sign", 0, result.signum()); + } + + /** + * gcd: the first number is longer + */ + public void testGcdFirstLonger() { + byte aBytes[] = {-15, 24, 123, 56, -11, -112, -34, -98, 8, 10, 12, 14, 25, 125, -15, 28, -127}; + byte bBytes[] = {-12, 1, 0, 0, 0, 23, 44, 55, 66}; + int aSign = 1; + int bSign = 1; + byte rBytes[] = {7}; + BigInteger aNumber = new BigInteger(aSign, aBytes); + BigInteger bNumber = new BigInteger(bSign, bBytes); + BigInteger result = aNumber.gcd(bNumber); + byte resBytes[] = new byte[rBytes.length]; + resBytes = result.toByteArray(); + for(int i = 0; i < resBytes.length; i++) { + assertTrue(resBytes[i] == rBytes[i]); + } + assertEquals("incorrect sign", 1, result.signum()); + } + + /** + * gcd: the second number is longer + */ + public void testGcdSecondLonger() { + byte aBytes[] = {-12, 1, 0, 0, 0, 23, 44, 55, 66}; + byte bBytes[] = {-15, 24, 123, 56, -11, -112, -34, -98, 8, 10, 12, 14, 25, 125, -15, 28, -127}; + int aSign = 1; + int bSign = 1; + byte rBytes[] = {7}; + BigInteger aNumber = new BigInteger(aSign, aBytes); + BigInteger bNumber = new BigInteger(bSign, bBytes); + BigInteger result = aNumber.gcd(bNumber); + byte resBytes[] = new byte[rBytes.length]; + resBytes = result.toByteArray(); + for(int i = 0; i < resBytes.length; i++) { + assertTrue(resBytes[i] == rBytes[i]); + } + assertEquals("incorrect sign", 1, result.signum()); + } +} diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/math/BigIntegerMultiplyTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/math/BigIntegerMultiplyTest.java new file mode 100644 index 0000000..0bfcbf0 --- /dev/null +++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/math/BigIntegerMultiplyTest.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. + */ +/** + * @author Elena Semukhina + */ + +package org.apache.harmony.tests.java.math; + +import junit.framework.TestCase; +import java.math.BigInteger; + +/** + * Class: java.math.BigInteger + * Method: multiply + */ +public class BigIntegerMultiplyTest extends TestCase { + /** + * Multiply two negative numbers of the same length + */ + public void testCase1() { + byte aBytes[] = {1, 2, 3, 4, 5, 6, 7, 1, 2, 3}; + byte bBytes[] = {10, 20, 30, 40, 50, 60, 70, 10, 20, 30}; + int aSign = -1; + int bSign = -1; + byte rBytes[] = {10, 40, 100, -55, 96, 51, 76, 40, -45, 85, 105, 4, 28, -86, -117, -52, 100, 120, 90}; + BigInteger aNumber = new BigInteger(aSign, aBytes); + BigInteger bNumber = new BigInteger(bSign, bBytes); + BigInteger result = aNumber.multiply(bNumber); + byte resBytes[] = new byte[rBytes.length]; + resBytes = result.toByteArray(); + for(int i = 0; i < resBytes.length; i++) { + assertTrue(resBytes[i] == rBytes[i]); + } + assertEquals("incorrect sign", 1, result.signum()); + } + + /** + * Multiply two numbers of the same length and different signs. + * The first is negative. + */ + public void testCase2() { + byte aBytes[] = {1, 2, 3, 4, 5, 6, 7, 1, 2, 3}; + byte bBytes[] = {10, 20, 30, 40, 50, 60, 70, 10, 20, 30}; + int aSign = -1; + int bSign = 1; + byte rBytes[] = {-11, -41, -101, 54, -97, -52, -77, -41, 44, -86, -106, -5, -29, 85, 116, 51, -101, -121, -90}; + BigInteger aNumber = new BigInteger(aSign, aBytes); + BigInteger bNumber = new BigInteger(bSign, bBytes); + BigInteger result = aNumber.multiply(bNumber); + byte resBytes[] = new byte[rBytes.length]; + resBytes = result.toByteArray(); + for(int i = 0; i < resBytes.length; i++) { + assertTrue(resBytes[i] == rBytes[i]); + } + assertEquals("incorrect sign", -1, result.signum()); + } + + /** + * Multiply two positive numbers of different length. + * The first is longer. + */ + public void testCase3() { + byte aBytes[] = {1, 2, 3, 4, 5, 6, 7, 1, 2, 3, 1, 2, 3, 4, 5}; + byte bBytes[] = {10, 20, 30, 40, 50, 60, 70, 10, 20, 30}; + int aSign = 1; + int bSign = 1; + byte rBytes[] = {10, 40, 100, -55, 96, 51, 76, 40, -45, 85, 115, 44, -127, + 115, -21, -62, -15, 85, 64, -87, -2, -36, -36, -106}; + BigInteger aNumber = new BigInteger(aSign, aBytes); + BigInteger bNumber = new BigInteger(bSign, bBytes); + BigInteger result = aNumber.multiply(bNumber); + byte resBytes[] = new byte[rBytes.length]; + resBytes = result.toByteArray(); + for(int i = 0; i < resBytes.length; i++) { + assertTrue(resBytes[i] == rBytes[i]); + } + assertEquals("incorrect sign", 1, result.signum()); + } + + /** + * Multiply two positive numbers of different length. + * The second is longer. + */ + public void testCase4() { + byte aBytes[] = {10, 20, 30, 40, 50, 60, 70, 10, 20, 30}; + byte bBytes[] = {1, 2, 3, 4, 5, 6, 7, 1, 2, 3, 1, 2, 3, 4, 5}; + int aSign = 1; + int bSign = 1; + byte rBytes[] = {10, 40, 100, -55, 96, 51, 76, 40, -45, 85, 115, 44, -127, + 115, -21, -62, -15, 85, 64, -87, -2, -36, -36, -106}; + BigInteger aNumber = new BigInteger(aSign, aBytes); + BigInteger bNumber = new BigInteger(bSign, bBytes); + BigInteger result = aNumber.multiply(bNumber); + byte resBytes[] = new byte[rBytes.length]; + resBytes = result.toByteArray(); + for(int i = 0; i < resBytes.length; i++) { + assertTrue(resBytes[i] == rBytes[i]); + } + assertEquals("incorrect sign", 1, result.signum()); + } + + /** + * Multiply two numbers of different length and different signs. + * The first is positive. + * The first is longer. + */ + public void testCase5() { + byte aBytes[] = {1, 2, 3, 4, 5, 6, 7, 1, 2, 3, 1, 2, 3, 4, 5}; + byte bBytes[] = {10, 20, 30, 40, 50, 60, 70, 10, 20, 30}; + int aSign = 1; + int bSign = -1; + byte rBytes[] = {-11, -41, -101, 54, -97, -52, -77, -41, 44, -86, -116, -45, 126, + -116, 20, 61, 14, -86, -65, 86, 1, 35, 35, 106}; + BigInteger aNumber = new BigInteger(aSign, aBytes); + BigInteger bNumber = new BigInteger(bSign, bBytes); + BigInteger result = aNumber.multiply(bNumber); + byte resBytes[] = new byte[rBytes.length]; + resBytes = result.toByteArray(); + for(int i = 0; i < resBytes.length; i++) { + assertTrue(resBytes[i] == rBytes[i]); + } + assertEquals("incorrect sign", -1, result.signum()); + } + + /** + * Multiply two numbers of different length and different signs. + * The first is positive. + * The second is longer. + */ + public void testCase6() { + byte aBytes[] = {10, 20, 30, 40, 50, 60, 70, 10, 20, 30}; + byte bBytes[] = {1, 2, 3, 4, 5, 6, 7, 1, 2, 3, 1, 2, 3, 4, 5}; + int aSign = 1; + int bSign = -1; + byte rBytes[] = {-11, -41, -101, 54, -97, -52, -77, -41, 44, -86, -116, -45, 126, + -116, 20, 61, 14, -86, -65, 86, 1, 35, 35, 106}; + BigInteger aNumber = new BigInteger(aSign, aBytes); + BigInteger bNumber = new BigInteger(bSign, bBytes); + BigInteger result = aNumber.multiply(bNumber); + byte resBytes[] = new byte[rBytes.length]; + resBytes = result.toByteArray(); + for(int i = 0; i < resBytes.length; i++) { + assertTrue(resBytes[i] == rBytes[i]); + } + assertEquals("incorrect sign", -1, result.signum()); + } + + /** + * Multiply a number by zero. + */ + public void testCase7() { + byte aBytes[] = {1, 2, 3, 4, 5, 6, 7, 1, 2, 3, 1, 2, 3, 4, 5}; + byte bBytes[] = {0}; + int aSign = 1; + int bSign = 0; + byte rBytes[] = {0}; + BigInteger aNumber = new BigInteger(aSign, aBytes); + BigInteger bNumber = new BigInteger(bSign, bBytes); + BigInteger result = aNumber.multiply(bNumber); + byte resBytes[] = new byte[rBytes.length]; + resBytes = result.toByteArray(); + for(int i = 0; i < resBytes.length; i++) { + assertTrue(resBytes[i] == rBytes[i]); + } + assertEquals("incorrect sign", 0, result.signum()); + } + + /** + * Multiply a number by ZERO. + */ + public void testCase8() { + byte aBytes[] = {1, 2, 3, 4, 5, 6, 7, 1, 2, 3, 1, 2, 3, 4, 5}; + int aSign = 1; + byte rBytes[] = {0}; + BigInteger aNumber = new BigInteger(aSign, aBytes); + BigInteger bNumber = BigInteger.ZERO; + BigInteger result = aNumber.multiply(bNumber); + byte resBytes[] = new byte[rBytes.length]; + resBytes = result.toByteArray(); + for(int i = 0; i < resBytes.length; i++) { + assertTrue(resBytes[i] == rBytes[i]); + } + assertEquals("incorrect sign", 0, result.signum()); + } + + /** + * Multiply a positive number by ONE. + */ + public void testCase9() { + byte aBytes[] = {1, 2, 3, 4, 5, 6, 7, 1, 2, 3, 1, 2, 3, 4, 5}; + int aSign = 1; + byte rBytes[] = {1, 2, 3, 4, 5, 6, 7, 1, 2, 3, 1, 2, 3, 4, 5}; + BigInteger aNumber = new BigInteger(aSign, aBytes); + BigInteger bNumber = BigInteger.ONE; + BigInteger result = aNumber.multiply(bNumber); + byte resBytes[] = new byte[rBytes.length]; + resBytes = result.toByteArray(); + for(int i = 0; i < resBytes.length; i++) { + assertTrue(resBytes[i] == rBytes[i]); + } + assertEquals("incorrect sign", 1, result.signum()); + } + + /** + * Multiply a negative number by ONE. + */ + public void testCase10() { + byte aBytes[] = {1, 2, 3, 4, 5, 6, 7, 1, 2, 3, 1, 2, 3, 4, 5}; + int aSign = -1; + byte rBytes[] = {-2, -3, -4, -5, -6, -7, -8, -2, -3, -4, -2, -3, -4, -5, -5}; + BigInteger aNumber = new BigInteger(aSign, aBytes); + BigInteger bNumber = BigInteger.ONE; + BigInteger result = aNumber.multiply(bNumber); + byte resBytes[] = new byte[rBytes.length]; + resBytes = result.toByteArray(); + for(int i = 0; i < resBytes.length; i++) { + assertTrue(resBytes[i] == rBytes[i]); + } + assertEquals("incorrect sign", -1, result.signum()); + } + + /** + * Multiply two numbers of 4 bytes length. + */ + public void testIntbyInt1() { + byte aBytes[] = {10, 20, 30, 40}; + byte bBytes[] = {1, 2, 3, 4}; + int aSign = 1; + int bSign = -1; + byte rBytes[] = {-11, -41, -101, 55, 5, 15, 96}; + BigInteger aNumber = new BigInteger(aSign, aBytes); + BigInteger bNumber = new BigInteger(bSign, bBytes); + BigInteger result = aNumber.multiply(bNumber); + byte resBytes[] = new byte[rBytes.length]; + resBytes = result.toByteArray(); + for(int i = 0; i < resBytes.length; i++) { + assertTrue(resBytes[i] == rBytes[i]); + } + assertEquals("incorrect sign", -1, result.signum()); + } + + /** + * Multiply two numbers of 4 bytes length. + */ + public void testIntbyInt2() { + byte aBytes[] = {-1, -1, -1, -1}; + byte bBytes[] = {-1, -1, -1, -1}; + int aSign = 1; + int bSign = 1; + byte rBytes[] = {0, -1, -1, -1, -2, 0, 0, 0, 1}; + BigInteger aNumber = new BigInteger(aSign, aBytes); + BigInteger bNumber = new BigInteger(bSign, bBytes); + BigInteger result = aNumber.multiply(bNumber); + byte resBytes[] = new byte[rBytes.length]; + resBytes = result.toByteArray(); + for(int i = 0; i < resBytes.length; i++) { + assertTrue(resBytes[i] == rBytes[i]); + } + assertEquals("incorrect sign", 1, result.signum()); + } + + /** + * Negative exponent. + */ + public void testPowException() { + byte aBytes[] = {1, 2, 3, 4, 5, 6, 7}; + int aSign = 1; + int exp = -5; + BigInteger aNumber = new BigInteger(aSign, aBytes); + try { + aNumber.pow(exp); + fail("ArithmeticException has not been caught"); + } catch (ArithmeticException e) { + } + } + + /** + * Exponentiation of a negative number to an odd exponent. + */ + public void testPowNegativeNumToOddExp() { + byte aBytes[] = {50, -26, 90, 69, 120, 32, 63, -103, -14, 35}; + int aSign = -1; + int exp = 5; + byte rBytes[] = {-21, -94, -42, -15, -127, 113, -50, -88, 115, -35, 3, + 59, -92, 111, -75, 103, -42, 41, 34, -114, 99, -32, 105, -59, 127, + 45, 108, 74, -93, 105, 33, 12, -5, -20, 17, -21, -119, -127, -115, + 27, -122, 26, -67, 109, -125, 16, 91, -70, 109}; + BigInteger aNumber = new BigInteger(aSign, aBytes); + BigInteger result = aNumber.pow(exp); + byte resBytes[] = new byte[rBytes.length]; + resBytes = result.toByteArray(); + for(int i = 0; i < resBytes.length; i++) { + assertTrue(resBytes[i] == rBytes[i]); + } + assertEquals("incorrect sign", -1, result.signum()); + } + + /** + * Exponentiation of a negative number to an even exponent. + */ + public void testPowNegativeNumToEvenExp() { + byte aBytes[] = {50, -26, 90, 69, 120, 32, 63, -103, -14, 35}; + int aSign = -1; + int exp = 4; + byte rBytes[] = {102, 107, -122, -43, -52, -20, -27, 25, -9, 88, -13, + 75, 78, 81, -33, -77, 39, 27, -37, 106, 121, -73, 108, -47, -101, + 80, -25, 71, 13, 94, -7, -33, 1, -17, -65, -70, -61, -3, -47}; + BigInteger aNumber = new BigInteger(aSign, aBytes); + BigInteger result = aNumber.pow(exp); + byte resBytes[] = new byte[rBytes.length]; + resBytes = result.toByteArray(); + for(int i = 0; i < resBytes.length; i++) { + assertTrue(resBytes[i] == rBytes[i]); + } + assertEquals("incorrect sign", 1, result.signum()); + } + + /** + * Exponentiation of a negative number to zero exponent. + */ + public void testPowNegativeNumToZeroExp() { + byte aBytes[] = {50, -26, 90, 69, 120, 32, 63, -103, -14, 35}; + int aSign = -1; + int exp = 0; + byte rBytes[] = {1}; + BigInteger aNumber = new BigInteger(aSign, aBytes); + BigInteger result = aNumber.pow(exp); + byte resBytes[] = new byte[rBytes.length]; + resBytes = result.toByteArray(); + for(int i = 0; i < resBytes.length; i++) { + assertTrue(resBytes[i] == rBytes[i]); + } + assertEquals("incorrect sign", 1, result.signum()); + } + + /** + * Exponentiation of a positive number. + */ + public void testPowPositiveNum() { + byte aBytes[] = {50, -26, 90, 69, 120, 32, 63, -103, -14, 35}; + int aSign = 1; + int exp = 5; + byte rBytes[] = {20, 93, 41, 14, 126, -114, 49, 87, -116, 34, -4, -60, + 91, -112, 74, -104, 41, -42, -35, 113, -100, 31, -106, 58, -128, + -46, -109, -75, 92, -106, -34, -13, 4, 19, -18, 20, 118, 126, 114, + -28, 121, -27, 66, -110, 124, -17, -92, 69, -109}; + BigInteger aNumber = new BigInteger(aSign, aBytes); + BigInteger result = aNumber.pow(exp); + byte resBytes[] = new byte[rBytes.length]; + resBytes = result.toByteArray(); + for(int i = 0; i < resBytes.length; i++) { + assertTrue(resBytes[i] == rBytes[i]); + } + assertEquals("incorrect sign", 1, result.signum()); + } + + /** + * Exponentiation of a negative number to zero exponent. + */ + public void testPowPositiveNumToZeroExp() { + byte aBytes[] = {50, -26, 90, 69, 120, 32, 63, -103, -14, 35}; + int aSign = 1; + int exp = 0; + byte rBytes[] = {1}; + BigInteger aNumber = new BigInteger(aSign, aBytes); + BigInteger result = aNumber.pow(exp); + byte resBytes[] = new byte[rBytes.length]; + resBytes = result.toByteArray(); + for(int i = 0; i < resBytes.length; i++) { + assertTrue(resBytes[i] == rBytes[i]); + } + assertEquals("incorrect sign", 1, result.signum()); + } +} diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/math/BigIntegerNotTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/math/BigIntegerNotTest.java new file mode 100644 index 0000000..615afc1 --- /dev/null +++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/math/BigIntegerNotTest.java @@ -0,0 +1,192 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 Elena Semukhina + */ + +package org.apache.harmony.tests.java.math; + +import junit.framework.TestCase; +import java.math.BigInteger; + +/** + * Class: java.math.BigInteger + * Methods: and, andNot + */ +public class BigIntegerNotTest extends TestCase { + /** + * andNot for two positive numbers; the first is longer + */ + public void testAndNotPosPosFirstLonger() { + byte aBytes[] = {-128, 9, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26, -117, 23, 87, -25, -75}; + byte bBytes[] = {-2, -3, -4, -4, 5, 14, 23, 39, 48, 57, 66, 5, 14, 23}; + int aSign = 1; + int bSign = 1; + byte rBytes[] = {0, -128, 9, 56, 100, 0, 0, 1, 1, 90, 1, -32, 0, 10, -126, 21, 82, -31, -96}; + BigInteger aNumber = new BigInteger(aSign, aBytes); + BigInteger bNumber = new BigInteger(bSign, bBytes); + BigInteger result = aNumber.andNot(bNumber); + byte resBytes[] = new byte[rBytes.length]; + resBytes = result.toByteArray(); + for(int i = 0; i < resBytes.length; i++) { + assertTrue(resBytes[i] == rBytes[i]); + } + assertEquals("incorrect sign", 1, result.signum()); + } + + /** + * andNot for two positive numbers; the first is shorter + */ + public void testAndNotPosPosFirstShorter() { + byte aBytes[] = {-2, -3, -4, -4, 5, 14, 23, 39, 48, 57, 66, 5, 14, 23}; + byte bBytes[] = {-128, 9, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26, -117, 23, 87, -25, -75}; + int aSign = 1; + int bSign = 1; + byte rBytes[] = {73, -92, -48, 4, 12, 6, 4, 32, 48, 64, 0, 8, 2}; + BigInteger aNumber = new BigInteger(aSign, aBytes); + BigInteger bNumber = new BigInteger(bSign, bBytes); + BigInteger result = aNumber.andNot(bNumber); + byte resBytes[] = new byte[rBytes.length]; + resBytes = result.toByteArray(); + for(int i = 0; i < resBytes.length; i++) { + assertTrue(resBytes[i] == rBytes[i]); + } + assertEquals("incorrect sign", 1, result.signum()); + } + + /** + * andNot for two negative numbers; the first is longer + */ + public void testAndNotNegNegFirstLonger() { + byte aBytes[] = {-128, 9, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26, -117, 23, 87, -25, -75}; + byte bBytes[] = {-2, -3, -4, -4, 5, 14, 23, 39, 48, 57, 66, 5, 14, 23}; + int aSign = -1; + int bSign = -1; + byte rBytes[] = {73, -92, -48, 4, 12, 6, 4, 32, 48, 64, 0, 8, 2}; + BigInteger aNumber = new BigInteger(aSign, aBytes); + BigInteger bNumber = new BigInteger(bSign, bBytes); + BigInteger result = aNumber.andNot(bNumber); + byte resBytes[] = new byte[rBytes.length]; + resBytes = result.toByteArray(); + for(int i = 0; i < resBytes.length; i++) { + assertTrue(resBytes[i] == rBytes[i]); + } + assertEquals("incorrect sign", 1, result.signum()); + } + + /** + * andNot for a negative and a positive numbers; the first is longer + */ + public void testNegPosFirstLonger() { + byte aBytes[] = {-128, 9, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26, -117, 23, 87, -25, -75}; + byte bBytes[] = {-2, -3, -4, -4, 5, 14, 23, 39, 48, 57, 66, 5, 14, 23}; + int aSign = -1; + int bSign = 1; + byte rBytes[] = {-1, 127, -10, -57, -101, 1, 2, 2, 2, -96, -16, 8, -40, -59, 68, -88, -88, 16, 72}; + BigInteger aNumber = new BigInteger(aSign, aBytes); + BigInteger bNumber = new BigInteger(bSign, bBytes); + BigInteger result = aNumber.andNot(bNumber); + byte resBytes[] = new byte[rBytes.length]; + resBytes = result.toByteArray(); + for(int i = 0; i < resBytes.length; i++) { + assertTrue(resBytes[i] == rBytes[i]); + } + assertEquals("incorrect sign", -1, result.signum()); + } + + /** + * Not for ZERO + */ + public void testNotZero() { + byte rBytes[] = {-1}; + BigInteger aNumber = BigInteger.ZERO; + BigInteger result = aNumber.not(); + byte resBytes[] = new byte[rBytes.length]; + resBytes = result.toByteArray(); + for(int i = 0; i < resBytes.length; i++) { + assertTrue(resBytes[i] == rBytes[i]); + } + assertEquals("incorrect sign", -1, result.signum()); + } + + /** + * Not for ONE + */ + public void testNotOne() { + byte rBytes[] = {-2}; + BigInteger aNumber = BigInteger.ONE; + BigInteger result = aNumber.not(); + byte resBytes[] = new byte[rBytes.length]; + resBytes = result.toByteArray(); + for(int i = 0; i < resBytes.length; i++) { + assertTrue(resBytes[i] == rBytes[i]); + } + assertEquals("incorrect sign", -1, result.signum()); + } + + /** + * Not for a positive number + */ + public void testNotPos() { + byte aBytes[] = {-128, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26, -117}; + int aSign = 1; + byte rBytes[] = {-1, 127, -57, -101, 1, 75, -90, -46, -92, -4, 14, -36, -27, 116}; + BigInteger aNumber = new BigInteger(aSign, aBytes); + BigInteger result = aNumber.not(); + byte resBytes[] = new byte[rBytes.length]; + resBytes = result.toByteArray(); + for(int i = 0; i < resBytes.length; i++) { + assertTrue(resBytes[i] == rBytes[i]); + } + assertEquals("incorrect sign", -1, result.signum()); + } + + /** + * Not for a negative number + */ + public void testNotNeg() { + byte aBytes[] = {-128, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26, -117}; + int aSign = -1; + byte rBytes[] = {0, -128, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26, -118}; + BigInteger aNumber = new BigInteger(aSign, aBytes); + BigInteger result = aNumber.not(); + byte resBytes[] = new byte[rBytes.length]; + resBytes = result.toByteArray(); + for(int i = 0; i < resBytes.length; i++) { + assertTrue(resBytes[i] == rBytes[i]); + } + assertEquals("incorrect sign", 1, result.signum()); + } + + /** + * Not for a negative number + */ + + public void testNotSpecialCase() { + byte aBytes[] = {-1, -1, -1, -1}; + int aSign = 1; + byte rBytes[] = {-1, 0, 0, 0, 0}; + BigInteger aNumber = new BigInteger(aSign, aBytes); + BigInteger result = aNumber.not(); + byte resBytes[] = new byte[rBytes.length]; + resBytes = result.toByteArray(); + for(int i = 0; i < resBytes.length; i++) { + assertTrue(resBytes[i] == rBytes[i]); + } + assertEquals("incorrect sign", -1, result.signum()); + } +}
\ No newline at end of file diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/math/BigIntegerOperateBitsTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/math/BigIntegerOperateBitsTest.java new file mode 100644 index 0000000..9b7c198 --- /dev/null +++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/math/BigIntegerOperateBitsTest.java @@ -0,0 +1,1375 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 Elena Semukhina + */ + +package org.apache.harmony.tests.java.math; + +import junit.framework.TestCase; +import java.math.BigInteger; + +/** + * Class: java.math.BigInteger + * Methods: bitLength, shiftLeft, shiftRight, + * clearBit, flipBit, setBit, testBit + */ +public class BigIntegerOperateBitsTest extends TestCase { + /** + * bitCount() of zero. + */ + public void testBitCountZero() { + BigInteger aNumber = new BigInteger("0"); + assertEquals(0, aNumber.bitCount()); + } + + /** + * bitCount() of a negative number. + */ + public void testBitCountNeg() { + BigInteger aNumber = new BigInteger("-12378634756382937873487638746283767238657872368748726875"); + assertEquals(87, aNumber.bitCount()); + } + + /** + * bitCount() of a negative number. + */ + public void testBitCountPos() { + BigInteger aNumber = new BigInteger("12378634756343564757582937873487638746283767238657872368748726875"); + assertEquals(107, aNumber.bitCount()); + } + + /** + * bitLength() of zero. + */ + public void testBitLengthZero() { + BigInteger aNumber = new BigInteger("0"); + assertEquals(0, aNumber.bitLength()); + } + + /** + * bitLength() of a positive number. + */ + public void testBitLengthPositive1() { + byte aBytes[] = {12, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26, 3, 91}; + int aSign = 1; + BigInteger aNumber = new BigInteger(aSign, aBytes); + assertEquals(108, aNumber.bitLength()); + } + + /** + * bitLength() of a positive number with the leftmost bit set + */ + public void testBitLengthPositive2() { + byte aBytes[] = {-128, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26}; + int aSign = 1; + BigInteger aNumber = new BigInteger(aSign, aBytes); + assertEquals(96, aNumber.bitLength()); + } + + /** + * bitLength() of a positive number which is a power of 2 + */ + public void testBitLengthPositive3() { + byte aBytes[] = {1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; + int aSign = 1; + BigInteger aNumber = new BigInteger(aSign, aBytes); + assertEquals(81, aNumber.bitLength()); + } + + /** + * bitLength() of a negative number. + */ + public void testBitLengthNegative1() { + byte aBytes[] = {12, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26, 3, 91}; + int aSign = -1; + BigInteger aNumber = new BigInteger(aSign, aBytes); + assertEquals(108, aNumber.bitLength()); + } + + /** + * bitLength() of a negative number with the leftmost bit set + */ + public void testBitLengthNegative2() { + byte aBytes[] = {-128, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26}; + int aSign = -1; + BigInteger aNumber = new BigInteger(aSign, aBytes); + assertEquals(96, aNumber.bitLength()); + } + + /** + * bitLength() of a negative number which is a power of 2 + */ + public void testBitLengthNegative3() { + byte aBytes[] = {1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; + int aSign = -1; + BigInteger aNumber = new BigInteger(aSign, aBytes); + assertEquals(80, aNumber.bitLength()); + } + + /** + * clearBit(int n) of a negative n + */ + public void testClearBitException() { + byte aBytes[] = {-1, -128, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26}; + int aSign = 1; + int number = -7; + BigInteger aNumber = new BigInteger(aSign, aBytes); + try { + aNumber.clearBit(number); + fail("ArithmeticException has not been caught"); + } catch (ArithmeticException e) { + } + } + + /** + * clearBit(int n) outside zero + */ + public void testClearBitZero() { + byte aBytes[] = {0}; + int aSign = 0; + int number = 0; + byte rBytes[] = {0}; + BigInteger aNumber = new BigInteger(aSign, aBytes); + BigInteger result = aNumber.clearBit(number); + byte resBytes[] = new byte[rBytes.length]; + resBytes = result.toByteArray(); + for(int i = 0; i < resBytes.length; i++) { + assertTrue(resBytes[i] == rBytes[i]); + } + assertEquals("incorrect sign", 0, result.signum()); + } + + /** + * clearBit(int n) outside zero + */ + public void testClearBitZeroOutside1() { + byte aBytes[] = {0}; + int aSign = 0; + int number = 95; + byte rBytes[] = {0}; + BigInteger aNumber = new BigInteger(aSign, aBytes); + BigInteger result = aNumber.clearBit(number); + byte resBytes[] = new byte[rBytes.length]; + resBytes = result.toByteArray(); + for(int i = 0; i < resBytes.length; i++) { + assertTrue(resBytes[i] == rBytes[i]); + } + assertEquals("incorrect sign", 0, result.signum()); + } + + /** + * clearBit(int n) inside a negative number + */ + public void testClearBitNegativeInside1() { + byte aBytes[] = {1, -128, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26}; + int aSign = -1; + int number = 15; + byte rBytes[] = {-2, 127, -57, -101, 1, 75, -90, -46, -92, -4, 14, 92, -26}; + BigInteger aNumber = new BigInteger(aSign, aBytes); + BigInteger result = aNumber.clearBit(number); + byte resBytes[] = new byte[rBytes.length]; + resBytes = result.toByteArray(); + for(int i = 0; i < resBytes.length; i++) { + assertTrue(resBytes[i] == rBytes[i]); + } + assertEquals("incorrect sign", -1, result.signum()); + } + + /** + * clearBit(int n) inside a negative number + */ + public void testClearBitNegativeInside2() { + byte aBytes[] = {1, -128, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26}; + int aSign = -1; + int number = 44; + byte rBytes[] = {-2, 127, -57, -101, 1, 75, -90, -62, -92, -4, 14, -36, -26}; + BigInteger aNumber = new BigInteger(aSign, aBytes); + BigInteger result = aNumber.clearBit(number); + byte resBytes[] = new byte[rBytes.length]; + resBytes = result.toByteArray(); + for(int i = 0; i < resBytes.length; i++) { + assertTrue(resBytes[i] == rBytes[i]); + } + assertEquals("incorrect sign", -1, result.signum()); + } + + /** + * clearBit(2) in the negative number with all ones in bit representation + */ + public void testClearBitNegativeInside3() { + String as = "-18446744073709551615"; + int number = 2; + BigInteger aNumber = new BigInteger(as); + BigInteger result = aNumber.clearBit(number); + assertEquals(as, result.toString()); + } + + /** + * clearBit(0) in the negative number of length 1 + * with all ones in bit representation. + * the resulting number's length is 2. + */ + public void testClearBitNegativeInside4() { + String as = "-4294967295"; + String res = "-4294967296"; + int number = 0; + BigInteger aNumber = new BigInteger(as); + BigInteger result = aNumber.clearBit(number); + assertEquals(res, result.toString()); + } + + /** + * clearBit(0) in the negative number of length 2 + * with all ones in bit representation. + * the resulting number's length is 3. + */ + public void testClearBitNegativeInside5() { + String as = "-18446744073709551615"; + String res = "-18446744073709551616"; + int number = 0; + BigInteger aNumber = new BigInteger(as); + BigInteger result = aNumber.clearBit(number); + assertEquals(res, result.toString()); + } + + /** + * clearBit(int n) outside a negative number + */ + public void testClearBitNegativeOutside1() { + byte aBytes[] = {1, -128, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26}; + int aSign = -1; + int number = 150; + byte rBytes[] = {-65, -1, -1, -1, -1, -1, -2, 127, -57, -101, 1, 75, -90, -46, -92, -4, 14, -36, -26}; + BigInteger aNumber = new BigInteger(aSign, aBytes); + BigInteger result = aNumber.clearBit(number); + byte resBytes[] = new byte[rBytes.length]; + resBytes = result.toByteArray(); + for(int i = 0; i < resBytes.length; i++) { + assertTrue(resBytes[i] == rBytes[i]); + } + assertEquals("incorrect sign", -1, result.signum()); + } + + /** + * clearBit(int n) outside a negative number + */ + public void testClearBitNegativeOutside2() { + byte aBytes[] = {1, -128, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26}; + int aSign = -1; + int number = 165; + byte rBytes[] = {-33, -1, -1, -1, -1, -1, -1, -1, -2, 127, -57, -101, 1, 75, -90, -46, -92, -4, 14, -36, -26}; + BigInteger aNumber = new BigInteger(aSign, aBytes); + BigInteger result = aNumber.clearBit(number); + byte resBytes[] = new byte[rBytes.length]; + resBytes = result.toByteArray(); + for(int i = 0; i < resBytes.length; i++) { + assertTrue(resBytes[i] == rBytes[i]); + } + assertEquals("incorrect sign", -1, result.signum()); + } + + /** + * clearBit(int n) inside a positive number + */ + public void testClearBitPositiveInside1() { + byte aBytes[] = {1, -128, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26}; + int aSign = 1; + int number = 20; + byte rBytes[] = {1, -128, 56, 100, -2, -76, 89, 45, 91, 3, -31, 35, 26}; + BigInteger aNumber = new BigInteger(aSign, aBytes); + BigInteger result = aNumber.clearBit(number); + byte resBytes[] = new byte[rBytes.length]; + resBytes = result.toByteArray(); + for(int i = 0; i < resBytes.length; i++) { + assertTrue(resBytes[i] == rBytes[i]); + } + assertEquals("incorrect sign", 1, result.signum()); + } + + /** + * clearBit(int n) inside a positive number + */ + public void testClearBitPositiveInside2() { + byte aBytes[] = {1, -128, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26}; + int aSign = 1; + int number = 17; + byte rBytes[] = {1, -128, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26}; + BigInteger aNumber = new BigInteger(aSign, aBytes); + BigInteger result = aNumber.clearBit(number); + byte resBytes[] = new byte[rBytes.length]; + resBytes = result.toByteArray(); + for(int i = 0; i < resBytes.length; i++) { + assertTrue(resBytes[i] == rBytes[i]); + } + assertEquals("incorrect sign", 1, result.signum()); + } + + /** + * clearBit(int n) inside a positive number + */ + public void testClearBitPositiveInside3() { + byte aBytes[] = {1, -128, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26}; + int aSign = 1; + int number = 45; + byte rBytes[] = {1, -128, 56, 100, -2, -76, 89, 13, 91, 3, -15, 35, 26}; + BigInteger aNumber = new BigInteger(aSign, aBytes); + BigInteger result = aNumber.clearBit(number); + byte resBytes[] = new byte[rBytes.length]; + resBytes = result.toByteArray(); + for(int i = 0; i < resBytes.length; i++) { + assertTrue(resBytes[i] == rBytes[i]); + } + assertEquals("incorrect sign", 1, result.signum()); + } + + /** + * clearBit(int n) inside a positive number + */ + public void testClearBitPositiveInside4 () { + byte aBytes[] = {1, -128, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26}; + int aSign = 1; + int number = 50; + byte rBytes[] = {1, -128, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26}; + BigInteger aNumber = new BigInteger(aSign, aBytes); + BigInteger result = aNumber.clearBit(number); + byte resBytes[] = new byte[rBytes.length]; + resBytes = result.toByteArray(); + for(int i = 0; i < resBytes.length; i++) { + assertTrue(resBytes[i] == rBytes[i]); + } + assertEquals("incorrect sign", 1, result.signum()); + } + + /** + * clearBit(int n) inside a positive number + */ + public void testClearBitPositiveInside5 () { + byte aBytes[] = {1, -128, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26}; + int aSign = 1; + int number = 63; + byte rBytes[] = {1, -128, 56, 100, -2, 52, 89, 45, 91, 3, -15, 35, 26}; + BigInteger aNumber = new BigInteger(aSign, aBytes); + BigInteger result = aNumber.clearBit(number); + byte resBytes[] = new byte[rBytes.length]; + resBytes = result.toByteArray(); + for(int i = 0; i < resBytes.length; i++) { + assertTrue(resBytes[i] == rBytes[i]); + } + assertEquals("incorrect sign", 1, result.signum()); + } + + /** + * clearBit(int n) outside a positive number + */ + public void testClearBitPositiveOutside1() { + byte aBytes[] = {1, -128, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26}; + int aSign = 1; + int number = 150; + byte rBytes[] = {1, -128, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26}; + BigInteger aNumber = new BigInteger(aSign, aBytes); + BigInteger result = aNumber.clearBit(number); + byte resBytes[] = new byte[rBytes.length]; + resBytes = result.toByteArray(); + for(int i = 0; i < resBytes.length; i++) { + assertTrue(resBytes[i] == rBytes[i]); + } + assertEquals("incorrect sign", 1, result.signum()); + } + + /** + * clearBit(int n) outside a positive number + */ + public void testClearBitPositiveOutside2() { + byte aBytes[] = {1, -128, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26}; + int aSign = 1; + int number = 191; + byte rBytes[] = {1, -128, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26}; + BigInteger aNumber = new BigInteger(aSign, aBytes); + BigInteger result = aNumber.clearBit(number); + byte resBytes[] = new byte[rBytes.length]; + resBytes = result.toByteArray(); + for(int i = 0; i < resBytes.length; i++) { + assertTrue(resBytes[i] == rBytes[i]); + } + assertEquals("incorrect sign", 1, result.signum()); + } + + /** + * clearBit(int n) the leftmost bit in a negative number + */ + public void testClearBitTopNegative() { + byte aBytes[] = {1, -128, 56, 100, -15, 35, 26}; + int aSign = -1; + int number = 63; + byte rBytes[] = {-1, 127, -2, 127, -57, -101, 14, -36, -26}; + BigInteger aNumber = new BigInteger(aSign, aBytes); + BigInteger result = aNumber.clearBit(number); + byte resBytes[] = new byte[rBytes.length]; + resBytes = result.toByteArray(); + for(int i = 0; i < resBytes.length; i++) { + assertTrue(resBytes[i] == rBytes[i]); + } + assertEquals("incorrect sign", -1, result.signum()); + } + + /** + * flipBit(int n) of a negative n + */ + public void testFlipBitException() { + byte aBytes[] = {-1, -128, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26}; + int aSign = 1; + int number = -7; + BigInteger aNumber = new BigInteger(aSign, aBytes); + try { + aNumber.flipBit(number); + fail("ArithmeticException has not been caught"); + } catch (ArithmeticException e) { + } + } + + /** + * flipBit(int n) zero + */ + public void testFlipBitZero() { + byte aBytes[] = {0}; + int aSign = 0; + int number = 0; + byte rBytes[] = {1}; + BigInteger aNumber = new BigInteger(aSign, aBytes); + BigInteger result = aNumber.flipBit(number); + byte resBytes[] = new byte[rBytes.length]; + resBytes = result.toByteArray(); + for(int i = 0; i < resBytes.length; i++) { + assertTrue(resBytes[i] == rBytes[i]); + } + assertEquals("incorrect sign", 1, result.signum()); + } + + /** + * flipBit(int n) outside zero + */ + public void testFlipBitZeroOutside1() { + byte aBytes[] = {0}; + int aSign = 0; + int number = 62; + byte rBytes[] = {64, 0, 0, 0, 0, 0, 0, 0}; + BigInteger aNumber = new BigInteger(aSign, aBytes); + BigInteger result = aNumber.flipBit(number); + byte resBytes[] = new byte[rBytes.length]; + resBytes = result.toByteArray(); + for(int i = 0; i < resBytes.length; i++) { + assertTrue("incorrect value", resBytes[i] == rBytes[i]); + } + assertEquals("incorrect sign", 1, result.signum()); + } + + /** + * flipBit(int n) outside zero + */ + public void testFlipBitZeroOutside2() { + byte aBytes[] = {0}; + int aSign = 0; + int number = 63; + byte rBytes[] = {0, -128, 0, 0, 0, 0, 0, 0, 0}; + BigInteger aNumber = new BigInteger(aSign, aBytes); + BigInteger result = aNumber.flipBit(number); + byte resBytes[] = new byte[rBytes.length]; + resBytes = result.toByteArray(); + for(int i = 0; i < resBytes.length; i++) { + assertTrue("incorrect value", resBytes[i] == rBytes[i]); + } + assertEquals("incorrect sign", 1, result.signum()); + } + + /** + * flipBit(int n) the leftmost bit in a negative number + */ + public void testFlipBitLeftmostNegative() { + byte aBytes[] = {1, -128, 56, 100, -15, 35, 26}; + int aSign = -1; + int number = 48; + byte rBytes[] = {-1, 127, -57, -101, 14, -36, -26, 49}; + BigInteger aNumber = new BigInteger(aSign, aBytes); + BigInteger result = aNumber.flipBit(number); + byte resBytes[] = new byte[rBytes.length]; + resBytes = result.toByteArray(); + for(int i = 0; i < resBytes.length; i++) { + assertTrue(resBytes[i] == rBytes[i]); + } + assertEquals("incorrect sign", -1, result.signum()); + } + + /** + * flipBit(int n) the leftmost bit in a positive number + */ + public void testFlipBitLeftmostPositive() { + byte aBytes[] = {1, -128, 56, 100, -15, 35, 26}; + int aSign = 1; + int number = 48; + byte rBytes[] = {0, -128, 56, 100, -15, 35, 26}; + BigInteger aNumber = new BigInteger(aSign, aBytes); + BigInteger result = aNumber.flipBit(number); + byte resBytes[] = new byte[rBytes.length]; + resBytes = result.toByteArray(); + for(int i = 0; i < resBytes.length; i++) { + assertTrue(resBytes[i] == rBytes[i]); + } + assertEquals("incorrect sign", 1, result.signum()); + } + + /** + * flipBit(int n) inside a negative number + */ + public void testFlipBitNegativeInside1() { + byte aBytes[] = {1, -128, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26}; + int aSign = -1; + int number = 15; + byte rBytes[] = {-2, 127, -57, -101, 1, 75, -90, -46, -92, -4, 14, 92, -26}; + BigInteger aNumber = new BigInteger(aSign, aBytes); + BigInteger result = aNumber.flipBit(number); + byte resBytes[] = new byte[rBytes.length]; + resBytes = result.toByteArray(); + for(int i = 0; i < resBytes.length; i++) { + assertTrue(resBytes[i] == rBytes[i]); + } + assertEquals("incorrect sign", -1, result.signum()); + } + + /** + * flipBit(int n) inside a negative number + */ + public void testFlipBitNegativeInside2() { + byte aBytes[] = {1, -128, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26}; + int aSign = -1; + int number = 45; + byte rBytes[] = {-2, 127, -57, -101, 1, 75, -90, -14, -92, -4, 14, -36, -26}; + BigInteger aNumber = new BigInteger(aSign, aBytes); + BigInteger result = aNumber.flipBit(number); + byte resBytes[] = new byte[rBytes.length]; + resBytes = result.toByteArray(); + for(int i = 0; i < resBytes.length; i++) { + assertTrue(resBytes[i] == rBytes[i]); + } + assertEquals("incorrect sign", -1, result.signum()); + } + + /** + * flipBit(int n) inside a negative number with all ones in bit representation + */ + public void testFlipBitNegativeInside3() { + String as = "-18446744073709551615"; + String res = "-18446744073709551611"; + int number = 2; + BigInteger aNumber = new BigInteger(as); + BigInteger result = aNumber.flipBit(number); + assertEquals(res, result.toString()); + } + + /** + * flipBit(0) in the negative number of length 1 + * with all ones in bit representation. + * the resulting number's length is 2. + */ + public void testFlipBitNegativeInside4() { + String as = "-4294967295"; + String res = "-4294967296"; + int number = 0; + BigInteger aNumber = new BigInteger(as); + BigInteger result = aNumber.flipBit(number); + assertEquals(res, result.toString()); + } + + /** + * flipBit(0) in the negative number of length 2 + * with all ones in bit representation. + * the resulting number's length is 3. + */ + public void testFlipBitNegativeInside5() { + String as = "-18446744073709551615"; + String res = "-18446744073709551616"; + int number = 0; + BigInteger aNumber = new BigInteger(as); + BigInteger result = aNumber.flipBit(number); + assertEquals(res, result.toString()); + } + + /** + * flipBit(int n) outside a negative number + */ + public void testFlipBitNegativeOutside1() { + byte aBytes[] = {1, -128, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26}; + int aSign = -1; + int number = 150; + byte rBytes[] = {-65, -1, -1, -1, -1, -1, -2, 127, -57, -101, 1, 75, -90, -46, -92, -4, 14, -36, -26}; + BigInteger aNumber = new BigInteger(aSign, aBytes); + BigInteger result = aNumber.flipBit(number); + byte resBytes[] = new byte[rBytes.length]; + resBytes = result.toByteArray(); + for(int i = 0; i < resBytes.length; i++) { + assertTrue(resBytes[i] == rBytes[i]); + } + assertEquals("incorrect sign", -1, result.signum()); + } + + /** + * flipBit(int n) outside a negative number + */ + public void testFlipBitNegativeOutside2() { + byte aBytes[] = {1, -128, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26}; + int aSign = -1; + int number = 191; + byte rBytes[] = {-1, 127, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -2, 127, -57, -101, 1, 75, -90, -46, -92, -4, 14, -36, -26}; + BigInteger aNumber = new BigInteger(aSign, aBytes); + BigInteger result = aNumber.flipBit(number); + byte resBytes[] = new byte[rBytes.length]; + resBytes = result.toByteArray(); + for(int i = 0; i < resBytes.length; i++) { + assertTrue(resBytes[i] == rBytes[i]); + } + assertEquals("incorrect sign", -1, result.signum()); + } + + /** + * flipBit(int n) inside a positive number + */ + public void testFlipBitPositiveInside1() { + byte aBytes[] = {1, -128, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26}; + int aSign = 1; + int number = 15; + byte rBytes[] = {1, -128, 56, 100, -2, -76, 89, 45, 91, 3, -15, -93, 26}; + BigInteger aNumber = new BigInteger(aSign, aBytes); + BigInteger result = aNumber.flipBit(number); + byte resBytes[] = new byte[rBytes.length]; + resBytes = result.toByteArray(); + for(int i = 0; i < resBytes.length; i++) { + assertTrue(resBytes[i] == rBytes[i]); + } + assertEquals("incorrect sign", 1, result.signum()); + } + + /** + * flipBit(int n) inside a positive number + */ + public void testFlipBitPositiveInside2() { + byte aBytes[] = {1, -128, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26}; + int aSign = 1; + int number = 45; + byte rBytes[] = {1, -128, 56, 100, -2, -76, 89, 13, 91, 3, -15, 35, 26}; + BigInteger aNumber = new BigInteger(aSign, aBytes); + BigInteger result = aNumber.flipBit(number); + byte resBytes[] = new byte[rBytes.length]; + resBytes = result.toByteArray(); + for(int i = 0; i < resBytes.length; i++) { + assertTrue(resBytes[i] == rBytes[i]); + } + assertEquals("incorrect sign", 1, result.signum()); + } + + /** + * flipBit(int n) outside a positive number + */ + public void testFlipBitPositiveOutside1() { + byte aBytes[] = {1, -128, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26}; + int aSign = 1; + int number = 150; + byte rBytes[] = {64, 0, 0, 0, 0, 0, 1, -128, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26}; + BigInteger aNumber = new BigInteger(aSign, aBytes); + BigInteger result = aNumber.flipBit(number); + byte resBytes[] = new byte[rBytes.length]; + resBytes = result.toByteArray(); + for(int i = 0; i < resBytes.length; i++) { + assertTrue(resBytes[i] == rBytes[i]); + } + assertEquals("incorrect sign", 1, result.signum()); + } + + /** + * flipBit(int n) outside a positive number + */ + public void testFlipBitPositiveOutside2() { + byte aBytes[] = {1, -128, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26}; + int aSign = 1; + int number = 191; + byte rBytes[] = {0, -128, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, -128, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26}; + BigInteger aNumber = new BigInteger(aSign, aBytes); + BigInteger result = aNumber.flipBit(number); + byte resBytes[] = new byte[rBytes.length]; + resBytes = result.toByteArray(); + for(int i = 0; i < resBytes.length; i++) { + assertTrue(resBytes[i] == rBytes[i]); + } + assertEquals("incorrect sign", 1, result.signum()); + } + + /** + * setBit(int n) of a negative n + */ + public void testSetBitException() { + byte aBytes[] = {-1, -128, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26}; + int aSign = 1; + int number = -7; + BigInteger aNumber = new BigInteger(aSign, aBytes); + try { + aNumber.setBit(number); + fail("ArithmeticException has not been caught"); + } catch (ArithmeticException e) { + } + } + + /** + * setBit(int n) outside zero + */ + public void testSetBitZero() { + byte aBytes[] = {0}; + int aSign = 0; + int number = 0; + byte rBytes[] = {1}; + BigInteger aNumber = new BigInteger(aSign, aBytes); + BigInteger result = aNumber.setBit(number); + byte resBytes[] = new byte[rBytes.length]; + resBytes = result.toByteArray(); + for(int i = 0; i < resBytes.length; i++) { + assertTrue(resBytes[i] == rBytes[i]); + } + assertEquals("incorrect sign", 1, result.signum()); + } + + /** + * setBit(int n) outside zero + */ + public void testSetBitZeroOutside1() { + byte aBytes[] = {0}; + int aSign = 0; + int number = 95; + byte rBytes[] = {0, -128, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; + BigInteger aNumber = new BigInteger(aSign, aBytes); + BigInteger result = aNumber.setBit(number); + byte resBytes[] = new byte[rBytes.length]; + resBytes = result.toByteArray(); + for(int i = 0; i < resBytes.length; i++) { + assertTrue(resBytes[i] == rBytes[i]); + } + assertEquals("incorrect sign", 1, result.signum()); + } + + /** + * setBit(int n) inside a positive number + */ + public void testSetBitPositiveInside1() { + byte aBytes[] = {1, -128, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26}; + int aSign = 1; + int number = 20; + byte rBytes[] = {1, -128, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26}; + BigInteger aNumber = new BigInteger(aSign, aBytes); + BigInteger result = aNumber.setBit(number); + byte resBytes[] = new byte[rBytes.length]; + resBytes = result.toByteArray(); + for(int i = 0; i < resBytes.length; i++) { + assertTrue(resBytes[i] == rBytes[i]); + } + assertEquals("incorrect sign", 1, result.signum()); + } + + /** + * setBit(int n) inside a positive number + */ + public void testSetBitPositiveInside2() { + byte aBytes[] = {1, -128, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26}; + int aSign = 1; + int number = 17; + byte rBytes[] = {1, -128, 56, 100, -2, -76, 89, 45, 91, 3, -13, 35, 26}; + BigInteger aNumber = new BigInteger(aSign, aBytes); + BigInteger result = aNumber.setBit(number); + byte resBytes[] = new byte[rBytes.length]; + resBytes = result.toByteArray(); + for(int i = 0; i < resBytes.length; i++) { + assertTrue(resBytes[i] == rBytes[i]); + } + assertEquals("incorrect sign", 1, result.signum()); + } + + /** + * setBit(int n) inside a positive number + */ + public void testSetBitPositiveInside3() { + byte aBytes[] = {1, -128, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26}; + int aSign = 1; + int number = 45; + byte rBytes[] = {1, -128, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26}; + BigInteger aNumber = new BigInteger(aSign, aBytes); + BigInteger result = aNumber.setBit(number); + byte resBytes[] = new byte[rBytes.length]; + resBytes = result.toByteArray(); + for(int i = 0; i < resBytes.length; i++) { + assertTrue(resBytes[i] == rBytes[i]); + } + assertEquals("incorrect sign", 1, result.signum()); + } + + /** + * setBit(int n) inside a positive number + */ + public void testSetBitPositiveInside4 () { + byte aBytes[] = {1, -128, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26}; + int aSign = 1; + int number = 50; + byte rBytes[] = {1, -128, 56, 100, -2, -76, 93, 45, 91, 3, -15, 35, 26}; + BigInteger aNumber = new BigInteger(aSign, aBytes); + BigInteger result = aNumber.setBit(number); + byte resBytes[] = new byte[rBytes.length]; + resBytes = result.toByteArray(); + for(int i = 0; i < resBytes.length; i++) { + assertTrue(resBytes[i] == rBytes[i]); + } + assertEquals("incorrect sign", 1, result.signum()); + } + + /** + * setBit(int n) outside a positive number + */ + public void testSetBitPositiveOutside1() { + byte aBytes[] = {1, -128, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26}; + int aSign = 1; + int number = 150; + byte rBytes[] = {64, 0, 0, 0, 0, 0, 1, -128, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26}; + BigInteger aNumber = new BigInteger(aSign, aBytes); + BigInteger result = aNumber.setBit(number); + byte resBytes[] = new byte[rBytes.length]; + resBytes = result.toByteArray(); + for(int i = 0; i < resBytes.length; i++) { + assertTrue(resBytes[i] == rBytes[i]); + } + assertEquals("incorrect sign", 1, result.signum()); + } + + /** + * setBit(int n) outside a positive number + */ + public void testSetBitPositiveOutside2() { + byte aBytes[] = {1, -128, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26}; + int aSign = 1; + int number = 223; + byte rBytes[] = {0, -128, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, -128, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26}; + BigInteger aNumber = new BigInteger(aSign, aBytes); + BigInteger result = aNumber.setBit(number); + byte resBytes[] = new byte[rBytes.length]; + resBytes = result.toByteArray(); + for(int i = 0; i < resBytes.length; i++) { + assertTrue(resBytes[i] == rBytes[i]); + } + assertEquals("incorrect sign", 1, result.signum()); + } + + /** + * setBit(int n) the leftmost bit in a positive number + */ + public void testSetBitTopPositive() { + byte aBytes[] = {1, -128, 56, 100, -15, 35, 26}; + int aSign = 1; + int number = 63; + byte rBytes[] = {0, -128, 1, -128, 56, 100, -15, 35, 26}; + BigInteger aNumber = new BigInteger(aSign, aBytes); + BigInteger result = aNumber.setBit(number); + byte resBytes[] = new byte[rBytes.length]; + resBytes = result.toByteArray(); + for(int i = 0; i < resBytes.length; i++) { + assertTrue(resBytes[i] == rBytes[i]); + } + assertEquals("incorrect sign", 1, result.signum()); + } + + /** + * setBit(int n) the leftmost bit in a negative number + */ + public void testSetBitLeftmostNegative() { + byte aBytes[] = {1, -128, 56, 100, -15, 35, 26}; + int aSign = -1; + int number = 48; + byte rBytes[] = {-1, 127, -57, -101, 14, -36, -26, 49}; + BigInteger aNumber = new BigInteger(aSign, aBytes); + BigInteger result = aNumber.setBit(number); + byte resBytes[] = new byte[rBytes.length]; + resBytes = result.toByteArray(); + for(int i = 0; i < resBytes.length; i++) { + assertTrue(resBytes[i] == rBytes[i]); + } + assertEquals("incorrect sign", -1, result.signum()); + } + + /** + * setBit(int n) inside a negative number + */ + public void testSetBitNegativeInside1() { + byte aBytes[] = {1, -128, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26}; + int aSign = -1; + int number = 15; + byte rBytes[] = {-2, 127, -57, -101, 1, 75, -90, -46, -92, -4, 14, -36, -26}; + BigInteger aNumber = new BigInteger(aSign, aBytes); + BigInteger result = aNumber.setBit(number); + byte resBytes[] = new byte[rBytes.length]; + resBytes = result.toByteArray(); + for(int i = 0; i < resBytes.length; i++) { + assertTrue(resBytes[i] == rBytes[i]); + } + assertEquals("incorrect sign", -1, result.signum()); + } + + /** + * setBit(int n) inside a negative number + */ + public void testSetBitNegativeInside2() { + byte aBytes[] = {1, -128, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26}; + int aSign = -1; + int number = 44; + byte rBytes[] = {-2, 127, -57, -101, 1, 75, -90, -46, -92, -4, 14, -36, -26}; + BigInteger aNumber = new BigInteger(aSign, aBytes); + BigInteger result = aNumber.setBit(number); + byte resBytes[] = new byte[rBytes.length]; + resBytes = result.toByteArray(); + for(int i = 0; i < resBytes.length; i++) { + assertTrue(resBytes[i] == rBytes[i]); + } + assertEquals("incorrect sign", -1, result.signum()); + } + + /** + * setBit(int n) inside a negative number with all ones in bit representation + */ + public void testSetBitNegativeInside3() { + String as = "-18446744073709551615"; + String res = "-18446744073709551611"; + int number = 2; + BigInteger aNumber = new BigInteger(as); + BigInteger result = aNumber.setBit(number); + assertEquals(res, result.toString()); + } + + /** + * setBit(0) in the negative number of length 1 + * with all ones in bit representation. + * the resulting number's length is 2. + */ + public void testSetBitNegativeInside4() { + String as = "-4294967295"; + int number = 0; + BigInteger aNumber = new BigInteger(as); + BigInteger result = aNumber.setBit(number); + assertEquals(as, result.toString()); + } + + /** + * setBit(0) in the negative number of length 2 + * with all ones in bit representation. + * the resulting number's length is 3. + */ + public void testSetBitNegativeInside5() { + String as = "-18446744073709551615"; + int number = 0; + BigInteger aNumber = new BigInteger(as); + BigInteger result = aNumber.setBit(number); + assertEquals(as, result.toString()); + } + + /** + * setBit(int n) outside a negative number + */ + public void testSetBitNegativeOutside1() { + byte aBytes[] = {1, -128, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26}; + int aSign = -1; + int number = 150; + byte rBytes[] = {-2, 127, -57, -101, 1, 75, -90, -46, -92, -4, 14, -36, -26}; + BigInteger aNumber = new BigInteger(aSign, aBytes); + BigInteger result = aNumber.setBit(number); + byte resBytes[] = new byte[rBytes.length]; + resBytes = result.toByteArray(); + for(int i = 0; i < resBytes.length; i++) { + assertTrue(resBytes[i] == rBytes[i]); + } + assertEquals("incorrect sign", -1, result.signum()); + } + + /** + * setBit(int n) outside a negative number + */ + public void testSetBitNegativeOutside2() { + byte aBytes[] = {1, -128, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26}; + int aSign = -1; + int number = 191; + byte rBytes[] = {-2, 127, -57, -101, 1, 75, -90, -46, -92, -4, 14, -36, -26}; + BigInteger aNumber = new BigInteger(aSign, aBytes); + BigInteger result = aNumber.setBit(number); + byte resBytes[] = new byte[rBytes.length]; + resBytes = result.toByteArray(); + for(int i = 0; i < resBytes.length; i++) { + assertTrue(resBytes[i] == rBytes[i]); + } + assertEquals("incorrect sign", -1, result.signum()); + } + + /** + * setBit: check the case when the number of bit to be set can be + * represented as n * 32 + 31, where n is an arbitrary integer. + * Here 191 = 5 * 32 + 31 + */ + public void testSetBitBug1331() { + BigInteger result = BigInteger.valueOf(0L).setBit(191); + assertEquals("incorrect value", "3138550867693340381917894711603833208051177722232017256448", result.toString()); + assertEquals("incorrect sign", 1, result.signum()); + } + + /** + * shiftLeft(int n), n = 0 + */ + public void testShiftLeft1() { + byte aBytes[] = {1, -128, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26}; + int aSign = 1; + int number = 0; + byte rBytes[] = {1, -128, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26}; + BigInteger aNumber = new BigInteger(aSign, aBytes); + BigInteger result = aNumber.shiftLeft(number); + byte resBytes[] = new byte[rBytes.length]; + resBytes = result.toByteArray(); + for(int i = 0; i < resBytes.length; i++) { + assertTrue(resBytes[i] == rBytes[i]); + } + assertEquals("incorrect sign", 1, result.signum()); + } + + /** + * shiftLeft(int n), n < 0 + */ + public void testShiftLeft2() { + byte aBytes[] = {1, -128, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26}; + int aSign = 1; + int number = -27; + byte rBytes[] = {48, 7, 12, -97, -42, -117, 37, -85, 96}; + BigInteger aNumber = new BigInteger(aSign, aBytes); + BigInteger result = aNumber.shiftLeft(number); + byte resBytes[] = new byte[rBytes.length]; + resBytes = result.toByteArray(); + for(int i = 0; i < resBytes.length; i++) { + assertTrue(resBytes[i] == rBytes[i]); + } + assertEquals("incorrect sign", 1, result.signum()); + } + + /** + * shiftLeft(int n) a positive number, n > 0 + */ + public void testShiftLeft3() { + byte aBytes[] = {1, -128, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26}; + int aSign = 1; + int number = 27; + byte rBytes[] = {12, 1, -61, 39, -11, -94, -55, 106, -40, 31, -119, 24, -48, 0, 0, 0}; + BigInteger aNumber = new BigInteger(aSign, aBytes); + BigInteger result = aNumber.shiftLeft(number); + byte resBytes[] = new byte[rBytes.length]; + resBytes = result.toByteArray(); + for(int i = 0; i < resBytes.length; i++) { + assertTrue(resBytes[i] == rBytes[i]); + } + assertEquals("incorrect sign", 1, result.signum()); + } + + /** + * shiftLeft(int n) a positive number, n > 0 + */ + public void testShiftLeft4() { + byte aBytes[] = {1, -128, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26}; + int aSign = 1; + int number = 45; + byte rBytes[] = {48, 7, 12, -97, -42, -117, 37, -85, 96, 126, 36, 99, 64, 0, 0, 0, 0, 0}; + BigInteger aNumber = new BigInteger(aSign, aBytes); + BigInteger result = aNumber.shiftLeft(number); + byte resBytes[] = new byte[rBytes.length]; + resBytes = result.toByteArray(); + for(int i = 0; i < resBytes.length; i++) { + assertTrue(resBytes[i] == rBytes[i]); + } + assertEquals("incorrect sign", 1, result.signum()); + } + + /** + * shiftLeft(int n) a negative number, n > 0 + */ + public void testShiftLeft5() { + byte aBytes[] = {1, -128, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26}; + int aSign = -1; + int number = 45; + byte rBytes[] = {-49, -8, -13, 96, 41, 116, -38, 84, -97, -127, -37, -100, -64, 0, 0, 0, 0, 0}; + BigInteger aNumber = new BigInteger(aSign, aBytes); + BigInteger result = aNumber.shiftLeft(number); + byte resBytes[] = new byte[rBytes.length]; + resBytes = result.toByteArray(); + for(int i = 0; i < resBytes.length; i++) { + assertTrue(resBytes[i] == rBytes[i]); + } + assertEquals("incorrect sign", -1, result.signum()); + } + + /** + * shiftRight(int n), n = 0 + */ + public void testShiftRight1() { + byte aBytes[] = {1, -128, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26}; + int aSign = 1; + int number = 0; + byte rBytes[] = {1, -128, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26}; + BigInteger aNumber = new BigInteger(aSign, aBytes); + BigInteger result = aNumber.shiftRight(number); + byte resBytes[] = new byte[rBytes.length]; + resBytes = result.toByteArray(); + for(int i = 0; i < resBytes.length; i++) { + assertTrue(resBytes[i] == rBytes[i]); + } + assertEquals("incorrect sign", 1, result.signum()); + } + + /** + * shiftRight(int n), n < 0 + */ + public void testShiftRight2() { + byte aBytes[] = {1, -128, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26}; + int aSign = 1; + int number = -27; + byte rBytes[] = {12, 1, -61, 39, -11, -94, -55, 106, -40, 31, -119, 24, -48, 0, 0, 0}; + BigInteger aNumber = new BigInteger(aSign, aBytes); + BigInteger result = aNumber.shiftRight(number); + byte resBytes[] = new byte[rBytes.length]; + resBytes = result.toByteArray(); + for(int i = 0; i < resBytes.length; i++) { + assertTrue(resBytes[i] == rBytes[i]); + } + assertEquals("incorrect sign", 1, result.signum()); + } + + /** + * shiftRight(int n), 0 < n < 32 + */ + public void testShiftRight3() { + byte aBytes[] = {1, -128, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26}; + int aSign = 1; + int number = 27; + byte rBytes[] = {48, 7, 12, -97, -42, -117, 37, -85, 96}; + BigInteger aNumber = new BigInteger(aSign, aBytes); + BigInteger result = aNumber.shiftRight(number); + byte resBytes[] = new byte[rBytes.length]; + resBytes = result.toByteArray(); + for(int i = 0; i < resBytes.length; i++) { + assertTrue(resBytes[i] == rBytes[i]); + } + assertEquals("incorrect sign", 1, result.signum()); + } + + /** + * shiftRight(int n), n > 32 + */ + public void testShiftRight4() { + byte aBytes[] = {1, -128, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26}; + int aSign = 1; + int number = 45; + byte rBytes[] = {12, 1, -61, 39, -11, -94, -55}; + BigInteger aNumber = new BigInteger(aSign, aBytes); + BigInteger result = aNumber.shiftRight(number); + byte resBytes[] = new byte[rBytes.length]; + resBytes = result.toByteArray(); + for(int i = 0; i < resBytes.length; i++) { + assertTrue(resBytes[i] == rBytes[i]); + } + assertEquals("incorrect sign", 1, result.signum()); + } + + /** + * shiftRight(int n), n is greater than bitLength() + */ + public void testShiftRight5() { + byte aBytes[] = {1, -128, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26}; + int aSign = 1; + int number = 300; + byte rBytes[] = {0}; + BigInteger aNumber = new BigInteger(aSign, aBytes); + BigInteger result = aNumber.shiftRight(number); + byte resBytes[] = new byte[rBytes.length]; + resBytes = result.toByteArray(); + for(int i = 0; i < resBytes.length; i++) { + assertTrue(resBytes[i] == rBytes[i]); + } + assertEquals("incorrect sign", 0, result.signum()); + } + + /** + * shiftRight a negative number; + * shift distance is multiple of 32; + * shifted bits are NOT zeroes. + */ + public void testShiftRightNegNonZeroesMul32() { + byte aBytes[] = {1, -128, 56, 100, -2, -76, 89, 45, 91, 1, 0, 0, 0, 0, 0, 0, 0}; + int aSign = -1; + int number = 64; + byte rBytes[] = {-2, 127, -57, -101, 1, 75, -90, -46, -92}; + BigInteger aNumber = new BigInteger(aSign, aBytes); + BigInteger result = aNumber.shiftRight(number); + byte resBytes[] = new byte[rBytes.length]; + resBytes = result.toByteArray(); + for(int i = 0; i < resBytes.length; i++) { + assertTrue(resBytes[i] == rBytes[i]); + } + assertEquals("incorrect sign", -1, result.signum()); + } + + /** + * shiftRight a negative number; + * shift distance is NOT multiple of 32; + * shifted bits are NOT zeroes. + */ + public void testShiftRightNegNonZeroes() { + byte aBytes[] = {1, -128, 56, 100, -2, -76, 89, 45, 91, 0, 0, 0, 0, 0, 0, 0, 0}; + int aSign = -1; + int number = 68; + byte rBytes[] = {-25, -4, 121, -80, 20, -70, 109, 42}; + BigInteger aNumber = new BigInteger(aSign, aBytes); + BigInteger result = aNumber.shiftRight(number); + byte resBytes[] = new byte[rBytes.length]; + resBytes = result.toByteArray(); + for(int i = 0; i < resBytes.length; i++) { + assertTrue(resBytes[i] == rBytes[i]); + } + assertEquals("incorrect sign", -1, result.signum()); + } + + /** + * shiftRight a negative number; + * shift distance is NOT multiple of 32; + * shifted bits are zeroes. + */ + public void testShiftRightNegZeroes() { + byte aBytes[] = {1, -128, 56, 100, -2, -76, 89, 45, 0, 0, 0, 0, 0, 0, 0, 0, 0}; + int aSign = -1; + int number = 68; + byte rBytes[] = {-25, -4, 121, -80, 20, -70, 109, 48}; + BigInteger aNumber = new BigInteger(aSign, aBytes); + BigInteger result = aNumber.shiftRight(number); + byte resBytes[] = new byte[rBytes.length]; + resBytes = result.toByteArray(); + for(int i = 0; i < resBytes.length; i++) { + assertTrue(resBytes[i] == rBytes[i]); + } + assertEquals("incorrect sign", -1, result.signum()); + } + + /** + * shiftRight a negative number; + * shift distance is multiple of 32; + * shifted bits are zeroes. + */ + public void testShiftRightNegZeroesMul32() { + byte aBytes[] = {1, -128, 56, 100, -2, -76, 89, 45, 91, 0, 0, 0, 0, 0, 0, 0, 0}; + int aSign = -1; + int number = 64; + byte rBytes[] = {-2, 127, -57, -101, 1, 75, -90, -46, -91}; + BigInteger aNumber = new BigInteger(aSign, aBytes); + BigInteger result = aNumber.shiftRight(number); + byte resBytes[] = new byte[rBytes.length]; + resBytes = result.toByteArray(); + for(int i = 0; i < resBytes.length; i++) { + assertTrue(resBytes[i] == rBytes[i]); + } + assertEquals("incorrect sign", -1, result.signum()); + } + + /** + * testBit(int n) of a negative n + */ + public void testTestBitException() { + byte aBytes[] = {-1, -128, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26}; + int aSign = 1; + int number = -7; + BigInteger aNumber = new BigInteger(aSign, aBytes); + try { + aNumber.testBit(number); + fail("ArithmeticException has not been caught"); + } catch (ArithmeticException e) { + } + } + + /** + * testBit(int n) of a positive number + */ + public void testTestBitPositive1() { + byte aBytes[] = {-1, -128, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26}; + int aSign = 1; + int number = 7; + BigInteger aNumber = new BigInteger(aSign, aBytes); + assertTrue(!aNumber.testBit(number)); + } + + /** + * testBit(int n) of a positive number + */ + public void testTestBitPositive2() { + byte aBytes[] = {-1, -128, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26}; + int aSign = 1; + int number = 45; + BigInteger aNumber = new BigInteger(aSign, aBytes); + assertTrue(aNumber.testBit(number)); + } + + /** + * testBit(int n) of a positive number, n > bitLength() + */ + public void testTestBitPositive3() { + byte aBytes[] = {-1, -128, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26}; + int aSign = 1; + int number = 300; + BigInteger aNumber = new BigInteger(aSign, aBytes); + assertTrue(!aNumber.testBit(number)); + } + + /** + * testBit(int n) of a negative number + */ + public void testTestBitNegative1() { + byte aBytes[] = {-1, -128, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26}; + int aSign = -1; + int number = 7; + BigInteger aNumber = new BigInteger(aSign, aBytes); + assertTrue(aNumber.testBit(number)); + } + + /** + * testBit(int n) of a positive n + */ + public void testTestBitNegative2() { + byte aBytes[] = {-1, -128, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26}; + int aSign = -1; + int number = 45; + BigInteger aNumber = new BigInteger(aSign, aBytes); + assertTrue(!aNumber.testBit(number)); + } + + /** + * testBit(int n) of a positive n, n > bitLength() + */ + public void testTestBitNegative3() { + byte aBytes[] = {-1, -128, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26}; + int aSign = -1; + int number = 300; + BigInteger aNumber = new BigInteger(aSign, aBytes); + assertTrue(aNumber.testBit(number)); + } +} diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/math/BigIntegerOrTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/math/BigIntegerOrTest.java new file mode 100644 index 0000000..3509643 --- /dev/null +++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/math/BigIntegerOrTest.java @@ -0,0 +1,419 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 Elena Semukhina + */ + +package org.apache.harmony.tests.java.math; + +import junit.framework.TestCase; +import java.math.BigInteger; + +/** + * Class: java.math.BigInteger + * Method: or + */ +public class BigIntegerOrTest extends TestCase { + /** + * Or for zero and a positive number + */ + public void testZeroPos() { + byte aBytes[] = {0}; + byte bBytes[] = {-2, -3, -4, -4, 5, 14, 23, 39, 48, 57, 66, 5, 14, 23}; + int aSign = 0; + int bSign = 1; + byte rBytes[] = {0, -2, -3, -4, -4, 5, 14, 23, 39, 48, 57, 66, 5, 14, 23}; + BigInteger aNumber = new BigInteger(aSign, aBytes); + BigInteger bNumber = new BigInteger(bSign, bBytes); + BigInteger result = aNumber.or(bNumber); + byte resBytes[] = new byte[rBytes.length]; + resBytes = result.toByteArray(); + for(int i = 0; i < resBytes.length; i++) { + assertTrue(resBytes[i] == rBytes[i]); + } + assertEquals("incorrect sign", 1, result.signum()); + } + + /** + * Or for zero and a negative number + */ + public void testZeroNeg() { + byte aBytes[] = {0}; + byte bBytes[] = {-2, -3, -4, -4, 5, 14, 23, 39, 48, 57, 66, 5, 14, 23}; + int aSign = 0; + int bSign = -1; + byte rBytes[] = {-1, 1, 2, 3, 3, -6, -15, -24, -40, -49, -58, -67, -6, -15, -23}; + BigInteger aNumber = new BigInteger(aSign, aBytes); + BigInteger bNumber = new BigInteger(bSign, bBytes); + BigInteger result = aNumber.or(bNumber); + byte resBytes[] = new byte[rBytes.length]; + resBytes = result.toByteArray(); + for(int i = 0; i < resBytes.length; i++) { + assertTrue(resBytes[i] == rBytes[i]); + } + assertEquals("incorrect sign", -1, result.signum()); + } + + /** + * Or for a positive number and zero + */ + public void testPosZero() { + byte aBytes[] = {-2, -3, -4, -4, 5, 14, 23, 39, 48, 57, 66, 5, 14, 23}; + byte bBytes[] = {0}; + int aSign = 1; + int bSign = 0; + byte rBytes[] = {0, -2, -3, -4, -4, 5, 14, 23, 39, 48, 57, 66, 5, 14, 23}; + BigInteger aNumber = new BigInteger(aSign, aBytes); + BigInteger bNumber = new BigInteger(bSign, bBytes); + BigInteger result = aNumber.or(bNumber); + byte resBytes[] = new byte[rBytes.length]; + resBytes = result.toByteArray(); + for(int i = 0; i < resBytes.length; i++) { + assertTrue(resBytes[i] == rBytes[i]); + } + assertEquals("incorrect sign", 1, result.signum()); + } + + /** + * Or for a negative number and zero + */ + public void testNegPos() { + byte aBytes[] = {-2, -3, -4, -4, 5, 14, 23, 39, 48, 57, 66, 5, 14, 23}; + byte bBytes[] = {0}; + int aSign = -1; + int bSign = 0; + byte rBytes[] = {-1, 1, 2, 3, 3, -6, -15, -24, -40, -49, -58, -67, -6, -15, -23}; + BigInteger aNumber = new BigInteger(aSign, aBytes); + BigInteger bNumber = new BigInteger(bSign, bBytes); + BigInteger result = aNumber.or(bNumber); + byte resBytes[] = new byte[rBytes.length]; + resBytes = result.toByteArray(); + for(int i = 0; i < resBytes.length; i++) { + assertTrue(resBytes[i] == rBytes[i]); + } + assertEquals("incorrect sign", -1, result.signum()); + } + + /** + * Or for zero and zero + */ + public void testZeroZero() { + byte aBytes[] = {0}; + byte bBytes[] = {0}; + int aSign = 0; + int bSign = 0; + byte rBytes[] = {0}; + BigInteger aNumber = new BigInteger(aSign, aBytes); + BigInteger bNumber = new BigInteger(bSign, bBytes); + BigInteger result = aNumber.or(bNumber); + byte resBytes[] = new byte[rBytes.length]; + resBytes = result.toByteArray(); + for(int i = 0; i < resBytes.length; i++) { + assertTrue(resBytes[i] == rBytes[i]); + } + assertEquals("incorrect sign", 0, result.signum()); + } + + /** + * Or for zero and one + */ + public void testZeroOne() { + byte aBytes[] = {0}; + byte bBytes[] = {1}; + int aSign = 0; + int bSign = 1; + byte rBytes[] = {1}; + BigInteger aNumber = new BigInteger(aSign, aBytes); + BigInteger bNumber = new BigInteger(bSign, bBytes); + BigInteger result = aNumber.or(bNumber); + byte resBytes[] = new byte[rBytes.length]; + resBytes = result.toByteArray(); + for(int i = 0; i < resBytes.length; i++) { + assertTrue(resBytes[i] == rBytes[i]); + } + assertEquals("incorrect sign", 1, result.signum()); + } + + /** + * Or for one and one + */ + public void testOneOne() { + byte aBytes[] = {1}; + byte bBytes[] = {1}; + int aSign = 1; + int bSign = 1; + byte rBytes[] = {1}; + BigInteger aNumber = new BigInteger(aSign, aBytes); + BigInteger bNumber = new BigInteger(bSign, bBytes); + BigInteger result = aNumber.or(bNumber); + byte resBytes[] = new byte[rBytes.length]; + resBytes = result.toByteArray(); + for(int i = 0; i < resBytes.length; i++) { + assertTrue(resBytes[i] == rBytes[i]); + } + assertEquals("incorrect sign", 1, result.signum()); + } + + /** + * Or for two positive numbers of the same length + */ + public void testPosPosSameLength() { + byte aBytes[] = {-128, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26, -117}; + byte bBytes[] = {-2, -3, -4, -4, 5, 14, 23, 39, 48, 57, 66, 5, 14, 23}; + int aSign = 1; + int bSign = 1; + byte rBytes[] = {0, -2, -3, -4, -4, -1, -66, 95, 47, 123, 59, -13, 39, 30, -97}; + BigInteger aNumber = new BigInteger(aSign, aBytes); + BigInteger bNumber = new BigInteger(bSign, bBytes); + BigInteger result = aNumber.or(bNumber); + byte resBytes[] = new byte[rBytes.length]; + resBytes = result.toByteArray(); + for(int i = 0; i < resBytes.length; i++) { + assertTrue(resBytes[i] == rBytes[i]); + } + assertEquals("incorrect sign", 1, result.signum()); + } + + /** + * Or for two positive numbers; the first is longer + */ + public void testPosPosFirstLonger() { + byte aBytes[] = {-128, 9, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26, -117, 23, 87, -25, -75}; + byte bBytes[] = {-2, -3, -4, -4, 5, 14, 23, 39, 48, 57, 66, 5, 14, 23}; + int aSign = 1; + int bSign = 1; + byte rBytes[] = {0, -128, 9, 56, 100, -2, -3, -3, -3, 95, 15, -9, 39, 58, -69, 87, 87, -17, -73}; + BigInteger aNumber = new BigInteger(aSign, aBytes); + BigInteger bNumber = new BigInteger(bSign, bBytes); + BigInteger result = aNumber.or(bNumber); + byte resBytes[] = new byte[rBytes.length]; + resBytes = result.toByteArray(); + for(int i = 0; i < resBytes.length; i++) { + assertTrue(resBytes[i] == rBytes[i]); + } + assertEquals("incorrect sign", 1, result.signum()); + } + + /** + * Or for two positive numbers; the first is shorter + */ + public void testPosPosFirstShorter() { + byte aBytes[] = {-2, -3, -4, -4, 5, 14, 23, 39, 48, 57, 66, 5, 14, 23}; + byte bBytes[] = {-128, 9, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26, -117, 23, 87, -25, -75}; + int aSign = 1; + int bSign = 1; + byte rBytes[] = {0, -128, 9, 56, 100, -2, -3, -3, -3, 95, 15, -9, 39, 58, -69, 87, 87, -17, -73}; + BigInteger aNumber = new BigInteger(aSign, aBytes); + BigInteger bNumber = new BigInteger(bSign, bBytes); + BigInteger result = aNumber.or(bNumber); + byte resBytes[] = new byte[rBytes.length]; + resBytes = result.toByteArray(); + for(int i = 0; i < resBytes.length; i++) { + assertTrue(resBytes[i] == rBytes[i]); + } + assertEquals("incorrect sign", 1, result.signum()); + } + + /** + * Or for two negative numbers of the same length + */ + public void testNegNegSameLength() { + byte aBytes[] = {-128, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26, -117}; + byte bBytes[] = {-2, -3, -4, -4, 5, 14, 23, 39, 48, 57, 66, 5, 14, 23}; + int aSign = -1; + int bSign = -1; + byte rBytes[] = {-1, 127, -57, -101, -5, -5, -18, -38, -17, -2, -65, -2, -11, -3}; + BigInteger aNumber = new BigInteger(aSign, aBytes); + BigInteger bNumber = new BigInteger(bSign, bBytes); + BigInteger result = aNumber.or(bNumber); + byte resBytes[] = new byte[rBytes.length]; + resBytes = result.toByteArray(); + for(int i = 0; i < resBytes.length; i++) { + assertTrue(resBytes[i] == rBytes[i]); + } + assertEquals("incorrect sign", -1, result.signum()); + } + + /** + * Or for two negative numbers; the first is longer + */ + public void testNegNegFirstLonger() { + byte aBytes[] = {-128, 9, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26, -117, 23, 87, -25, -75}; + byte bBytes[] = {-2, -3, -4, -4, 5, 14, 23, 39, 48, 57, 66, 5, 14, 23}; + int aSign = -1; + int bSign = -1; + byte rBytes[] = {-1, 1, 75, -89, -45, -2, -3, -18, -36, -17, -10, -3, -6, -7, -21}; + BigInteger aNumber = new BigInteger(aSign, aBytes); + BigInteger bNumber = new BigInteger(bSign, bBytes); + BigInteger result = aNumber.or(bNumber); + byte resBytes[] = new byte[rBytes.length]; + resBytes = result.toByteArray(); + for(int i = 0; i < resBytes.length; i++) { + assertTrue(resBytes[i] == rBytes[i]); + } + assertEquals("incorrect sign", -1, result.signum()); + } + + /** + * Or for two negative numbers; the first is shorter + */ + public void testNegNegFirstShorter() { + byte aBytes[] = {-2, -3, -4, -4, 5, 14, 23, 39, 48, 57, 66, 5, 14, 23}; + byte bBytes[] = {-128, 9, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26, -117, 23, 87, -25, -75}; + int aSign = -1; + int bSign = -1; + byte rBytes[] = {-1, 1, 75, -89, -45, -2, -3, -18, -36, -17, -10, -3, -6, -7, -21}; + BigInteger aNumber = new BigInteger(aSign, aBytes); + BigInteger bNumber = new BigInteger(bSign, bBytes); + BigInteger result = aNumber.or(bNumber); + byte resBytes[] = new byte[rBytes.length]; + resBytes = result.toByteArray(); + for(int i = 0; i < resBytes.length; i++) { + assertTrue(resBytes[i] == rBytes[i]); + } + assertEquals("incorrect sign", -1, result.signum()); + } + + /** + * Or for two numbers of different signs and the same length + */ + public void testPosNegSameLength() { + byte aBytes[] = {-128, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26, -117}; + byte bBytes[] = {-2, -3, -4, -4, 5, 14, 23, 39, 48, 57, 66, 5, 14, 23}; + int aSign = 1; + int bSign = -1; + byte rBytes[] = {-1, 1, -126, 59, 103, -2, -11, -7, -3, -33, -57, -3, -5, -5, -21}; + BigInteger aNumber = new BigInteger(aSign, aBytes); + BigInteger bNumber = new BigInteger(bSign, bBytes); + BigInteger result = aNumber.or(bNumber); + byte resBytes[] = new byte[rBytes.length]; + resBytes = result.toByteArray(); + for(int i = 0; i < resBytes.length; i++) { + assertTrue(resBytes[i] == rBytes[i]); + } + assertEquals("incorrect sign", -1, result.signum()); + } + + /** + * Or for two numbers of different signs and the same length + */ + public void testNegPosSameLength() { + byte aBytes[] = {-128, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26, -117}; + byte bBytes[] = {-2, -3, -4, -4, 5, 14, 23, 39, 48, 57, 66, 5, 14, 23}; + int aSign = -1; + int bSign = 1; + byte rBytes[] = {-1, 5, 79, -73, -9, -76, -3, 78, -35, -17, 119}; + BigInteger aNumber = new BigInteger(aSign, aBytes); + BigInteger bNumber = new BigInteger(bSign, bBytes); + BigInteger result = aNumber.or(bNumber); + byte resBytes[] = new byte[rBytes.length]; + resBytes = result.toByteArray(); + for(int i = 0; i < resBytes.length; i++) { + assertTrue(resBytes[i] == rBytes[i]); + } + assertEquals("incorrect sign", -1, result.signum()); + } + + /** + * Or for a negative and a positive numbers; the first is longer + */ + public void testNegPosFirstLonger() { + byte aBytes[] = {-128, 9, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26, -117, 23, 87, -25, -75}; + byte bBytes[] = {-2, -3, -4, -4, 5, 14, 23, 39, 48, 57, 66, 5, 14, 23}; + int aSign = -1; + int bSign = 1; + byte rBytes[] = {-1, 127, -10, -57, -101, -1, -1, -2, -2, -91, -2, 31, -1, -11, 125, -22, -83, 30, 95}; + BigInteger aNumber = new BigInteger(aSign, aBytes); + BigInteger bNumber = new BigInteger(bSign, bBytes); + BigInteger result = aNumber.or(bNumber); + byte resBytes[] = new byte[rBytes.length]; + resBytes = result.toByteArray(); + for(int i = 0; i < resBytes.length; i++) { + assertTrue(resBytes[i] == rBytes[i]); + } + assertEquals("incorrect sign", -1, result.signum()); + } + + /** + * Or for two negative numbers; the first is shorter + */ + public void testNegPosFirstShorter() { + byte aBytes[] = {-2, -3, -4, -4, 5, 14, 23, 39, 48, 57, 66, 5, 14, 23}; + byte bBytes[] = {-128, 9, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26, -117, 23, 87, -25, -75}; + int aSign = -1; + int bSign = 1; + byte rBytes[] = {-74, 91, 47, -5, -13, -7, -5, -33, -49, -65, -1, -9, -3}; + BigInteger aNumber = new BigInteger(aSign, aBytes); + BigInteger bNumber = new BigInteger(bSign, bBytes); + BigInteger result = aNumber.or(bNumber); + byte resBytes[] = new byte[rBytes.length]; + resBytes = result.toByteArray(); + for(int i = 0; i < resBytes.length; i++) { + assertTrue(resBytes[i] == rBytes[i]); + } + assertEquals("incorrect sign", -1, result.signum()); + } + + /** + * Or for a positive and a negative numbers; the first is longer + */ + public void testPosNegFirstLonger() { + byte aBytes[] = {-128, 9, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26, -117, 23, 87, -25, -75}; + byte bBytes[] = {-2, -3, -4, -4, 5, 14, 23, 39, 48, 57, 66, 5, 14, 23}; + int aSign = 1; + int bSign = -1; + byte rBytes[] = {-74, 91, 47, -5, -13, -7, -5, -33, -49, -65, -1, -9, -3}; + BigInteger aNumber = new BigInteger(aSign, aBytes); + BigInteger bNumber = new BigInteger(bSign, bBytes); + BigInteger result = aNumber.or(bNumber); + byte resBytes[] = new byte[rBytes.length]; + resBytes = result.toByteArray(); + for(int i = 0; i < resBytes.length; i++) { + assertTrue(resBytes[i] == rBytes[i]); + } + assertEquals("incorrect sign", -1, result.signum()); + } + + /** + * Or for a positive and a negative number; the first is shorter + */ + public void testPosNegFirstShorter() { + byte aBytes[] = {-2, -3, -4, -4, 5, 14, 23, 39, 48, 57, 66, 5, 14, 23}; + byte bBytes[] = {-128, 9, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26, -117, 23, 87, -25, -75}; + int aSign = 1; + int bSign = -1; + byte rBytes[] = {-1, 127, -10, -57, -101, -1, -1, -2, -2, -91, -2, 31, -1, -11, 125, -22, -83, 30, 95}; + BigInteger aNumber = new BigInteger(aSign, aBytes); + BigInteger bNumber = new BigInteger(bSign, bBytes); + BigInteger result = aNumber.or(bNumber); + byte resBytes[] = new byte[rBytes.length]; + resBytes = result.toByteArray(); + for(int i = 0; i < resBytes.length; i++) { + assertTrue(resBytes[i] == rBytes[i]); + } + assertEquals("incorrect sign", -1, result.signum()); + } + + public void testRegression() { + // Regression test for HARMONY-1996 + BigInteger x = new BigInteger("-1023"); + BigInteger r1 = x.and((BigInteger.ZERO.not()).shiftLeft(32)); + BigInteger r3 = x.and((BigInteger.ZERO.not().shiftLeft(32) ).not()); + BigInteger result = r1.or(r3); + assertEquals(x, result); + } +} diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/math/BigIntegerSubtractTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/math/BigIntegerSubtractTest.java new file mode 100644 index 0000000..aaddd39 --- /dev/null +++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/math/BigIntegerSubtractTest.java @@ -0,0 +1,547 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 Elena Semukhina + */ + +package org.apache.harmony.tests.java.math; + +import junit.framework.TestCase; +import java.math.BigInteger; + +/** + * Class: java.math.BigInteger + * Method: subtract + */ +public class BigIntegerSubtractTest extends TestCase { + /** + * Subtract two positive numbers of the same length. + * The first is greater. + */ + public void testCase1() { + byte aBytes[] = {10, 20, 30, 40, 50, 60, 70, 10, 20, 30}; + byte bBytes[] = {1, 2, 3, 4, 5, 6, 7, 1, 2, 3}; + int aSign = 1; + int bSign = 1; + byte rBytes[] = {9, 18, 27, 36, 45, 54, 63, 9, 18, 27}; + BigInteger aNumber = new BigInteger(aSign, aBytes); + BigInteger bNumber = new BigInteger(bSign, bBytes); + BigInteger result = aNumber.subtract(bNumber); + byte resBytes[] = new byte[rBytes.length]; + resBytes = result.toByteArray(); + for(int i = 0; i < resBytes.length; i++) { + assertTrue(resBytes[i] == rBytes[i]); + } + assertEquals(1, result.signum()); + } + + /** + * Subtract two positive numbers of the same length. + * The second is greater. + */ + public void testCase2() { + byte aBytes[] = {1, 2, 3, 4, 5, 6, 7, 1, 2, 3}; + byte bBytes[] = {10, 20, 30, 40, 50, 60, 70, 10, 20, 30}; + int aSign = 1; + int bSign = 1; + byte rBytes[] = {-10, -19, -28, -37, -46, -55, -64, -10, -19, -27}; + BigInteger aNumber = new BigInteger(aSign, aBytes); + BigInteger bNumber = new BigInteger(bSign, bBytes); + BigInteger result = aNumber.subtract(bNumber); + byte resBytes[] = new byte[rBytes.length]; + resBytes = result.toByteArray(); + for(int i = 0; i < resBytes.length; i++) { + assertTrue(resBytes[i] == rBytes[i]); + } + assertEquals(-1, result.signum()); + } + + /** + * Subtract two numbers of the same length and different signs. + * The first is positive. + * The first is greater in absolute value. + */ + public void testCase3() { + byte aBytes[] = {10, 20, 30, 40, 50, 60, 70, 10, 20, 30}; + byte bBytes[] = {1, 2, 3, 4, 5, 6, 7, 1, 2, 3}; + int aSign = 1; + int bSign = -1; + byte rBytes[] = {11, 22, 33, 44, 55, 66, 77, 11, 22, 33}; + BigInteger aNumber = new BigInteger(aSign, aBytes); + BigInteger bNumber = new BigInteger(bSign, bBytes); + BigInteger result = aNumber.subtract(bNumber); + byte resBytes[] = new byte[rBytes.length]; + resBytes = result.toByteArray(); + for(int i = 0; i < resBytes.length; i++) { + assertTrue(resBytes[i] == rBytes[i]); + } + assertEquals(1, result.signum()); + } + + /** + * Subtract two numbers of the same length and different signs. + * The first is positive. + * The second is greater in absolute value. + */ + public void testCase4() { + byte aBytes[] = {1, 2, 3, 4, 5, 6, 7, 1, 2, 3}; + byte bBytes[] = {10, 20, 30, 40, 50, 60, 70, 10, 20, 30}; + int aSign = 1; + int bSign = -1; + byte rBytes[] = {11, 22, 33, 44, 55, 66, 77, 11, 22, 33}; + BigInteger aNumber = new BigInteger(aSign, aBytes); + BigInteger bNumber = new BigInteger(bSign, bBytes); + BigInteger result = aNumber.subtract(bNumber); + byte resBytes[] = new byte[rBytes.length]; + resBytes = result.toByteArray(); + for(int i = 0; i < resBytes.length; i++) { + assertTrue(resBytes[i] == rBytes[i]); + } + assertEquals(1, result.signum()); + } + + /** + * Subtract two negative numbers of the same length. + * The first is greater in absolute value. + */ + public void testCase5() { + byte aBytes[] = {10, 20, 30, 40, 50, 60, 70, 10, 20, 30}; + byte bBytes[] = {1, 2, 3, 4, 5, 6, 7, 1, 2, 3}; + int aSign = -1; + int bSign = -1; + byte rBytes[] = {-10, -19, -28, -37, -46, -55, -64, -10, -19, -27}; + BigInteger aNumber = new BigInteger(aSign, aBytes); + BigInteger bNumber = new BigInteger(bSign, bBytes); + BigInteger result = aNumber.subtract(bNumber); + byte resBytes[] = new byte[rBytes.length]; + resBytes = result.toByteArray(); + for(int i = 0; i < resBytes.length; i++) { + assertTrue(resBytes[i] == rBytes[i]); + } + assertEquals(-1, result.signum()); + } + + /** + * Subtract two negative numbers of the same length. + * The second is greater in absolute value. + */ + public void testCase6() { + byte aBytes[] = {1, 2, 3, 4, 5, 6, 7, 1, 2, 3}; + byte bBytes[] = {10, 20, 30, 40, 50, 60, 70, 10, 20, 30}; + int aSign = -1; + int bSign = -1; + byte rBytes[] = {9, 18, 27, 36, 45, 54, 63, 9, 18, 27}; + BigInteger aNumber = new BigInteger(aSign, aBytes); + BigInteger bNumber = new BigInteger(bSign, bBytes); + BigInteger result = aNumber.subtract(bNumber); + byte resBytes[] = new byte[rBytes.length]; + resBytes = result.toByteArray(); + for(int i = 0; i < resBytes.length; i++) { + assertTrue(resBytes[i] == rBytes[i]); + } + assertEquals(1, result.signum()); + } + + /** + * Subtract two numbers of the same length and different signs. + * The first is negative. + * The first is greater in absolute value. + */ + public void testCase7() { + byte aBytes[] = {10, 20, 30, 40, 50, 60, 70, 10, 20, 30}; + byte bBytes[] = {1, 2, 3, 4, 5, 6, 7, 1, 2, 3}; + int aSign = -1; + int bSign = 1; + byte rBytes[] = {-12, -23, -34, -45, -56, -67, -78, -12, -23, -33}; + BigInteger aNumber = new BigInteger(aSign, aBytes); + BigInteger bNumber = new BigInteger(bSign, bBytes); + BigInteger result = aNumber.subtract(bNumber); + byte resBytes[] = new byte[rBytes.length]; + resBytes = result.toByteArray(); + for(int i = 0; i < resBytes.length; i++) { + assertTrue(resBytes[i] == rBytes[i]); + } + assertEquals(-1, result.signum()); + } + + /** + * Subtract two numbers of the same length and different signs. + * The first is negative. + * The second is greater in absolute value. + */ + public void testCase8() { + byte aBytes[] = {1, 2, 3, 4, 5, 6, 7, 1, 2, 3}; + byte bBytes[] = {10, 20, 30, 40, 50, 60, 70, 10, 20, 30}; + int aSign = -1; + int bSign = 1; + byte rBytes[] = {-12, -23, -34, -45, -56, -67, -78, -12, -23, -33}; + BigInteger aNumber = new BigInteger(aSign, aBytes); + BigInteger bNumber = new BigInteger(bSign, bBytes); + BigInteger result = aNumber.subtract(bNumber); + byte resBytes[] = new byte[rBytes.length]; + resBytes = result.toByteArray(); + for(int i = 0; i < resBytes.length; i++) { + assertTrue(resBytes[i] == rBytes[i]); + } + assertEquals(-1, result.signum()); + } + + /** + * Subtract two positive numbers of different length. + * The first is longer. + */ + public void testCase9() { + byte aBytes[] = {1, 2, 3, 4, 5, 6, 7, 1, 2, 3, 4, 5, 6, 7}; + byte bBytes[] = {10, 20, 30, 40, 50, 60, 70, 10, 20, 30}; + int aSign = 1; + int bSign = 1; + byte rBytes[] = {1, 2, 3, 3, -6, -15, -24, -40, -49, -58, -67, -6, -15, -23}; + BigInteger aNumber = new BigInteger(aSign, aBytes); + BigInteger bNumber = new BigInteger(bSign, bBytes); + BigInteger result = aNumber.subtract(bNumber); + byte resBytes[] = new byte[rBytes.length]; + resBytes = result.toByteArray(); + for(int i = 0; i < resBytes.length; i++) { + assertTrue(resBytes[i] == rBytes[i]); + } + assertEquals(1, result.signum()); + } + + /** + * Subtract two positive numbers of different length. + * The second is longer. + */ + public void testCase10() { + byte aBytes[] = {10, 20, 30, 40, 50, 60, 70, 10, 20, 30}; + byte bBytes[] = {1, 2, 3, 4, 5, 6, 7, 1, 2, 3, 4, 5, 6, 7}; + int aSign = 1; + int bSign = 1; + byte rBytes[] = {-2, -3, -4, -4, 5, 14, 23, 39, 48, 57, 66, 5, 14, 23}; + BigInteger aNumber = new BigInteger(aSign, aBytes); + BigInteger bNumber = new BigInteger(bSign, bBytes); + BigInteger result = aNumber.subtract(bNumber); + byte resBytes[] = new byte[rBytes.length]; + resBytes = result.toByteArray(); + for(int i = 0; i < resBytes.length; i++) { + assertTrue(resBytes[i] == rBytes[i]); + } + assertEquals(-1, result.signum()); + } + + /** + * Subtract two numbers of different length and different signs. + * The first is positive. + * The first is greater in absolute value. + */ + public void testCase11() { + byte aBytes[] = {1, 2, 3, 4, 5, 6, 7, 1, 2, 3, 4, 5, 6, 7}; + byte bBytes[] = {10, 20, 30, 40, 50, 60, 70, 10, 20, 30}; + int aSign = 1; + int bSign = -1; + byte rBytes[] = {1, 2, 3, 4, 15, 26, 37, 41, 52, 63, 74, 15, 26, 37}; + BigInteger aNumber = new BigInteger(aSign, aBytes); + BigInteger bNumber = new BigInteger(bSign, bBytes); + BigInteger result = aNumber.subtract(bNumber); + byte resBytes[] = new byte[rBytes.length]; + resBytes = result.toByteArray(); + for(int i = 0; i < resBytes.length; i++) { + assertTrue(resBytes[i] == rBytes[i]); + } + assertEquals(1, result.signum()); + } + + /** + * Subtract two numbers of the same length and different signs. + * The first is positive. + * The second is greater in absolute value. + */ + public void testCase12() { + byte aBytes[] = {10, 20, 30, 40, 50, 60, 70, 10, 20, 30}; + byte bBytes[] = {1, 2, 3, 4, 5, 6, 7, 1, 2, 3, 4, 5, 6, 7}; + int aSign = 1; + int bSign = -1; + byte rBytes[] = {1, 2, 3, 4, 15, 26, 37, 41, 52, 63, 74, 15, 26, 37}; + BigInteger aNumber = new BigInteger(aSign, aBytes); + BigInteger bNumber = new BigInteger(bSign, bBytes); + BigInteger result = aNumber.subtract(bNumber); + byte resBytes[] = new byte[rBytes.length]; + resBytes = result.toByteArray(); + for(int i = 0; i < resBytes.length; i++) { + assertTrue(resBytes[i] == rBytes[i]); + } + assertEquals(1, result.signum()); + } + + /** + * Subtract two numbers of different length and different signs. + * The first is negative. + * The first is longer. + */ + public void testCase13() { + byte aBytes[] = {1, 2, 3, 4, 5, 6, 7, 1, 2, 3, 4, 5, 6, 7}; + byte bBytes[] = {10, 20, 30, 40, 50, 60, 70, 10, 20, 30}; + int aSign = -1; + int bSign = 1; + byte rBytes[] = {-2, -3, -4, -5, -16, -27, -38, -42, -53, -64, -75, -16, -27, -37}; + BigInteger aNumber = new BigInteger(aSign, aBytes); + BigInteger bNumber = new BigInteger(bSign, bBytes); + BigInteger result = aNumber.subtract(bNumber); + byte resBytes[] = new byte[rBytes.length]; + resBytes = result.toByteArray(); + for(int i = 0; i < resBytes.length; i++) { + assertTrue(resBytes[i] == rBytes[i]); + } + assertEquals(-1, result.signum()); + } + + /** + * Subtract two numbers of the same length and different signs. + * The first is negative. + * The second is longer. + */ + public void testCase14() { + byte aBytes[] = {1, 2, 3, 4, 5, 6, 7, 1, 2, 3, 4, 5, 6, 7}; + byte bBytes[] = {10, 20, 30, 40, 50, 60, 70, 10, 20, 30}; + int aSign = -1; + int bSign = 1; + byte rBytes[] = {-2, -3, -4, -5, -16, -27, -38, -42, -53, -64, -75, -16, -27, -37}; + BigInteger aNumber = new BigInteger(aSign, aBytes); + BigInteger bNumber = new BigInteger(bSign, bBytes); + BigInteger result = aNumber.subtract(bNumber); + byte resBytes[] = new byte[rBytes.length]; + resBytes = result.toByteArray(); + for(int i = 0; i < resBytes.length; i++) { + assertTrue(resBytes[i] == rBytes[i]); + } + assertEquals(-1, result.signum()); + } + + /** + * Subtract two negative numbers of different length. + * The first is longer. + */ + public void testCase15() { + byte aBytes[] = {1, 2, 3, 4, 5, 6, 7, 1, 2, 3, 4, 5, 6, 7}; + byte bBytes[] = {10, 20, 30, 40, 50, 60, 70, 10, 20, 30}; + int aSign = -1; + int bSign = -1; + byte rBytes[] = {-2, -3, -4, -4, 5, 14, 23, 39, 48, 57, 66, 5, 14, 23}; + BigInteger aNumber = new BigInteger(aSign, aBytes); + BigInteger bNumber = new BigInteger(bSign, bBytes); + BigInteger result = aNumber.subtract(bNumber); + byte resBytes[] = new byte[rBytes.length]; + resBytes = result.toByteArray(); + for(int i = 0; i < resBytes.length; i++) { + assertTrue(resBytes[i] == rBytes[i]); + } + assertEquals(-1, result.signum()); +} + + /** + * Subtract two negative numbers of different length. + * The second is longer. + */ + public void testCase16() { + byte aBytes[] = {10, 20, 30, 40, 50, 60, 70, 10, 20, 30}; + byte bBytes[] = {1, 2, 3, 4, 5, 6, 7, 1, 2, 3, 4, 5, 6, 7}; + int aSign = -1; + int bSign = -1; + byte rBytes[] = {1, 2, 3, 3, -6, -15, -24, -40, -49, -58, -67, -6, -15, -23}; + BigInteger aNumber = new BigInteger(aSign, aBytes); + BigInteger bNumber = new BigInteger(bSign, bBytes); + BigInteger result = aNumber.subtract(bNumber); + byte resBytes[] = new byte[rBytes.length]; + resBytes = result.toByteArray(); + for(int i = 0; i < resBytes.length; i++) { + assertTrue(resBytes[i] == rBytes[i]); + } + assertEquals(1, result.signum()); + } + + /** + * Subtract two positive equal in absolute value numbers. + */ + public void testCase17() { + byte aBytes[] = {-120, 34, 78, -23, -111, 45, 127, 23, 45, -3}; + byte bBytes[] = {-120, 34, 78, -23, -111, 45, 127, 23, 45, -3}; + byte rBytes[] = {0}; + int aSign = 1; + int bSign = 1; + BigInteger aNumber = new BigInteger(aSign, aBytes); + BigInteger bNumber = new BigInteger(bSign, bBytes); + BigInteger result = aNumber.subtract(bNumber); + byte resBytes[] = new byte[rBytes.length]; + resBytes = result.toByteArray(); + for(int i = 0; i < resBytes.length; i++) { + assertTrue(resBytes[i] == rBytes[i]); + } + assertEquals(0, result.signum()); + } + + /** + * Subtract zero from a number. + * The number is positive. + */ + public void testCase18() { + byte aBytes[] = {120, 34, 78, -23, -111, 45, 127, 23, 45, -3}; + byte bBytes[] = {0}; + byte rBytes[] = {120, 34, 78, -23, -111, 45, 127, 23, 45, -3}; + int aSign = 1; + int bSign = 0; + BigInteger aNumber = new BigInteger(aSign, aBytes); + BigInteger bNumber = new BigInteger(bSign, bBytes); + BigInteger result = aNumber.subtract(bNumber); + byte resBytes[] = new byte[rBytes.length]; + resBytes = result.toByteArray(); + for(int i = 0; i < resBytes.length; i++) { + assertTrue(resBytes[i] == rBytes[i]); + } + assertEquals(1, result.signum()); + } + + /** + * Subtract a number from zero. + * The number is negative. + */ + public void testCase19() { + byte aBytes[] = {0}; + byte bBytes[] = {120, 34, 78, -23, -111, 45, 127, 23, 45, -3}; + byte rBytes[] = {120, 34, 78, -23, -111, 45, 127, 23, 45, -3}; + int aSign = 0; + int bSign = -1; + BigInteger aNumber = new BigInteger(aSign, aBytes); + BigInteger bNumber = new BigInteger(bSign, bBytes); + BigInteger result = aNumber.subtract(bNumber); + byte resBytes[] = new byte[rBytes.length]; + resBytes = result.toByteArray(); + for(int i = 0; i < resBytes.length; i++) { + assertTrue(resBytes[i] == rBytes[i]); + } + assertEquals(1, result.signum()); + } + + /** + * Subtract zero from zero. + */ + public void testCase20() { + byte aBytes[] = {0}; + byte bBytes[] = {0}; + byte rBytes[] = {0}; + int aSign = 0; + int bSign = 0; + BigInteger aNumber = new BigInteger(aSign, aBytes); + BigInteger bNumber = new BigInteger(bSign, bBytes); + BigInteger result = aNumber.subtract(bNumber); + byte resBytes[] = new byte[rBytes.length]; + resBytes = result.toByteArray(); + for(int i = 0; i < resBytes.length; i++) { + assertTrue(resBytes[i] == rBytes[i]); + } + assertEquals(0, result.signum()); + } + + /** + * Subtract ZERO from a number. + * The number is positive. + */ + public void testCase21() { + byte aBytes[] = {120, 34, 78, -23, -111, 45, 127, 23, 45, -3}; + byte rBytes[] = {120, 34, 78, -23, -111, 45, 127, 23, 45, -3}; + int aSign = 1; + BigInteger aNumber = new BigInteger(aSign, aBytes); + BigInteger bNumber = BigInteger.ZERO; + BigInteger result = aNumber.subtract(bNumber); + byte resBytes[] = new byte[rBytes.length]; + resBytes = result.toByteArray(); + for(int i = 0; i < resBytes.length; i++) { + assertTrue(resBytes[i] == rBytes[i]); + } + assertEquals(1, result.signum()); + } + + /** + * Subtract a number from ZERO. + * The number is negative. + */ + public void testCase22() { + byte bBytes[] = {120, 34, 78, -23, -111, 45, 127, 23, 45, -3}; + byte rBytes[] = {120, 34, 78, -23, -111, 45, 127, 23, 45, -3}; + int bSign = -1; + BigInteger aNumber = BigInteger.ZERO; + BigInteger bNumber = new BigInteger(bSign, bBytes); + BigInteger result = aNumber.subtract(bNumber); + byte resBytes[] = new byte[rBytes.length]; + resBytes = result.toByteArray(); + for(int i = 0; i < resBytes.length; i++) { + assertTrue(resBytes[i] == rBytes[i]); + } + assertEquals(1, result.signum()); + } + + /** + * Subtract ZERO from ZERO. + */ + public void testCase23() { + byte rBytes[] = {0}; + BigInteger aNumber = BigInteger.ZERO; + BigInteger bNumber = BigInteger.ZERO; + BigInteger result = aNumber.subtract(bNumber); + byte resBytes[] = new byte[rBytes.length]; + resBytes = result.toByteArray(); + for(int i = 0; i < resBytes.length; i++) { + assertTrue(resBytes[i] == rBytes[i]); + } + assertEquals(0, result.signum()); + } + + /** + * Subtract ONE from ONE. + */ + public void testCase24() { + byte rBytes[] = {0}; + BigInteger aNumber = BigInteger.ONE; + BigInteger bNumber = BigInteger.ONE; + BigInteger result = aNumber.subtract(bNumber); + byte resBytes[] = new byte[rBytes.length]; + resBytes = result.toByteArray(); + for(int i = 0; i < resBytes.length; i++) { + assertTrue(resBytes[i] == rBytes[i]); + } + assertEquals(0, result.signum()); + } + + /** + * Subtract two numbers so that borrow is 1. + */ + public void testCase25() { + byte aBytes[] = {-1, -1, -1, -1, -1, -1, -1, -1}; + byte bBytes[] = {-128, -128, -128, -128, -128, -128, -128, -128, -128}; + int aSign = 1; + int bSign = 1; + byte rBytes[] = {-128, 127, 127, 127, 127, 127, 127, 127, 127}; + BigInteger aNumber = new BigInteger(aSign, aBytes); + BigInteger bNumber = new BigInteger(bSign, bBytes); + BigInteger result = aNumber.subtract(bNumber); + byte resBytes[] = new byte[rBytes.length]; + resBytes = result.toByteArray(); + for(int i = 0; i < resBytes.length; i++) { + assertTrue(resBytes[i] == rBytes[i]); + } + assertEquals(-1, result.signum()); + } +} + diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/math/BigIntegerToStringTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/math/BigIntegerToStringTest.java new file mode 100644 index 0000000..3f20414 --- /dev/null +++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/math/BigIntegerToStringTest.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. + */ +/** + * @author Elena Semukhina + */ + +package org.apache.harmony.tests.java.math; + +import java.math.BigInteger; + +import junit.framework.TestCase; + +/** + * Class: java.math.BigInteger + * Method: toString(int radix) + */ +public class BigIntegerToStringTest extends TestCase { + /** + * If 36 < radix < 2 it should be set to 10 + */ + public void testRadixOutOfRange() { + String value = "442429234853876401"; + int radix = 10; + BigInteger aNumber = new BigInteger(value, radix); + String result = aNumber.toString(45); + assertTrue(result.equals(value)); + } + + /** + * test negative number of radix 2 + */ + public void testRadix2Neg() { + String value = "-101001100010010001001010101110000101010110001010010101010101010101010101010101010101010101010010101"; + int radix = 2; + BigInteger aNumber = new BigInteger(value, radix); + String result = aNumber.toString(radix); + assertTrue(result.equals(value)); + } + + /** + * test positive number of radix 2 + */ + public void testRadix2Pos() { + String value = "101000011111000000110101010101010101010001001010101010101010010101010101010000100010010"; + int radix = 2; + BigInteger aNumber = new BigInteger(value, radix); + String result = aNumber.toString(radix); + assertTrue(result.equals(value)); + } + + /** + * test negative number of radix 10 + */ + public void testRadix10Neg() { + String value = "-2489756308572364789878394872984"; + int radix = 16; + BigInteger aNumber = new BigInteger(value, radix); + String result = aNumber.toString(radix); + assertTrue(result.equals(value)); + } + + /** + * test positive number of radix 10 + */ + public void testRadix10Pos() { + String value = "2387627892347567398736473476"; + int radix = 16; + BigInteger aNumber = new BigInteger(value, radix); + String result = aNumber.toString(radix); + assertTrue(result.equals(value)); + } + + /** + * test negative number of radix 16 + */ + public void testRadix16Neg() { + String value = "-287628a883451b800865c67e8d7ff20"; + int radix = 16; + BigInteger aNumber = new BigInteger(value, radix); + String result = aNumber.toString(radix); + assertTrue(result.equals(value)); + } + + /** + * test positive number of radix 16 + */ + public void testRadix16Pos() { + String value = "287628a883451b800865c67e8d7ff20"; + int radix = 16; + BigInteger aNumber = new BigInteger(value, radix); + String result = aNumber.toString(radix); + assertTrue(result.equals(value)); + } + + /** + * test negative number of radix 24 + */ + public void testRadix24Neg() { + String value = "-287628a88gmn3451b8ijk00865c67e8d7ff20"; + int radix = 24; + BigInteger aNumber = new BigInteger(value, radix); + String result = aNumber.toString(radix); + assertTrue(result.equals(value)); + } + + /** + * test positive number of radix 24 + */ + public void testRadix24Pos() { + String value = "287628a883451bg80ijhk0865c67e8d7ff20"; + int radix = 24; + BigInteger aNumber = new BigInteger(value, radix); + String result = aNumber.toString(radix); + assertTrue(result.equals(value)); + } + + /** + * test negative number of radix 24 + */ + public void testRadix36Neg() { + String value = "-uhguweut98iu4h3478tq3985pq98yeiuth33485yq4aiuhalai485yiaehasdkr8tywi5uhslei8"; + int radix = 36; + BigInteger aNumber = new BigInteger(value, radix); + String result = aNumber.toString(radix); + assertTrue(result.equals(value)); + } + + /** + * test positive number of radix 24 + */ + public void testRadix36Pos() { + String value = "23895lt45y6vhgliuwhgi45y845htsuerhsi4586ysuerhtsio5y68peruhgsil4568ypeorihtse48y6"; + int radix = 36; + BigInteger aNumber = new BigInteger(value, radix); + String result = aNumber.toString(radix); + assertTrue(result.equals(value)); + } +} diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/math/BigIntegerXorTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/math/BigIntegerXorTest.java new file mode 100644 index 0000000..57ca78a --- /dev/null +++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/math/BigIntegerXorTest.java @@ -0,0 +1,277 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 Elena Semukhina + */ + +package org.apache.harmony.tests.java.math; + +import junit.framework.TestCase; +import java.math.BigInteger; + +/** + * Class: java.math.BigInteger + * Method: xor + */ +public class BigIntegerXorTest extends TestCase { + /** + * Xor for zero and a positive number + */ + public void testZeroPos() { + String numA = "0"; + String numB = "27384627835298756289327365"; + String res = "27384627835298756289327365"; + BigInteger aNumber = new BigInteger(numA); + BigInteger bNumber = new BigInteger(numB); + BigInteger result = aNumber.xor(bNumber); + assertTrue(res.equals(result.toString())); + } + + /** + * Xor for zero and a negative number + */ + public void testZeroNeg() { + String numA = "0"; + String numB = "-27384627835298756289327365"; + String res = "-27384627835298756289327365"; + BigInteger aNumber = new BigInteger(numA); + BigInteger bNumber = new BigInteger(numB); + BigInteger result = aNumber.xor(bNumber); + assertTrue(res.equals(result.toString())); + } + + /** + * Xor for a positive number and zero + */ + public void testPosZero() { + String numA = "27384627835298756289327365"; + String numB = "0"; + String res = "27384627835298756289327365"; + BigInteger aNumber = new BigInteger(numA); + BigInteger bNumber = new BigInteger(numB); + BigInteger result = aNumber.xor(bNumber); + assertTrue(res.equals(result.toString())); + } + + /** + * Xor for a negative number and zero + */ + public void testNegPos() { + String numA = "-27384627835298756289327365"; + String numB = "0"; + String res = "-27384627835298756289327365"; + BigInteger aNumber = new BigInteger(numA); + BigInteger bNumber = new BigInteger(numB); + BigInteger result = aNumber.xor(bNumber); + assertTrue(res.equals(result.toString())); + } + + /** + * Xor for zero and zero + */ + public void testZeroZero() { + String numA = "0"; + String numB = "0"; + String res = "0"; + BigInteger aNumber = new BigInteger(numA); + BigInteger bNumber = new BigInteger(numB); + BigInteger result = aNumber.xor(bNumber); + assertTrue(res.equals(result.toString())); + } + + /** + * Xor for zero and one + */ + public void testZeroOne() { + String numA = "0"; + String numB = "1"; + String res = "1"; + BigInteger aNumber = new BigInteger(numA); + BigInteger bNumber = new BigInteger(numB); + BigInteger result = aNumber.xor(bNumber); + assertTrue(res.equals(result.toString())); + } + + /** + * Xor for one and one + */ + public void testOneOne() { + String numA = "1"; + String numB = "1"; + String res = "0"; + BigInteger aNumber = new BigInteger(numA); + BigInteger bNumber = new BigInteger(numB); + BigInteger result = aNumber.xor(bNumber); + assertTrue(res.equals(result.toString())); + } + + /** + * Xor for two positive numbers of the same length + */ + public void testPosPosSameLength() { + String numA = "283746278342837476784564875684767"; + String numB = "293478573489347658763745839457637"; + String res = "71412358434940908477702819237626"; + BigInteger aNumber = new BigInteger(numA); + BigInteger bNumber = new BigInteger(numB); + BigInteger result = aNumber.xor(bNumber); + assertTrue(res.equals(result.toString())); + } + + /** + * Xor for two positive numbers; the first is longer + */ + public void testPosPosFirstLonger() { + String numA = "2837462783428374767845648748973847593874837948575684767"; + String numB = "293478573489347658763745839457637"; + String res = "2837462783428374767845615168483972194300564226167553530"; + BigInteger aNumber = new BigInteger(numA); + BigInteger bNumber = new BigInteger(numB); + BigInteger result = aNumber.xor(bNumber); + assertTrue(res.equals(result.toString())); + } + + /** + * Xor for two positive numbers; the first is shorter + */ + public void testPosPosFirstShorter() { + String numA = "293478573489347658763745839457637"; + String numB = "2837462783428374767845648748973847593874837948575684767"; + String res = "2837462783428374767845615168483972194300564226167553530"; + BigInteger aNumber = new BigInteger(numA); + BigInteger bNumber = new BigInteger(numB); + BigInteger result = aNumber.xor(bNumber); + assertTrue(res.equals(result.toString())); + } + + /** + * Xor for two negative numbers of the same length + */ + public void testNegNegSameLength() { + String numA = "-283746278342837476784564875684767"; + String numB = "-293478573489347658763745839457637"; + String res = "71412358434940908477702819237626"; + BigInteger aNumber = new BigInteger(numA); + BigInteger bNumber = new BigInteger(numB); + BigInteger result = aNumber.xor(bNumber); + assertTrue(res.equals(result.toString())); + } + + /** + * Xor for two negative numbers; the first is longer + */ + public void testNegNegFirstLonger() { + String numA = "-2837462783428374767845648748973847593874837948575684767"; + String numB = "-293478573489347658763745839457637"; + String res = "2837462783428374767845615168483972194300564226167553530"; + BigInteger aNumber = new BigInteger(numA); + BigInteger bNumber = new BigInteger(numB); + BigInteger result = aNumber.xor(bNumber); + assertTrue(res.equals(result.toString())); + } + + /** + * Xor for two negative numbers; the first is shorter + */ + public void testNegNegFirstShorter() { + String numA = "293478573489347658763745839457637"; + String numB = "2837462783428374767845648748973847593874837948575684767"; + String res = "2837462783428374767845615168483972194300564226167553530"; + BigInteger aNumber = new BigInteger(numA); + BigInteger bNumber = new BigInteger(numB); + BigInteger result = aNumber.xor(bNumber); + assertTrue(res.equals(result.toString())); + } + + /** + * Xor for two numbers of different signs and the same length + */ + public void testPosNegSameLength() { + String numA = "283746278342837476784564875684767"; + String numB = "-293478573489347658763745839457637"; + String res = "-71412358434940908477702819237628"; + BigInteger aNumber = new BigInteger(numA); + BigInteger bNumber = new BigInteger(numB); + BigInteger result = aNumber.xor(bNumber); + assertTrue(res.equals(result.toString())); + } + + /** + * Xor for two numbers of different signs and the same length + */ + public void testNegPosSameLength() { + String numA = "-283746278342837476784564875684767"; + String numB = "293478573489347658763745839457637"; + String res = "-71412358434940908477702819237628"; + BigInteger aNumber = new BigInteger(numA); + BigInteger bNumber = new BigInteger(numB); + BigInteger result = aNumber.xor(bNumber); + assertTrue(res.equals(result.toString())); + } + + /** + * Xor for a negative and a positive numbers; the first is longer + */ + public void testNegPosFirstLonger() { + String numA = "-2837462783428374767845648748973847593874837948575684767"; + String numB = "293478573489347658763745839457637"; + String res = "-2837462783428374767845615168483972194300564226167553532"; + BigInteger aNumber = new BigInteger(numA); + BigInteger bNumber = new BigInteger(numB); + BigInteger result = aNumber.xor(bNumber); + assertTrue(res.equals(result.toString())); + } + + /** + * Xor for two negative numbers; the first is shorter + */ + public void testNegPosFirstShorter() { + String numA = "-293478573489347658763745839457637"; + String numB = "2837462783428374767845648748973847593874837948575684767"; + String res = "-2837462783428374767845615168483972194300564226167553532"; + BigInteger aNumber = new BigInteger(numA); + BigInteger bNumber = new BigInteger(numB); + BigInteger result = aNumber.xor(bNumber); + assertTrue(res.equals(result.toString())); + } + + /** + * Xor for a positive and a negative numbers; the first is longer + */ + public void testPosNegFirstLonger() { + String numA = "2837462783428374767845648748973847593874837948575684767"; + String numB = "-293478573489347658763745839457637"; + String res = "-2837462783428374767845615168483972194300564226167553532"; + BigInteger aNumber = new BigInteger(numA); + BigInteger bNumber = new BigInteger(numB); + BigInteger result = aNumber.xor(bNumber); + assertTrue(res.equals(result.toString())); + } + + /** + * Xor for a positive and a negative number; the first is shorter + */ + public void testPosNegFirstShorter() { + String numA = "293478573489347658763745839457637"; + String numB = "-2837462783428374767845648748973847593874837948575684767"; + String res = "-2837462783428374767845615168483972194300564226167553532"; + BigInteger aNumber = new BigInteger(numA); + BigInteger bNumber = new BigInteger(numB); + BigInteger result = aNumber.xor(bNumber); + assertTrue(res.equals(result.toString())); + } +} diff --git a/harmony-tests/src/test/java/tests/api/java/math/BigDecimalTest.java b/harmony-tests/src/test/java/tests/api/java/math/BigDecimalTest.java new file mode 100644 index 0000000..4fd27bf --- /dev/null +++ b/harmony-tests/src/test/java/tests/api/java/math/BigDecimalTest.java @@ -0,0 +1,952 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package tests.api.java.math; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.ObjectInputStream; +import java.io.ObjectOutputStream; +import java.math.BigDecimal; +import java.math.BigInteger; +import java.math.MathContext; +import java.math.RoundingMode; + + +public class BigDecimalTest extends junit.framework.TestCase { + BigInteger value = new BigInteger("12345908"); + + BigInteger value2 = new BigInteger("12334560000"); + + /** + * @tests java.math.BigDecimal#BigDecimal(java.math.BigInteger) + */ + public void test_ConstructorLjava_math_BigInteger() { + BigDecimal big = new BigDecimal(value); + assertTrue("the BigDecimal value is not initialized properly", big + .unscaledValue().equals(value) + && big.scale() == 0); + } + + /** + * @tests java.math.BigDecimal#BigDecimal(java.math.BigInteger, int) + */ + public void test_ConstructorLjava_math_BigIntegerI() { + BigDecimal big = new BigDecimal(value2, 5); + assertTrue("the BigDecimal value is not initialized properly", big + .unscaledValue().equals(value2) + && big.scale() == 5); + assertTrue("the BigDecimal value is not represented properly", big + .toString().equals("123345.60000")); + } + + /** + * @tests java.math.BigDecimal#BigDecimal(double) + */ + public void test_ConstructorD() { + BigDecimal big = new BigDecimal(123E04); + assertTrue( + "the BigDecimal value taking a double argument is not initialized properly", + big.toString().equals("1230000")); + big = new BigDecimal(1.2345E-12); + assertTrue("the double representation is not correct", big + .doubleValue() == 1.2345E-12); + big = new BigDecimal(-12345E-3); + assertTrue("the double representation is not correct", big + .doubleValue() == -12.345); + big = new BigDecimal(5.1234567897654321e138); + assertTrue("the double representation is not correct", big + .doubleValue() == 5.1234567897654321E138 + && big.scale() == 0); + big = new BigDecimal(0.1); + assertTrue( + "the double representation of 0.1 bigDecimal is not correct", + big.doubleValue() == 0.1); + big = new BigDecimal(0.00345); + assertTrue( + "the double representation of 0.00345 bigDecimal is not correct", + big.doubleValue() == 0.00345); + // regression test for HARMONY-2429 + big = new BigDecimal(-0.0); + assertTrue( + "the double representation of -0.0 bigDecimal is not correct", + big.scale() == 0); + } + + /** + * @tests java.math.BigDecimal#BigDecimal(java.lang.String) + */ + public void test_ConstructorLjava_lang_String() throws NumberFormatException { + BigDecimal big = new BigDecimal("345.23499600293850"); + assertTrue("the BigDecimal value is not initialized properly", big + .toString().equals("345.23499600293850") + && big.scale() == 14); + big = new BigDecimal("-12345"); + assertTrue("the BigDecimal value is not initialized properly", big + .toString().equals("-12345") + && big.scale() == 0); + big = new BigDecimal("123."); + assertTrue("the BigDecimal value is not initialized properly", big + .toString().equals("123") + && big.scale() == 0); + + new BigDecimal("1.234E02"); + } + + /** + * @tests java.math.BigDecimal#BigDecimal(java.lang.String) + */ + public void test_constructor_String_plus_exp() { + /* + * BigDecimal does not support a + sign in the exponent when converting + * from a String + */ + new BigDecimal(+23e-0); + new BigDecimal(-23e+0); + } + + /** + * @tests java.math.BigDecimal#BigDecimal(java.lang.String) + */ + public void test_constructor_String_empty() { + try { + new BigDecimal(""); + fail("NumberFormatException expected"); + } catch (NumberFormatException e) { + } + } + + /** + * @tests java.math.BigDecimal#BigDecimal(java.lang.String) + */ + public void test_constructor_String_plus_minus_exp() { + try { + new BigDecimal("+35e+-2"); + fail("NumberFormatException expected"); + } catch (NumberFormatException e) { + } + + try { + new BigDecimal("-35e-+2"); + fail("NumberFormatException expected"); + } catch (NumberFormatException e) { + } + } + + /** + * @tests java.math.BigDecimal#BigDecimal(char[]) + */ + public void test_constructor_CC_plus_minus_exp() { + try { + new BigDecimal("+35e+-2".toCharArray()); + fail("NumberFormatException expected"); + } catch (NumberFormatException e) { + } + + try { + new BigDecimal("-35e-+2".toCharArray()); + fail("NumberFormatException expected"); + } catch (NumberFormatException e) { + } + } + + /** + * @tests java.math.BigDecimal#abs() + */ + public void test_abs() { + BigDecimal big = new BigDecimal("-1234"); + BigDecimal bigabs = big.abs(); + assertTrue("the absolute value of -1234 is not 1234", bigabs.toString() + .equals("1234")); + big = new BigDecimal(new BigInteger("2345"), 2); + bigabs = big.abs(); + assertTrue("the absolute value of 23.45 is not 23.45", bigabs + .toString().equals("23.45")); + } + + /** + * @tests java.math.BigDecimal#add(java.math.BigDecimal) + */ + public void test_addLjava_math_BigDecimal() { + BigDecimal add1 = new BigDecimal("23.456"); + BigDecimal add2 = new BigDecimal("3849.235"); + BigDecimal sum = add1.add(add2); + assertTrue("the sum of 23.456 + 3849.235 is wrong", sum.unscaledValue() + .toString().equals("3872691") + && sum.scale() == 3); + assertTrue("the sum of 23.456 + 3849.235 is not printed correctly", sum + .toString().equals("3872.691")); + BigDecimal add3 = new BigDecimal(12.34E02D); + assertTrue("the sum of 23.456 + 12.34E02 is not printed correctly", + (add1.add(add3)).toString().equals("1257.456")); + } + + /** + * @tests java.math.BigDecimal#compareTo(java.math.BigDecimal) + */ + public void test_compareToLjava_math_BigDecimal() { + BigDecimal comp1 = new BigDecimal("1.00"); + BigDecimal comp2 = new BigDecimal(1.000000D); + assertTrue("1.00 and 1.000000 should be equal", + comp1.compareTo(comp2) == 0); + BigDecimal comp3 = new BigDecimal("1.02"); + assertTrue("1.02 should be bigger than 1.00", + comp3.compareTo(comp1) == 1); + BigDecimal comp4 = new BigDecimal(0.98D); + assertTrue("0.98 should be less than 1.00", + comp4.compareTo(comp1) == -1); + } + + /** + * @tests java.math.BigDecimal#divide(java.math.BigDecimal, int) + */ + public void test_divideLjava_math_BigDecimalI() { + BigDecimal divd1 = new BigDecimal(value, 2); + BigDecimal divd2 = new BigDecimal("2.335"); + BigDecimal divd3 = divd1.divide(divd2, BigDecimal.ROUND_UP); + assertTrue("123459.08/2.335 is not correct", divd3.toString().equals( + "52873.27") + && divd3.scale() == divd1.scale()); + assertTrue( + "the unscaledValue representation of 123459.08/2.335 is not correct", + divd3.unscaledValue().toString().equals("5287327")); + divd2 = new BigDecimal(123.4D); + divd3 = divd1.divide(divd2, BigDecimal.ROUND_DOWN); + assertTrue("123459.08/123.4 is not correct", divd3.toString().equals( + "1000.47") + && divd3.scale() == 2); + divd2 = new BigDecimal(000D); + + try { + divd1.divide(divd2, BigDecimal.ROUND_DOWN); + fail("divide by zero is not caught"); + } catch (ArithmeticException e) { + } + } + + /** + * @tests java.math.BigDecimal#divide(java.math.BigDecimal, int, int) + */ + public void test_divideLjava_math_BigDecimalII() { + BigDecimal divd1 = new BigDecimal(value2, 4); + BigDecimal divd2 = new BigDecimal("0.0023"); + BigDecimal divd3 = divd1.divide(divd2, 3, BigDecimal.ROUND_HALF_UP); + assertTrue("1233456/0.0023 is not correct", divd3.toString().equals( + "536285217.391") + && divd3.scale() == 3); + divd2 = new BigDecimal(1345.5E-02D); + divd3 = divd1.divide(divd2, 0, BigDecimal.ROUND_DOWN); + assertTrue( + "1233456/13.455 is not correct or does not have the correct scale", + divd3.toString().equals("91672") && divd3.scale() == 0); + divd2 = new BigDecimal(0000D); + + try { + divd1.divide(divd2, 4, BigDecimal.ROUND_DOWN); + fail("divide by zero is not caught"); + } catch (ArithmeticException e) { + } + } + + /** + * @tests java.math.BigDecimal#doubleValue() + */ + public void test_doubleValue() { + BigDecimal bigDB = new BigDecimal(-1.234E-112); +// Commenting out this part because it causes an endless loop (see HARMONY-319 and HARMONY-329) +// assertTrue( +// "the double representation of this BigDecimal is not correct", +// bigDB.doubleValue() == -1.234E-112); + bigDB = new BigDecimal(5.00E-324); + assertTrue("the double representation of bigDecimal is not correct", + bigDB.doubleValue() == 5.00E-324); + bigDB = new BigDecimal(1.79E308); + assertTrue("the double representation of bigDecimal is not correct", + bigDB.doubleValue() == 1.79E308 && bigDB.scale() == 0); + bigDB = new BigDecimal(-2.33E102); + assertTrue( + "the double representation of bigDecimal -2.33E102 is not correct", + bigDB.doubleValue() == -2.33E102 && bigDB.scale() == 0); + bigDB = new BigDecimal(Double.MAX_VALUE); + bigDB = bigDB.add(bigDB); + assertTrue( + "a + number out of the double range should return infinity", + bigDB.doubleValue() == Double.POSITIVE_INFINITY); + bigDB = new BigDecimal(-Double.MAX_VALUE); + bigDB = bigDB.add(bigDB); + assertTrue( + "a - number out of the double range should return neg infinity", + bigDB.doubleValue() == Double.NEGATIVE_INFINITY); + } + + /** + * @tests java.math.BigDecimal#equals(java.lang.Object) + */ + public void test_equalsLjava_lang_Object() { + BigDecimal equal1 = new BigDecimal(1.00D); + BigDecimal equal2 = new BigDecimal("1.0"); + assertFalse("1.00 and 1.0 should not be equal", + equal1.equals(equal2)); + equal2 = new BigDecimal(1.01D); + assertFalse("1.00 and 1.01 should not be equal", + equal1.equals(equal2)); + equal2 = new BigDecimal("1.00"); + assertFalse("1.00D and 1.00 should not be equal", + equal1.equals(equal2)); + BigInteger val = new BigInteger("100"); + equal1 = new BigDecimal("1.00"); + equal2 = new BigDecimal(val, 2); + assertTrue("1.00(string) and 1.00(bigInteger) should be equal", equal1 + .equals(equal2)); + equal1 = new BigDecimal(100D); + equal2 = new BigDecimal("2.34576"); + assertFalse("100D and 2.34576 should not be equal", equal1 + .equals(equal2)); + assertFalse("bigDecimal 100D does not equal string 23415", equal1 + .equals("23415")); + } + + /** + * @tests java.math.BigDecimal#floatValue() + */ + public void test_floatValue() { + BigDecimal fl1 = new BigDecimal("234563782344567"); + assertTrue("the float representation of bigDecimal 234563782344567", + fl1.floatValue() == 234563782344567f); + BigDecimal fl2 = new BigDecimal(2.345E37); + assertTrue("the float representation of bigDecimal 2.345E37", fl2 + .floatValue() == 2.345E37F); + fl2 = new BigDecimal(-1.00E-44); + assertTrue("the float representation of bigDecimal -1.00E-44", fl2 + .floatValue() == -1.00E-44F); + fl2 = new BigDecimal(-3E12); + assertTrue("the float representation of bigDecimal -3E12", fl2 + .floatValue() == -3E12F); + fl2 = new BigDecimal(Double.MAX_VALUE); + assertTrue( + "A number can't be represented by float should return infinity", + fl2.floatValue() == Float.POSITIVE_INFINITY); + fl2 = new BigDecimal(-Double.MAX_VALUE); + assertTrue( + "A number can't be represented by float should return infinity", + fl2.floatValue() == Float.NEGATIVE_INFINITY); + + } + + /** + * @tests java.math.BigDecimal#hashCode() + */ + public void test_hashCode() { + // anything that is equal must have the same hashCode + BigDecimal hash = new BigDecimal("1.00"); + BigDecimal hash2 = new BigDecimal(1.00D); + assertTrue("the hashCode of 1.00 and 1.00D is equal", + hash.hashCode() != hash2.hashCode() && !hash.equals(hash2)); + hash2 = new BigDecimal("1.0"); + assertTrue("the hashCode of 1.0 and 1.00 is equal", + hash.hashCode() != hash2.hashCode() && !hash.equals(hash2)); + BigInteger val = new BigInteger("100"); + hash2 = new BigDecimal(val, 2); + assertTrue("hashCode of 1.00 and 1.00(bigInteger) is not equal", hash + .hashCode() == hash2.hashCode() + && hash.equals(hash2)); + hash = new BigDecimal(value, 2); + hash2 = new BigDecimal("-1233456.0000"); + assertTrue("hashCode of 123459.08 and -1233456.0000 is not equal", hash + .hashCode() != hash2.hashCode() + && !hash.equals(hash2)); + hash2 = new BigDecimal(value.negate(), 2); + assertTrue("hashCode of 123459.08 and -123459.08 is not equal", hash + .hashCode() != hash2.hashCode() + && !hash.equals(hash2)); + } + + /** + * @tests java.math.BigDecimal#intValue() + */ + public void test_intValue() { + BigDecimal int1 = new BigDecimal(value, 3); + assertTrue("the int value of 12345.908 is not 12345", + int1.intValue() == 12345); + int1 = new BigDecimal("1.99"); + assertTrue("the int value of 1.99 is not 1", int1.intValue() == 1); + int1 = new BigDecimal("23423419083091823091283933"); + // ran JDK and found representation for the above was -249268259 + assertTrue("the int value of 23423419083091823091283933 is wrong", int1 + .intValue() == -249268259); + int1 = new BigDecimal(-1235D); + assertTrue("the int value of -1235 is not -1235", + int1.intValue() == -1235); + } + + /** + * @tests java.math.BigDecimal#longValue() + */ + public void test_longValue() { + BigDecimal long1 = new BigDecimal(value2.negate(), 0); + assertTrue("the long value of 12334560000 is not 12334560000", long1 + .longValue() == -12334560000L); + long1 = new BigDecimal(-1345.348E-123D); + assertTrue("the long value of -1345.348E-123D is not zero", long1 + .longValue() == 0); + long1 = new BigDecimal("31323423423419083091823091283933"); + // ran JDK and found representation for the above was + // -5251313250005125155 + assertTrue( + "the long value of 31323423423419083091823091283933 is wrong", + long1.longValue() == -5251313250005125155L); + } + + /** + * @tests java.math.BigDecimal#max(java.math.BigDecimal) + */ + public void test_maxLjava_math_BigDecimal() { + BigDecimal max1 = new BigDecimal(value2, 1); + BigDecimal max2 = new BigDecimal(value2, 4); + assertTrue("1233456000.0 is not greater than 1233456", max1.max(max2) + .equals(max1)); + max1 = new BigDecimal(-1.224D); + max2 = new BigDecimal(-1.2245D); + assertTrue("-1.224 is not greater than -1.2245", max1.max(max2).equals( + max1)); + max1 = new BigDecimal(123E18); + max2 = new BigDecimal(123E19); + assertTrue("123E19 is the not the max", max1.max(max2).equals(max2)); + } + + /** + * @tests java.math.BigDecimal#min(java.math.BigDecimal) + */ + public void test_minLjava_math_BigDecimal() { + BigDecimal min1 = new BigDecimal(-12345.4D); + BigDecimal min2 = new BigDecimal(-12345.39D); + assertTrue("-12345.39 should have been returned", min1.min(min2) + .equals(min1)); + min1 = new BigDecimal(value2, 5); + min2 = new BigDecimal(value2, 0); + assertTrue("123345.6 should have been returned", min1.min(min2).equals( + min1)); + } + + /** + * @tests java.math.BigDecimal#movePointLeft(int) + */ + public void test_movePointLeftI() { + BigDecimal movePtLeft = new BigDecimal("123456265.34"); + BigDecimal alreadyMoved = movePtLeft.movePointLeft(5); + assertTrue("move point left 5 failed", alreadyMoved.scale() == 7 + && alreadyMoved.toString().equals("1234.5626534")); + movePtLeft = new BigDecimal(value2.negate(), 0); + alreadyMoved = movePtLeft.movePointLeft(12); + assertTrue("move point left 12 failed", alreadyMoved.scale() == 12 + && alreadyMoved.toString().equals("-0.012334560000")); + movePtLeft = new BigDecimal(123E18); + alreadyMoved = movePtLeft.movePointLeft(2); + assertTrue("move point left 2 failed", + alreadyMoved.scale() == movePtLeft.scale() + 2 + && alreadyMoved.doubleValue() == 1.23E18); + movePtLeft = new BigDecimal(1.123E-12); + alreadyMoved = movePtLeft.movePointLeft(3); + assertTrue("move point left 3 failed", + alreadyMoved.scale() == movePtLeft.scale() + 3 + && alreadyMoved.doubleValue() == 1.123E-15); + movePtLeft = new BigDecimal(value, 2); + alreadyMoved = movePtLeft.movePointLeft(-2); + assertTrue("move point left -2 failed", + alreadyMoved.scale() == movePtLeft.scale() - 2 + && alreadyMoved.toString().equals("12345908")); + } + + /** + * @tests java.math.BigDecimal#movePointRight(int) + */ + public void test_movePointRightI() { + BigDecimal movePtRight = new BigDecimal("-1.58796521458"); + BigDecimal alreadyMoved = movePtRight.movePointRight(8); + assertTrue("move point right 8 failed", alreadyMoved.scale() == 3 + && alreadyMoved.toString().equals("-158796521.458")); + movePtRight = new BigDecimal(value, 2); + alreadyMoved = movePtRight.movePointRight(4); + assertTrue("move point right 4 failed", alreadyMoved.scale() == 0 + && alreadyMoved.toString().equals("1234590800")); + movePtRight = new BigDecimal(134E12); + alreadyMoved = movePtRight.movePointRight(2); + assertTrue("move point right 2 failed", alreadyMoved.scale() == 0 + && alreadyMoved.toString().equals("13400000000000000")); + movePtRight = new BigDecimal(-3.4E-10); + alreadyMoved = movePtRight.movePointRight(5); + assertTrue("move point right 5 failed", + alreadyMoved.scale() == movePtRight.scale() - 5 + && alreadyMoved.doubleValue() == -0.000034); + alreadyMoved = alreadyMoved.movePointRight(-5); + assertTrue("move point right -5 failed", alreadyMoved + .equals(movePtRight)); + } + + /** + * @tests java.math.BigDecimal#multiply(java.math.BigDecimal) + */ + public void test_multiplyLjava_math_BigDecimal() { + BigDecimal multi1 = new BigDecimal(value, 5); + BigDecimal multi2 = new BigDecimal(2.345D); + BigDecimal result = multi1.multiply(multi2); + assertTrue("123.45908 * 2.345 is not correct: " + result, result + .toString().startsWith("289.51154260") + && result.scale() == multi1.scale() + multi2.scale()); + multi1 = new BigDecimal("34656"); + multi2 = new BigDecimal("-2"); + result = multi1.multiply(multi2); + assertTrue("34656 * 2 is not correct", result.toString().equals( + "-69312") + && result.scale() == 0); + multi1 = new BigDecimal(-2.345E-02); + multi2 = new BigDecimal(-134E130); + result = multi1.multiply(multi2); + assertTrue("-2.345E-02 * -134E130 is not correct " + result.doubleValue(), + result.doubleValue() == 3.1422999999999997E130 + && result.scale() == multi1.scale() + multi2.scale()); + multi1 = new BigDecimal("11235"); + multi2 = new BigDecimal("0"); + result = multi1.multiply(multi2); + assertTrue("11235 * 0 is not correct", result.doubleValue() == 0 + && result.scale() == 0); + multi1 = new BigDecimal("-0.00234"); + multi2 = new BigDecimal(13.4E10); + result = multi1.multiply(multi2); + assertTrue("-0.00234 * 13.4E10 is not correct", + result.doubleValue() == -313560000 + && result.scale() == multi1.scale() + multi2.scale()); + } + + /** + * @tests java.math.BigDecimal#negate() + */ + public void test_negate() { + BigDecimal negate1 = new BigDecimal(value2, 7); + assertTrue("the negate of 1233.4560000 is not -1233.4560000", negate1 + .negate().toString().equals("-1233.4560000")); + negate1 = new BigDecimal("-23465839"); + assertTrue("the negate of -23465839 is not 23465839", negate1.negate() + .toString().equals("23465839")); + negate1 = new BigDecimal(-3.456E6); + assertTrue("the negate of -3.456E6 is not 3.456E6", negate1.negate() + .negate().equals(negate1)); + } + + /** + * @tests java.math.BigDecimal#scale() + */ + public void test_scale() { + BigDecimal scale1 = new BigDecimal(value2, 8); + assertTrue("the scale of the number 123.34560000 is wrong", scale1 + .scale() == 8); + BigDecimal scale2 = new BigDecimal("29389."); + assertTrue("the scale of the number 29389. is wrong", + scale2.scale() == 0); + BigDecimal scale3 = new BigDecimal(3.374E13); + assertTrue("the scale of the number 3.374E13 is wrong", + scale3.scale() == 0); + BigDecimal scale4 = new BigDecimal("-3.45E-203"); + // note the scale is calculated as 15 digits of 345000.... + exponent - + // 1. -1 for the 3 + assertTrue("the scale of the number -3.45E-203 is wrong: " + + scale4.scale(), scale4.scale() == 205); + scale4 = new BigDecimal("-345.4E-200"); + assertTrue("the scale of the number -345.4E-200 is wrong", scale4 + .scale() == 201); + } + + /** + * @tests java.math.BigDecimal#setScale(int) + */ + public void test_setScaleI() { + // rounding mode defaults to zero + BigDecimal setScale1 = new BigDecimal(value, 3); + BigDecimal setScale2 = setScale1.setScale(5); + BigInteger setresult = new BigInteger("1234590800"); + assertTrue("the number 12345.908 after setting scale is wrong", + setScale2.unscaledValue().equals(setresult) + && setScale2.scale() == 5); + + try { + setScale2 = setScale1.setScale(2, BigDecimal.ROUND_UNNECESSARY); + fail("arithmetic Exception not caught as a result of loosing precision"); + } catch (ArithmeticException e) { + } + } + + /** + * @tests java.math.BigDecimal#setScale(int, int) + */ + public void test_setScaleII() { + BigDecimal setScale1 = new BigDecimal(2.323E102); + BigDecimal setScale2 = setScale1.setScale(4); + assertTrue("the number 2.323E102 after setting scale is wrong", + setScale2.scale() == 4); + assertTrue("the representation of the number 2.323E102 is wrong", + setScale2.doubleValue() == 2.323E102); + setScale1 = new BigDecimal("-1.253E-12"); + setScale2 = setScale1.setScale(17, BigDecimal.ROUND_CEILING); + assertTrue("the number -1.253E-12 after setting scale is wrong", + setScale2.scale() == 17); + assertTrue( + "the representation of the number -1.253E-12 after setting scale is wrong, " + setScale2.toString(), + setScale2.toString().equals("-1.25300E-12")); + + // testing rounding Mode ROUND_CEILING + setScale1 = new BigDecimal(value, 4); + setScale2 = setScale1.setScale(1, BigDecimal.ROUND_CEILING); + assertTrue( + "the number 1234.5908 after setting scale to 1/ROUND_CEILING is wrong", + setScale2.toString().equals("1234.6") && setScale2.scale() == 1); + BigDecimal setNeg = new BigDecimal(value.negate(), 4); + setScale2 = setNeg.setScale(1, BigDecimal.ROUND_CEILING); + assertTrue( + "the number -1234.5908 after setting scale to 1/ROUND_CEILING is wrong", + setScale2.toString().equals("-1234.5") + && setScale2.scale() == 1); + + // testing rounding Mode ROUND_DOWN + setScale2 = setNeg.setScale(1, BigDecimal.ROUND_DOWN); + assertTrue( + "the number -1234.5908 after setting scale to 1/ROUND_DOWN is wrong", + setScale2.toString().equals("-1234.5") + && setScale2.scale() == 1); + setScale1 = new BigDecimal(value, 4); + setScale2 = setScale1.setScale(1, BigDecimal.ROUND_DOWN); + assertTrue( + "the number 1234.5908 after setting scale to 1/ROUND_DOWN is wrong", + setScale2.toString().equals("1234.5") && setScale2.scale() == 1); + + // testing rounding Mode ROUND_FLOOR + setScale2 = setScale1.setScale(1, BigDecimal.ROUND_FLOOR); + assertTrue( + "the number 1234.5908 after setting scale to 1/ROUND_FLOOR is wrong", + setScale2.toString().equals("1234.5") && setScale2.scale() == 1); + setScale2 = setNeg.setScale(1, BigDecimal.ROUND_FLOOR); + assertTrue( + "the number -1234.5908 after setting scale to 1/ROUND_FLOOR is wrong", + setScale2.toString().equals("-1234.6") + && setScale2.scale() == 1); + + // testing rounding Mode ROUND_HALF_DOWN + setScale2 = setScale1.setScale(3, BigDecimal.ROUND_HALF_DOWN); + assertTrue( + "the number 1234.5908 after setting scale to 3/ROUND_HALF_DOWN is wrong", + setScale2.toString().equals("1234.591") + && setScale2.scale() == 3); + setScale1 = new BigDecimal(new BigInteger("12345000"), 5); + setScale2 = setScale1.setScale(1, BigDecimal.ROUND_HALF_DOWN); + assertTrue( + "the number 123.45908 after setting scale to 1/ROUND_HALF_DOWN is wrong", + setScale2.toString().equals("123.4") && setScale2.scale() == 1); + setScale2 = new BigDecimal("-1234.5000").setScale(0, + BigDecimal.ROUND_HALF_DOWN); + assertTrue( + "the number -1234.5908 after setting scale to 0/ROUND_HALF_DOWN is wrong", + setScale2.toString().equals("-1234") && setScale2.scale() == 0); + + // testing rounding Mode ROUND_HALF_EVEN + setScale1 = new BigDecimal(1.2345789D); + setScale2 = setScale1.setScale(4, BigDecimal.ROUND_HALF_EVEN); + assertTrue( + "the number 1.2345789 after setting scale to 4/ROUND_HALF_EVEN is wrong", + setScale2.doubleValue() == 1.2346D && setScale2.scale() == 4); + setNeg = new BigDecimal(-1.2335789D); + setScale2 = setNeg.setScale(2, BigDecimal.ROUND_HALF_EVEN); + assertTrue( + "the number -1.2335789 after setting scale to 2/ROUND_HALF_EVEN is wrong", + setScale2.doubleValue() == -1.23D && setScale2.scale() == 2); + setScale2 = new BigDecimal("1.2345000").setScale(3, + BigDecimal.ROUND_HALF_EVEN); + assertTrue( + "the number 1.2345789 after setting scale to 3/ROUND_HALF_EVEN is wrong", + setScale2.doubleValue() == 1.234D && setScale2.scale() == 3); + setScale2 = new BigDecimal("-1.2345000").setScale(3, + BigDecimal.ROUND_HALF_EVEN); + assertTrue( + "the number -1.2335789 after setting scale to 3/ROUND_HALF_EVEN is wrong", + setScale2.doubleValue() == -1.234D && setScale2.scale() == 3); + + // testing rounding Mode ROUND_HALF_UP + setScale1 = new BigDecimal("134567.34650"); + setScale2 = setScale1.setScale(3, BigDecimal.ROUND_HALF_UP); + assertTrue( + "the number 134567.34658 after setting scale to 3/ROUND_HALF_UP is wrong", + setScale2.toString().equals("134567.347") + && setScale2.scale() == 3); + setNeg = new BigDecimal("-1234.4567"); + setScale2 = setNeg.setScale(0, BigDecimal.ROUND_HALF_UP); + assertTrue( + "the number -1234.4567 after setting scale to 0/ROUND_HALF_UP is wrong", + setScale2.toString().equals("-1234") && setScale2.scale() == 0); + + // testing rounding Mode ROUND_UNNECESSARY + try { + setScale1.setScale(3, BigDecimal.ROUND_UNNECESSARY); + fail("arithmetic Exception not caught for round unnecessary"); + } catch (ArithmeticException e) { + } + + // testing rounding Mode ROUND_UP + setScale1 = new BigDecimal("100000.374"); + setScale2 = setScale1.setScale(2, BigDecimal.ROUND_UP); + assertTrue( + "the number 100000.374 after setting scale to 2/ROUND_UP is wrong", + setScale2.toString().equals("100000.38") + && setScale2.scale() == 2); + setNeg = new BigDecimal(-134.34589D); + setScale2 = setNeg.setScale(2, BigDecimal.ROUND_UP); + assertTrue( + "the number -134.34589 after setting scale to 2/ROUND_UP is wrong", + setScale2.doubleValue() == -134.35D && setScale2.scale() == 2); + + // testing invalid rounding modes + try { + setScale2 = setScale1.setScale(0, -123); + fail("IllegalArgumentException is not caught for wrong rounding mode"); + } catch (IllegalArgumentException e) { + } + } + + /** + * @tests java.math.BigDecimal#signum() + */ + public void test_signum() { + BigDecimal sign = new BigDecimal(123E-104); + assertTrue("123E-104 is not positive in signum()", sign.signum() == 1); + sign = new BigDecimal("-1234.3959"); + assertTrue("-1234.3959 is not negative in signum()", + sign.signum() == -1); + sign = new BigDecimal(000D); + assertTrue("000D is not zero in signum()", sign.signum() == 0); + } + + /** + * @tests java.math.BigDecimal#subtract(java.math.BigDecimal) + */ + public void test_subtractLjava_math_BigDecimal() { + BigDecimal sub1 = new BigDecimal("13948"); + BigDecimal sub2 = new BigDecimal("2839.489"); + BigDecimal result = sub1.subtract(sub2); + assertTrue("13948 - 2839.489 is wrong: " + result, result.toString() + .equals("11108.511") + && result.scale() == 3); + BigDecimal result2 = sub2.subtract(sub1); + assertTrue("2839.489 - 13948 is wrong", result2.toString().equals( + "-11108.511") + && result2.scale() == 3); + assertTrue("13948 - 2839.489 is not the negative of 2839.489 - 13948", + result.equals(result2.negate())); + sub1 = new BigDecimal(value, 1); + sub2 = new BigDecimal("0"); + result = sub1.subtract(sub2); + assertTrue("1234590.8 - 0 is wrong", result.equals(sub1)); + sub1 = new BigDecimal(1.234E-03); + sub2 = new BigDecimal(3.423E-10); + result = sub1.subtract(sub2); + assertTrue("1.234E-03 - 3.423E-10 is wrong, " + result.doubleValue(), + result.doubleValue() == 0.0012339996577); + sub1 = new BigDecimal(1234.0123); + sub2 = new BigDecimal(1234.0123000); + result = sub1.subtract(sub2); + assertTrue("1234.0123 - 1234.0123000 is wrong, " + result.doubleValue(), + result.doubleValue() == 0.0); + } + + /** + * @tests java.math.BigDecimal#toBigInteger() + */ + public void test_toBigInteger() { + BigDecimal sub1 = new BigDecimal("-29830.989"); + BigInteger result = sub1.toBigInteger(); + + assertTrue("the bigInteger equivalent of -29830.989 is wrong", result + .toString().equals("-29830")); + sub1 = new BigDecimal(-2837E10); + result = sub1.toBigInteger(); + assertTrue("the bigInteger equivalent of -2837E10 is wrong", result + .doubleValue() == -2837E10); + sub1 = new BigDecimal(2.349E-10); + result = sub1.toBigInteger(); + assertTrue("the bigInteger equivalent of 2.349E-10 is wrong", result + .equals(BigInteger.ZERO)); + sub1 = new BigDecimal(value2, 6); + result = sub1.toBigInteger(); + assertTrue("the bigInteger equivalent of 12334.560000 is wrong", result + .toString().equals("12334")); + } + + /** + * @tests java.math.BigDecimal#toString() + */ + public void test_toString() { + BigDecimal toString1 = new BigDecimal("1234.000"); + assertTrue("the toString representation of 1234.000 is wrong", + toString1.toString().equals("1234.000")); + toString1 = new BigDecimal("-123.4E-5"); + assertTrue("the toString representation of -123.4E-5 is wrong: " + + toString1, toString1.toString().equals("-0.001234")); + toString1 = new BigDecimal("-1.455E-20"); + assertTrue("the toString representation of -1.455E-20 is wrong", + toString1.toString().equals("-1.455E-20")); + toString1 = new BigDecimal(value2, 4); + assertTrue("the toString representation of 1233456.0000 is wrong", + toString1.toString().equals("1233456.0000")); + } + + /** + * @tests java.math.BigDecimal#unscaledValue() + */ + public void test_unscaledValue() { + BigDecimal unsVal = new BigDecimal("-2839485.000"); + assertTrue("the unscaledValue of -2839485.000 is wrong", unsVal + .unscaledValue().toString().equals("-2839485000")); + unsVal = new BigDecimal(123E10); + assertTrue("the unscaledValue of 123E10 is wrong", unsVal + .unscaledValue().toString().equals("1230000000000")); + unsVal = new BigDecimal("-4.56E-13"); + assertTrue("the unscaledValue of -4.56E-13 is wrong: " + + unsVal.unscaledValue(), unsVal.unscaledValue().toString() + .equals("-456")); + unsVal = new BigDecimal(value, 3); + assertTrue("the unscaledValue of 12345.908 is wrong", unsVal + .unscaledValue().toString().equals("12345908")); + + } + + /** + * @tests java.math.BigDecimal#valueOf(long) + */ + public void test_valueOfJ() { + BigDecimal valueOfL = BigDecimal.valueOf(9223372036854775806L); + assertTrue("the bigDecimal equivalent of 9223372036854775806 is wrong", + valueOfL.unscaledValue().toString().equals( + "9223372036854775806") + && valueOfL.scale() == 0); + assertTrue( + "the toString representation of 9223372036854775806 is wrong", + valueOfL.toString().equals("9223372036854775806")); + valueOfL = BigDecimal.valueOf(0L); + assertTrue("the bigDecimal equivalent of 0 is wrong", valueOfL + .unscaledValue().toString().equals("0") + && valueOfL.scale() == 0); + } + + /** + * @tests java.math.BigDecimal#valueOf(long, int) + */ + public void test_valueOfJI() { + BigDecimal valueOfJI = BigDecimal.valueOf(9223372036854775806L, 5); + assertTrue( + "the bigDecimal equivalent of 92233720368547.75806 is wrong", + valueOfJI.unscaledValue().toString().equals( + "9223372036854775806") + && valueOfJI.scale() == 5); + assertTrue( + "the toString representation of 9223372036854775806 is wrong", + valueOfJI.toString().equals("92233720368547.75806")); + valueOfJI = BigDecimal.valueOf(1234L, 8); + assertTrue( + "the bigDecimal equivalent of 92233720368547.75806 is wrong", + valueOfJI.unscaledValue().toString().equals("1234") + && valueOfJI.scale() == 8); + assertTrue( + "the toString representation of 9223372036854775806 is wrong", + valueOfJI.toString().equals("0.00001234")); + valueOfJI = BigDecimal.valueOf(0, 3); + assertTrue( + "the bigDecimal equivalent of 92233720368547.75806 is wrong", + valueOfJI.unscaledValue().toString().equals("0") + && valueOfJI.scale() == 3); + assertTrue( + "the toString representation of 9223372036854775806 is wrong", + valueOfJI.toString().equals("0.000")); + + } + + public void test_BigDecimal_serialization() throws Exception { + // Regression for HARMONY-1896 + char[] in = { '1', '5', '6', '7', '8', '7', '.', '0', '0' }; + BigDecimal bd = new BigDecimal(in, 0, 9); + + ByteArrayOutputStream bos = new ByteArrayOutputStream(); + ObjectOutputStream oos = new ObjectOutputStream(bos); + oos.writeObject(bd); + + ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray()); + ObjectInputStream ois = new ObjectInputStream(bis); + BigDecimal nbd = (BigDecimal) ois.readObject(); + + assertEquals(bd.intValue(), nbd.intValue()); + assertEquals(bd.doubleValue(), nbd.doubleValue(), 0.0); + assertEquals(bd.toString(), nbd.toString()); + } + + /** + * @tests java.math.BigDecimal#stripTrailingZero(long) + */ + public void test_stripTrailingZero() { + BigDecimal sixhundredtest = new BigDecimal("600.0"); + assertTrue("stripTrailingZero failed for 600.0", + ((sixhundredtest.stripTrailingZeros()).scale() == -2) + ); + + /* Single digit, no trailing zero, odd number */ + BigDecimal notrailingzerotest = new BigDecimal("1"); + assertTrue("stripTrailingZero failed for 1", + ((notrailingzerotest.stripTrailingZeros()).scale() == 0) + ); + + // BEGIN android-changed: preserve RI compatibility, so BigDecimal.equals (which checks + // value *and* scale) continues to work. https://issues.apache.org/jira/browse/HARMONY-4623 + /* Zero */ + BigDecimal zerotest = new BigDecimal("0.0000"); + assertEquals("stripTrailingZero failed for 0.0000", 4, zerotest.stripTrailingZeros().scale()); + } + + public void testMathContextConstruction() { + String a = "-12380945E+61"; + BigDecimal aNumber = new BigDecimal(a); + int precision = 6; + RoundingMode rm = RoundingMode.HALF_DOWN; + MathContext mcIntRm = new MathContext(precision, rm); + MathContext mcStr = new MathContext("precision=6 roundingMode=HALF_DOWN"); + MathContext mcInt = new MathContext(precision); + BigDecimal res = aNumber.abs(mcInt); + assertEquals("MathContext Constructer with int precision failed", + res, + new BigDecimal("1.23809E+68")); + + assertEquals("Equal MathContexts are not Equal ", + mcIntRm, + mcStr); + + assertEquals("Different MathContext are reported as Equal ", + mcInt.equals(mcStr), + false); + + assertEquals("Equal MathContexts have different hashcodes ", + mcIntRm.hashCode(), + mcStr.hashCode()); + + assertEquals("MathContext.toString() returning incorrect value", + mcIntRm.toString(), + "precision=6 roundingMode=HALF_DOWN"); + } + +} diff --git a/harmony-tests/src/test/java/tests/api/java/math/BigIntegerTest.java b/harmony-tests/src/test/java/tests/api/java/math/BigIntegerTest.java new file mode 100644 index 0000000..28995cb --- /dev/null +++ b/harmony-tests/src/test/java/tests/api/java/math/BigIntegerTest.java @@ -0,0 +1,988 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package tests.api.java.math; + +import java.math.BigInteger; +import java.util.Random; + +public class BigIntegerTest extends junit.framework.TestCase { + + BigInteger minusTwo = new BigInteger("-2", 10); + + BigInteger minusOne = new BigInteger("-1", 10); + + BigInteger zero = new BigInteger("0", 10); + + BigInteger one = new BigInteger("1", 10); + + BigInteger two = new BigInteger("2", 10); + + BigInteger ten = new BigInteger("10", 10); + + BigInteger sixteen = new BigInteger("16", 10); + + BigInteger oneThousand = new BigInteger("1000", 10); + + BigInteger aZillion = new BigInteger( + "100000000000000000000000000000000000000000000000000", 10); + + BigInteger twoToTheTen = new BigInteger("1024", 10); + + BigInteger twoToTheSeventy = two.pow(70); + + Random rand = new Random(); + + BigInteger bi; + + BigInteger bi1; + + BigInteger bi2; + + BigInteger bi3; + + BigInteger bi11; + + BigInteger bi22; + + BigInteger bi33; + + BigInteger bi12; + + BigInteger bi23; + + BigInteger bi13; + + BigInteger largePos; + + BigInteger smallPos; + + BigInteger largeNeg; + + BigInteger smallNeg; + + BigInteger[][] booleanPairs; + + /** + * @tests java.math.BigInteger#BigInteger(int, java.util.Random) + */ + public void test_ConstructorILjava_util_Random() { + // regression test for HARMONY-1047 + try { + new BigInteger(Integer.MAX_VALUE, (Random)null); + fail("NegativeArraySizeException expected"); + } catch (NegativeArraySizeException e) { + // PASSED + } + + bi = new BigInteger(70, rand); + bi2 = new BigInteger(70, rand); + assertTrue("Random number is negative", bi.compareTo(zero) >= 0); + assertTrue("Random number is too big", + bi.compareTo(twoToTheSeventy) < 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)); + } + + /** + * @tests java.math.BigInteger#BigInteger(byte[]) + */ + public void test_Constructor$B() { + byte[] myByteArray; + myByteArray = new byte[] { (byte) 0x00, (byte) 0xFF, (byte) 0xFE }; + bi = new BigInteger(myByteArray); + assertTrue("Incorrect value for pos number", bi.equals(BigInteger.ZERO + .setBit(16).subtract(two))); + myByteArray = new byte[] { (byte) 0xFF, (byte) 0xFE }; + bi = new BigInteger(myByteArray); + assertTrue("Incorrect value for neg number", bi.equals(minusTwo)); + } + + /** + * @tests java.math.BigInteger#BigInteger(int, byte[]) + */ + public void test_ConstructorI$B() { + byte[] myByteArray; + myByteArray = new byte[] { (byte) 0xFF, (byte) 0xFE }; + bi = new BigInteger(1, myByteArray); + assertTrue("Incorrect value for pos number", bi.equals(BigInteger.ZERO + .setBit(16).subtract(two))); + bi = new BigInteger(-1, myByteArray); + assertTrue("Incorrect value for neg number", bi.equals(BigInteger.ZERO + .setBit(16).subtract(two).negate())); + myByteArray = new byte[] { (byte) 0, (byte) 0 }; + bi = new BigInteger(0, myByteArray); + assertTrue("Incorrect value for zero", bi.equals(zero)); + myByteArray = new byte[] { (byte) 1 }; + try { + new BigInteger(0, myByteArray); + fail("Failed to throw NumberFormatException"); + } catch (NumberFormatException e) { + // correct + } + } + + /** + * @tests java.math.BigInteger#BigInteger(java.lang.String) + */ + public void test_constructor_String_empty() { + try { + new BigInteger(""); + fail("Expected NumberFormatException for new BigInteger(\"\")"); + } catch (NumberFormatException e) { + } + } + + /** + * @tests java.math.BigInteger#toByteArray() + */ + public void test_toByteArray() { + byte[] myByteArray, anotherByteArray; + myByteArray = new byte[] { 97, 33, 120, 124, 50, 2, 0, 0, 0, 12, 124, + 42 }; + anotherByteArray = new BigInteger(myByteArray).toByteArray(); + assertTrue("Incorrect byte array returned", + myByteArray.length == anotherByteArray.length); + for (int counter = myByteArray.length - 1; counter >= 0; counter--) { + assertTrue("Incorrect values in returned byte array", + myByteArray[counter] == anotherByteArray[counter]); + } + } + + /** + * @tests 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); + } + + /** + * @tests java.math.BigInteger#equals(java.lang.Object) + */ + public void test_equalsLjava_lang_Object() { + assertTrue("0=0", zero.equals(BigInteger.valueOf(0))); + assertTrue("-123=-123", BigInteger.valueOf(-123).equals( + BigInteger.valueOf(-123))); + assertTrue("0=1", !zero.equals(one)); + assertTrue("0=-1", !zero.equals(minusOne)); + assertTrue("1=-1", !one.equals(minusOne)); + assertTrue("bi3=bi3", bi3.equals(bi3)); + assertTrue("bi3=copy of bi3", bi3.equals(bi3.negate().negate())); + assertTrue("bi3=bi2", !bi3.equals(bi2)); + } + + /** + * @tests java.math.BigInteger#compareTo(java.math.BigInteger) + */ + public void test_compareToLjava_math_BigInteger() { + assertTrue("Smaller number returned >= 0", one.compareTo(two) < 0); + assertTrue("Larger number returned >= 0", two.compareTo(one) > 0); + assertTrue("Equal numbers did not return 0", one.compareTo(one) == 0); + assertTrue("Neg number messed things up", + two.negate().compareTo(one) < 0); + } + + /** + * @tests java.math.BigInteger#intValue() + */ + public void test_intValue() { + assertTrue("Incorrect intValue for 2**70", + twoToTheSeventy.intValue() == 0); + assertTrue("Incorrect intValue for 2", two.intValue() == 2); + } + + /** + * @tests java.math.BigInteger#longValue() + */ + public void test_longValue() { + assertTrue("Incorrect longValue for 2**70", + twoToTheSeventy.longValue() == 0); + assertTrue("Incorrect longValue for 2", two.longValue() == 2); + } + + /** + * @tests java.math.BigInteger#valueOf(long) + */ + public void test_valueOfJ() { + assertTrue("Incurred number returned for 2", BigInteger.valueOf(2L) + .equals(two)); + assertTrue("Incurred number returned for 200", BigInteger.valueOf(200L) + .equals(BigInteger.valueOf(139).add(BigInteger.valueOf(61)))); + } + + /** + * @tests 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", zero.add(zero).equals(zero)); + assertTrue("0+1", zero.add(one).equals(one)); + assertTrue("1+0", one.add(zero).equals(one)); + assertTrue("1+1", one.add(one).equals(two)); + assertTrue("0+(-1)", zero.add(minusOne).equals(minusOne)); + assertTrue("(-1)+0", minusOne.add(zero).equals(minusOne)); + assertTrue("(-1)+(-1)", minusOne.add(minusOne).equals(minusTwo)); + assertTrue("1+(-1)", one.add(minusOne).equals(zero)); + assertTrue("(-1)+1", minusOne.add(one).equals(zero)); + + for (int i = 0; i < 200; i++) { + BigInteger midbit = zero.setBit(i); + assertTrue("add fails to carry on bit " + i, midbit.add(midbit) + .equals(zero.setBit(i + 1))); + } + BigInteger bi2p3 = bi2.add(bi3); + BigInteger bi3p2 = bi3.add(bi2); + assertTrue("bi2p3=bi3p2", bi2p3.equals(bi3p2)); + + // add large positive + small positive + + // add large positive + small negative + + // add large negative + small positive + + // add large negative + small negative + } + + /** + * @tests java.math.BigInteger#negate() + */ + public void test_negate() { + assertTrue("Single negation of zero did not result in zero", zero + .negate().equals(zero)); + assertTrue("Single negation resulted in original nonzero number", + !aZillion.negate().equals(aZillion)); + assertTrue("Double negation did not result in original number", + aZillion.negate().negate().equals(aZillion)); + + assertTrue("0.neg", zero.negate().equals(zero)); + assertTrue("1.neg", one.negate().equals(minusOne)); + assertTrue("2.neg", two.negate().equals(minusTwo)); + assertTrue("-1.neg", minusOne.negate().equals(one)); + assertTrue("-2.neg", minusTwo.negate().equals(two)); + assertTrue("0x62EB40FEF85AA9EBL*2.neg", BigInteger.valueOf( + 0x62EB40FEF85AA9EBL * 2).negate().equals( + BigInteger.valueOf(-0x62EB40FEF85AA9EBL * 2))); + for (int i = 0; i < 200; i++) { + BigInteger midbit = zero.setBit(i); + BigInteger negate = midbit.negate(); + assertTrue("negate negate", negate.negate().equals(midbit)); + assertTrue("neg fails on bit " + i, midbit.negate().add(midbit) + .equals(zero)); + } + } + + /** + * @tests java.math.BigInteger#signum() + */ + public void test_signum() { + assertTrue("Wrong positive signum", two.signum() == 1); + assertTrue("Wrong zero signum", zero.signum() == 0); + assertTrue("Wrong neg zero signum", zero.negate().signum() == 0); + assertTrue("Wrong neg signum", two.negate().signum() == -1); + } + + /** + * @tests java.math.BigInteger#abs() + */ + public void test_abs() { + assertTrue("Invalid number returned for zillion", aZillion.negate() + .abs().equals(aZillion.abs())); + assertTrue("Invalid number returned for zero neg", zero.negate().abs() + .equals(zero)); + assertTrue("Invalid number returned for zero", zero.abs().equals(zero)); + assertTrue("Invalid number returned for two", two.negate().abs() + .equals(two)); + } + + /** + * @tests java.math.BigInteger#pow(int) + */ + public void test_powI() { + assertTrue("Incorrect exponent returned for 2**10", two.pow(10).equals( + twoToTheTen)); + assertTrue("Incorrect exponent returned for 2**70", two.pow(30) + .multiply(two.pow(40)).equals(twoToTheSeventy)); + assertTrue("Incorrect exponent returned for 10**50", ten.pow(50) + .equals(aZillion)); + } + + /** + * @tests java.math.BigInteger#modInverse(java.math.BigInteger) + */ + public void test_modInverseLjava_math_BigInteger() { + BigInteger a = zero, mod, inv; + for (int j = 3; j < 50; j++) { + mod = BigInteger.valueOf(j); + for (int i = -j + 1; i < j; i++) { + try { + a = BigInteger.valueOf(i); + inv = a.modInverse(mod); + assertTrue("bad inverse: " + a + " inv mod " + mod + + " equals " + inv, one.equals(a.multiply(inv).mod( + mod))); + assertTrue("inverse greater than modulo: " + a + + " inv mod " + mod + " equals " + inv, inv + .compareTo(mod) < 0); + assertTrue("inverse less than zero: " + a + " inv mod " + + mod + " equals " + inv, inv + .compareTo(BigInteger.ZERO) >= 0); + } catch (ArithmeticException e) { + assertTrue("should have found inverse for " + a + " mod " + + mod, !one.equals(a.gcd(mod))); + } + } + } + for (int j = 1; j < 10; j++) { + mod = bi2.add(BigInteger.valueOf(j)); + for (int i = 0; i < 20; i++) { + try { + a = bi3.add(BigInteger.valueOf(i)); + inv = a.modInverse(mod); + assertTrue("bad inverse: " + a + " inv mod " + mod + + " equals " + inv, one.equals(a.multiply(inv).mod( + mod))); + assertTrue("inverse greater than modulo: " + a + + " inv mod " + mod + " equals " + inv, inv + .compareTo(mod) < 0); + assertTrue("inverse less than zero: " + a + " inv mod " + + mod + " equals " + inv, inv + .compareTo(BigInteger.ZERO) >= 0); + } catch (ArithmeticException e) { + assertTrue("should have found inverse for " + a + " mod " + + mod, !one.equals(a.gcd(mod))); + } + } + } + } + + /** + * @tests java.math.BigInteger#shiftRight(int) + */ + public void test_shiftRightI() { + assertTrue("1 >> 0", BigInteger.valueOf(1).shiftRight(0).equals( + BigInteger.ONE)); + assertTrue("1 >> 1", BigInteger.valueOf(1).shiftRight(1).equals( + BigInteger.ZERO)); + assertTrue("1 >> 63", BigInteger.valueOf(1).shiftRight(63).equals( + BigInteger.ZERO)); + assertTrue("1 >> 64", BigInteger.valueOf(1).shiftRight(64).equals( + BigInteger.ZERO)); + assertTrue("1 >> 65", BigInteger.valueOf(1).shiftRight(65).equals( + BigInteger.ZERO)); + assertTrue("1 >> 1000", BigInteger.valueOf(1).shiftRight(1000).equals( + BigInteger.ZERO)); + assertTrue("-1 >> 0", BigInteger.valueOf(-1).shiftRight(0).equals( + minusOne)); + assertTrue("-1 >> 1", BigInteger.valueOf(-1).shiftRight(1).equals( + minusOne)); + assertTrue("-1 >> 63", BigInteger.valueOf(-1).shiftRight(63).equals( + minusOne)); + assertTrue("-1 >> 64", BigInteger.valueOf(-1).shiftRight(64).equals( + minusOne)); + assertTrue("-1 >> 65", BigInteger.valueOf(-1).shiftRight(65).equals( + minusOne)); + assertTrue("-1 >> 1000", BigInteger.valueOf(-1).shiftRight(1000) + .equals(minusOne)); + + BigInteger a = BigInteger.ONE; + BigInteger c = bi3; + BigInteger E = bi3.negate(); + BigInteger e = E; + for (int i = 0; i < 200; i++) { + BigInteger b = BigInteger.ZERO.setBit(i); + assertTrue("a==b", a.equals(b)); + a = a.shiftLeft(1); + assertTrue("a non-neg", a.signum() >= 0); + + BigInteger d = bi3.shiftRight(i); + assertTrue("c==d", c.equals(d)); + c = c.shiftRight(1); + assertTrue(">>1 == /2", d.divide(two).equals(c)); + assertTrue("c non-neg", c.signum() >= 0); + + BigInteger f = E.shiftRight(i); + assertTrue("e==f", e.equals(f)); + e = e.shiftRight(1); + assertTrue(">>1 == /2", f.subtract(one).divide(two).equals(e)); + assertTrue("e negative", e.signum() == -1); + + assertTrue("b >> i", b.shiftRight(i).equals(one)); + assertTrue("b >> i+1", b.shiftRight(i + 1).equals(zero)); + assertTrue("b >> i-1", b.shiftRight(i - 1).equals(two)); + } + } + + /** + * @tests java.math.BigInteger#shiftLeft(int) + */ + public void test_shiftLeftI() { + assertTrue("1 << 0", one.shiftLeft(0).equals(one)); + assertTrue("1 << 1", one.shiftLeft(1).equals(two)); + assertTrue("1 << 63", one.shiftLeft(63).equals( + new BigInteger("8000000000000000", 16))); + assertTrue("1 << 64", one.shiftLeft(64).equals( + new BigInteger("10000000000000000", 16))); + assertTrue("1 << 65", one.shiftLeft(65).equals( + new BigInteger("20000000000000000", 16))); + assertTrue("-1 << 0", minusOne.shiftLeft(0).equals(minusOne)); + assertTrue("-1 << 1", minusOne.shiftLeft(1).equals(minusTwo)); + assertTrue("-1 << 63", minusOne.shiftLeft(63).equals( + new BigInteger("-9223372036854775808"))); + assertTrue("-1 << 64", minusOne.shiftLeft(64).equals( + new BigInteger("-18446744073709551616"))); + assertTrue("-1 << 65", minusOne.shiftLeft(65).equals( + new BigInteger("-36893488147419103232"))); + + BigInteger a = bi3; + BigInteger c = minusOne; + for (int i = 0; i < 200; i++) { + BigInteger b = bi3.shiftLeft(i); + assertTrue("a==b", a.equals(b)); + assertTrue("a >> i == bi3", a.shiftRight(i).equals(bi3)); + a = a.shiftLeft(1); + assertTrue("<<1 == *2", b.multiply(two).equals(a)); + assertTrue("a non-neg", a.signum() >= 0); + assertTrue("a.bitCount==b.bitCount", a.bitCount() == b.bitCount()); + + BigInteger d = minusOne.shiftLeft(i); + assertTrue("c==d", c.equals(d)); + c = c.shiftLeft(1); + assertTrue("<<1 == *2 negative", d.multiply(two).equals(c)); + assertTrue("c negative", c.signum() == -1); + assertTrue("d >> i == minusOne", d.shiftRight(i).equals(minusOne)); + } + } + + /** + * @tests java.math.BigInteger#multiply(java.math.BigInteger) + */ + public void test_multiplyLjava_math_BigInteger() { + assertTrue("Incorrect sum--wanted three zillion", aZillion + .add(aZillion).add(aZillion).equals( + aZillion.multiply(new BigInteger("3", 10)))); + + assertTrue("0*0", zero.multiply(zero).equals(zero)); + assertTrue("0*1", zero.multiply(one).equals(zero)); + assertTrue("1*0", one.multiply(zero).equals(zero)); + assertTrue("1*1", one.multiply(one).equals(one)); + assertTrue("0*(-1)", zero.multiply(minusOne).equals(zero)); + assertTrue("(-1)*0", minusOne.multiply(zero).equals(zero)); + assertTrue("(-1)*(-1)", minusOne.multiply(minusOne).equals(one)); + assertTrue("1*(-1)", one.multiply(minusOne).equals(minusOne)); + assertTrue("(-1)*1", minusOne.multiply(one).equals(minusOne)); + + testAllMults(bi1, bi1, bi11); + testAllMults(bi2, bi2, bi22); + testAllMults(bi3, bi3, bi33); + testAllMults(bi1, bi2, bi12); + testAllMults(bi1, bi3, bi13); + testAllMults(bi2, bi3, bi23); + } + + /** + * @tests java.math.BigInteger#divide(java.math.BigInteger) + */ + public void test_divideLjava_math_BigInteger() { + testAllDivs(bi33, bi3); + testAllDivs(bi22, bi2); + testAllDivs(bi11, bi1); + testAllDivs(bi13, bi1); + testAllDivs(bi13, bi3); + testAllDivs(bi12, bi1); + testAllDivs(bi12, bi2); + testAllDivs(bi23, bi2); + testAllDivs(bi23, bi3); + testAllDivs(largePos, bi1); + testAllDivs(largePos, bi2); + testAllDivs(largePos, bi3); + testAllDivs(largeNeg, bi1); + testAllDivs(largeNeg, bi2); + testAllDivs(largeNeg, bi3); + testAllDivs(largeNeg, largePos); + testAllDivs(largePos, largeNeg); + testAllDivs(bi3, bi3); + testAllDivs(bi2, bi2); + testAllDivs(bi1, bi1); + testDivRanges(bi1); + testDivRanges(bi2); + testDivRanges(bi3); + testDivRanges(smallPos); + testDivRanges(largePos); + testDivRanges(new BigInteger("62EB40FEF85AA9EB", 16)); + testAllDivs(BigInteger.valueOf(0xCC0225953CL), BigInteger + .valueOf(0x1B937B765L)); + + try { + largePos.divide(zero); + fail("ArithmeticException expected"); + } catch (ArithmeticException e) { + } + + try { + bi1.divide(zero); + fail("ArithmeticException expected"); + } catch (ArithmeticException e) { + } + + try { + bi3.negate().divide(zero); + fail("ArithmeticException expected"); + } catch (ArithmeticException e) { + } + + try { + zero.divide(zero); + fail("ArithmeticException expected"); + } catch (ArithmeticException e) { + } + } + + /** + * @tests java.math.BigInteger#remainder(java.math.BigInteger) + */ + public void test_remainderLjava_math_BigInteger() { + try { + largePos.remainder(zero); + fail("ArithmeticException expected"); + } catch (ArithmeticException e) { + } + + try { + bi1.remainder(zero); + fail("ArithmeticException expected"); + } catch (ArithmeticException e) { + } + + try { + bi3.negate().remainder(zero); + fail("ArithmeticException expected"); + } catch (ArithmeticException e) { + } + + try { + zero.remainder(zero); + fail("ArithmeticException expected"); + } catch (ArithmeticException e) { + } + } + + /** + * @tests java.math.BigInteger#mod(java.math.BigInteger) + */ + public void test_modLjava_math_BigInteger() { + try { + largePos.mod(zero); + fail("ArithmeticException expected"); + } catch (ArithmeticException e) { + } + + try { + bi1.mod(zero); + fail("ArithmeticException expected"); + } catch (ArithmeticException e) { + } + + try { + bi3.negate().mod(zero); + fail("ArithmeticException expected"); + } catch (ArithmeticException e) { + } + + try { + zero.mod(zero); + fail("ArithmeticException expected"); + } catch (ArithmeticException e) { + } + } + + /** + * @tests java.math.BigInteger#divideAndRemainder(java.math.BigInteger) + */ + public void test_divideAndRemainderLjava_math_BigInteger() { + try { + largePos.divideAndRemainder(zero); + fail("ArithmeticException expected"); + } catch (ArithmeticException e) { + } + + try { + bi1.divideAndRemainder(zero); + fail("ArithmeticException expected"); + } catch (ArithmeticException e) { + } + + try { + bi3.negate().divideAndRemainder(zero); + fail("ArithmeticException expected"); + } catch (ArithmeticException e) { + } + + try { + zero.divideAndRemainder(zero); + fail("ArithmeticException expected"); + } catch (ArithmeticException e) { + } + } + + /** + * @tests java.math.BigInteger#BigInteger(java.lang.String) + */ + public void test_ConstructorLjava_lang_String() { + assertTrue("new(0)", new BigInteger("0").equals(BigInteger.valueOf(0))); + assertTrue("new(1)", new BigInteger("1").equals(BigInteger.valueOf(1))); + assertTrue("new(12345678901234)", new BigInteger("12345678901234") + .equals(BigInteger.valueOf(12345678901234L))); + assertTrue("new(-1)", new BigInteger("-1").equals(BigInteger + .valueOf(-1))); + assertTrue("new(-12345678901234)", new BigInteger("-12345678901234") + .equals(BigInteger.valueOf(-12345678901234L))); + } + + /** + * @tests java.math.BigInteger#BigInteger(java.lang.String, int) + */ + public void test_ConstructorLjava_lang_StringI() { + assertTrue("new(0,16)", new BigInteger("0", 16).equals(BigInteger + .valueOf(0))); + assertTrue("new(1,16)", new BigInteger("1", 16).equals(BigInteger + .valueOf(1))); + assertTrue("new(ABF345678901234,16)", new BigInteger("ABF345678901234", + 16).equals(BigInteger.valueOf(0xABF345678901234L))); + assertTrue("new(abf345678901234,16)", new BigInteger("abf345678901234", + 16).equals(BigInteger.valueOf(0xABF345678901234L))); + assertTrue("new(-1,16)", new BigInteger("-1", 16).equals(BigInteger + .valueOf(-1))); + assertTrue("new(-ABF345678901234,16)", new BigInteger( + "-ABF345678901234", 16).equals(BigInteger + .valueOf(-0xABF345678901234L))); + assertTrue("new(-abf345678901234,16)", new BigInteger( + "-abf345678901234", 16).equals(BigInteger + .valueOf(-0xABF345678901234L))); + assertTrue("new(-101010101,2)", new BigInteger("-101010101", 2) + .equals(BigInteger.valueOf(-341))); + } + + /** + * @tests java.math.BigInteger#toString() + */ + public void test_toString() { + assertTrue("0.toString", "0".equals(BigInteger.valueOf(0).toString())); + assertTrue("1.toString", "1".equals(BigInteger.valueOf(1).toString())); + assertTrue("12345678901234.toString", "12345678901234" + .equals(BigInteger.valueOf(12345678901234L).toString())); + assertTrue("-1.toString", "-1" + .equals(BigInteger.valueOf(-1).toString())); + assertTrue("-12345678901234.toString", "-12345678901234" + .equals(BigInteger.valueOf(-12345678901234L).toString())); + } + + /** + * @tests java.math.BigInteger#toString(int) + */ + public void test_toStringI() { + assertTrue("0.toString(16)", "0".equals(BigInteger.valueOf(0).toString( + 16))); + assertTrue("1.toString(16)", "1".equals(BigInteger.valueOf(1).toString( + 16))); + assertTrue("ABF345678901234.toString(16)", "abf345678901234" + .equals(BigInteger.valueOf(0xABF345678901234L).toString(16))); + assertTrue("-1.toString(16)", "-1".equals(BigInteger.valueOf(-1) + .toString(16))); + assertTrue("-ABF345678901234.toString(16)", "-abf345678901234" + .equals(BigInteger.valueOf(-0xABF345678901234L).toString(16))); + assertTrue("-101010101.toString(2)", "-101010101".equals(BigInteger + .valueOf(-341).toString(2))); + } + + /** + * @tests java.math.BigInteger#and(java.math.BigInteger) + */ + public void test_andLjava_math_BigInteger() { + for (BigInteger[] element : booleanPairs) { + BigInteger i1 = element[0], i2 = element[1]; + BigInteger res = i1.and(i2); + assertTrue("symmetry of and", res.equals(i2.and(i1))); + int len = Math.max(i1.bitLength(), i2.bitLength()) + 66; + for (int i = 0; i < len; i++) { + assertTrue("and", (i1.testBit(i) && i2.testBit(i)) == res + .testBit(i)); + } + } + } + + /** + * @tests java.math.BigInteger#or(java.math.BigInteger) + */ + public void test_orLjava_math_BigInteger() { + for (BigInteger[] element : booleanPairs) { + BigInteger i1 = element[0], i2 = element[1]; + BigInteger res = i1.or(i2); + assertTrue("symmetry of or", res.equals(i2.or(i1))); + int len = Math.max(i1.bitLength(), i2.bitLength()) + 66; + for (int i = 0; i < len; i++) { + assertTrue("or", (i1.testBit(i) || i2.testBit(i)) == res + .testBit(i)); + } + } + } + + /** + * @tests java.math.BigInteger#xor(java.math.BigInteger) + */ + public void test_xorLjava_math_BigInteger() { + for (BigInteger[] element : booleanPairs) { + BigInteger i1 = element[0], i2 = element[1]; + BigInteger res = i1.xor(i2); + assertTrue("symmetry of xor", res.equals(i2.xor(i1))); + int len = Math.max(i1.bitLength(), i2.bitLength()) + 66; + for (int i = 0; i < len; i++) { + assertTrue("xor", (i1.testBit(i) ^ i2.testBit(i)) == res + .testBit(i)); + } + } + } + + /** + * @tests java.math.BigInteger#not() + */ + public void test_not() { + for (BigInteger[] element : booleanPairs) { + BigInteger i1 = element[0]; + BigInteger res = i1.not(); + int len = i1.bitLength() + 66; + for (int i = 0; i < len; i++) { + assertTrue("not", !i1.testBit(i) == res.testBit(i)); + } + } + } + + /** + * @tests java.math.BigInteger#andNot(java.math.BigInteger) + */ + public void test_andNotLjava_math_BigInteger() { + for (BigInteger[] element : booleanPairs) { + BigInteger i1 = element[0], i2 = element[1]; + BigInteger res = i1.andNot(i2); + int len = Math.max(i1.bitLength(), i2.bitLength()) + 66; + for (int i = 0; i < len; i++) { + assertTrue("andNot", (i1.testBit(i) && !i2.testBit(i)) == res + .testBit(i)); + } + // asymmetrical + i1 = element[1]; + i2 = element[0]; + res = i1.andNot(i2); + for (int i = 0; i < len; i++) { + assertTrue("andNot reversed", + (i1.testBit(i) && !i2.testBit(i)) == res.testBit(i)); + } + } + //regression for HARMONY-4653 + try{ + BigInteger.ZERO.andNot(null); + fail("should throw NPE"); + }catch(Exception e){ + //expected + } + BigInteger bi = new BigInteger(0, new byte[]{}); + assertEquals(BigInteger.ZERO, bi.andNot(BigInteger.ZERO)); + } + + + 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) { + return null; + } + } + } + + @Override + protected void setUp() { + bi1 = new BigInteger("2436798324768978", 16); + bi2 = new BigInteger("4576829475724387584378543764555", 16); + bi3 = new BigInteger("43987298363278574365732645872643587624387563245", + 16); + + bi33 = new BigInteger( + "10730846694701319120609898625733976090865327544790136667944805934175543888691400559249041094474885347922769807001", + 10); + bi22 = new BigInteger( + "33301606932171509517158059487795669025817912852219962782230629632224456249", + 10); + bi11 = new BigInteger("6809003003832961306048761258711296064", 10); + bi23 = new BigInteger( + "597791300268191573513888045771594235932809890963138840086083595706565695943160293610527214057", + 10); + bi13 = new BigInteger( + "270307912162948508387666703213038600031041043966215279482940731158968434008", + 10); + bi12 = new BigInteger( + "15058244971895641717453176477697767050482947161656458456", 10); + + largePos = new BigInteger( + "834759814379857314986743298675687569845986736578576375675678998612743867438632986243982098437620983476924376", + 16); + smallPos = new BigInteger("48753269875973284765874598630960986276", 16); + largeNeg = new BigInteger( + "-878824397432651481891353247987891423768534321387864361143548364457698487264387568743568743265873246576467643756437657436587436", + 16); + smallNeg = new BigInteger("-567863254343798609857456273458769843", 16); + booleanPairs = new BigInteger[][] { { largePos, smallPos }, + { largePos, smallNeg }, { largeNeg, smallPos }, + { largeNeg, smallNeg } }; + } + + private void testDiv(BigInteger i1, BigInteger i2) { + BigInteger q = i1.divide(i2); + BigInteger r = i1.remainder(i2); + BigInteger[] temp = i1.divideAndRemainder(i2); + + assertTrue("divide and divideAndRemainder do not agree", q + .equals(temp[0])); + assertTrue("remainder and divideAndRemainder do not agree", r + .equals(temp[1])); + assertTrue("signum and equals(zero) do not agree on quotient", q + .signum() != 0 + || q.equals(zero)); + assertTrue("signum and equals(zero) do not agree on remainder", r + .signum() != 0 + || r.equals(zero)); + assertTrue("wrong sign on quotient", q.signum() == 0 + || q.signum() == i1.signum() * i2.signum()); + assertTrue("wrong sign on remainder", r.signum() == 0 + || r.signum() == i1.signum()); + assertTrue("remainder out of range", r.abs().compareTo(i2.abs()) < 0); + assertTrue("quotient too small", q.abs().add(one).multiply(i2.abs()) + .compareTo(i1.abs()) > 0); + assertTrue("quotient too large", q.abs().multiply(i2.abs()).compareTo( + i1.abs()) <= 0); + BigInteger p = q.multiply(i2); + BigInteger a = p.add(r); + assertTrue("(a/b)*b+(a%b) != a", a.equals(i1)); + try { + BigInteger mod = i1.mod(i2); + assertTrue("mod is negative", mod.signum() >= 0); + assertTrue("mod out of range", mod.abs().compareTo(i2.abs()) < 0); + assertTrue("positive remainder == mod", r.signum() < 0 + || r.equals(mod)); + assertTrue("negative remainder == mod - divisor", r.signum() >= 0 + || r.equals(mod.subtract(i2))); + } catch (ArithmeticException e) { + assertTrue("mod fails on negative divisor only", i2.signum() <= 0); + } + } + + private void testDivRanges(BigInteger i) { + BigInteger bound = i.multiply(two); + for (BigInteger j = bound.negate(); j.compareTo(bound) <= 0; j = j + .add(i)) { + BigInteger innerbound = j.add(two); + BigInteger k = j.subtract(two); + for (; k.compareTo(innerbound) <= 0; k = k.add(one)) { + testDiv(k, i); + } + } + } + + 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; + } + + private void testAllMults(BigInteger i1, BigInteger i2, BigInteger ans) { + assertTrue("i1*i2=ans", i1.multiply(i2).equals(ans)); + assertTrue("i2*i1=ans", i2.multiply(i1).equals(ans)); + assertTrue("-i1*i2=-ans", i1.negate().multiply(i2).equals(ans.negate())); + assertTrue("-i2*i1=-ans", i2.negate().multiply(i1).equals(ans.negate())); + assertTrue("i1*-i2=-ans", i1.multiply(i2.negate()).equals(ans.negate())); + assertTrue("i2*-i1=-ans", i2.multiply(i1.negate()).equals(ans.negate())); + assertTrue("-i1*-i2=ans", i1.negate().multiply(i2.negate()).equals(ans)); + assertTrue("-i2*-i1=ans", i2.negate().multiply(i1.negate()).equals(ans)); + } + + private void testAllDivs(BigInteger i1, BigInteger i2) { + testDiv(i1, i2); + testDiv(i1.negate(), i2); + testDiv(i1, i2.negate()); + testDiv(i1.negate(), i2.negate()); + } +} |