diff options
author | Andreas Beeker <kiwiwings@apache.org> | 2021-03-27 14:03:16 +0000 |
---|---|---|
committer | Andreas Beeker <kiwiwings@apache.org> | 2021-03-27 14:03:16 +0000 |
commit | 37791e4bdfc706aa5684745594260f243b4be7ee (patch) | |
tree | a8dd8d0976fc478074d52cd3de79e0e6b5e6a33a /src/testcases/org/apache/poi/util | |
parent | 2bb3839bfe3e3bacff79f8157465633e311239ce (diff) | |
download | poi-37791e4bdfc706aa5684745594260f243b4be7ee.tar.gz poi-37791e4bdfc706aa5684745594260f243b4be7ee.zip |
65206 - Migrate ant / maven to gradle build
update gradle files and project structure along https://github.com/centic9/poi/tree/gradle_build
remove eclipse IDE project files
remove obsolete record generator files
git-svn-id: https://svn.apache.org/repos/asf/poi/trunk@1888111 13f79535-47bb-0310-9956-ffa450edef68
Diffstat (limited to 'src/testcases/org/apache/poi/util')
23 files changed, 0 insertions, 3760 deletions
diff --git a/src/testcases/org/apache/poi/util/MemoryLeakVerifier.java b/src/testcases/org/apache/poi/util/MemoryLeakVerifier.java deleted file mode 100644 index da84469c3f..0000000000 --- a/src/testcases/org/apache/poi/util/MemoryLeakVerifier.java +++ /dev/null @@ -1,105 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.util; - -import static org.junit.jupiter.api.Assertions.assertNull; - -import java.lang.ref.WeakReference; -import java.util.ArrayList; -import java.util.List; - -/** - * A simple utility class that can verify that objects have been successfully garbage collected. - * - * Usage is something like - * - * private final MemoryLeakVerifier verifier = new MemoryLeakVerifier(); - - {@literal}After - void tearDown() { - verifier.assertGarbageCollected(); - } - - {@literal}Test - void someTest() { - ... - verifier.addObject(object); - } - - * - * This will verify at the end of the test if the object is actually removed by the - * garbage collector or if it lingers in memory for some reason. - * - * Idea taken from http://stackoverflow.com/a/7410460/411846 - */ -public class MemoryLeakVerifier { - private static final int MAX_GC_ITERATIONS = 50; - private static final int GC_SLEEP_TIME = 100; - - private final List<WeakReference<Object>> references = new ArrayList<>(); - - public MemoryLeakVerifier() { - } - - public void addObject(Object object) { - references.add(new WeakReference<>(object)); - } - - /** - * Attempts to perform a full garbage collection so that all weak references will be removed. Usually only - * a single GC is required, but there have been situations where some unused memory is not cleared up on the - * first pass. This method performs a full garbage collection and then validates that the weak reference - * now has been cleared. If it hasn't then the thread will sleep for 100 milliseconds and then retry up to - * 50 more times. If after this the object still has not been collected then the assertion will fail. - * - * Based upon the method described in: http://www.javaworld.com/javaworld/javatips/jw-javatip130.html - */ - public void assertGarbageCollected() { - assertGarbageCollected(MAX_GC_ITERATIONS); - } - - /** - * Used only for testing the class itself where we would like to fail faster than 5 seconds - * @param maxIterations The number of times a GC will be invoked until a possible memory leak is reported - */ - void assertGarbageCollected(int maxIterations) { - try { - for(WeakReference<Object> ref : references) { - assertGarbageCollected(ref, maxIterations); - } - } catch (InterruptedException e) { - // just ensure that we quickly return when the thread is interrupted - } - } - - private static void assertGarbageCollected(WeakReference<Object> ref, int maxIterations) throws InterruptedException { - Runtime runtime = Runtime.getRuntime(); - for (int i = 0; i < maxIterations; i++) { - runtime.runFinalization(); - runtime.gc(); - if (ref.get() == null) - break; - - // Pause for a while and then go back around the loop to try again... - //EventQueue.invokeAndWait(Procedure.NoOp); // Wait for the AWT event queue to have completed processing - Thread.sleep(GC_SLEEP_TIME); - } - - assertNull(ref.get(), "Object should not exist after " + MAX_GC_ITERATIONS + " collections, but still had: " + ref.get()); - } -} diff --git a/src/testcases/org/apache/poi/util/NullOutputStream.java b/src/testcases/org/apache/poi/util/NullOutputStream.java deleted file mode 100644 index ac76123a3c..0000000000 --- a/src/testcases/org/apache/poi/util/NullOutputStream.java +++ /dev/null @@ -1,41 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.util; - -import java.io.OutputStream; - -/** - * Implementation of an OutputStream which does nothing, used - * to redirect stdout to avoid spamming the console with output - */ -public final class NullOutputStream extends OutputStream { - public NullOutputStream() { - } - - @Override - public void write(byte[] b, int off, int len) { - } - - @Override - public void write(int b) { - } - - @Override - public void write(byte[] b) { - } -} diff --git a/src/testcases/org/apache/poi/util/NullPrintStream.java b/src/testcases/org/apache/poi/util/NullPrintStream.java deleted file mode 100644 index 5fd6bc64ad..0000000000 --- a/src/testcases/org/apache/poi/util/NullPrintStream.java +++ /dev/null @@ -1,88 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.util; - -import java.io.PrintStream; -import java.util.Locale; - -// need to override all methods to omit calls to UTF-handling methods -@SuppressForbidden("ignore super constructor with charset - omits declaring UnsupportedEncodingException") -public class NullPrintStream extends PrintStream { - @SuppressWarnings("resource") - public NullPrintStream() { - super(new NullOutputStream(), true); - } - @Override - public void write(int b) {} - @Override - public void write(byte[] buf, int off, int len) {} - @Override - public void print(boolean b) {} - @Override - public void print(char c) {} - @Override - public void print(int i) {} - @Override - public void print(long l) {} - @Override - public void print(float f) {} - @Override - public void print(double d) {} - @Override - public void print(char[] s) {} - @Override - public void print(String s) {} - @Override - public void print(Object obj) {} - @Override - public void println() {} - @Override - public void println(boolean x) {} - @Override - public void println(char x) {} - @Override - public void println(int x) {} - @Override - public void println(long x) {} - @Override - public void println(float x) {} - @Override - public void println(double x) {} - @Override - public void println(char[] x) {} - @Override - public void println(String x) {} - @Override - public void println(Object x) {} - @Override - public PrintStream printf(String format, Object... args) { return this; } - @Override - public PrintStream printf(Locale l, String format, Object... args) { return this; } - @Override - public PrintStream format(String format, Object... args) { return this; } - @Override - public PrintStream format(Locale l, String format, Object... args) { return this; } - @Override - public PrintStream append(CharSequence csq) { return this; } - @Override - public PrintStream append(CharSequence csq, int start, int end) { return this; } - @Override - public PrintStream append(char c) { return this; } - @Override - public void write(byte[] b) {} -} diff --git a/src/testcases/org/apache/poi/util/TestArrayUtil.java b/src/testcases/org/apache/poi/util/TestArrayUtil.java deleted file mode 100644 index 0038aa019d..0000000000 --- a/src/testcases/org/apache/poi/util/TestArrayUtil.java +++ /dev/null @@ -1,93 +0,0 @@ - -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.util; - -import static org.junit.jupiter.api.Assertions.assertArrayEquals; -import static org.junit.jupiter.api.Assertions.assertThrows; - -import java.util.Arrays; - -import org.junit.jupiter.api.Test; - -/** - * Unit test for ArrayUtil - */ -class TestArrayUtil { - /** - * Helper for testArrayMoveWithin - */ - private Integer[] getIntsList() { - return new Integer[] {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; - } - - /** - * Test to ensure that arrayMoveWithin works as expected - */ - @Test - void testArrayMoveWithin() { - // moveFrom, moveTo, numToMove, values... - Integer[][] data = { - // Moving to a later point in the array - // Shift 1 back - { 4, 8, 1, 0, 1, 2, 3, 5, 6, 7, 8, 4, 9 }, - // Shift front 1 back - { 0, 7, 1, 1, 2, 3, 4, 5, 6, 7, 0, 8, 9 }, - // Shift 1 to end - { 4, 9, 1, 0, 1, 2, 3, 5, 6, 7, 8, 9, 4 }, - - // Moving to an earlier point in the array - // Shift 1 forward - { 8, 3, 1, 0, 1, 2, 8, 3, 4, 5, 6, 7, 9 }, - // Shift end 1 forward - { 9, 2, 1, 0, 1, 9, 2, 3, 4, 5, 6, 7, 8 }, - // Shift 1 to front - { 5, 0, 1, 5, 0, 1, 2, 3, 4, 6, 7, 8, 9 }, - - // Moving many to a later point in the array - // Shift 3 back - { 2, 6, 3, 0, 1, 5, 6, 7, 8, 2, 3, 4, 9 }, - // Shift 3 to back - { 2, 7, 3, 0, 1, 5, 6, 7, 8, 9, 2, 3, 4 }, - // Shift from 3 front - { 0, 5, 3, 3, 4, 5, 6, 7, 0, 1, 2, 8, 9 }, - - // Moving many to an earlier point in the array - // Shift 3 forward - { 6, 2, 3, 0, 1, 6, 7, 8, 2, 3, 4, 5, 9 }, - // Shift 3 to front - { 6, 0, 3, 6, 7, 8, 0, 1, 2, 3, 4, 5, 9 }, - // Shift from 3 back - { 7, 3, 3, 0, 1, 2, 7, 8, 9, 3, 4, 5, 6 } - }; - - for (Integer[] entry : data) { - Integer[] ints = getIntsList(); - ArrayUtil.arrayMoveWithin(ints, entry[0], entry[1], entry[2]); - assertArrayEquals(ints, Arrays.copyOfRange(entry, 3, 13)); - } - - // Check can't shift more than we have - assertThrows(IllegalArgumentException.class, () -> ArrayUtil.arrayMoveWithin(getIntsList(), 7, 3, 5)); - // Good, we don't have 5 from 7 onwards - - // Check can't shift where would overshoot - assertThrows(IllegalArgumentException.class, () -> ArrayUtil.arrayMoveWithin(getIntsList(), 2, 7, 5)); - // Good, we can't fit 5 in starting at 7 - } -} diff --git a/src/testcases/org/apache/poi/util/TestBitField.java b/src/testcases/org/apache/poi/util/TestBitField.java deleted file mode 100644 index 55c30087fa..0000000000 --- a/src/testcases/org/apache/poi/util/TestBitField.java +++ /dev/null @@ -1,217 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.util; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertTrue; - -import org.junit.jupiter.api.Test; - -/** - * Class to test BitField functionality - */ -final class TestBitField { - private static BitField bf_multi = BitFieldFactory.getInstance(0x3F80); - private static BitField bf_single = BitFieldFactory.getInstance(0x4000); - - @Test - void testGetValue() { - assertEquals(bf_multi.getValue(-1), 127); - assertEquals(bf_multi.getValue(0), 0); - assertEquals(bf_single.getValue(-1), 1); - assertEquals(bf_single.getValue(0), 0); - } - - @Test - void testGetShortValue() { - assertEquals(bf_multi.getShortValue(( short ) -1), ( short ) 127); - assertEquals(bf_multi.getShortValue(( short ) 0), ( short ) 0); - assertEquals(bf_single.getShortValue(( short ) -1), ( short ) 1); - assertEquals(bf_single.getShortValue(( short ) 0), ( short ) 0); - } - - @Test - void testGetRawValue() { - assertEquals(bf_multi.getRawValue(-1), 0x3F80); - assertEquals(bf_multi.getRawValue(0), 0); - assertEquals(bf_single.getRawValue(-1), 0x4000); - assertEquals(bf_single.getRawValue(0), 0); - } - - @Test - void testGetShortRawValue() { - assertEquals(bf_multi.getShortRawValue(( short ) -1), - ( short ) 0x3F80); - assertEquals(bf_multi.getShortRawValue(( short ) 0), ( short ) 0); - assertEquals(bf_single.getShortRawValue(( short ) -1), - ( short ) 0x4000); - assertEquals(bf_single.getShortRawValue(( short ) 0), ( short ) 0); - } - - @Test - void testIsSet() { - assertFalse(bf_multi.isSet(0)); - for (int j = 0x80; j <= 0x3F80; j += 0x80) - { - assertTrue(bf_multi.isSet(j)); - } - assertFalse(bf_single.isSet(0)); - assertTrue(bf_single.isSet(0x4000)); - } - - @Test - void testIsAllSet() { - for (int j = 0; j < 0x3F80; j += 0x80) - { - assertFalse(bf_multi.isAllSet(j)); - } - assertTrue(bf_multi.isAllSet(0x3F80)); - assertFalse(bf_single.isAllSet(0)); - assertTrue(bf_single.isAllSet(0x4000)); - } - - @Test - void testSetValue() { - for (int j = 0; j < 128; j++) - { - assertEquals(bf_multi.getValue(bf_multi.setValue(0, j)), j); - assertEquals(bf_multi.setValue(0, j), j << 7); - } - - // verify that excess bits are stripped off - assertEquals(bf_multi.setValue(0x3f80, 128), 0); - for (int j = 0; j < 2; j++) - { - assertEquals(bf_single.getValue(bf_single.setValue(0, j)), j); - assertEquals(bf_single.setValue(0, j), j << 14); - } - - // verify that excess bits are stripped off - assertEquals(bf_single.setValue(0x4000, 2), 0); - } - - @Test - void testSetShortValue() { - for (int j = 0; j < 128; j++) - { - assertEquals(bf_multi - .getShortValue(bf_multi - .setShortValue(( short ) 0, ( short ) j)), ( short ) j); - assertEquals(bf_multi.setShortValue(( short ) 0, ( short ) j), - ( short ) (j << 7)); - } - - // verify that excess bits are stripped off - assertEquals(bf_multi.setShortValue(( short ) 0x3f80, ( short ) 128), - ( short ) 0); - for (int j = 0; j < 2; j++) - { - assertEquals(bf_single - .getShortValue(bf_single - .setShortValue(( short ) 0, ( short ) j)), ( short ) j); - assertEquals(bf_single.setShortValue(( short ) 0, ( short ) j), - ( short ) (j << 14)); - } - - // verify that excess bits are stripped off - assertEquals(bf_single.setShortValue(( short ) 0x4000, ( short ) 2), - ( short ) 0); - } - - @Test - void testByte() { - assertEquals(1, BitFieldFactory.getInstance(1).setByteBoolean(( byte ) 0, true)); - assertEquals(2, BitFieldFactory.getInstance(2).setByteBoolean(( byte ) 0, true)); - assertEquals(4, BitFieldFactory.getInstance(4).setByteBoolean(( byte ) 0, true)); - assertEquals(8, BitFieldFactory.getInstance(8).setByteBoolean(( byte ) 0, true)); - assertEquals(16, BitFieldFactory.getInstance(16).setByteBoolean(( byte ) 0, true)); - assertEquals(32, BitFieldFactory.getInstance(32).setByteBoolean(( byte ) 0, true)); - assertEquals(64, BitFieldFactory.getInstance(64).setByteBoolean(( byte ) 0, true)); - assertEquals(-128, - BitFieldFactory.getInstance(128).setByteBoolean(( byte ) 0, true)); - assertEquals(0, BitFieldFactory.getInstance(1).setByteBoolean(( byte ) 1, false)); - assertEquals(0, BitFieldFactory.getInstance(2).setByteBoolean(( byte ) 2, false)); - assertEquals(0, BitFieldFactory.getInstance(4).setByteBoolean(( byte ) 4, false)); - assertEquals(0, BitFieldFactory.getInstance(8).setByteBoolean(( byte ) 8, false)); - assertEquals(0, BitFieldFactory.getInstance(16).setByteBoolean(( byte ) 16, false)); - assertEquals(0, BitFieldFactory.getInstance(32).setByteBoolean(( byte ) 32, false)); - assertEquals(0, BitFieldFactory.getInstance(64).setByteBoolean(( byte ) 64, false)); - assertEquals(0, BitFieldFactory.getInstance(128).setByteBoolean(( byte ) 128, - false)); - assertEquals(-2, BitFieldFactory.getInstance(1).setByteBoolean(( byte ) 255, false)); - byte clearedBit = BitFieldFactory.getInstance(0x40).setByteBoolean(( byte ) -63, - false); - - assertFalse(BitFieldFactory.getInstance(0x40).isSet(clearedBit)); - } - - @Test - void testClear() { - assertEquals(bf_multi.clear(-1), 0xFFFFC07F); - assertEquals(bf_single.clear(-1), 0xFFFFBFFF); - } - - @Test - void testClearShort() { - assertEquals(bf_multi.clearShort(( short ) -1), ( short ) 0xC07F); - assertEquals(bf_single.clearShort(( short ) -1), ( short ) 0xBFFF); - } - - @Test - void testSet() { - assertEquals(bf_multi.set(0), 0x3F80); - assertEquals(bf_single.set(0), 0x4000); - } - - @Test - void testSetShort() { - assertEquals(bf_multi.setShort(( short ) 0), ( short ) 0x3F80); - assertEquals(bf_single.setShort(( short ) 0), ( short ) 0x4000); - } - - @Test - void testSetBoolean() { - assertEquals(bf_multi.set(0), bf_multi.setBoolean(0, true)); - assertEquals(bf_single.set(0), bf_single.setBoolean(0, true)); - assertEquals(bf_multi.clear(-1), bf_multi.setBoolean(-1, false)); - assertEquals(bf_single.clear(-1), bf_single.setBoolean(-1, false)); - } - - @Test - void testSetShortBoolean() { - assertEquals(bf_multi.setShort(( short ) 0), - bf_multi.setShortBoolean(( short ) 0, true)); - assertEquals(bf_single.setShort(( short ) 0), - bf_single.setShortBoolean(( short ) 0, true)); - assertEquals(bf_multi.clearShort(( short ) -1), - bf_multi.setShortBoolean(( short ) -1, false)); - assertEquals(bf_single.clearShort(( short ) -1), - bf_single.setShortBoolean(( short ) -1, false)); - } - - @Test - void testSetLargeValues() { - final BitField bf1 = new BitField(0xF), bf2 = new BitField(0xF0000000); - int a = 0; - a = bf1.setValue(a, 9); - a = bf2.setValue(a, 9); - assertEquals(9, bf1.getValue(a)); - assertEquals(9, bf2.getValue(a)); - } -} diff --git a/src/testcases/org/apache/poi/util/TestByteField.java b/src/testcases/org/apache/poi/util/TestByteField.java deleted file mode 100644 index 8c37667fbc..0000000000 --- a/src/testcases/org/apache/poi/util/TestByteField.java +++ /dev/null @@ -1,138 +0,0 @@ - -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.util; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.fail; - -import java.io.ByteArrayInputStream; -import java.io.IOException; - -import org.junit.jupiter.api.Test; - -/** - * Unit test for ByteField class - */ -final class TestByteField { - - private static final byte[] _test_array = { - Byte.MIN_VALUE, ( byte ) -1, ( byte ) 0, ( byte ) 1, Byte.MAX_VALUE - }; - - @Test - void testConstructors() { - try { - new ByteField(-1); - fail("Should have caught ArrayIndexOutOfBoundsException"); - } catch (ArrayIndexOutOfBoundsException ignored_e) { - // as expected - } - ByteField field = new ByteField(2); - - assertEquals(( byte ) 0, field.get()); - try { - new ByteField(-1, ( byte ) 1); - fail("Should have caught ArrayIndexOutOfBoundsException"); - } catch (ArrayIndexOutOfBoundsException ignored_e) { - // as expected - } - field = new ByteField(2, ( byte ) 3); - assertEquals(( byte ) 3, field.get()); - byte[] array = new byte[ 3 ]; - - try { - new ByteField(-1, ( byte ) 1, array); - fail("Should have caught ArrayIndexOutOfBoundsException"); - } catch (ArrayIndexOutOfBoundsException ignored_e) { - // as expected - } - field = new ByteField(2, ( byte ) 4, array); - assertEquals(( byte ) 4, field.get()); - assertEquals(( byte ) 4, array[ 2 ]); - array = new byte[ 2 ]; - try { - new ByteField(2, ( byte ) 5, array); - fail("should have gotten ArrayIndexOutOfBoundsException"); - } catch (ArrayIndexOutOfBoundsException ignored_e) { - // as expected - } - for (byte b : _test_array) { - array = new byte[ 1 ]; - new ByteField(0, b, array); - assertEquals(b, new ByteField(0, array).get()); - } - } - - @Test - void testSet() { - ByteField field = new ByteField(0); - byte[] array = new byte[ 1 ]; - - for (int j = 0; j < _test_array.length; j++) { - field.set(_test_array[ j ]); - assertEquals(_test_array[ j ], field.get(), "testing _1 " + j); - field = new ByteField(0); - field.set(_test_array[ j ], array); - assertEquals(_test_array[ j ], field.get(), "testing _2 "); - assertEquals(_test_array[ j ], array[ 0 ], "testing _3 "); - } - } - - @Test - void testReadFromBytes() { - ByteField field = new ByteField(1); - byte[] array = new byte[ 1 ]; - - try { - field.readFromBytes(array); - fail("should have caught ArrayIndexOutOfBoundsException"); - } catch (ArrayIndexOutOfBoundsException ignored_e) { - // as expected - } - field = new ByteField(0); - for (int j = 0; j < _test_array.length; j++) { - array[ 0 ] = _test_array[ j ]; - field.readFromBytes(array); - assertEquals(_test_array[ j ], field.get(), "testing " + j); - } - } - - @Test - void testReadFromStream() throws IOException { - ByteField field = new ByteField(0); - ByteArrayInputStream stream = new ByteArrayInputStream(_test_array.clone()); - - for (int j = 0; j < _test_array.length; j++) { - field.readFromStream(stream); - assertEquals(_test_array[ j ], field.get(), "Testing " + j); - } - } - - @Test - void testWriteToBytes() { - ByteField field = new ByteField(0); - byte[] array = new byte[ 1 ]; - - for (byte b : _test_array) { - field.set(b); - field.writeToBytes(array); - assertEquals(b, array[ 0 ], "testing "); - } - } -} diff --git a/src/testcases/org/apache/poi/util/TestHexDump.java b/src/testcases/org/apache/poi/util/TestHexDump.java deleted file mode 100644 index 4a465cb4be..0000000000 --- a/src/testcases/org/apache/poi/util/TestHexDump.java +++ /dev/null @@ -1,196 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.util; - -import static org.junit.jupiter.api.Assertions.assertArrayEquals; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.junit.jupiter.api.Assertions.assertTrue; - -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.PrintStream; -import java.io.UnsupportedEncodingException; - -import org.junit.jupiter.api.AfterAll; -import org.junit.jupiter.api.BeforeAll; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.params.ParameterizedTest; -import org.junit.jupiter.params.provider.ValueSource; - -class TestHexDump { - - private static PrintStream SYSTEM_OUT; - - @BeforeAll - public static void setUp() throws UnsupportedEncodingException { - SYSTEM_OUT = System.out; - System.setOut(new NullPrintStream()); - } - - @AfterAll - public static void tearDown() { - System.setOut(SYSTEM_OUT); - } - - @Test - void testDump() throws IOException { - byte[] testArray = testArray(); - ByteArrayOutputStream streamAct = new ByteArrayOutputStream(); - HexDump.dump(testArray, 0, streamAct, 0); - byte[] bytesAct = streamAct.toByteArray(); - byte[] bytesExp = toHexDump(0, 0); - - assertEquals(bytesExp.length, bytesAct.length, "array size mismatch"); - assertArrayEquals(bytesExp, bytesAct, "array mismatch"); - - // verify proper behavior with non-zero offset - streamAct.reset(); - HexDump.dump(testArray, 0x10000000L, streamAct, 0); - bytesAct = streamAct.toByteArray(); - bytesExp = toHexDump(0x10000000L,0); - - assertEquals(bytesExp.length, bytesAct.length, "array size mismatch"); - assertArrayEquals(bytesExp, bytesAct, "array mismatch"); - - // verify proper behavior with negative offset - streamAct.reset(); - HexDump.dump(testArray, 0xFF000000L, streamAct, 0); - bytesAct = streamAct.toByteArray(); - bytesExp = toHexDump(0xFF000000L,0); - - assertEquals(bytesExp.length, bytesAct.length, "array size mismatch"); - assertArrayEquals(bytesExp, bytesAct, "array mismatch"); - - // verify proper behavior with non-zero index - streamAct.reset(); - HexDump.dump(testArray, 0xFF000000L, streamAct, 0x81); - bytesAct = streamAct.toByteArray(); - bytesExp = toHexDump(0xFF000000L,0x81); - - assertEquals(bytesExp.length, bytesAct.length, "array size mismatch"); - assertArrayEquals(bytesExp, bytesAct, "array mismatch"); - - - // verify proper behavior with negative index - streamAct.reset(); - assertThrows(ArrayIndexOutOfBoundsException.class, () -> HexDump.dump(testArray, 0x10000000L, streamAct, -1)); - - // verify proper behavior with index that is too large - streamAct.reset(); - assertThrows(ArrayIndexOutOfBoundsException.class, () -> HexDump.dump(testArray, 0x10000000L, streamAct, testArray.length)); - - // verify proper behavior with null stream - assertThrows(IllegalArgumentException.class, () -> HexDump.dump(testArray, 0x10000000L, null, 0)); - - // verify proper behaviour with empty byte array - streamAct.reset(); - HexDump.dump( new byte[0], 0, streamAct, 0 ); - assertEquals( "No Data" + System.getProperty( "line.separator"), streamAct.toString(LocaleUtil.CHARSET_1252.name()) ); - - } - - private byte[] toHexDump(long offset, int index) { - StringBuilder strExp = new StringBuilder(), chrs = new StringBuilder(); - Object[] obj = new Object[33]; - StringBuilder format = new StringBuilder(); - - for (int j = 0; j < 16 && (index + j*16) < 256; j++) { - obj[0] = offset+index+j*16L; - chrs.setLength(0); - format.setLength(0); - format.append("%08X "); - for (int k = 0; k < 16; k++) { - if (index+j*16+k < 256){ - obj[k+1] = index+j*16+k; - chrs.append(HexDump.toAscii(index+j*16+k)); - format.append("%02X "); - } else { - format.append(" "); - } - } - obj[17] = chrs.toString(); - format.append("%18$s").append(HexDump.EOL); - - String str = String.format(LocaleUtil.getUserLocale(), format.toString(), obj); - strExp.append(str); - } - return strExp.toString().getBytes(HexDump.UTF8); - } - - @Test - void testToHex() { - assertEquals("000A", HexDump.toHex((short)0xA)); - - assertEquals("0A", HexDump.toHex((byte)0xA)); - assertEquals("0000000A", HexDump.toHex(0xA)); - - assertEquals("[]", HexDump.toHex(new byte[] { })); - assertEquals("[0A]", HexDump.toHex(new byte[] { 0xA })); - assertEquals("[0A, 0B]", HexDump.toHex(new byte[] { 0xA, 0xB })); - - assertEquals("FFFF", HexDump.toHex((short)0xFFFF)); - - assertEquals("00000000000004D2", HexDump.toHex(1234L)); - - assertEquals("0xFE", HexDump.byteToHex(-2)); - assertEquals("0x25", HexDump.byteToHex(37)); - assertEquals("0xFFFE", HexDump.shortToHex(-2)); - assertEquals("0x0005", HexDump.shortToHex(5)); - assertEquals("0xFFFFFF9C", HexDump.intToHex(-100)); - assertEquals("0x00001001", HexDump.intToHex(4097)); - assertEquals("0xFFFFFFFFFFFF0006", HexDump.longToHex(-65530)); - assertEquals("0x0000000000003FCD", HexDump.longToHex(16333)); - } - - @Test - void testDumpToString() { - byte[] testArray = testArray(); - String dump = HexDump.dump(testArray, 0, 0); - //System.out.println("Hex: \n" + dump); - assertTrue(dump.contains("0123456789:;<=>?"), "Had: \n" + dump); - - dump = HexDump.dump(testArray, 2, 1); - //System.out.println("Hex: \n" + dump); - assertTrue(dump.contains("123456789:;<=>?@"), "Had: \n" + dump); - } - - @ParameterizedTest - @ValueSource(ints = {-1, 2, 1}) - void testDumpToStringOutOfIndex1(int index) { - assertThrows(ArrayIndexOutOfBoundsException.class, () -> - HexDump.dump(new byte[1], 0, index)); - } - - @ParameterizedTest - @ValueSource(ints = {0, 1}) - void testDumpToStringNoDataEOL(int index) { - String s = HexDump.dump(new byte[0], 0, index); - assertEquals("No Data", s.trim()); - } - - private static byte[] testArray() { - byte[] testArray = new byte[ 256 ]; - - for (int j = 0; j < 256; j++) { - testArray[ j ] = ( byte ) j; - } - - return testArray; - } -} diff --git a/src/testcases/org/apache/poi/util/TestIOUtils.java b/src/testcases/org/apache/poi/util/TestIOUtils.java deleted file mode 100644 index 19b64dd3c1..0000000000 --- a/src/testcases/org/apache/poi/util/TestIOUtils.java +++ /dev/null @@ -1,579 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.util; - -import static org.junit.jupiter.api.Assertions.assertArrayEquals; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.junit.jupiter.api.Assertions.assertTrue; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.EOFException; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.io.PushbackInputStream; -import java.nio.ByteBuffer; -import java.nio.channels.ReadableByteChannel; -import java.nio.charset.StandardCharsets; -import java.util.Random; - -import org.apache.poi.EmptyFileException; -import org.junit.jupiter.api.AfterAll; -import org.junit.jupiter.api.BeforeAll; -import org.junit.jupiter.api.Test; - -final class TestIOUtils { - private static File TMP; - private static final long LENGTH = 300 + new Random().nextInt(9000); - - @BeforeAll - public static void setUp() throws IOException { - TMP = File.createTempFile("poi-ioutils-", ""); - try (OutputStream os = new FileOutputStream(TMP)) { - for (int i = 0; i < LENGTH; i++) { - os.write(0x01); - } - } - } - - @AfterAll - public static void tearDown() { - if (TMP != null) { - assertTrue(TMP.delete()); - } - } - - private static InputStream data123() { - return new ByteArrayInputStream(new byte[]{1,2,3}); - } - - @Test - void testPeekFirst8Bytes() throws Exception { - assertArrayEquals("01234567".getBytes(StandardCharsets.UTF_8), - IOUtils.peekFirst8Bytes(new ByteArrayInputStream("0123456789".getBytes(StandardCharsets.UTF_8)))); - } - - @Test - void testPeekFirst8BytesWithPushbackInputStream() throws Exception { - assertArrayEquals("01234567".getBytes(StandardCharsets.UTF_8), - IOUtils.peekFirst8Bytes(new PushbackInputStream(new ByteArrayInputStream("0123456789".getBytes(StandardCharsets.UTF_8)), 8))); - } - - @Test - void testPeekFirst8BytesTooLessAvailable() throws Exception { - assertArrayEquals(new byte[] { 1, 2, 3, 0, 0, 0, 0, 0}, IOUtils.peekFirst8Bytes(data123())); - } - - @Test - void testPeekFirst8BytesEmpty() { - assertThrows(EmptyFileException.class, () -> - IOUtils.peekFirst8Bytes(new ByteArrayInputStream(new byte[0]))); - } - - @Test - void testToByteArray() throws Exception { - assertArrayEquals(new byte[] { 1, 2, 3}, IOUtils.toByteArray(data123())); - } - - @Test - void testToByteArrayToSmall() { - assertThrows(IOException.class, () -> IOUtils.toByteArray(data123(), 10)); - } - - @Test - void testToByteArrayMaxLengthToSmall() { - assertThrows(IOException.class, () -> IOUtils.toByteArray(data123(), 10, 10)); - } - - @Test - void testToByteArrayNegativeLength() { - assertThrows(RecordFormatException.class, () -> IOUtils.toByteArray(data123(), -1)); - } - - @Test - void testToByteArrayNegativeMaxLength() { - assertThrows(RecordFormatException.class, () -> IOUtils.toByteArray(data123(), 10, -1)); - } - - @Test - void testToByteArrayByteBuffer() { - assertArrayEquals(new byte[] { 1, 2, 3}, - IOUtils.toByteArray(ByteBuffer.wrap(new byte[]{1, 2, 3}), 10)); - } - - @Test - void testToByteArrayByteBufferNonArray() { - ByteBuffer buffer = ByteBuffer.allocate(3); - buffer.put(new byte[] { 1, 2, 3}); - buffer.position(0); - assertFalse(buffer.asReadOnlyBuffer().hasArray()); - assertEquals(3, buffer.asReadOnlyBuffer().remaining()); - - assertArrayEquals(new byte[] { 1, 2, 3}, - IOUtils.toByteArray(buffer.asReadOnlyBuffer(), 3)); - } - - @Test - void testToByteArrayByteBufferToSmall() { - assertArrayEquals(new byte[] { 1, 2, 3, 4, 5, 6, 7}, - IOUtils.toByteArray(ByteBuffer.wrap(new byte[]{1, 2, 3, 4, 5, 6, 7}), 3)); - } - - @Test - void testSkipFully() throws IOException { - try (InputStream is = new FileInputStream(TMP)) { - long skipped = IOUtils.skipFully(is, 20000L); - assertEquals(LENGTH, skipped); - } - } - - @Test - void testSkipFullyGtIntMax() throws IOException { - try (InputStream is = new FileInputStream(TMP)) { - long skipped = IOUtils.skipFully(is, Integer.MAX_VALUE + 20000L); - assertEquals(LENGTH, skipped); - } - } - - @Test - void testSkipFullyByteArray() throws IOException { - ByteArrayOutputStream bos = new ByteArrayOutputStream(); - try (InputStream is = new FileInputStream(TMP)) { - assertEquals(LENGTH, IOUtils.copy(is, bos)); - long skipped = IOUtils.skipFully(new ByteArrayInputStream(bos.toByteArray()), 20000L); - assertEquals(LENGTH, skipped); - } - } - - @Test - void testSkipFullyByteArrayGtIntMax() throws IOException { - ByteArrayOutputStream bos = new ByteArrayOutputStream(); - try (InputStream is = new FileInputStream(TMP)) { - assertEquals(LENGTH, IOUtils.copy(is, bos)); - long skipped = IOUtils.skipFully(new ByteArrayInputStream(bos.toByteArray()), Integer.MAX_VALUE + 20000L); - assertEquals(LENGTH, skipped); - } - } - - @Test - void testCopyToFile() throws IOException { - File dest = File.createTempFile("poi-ioutils-", ""); - try { - try (InputStream is = new FileInputStream(TMP)) { - assertEquals(LENGTH, IOUtils.copy(is, dest)); - } - - try (FileInputStream strOrig = new FileInputStream(TMP); - FileInputStream strDest = new FileInputStream(dest)) { - byte[] bytesOrig = new byte[(int)LENGTH]; - byte[] bytesDest = new byte[(int)LENGTH]; - IOUtils.readFully(strOrig, bytesOrig); - IOUtils.readFully(strDest, bytesDest); - assertArrayEquals(bytesOrig, bytesDest); - } - } finally { - assertTrue(dest.delete()); - } - } - - @Test - void testCopyToInvalidFile() throws IOException { - try (InputStream is = new FileInputStream(TMP)) { - assertThrows(RuntimeException.class, - () -> { - // try with two different paths so we fail on both Unix and Windows - IOUtils.copy(is, new File("/notexisting/directory/structure")); - IOUtils.copy(is, new File("c:\\note&/()\"§=§%&!§$81§0_:;,.-'#*+~`?ß´ß0´ß9243xisting\\directory\\structure")); - }); - } - } - - @Test - void testSkipFullyBug61294() throws IOException { - long skipped = IOUtils.skipFully(new ByteArrayInputStream(new byte[0]), 1); - assertEquals(-1L, skipped); - } - - @Test - void testZeroByte() throws IOException { - long skipped = IOUtils.skipFully((new ByteArrayInputStream(new byte[0])), 100); - assertEquals(-1L, skipped); - } - - @Test - void testSkipZero() throws IOException { - try (InputStream is = new FileInputStream(TMP)) { - long skipped = IOUtils.skipFully(is, 0); - assertEquals(0, skipped); - } - } - - @Test - void testSkipNegative() throws IOException { - try (InputStream is = new FileInputStream(TMP)) { - assertThrows(IllegalArgumentException.class, () -> IOUtils.skipFully(is, -1)); - } - } - - @Test - void testMaxLengthTooLong() throws IOException { - try (InputStream is = new FileInputStream(TMP)) { - assertThrows(RecordFormatException.class, () -> IOUtils.toByteArray(is, Integer.MAX_VALUE, 100)); - } - } - - @Test - void testMaxLengthIgnored() throws IOException { - try (InputStream is = new FileInputStream(TMP)) { - int len = IOUtils.toByteArray(is, 90, Integer.MAX_VALUE).length; - assertEquals(90, len); - len = IOUtils.toByteArray(is, 90, 100).length; - assertEquals(90, len); - len = IOUtils.toByteArray(is, Integer.MAX_VALUE, Integer.MAX_VALUE).length; - assertTrue(len > 300-2*90); - } - } - - @Test - void testMaxLengthInvalid() throws IOException { - try (InputStream is = new FileInputStream(TMP)) { - assertThrows(RecordFormatException.class, () -> IOUtils.toByteArray(is, 90, 80)); - } - } - - @Test - void testWonkyInputStream() throws IOException { - long skipped = IOUtils.skipFully(new WonkyInputStream(), 10000); - assertEquals(10000, skipped); - } - - @Test - void testSetMaxOverride() throws IOException { - ByteArrayInputStream stream = new ByteArrayInputStream("abc".getBytes(StandardCharsets.UTF_8)); - byte[] bytes = IOUtils.toByteArray(stream); - assertNotNull(bytes); - assertEquals("abc", new String(bytes, StandardCharsets.UTF_8)); - } - - @Test - void testSetMaxOverrideLimit() throws IOException { - IOUtils.setByteArrayMaxOverride(30 * 1024 * 1024); - try { - ByteArrayInputStream stream = new ByteArrayInputStream("abc".getBytes(StandardCharsets.UTF_8)); - byte[] bytes = IOUtils.toByteArray(stream); - assertNotNull(bytes); - assertEquals("abc", new String(bytes, StandardCharsets.UTF_8)); - } finally { - IOUtils.setByteArrayMaxOverride(-1); - } - } - - @Test - void testSetMaxOverrideOverLimit() { - IOUtils.setByteArrayMaxOverride(2); - try { - ByteArrayInputStream stream = new ByteArrayInputStream("abc".getBytes(StandardCharsets.UTF_8)); - assertThrows(RecordFormatException.class, () -> IOUtils.toByteArray(stream)); - } finally { - IOUtils.setByteArrayMaxOverride(-1); - } - } - - @Test - void testSetMaxOverrideWithLength() throws IOException { - ByteArrayInputStream stream = new ByteArrayInputStream("abc".getBytes(StandardCharsets.UTF_8)); - byte[] bytes = IOUtils.toByteArray(stream, 3, 100); - assertNotNull(bytes); - assertEquals("abc", new String(bytes, StandardCharsets.UTF_8)); - } - - @Test - void testSetMaxOverrideLimitWithLength() throws IOException { - IOUtils.setByteArrayMaxOverride(30 * 1024 * 1024); - try { - ByteArrayInputStream stream = new ByteArrayInputStream("abc".getBytes(StandardCharsets.UTF_8)); - byte[] bytes = IOUtils.toByteArray(stream, 3, 100); - assertNotNull(bytes); - assertEquals("abc", new String(bytes, StandardCharsets.UTF_8)); - } finally { - IOUtils.setByteArrayMaxOverride(-1); - } - } - - @Test - void testSetMaxOverrideOverLimitWithLength() { - IOUtils.setByteArrayMaxOverride(2); - try { - ByteArrayInputStream stream = new ByteArrayInputStream("abc".getBytes(StandardCharsets.UTF_8)); - assertThrows(RecordFormatException.class, () -> IOUtils.toByteArray(stream, 3, 100)); - } finally { - IOUtils.setByteArrayMaxOverride(-1); - } - } - - @Test - void testSafelyAllocate() { - byte[] bytes = IOUtils.safelyAllocate(30, 200); - assertNotNull(bytes); - assertEquals(30, bytes.length); - } - - @Test - void testSafelyAllocateLimit() { - IOUtils.setByteArrayMaxOverride(40); - try { - byte[] bytes = IOUtils.safelyAllocate(30, 200); - assertNotNull(bytes); - assertEquals(30, bytes.length); - } finally { - IOUtils.setByteArrayMaxOverride(-1); - } - } - - @Test - void testReadFully() throws IOException { - byte[] bytes = new byte[2]; - assertEquals(2, IOUtils.readFully(new ByteArrayInputStream(new byte[] {1, 2, 3}), bytes, 0, 2)); - assertArrayEquals(new byte[] {1,2}, bytes); - } - - @Test - void testReadFullyEOF() throws IOException { - byte[] bytes = new byte[2]; - assertEquals(2, IOUtils.readFully(new NullInputStream(2), bytes, 0, 4)); - assertArrayEquals(new byte[] {0,0}, bytes); - } - - @Test - void testReadFullyEOFZero() throws IOException { - byte[] bytes = new byte[2]; - assertEquals(-1, IOUtils.readFully(new NullInputStream(0), bytes, 0, 4)); - assertArrayEquals(new byte[] {0,0}, bytes); - } - - @Test - void testReadFullySimple() throws IOException { - byte[] bytes = new byte[2]; - assertEquals(2, IOUtils.readFully(new ByteArrayInputStream(new byte[] {1, 2, 3}), bytes)); - assertArrayEquals(new byte[] {1,2}, bytes); - } - - @Test - void testReadFullyOffset() throws IOException { - byte[] bytes = new byte[3]; - assertEquals(2, IOUtils.readFully(new ByteArrayInputStream(new byte[] {1, 2, 3}), bytes, 1, 2)); - assertArrayEquals(new byte[] {0, 1,2}, bytes); - } - - @Test - void testReadFullyAtLength() throws IOException { - byte[] bytes = new byte[3]; - assertEquals(3, IOUtils.readFully(new ByteArrayInputStream(new byte[] {1, 2, 3}), bytes, 0, 3)); - assertArrayEquals(new byte[] {1,2, 3}, bytes); - } - - - @Test - void testReadFullyChannel() throws IOException { - ByteBuffer bytes = ByteBuffer.allocate(2); - assertEquals(2, IOUtils.readFully(new SimpleByteChannel(new byte[]{1, 2, 3}), bytes)); - assertArrayEquals(new byte[] {1,2}, bytes.array()); - assertEquals(2, bytes.position()); - } - - @Test - void testReadFullyChannelEOF() throws IOException { - ByteBuffer bytes = ByteBuffer.allocate(2); - assertEquals(-1, IOUtils.readFully(new EOFByteChannel(false), bytes)); - assertArrayEquals(new byte[] {0,0}, bytes.array()); - assertEquals(0, bytes.position()); - } - - @Test - void testReadFullyChannelEOFException() { - ByteBuffer bytes = ByteBuffer.allocate(2); - assertThrows(IOException.class, - () -> IOUtils.readFully(new EOFByteChannel(true), bytes)); - } - - @Test - void testReadFullyChannelSimple() throws IOException { - ByteBuffer bytes = ByteBuffer.allocate(2); - assertEquals(2, IOUtils.readFully(new SimpleByteChannel(new byte[] {1, 2, 3}), bytes)); - assertArrayEquals(new byte[] {1,2}, bytes.array()); - assertEquals(2, bytes.position()); - } - - @Test - public void testChecksum() { - assertEquals(0L, IOUtils.calculateChecksum(new byte[0])); - assertEquals(3057449933L, IOUtils.calculateChecksum(new byte[] { 1, 2, 3, 4})); - } - - @Test - public void testChecksumStream() throws IOException { - assertEquals(0L, IOUtils.calculateChecksum(new NullInputStream(0))); - assertEquals(0L, IOUtils.calculateChecksum(new NullInputStream(1))); - assertEquals(3057449933L, IOUtils.calculateChecksum(new ByteArrayInputStream(new byte[] { 1, 2, 3, 4}))); - assertThrows(EOFException.class, - () -> IOUtils.calculateChecksum(new NullInputStream(1, true))); - } - - /** - * This returns 0 for the first call to skip and then reads - * as requested. This tests that the fallback to read() works. - */ - private static class WonkyInputStream extends InputStream { - int skipCalled; - int readCalled; - - @Override - public int read() { - readCalled++; - return 0; - } - - @Override - public int read(byte[] arr, int offset, int len) { - readCalled++; - return len; - } - - @Override - public long skip(long len) { - skipCalled++; - if (skipCalled == 1) { - return 0; - } else if (skipCalled > 100) { - return len; - } else { - return 100; - } - } - - @Override - public int available() { - return 100000; - } - } - - private static class EOFByteChannel implements ReadableByteChannel { - private final boolean throwException; - - public EOFByteChannel(boolean throwException) { - this.throwException = throwException; - } - - @Override - public int read(ByteBuffer dst) throws IOException { - if (throwException) { - throw new IOException("EOF"); - } - - return -1; - } - - @Override - public boolean isOpen() { - return false; - } - - @Override - public void close() throws IOException { - - } - } - - private static class SimpleByteChannel extends InputStream implements ReadableByteChannel { - private final byte[] bytes; - - public SimpleByteChannel(byte[] bytes) { - this.bytes = bytes; - } - - @Override - public int read() throws IOException { - throw new UnsupportedOperationException(); - } - - @Override - public int read(ByteBuffer dst) throws IOException { - int toRead = Math.min(bytes.length, dst.capacity()); - dst.put(bytes, 0, toRead); - return toRead; - } - - @Override - public boolean isOpen() { - return false; - } - } - - public class NullInputStream extends InputStream { - private final int bytes; - private final boolean exception; - - private int position; - - public NullInputStream(int bytes) { - this(bytes, false); - } - - public NullInputStream(int bytes, boolean exception) { - this.bytes = bytes; - this.exception = exception; - } - - @Override - public int read() throws IOException { - if (position >= bytes) { - return handleReturn(); - } - - position++; - return 0; - } - - private int handleReturn() throws EOFException { - if (exception) { - throw new EOFException(); - } else { - return -1; - } - } - - @Override - public int read(byte[] b, int off, int len) throws IOException { - int toRead = Math.min(b.length, len); - if (toRead > (bytes - position)) { - return handleReturn(); - } - toRead = Math.min(toRead, (bytes - position)); - - position += toRead; - return toRead; - } - } -} diff --git a/src/testcases/org/apache/poi/util/TestIntList.java b/src/testcases/org/apache/poi/util/TestIntList.java deleted file mode 100644 index 3483933ce4..0000000000 --- a/src/testcases/org/apache/poi/util/TestIntList.java +++ /dev/null @@ -1,515 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.util; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertNotEquals; -import static org.junit.jupiter.api.Assertions.assertNotSame; -import static org.junit.jupiter.api.Assertions.assertSame; -import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.junit.jupiter.api.Assertions.assertTrue; - -import org.junit.jupiter.api.Test; - -/** - * Class to test IntList - * - * @author Marc Johnson - */ -final class TestIntList { - @Test - void testConstructors() { - IntList list = new IntList(); - - assertTrue(list.isEmpty()); - list.add(0); - list.add(1); - IntList list2 = new IntList(list); - - assertEquals(list, list2); - IntList list3 = new IntList(2); - - assertTrue(list3.isEmpty()); - } - - @Test - void testAdd() { - IntList list = new IntList(); - int[] testArray = - { - 0, 1, 2, 3, 5 - }; - - for (int element : testArray) { - list.add(element); - } - for (int j = 0; j < testArray.length; j++) { - assertEquals(testArray[j], list.get(j)); - } - assertEquals(testArray.length, list.size()); - - // add at the beginning - list.add(0, -1); - assertEquals(-1, list.get(0)); - assertEquals(testArray.length + 1, list.size()); - for (int j = 0; j < testArray.length; j++) { - assertEquals(testArray[j], list.get(j + 1)); - } - - // add in the middle - list.add(5, 4); - assertEquals(4, list.get(5)); - assertEquals(testArray.length + 2, list.size()); - for (int j = 0; j < list.size(); j++) { - assertEquals(j - 1, list.get(j)); - } - - // add at the end - list.add(list.size(), 6); - assertEquals(testArray.length + 3, list.size()); - for (int j = 0; j < list.size(); j++) { - assertEquals(j - 1, list.get(j)); - } - - // add past end - IntList list2 = list; - assertThrows(IndexOutOfBoundsException.class, () -> list2.add(list2.size() + 1, 8)); - - // test growth - list = new IntList(0); - for (int j = 0; j < 1000; j++) { - list.add(j); - } - assertEquals(1000, list.size()); - for (int j = 0; j < 1000; j++) { - assertEquals(j, list.get(j)); - } - list = new IntList(0); - for (int j = 0; j < 1000; j++) { - list.add(0, j); - } - assertEquals(1000, list.size()); - for (int j = 0; j < 1000; j++) { - assertEquals(j, list.get(999 - j)); - } - } - - @Test - void testAddAll() { - IntList list = new IntList(); - - for (int j = 0; j < 5; j++) { - list.add(j); - } - IntList list2 = new IntList(0); - - list2.addAll(list); - list2.addAll(list); - assertEquals(2 * list.size(), list2.size()); - for (int j = 0; j < 5; j++) { - assertEquals(list2.get(j), j); - assertEquals(list2.get(j + list.size()), j); - } - IntList empty = new IntList(); - int limit = list.size(); - - for (int j = 0; j < limit; j++) { - assertTrue(list.addAll(j, empty)); - assertEquals(limit, list.size()); - } - - assertThrows(IndexOutOfBoundsException.class, () -> list.addAll(limit + 1, empty)); - - // try add at beginning - empty.addAll(0, list); - assertEquals(empty, list); - - // try in the middle - empty.addAll(1, list); - assertEquals(2 * list.size(), empty.size()); - assertEquals(list.get(0), empty.get(0)); - assertEquals(list.get(0), empty.get(1)); - assertEquals(list.get(1), empty.get(2)); - assertEquals(list.get(1), empty.get(6)); - assertEquals(list.get(2), empty.get(3)); - assertEquals(list.get(2), empty.get(7)); - assertEquals(list.get(3), empty.get(4)); - assertEquals(list.get(3), empty.get(8)); - assertEquals(list.get(4), empty.get(5)); - assertEquals(list.get(4), empty.get(9)); - - // try at the end - empty.addAll(empty.size(), list); - assertEquals(3 * list.size(), empty.size()); - assertEquals(list.get(0), empty.get(0)); - assertEquals(list.get(0), empty.get(1)); - assertEquals(list.get(0), empty.get(10)); - assertEquals(list.get(1), empty.get(2)); - assertEquals(list.get(1), empty.get(6)); - assertEquals(list.get(1), empty.get(11)); - assertEquals(list.get(2), empty.get(3)); - assertEquals(list.get(2), empty.get(7)); - assertEquals(list.get(2), empty.get(12)); - assertEquals(list.get(3), empty.get(4)); - assertEquals(list.get(3), empty.get(8)); - assertEquals(list.get(3), empty.get(13)); - assertEquals(list.get(4), empty.get(5)); - assertEquals(list.get(4), empty.get(9)); - assertEquals(list.get(4), empty.get(14)); - } - - @Test - void testAddAllGrow() { - IntList list = new IntList(0); - IntList addList = new IntList(0); - addList.add(1); - addList.add(2); - - assertTrue(list.addAll(0, addList)); - } - - @Test - void testClear() { - IntList list = new IntList(); - - for (int j = 0; j < 500; j++) { - list.add(j); - } - assertEquals(500, list.size()); - list.clear(); - assertEquals(0, list.size()); - for (int j = 0; j < 500; j++) { - list.add(j + 1); - } - assertEquals(500, list.size()); - for (int j = 0; j < 500; j++) { - assertEquals(j + 1, list.get(j)); - } - } - - @Test - void testContains() { - IntList list = new IntList(); - - for (int j = 0; j < 1000; j += 2) { - list.add(j); - } - for (int j = 0; j < 1000; j++) { - if (j % 2 == 0) { - assertTrue(list.contains(j)); - } else { - assertFalse(list.contains(j)); - } - } - } - - @Test - void testContainsAll() { - IntList list = new IntList(); - - assertTrue(list.containsAll(list)); - for (int j = 0; j < 10; j++) { - list.add(j); - } - IntList list2 = new IntList(list); - - assertTrue(list2.containsAll(list)); - assertTrue(list.containsAll(list2)); - list2.add(10); - assertTrue(list2.containsAll(list)); - assertFalse(list.containsAll(list2)); - list.add(11); - assertFalse(list2.containsAll(list)); - assertFalse(list.containsAll(list2)); - } - - @Test - void testEquals() { - IntList list = new IntList(); - - assertEquals(list, list); - //noinspection ObjectEqualsNull - assertNotEquals(null, list); - IntList list2 = new IntList(200); - - assertEquals(list, list2); - assertEquals(list2, list); - assertEquals(list.hashCode(), list2.hashCode()); - list.add(0); - list.add(1); - list2.add(1); - list2.add(0); - assertNotEquals(list, list2); - list2.removeValue(1); - list2.add(1); - assertEquals(list, list2); - assertEquals(list2, list); - assertEquals(list.hashCode(), list2.hashCode()); - list2.add(2); - assertNotEquals(list, list2); - assertNotEquals(list2, list); - } - - @Test - void testGet() { - IntList list = new IntList(); - - for (int j = 0; j < 1000; j++) { - list.add(j); - } - for (int j = 0; j < 1000; j++) { - assertEquals(j, list.get(j)); - } - - assertThrows(IndexOutOfBoundsException.class, () -> list.get(1000)); - } - - @Test - void testIndexOf() { - IntList list = new IntList(); - - for (int j = 0; j < 1000; j++) { - list.add(j / 2); - } - for (int j = 0; j < 1000; j++) { - if (j < 500) { - assertEquals(j * 2, list.indexOf(j)); - } else { - assertEquals(-1, list.indexOf(j)); - } - } - } - - @Test - void testIsEmpty() { - IntList list1 = new IntList(); - IntList list2 = new IntList(1000); - IntList list3 = new IntList(list1); - - assertTrue(list1.isEmpty()); - assertTrue(list2.isEmpty()); - assertTrue(list3.isEmpty()); - list1.add(1); - list2.add(2); - list3 = new IntList(list2); - assertFalse(list1.isEmpty()); - assertFalse(list2.isEmpty()); - assertFalse(list3.isEmpty()); - list1.clear(); - list2.remove(0); - list3.removeValue(2); - assertTrue(list1.isEmpty()); - assertTrue(list2.isEmpty()); - assertTrue(list3.isEmpty()); - } - - @Test - void testLastIndexOf() { - IntList list = new IntList(); - - for (int j = 0; j < 1000; j++) { - list.add(j / 2); - } - for (int j = 0; j < 1000; j++) { - if (j < 500) { - assertEquals(1 + j * 2, list.lastIndexOf(j)); - } else { - assertEquals(-1, list.indexOf(j)); - } - } - } - - @Test - void testRemove() { - IntList list = new IntList(); - - for (int j = 0; j < 1000; j++) { - list.add(j); - } - for (int j = 0; j < 1000; j++) { - assertEquals(j, list.remove(0)); - assertEquals(999 - j, list.size()); - } - for (int j = 0; j < 1000; j++) { - list.add(j); - } - for (int j = 0; j < 1000; j++) { - assertEquals(999 - j, list.remove(999 - j)); - assertEquals(999 - j, list.size()); - } - - assertThrows(IndexOutOfBoundsException.class, () -> list.remove(0)); - } - - @Test - void testRemoveValue() { - IntList list = new IntList(); - - for (int j = 0; j < 1000; j++) { - list.add(j / 2); - } - for (int j = 0; j < 1000; j++) { - if (j < 500) { - assertTrue(list.removeValue(j)); - assertTrue(list.removeValue(j)); - } - assertFalse(list.removeValue(j)); - } - } - - @Test - void testRemoveAll() { - IntList list = new IntList(); - - for (int j = 0; j < 1000; j++) { - list.add(j); - } - IntList listCopy = new IntList(list); - IntList listOdd = new IntList(); - IntList listEven = new IntList(); - - for (int j = 0; j < 1000; j++) { - if (j % 2 == 0) { - listEven.add(j); - } else { - listOdd.add(j); - } - } - - assertTrue(list.removeAll(listEven)); - assertEquals(list, listOdd); - - assertTrue(list.removeAll(listOdd)); - assertTrue(list.isEmpty()); - - assertTrue(listCopy.removeAll(listOdd)); - assertEquals(listCopy, listEven); - - assertTrue(listCopy.removeAll(listEven)); - assertTrue(listCopy.isEmpty()); - - assertFalse(list.removeAll(listEven)); - assertFalse(list.removeAll(listOdd)); - assertFalse(listCopy.removeAll(listEven)); - assertFalse(listCopy.removeAll(listEven)); - } - - @Test - void testRetainAll() { - IntList list = new IntList(); - - for (int j = 0; j < 1000; j++) { - list.add(j); - } - IntList listCopy = new IntList(list); - IntList listOdd = new IntList(); - IntList listEven = new IntList(); - - for (int j = 0; j < 1000; j++) { - if (j % 2 == 0) { - listEven.add(j); - } else { - listOdd.add(j); - } - } - assertTrue(list.retainAll(listOdd)); - assertEquals(list, listOdd); - - assertTrue(list.retainAll(listEven)); - assertTrue(list.isEmpty()); - - assertTrue(listCopy.retainAll(listEven)); - assertEquals(listCopy, listEven); - - assertTrue(listCopy.retainAll(listOdd)); - assertTrue(listCopy.isEmpty()); - - assertFalse(list.retainAll(listOdd)); - assertFalse(list.retainAll(listEven)); - assertFalse(listCopy.retainAll(listEven)); - assertFalse(listCopy.retainAll(listOdd)); - } - - @Test - void testSet() { - IntList list = new IntList(); - - for (int j = 0; j < 1000; j++) { - list.add(j); - } - for (int j = 0; j < 1000; j++) { - list.set(j, j + 1); - assertEquals(j + 1, list.get(j)); - } - assertThrows(IndexOutOfBoundsException.class, () -> list.set(1000, 1001)); - } - - @Test - void testSize() { - IntList list = new IntList(); - - for (int j = 0; j < 1000; j++) { - assertEquals(j, list.size()); - list.add(j); - assertEquals(j + 1, list.size()); - } - for (int j = 0; j < 1000; j++) { - assertEquals(1000 - j, list.size()); - list.removeValue(j); - assertEquals(999 - j, list.size()); - } - } - - @Test - void testToArray() { - IntList list = new IntList(); - - for (int j = 0; j < 1000; j++) { - list.add(j); - } - int[] a1 = list.toArray(); - - assertEquals(a1.length, list.size()); - for (int j = 0; j < 1000; j++) { - assertEquals(a1[j], list.get(j)); - } - int[] a2 = new int[list.size()]; - int[] a3 = list.toArray(a2); - - assertSame(a2, a3); - for (int j = 0; j < 1000; j++) { - assertEquals(a2[j], list.get(j)); - } - int[] aShort = new int[list.size() - 1]; - int[] aLong = new int[list.size() + 1]; - int[] a4 = list.toArray(aShort); - int[] a5 = list.toArray(aLong); - - assertNotSame(a4, aShort); - assertNotSame(a5, aLong); - assertEquals(a4.length, list.size()); - for (int j = 0; j < 1000; j++) { - assertEquals(a3[j], list.get(j)); - } - assertEquals(a5.length, list.size()); - for (int j = 0; j < 1000; j++) { - assertEquals(a5[j], list.get(j)); - } - } -} diff --git a/src/testcases/org/apache/poi/util/TestIntegerField.java b/src/testcases/org/apache/poi/util/TestIntegerField.java deleted file mode 100644 index d8e2f1b66f..0000000000 --- a/src/testcases/org/apache/poi/util/TestIntegerField.java +++ /dev/null @@ -1,135 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.util; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertThrows; - -import java.io.ByteArrayInputStream; -import java.io.IOException; - -import org.junit.jupiter.api.Test; - -/** - * Test IntegerField code - */ -final class TestIntegerField { - - private static final int[] _test_array = {Integer.MIN_VALUE, -1, 0, 1, Integer.MAX_VALUE}; - - @Test - void testConstructors() { - assertThrows(ArrayIndexOutOfBoundsException.class, () -> new IntegerField(-1)); - IntegerField field = new IntegerField(2); - - assertEquals(0, field.get()); - assertThrows(ArrayIndexOutOfBoundsException.class, () -> new IntegerField(-1, 1)); - field = new IntegerField(2, 0x12345678); - assertEquals(0x12345678, field.get()); - - assertThrows(ArrayIndexOutOfBoundsException.class, () -> new IntegerField(-1, 1, new byte[ 6 ])); - - byte[] array = new byte[ 6 ]; - field = new IntegerField(2, 0x12345678, array); - assertEquals(0x12345678, field.get()); - assertEquals(( byte ) 0x78, array[ 2 ]); - assertEquals(( byte ) 0x56, array[ 3 ]); - assertEquals(( byte ) 0x34, array[ 4 ]); - assertEquals(( byte ) 0x12, array[ 5 ]); - - assertThrows(ArrayIndexOutOfBoundsException.class, () -> new IntegerField(2, 5, new byte[ 5 ])); - - for (int element : _test_array) { - array = new byte[ 4 ]; - new IntegerField(0, element, array); - assertEquals(element, new IntegerField(0, array).get()); - } - } - - @Test - void testSet() { - IntegerField field = new IntegerField(0); - byte[] array = new byte[ 4 ]; - - for (int j = 0; j < _test_array.length; j++) { - field.set(_test_array[ j ]); - assertEquals(_test_array[ j ], field.get(), "testing _1 " + j); - field = new IntegerField(0); - field.set(_test_array[ j ], array); - assertEquals(_test_array[ j ], field.get(), "testing _2 "); - assertEquals(( byte ) (_test_array[ j ] % 256), array[ 0 ], "testing _3.0 " + _test_array[ j ]); - assertEquals(( byte ) ((_test_array[ j ] >> 8) % 256), array[ 1 ], "testing _3.1 " + _test_array[ j ]); - assertEquals(( byte ) ((_test_array[ j ] >> 16) % 256), array[ 2 ], "testing _3.2 " + _test_array[ j ]); - assertEquals(( byte ) ((_test_array[ j ] >> 24) % 256), array[ 3 ], "testing _3.3 " + _test_array[ j ]); - } - } - - @Test - void testReadFromBytes() { - IntegerField field1 = new IntegerField(1); - byte[] array = new byte[ 4 ]; - - assertThrows(ArrayIndexOutOfBoundsException.class, () -> field1.readFromBytes(array)); - IntegerField field2 = new IntegerField(0); - for (int j = 0; j < _test_array.length; j++) { - array[ 0 ] = ( byte ) (_test_array[ j ] % 256); - array[ 1 ] = ( byte ) ((_test_array[ j ] >> 8) % 256); - array[ 2 ] = ( byte ) ((_test_array[ j ] >> 16) % 256); - array[ 3 ] = ( byte ) ((_test_array[ j ] >> 24) % 256); - field2.readFromBytes(array); - assertEquals(_test_array[ j ], field2.get(), "testing " + j); - } - } - - @Test - void testReadFromStream() throws IOException { - IntegerField field = new IntegerField(0); - byte[] buffer = new byte[ _test_array.length * 4 ]; - - for (int j = 0; j < _test_array.length; j++) { - buffer[ (j * 4) + 0 ] = ( byte ) (_test_array[ j ] % 256); - buffer[ (j * 4) + 1 ] = ( byte ) ((_test_array[ j ] >> 8) % 256); - buffer[ (j * 4) + 2 ] = ( byte ) ((_test_array[ j ] >> 16) % 256); - buffer[ (j * 4) + 3 ] = ( byte ) ((_test_array[ j ] >> 24) % 256); - } - ByteArrayInputStream stream = new ByteArrayInputStream(buffer); - - for (int j = 0; j < buffer.length / 4; j++) { - field.readFromStream(stream); - assertEquals(_test_array[ j ], field.get(), "Testing " + j); - } - } - - @Test - void testWriteToBytes() { - IntegerField field = new IntegerField(0); - byte[] array = new byte[ 4 ]; - - for (int b : _test_array) { - field.set(b); - field.writeToBytes(array); - int val = array[ 3 ] << 24; - - val &= 0xFF000000; - val += (array[ 2 ] << 16) & 0x00FF0000; - val += (array[ 1 ] << 8) & 0x0000FF00; - val += (array[ 0 ] & 0x000000FF); - assertEquals(b, val, "testing "); - } - } -} diff --git a/src/testcases/org/apache/poi/util/TestLittleEndian.java b/src/testcases/org/apache/poi/util/TestLittleEndian.java deleted file mode 100644 index 27e5e3fe1a..0000000000 --- a/src/testcases/org/apache/poi/util/TestLittleEndian.java +++ /dev/null @@ -1,356 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.util; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.junit.jupiter.api.Assertions.assertTrue; - -import java.io.ByteArrayInputStream; -import java.io.IOException; -import java.io.InputStream; - -import org.apache.poi.util.LittleEndian.BufferUnderrunException; -import org.junit.jupiter.api.Test; - -/** - * Class to test LittleEndian functionality - */ -final class TestLittleEndian { - - /** - * test the getShort() method - */ - @Test - void testGetShort() { - byte[] testdata = new byte[ LittleEndianConsts.SHORT_SIZE + 1 ]; - - testdata[0] = 0x01; - testdata[1] = (byte) 0xFF; - testdata[2] = 0x02; - short[] expected = new short[2]; - - expected[0] = ( short ) 0xFF01; - expected[1] = 0x02FF; - assertEquals(expected[0], LittleEndian.getShort(testdata)); - assertEquals(expected[1], LittleEndian.getShort(testdata, 1)); - } - - @Test - void testGetUShort() { - byte[] testdata = { - (byte) 0x01, - (byte) 0xFF, - (byte) 0x02, - }; - byte[] testdata2 = { - (byte) 0x0D, - (byte) 0x93, - (byte) 0xFF, - }; - - int expected0 = 0xFF01; - int expected1 = 0x02FF; - int expected2 = 0x930D; - int expected3 = 0xFF93; - assertEquals(expected0, LittleEndian.getUShort(testdata)); - assertEquals(expected1, LittleEndian.getUShort(testdata, 1)); - assertEquals(expected2, LittleEndian.getUShort(testdata2)); - assertEquals(expected3, LittleEndian.getUShort(testdata2, 1)); - - byte[] testdata3 = new byte[ LittleEndianConsts.SHORT_SIZE + 1 ]; - LittleEndian.putUShort(testdata3, 0, expected2); - LittleEndian.putUShort(testdata3, 1, expected3); - assertEquals(testdata3[0], 0x0D); - assertEquals(testdata3[1], (byte)0x93); - assertEquals(testdata3[2], (byte)0xFF); - assertEquals(expected2, LittleEndian.getUShort(testdata3)); - assertEquals(expected3, LittleEndian.getUShort(testdata3, 1)); - - } - - private static final byte[] _double_array = - { - 56, 50, -113, -4, -63, -64, -13, 63, 76, -32, -42, -35, 60, -43, 3, 64 - }; - /** 0x7ff8000000000000 encoded in little endian order */ - private static final byte[] _nan_double_array = HexRead.readFromString("00 00 00 00 00 00 F8 7F"); - private static final double[] _doubles = - { - 1.23456, 2.47912, Double.NaN - }; - - /** - * test the getDouble() method - */ - @Test - void testGetDouble() { - assertEquals(_doubles[0], LittleEndian.getDouble(_double_array, 0), 0.000001 ); - assertEquals(_doubles[1], LittleEndian.getDouble( _double_array, LittleEndianConsts.DOUBLE_SIZE), 0.000001); - assertTrue(Double.isNaN(LittleEndian.getDouble(_nan_double_array, 0))); - - double nan = LittleEndian.getDouble(_nan_double_array, 0); - byte[] data = new byte[8]; - LittleEndian.putDouble(data, 0, nan); - for ( int i = 0; i < data.length; i++ ) { - assertEquals(data[i], _nan_double_array[i]); - } - } - - /** - * test the getInt() method - */ - @Test - void testGetInt() { - // reading 4 byte data from a 5 byte buffer - byte[] testdata = { - (byte) 0x01, - (byte) 0xFF, - (byte) 0xFF, - (byte) 0xFF, - (byte) 0x02, - }; - - assertEquals(0xFFFFFF01, LittleEndian.getInt(testdata)); - assertEquals(0x02FFFFFF, LittleEndian.getInt(testdata, 1)); - } - - /** - * test the getLong method - */ - @Test - void testGetLong() { - - // reading 8 byte values from a 9 byte buffer - byte[] testdata = { - (byte) 0x01, - (byte) 0xFF, - (byte) 0xFF, - (byte) 0xFF, - (byte) 0xFF, - (byte) 0xFF, - (byte) 0xFF, - (byte) 0xFF, - (byte) 0x02, - }; - - assertEquals(0xFFFFFFFFFFFFFF01L, LittleEndian.getLong(testdata, 0)); - assertEquals(0x02FFFFFFFFFFFFFFL, LittleEndian.getLong(testdata, 1)); - } - - /** - * test the PutShort method - */ - @Test - void testPutShort() { - byte[] expected = new byte[ LittleEndianConsts.SHORT_SIZE + 1 ]; - - expected[0] = 0x01; - expected[1] = (byte) 0xFF; - expected[2] = 0x02; - byte[] received = new byte[ LittleEndianConsts.SHORT_SIZE + 1 ]; - short[] testdata = new short[2]; - - testdata[0] = ( short ) 0xFF01; - testdata[1] = 0x02FF; - LittleEndian.putShort(received, 0, testdata[0]); - assertTrue(compareByteArrays(received, expected, 0, LittleEndianConsts.SHORT_SIZE)); - LittleEndian.putShort(received, 1, testdata[1]); - assertTrue(compareByteArrays(received, expected, 1, LittleEndianConsts.SHORT_SIZE)); - } - - /** - * test the putInt method - */ - @Test - void testPutInt() { - // writing 4 byte data to a 5 byte buffer - byte[] expected = { - (byte) 0x01, - (byte) 0xFF, - (byte) 0xFF, - (byte) 0xFF, - (byte) 0x02, - }; - byte[] received = new byte[ LittleEndianConsts.INT_SIZE + 1 ]; - - LittleEndian.putInt(received, 0, 0xFFFFFF01); - assertTrue(compareByteArrays(received, expected, 0, LittleEndianConsts.INT_SIZE)); - LittleEndian.putInt(received, 1, 0x02FFFFFF); - assertTrue(compareByteArrays(received, expected, 1, LittleEndianConsts.INT_SIZE)); - } - - /** - * test the putDouble methods - */ - @Test - void testPutDouble() { - byte[] received = new byte[ LittleEndianConsts.DOUBLE_SIZE + 1 ]; - - LittleEndian.putDouble(received, 0, _doubles[0]); - assertTrue(compareByteArrays(received, _double_array, 0, LittleEndianConsts.DOUBLE_SIZE)); - LittleEndian.putDouble(received, 1, _doubles[1]); - byte[] expected = new byte[ LittleEndianConsts.DOUBLE_SIZE + 1 ]; - - System.arraycopy(_double_array, LittleEndianConsts.DOUBLE_SIZE, expected, - 1, LittleEndianConsts.DOUBLE_SIZE); - assertTrue(compareByteArrays(received, expected, 1, LittleEndianConsts.DOUBLE_SIZE)); - } - - /** - * test the putLong method - */ - @Test - void testPutLong() { - // writing 8 byte values to a 9 byte buffer - byte[] expected = { - (byte) 0x01, - (byte) 0xFF, - (byte) 0xFF, - (byte) 0xFF, - (byte) 0xFF, - (byte) 0xFF, - (byte) 0xFF, - (byte) 0xFF, - (byte) 0x02, - }; - byte[] received = new byte[ LittleEndianConsts.LONG_SIZE + 1 ]; - - long testdata0 = 0xFFFFFFFFFFFFFF01L; - long testdata1 = 0x02FFFFFFFFFFFFFFL; - LittleEndian.putLong(received, 0, testdata0); - assertTrue(compareByteArrays(received, expected, 0, LittleEndianConsts.LONG_SIZE)); - LittleEndian.putLong(received, 1, testdata1); - assertTrue(compareByteArrays(received, expected, 1, LittleEndianConsts.LONG_SIZE)); - } - - private static final byte[] _good_array = { - 0x01, 0x02, 0x01, 0x02, - 0x01, 0x02, 0x01, 0x02, - 0x01, 0x02, 0x01, 0x02, - 0x01, 0x02, 0x01, 0x02, - }; - private static final byte[] _bad_array = { - 0x01 - }; - - /** - * test the readShort method - */ - @Test - void testReadShort() throws IOException { - short expected_value = 0x0201; - InputStream stream = new ByteArrayInputStream(_good_array); - int count = 0; - - while (true) { - try { - short value = LittleEndian.readShort(stream); - assertEquals(value, expected_value); - count++; - } catch (BufferUnderrunException e) { - break; - } - } - assertEquals(count, - _good_array.length / LittleEndianConsts.SHORT_SIZE); - ByteArrayInputStream stream2 = new ByteArrayInputStream(_bad_array); - assertThrows(BufferUnderrunException.class, () -> LittleEndian.readShort(stream2)); - } - - /** - * test the readInt method - */ - @Test - void testReadInt() throws IOException { - int expected_value = 0x02010201; - InputStream stream = new ByteArrayInputStream(_good_array); - int count = 0; - - while (true) { - try { - int value = LittleEndian.readInt(stream); - assertEquals(value, expected_value); - count++; - } catch (BufferUnderrunException e) { - break; - } - } - assertEquals(count, _good_array.length / LittleEndianConsts.INT_SIZE); - ByteArrayInputStream stream2 = new ByteArrayInputStream(_bad_array); - assertThrows(BufferUnderrunException.class, () -> LittleEndian.readInt(stream2)); - } - - /** - * test the readLong method - */ - @Test - void testReadLong() throws IOException { - long expected_value = 0x0201020102010201L; - InputStream stream = new ByteArrayInputStream(_good_array); - int count = 0; - - while (true) { - try { - long value = LittleEndian.readLong(stream); - assertEquals(value, expected_value); - count++; - } catch (BufferUnderrunException e) { - break; - } - } - assertEquals(count, _good_array.length / LittleEndianConsts.LONG_SIZE); - ByteArrayInputStream stream2 = new ByteArrayInputStream(_bad_array); - assertThrows(BufferUnderrunException.class, () -> LittleEndian.readLong(stream2)); - } - - @Test - void testReadFromStream() throws IOException { - int actual; - actual = LittleEndian.readUShort(new ByteArrayInputStream(new byte[] { 5, -128, })); - assertEquals(32773, actual); - - actual = LittleEndian.readUShort(new ByteArrayInputStream(new byte[] { 1, 2, 3, 4, })); - assertEquals(513, actual); - - assertThrows(BufferUnderrunException.class, () -> - LittleEndian.readInt(new ByteArrayInputStream(new byte[] { 1, 2, 3, }))); - } - - @Test - void testUnsignedByteToInt() { - assertEquals(255, LittleEndian.ubyteToInt((byte)255)); - } - - private static boolean compareByteArrays(byte [] received, byte [] expected, - int offset, int size) { - - for (int j = offset; j < offset + size; j++) { - if (received[j] != expected[j]) { - System.out.println("difference at index " + j); - return false; - } - } - return true; - } - - @Test - void testUnsignedShort() { - assertEquals(0xffff, LittleEndian.getUShort(new byte[] { (byte)0xff, (byte)0xff }, 0)); - } -} diff --git a/src/testcases/org/apache/poi/util/TestLittleEndianStreams.java b/src/testcases/org/apache/poi/util/TestLittleEndianStreams.java deleted file mode 100644 index 54ebefa5b5..0000000000 --- a/src/testcases/org/apache/poi/util/TestLittleEndianStreams.java +++ /dev/null @@ -1,118 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.util; - -import static org.junit.jupiter.api.Assertions.assertArrayEquals; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.junit.jupiter.api.Assertions.assertTrue; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.IOException; - -import org.junit.jupiter.api.Test; - -/** - * Class to test {@link LittleEndianInputStream} and {@link LittleEndianOutputStream} - */ -final class TestLittleEndianStreams { - - @Test - void testRead() throws IOException { - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - try (LittleEndianOutputStream leo = new LittleEndianOutputStream(baos)) { - leo.writeInt(12345678); - leo.writeShort(12345); - leo.writeByte(123); - leo.writeShort(40000); - leo.writeByte(200); - leo.writeLong(1234567890123456789L); - leo.writeDouble(123.456); - } - - try (LittleEndianInputStream lei = new LittleEndianInputStream(new ByteArrayInputStream(baos.toByteArray()))) { - assertEquals(12345678, lei.readInt()); - assertEquals(12345, lei.readShort()); - assertEquals(123, lei.readByte()); - assertEquals(40000, lei.readUShort()); - assertEquals(200, lei.readUByte()); - assertEquals(1234567890123456789L, lei.readLong()); - assertEquals(123.456, lei.readDouble(), 0.0); - } - } - - /** - * Up until svn r836101 {@link LittleEndianByteArrayInputStream#readFully(byte[], int, int)} - * had an error which resulted in the data being read and written back to the source byte - * array. - */ - @Test - void testReadFully() { - byte[] srcBuf = HexRead.readFromString("99 88 77 66 55 44 33"); - LittleEndianInput lei = new LittleEndianByteArrayInputStream(srcBuf); - - // do initial read to increment the read index beyond zero - assertEquals(0x8899, lei.readUShort()); - - byte[] actBuf = new byte[4]; - lei.readFully(actBuf); - - assertFalse(actBuf[0] == 0x00 && srcBuf[0] == 0x77 && srcBuf[3] == 0x44, - "Identified bug in readFully() - source buffer was modified"); - - byte[] expBuf = HexRead.readFromString("77 66 55 44"); - assertArrayEquals(actBuf, expBuf); - assertEquals(0x33, lei.readUByte()); - assertEquals(0, lei.available()); - } - - @Test - void testBufferOverrun() { - byte[] srcBuf = HexRead.readFromString("99 88 77"); - LittleEndianInput lei = new LittleEndianByteArrayInputStream(srcBuf); - - // do initial read to increment the read index beyond zero - assertEquals(0x8899, lei.readUShort()); - - // only one byte left, so this should fail - RuntimeException ex = assertThrows(RuntimeException.class, () -> lei.readFully(new byte[4])); - assertTrue(ex.getMessage().contains("Buffer overrun")); - } - - @Test - void testBufferOverrunStartOffset() { - byte[] srcBuf = HexRead.readFromString("99 88 77 88 99"); - LittleEndianInput lei = new LittleEndianByteArrayInputStream(srcBuf, 2); - - // only one byte left, so this should fail - RuntimeException ex = assertThrows(RuntimeException.class, () -> lei.readFully(new byte[4])); - assertTrue(ex.getMessage().contains("Buffer overrun")); - } - - @Test - void testBufferOverrunStartOffset2() { - byte[] srcBuf = HexRead.readFromString("99 88 77 88 99"); - LittleEndianInput lei = new LittleEndianByteArrayInputStream(srcBuf, 2, 2); - - // only one byte left, so this should fail - RuntimeException ex = assertThrows(RuntimeException.class, () -> lei.readFully(new byte[4])); - assertTrue(ex.getMessage().contains("Buffer overrun")); - } -} diff --git a/src/testcases/org/apache/poi/util/TestLocaleUtil.java b/src/testcases/org/apache/poi/util/TestLocaleUtil.java deleted file mode 100644 index 3335b85368..0000000000 --- a/src/testcases/org/apache/poi/util/TestLocaleUtil.java +++ /dev/null @@ -1,127 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.util; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotEquals; -import static org.junit.jupiter.api.Assumptions.assumeFalse; - -import java.util.Calendar; -import java.util.Locale; -import java.util.TimeZone; - -import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; - - -class TestLocaleUtil { - // This unit test assumes that the user's locale isn't ja-JP and timezone isn't Asia/Tokyo - // If this is the case, change the values to something else - private static final Locale ja_JP = Locale.JAPAN; - private static final TimeZone TOKYO = TimeZone.getTimeZone("Asia/Tokyo"); - private static final Calendar JAPAN_CALENDAR = Calendar.getInstance(TOKYO, ja_JP); - - /** - * Reset the Locale to the user default before the test so that it isn't influenced - * by the LocaleUtil's state being changed by previous tests. - */ - @BeforeEach - @SuppressForbidden("implementation around default locales in POI") - void setUp() { - // reset the user locale and time zone so that tests do not interfere with each other - // the other and better way would be to run each test in its own thread since - // LocaleUtil uses per-thread settings. - // Helpful, but not ASL 2.0 licensed: - // http://www.codeaffine.com/2014/07/21/a-junit-rule-to-run-a-test-in-its-own-thread/ - LocaleUtil.setUserLocale(Locale.getDefault()); - LocaleUtil.setUserTimeZone(TimeZone.getDefault()); - - assumeFalse(ja_JP.equals(LocaleUtil.getUserLocale())); - assumeFalse(TOKYO.equals(LocaleUtil.getUserTimeZone())); - } - - /** - * Reset the Locale to the user default after the test so that it doesn't influence - * other tests. - */ - @AfterEach - void tearDown() { - LocaleUtil.resetUserLocale(); - LocaleUtil.resetUserTimeZone(); - } - - @Test - @SuppressForbidden("implementation around default locales in POI") - void userLocale() { - Locale DEFAULT_LOCALE = LocaleUtil.getUserLocale(); - - assertEquals(DEFAULT_LOCALE, LocaleUtil.getUserLocale()); - assertNotEquals(ja_JP, LocaleUtil.getUserLocale()); - - LocaleUtil.setUserLocale(ja_JP); - assertEquals(ja_JP, LocaleUtil.getUserLocale()); - - LocaleUtil.resetUserLocale(); - assertEquals(DEFAULT_LOCALE, LocaleUtil.getUserLocale()); - } - - @Test - @SuppressForbidden("implementation around default locales in POI") - void userTimeZone() { - TimeZone DEFAULT_TIME_ZONE = LocaleUtil.getUserTimeZone(); - - assertEquals(DEFAULT_TIME_ZONE, LocaleUtil.getUserTimeZone()); - assertNotEquals(TOKYO, LocaleUtil.getUserTimeZone()); - - LocaleUtil.setUserTimeZone(TOKYO); - assertEquals(TOKYO, LocaleUtil.getUserTimeZone()); - } - - @Test - @SuppressForbidden("implementation around default locales in POI") - void localeCalendar() { - Locale DEFAULT_LOCALE = LocaleUtil.getUserLocale(); - TimeZone DEFAULT_TIME_ZONE = LocaleUtil.getUserTimeZone(); - Calendar DEFAULT_CALENDAR = LocaleUtil.getLocaleCalendar(); - - assertEquals(DEFAULT_LOCALE, LocaleUtil.getUserLocale()); - assertEquals(DEFAULT_TIME_ZONE, LocaleUtil.getUserTimeZone()); - assertCalendarEquals(DEFAULT_CALENDAR, LocaleUtil.getLocaleCalendar()); - assertNotEquals(ja_JP, LocaleUtil.getUserLocale()); - assertNotEquals(TOKYO, LocaleUtil.getUserTimeZone()); - assertCalendarNotEquals(JAPAN_CALENDAR, LocaleUtil.getLocaleCalendar()); - - LocaleUtil.setUserLocale(ja_JP); - LocaleUtil.setUserTimeZone(TOKYO); - assertCalendarEquals(JAPAN_CALENDAR, LocaleUtil.getLocaleCalendar()); - assertCalendarEquals(JAPAN_CALENDAR, LocaleUtil.getLocaleCalendar(TOKYO)); - // FIXME: These might affect the time zone due to daylight savings: - //assertCalendarEquals(JAPAN_CALENDAR, LocaleUtil.getLocaleCalendar(2016, 00, 01)); - //assertCalendarEquals(JAPAN_CALENDAR, LocaleUtil.getLocaleCalendar(2016, 00, 01, 00, 00, 00)); - } - - private static void assertCalendarNotEquals(Calendar expected, Calendar actual) { - // FIXME: add more tests to compare calendars, ignoring whether the dates are equal - assertNotEquals(expected.getTimeZone(), actual.getTimeZone(), "time zone"); - } - private static void assertCalendarEquals(Calendar expected, Calendar actual) { - // FIXME: add more tests to compare calendars, ignoring whether the set dates are equal - assertEquals(expected.getTimeZone(), actual.getTimeZone(), "time zone"); - } -} diff --git a/src/testcases/org/apache/poi/util/TestLongField.java b/src/testcases/org/apache/poi/util/TestLongField.java deleted file mode 100644 index 8cd39aba92..0000000000 --- a/src/testcases/org/apache/poi/util/TestLongField.java +++ /dev/null @@ -1,167 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.util; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.junit.jupiter.api.Assertions.fail; - -import java.io.ByteArrayInputStream; -import java.io.IOException; - -import org.junit.jupiter.api.Test; - -/** - * Test LongField code - */ -final class TestLongField { - - static private final long[] _test_array = - { - Long.MIN_VALUE, -1L, 0L, 1L, Long.MAX_VALUE - }; - - @Test - void testConstructors() { - assertThrows(ArrayIndexOutOfBoundsException.class, () -> new LongField(-1)); - - LongField field1 = new LongField(2); - assertEquals(0L, field1.get()); - - assertThrows(ArrayIndexOutOfBoundsException.class, () -> new LongField(-1, 1L)); - - LongField field2 = new LongField(2, 0x123456789ABCDEF0L); - assertEquals(0x123456789ABCDEF0L, field2.get()); - - assertThrows(ArrayIndexOutOfBoundsException.class, () -> new LongField(-1, 1L, new byte[ 10 ])); - - - byte[] array = new byte[ 10 ]; - LongField field = new LongField(2, 0x123456789ABCDEF0L, array); - assertEquals(0x123456789ABCDEF0L, field.get()); - assertEquals(( byte ) 0xF0, array[ 2 ]); - assertEquals(( byte ) 0xDE, array[ 3 ]); - assertEquals(( byte ) 0xBC, array[ 4 ]); - assertEquals(( byte ) 0x9A, array[ 5 ]); - assertEquals(( byte ) 0x78, array[ 6 ]); - assertEquals(( byte ) 0x56, array[ 7 ]); - assertEquals(( byte ) 0x34, array[ 8 ]); - assertEquals(( byte ) 0x12, array[ 9 ]); - - assertThrows(ArrayIndexOutOfBoundsException.class, () -> new LongField(2, 5L, new byte[ 9 ])); - - for (long element : _test_array) { - array = new byte[ 8 ]; - new LongField(0, element, array); - assertEquals(element, new LongField(0, array).get()); - } - } - - @Test - void testSet() { - LongField field = new LongField(0); - byte[] array = new byte[ 8 ]; - - for (int j = 0; j < _test_array.length; j++) { - field.set(_test_array[ j ]); - assertEquals(_test_array[ j ], field.get(), "testing _1 " + j); - field = new LongField(0); - field.set(_test_array[ j ], array); - assertEquals(_test_array[ j ], field.get(), "testing _2 "); - assertEquals(( byte ) (_test_array[ j ] % 256), array[ 0 ], "testing _3.0 " + _test_array[ j ]); - assertEquals(( byte ) ((_test_array[ j ] >> 8) % 256), array[ 1 ], "testing _3.1 " + _test_array[ j ]); - assertEquals(( byte ) ((_test_array[ j ] >> 16) % 256), array[ 2 ], "testing _3.2 " + _test_array[ j ]); - assertEquals(( byte ) ((_test_array[ j ] >> 24) % 256), array[ 3 ], "testing _3.3 " + _test_array[ j ]); - assertEquals(( byte ) ((_test_array[ j ] >> 32) % 256), array[ 4 ], "testing _3.4 " + _test_array[ j ]); - assertEquals(( byte ) ((_test_array[ j ] >> 40) % 256), array[ 5 ], "testing _3.5 " + _test_array[ j ]); - assertEquals(( byte ) ((_test_array[ j ] >> 48) % 256), array[ 6 ], "testing _3.6 " + _test_array[ j ]); - assertEquals(( byte ) ((_test_array[ j ] >> 56) % 256), array[ 7 ], "testing _3.7 " + _test_array[ j ]); - } - } - - @Test - void testReadFromBytes() { - LongField field = new LongField(1); - byte[] array = new byte[ 8 ]; - - try { - field.readFromBytes(array); - fail("should have caught ArrayIndexOutOfBoundsException"); - } catch (ArrayIndexOutOfBoundsException ignored_e) { - // as expected - } - field = new LongField(0); - for (int j = 0; j < _test_array.length; j++) { - array[ 0 ] = ( byte ) (_test_array[ j ] % 256); - array[ 1 ] = ( byte ) ((_test_array[ j ] >> 8) % 256); - array[ 2 ] = ( byte ) ((_test_array[ j ] >> 16) % 256); - array[ 3 ] = ( byte ) ((_test_array[ j ] >> 24) % 256); - array[ 4 ] = ( byte ) ((_test_array[ j ] >> 32) % 256); - array[ 5 ] = ( byte ) ((_test_array[ j ] >> 40) % 256); - array[ 6 ] = ( byte ) ((_test_array[ j ] >> 48) % 256); - array[ 7 ] = ( byte ) ((_test_array[ j ] >> 56) % 256); - field.readFromBytes(array); - assertEquals(_test_array[ j ], field.get(), "testing " + j); - } - } - - @Test - void testReadFromStream() throws IOException { - LongField field = new LongField(0); - byte[] buffer = new byte[ _test_array.length * 8 ]; - - for (int j = 0; j < _test_array.length; j++) { - buffer[ (j * 8) ] = ( byte ) ((_test_array[ j ] ) % 256); - buffer[ (j * 8) + 1 ] = ( byte ) ((_test_array[ j ] >> 8) % 256); - buffer[ (j * 8) + 2 ] = ( byte ) ((_test_array[ j ] >> 16) % 256); - buffer[ (j * 8) + 3 ] = ( byte ) ((_test_array[ j ] >> 24) % 256); - buffer[ (j * 8) + 4 ] = ( byte ) ((_test_array[ j ] >> 32) % 256); - buffer[ (j * 8) + 5 ] = ( byte ) ((_test_array[ j ] >> 40) % 256); - buffer[ (j * 8) + 6 ] = ( byte ) ((_test_array[ j ] >> 48) % 256); - buffer[ (j * 8) + 7 ] = ( byte ) ((_test_array[ j ] >> 56) % 256); - } - ByteArrayInputStream stream = new ByteArrayInputStream(buffer); - - for (int j = 0; j < buffer.length / 8; j++) { - field.readFromStream(stream); - assertEquals(_test_array[ j ], field.get(), "Testing " + j); - } - } - - @Test - void testWriteToBytes() { - LongField field = new LongField(0); - byte[] array = new byte[ 8 ]; - - for (long element : _test_array) { - field.set(element); - field.writeToBytes(array); - long val = (( long ) array[ 7 ]) << 56; - - val &= 0xFF00000000000000L; - val += ((( long ) array[ 6 ]) << 48) & 0x00FF000000000000L; - val += ((( long ) array[ 5 ]) << 40) & 0x0000FF0000000000L; - val += ((( long ) array[ 4 ]) << 32) & 0x000000FF00000000L; - val += ((( long ) array[ 3 ]) << 24) & 0x00000000FF000000L; - val += ((( long ) array[ 2 ]) << 16) & 0x0000000000FF0000L; - val += ((( long ) array[ 1 ]) << 8) & 0x000000000000FF00L; - val += (array[ 0 ] & 0x00000000000000FFL); - assertEquals(element, val, "testing "); - } - } -} diff --git a/src/testcases/org/apache/poi/util/TestRLEDecompressingInputStream.java b/src/testcases/org/apache/poi/util/TestRLEDecompressingInputStream.java deleted file mode 100644 index 219e1460b1..0000000000 --- a/src/testcases/org/apache/poi/util/TestRLEDecompressingInputStream.java +++ /dev/null @@ -1,172 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.util; - -import static org.junit.jupiter.api.Assertions.assertArrayEquals; -import static org.junit.jupiter.api.Assertions.assertEquals; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.UnsupportedEncodingException; - -import org.junit.jupiter.api.Test; - -class TestRLEDecompressingInputStream { - - /** - * Section 3.2.1 No Compression Example - * - * The following string illustrates an ASCII text string with a set of characters that cannot be compressed - * by the compression algorithm specified in section 2.4.1. - * - * abcdefghijklmnopqrstuv. - * - * This example is provided to demonstrate the results of compressing and decompressing the string - * using an interoperable implementation of the algorithm specified in section 2.4.1. - * - * The following hex array represents the compressed byte array of the example string as compressed by - * the compression algorithm. - * - * 01 19 B0 00 61 62 63 64 65 66 67 68 00 69 6A 6B 6C - * 6D 6E 6F 70 00 71 72 73 74 75 76 2E - * - * The following hex array represents the decompressed byte array of the example string as - * decompressed by the decompression algorithm. - * - * 61 62 63 64 65 66 67 68 69 6A 6B 6C 6D 6E 6F 70 71 - * 72 73 74 75 76 2E - * - */ - @Test - void noCompressionExample() { - final byte[] compressed = { - 0x01, 0x19, (byte)0xB0, 0x00, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x00, 0x69, 0x6A, 0x6B, 0x6C, - 0x6D, 0x6E, 0x6F, 0x70, 0x00, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x2E - }; - final String expected = "abcdefghijklmnopqrstuv."; - checkRLEDecompression(expected, compressed); - } - - /** - * Section 3.2.2 Normal Compression Example - * - * The following string illustrates an ASCII text string with a typical set of characters that can be - * compressed by the compression algorithm. - * - * #aaabcdefaaaaghijaaaaaklaaamnopqaaaaaaaaaaaarstuvwxyzaaa - * - * This example is provided to demonstrate the results of compressing and decompressing the example - * string using an interoperable implementation of the algorithm specified in section 2.4.1. - * - * The following hex array represents the compressed byte array of the example string as compressed by - * the compression algorithm: - * - * 01 2F B0 00 23 61 61 61 62 63 64 65 82 66 00 70 - * 61 67 68 69 6A 01 38 08 61 6B 6C 00 30 6D 6E 6F - * 70 06 71 02 70 04 10 72 73 74 75 76 10 77 78 79 - * 7A 00 3C - * - * The following hex array represents the decompressed byte array of the example string as - * decompressed by the decompression algorithm: - * - * 23 61 61 61 62 63 64 65 66 61 61 61 61 67 68 69 - * 6a 61 61 61 61 61 6B 6C 61 61 61 6D 6E 6F 70 71 - * 61 61 61 61 61 61 61 61 61 61 61 61 72 73 74 75 - * 76 77 78 79 7A 61 61 61 - */ - @Test - void normalCompressionExample() { - final byte[] compressed = { - 0x01, 0x2F, (byte)0xB0, 0x00, 0x23, 0x61, 0x61, 0x61, 0x62, 0x63, 0x64, 0x65, (byte)0x82, 0x66, 0x00, 0x70, - 0x61, 0x67, 0x68, 0x69, 0x6A, 0x01, 0x38, 0x08, 0x61, 0x6B, 0x6C, 0x00, 0x30, 0x6D, 0x6E, 0x6F, - 0x70, 0x06, 0x71, 0x02, 0x70, 0x04, 0x10, 0x72, 0x73, 0x74, 0x75, 0x76, 0x10, 0x77, 0x78, 0x79, - 0x7A, 0x00, 0x3C - }; - final String expected = "#aaabcdefaaaaghijaaaaaklaaamnopqaaaaaaaaaaaarstuvwxyzaaa"; - checkRLEDecompression(expected, compressed); - } - - /** - * Section 3.2.3 Maximum Compression Example - * - * The following string illustrates an ASCII text string with a typical set of characters that can be - * compressed by the compression algorithm. - * - * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa - * - * This example is provided to demonstrate the results of compressing and decompressing the example - * string using an interoperable implementation of the algorithm specified in section 2.4.1. - * - * The following hex array represents the compressed byte array of the example string as compressed by - * the compression algorithm: - * - * 01 03 B0 02 61 45 00 - * - * The following hex array represents the decompressed byte array of the example string as - * decompressed by the decompression algorithm: - * - * 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 - * 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 - * 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 - * 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 - * 61 61 61 61 61 61 61 61 61 - */ - @Test - void maximumCompressionExample() { - final byte[] compressed = { - 0x01, 0x03, (byte)0xB0, 0x02, 0x61, 0x45, 0x00 - }; - final String expected = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"; - checkRLEDecompression(expected, compressed); - } - - @Test - void decompress() throws IOException { - final byte[] compressed = { - 0x01, 0x03, (byte)0xB0, 0x02, 0x61, 0x45, 0x00 - }; - final byte[] expanded = RLEDecompressingInputStream.decompress(compressed); - final byte[] expected = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa".getBytes(StringUtil.UTF8); - assertArrayEquals(expected, expanded); - } - - private static void checkRLEDecompression(String expected, byte[] runLengthEncodedData) { - InputStream compressedStream = new ByteArrayInputStream(runLengthEncodedData); - ByteArrayOutputStream out = new ByteArrayOutputStream(); - try { - InputStream stream = new RLEDecompressingInputStream(compressedStream); - try { - IOUtils.copy(stream, out); - } finally { - out.close(); - stream.close(); - } - } catch (final IOException e) { - throw new RuntimeException(e); - } - String expanded; - try { - expanded = out.toString(StringUtil.UTF8.name()); - } catch (final UnsupportedEncodingException e) { - throw new RuntimeException(e); - } - assertEquals(expected, expanded); - } -} diff --git a/src/testcases/org/apache/poi/util/TestShortField.java b/src/testcases/org/apache/poi/util/TestShortField.java deleted file mode 100644 index 8c863ee074..0000000000 --- a/src/testcases/org/apache/poi/util/TestShortField.java +++ /dev/null @@ -1,129 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.util; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertThrows; - -import java.io.ByteArrayInputStream; -import java.io.IOException; - -import org.junit.jupiter.api.Test; - -/** - * Test ShortField code - */ -final class TestShortField { - - private static final short[] _test_array = {Short.MIN_VALUE, -1, 0, 1, Short.MAX_VALUE}; - - @Test - void testConstructors() { - assertThrows(ArrayIndexOutOfBoundsException.class, () -> new ShortField(-1)); - ShortField field = new ShortField(2); - - assertEquals(0, field.get()); - assertThrows(ArrayIndexOutOfBoundsException.class, () -> new ShortField(-1, ( short ) 1)); - field = new ShortField(2, ( short ) 0x1234); - assertEquals(0x1234, field.get()); - - assertThrows(ArrayIndexOutOfBoundsException.class, () -> new ShortField(-1, ( short ) 1, new byte[ 4 ])); - - byte[] array = new byte[ 4 ]; - field = new ShortField(2, ( short ) 0x1234, array); - assertEquals(( short ) 0x1234, field.get()); - assertEquals(( byte ) 0x34, array[ 2 ]); - assertEquals(( byte ) 0x12, array[ 3 ]); - - assertThrows(ArrayIndexOutOfBoundsException.class, () -> new ShortField(2, ( short ) 5, new byte[ 3 ])); - - for (short element : _test_array) { - array = new byte[ 2 ]; - new ShortField(0, element, array); - assertEquals(element, new ShortField(0, array).get()); - } - } - - @Test - void testSet() { - ShortField field = new ShortField(0); - byte[] array = new byte[ 2 ]; - - for (int j = 0; j < _test_array.length; j++) { - field.set(_test_array[ j ]); - assertEquals(_test_array[ j ], field.get(), "testing _1 " + j); - field = new ShortField(0); - field.set(_test_array[ j ], array); - assertEquals(_test_array[ j ], field.get(), "testing _2 "); - assertEquals(( byte ) (_test_array[ j ] % 256), array[ 0 ], "testing _3.0 " + _test_array[ j ]); - assertEquals(( byte ) ((_test_array[ j ] >> 8) % 256), array[ 1 ], "testing _3.1 " + _test_array[ j ]); - } - } - - @Test - void testReadFromBytes() { - ShortField field1 = new ShortField(1); - byte[] array = new byte[ 2 ]; - - assertThrows(ArrayIndexOutOfBoundsException.class, () -> field1.readFromBytes(array)); - - ShortField field2 = new ShortField(0); - for (int j = 0; j < _test_array.length; j++) - { - array[ 0 ] = ( byte ) (_test_array[ j ] % 256); - array[ 1 ] = ( byte ) ((_test_array[ j ] >> 8) % 256); - field2.readFromBytes(array); - assertEquals(_test_array[ j ], field2.get(), "testing " + j); - } - } - - @Test - void testReadFromStream() throws IOException { - ShortField field = new ShortField(0); - byte[] buffer = new byte[ _test_array.length * 2 ]; - - for (int j = 0; j < _test_array.length; j++) - { - buffer[ (j * 2) ] = ( byte ) (_test_array[ j ] % 256); - buffer[ (j * 2) + 1 ] = ( byte ) ((_test_array[ j ] >> 8) % 256); - } - ByteArrayInputStream stream = new ByteArrayInputStream(buffer); - - for (int j = 0; j < buffer.length / 2; j++) - { - field.readFromStream(stream); - assertEquals(_test_array[ j ], field.get(), "Testing " + j); - } - } - - @Test - void testWriteToBytes() { - ShortField field = new ShortField(0); - byte[] array = new byte[ 2 ]; - - for (short element : _test_array) { - field.set(element); - field.writeToBytes(array); - short val = ( short ) (array[ 1 ] << 8); - - val &= ( short ) 0xFF00; - val += ( short ) (array[ 0 ] & 0x00FF); - assertEquals(element, val, "testing "); - } - } -} diff --git a/src/testcases/org/apache/poi/util/TestStringCodepointsIterable.java b/src/testcases/org/apache/poi/util/TestStringCodepointsIterable.java deleted file mode 100644 index 4630a3cd0d..0000000000 --- a/src/testcases/org/apache/poi/util/TestStringCodepointsIterable.java +++ /dev/null @@ -1,46 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.util; - -import static org.junit.jupiter.api.Assertions.assertEquals; - -import java.util.ArrayList; -import java.util.List; - -import org.junit.jupiter.api.Test; - -/** - * Unit test for StringCodepointsIterable - */ -class TestStringCodepointsIterable { - - @Test - void testIterable() { - final String unicodeSurrogates = "\uD835\uDF4A\uD835\uDF4B\uD835\uDF4C\uD835\uDF4D\uD835\uDF4E" - + "abcdef123456"; - StringCodepointsIterable sci = new StringCodepointsIterable(unicodeSurrogates); - List<String> codePoints = new ArrayList<>(); - List<String> codePoints2 = new ArrayList<>(); - sci.iterator().forEachRemaining(codePoints::add); - sci.iterator().forEachRemaining(codePoints2::add); - assertEquals(17, codePoints.size()); - assertEquals(codePoints, codePoints2); - } - -} - diff --git a/src/testcases/org/apache/poi/util/TestStringUtil.java b/src/testcases/org/apache/poi/util/TestStringUtil.java deleted file mode 100644 index c0545cd762..0000000000 --- a/src/testcases/org/apache/poi/util/TestStringUtil.java +++ /dev/null @@ -1,157 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.util; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.junit.jupiter.api.Assertions.assertTrue; -import static org.junit.jupiter.api.Assertions.fail; - -import java.nio.charset.Charset; - -import org.junit.jupiter.api.Test; - -/** - * Unit test for StringUtil - */ -class TestStringUtil { - - /** - * test getFromUnicodeHigh for symbols with code below and more 127 - */ - @Test - void testGetFromUnicodeHighSymbolsWithCodesMoreThan127() { - byte[] test_data = new byte[]{0x22, 0x04, - 0x35, 0x04, - 0x41, 0x04, - 0x42, 0x04, - 0x20, 0x00, - 0x74, 0x00, - 0x65, 0x00, - 0x73, 0x00, - 0x74, 0x00, - }; - - - assertEquals( "\u0422\u0435\u0441\u0442 test", - StringUtil.getFromUnicodeLE( test_data ) ); - } - - @Test - void testPutCompressedUnicode() { - byte[] output = new byte[100]; - byte[] expected_output = - { - (byte) 'H', (byte) 'e', (byte) 'l', (byte) 'l', - (byte) 'o', (byte) ' ', (byte) 'W', (byte) 'o', - (byte) 'r', (byte) 'l', (byte) 'd', (byte) 0xAE - }; - String input = new String( expected_output, Charset.forName(StringUtil.getPreferredEncoding()) ); - - StringUtil.putCompressedUnicode( input, output, 0 ); - for ( int j = 0; j < expected_output.length; j++ ) - { - assertEquals( expected_output[j], output[j], "testing offset " + j ); - } - StringUtil.putCompressedUnicode( input, output, - 100 - expected_output.length ); - for ( int j = 0; j < expected_output.length; j++ ) - { - assertEquals( expected_output[j], output[100 + j - expected_output.length], "testing offset " + j ); - } - - assertThrows(ArrayIndexOutOfBoundsException.class, - () -> StringUtil.putCompressedUnicode( input, output, 101 - expected_output.length )); - } - - @Test - void testPutUncompressedUnicode() { - byte[] output = new byte[100]; - String input = "Hello World"; - byte[] expected_output = { - (byte) 'H', (byte) 0, (byte) 'e', (byte) 0, (byte) 'l', - (byte) 0, (byte) 'l', (byte) 0, (byte) 'o', (byte) 0, - (byte) ' ', (byte) 0, (byte) 'W', (byte) 0, (byte) 'o', - (byte) 0, (byte) 'r', (byte) 0, (byte) 'l', (byte) 0, - (byte) 'd', (byte) 0 - }; - - StringUtil.putUnicodeLE( input, output, 0 ); - for ( int j = 0; j < expected_output.length; j++ ) { - assertEquals( expected_output[j], output[j], "testing offset " + j ); - } - StringUtil.putUnicodeLE( input, output, 100 - expected_output.length ); - for ( int j = 0; j < expected_output.length; j++ ) { - assertEquals( expected_output[j], output[100 + j - expected_output.length], "testing offset " + j ); - } - - assertThrows(ArrayIndexOutOfBoundsException.class, () -> - StringUtil.putUnicodeLE( input, output, 101 - expected_output.length )); - } - - @Test - void startsWithIgnoreCase() { - assertTrue(StringUtil.startsWithIgnoreCase("Apache POI", "Apache POI"), "same string"); - assertTrue(StringUtil.startsWithIgnoreCase("Apache POI project", "Apache POI"), "longer string"); - assertTrue(StringUtil.startsWithIgnoreCase("APACHE POI", "Apache POI"), "different case"); - assertFalse(StringUtil.startsWithIgnoreCase(" Apache POI project", "Apache POI"), "leading whitespace should not be ignored"); - assertFalse(StringUtil.startsWithIgnoreCase("Apache", "Apache POI"), "shorter string"); - } - - @Test - void endsWithIgnoreCase() { - assertTrue(StringUtil.endsWithIgnoreCase("Apache POI", "Apache POI"), "same string"); - assertTrue(StringUtil.endsWithIgnoreCase("Project Apache POI", "Apache POI"), "longer string"); - assertTrue(StringUtil.endsWithIgnoreCase("APACHE POI", "Apache POI"), "different case"); - assertFalse(StringUtil.endsWithIgnoreCase("Apache POI project ", "Apache POI"), "trailing whitespace should not be ignored"); - assertFalse(StringUtil.endsWithIgnoreCase("Apache", "Apache POI"), "shorter string"); - } - - @Test - void join() { - assertEquals("", StringUtil.join(",")); // degenerate case: nothing to join - assertEquals("abc", StringUtil.join(",", "abc")); // degenerate case: one thing to join, no trailing comma - assertEquals("abc|def|ghi", StringUtil.join("|", "abc", "def", "ghi")); - assertEquals("5|8.5|true|string", StringUtil.join("|", 5, 8.5, true, "string")); //assumes Locale prints number decimal point as a period rather than a comma - - String[] arr = new String[] { "Apache", "POI", "project" }; - assertEquals("ApachePOIproject", StringUtil.join(arr), "no separator"); - assertEquals("Apache POI project", StringUtil.join(arr, " "), "separator"); - } - - @Test - void count() { - String test = "Apache POI project\n\u00a9 Copyright 2016"; - // supports search in null or empty string - assertEquals(0, StringUtil.countMatches(null, 'A'), "null"); - assertEquals(0, StringUtil.countMatches("", 'A'), "empty string"); - - assertEquals(2, StringUtil.countMatches(test, 'e'), "normal"); - assertEquals(1, StringUtil.countMatches(test, 'a'), "normal, should not find a in escaped copyright"); - - // search for non-printable characters - assertEquals(0, StringUtil.countMatches(test, '\0'), "null character"); - assertEquals(0, StringUtil.countMatches(test, '\r'), "CR"); - assertEquals(1, StringUtil.countMatches(test, '\n'), "LF"); - - // search for unicode characters - assertEquals(1, StringUtil.countMatches(test, '\u00a9'), "Unicode"); - } -} - diff --git a/src/testcases/org/apache/poi/util/TestTempFile.java b/src/testcases/org/apache/poi/util/TestTempFile.java deleted file mode 100644 index ec195e35f8..0000000000 --- a/src/testcases/org/apache/poi/util/TestTempFile.java +++ /dev/null @@ -1,142 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.util; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.junit.jupiter.api.Assertions.assertTrue; - -import java.io.File; -import java.io.FileOutputStream; -import java.io.IOException; -import java.util.Arrays; - -import org.apache.poi.poifs.dev.TestPOIFSDump; -import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; - -class TestTempFile { - private String previousTempDir; - private File tempDir; - - @BeforeEach - void setUp() throws IOException { - previousTempDir = System.getProperty(TempFile.JAVA_IO_TMPDIR); - if(previousTempDir != null) { - assertTrue(new File(previousTempDir).exists() || new File(previousTempDir).mkdirs(), - "Failed to create directory " + previousTempDir); - } - - // use a separate tempdir for the tests to be able to check for leftover files - tempDir = File.createTempFile("TestTempFile", ".tst"); - assertTrue(tempDir.delete()); - assertTrue(tempDir.mkdirs()); - System.setProperty(TempFile.JAVA_IO_TMPDIR, tempDir.getAbsolutePath()); - } - - @AfterEach - void tearDown() throws IOException { - if(tempDir != null) { - String[] files = tempDir.list(); - assertNotNull(files); - // can have the "poifiles" subdir - if (files.length == 1) { - assertEquals(DefaultTempFileCreationStrategy.POIFILES, files[0], "Had: " + Arrays.toString(files)); - files = new File(tempDir, files[0]).list(); - assertNotNull(files); - assertEquals(0, files.length, "Had: " + Arrays.toString(files)); - } else { - assertEquals(0, files.length, "Had: " + Arrays.toString(files)); - } - - // remove the directory after the tests - TestPOIFSDump.deleteDirectory(tempDir); - } - - if(previousTempDir == null) { - System.clearProperty(TempFile.JAVA_IO_TMPDIR); - } else { - System.setProperty(TempFile.JAVA_IO_TMPDIR, previousTempDir); - } - - // reset strategy to re-create the directory - TempFile.setTempFileCreationStrategy(new DefaultTempFileCreationStrategy()); - - // check that we can still create a tempfile - File testFile = TempFile.createTempFile("test", ".tst"); - assertTrue(testFile.exists()); - assertTrue(testFile.delete()); - } - - @Test - void testCreateTempFile() throws IOException - { - File tempFile = TempFile.createTempFile("test", ".txt"); - FileOutputStream fos = new FileOutputStream(tempFile); - fos.write(1); //file can be written to - fos.close(); - assertTrue(tempFile.exists()); - assertTrue(tempFile.isFile()); - assertTrue(tempFile.getName().startsWith("test")); - assertTrue(tempFile.getName().endsWith(".txt")); - assertEquals(DefaultTempFileCreationStrategy.POIFILES, tempFile.getParentFile().getName()); - - // Can't think of a good way to check whether a file is actually deleted since it would require the VM to stop. - // Solution: set TempFileCreationStrategy to something that the unit test can trigger a deletion" - assertTrue(tempFile.delete()); - } - - @Test - void createTempFileWithDefaultSuffix() throws IOException { - File tempFile = TempFile.createTempFile("test", null); - assertTrue(tempFile.getName().endsWith(".tmp")); - } - - @Test - void testCreateTempDirectory() throws IOException - { - File tempDir = TempFile.createTempDirectory("testDir"); - assertTrue(tempDir.exists()); - assertTrue(tempDir.isDirectory()); - assertTrue(tempDir.getName().startsWith("testDir")); - assertEquals(DefaultTempFileCreationStrategy.POIFILES, tempDir.getParentFile().getName()); - - // Can't think of a good way to check whether a directory is actually deleted since it would require the VM to stop. - // Solution: set TempFileCreationStrategy to something that the unit test can trigger a deletion" - assertTrue(tempDir.delete()); - } - - @Test - void testSetTempFileCreationStrategy() throws IOException { - TempFile.setTempFileCreationStrategy(new DefaultTempFileCreationStrategy()); - - // Should be able to create two tempfiles with same prefix and suffix - File file1 = TempFile.createTempFile("TestTempFile", ".tst"); - File file2 = TempFile.createTempFile("TestTempFile", ".tst"); - assertNotEquals(file1, file2); - assertNotNull(file2); - assertTrue(file2.delete()); - assertNotNull(file1); - assertTrue(file1.delete()); - - //noinspection ConstantConditions - assertThrows(IllegalArgumentException.class, () -> TempFile.setTempFileCreationStrategy(null)); - } -} diff --git a/src/testcases/org/apache/poi/util/TestXMLHelper.java b/src/testcases/org/apache/poi/util/TestXMLHelper.java deleted file mode 100644 index a4e8732b8d..0000000000 --- a/src/testcases/org/apache/poi/util/TestXMLHelper.java +++ /dev/null @@ -1,161 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.util; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertNotSame; -import static org.junit.jupiter.api.Assertions.assertTrue; - -import java.io.ByteArrayInputStream; -import java.nio.charset.StandardCharsets; -import java.util.ArrayList; -import java.util.HashSet; -import java.util.concurrent.CompletableFuture; -import java.util.concurrent.TimeUnit; - -import javax.xml.XMLConstants; -import javax.xml.parsers.DocumentBuilder; -import javax.xml.parsers.DocumentBuilderFactory; -import javax.xml.stream.XMLInputFactory; -import javax.xml.stream.XMLOutputFactory; - -import org.junit.jupiter.api.Test; -import org.xml.sax.InputSource; -import org.xml.sax.SAXNotRecognizedException; -import org.xml.sax.XMLReader; - -class TestXMLHelper { - @Test - void testDocumentBuilder() throws Exception { - DocumentBuilder documentBuilder = XMLHelper.newDocumentBuilder(); - assertNotSame(documentBuilder, XMLHelper.newDocumentBuilder()); - assertTrue(documentBuilder.isNamespaceAware()); - assertFalse(documentBuilder.isValidating()); - documentBuilder.parse(new InputSource(new ByteArrayInputStream("<xml></xml>".getBytes(StandardCharsets.UTF_8)))); - } - - @Test - void testCreatingManyDocumentBuilders() throws Exception { - int limit = 1000; - ArrayList<CompletableFuture<DocumentBuilder>> futures = new ArrayList<>(); - for (int i = 0; i < limit; i++) { - futures.add(CompletableFuture.supplyAsync(XMLHelper::newDocumentBuilder)); - } - HashSet<DocumentBuilder> dbs = new HashSet<>(); - for (CompletableFuture<DocumentBuilder> future : futures) { - DocumentBuilder documentBuilder = future.get(10, TimeUnit.SECONDS); - assertTrue(documentBuilder.isNamespaceAware()); - dbs.add(documentBuilder); - } - assertEquals(limit, dbs.size()); - } - - @Test - void testDocumentBuilderFactory() throws Exception { - try { - DocumentBuilderFactory dbf = XMLHelper.getDocumentBuilderFactory(); - assertTrue(dbf.getFeature(XMLConstants.FEATURE_SECURE_PROCESSING)); - assertTrue(dbf.getFeature(XMLHelper.FEATURE_DISALLOW_DOCTYPE_DECL)); - assertFalse(dbf.getFeature(XMLHelper.FEATURE_LOAD_DTD_GRAMMAR)); - assertFalse(dbf.getFeature(XMLHelper.FEATURE_LOAD_EXTERNAL_DTD)); - } catch (AbstractMethodError e) { - // ignore exceptions from old parsers that don't support this API (https://bz.apache.org/bugzilla/show_bug.cgi?id=62692) - } - } - - @Test - void testXMLReader() throws Exception { - XMLReader reader = XMLHelper.newXMLReader(); - assertNotSame(reader, XMLHelper.newXMLReader()); - try { - assertTrue(reader.getFeature(XMLConstants.FEATURE_SECURE_PROCESSING)); - assertFalse(reader.getFeature(XMLHelper.FEATURE_LOAD_DTD_GRAMMAR)); - assertFalse(reader.getFeature(XMLHelper.FEATURE_LOAD_EXTERNAL_DTD)); - // assertEquals(XMLHelper.IGNORING_ENTITY_RESOLVER, reader.getEntityResolver()); - assertNotNull(reader.getProperty(XMLHelper.PROPERTY_ENTITY_EXPANSION_LIMIT)); - assertEquals("1", reader.getProperty(XMLHelper.PROPERTY_ENTITY_EXPANSION_LIMIT)); - assertNotNull(reader.getProperty(XMLHelper.PROPERTY_SECURITY_MANAGER)); - } catch (SAXNotRecognizedException e) { - // ignore exceptions from old parsers that don't support these features - // (https://bz.apache.org/bugzilla/show_bug.cgi?id=62692) - } - reader.parse(new InputSource(new ByteArrayInputStream("<xml></xml>".getBytes(StandardCharsets.UTF_8)))); - } - - @Test - void testCreatingManyXMLReaders() throws Exception { - int limit = 1000; - ArrayList<CompletableFuture<XMLReader>> futures = new ArrayList<>(); - for (int i = 0; i < limit; i++) { - futures.add(CompletableFuture.supplyAsync(() -> { - try { - return XMLHelper.newXMLReader(); - } catch (RuntimeException e) { - throw e; - } catch (Exception e) { - throw new RuntimeException(e); - } - })); - } - HashSet<XMLReader> readers = new HashSet<>(); - for (CompletableFuture<XMLReader> future : futures) { - XMLReader reader = future.get(10, TimeUnit.SECONDS); - try { - assertTrue(reader.getFeature(XMLConstants.FEATURE_SECURE_PROCESSING)); - } catch (SAXNotRecognizedException e) { - // can happen for older XML Parsers, e.g. we have a CI Job which runs with Xerces XML Parser - assertTrue(reader.getClass().getName().contains("org.apache.xerces"), - "Had Exception about not-recognized SAX feature: " + e + " which is only expected" + - " for Xerces XML Parser, but had parser: " + reader); - } - readers.add(reader); - } - assertEquals(limit, readers.size()); - } - - /** - * test that newXMLInputFactory returns a factory with sensible defaults - */ - @Test - void testNewXMLInputFactory() { - XMLInputFactory factory = XMLHelper.newXMLInputFactory(); - assertTrue((boolean)factory.getProperty(XMLInputFactory.IS_NAMESPACE_AWARE)); - assertFalse((boolean)factory.getProperty(XMLInputFactory.IS_VALIDATING)); - assertFalse((boolean)factory.getProperty(XMLInputFactory.SUPPORT_DTD)); - assertFalse((boolean)factory.getProperty(XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES)); - } - - /** - * test that newXMLOutputFactory returns a factory with sensible defaults - */ - @Test - void testNewXMLOutputFactory() { - XMLOutputFactory factory = XMLHelper.newXMLOutputFactory(); - assertTrue((boolean)factory.getProperty(XMLOutputFactory.IS_REPAIRING_NAMESPACES)); - } - - /** - * test that newXMLEventFactory returns a factory - */ - @Test - void testNewXMLEventFactory() { - assertNotNull(XMLHelper.newXMLEventFactory()); - } -} diff --git a/src/testcases/org/apache/poi/util/data/test_properties1 b/src/testcases/org/apache/poi/util/data/test_properties1 deleted file mode 100644 index 5c88809b70..0000000000 --- a/src/testcases/org/apache/poi/util/data/test_properties1 +++ /dev/null @@ -1,26 +0,0 @@ -# Licensed to the Apache Software Foundation (ASF) under one or more -# contributor license agreements. See the NOTICE file distributed with -# this work for additional information regarding copyright ownership. -# The ASF licenses this file to You under the Apache License, Version 2.0 -# (the "License"); you may not use this file except in compliance with -# the License. You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -# Set root category priority to DEBUG and its only appender to A1. -log4j.rootCategory=DEBUG, A1 - -# A1 is set to be a FileAppender. -log4j.appender.A1=org.apache.log4j.FileAppender -log4j.appender.A1.File=p1.log - -# A1 uses PatternLayout. -log4j.appender.A1.layout=org.apache.log4j.PatternLayout -log4j.appender.A1.layout.ConversionPattern=%-4r [%t] %-5p %c %x - %m%n -#log4j.category.org.apache.cocoon.poi=WARN diff --git a/src/testcases/org/apache/poi/util/data/test_properties2 b/src/testcases/org/apache/poi/util/data/test_properties2 deleted file mode 100644 index dbf3f81e16..0000000000 --- a/src/testcases/org/apache/poi/util/data/test_properties2 +++ /dev/null @@ -1,26 +0,0 @@ -# Licensed to the Apache Software Foundation (ASF) under one or more -# contributor license agreements. See the NOTICE file distributed with -# this work for additional information regarding copyright ownership. -# The ASF licenses this file to You under the Apache License, Version 2.0 -# (the "License"); you may not use this file except in compliance with -# the License. You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -# Set root category priority to DEBUG and its only appender to A2. -log4j.rootCategory=DEBUG, A2 - -# A2 is set to be a FileAppender. -log4j.appender.A2=org.apache.log4j.FileAppender -log4j.appender.A2.File=p2.log - -# A2 uses PatternLayout. -log4j.appender.A2.layout=org.apache.log4j.PatternLayout -log4j.appender.A2.layout.ConversionPattern=%-4r [%t] %-5p %c %x - %m%n -#log4j.category.org.apache.cocoon.poi=WARN diff --git a/src/testcases/org/apache/poi/util/data/test_properties3 b/src/testcases/org/apache/poi/util/data/test_properties3 deleted file mode 100644 index 84ba40da05..0000000000 --- a/src/testcases/org/apache/poi/util/data/test_properties3 +++ /dev/null @@ -1,26 +0,0 @@ -# Licensed to the Apache Software Foundation (ASF) under one or more -# contributor license agreements. See the NOTICE file distributed with -# this work for additional information regarding copyright ownership. -# The ASF licenses this file to You under the Apache License, Version 2.0 -# (the "License"); you may not use this file except in compliance with -# the License. You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -# Set root category priority to DEBUG and its only appender to A3. -log4j.rootCategory=DEBUG, A3 - -# A3 is set to be a FileAppender. -log4j.appender.A3=org.apache.log4j.FileAppender -log4j.appender.A3.File=POILogger.log - -# A3 uses PatternLayout. -log4j.appender.A3.layout=org.apache.log4j.PatternLayout -log4j.appender.A3.layout.ConversionPattern=%-4r [%t] %-5p %c %x - %m%n -#log4j.category.org.apache.cocoon.poi=WARN |