Modified: ofbiz/trunk/framework/base/src/org/ofbiz/base/test/GenericTestCaseBase.java
URL: http://svn.apache.org/viewvc/ofbiz/trunk/framework/base/src/org/ofbiz/base/test/GenericTestCaseBase.java?rev=1695126&r1=1695125&r2=1695126&view=diff ============================================================================== --- ofbiz/trunk/framework/base/src/org/ofbiz/base/test/GenericTestCaseBase.java (original) +++ ofbiz/trunk/framework/base/src/org/ofbiz/base/test/GenericTestCaseBase.java Mon Aug 10 16:15:37 2015 @@ -1,389 +1,389 @@ -/******************************************************************************* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - *******************************************************************************/ -package org.ofbiz.base.test; - -import java.lang.reflect.Array; -import java.lang.reflect.Constructor; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; -import java.util.HashSet; -import java.util.Iterator; -import java.util.LinkedHashMap; -import java.util.LinkedHashSet; -import java.util.LinkedList; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.concurrent.ExecutionException; -import java.util.concurrent.Future; - -import junit.framework.TestCase; - -// This class can not use any other ofbiz helper methods, because it -// may be used to test those helper methods. -public abstract class GenericTestCaseBase extends TestCase { - protected GenericTestCaseBase(String name) { - super(name); - } - - public static void useAllMemory() throws Exception { - LinkedList<long[]> dummy = new LinkedList<long[]>(); - try { - do { - dummy.add(new long[1048576]); - } while (true); - } catch (OutOfMemoryError e) { - System.gc(); - Thread.sleep(100); - } - } - - public static void assertStaticHelperClass(Class<?> clz) throws Exception { - Constructor<?>[] constructors = clz.getDeclaredConstructors(); - assertEquals(clz.getName() + " constructor count", 1, constructors.length); - assertEquals(clz.getName() + " private declared constructor", 1 << Constructor.DECLARED, constructors[0].getModifiers() & ~(1 << Constructor.PUBLIC) & (1 << Constructor.DECLARED)); - constructors[0].setAccessible(true); - constructors[0].newInstance(); - } - - public static void assertComparison(String label, int wanted, int result) { - if (wanted == 0) { - assertEquals(label, wanted, result); - } else { - assertEquals(label, wanted, result / Math.abs(result)); - } - } - - public static <V, E extends Exception> void assertFuture(String label, Future<V> future, V wanted, boolean interruptable, Class<E> thrownClass, String thrownMessage) { - try { - assertEquals(label + ": future return", wanted, future.get()); - } catch (InterruptedException e) { - assertTrue(label + ": expected interruption", interruptable); - } catch (ExecutionException e) { - assertNotNull(label + ": expecting an exception", thrownClass); - Throwable caught = e.getCause(); - assertNotNull(label + ": captured exception", caught); - assertEquals(label + ": correct thrown class", thrownClass, caught.getClass()); - if (thrownMessage != null) { - assertEquals(label + ": exception message", thrownMessage, caught.getMessage()); - } - } - } - - public static <T> void assertNotEquals(Object wanted, Object got) { - assertNotEquals(null, wanted, got); - } - - public static <T> void assertNotEquals(String msg, Object wanted, Object got) { - if (wanted == null) { - if (got != null) { - return; - } - failEquals(msg, wanted, got); - } else if (wanted.equals(got)) { - failEquals(msg, wanted, got); - } - } - - private static void failEquals(String msg, Object wanted, Object got) { - StringBuilder sb = new StringBuilder(); - if (msg != null) { - sb.append(msg).append(' '); - } - sb.append(" expected value: ").append(wanted); - sb.append(" actual value: ").append(got); - fail(sb.toString()); - } - - public static <T> void assertEquals(List<T> wanted, Object got) { - assertEquals(null, wanted, got); - } - - public static <T> void assertEquals(String msg, List<T> wanted, Object got) { - msg = msg == null ? "" : msg + ' '; - assertNotNull(msg + "expected a value", got); - if (got.getClass().isArray()) { - assertEqualsListArray(msg, wanted, got); - return; - } - if (!(got instanceof Collection<?>)) fail(msg + "expected a collection, got a " + got.getClass()); - Iterator<T> leftIt = wanted.iterator(); - Iterator<?> rightIt = ((Collection<?>) got).iterator(); - int i = 0; - while (leftIt.hasNext() && rightIt.hasNext()) { - T left = leftIt.next(); - Object right = rightIt.next(); - assertEquals(msg + "item " + i, left, right); - i++; - } - assertFalse(msg + "not enough items", leftIt.hasNext()); - assertFalse(msg + "too many items", rightIt.hasNext()); - } - - public static <T> void assertEquals(Collection<T> wanted, Object got) { - assertEquals(null, wanted, got); - } - - public static <T> void assertEquals(String msg, Collection<T> wanted, Object got) { - if (wanted instanceof List<?> || wanted instanceof Set<?>) { - // list.equals(list) and set.equals(set), see docs for Collection.equals - if (got instanceof Set<?>) fail("Not a collection, is a set"); - if (got instanceof List<?>) fail("Not a collection, is a list"); - } - if (wanted.equals(got)) return; - if (!(got instanceof Collection<?>)) fail(msg + "not a collection"); - // Need to check the reverse, wanted may not implement equals, - // which is the case for HashMap.values() - if (got.equals(wanted)) return; - msg = msg == null ? "" : msg + ' '; - assertNotNull(msg + "expected a value", got); - List<T> list = new ArrayList<T>(wanted); - Iterator<?> rightIt = ((Collection<?>) got).iterator(); -OUTER: - while (rightIt.hasNext()) { - Object right = rightIt.next(); - for (int i = 0; i < list.size(); i++) { - T left = list.get(i); - if (left == null) { - if (right == null) { - list.remove(i); - continue OUTER; - } - } else if (left.equals(right)) { - list.remove(i); - continue OUTER; - } - } - fail(msg + "couldn't find " + right); - } - if (!list.isEmpty()) fail(msg + "not enough items: " + list); - } - - public static <T> void assertEquals(Set<T> wanted, Object got) { - assertEquals(null, wanted, got); - } - - public static <T> void assertEquals(String msg, Set<T> wanted, Object got) { - if (wanted.equals(got)) return; - if (!(got instanceof Set<?>)) fail(msg + "not a set"); - // Need to check the reverse, wanted may not implement equals, - // which is the case for HashMap.values() - if (got.equals(wanted)) return; - msg = msg == null ? "" : msg + ' '; - assertNotNull(msg + "expected a value", got); - Set<T> wantedSet = new HashSet<T>(wanted); - Iterator<?> rightIt = ((Set<?>) got).iterator(); - while (rightIt.hasNext()) { - Object right = rightIt.next(); - if (wantedSet.contains(right)) { - wantedSet.remove(right); - } else { - fail(msg + "couldn't find " + right); - } - } - if (!wantedSet.isEmpty()) fail(msg + "not enough items: " + wantedSet); - } - - private static <T> void assertEqualsArrayArray(String msg, Object wanted, Object got) { - int i = 0; - while (i < Array.getLength(wanted) && i < Array.getLength(got)) { - Object left = Array.get(wanted, i); - Object right = Array.get(got, i); - assertEquals(msg + "item " + i, left, right); - i++; - } - assertFalse(msg + "not enough items", i < Array.getLength(wanted)); - assertFalse(msg + "too many items", i < Array.getLength(got)); - } - - private static <T> void assertEqualsArrayList(String msg, Object wanted, List<T> got) { - Iterator<T> rightIt = got.iterator(); - int i = 0; - while (i < Array.getLength(wanted) && rightIt.hasNext()) { - Object left = Array.get(wanted, i); - T right = rightIt.next(); - assertEquals(msg + "item " + i, left, right); - i++; - } - assertFalse(msg + "too enough items", i < Array.getLength(wanted)); - assertFalse(msg + "not many items", rightIt.hasNext()); - } - - private static <T> void assertEqualsListArray(String msg, List<T> wanted, Object got) { - Iterator<T> leftIt = wanted.iterator(); - int i = 0; - while (leftIt.hasNext() && i < Array.getLength(got)) { - T left = leftIt.next(); - Object right = Array.get(got, i); - assertEquals(msg + "item " + i, left, right); - i++; - } - assertFalse(msg + "not enough items", leftIt.hasNext()); - assertFalse(msg + "too many items", i < Array.getLength(got)); - } - - public static <V, I extends Iterable<V>> void assertEqualsIterable(String label, List<? extends V> wanted, I got) { - assertEqualsIterable(label, wanted, 0, got, 0); - } - - public static <V, I extends Iterable<V>> void assertEqualsIterable(String label, List<? extends V> wanted, int wantedExtra, I got, int gotExtra) { - Iterator<? extends V> wantedIt = wanted.iterator(); - Iterator<V> gotIt = got.iterator(); - while (wantedIt.hasNext() && gotIt.hasNext()) { - assertEquals(label + ":iterate", wantedIt.next(), gotIt.next()); - } - while (wantedExtra > 0) { - assertTrue(label + ":wanted-extra(" + wantedExtra + ")", wantedIt.hasNext()); - wantedExtra--; - } - assertFalse(label + ":wanted-done", wantedIt.hasNext()); - while (gotExtra > 0) { - assertTrue(label + ":got-extra(" + gotExtra + ")", gotIt.hasNext()); - gotExtra--; - } - assertFalse(label + ":got-done", gotIt.hasNext()); - } - - public static <V, I extends Iterable<V>> void assertEqualsIterable(String label, List<? extends V> wanted, List<? extends V> wantedExtra, I got, List<? extends V> gotExtra) { - assertEqualsIterable(label, wanted, wantedExtra, false, got, gotExtra, false); - } - - public static <V, I extends Iterable<V>> void assertEqualsIterable(String label, List<? extends V> wanted, List<? extends V> wantedExtra, boolean removeWanted, I got, List<? extends V> gotExtra, boolean removeGot) { - Iterator<? extends V> wantedIt = wanted.iterator(); - Iterator<V> gotIt = got.iterator(); - while (wantedIt.hasNext() && gotIt.hasNext()) { - assertEquals(label + ":iterate", wantedIt.next(), gotIt.next()); - } - while (wantedExtra.size() > 0) { - assertTrue(label + ":wanted-extra(" + wantedExtra + ")-hasNext", wantedIt.hasNext()); - assertEquals(label + ":wanted-extra(" + wantedExtra + ")", wantedExtra.remove(0), wantedIt.next()); - if (removeWanted) { - wantedIt.remove(); - } - } - assertFalse(label + ":wanted-done", wantedIt.hasNext()); - while (gotExtra.size() > 0) { - assertTrue(label + ":got-extra(" + gotExtra + ")-hasNext", gotIt.hasNext()); - assertEquals(label + ":got-extra(" + gotExtra + ")", gotExtra.remove(0), gotIt.next()); - if (removeGot) { - gotIt.remove(); - } - } - assertFalse(label + ":got-done", gotIt.hasNext()); - } - - public static <T> void assertEquals(Map<T, ?> wanted, Object got) { - assertEquals(null, wanted, got); - } - - public static <T> void assertEquals(String msg, Map<T, ?> wanted, Object got) { - msg = msg == null ? "" : msg + ' '; - assertNotNull(msg + "expected a value", got); - if (!(got instanceof Map<?, ?>)) fail(msg + "expected a map"); - Map<?, ?> gotMap = (Map<?, ?>) got; - if (!got.equals(wanted)) { - Set<T> leftKeys = new LinkedHashSet<T>(wanted.keySet()); - HashSet<Object> rightKeys = new HashSet<Object>(gotMap.keySet()); - for (T key: leftKeys) { - assertTrue(msg + "got key(" + key + ")", rightKeys.remove(key)); - assertEquals(msg + "key(" + key + ") value", wanted.get(key), gotMap.get(key)); - } - assertTrue(msg + "extra entries", rightKeys.isEmpty()); - } - } - - public static void assertEquals(String msg, String wanted, String got) { - TestCase.assertEquals(msg, wanted, got); - } - - public static void assertEquals(Object wanted, Object got) { - assertEquals(null, wanted, got); - } - - @SuppressWarnings("unchecked") - public static void assertEquals(String msg, Object wanted, Object got) { - if (wanted instanceof List) { - assertEquals(msg, (List<?>) wanted, got); - } else if (wanted instanceof Map) { - assertEquals(msg, (Map<?, ?>) wanted, got); - } else if (wanted == null) { - TestCase.assertEquals(msg, wanted, got); - } else if (wanted instanceof Set) { - assertEquals(msg, (Set<?>) wanted, got); - } else if (wanted instanceof Collection) { - assertEquals(msg, (Collection<?>) wanted, got); - } else if (wanted.getClass().isArray()) { - if (got == null) { - TestCase.assertEquals(msg, wanted, got); - } else if (got.getClass().isArray()) { - assertEqualsArrayArray(msg, wanted, got); - } else if (got instanceof List) { - assertEqualsArrayList(msg, wanted, (List) got); - } else { - TestCase.assertEquals(msg, wanted, got); - } - } else { - TestCase.assertEquals(msg, wanted, got); - } - } - - public static <T> List<T> list(T value) { - ArrayList<T> list = new ArrayList<T>(1); - list.add(value); - return list; - } - - public static <T> List<T> list(T... list) { - return new ArrayList<T>(Arrays.asList(list)); - } - - public static <T> Set<T> set(T value) { - HashSet<T> set = new HashSet<T>(1); - set.add(value); - return set; - } - - public static <T> Set<T> set(T... list) { - return new HashSet<T>(Arrays.asList(list)); - } - - public static <T> Set<T> set(Iterable<T> iterable) { - return set(iterable.iterator()); - } - - public static <T> Set<T> set(Iterator<T> it) { - HashSet<T> set = new HashSet<T>(); - while (it.hasNext()) { - T item = it.next(); - set.add(item); - } - return set; - } - - @SuppressWarnings("unchecked") - public static <K, V> Map<K, V> map(Object... list) { - assertEquals("list has even number of elements", 0, list.length % 2); - Map<K, V> map = new LinkedHashMap<K, V>(); - for (int i = 0; i < list.length; i += 2) { - map.put((K) list[i], (V) list[i + 1]); - } - return map; - } -} +/******************************************************************************* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + *******************************************************************************/ +package org.ofbiz.base.test; + +import java.lang.reflect.Array; +import java.lang.reflect.Constructor; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.HashSet; +import java.util.Iterator; +import java.util.LinkedHashMap; +import java.util.LinkedHashSet; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.Future; + +import junit.framework.TestCase; + +// This class can not use any other ofbiz helper methods, because it +// may be used to test those helper methods. +public abstract class GenericTestCaseBase extends TestCase { + protected GenericTestCaseBase(String name) { + super(name); + } + + public static void useAllMemory() throws Exception { + LinkedList<long[]> dummy = new LinkedList<long[]>(); + try { + do { + dummy.add(new long[1048576]); + } while (true); + } catch (OutOfMemoryError e) { + System.gc(); + Thread.sleep(100); + } + } + + public static void assertStaticHelperClass(Class<?> clz) throws Exception { + Constructor<?>[] constructors = clz.getDeclaredConstructors(); + assertEquals(clz.getName() + " constructor count", 1, constructors.length); + assertEquals(clz.getName() + " private declared constructor", 1 << Constructor.DECLARED, constructors[0].getModifiers() & ~(1 << Constructor.PUBLIC) & (1 << Constructor.DECLARED)); + constructors[0].setAccessible(true); + constructors[0].newInstance(); + } + + public static void assertComparison(String label, int wanted, int result) { + if (wanted == 0) { + assertEquals(label, wanted, result); + } else { + assertEquals(label, wanted, result / Math.abs(result)); + } + } + + public static <V, E extends Exception> void assertFuture(String label, Future<V> future, V wanted, boolean interruptable, Class<E> thrownClass, String thrownMessage) { + try { + assertEquals(label + ": future return", wanted, future.get()); + } catch (InterruptedException e) { + assertTrue(label + ": expected interruption", interruptable); + } catch (ExecutionException e) { + assertNotNull(label + ": expecting an exception", thrownClass); + Throwable caught = e.getCause(); + assertNotNull(label + ": captured exception", caught); + assertEquals(label + ": correct thrown class", thrownClass, caught.getClass()); + if (thrownMessage != null) { + assertEquals(label + ": exception message", thrownMessage, caught.getMessage()); + } + } + } + + public static <T> void assertNotEquals(Object wanted, Object got) { + assertNotEquals(null, wanted, got); + } + + public static <T> void assertNotEquals(String msg, Object wanted, Object got) { + if (wanted == null) { + if (got != null) { + return; + } + failEquals(msg, wanted, got); + } else if (wanted.equals(got)) { + failEquals(msg, wanted, got); + } + } + + private static void failEquals(String msg, Object wanted, Object got) { + StringBuilder sb = new StringBuilder(); + if (msg != null) { + sb.append(msg).append(' '); + } + sb.append(" expected value: ").append(wanted); + sb.append(" actual value: ").append(got); + fail(sb.toString()); + } + + public static <T> void assertEquals(List<T> wanted, Object got) { + assertEquals(null, wanted, got); + } + + public static <T> void assertEquals(String msg, List<T> wanted, Object got) { + msg = msg == null ? "" : msg + ' '; + assertNotNull(msg + "expected a value", got); + if (got.getClass().isArray()) { + assertEqualsListArray(msg, wanted, got); + return; + } + if (!(got instanceof Collection<?>)) fail(msg + "expected a collection, got a " + got.getClass()); + Iterator<T> leftIt = wanted.iterator(); + Iterator<?> rightIt = ((Collection<?>) got).iterator(); + int i = 0; + while (leftIt.hasNext() && rightIt.hasNext()) { + T left = leftIt.next(); + Object right = rightIt.next(); + assertEquals(msg + "item " + i, left, right); + i++; + } + assertFalse(msg + "not enough items", leftIt.hasNext()); + assertFalse(msg + "too many items", rightIt.hasNext()); + } + + public static <T> void assertEquals(Collection<T> wanted, Object got) { + assertEquals(null, wanted, got); + } + + public static <T> void assertEquals(String msg, Collection<T> wanted, Object got) { + if (wanted instanceof List<?> || wanted instanceof Set<?>) { + // list.equals(list) and set.equals(set), see docs for Collection.equals + if (got instanceof Set<?>) fail("Not a collection, is a set"); + if (got instanceof List<?>) fail("Not a collection, is a list"); + } + if (wanted.equals(got)) return; + if (!(got instanceof Collection<?>)) fail(msg + "not a collection"); + // Need to check the reverse, wanted may not implement equals, + // which is the case for HashMap.values() + if (got.equals(wanted)) return; + msg = msg == null ? "" : msg + ' '; + assertNotNull(msg + "expected a value", got); + List<T> list = new ArrayList<T>(wanted); + Iterator<?> rightIt = ((Collection<?>) got).iterator(); +OUTER: + while (rightIt.hasNext()) { + Object right = rightIt.next(); + for (int i = 0; i < list.size(); i++) { + T left = list.get(i); + if (left == null) { + if (right == null) { + list.remove(i); + continue OUTER; + } + } else if (left.equals(right)) { + list.remove(i); + continue OUTER; + } + } + fail(msg + "couldn't find " + right); + } + if (!list.isEmpty()) fail(msg + "not enough items: " + list); + } + + public static <T> void assertEquals(Set<T> wanted, Object got) { + assertEquals(null, wanted, got); + } + + public static <T> void assertEquals(String msg, Set<T> wanted, Object got) { + if (wanted.equals(got)) return; + if (!(got instanceof Set<?>)) fail(msg + "not a set"); + // Need to check the reverse, wanted may not implement equals, + // which is the case for HashMap.values() + if (got.equals(wanted)) return; + msg = msg == null ? "" : msg + ' '; + assertNotNull(msg + "expected a value", got); + Set<T> wantedSet = new HashSet<T>(wanted); + Iterator<?> rightIt = ((Set<?>) got).iterator(); + while (rightIt.hasNext()) { + Object right = rightIt.next(); + if (wantedSet.contains(right)) { + wantedSet.remove(right); + } else { + fail(msg + "couldn't find " + right); + } + } + if (!wantedSet.isEmpty()) fail(msg + "not enough items: " + wantedSet); + } + + private static <T> void assertEqualsArrayArray(String msg, Object wanted, Object got) { + int i = 0; + while (i < Array.getLength(wanted) && i < Array.getLength(got)) { + Object left = Array.get(wanted, i); + Object right = Array.get(got, i); + assertEquals(msg + "item " + i, left, right); + i++; + } + assertFalse(msg + "not enough items", i < Array.getLength(wanted)); + assertFalse(msg + "too many items", i < Array.getLength(got)); + } + + private static <T> void assertEqualsArrayList(String msg, Object wanted, List<T> got) { + Iterator<T> rightIt = got.iterator(); + int i = 0; + while (i < Array.getLength(wanted) && rightIt.hasNext()) { + Object left = Array.get(wanted, i); + T right = rightIt.next(); + assertEquals(msg + "item " + i, left, right); + i++; + } + assertFalse(msg + "too enough items", i < Array.getLength(wanted)); + assertFalse(msg + "not many items", rightIt.hasNext()); + } + + private static <T> void assertEqualsListArray(String msg, List<T> wanted, Object got) { + Iterator<T> leftIt = wanted.iterator(); + int i = 0; + while (leftIt.hasNext() && i < Array.getLength(got)) { + T left = leftIt.next(); + Object right = Array.get(got, i); + assertEquals(msg + "item " + i, left, right); + i++; + } + assertFalse(msg + "not enough items", leftIt.hasNext()); + assertFalse(msg + "too many items", i < Array.getLength(got)); + } + + public static <V, I extends Iterable<V>> void assertEqualsIterable(String label, List<? extends V> wanted, I got) { + assertEqualsIterable(label, wanted, 0, got, 0); + } + + public static <V, I extends Iterable<V>> void assertEqualsIterable(String label, List<? extends V> wanted, int wantedExtra, I got, int gotExtra) { + Iterator<? extends V> wantedIt = wanted.iterator(); + Iterator<V> gotIt = got.iterator(); + while (wantedIt.hasNext() && gotIt.hasNext()) { + assertEquals(label + ":iterate", wantedIt.next(), gotIt.next()); + } + while (wantedExtra > 0) { + assertTrue(label + ":wanted-extra(" + wantedExtra + ")", wantedIt.hasNext()); + wantedExtra--; + } + assertFalse(label + ":wanted-done", wantedIt.hasNext()); + while (gotExtra > 0) { + assertTrue(label + ":got-extra(" + gotExtra + ")", gotIt.hasNext()); + gotExtra--; + } + assertFalse(label + ":got-done", gotIt.hasNext()); + } + + public static <V, I extends Iterable<V>> void assertEqualsIterable(String label, List<? extends V> wanted, List<? extends V> wantedExtra, I got, List<? extends V> gotExtra) { + assertEqualsIterable(label, wanted, wantedExtra, false, got, gotExtra, false); + } + + public static <V, I extends Iterable<V>> void assertEqualsIterable(String label, List<? extends V> wanted, List<? extends V> wantedExtra, boolean removeWanted, I got, List<? extends V> gotExtra, boolean removeGot) { + Iterator<? extends V> wantedIt = wanted.iterator(); + Iterator<V> gotIt = got.iterator(); + while (wantedIt.hasNext() && gotIt.hasNext()) { + assertEquals(label + ":iterate", wantedIt.next(), gotIt.next()); + } + while (wantedExtra.size() > 0) { + assertTrue(label + ":wanted-extra(" + wantedExtra + ")-hasNext", wantedIt.hasNext()); + assertEquals(label + ":wanted-extra(" + wantedExtra + ")", wantedExtra.remove(0), wantedIt.next()); + if (removeWanted) { + wantedIt.remove(); + } + } + assertFalse(label + ":wanted-done", wantedIt.hasNext()); + while (gotExtra.size() > 0) { + assertTrue(label + ":got-extra(" + gotExtra + ")-hasNext", gotIt.hasNext()); + assertEquals(label + ":got-extra(" + gotExtra + ")", gotExtra.remove(0), gotIt.next()); + if (removeGot) { + gotIt.remove(); + } + } + assertFalse(label + ":got-done", gotIt.hasNext()); + } + + public static <T> void assertEquals(Map<T, ?> wanted, Object got) { + assertEquals(null, wanted, got); + } + + public static <T> void assertEquals(String msg, Map<T, ?> wanted, Object got) { + msg = msg == null ? "" : msg + ' '; + assertNotNull(msg + "expected a value", got); + if (!(got instanceof Map<?, ?>)) fail(msg + "expected a map"); + Map<?, ?> gotMap = (Map<?, ?>) got; + if (!got.equals(wanted)) { + Set<T> leftKeys = new LinkedHashSet<T>(wanted.keySet()); + HashSet<Object> rightKeys = new HashSet<Object>(gotMap.keySet()); + for (T key: leftKeys) { + assertTrue(msg + "got key(" + key + ")", rightKeys.remove(key)); + assertEquals(msg + "key(" + key + ") value", wanted.get(key), gotMap.get(key)); + } + assertTrue(msg + "extra entries", rightKeys.isEmpty()); + } + } + + public static void assertEquals(String msg, String wanted, String got) { + TestCase.assertEquals(msg, wanted, got); + } + + public static void assertEquals(Object wanted, Object got) { + assertEquals(null, wanted, got); + } + + @SuppressWarnings("unchecked") + public static void assertEquals(String msg, Object wanted, Object got) { + if (wanted instanceof List) { + assertEquals(msg, (List<?>) wanted, got); + } else if (wanted instanceof Map) { + assertEquals(msg, (Map<?, ?>) wanted, got); + } else if (wanted == null) { + TestCase.assertEquals(msg, wanted, got); + } else if (wanted instanceof Set) { + assertEquals(msg, (Set<?>) wanted, got); + } else if (wanted instanceof Collection) { + assertEquals(msg, (Collection<?>) wanted, got); + } else if (wanted.getClass().isArray()) { + if (got == null) { + TestCase.assertEquals(msg, wanted, got); + } else if (got.getClass().isArray()) { + assertEqualsArrayArray(msg, wanted, got); + } else if (got instanceof List) { + assertEqualsArrayList(msg, wanted, (List) got); + } else { + TestCase.assertEquals(msg, wanted, got); + } + } else { + TestCase.assertEquals(msg, wanted, got); + } + } + + public static <T> List<T> list(T value) { + ArrayList<T> list = new ArrayList<T>(1); + list.add(value); + return list; + } + + public static <T> List<T> list(T... list) { + return new ArrayList<T>(Arrays.asList(list)); + } + + public static <T> Set<T> set(T value) { + HashSet<T> set = new HashSet<T>(1); + set.add(value); + return set; + } + + public static <T> Set<T> set(T... list) { + return new HashSet<T>(Arrays.asList(list)); + } + + public static <T> Set<T> set(Iterable<T> iterable) { + return set(iterable.iterator()); + } + + public static <T> Set<T> set(Iterator<T> it) { + HashSet<T> set = new HashSet<T>(); + while (it.hasNext()) { + T item = it.next(); + set.add(item); + } + return set; + } + + @SuppressWarnings("unchecked") + public static <K, V> Map<K, V> map(Object... list) { + assertEquals("list has even number of elements", 0, list.length % 2); + Map<K, V> map = new LinkedHashMap<K, V>(); + for (int i = 0; i < list.length; i += 2) { + map.put((K) list[i], (V) list[i + 1]); + } + return map; + } +} Propchange: ofbiz/trunk/framework/base/src/org/ofbiz/base/test/GenericTestCaseBase.java ('svn:eol-style' removed) Modified: ofbiz/trunk/framework/base/src/org/ofbiz/base/util/IndentingWriter.java URL: http://svn.apache.org/viewvc/ofbiz/trunk/framework/base/src/org/ofbiz/base/util/IndentingWriter.java?rev=1695126&r1=1695125&r2=1695126&view=diff ============================================================================== --- ofbiz/trunk/framework/base/src/org/ofbiz/base/util/IndentingWriter.java (original) +++ ofbiz/trunk/framework/base/src/org/ofbiz/base/util/IndentingWriter.java Mon Aug 10 16:15:37 2015 @@ -1,132 +1,132 @@ -/******************************************************************************* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - *******************************************************************************/ -package org.ofbiz.base.util; - -import java.io.IOException; -import java.io.FilterWriter; -import java.io.Writer; - -import org.ofbiz.base.lang.SourceMonitored; - -@SourceMonitored -public class IndentingWriter extends FilterWriter { - protected final StringBuilder indent = new StringBuilder(); - protected final boolean doSpace; - protected final boolean doNewline; - protected boolean lastWasNewline; - - public static IndentingWriter makeIndentingWriter(Writer writer) { - return writer instanceof IndentingWriter ? (IndentingWriter) writer : new IndentingWriter(writer); - } - - public IndentingWriter(Writer out, boolean doSpace, boolean doNewline) { - super(out); - this.doSpace = doSpace; - this.doNewline = doNewline; - } - - public IndentingWriter(Writer out) { - this(out, true, true); - } - - public IndentingWriter newline() throws IOException { - lastWasNewline = true; - if (doNewline) super.write('\n'); - return this; - } - - protected void checkAfterNewline() throws IOException { - if (lastWasNewline) { - if (doSpace) { - if (doNewline) { - super.write(indent.toString(), 0, indent.length()); - } else { - super.write(' '); - } - } - lastWasNewline = false; - } - } - - public IndentingWriter push() { - indent.append(' '); - return this; - } - - public IndentingWriter pop() { - indent.setLength(indent.length() - 1); - return this; - } - - public IndentingWriter space() throws IOException { - checkAfterNewline(); - if (doSpace) super.write(' '); - return this; - } - - @Override - public void write(char[] buf) throws IOException { - write(buf, 0, buf.length); - } - - @Override - public void write(char[] buf, int offset, int length) throws IOException { - int i; - for (i = offset; i < length; i++) { - if (buf[i] == '\n') { - checkAfterNewline(); - super.write(buf, offset, i - offset + 1); - offset = i + 1; - lastWasNewline = true; - } - } - checkAfterNewline(); - super.write(buf, offset, i - offset); - } - - @Override - public void write(int c) throws IOException { - checkAfterNewline(); - super.write(c); - if (c == '\n') { - lastWasNewline = true; - checkAfterNewline(); - } - } - - @Override - public void write(String s) throws IOException { - write(s, 0, s.length()); - } - - @Override - public void write(String s, int offset, int length) throws IOException { - int i; - for (i = offset; i < length; i++) { - if (s.charAt(i) == '\n') { - checkAfterNewline(); - super.write(s, offset, i - offset + 1); - offset = i + 1; - lastWasNewline = true; - } - } - checkAfterNewline(); - super.write(s, offset, i - offset); - } -} +/******************************************************************************* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + *******************************************************************************/ +package org.ofbiz.base.util; + +import java.io.IOException; +import java.io.FilterWriter; +import java.io.Writer; + +import org.ofbiz.base.lang.SourceMonitored; + +@SourceMonitored +public class IndentingWriter extends FilterWriter { + protected final StringBuilder indent = new StringBuilder(); + protected final boolean doSpace; + protected final boolean doNewline; + protected boolean lastWasNewline; + + public static IndentingWriter makeIndentingWriter(Writer writer) { + return writer instanceof IndentingWriter ? (IndentingWriter) writer : new IndentingWriter(writer); + } + + public IndentingWriter(Writer out, boolean doSpace, boolean doNewline) { + super(out); + this.doSpace = doSpace; + this.doNewline = doNewline; + } + + public IndentingWriter(Writer out) { + this(out, true, true); + } + + public IndentingWriter newline() throws IOException { + lastWasNewline = true; + if (doNewline) super.write('\n'); + return this; + } + + protected void checkAfterNewline() throws IOException { + if (lastWasNewline) { + if (doSpace) { + if (doNewline) { + super.write(indent.toString(), 0, indent.length()); + } else { + super.write(' '); + } + } + lastWasNewline = false; + } + } + + public IndentingWriter push() { + indent.append(' '); + return this; + } + + public IndentingWriter pop() { + indent.setLength(indent.length() - 1); + return this; + } + + public IndentingWriter space() throws IOException { + checkAfterNewline(); + if (doSpace) super.write(' '); + return this; + } + + @Override + public void write(char[] buf) throws IOException { + write(buf, 0, buf.length); + } + + @Override + public void write(char[] buf, int offset, int length) throws IOException { + int i; + for (i = offset; i < length; i++) { + if (buf[i] == '\n') { + checkAfterNewline(); + super.write(buf, offset, i - offset + 1); + offset = i + 1; + lastWasNewline = true; + } + } + checkAfterNewline(); + super.write(buf, offset, i - offset); + } + + @Override + public void write(int c) throws IOException { + checkAfterNewline(); + super.write(c); + if (c == '\n') { + lastWasNewline = true; + checkAfterNewline(); + } + } + + @Override + public void write(String s) throws IOException { + write(s, 0, s.length()); + } + + @Override + public void write(String s, int offset, int length) throws IOException { + int i; + for (i = offset; i < length; i++) { + if (s.charAt(i) == '\n') { + checkAfterNewline(); + super.write(s, offset, i - offset + 1); + offset = i + 1; + lastWasNewline = true; + } + } + checkAfterNewline(); + super.write(s, offset, i - offset); + } +} Propchange: ofbiz/trunk/framework/base/src/org/ofbiz/base/util/IndentingWriter.java ('svn:eol-style' removed) Modified: ofbiz/trunk/framework/base/src/org/ofbiz/base/util/RMIExtendedSocketFactory.java URL: http://svn.apache.org/viewvc/ofbiz/trunk/framework/base/src/org/ofbiz/base/util/RMIExtendedSocketFactory.java?rev=1695126&r1=1695125&r2=1695126&view=diff ============================================================================== --- ofbiz/trunk/framework/base/src/org/ofbiz/base/util/RMIExtendedSocketFactory.java (original) +++ ofbiz/trunk/framework/base/src/org/ofbiz/base/util/RMIExtendedSocketFactory.java Mon Aug 10 16:15:37 2015 @@ -1,104 +1,104 @@ -/******************************************************************************* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - *******************************************************************************/ -package org.ofbiz.base.util; - -import java.io.IOException; -import java.net.InetAddress; -import java.net.ServerSocket; -import java.net.Socket; -import java.net.UnknownHostException; -import java.rmi.server.RMISocketFactory; - -/** - * A <code>RMISocketFactory</code> implementation that creates <code>ServerSocket</code>s bound - * on a specified network interface. - */ -public class RMIExtendedSocketFactory extends RMISocketFactory { - - /** - * The network interface to bind the <code>ServerSocket</code> to. If null than bind to all interfaces. - */ - private InetAddress hostInetAddress; - - /** - * Default constructor. Bind the server sockets on all interfaces. - */ - public RMIExtendedSocketFactory() { - // leave hostInetAddress null - } - - /** - * Creates a new <code>RMIExtendedSocketFactory</code> which will create <code>ServerSocket</code>s - * bound on the specified network interface. - * - * @param inetAddress The <code>InetAddress</code> of the network interface. - */ - public RMIExtendedSocketFactory( InetAddress inetAddress ) { - this.hostInetAddress = inetAddress; - } - - /** - * Creates a new <code>RMIExtendedSocketFactory</code> which will create <code>ServerSocket</code>s - * bound on the specified network interface. - * - * @param hostIpAddress The IP address of the interface to bind the server sockets to. - * @throws UnknownHostException If an invalid IP address is provided. - */ - public RMIExtendedSocketFactory( String hostIpAddress ) throws UnknownHostException { - - // check if host length is at least equal to "0.0.0.0" - if ( hostIpAddress != null && hostIpAddress.length() >= 7 ) { - String[] octets = hostIpAddress.split( "\\." ); - - if ( octets == null || octets.length != 4 ) { - throw new UnknownHostException( "Invalid IP address: " + hostIpAddress ); - } - - byte[] ipAddr = new byte[4]; - for ( int i = 0; i < octets.length; i++ ) { - try { - ipAddr[i] = ( byte ) Integer.parseInt( octets[i] ); - } catch ( NumberFormatException nfEx ) { - throw new UnknownHostException( "Invalid IP address: " + hostIpAddress ); - } - } - - hostInetAddress = InetAddress.getByAddress( ipAddr ); - - } - - - } - - @Override - public ServerSocket createServerSocket(int port) throws IOException { - if ( hostInetAddress != null ) { - return new ServerSocket( port, 0, hostInetAddress ); - } else { - return new ServerSocket( port ); - } - } - - @Override - public Socket createSocket(String host, int port) throws IOException { - - return new Socket( host, port ); - } - -} +/******************************************************************************* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + *******************************************************************************/ +package org.ofbiz.base.util; + +import java.io.IOException; +import java.net.InetAddress; +import java.net.ServerSocket; +import java.net.Socket; +import java.net.UnknownHostException; +import java.rmi.server.RMISocketFactory; + +/** + * A <code>RMISocketFactory</code> implementation that creates <code>ServerSocket</code>s bound + * on a specified network interface. + */ +public class RMIExtendedSocketFactory extends RMISocketFactory { + + /** + * The network interface to bind the <code>ServerSocket</code> to. If null than bind to all interfaces. + */ + private InetAddress hostInetAddress; + + /** + * Default constructor. Bind the server sockets on all interfaces. + */ + public RMIExtendedSocketFactory() { + // leave hostInetAddress null + } + + /** + * Creates a new <code>RMIExtendedSocketFactory</code> which will create <code>ServerSocket</code>s + * bound on the specified network interface. + * + * @param inetAddress The <code>InetAddress</code> of the network interface. + */ + public RMIExtendedSocketFactory( InetAddress inetAddress ) { + this.hostInetAddress = inetAddress; + } + + /** + * Creates a new <code>RMIExtendedSocketFactory</code> which will create <code>ServerSocket</code>s + * bound on the specified network interface. + * + * @param hostIpAddress The IP address of the interface to bind the server sockets to. + * @throws UnknownHostException If an invalid IP address is provided. + */ + public RMIExtendedSocketFactory( String hostIpAddress ) throws UnknownHostException { + + // check if host length is at least equal to "0.0.0.0" + if ( hostIpAddress != null && hostIpAddress.length() >= 7 ) { + String[] octets = hostIpAddress.split( "\\." ); + + if ( octets == null || octets.length != 4 ) { + throw new UnknownHostException( "Invalid IP address: " + hostIpAddress ); + } + + byte[] ipAddr = new byte[4]; + for ( int i = 0; i < octets.length; i++ ) { + try { + ipAddr[i] = ( byte ) Integer.parseInt( octets[i] ); + } catch ( NumberFormatException nfEx ) { + throw new UnknownHostException( "Invalid IP address: " + hostIpAddress ); + } + } + + hostInetAddress = InetAddress.getByAddress( ipAddr ); + + } + + + } + + @Override + public ServerSocket createServerSocket(int port) throws IOException { + if ( hostInetAddress != null ) { + return new ServerSocket( port, 0, hostInetAddress ); + } else { + return new ServerSocket( port ); + } + } + + @Override + public Socket createSocket(String host, int port) throws IOException { + + return new Socket( host, port ); + } + +} Propchange: ofbiz/trunk/framework/base/src/org/ofbiz/base/util/RMIExtendedSocketFactory.java ('svn:eol-style' removed) Modified: ofbiz/trunk/framework/base/src/org/ofbiz/base/util/ReferenceCleaner.java URL: http://svn.apache.org/viewvc/ofbiz/trunk/framework/base/src/org/ofbiz/base/util/ReferenceCleaner.java?rev=1695126&r1=1695125&r2=1695126&view=diff ============================================================================== --- ofbiz/trunk/framework/base/src/org/ofbiz/base/util/ReferenceCleaner.java (original) +++ ofbiz/trunk/framework/base/src/org/ofbiz/base/util/ReferenceCleaner.java Mon Aug 10 16:15:37 2015 @@ -1,89 +1,89 @@ -/******************************************************************************* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - *******************************************************************************/ -package org.ofbiz.base.util; - -import java.lang.ref.PhantomReference; -import java.lang.ref.ReferenceQueue; -import java.lang.ref.SoftReference; -import java.lang.ref.WeakReference; - -public final class ReferenceCleaner { - public static final String module = ReferenceCleaner.class.getName(); - - private static final class CleanerThread extends Thread { - private boolean keepRunning = true; - - protected CleanerThread() { - setDaemon(true); - setName("ReferenceCleaner"); - } - - protected void stopRunning() { - keepRunning = false; - } - - @Override - public void run() { - while (keepRunning) { - try { - ((Removable) QUEUE.remove()).remove(); - } catch (Throwable t) { - // ignore - } - if (interrupted()) { - stopRunning(); - cleanerThread = new CleanerThread(); - cleanerThread.start(); - } - } - } - } - private static CleanerThread cleanerThread = new CleanerThread(); - - static { - cleanerThread.start(); - } - - private ReferenceCleaner() { - } - - private static final ReferenceQueue<Object> QUEUE = new ReferenceQueue<Object>(); - - public interface Removable { - void remove() throws Exception; - } - - public abstract static class Soft<V> extends SoftReference<V> implements Removable { - public Soft(V value) { - super(value, QUEUE); - } - } - - public abstract static class Phantom<V> extends PhantomReference<V> implements Removable { - public Phantom(V value) { - super(value, QUEUE); - } - } - - public abstract static class Weak<V> extends WeakReference<V> implements Removable { - public Weak(V value) { - super(value, QUEUE); - } - } -} +/******************************************************************************* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + *******************************************************************************/ +package org.ofbiz.base.util; + +import java.lang.ref.PhantomReference; +import java.lang.ref.ReferenceQueue; +import java.lang.ref.SoftReference; +import java.lang.ref.WeakReference; + +public final class ReferenceCleaner { + public static final String module = ReferenceCleaner.class.getName(); + + private static final class CleanerThread extends Thread { + private boolean keepRunning = true; + + protected CleanerThread() { + setDaemon(true); + setName("ReferenceCleaner"); + } + + protected void stopRunning() { + keepRunning = false; + } + + @Override + public void run() { + while (keepRunning) { + try { + ((Removable) QUEUE.remove()).remove(); + } catch (Throwable t) { + // ignore + } + if (interrupted()) { + stopRunning(); + cleanerThread = new CleanerThread(); + cleanerThread.start(); + } + } + } + } + private static CleanerThread cleanerThread = new CleanerThread(); + + static { + cleanerThread.start(); + } + + private ReferenceCleaner() { + } + + private static final ReferenceQueue<Object> QUEUE = new ReferenceQueue<Object>(); + + public interface Removable { + void remove() throws Exception; + } + + public abstract static class Soft<V> extends SoftReference<V> implements Removable { + public Soft(V value) { + super(value, QUEUE); + } + } + + public abstract static class Phantom<V> extends PhantomReference<V> implements Removable { + public Phantom(V value) { + super(value, QUEUE); + } + } + + public abstract static class Weak<V> extends WeakReference<V> implements Removable { + public Weak(V value) { + super(value, QUEUE); + } + } +} Propchange: ofbiz/trunk/framework/base/src/org/ofbiz/base/util/ReferenceCleaner.java ('svn:eol-style' removed) Modified: ofbiz/trunk/framework/base/src/org/ofbiz/base/util/UtilIO.java URL: http://svn.apache.org/viewvc/ofbiz/trunk/framework/base/src/org/ofbiz/base/util/UtilIO.java?rev=1695126&r1=1695125&r2=1695126&view=diff ============================================================================== --- ofbiz/trunk/framework/base/src/org/ofbiz/base/util/UtilIO.java (original) +++ ofbiz/trunk/framework/base/src/org/ofbiz/base/util/UtilIO.java Mon Aug 10 16:15:37 2015 @@ -1,318 +1,318 @@ -/******************************************************************************* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - *******************************************************************************/ -package org.ofbiz.base.util; - -import java.io.BufferedInputStream; -import java.io.File; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.io.OutputStream; -import java.io.OutputStreamWriter; -import java.io.Reader; -import java.io.Writer; -import java.nio.ByteBuffer; -import java.nio.CharBuffer; -import java.nio.charset.Charset; - -import org.apache.commons.io.IOUtils; - -public final class UtilIO { - public static final Charset UTF8 = Charset.forName("UTF-8"); - public static final String module = UtilIO.class.getName(); - - /** Copy an InputStream to an OutputStream, optionally closing either - * the input or the output. - * - * @param in the InputStream to copy from - * @param closeIn whether to close the input when the copy is done - * @param out the OutputStream to copy to - * @param closeOut whether to close the output when the copy is done - * @throws IOException if an error occurs - */ - public static void copy(InputStream in, boolean closeIn, OutputStream out, boolean closeOut) throws IOException { - try { - try { - IOUtils.copy(in, out); - } finally { - if (closeIn) IOUtils.closeQuietly(in); - } - } finally { - if (closeOut) IOUtils.closeQuietly(out); - } - } - - /** Copy a Reader to a Writer, optionally closing either the input or - * the output. - * - * @param reader the Reader to copy from - * @param closeIn whether to close the input when the copy is done - * @param writer the Writer to copy to - * @param closeOut whether to close the output when the copy is done - * @throws IOException if an error occurs - */ - public static void copy(Reader reader, boolean closeIn, Writer writer, boolean closeOut) throws IOException { - try { - try { - IOUtils.copy(reader, writer); - } finally { - if (closeIn) IOUtils.closeQuietly(reader); - } - } finally { - if (closeOut) IOUtils.closeQuietly(writer); - } - } - - /** Copy a Reader to an Appendable, optionally closing the input. - * - * @param reader the Reader to copy from - * @param closeIn whether to close the input when the copy is done - * @param out the Appendable to copy to - * @throws IOException if an error occurs - */ - public static void copy(Reader reader, boolean closeIn, Appendable out) throws IOException { - try { - CharBuffer buffer = CharBuffer.allocate(4096); - while (reader.read(buffer) > 0) { - buffer.flip(); - buffer.rewind(); - out.append(buffer); - } - } finally { - if (closeIn) IOUtils.closeQuietly(reader); - } - } - - /** Convert a byte array to a string; consistently uses \n line endings - * in java. This uses a default {@link Charset UTF-8} charset. - * - * @param bytes the array of bytes to convert - * @return the converted string, with platform line endings converted - * to \n - */ - public static final String readString(byte[] bytes) throws IOException { - return readString(bytes, 0, bytes.length, UTF8); - } - - /** Convert a byte array to a string; consistently uses \n line endings - * in java. The conversion is limited to the specified offset/length - * pair, and uses a default {@link Charset UTF-8} charset. - * - * @param bytes the array of bytes to convert - * @param offset the start of the conversion - * @param length how many bytes to convert - * @return the converted string, with platform line endings converted - * to \n - */ - public static final String readString(byte[] bytes, int offset, int length) throws IOException { - return readString(bytes, offset, length, UTF8); - } - - /** Convert a byte array to a string; consistently uses \n line endings - * in java. The conversion is limited to the specified offset/length - * pair, and uses the requested charset to decode the bytes. - * - * @param bytes the array of bytes to convert - * @param charset the charset to use to convert the raw bytes - * @return the converted string, with platform line endings converted - * to \n - */ - public static final String readString(byte[] bytes, String charset) throws IOException { - return readString(bytes, 0, bytes.length, Charset.forName(charset)); - } - - /** Convert a byte array to a string; consistently uses \n line - * endings in java. The conversion is limited to the specified - * offset/length pair, and uses the requested charset to decode the - * bytes. - * - * @param bytes the array of bytes to convert - * @param offset the start of the conversion - * @param length how many bytes to convert - * @param charset the charset to use to convert the raw bytes - * @return the converted string, with platform line endings converted - * to \n - */ - public static final String readString(byte[] bytes, int offset, int length, String charset) throws IOException { - return readString(bytes, 0, bytes.length, Charset.forName(charset)); - } - - /** Convert a byte array to a string, consistently uses \n line - * endings in java. The specified {@link Charset charset} is used - * to decode the bytes. - * @param bytes the array of bytes to convert - * @param charset the charset to use to convert the raw bytes - * @return the converted string, with platform line endings converted - * to \n - */ - public static final String readString(byte[] bytes, Charset charset) throws IOException { - return readString(bytes, 0, bytes.length, charset); - } - - /** Convert a byte array to a string, consistently uses \n line - * endings in java. The conversion is limited to the specified - * offset/length pair, and uses the requested {@link Charset - * charset} to decode the bytes. - * - * @param bytes the array of bytes to convert - * @param offset the start of the conversion - * @param length how many bytes to convert - * @param charset the charset to use to convert the raw bytes - * @return the converted string, with platform line endings converted - * to \n - */ - public static final String readString(byte[] bytes, int offset, int length, Charset charset) throws IOException { - ByteBuffer buf = ByteBuffer.allocate(length); - buf.put(bytes, offset, length); - buf.flip(); - return filterLineEndings(new StringBuilder(charset.decode(buf).toString())).toString(); - } - - /** Convert an {@link InputStream} to a string; consistently uses \n line endings - * in java. This uses a default {@link Charset UTF-8} charset. - * - * @param stream the stream of bytes to convert - * @return the converted string, with platform line endings converted - * to \n - */ - public static final String readString(InputStream stream) throws IOException { - return readString(stream, UTF8); - } - - /** Convert an {@link InputStream} to a string; consistently uses \n line endings - * in java. This uses a default {@link Charset UTF-8} charset. - * - * @param stream the stream of bytes to convert - * @param charset the charset to use to convert the raw bytes - * @return the converted string, with platform line endings converted - * to \n - */ - public static final String readString(InputStream stream, String charset) throws IOException { - return readString(stream, Charset.forName(charset)); - } - - /** Convert an {@link InputStream} to a string; consistently uses \n line endings - * in java. This uses a default {@link Charset UTF-8} charset. - * - * @param stream the stream of bytes to convert - * @param charset the charset to use to convert the raw bytes - * @return the converted string, with platform line endings converted - * to \n - */ - public static final String readString(InputStream stream, Charset charset) throws IOException { - return readString(new InputStreamReader(new BufferedInputStream(stream), charset)); - } - - /** Convert an {@link Reader} to a string; consistently uses \n line endings - * in java. - * - * @param reader the stream of characters convert - * @return the converted string, with platform line endings converted - * to \n - */ - public static final String readString(Reader reader) throws IOException { - try { - StringBuilder sb = new StringBuilder(); - char[] buf = new char[4096]; - int r; - while ((r = reader.read(buf, 0, 4096)) > 0) { - sb.append(buf, 0, r); - } - return filterLineEndings(sb).toString(); - } finally { - try { - reader.close(); - } catch (IOException e) { - Debug.logError(e, "Error closing after reading text: " + e.toString(), module); - } - } - } - - private static StringBuilder filterLineEndings(StringBuilder sb) { - String nl = System.getProperty("line.separator"); - if (!nl.equals("\n")) { - int r = 0; - while (r < sb.length()) { - int i = sb.indexOf(nl, r); - if (i == -1) { - break; - } - sb.replace(i, i + nl.length(), "\n"); - r = i + 1; - } - } - return sb; - } - - /** Convert a \n string to a platform encoding. This uses a default - * {@link Charset UTF-8} charset. - * - * @param file where to write the converted bytes to - * @param value the value to write - */ - public static void writeString(File file, String value) throws IOException { - writeString(new FileOutputStream(file), UTF8, value); - } - - /** Convert a \n string to a platform encoding. This uses a default - * {@link Charset UTF-8} charset. - * - * @param out where to write the converted bytes to - * @param value the value to write - */ - public static void writeString(OutputStream out, String value) throws IOException { - writeString(out, UTF8, value); - } - - /** Convert a \n string to a platform encoding. This uses the - * specified charset to extract the raw bytes. - * - * @param out where to write the converted bytes to - * @param charset the charset to use to convert the raw bytes - * @param value the value to write - */ - public static void writeString(OutputStream out, String charset, String value) throws IOException { - writeString(out, Charset.forName(charset), value); - } - - /** Convert a \n string to a platform encoding. This uses the - * specified charset to extract the raw bytes. - * - * @param out where to write the converted bytes to - * @param charset the charset to use to convert the raw bytes - * @param value the value to write - */ - public static void writeString(OutputStream out, Charset charset, String value) throws IOException { - Writer writer = new OutputStreamWriter(out, charset); - String nl = System.getProperty("line.separator"); - int r = 0; - while (r < value.length()) { - int i = value.indexOf("\n", r); - if (i == -1) { - break; - } - writer.write(value.substring(r, i)); - writer.write(nl); - r = i + 1; - } - writer.write(value.substring(r)); - writer.close(); - } -} +/******************************************************************************* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + *******************************************************************************/ +package org.ofbiz.base.util; + +import java.io.BufferedInputStream; +import java.io.File; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.io.OutputStream; +import java.io.OutputStreamWriter; +import java.io.Reader; +import java.io.Writer; +import java.nio.ByteBuffer; +import java.nio.CharBuffer; +import java.nio.charset.Charset; + +import org.apache.commons.io.IOUtils; + +public final class UtilIO { + public static final Charset UTF8 = Charset.forName("UTF-8"); + public static final String module = UtilIO.class.getName(); + + /** Copy an InputStream to an OutputStream, optionally closing either + * the input or the output. + * + * @param in the InputStream to copy from + * @param closeIn whether to close the input when the copy is done + * @param out the OutputStream to copy to + * @param closeOut whether to close the output when the copy is done + * @throws IOException if an error occurs + */ + public static void copy(InputStream in, boolean closeIn, OutputStream out, boolean closeOut) throws IOException { + try { + try { + IOUtils.copy(in, out); + } finally { + if (closeIn) IOUtils.closeQuietly(in); + } + } finally { + if (closeOut) IOUtils.closeQuietly(out); + } + } + + /** Copy a Reader to a Writer, optionally closing either the input or + * the output. + * + * @param reader the Reader to copy from + * @param closeIn whether to close the input when the copy is done + * @param writer the Writer to copy to + * @param closeOut whether to close the output when the copy is done + * @throws IOException if an error occurs + */ + public static void copy(Reader reader, boolean closeIn, Writer writer, boolean closeOut) throws IOException { + try { + try { + IOUtils.copy(reader, writer); + } finally { + if (closeIn) IOUtils.closeQuietly(reader); + } + } finally { + if (closeOut) IOUtils.closeQuietly(writer); + } + } + + /** Copy a Reader to an Appendable, optionally closing the input. + * + * @param reader the Reader to copy from + * @param closeIn whether to close the input when the copy is done + * @param out the Appendable to copy to + * @throws IOException if an error occurs + */ + public static void copy(Reader reader, boolean closeIn, Appendable out) throws IOException { + try { + CharBuffer buffer = CharBuffer.allocate(4096); + while (reader.read(buffer) > 0) { + buffer.flip(); + buffer.rewind(); + out.append(buffer); + } + } finally { + if (closeIn) IOUtils.closeQuietly(reader); + } + } + + /** Convert a byte array to a string; consistently uses \n line endings + * in java. This uses a default {@link Charset UTF-8} charset. + * + * @param bytes the array of bytes to convert + * @return the converted string, with platform line endings converted + * to \n + */ + public static final String readString(byte[] bytes) throws IOException { + return readString(bytes, 0, bytes.length, UTF8); + } + + /** Convert a byte array to a string; consistently uses \n line endings + * in java. The conversion is limited to the specified offset/length + * pair, and uses a default {@link Charset UTF-8} charset. + * + * @param bytes the array of bytes to convert + * @param offset the start of the conversion + * @param length how many bytes to convert + * @return the converted string, with platform line endings converted + * to \n + */ + public static final String readString(byte[] bytes, int offset, int length) throws IOException { + return readString(bytes, offset, length, UTF8); + } + + /** Convert a byte array to a string; consistently uses \n line endings + * in java. The conversion is limited to the specified offset/length + * pair, and uses the requested charset to decode the bytes. + * + * @param bytes the array of bytes to convert + * @param charset the charset to use to convert the raw bytes + * @return the converted string, with platform line endings converted + * to \n + */ + public static final String readString(byte[] bytes, String charset) throws IOException { + return readString(bytes, 0, bytes.length, Charset.forName(charset)); + } + + /** Convert a byte array to a string; consistently uses \n line + * endings in java. The conversion is limited to the specified + * offset/length pair, and uses the requested charset to decode the + * bytes. + * + * @param bytes the array of bytes to convert + * @param offset the start of the conversion + * @param length how many bytes to convert + * @param charset the charset to use to convert the raw bytes + * @return the converted string, with platform line endings converted + * to \n + */ + public static final String readString(byte[] bytes, int offset, int length, String charset) throws IOException { + return readString(bytes, 0, bytes.length, Charset.forName(charset)); + } + + /** Convert a byte array to a string, consistently uses \n line + * endings in java. The specified {@link Charset charset} is used + * to decode the bytes. + * @param bytes the array of bytes to convert + * @param charset the charset to use to convert the raw bytes + * @return the converted string, with platform line endings converted + * to \n + */ + public static final String readString(byte[] bytes, Charset charset) throws IOException { + return readString(bytes, 0, bytes.length, charset); + } + + /** Convert a byte array to a string, consistently uses \n line + * endings in java. The conversion is limited to the specified + * offset/length pair, and uses the requested {@link Charset + * charset} to decode the bytes. + * + * @param bytes the array of bytes to convert + * @param offset the start of the conversion + * @param length how many bytes to convert + * @param charset the charset to use to convert the raw bytes + * @return the converted string, with platform line endings converted + * to \n + */ + public static final String readString(byte[] bytes, int offset, int length, Charset charset) throws IOException { + ByteBuffer buf = ByteBuffer.allocate(length); + buf.put(bytes, offset, length); + buf.flip(); + return filterLineEndings(new StringBuilder(charset.decode(buf).toString())).toString(); + } + + /** Convert an {@link InputStream} to a string; consistently uses \n line endings + * in java. This uses a default {@link Charset UTF-8} charset. + * + * @param stream the stream of bytes to convert + * @return the converted string, with platform line endings converted + * to \n + */ + public static final String readString(InputStream stream) throws IOException { + return readString(stream, UTF8); + } + + /** Convert an {@link InputStream} to a string; consistently uses \n line endings + * in java. This uses a default {@link Charset UTF-8} charset. + * + * @param stream the stream of bytes to convert + * @param charset the charset to use to convert the raw bytes + * @return the converted string, with platform line endings converted + * to \n + */ + public static final String readString(InputStream stream, String charset) throws IOException { + return readString(stream, Charset.forName(charset)); + } + + /** Convert an {@link InputStream} to a string; consistently uses \n line endings + * in java. This uses a default {@link Charset UTF-8} charset. + * + * @param stream the stream of bytes to convert + * @param charset the charset to use to convert the raw bytes + * @return the converted string, with platform line endings converted + * to \n + */ + public static final String readString(InputStream stream, Charset charset) throws IOException { + return readString(new InputStreamReader(new BufferedInputStream(stream), charset)); + } + + /** Convert an {@link Reader} to a string; consistently uses \n line endings + * in java. + * + * @param reader the stream of characters convert + * @return the converted string, with platform line endings converted + * to \n + */ + public static final String readString(Reader reader) throws IOException { + try { + StringBuilder sb = new StringBuilder(); + char[] buf = new char[4096]; + int r; + while ((r = reader.read(buf, 0, 4096)) > 0) { + sb.append(buf, 0, r); + } + return filterLineEndings(sb).toString(); + } finally { + try { + reader.close(); + } catch (IOException e) { + Debug.logError(e, "Error closing after reading text: " + e.toString(), module); + } + } + } + + private static StringBuilder filterLineEndings(StringBuilder sb) { + String nl = System.getProperty("line.separator"); + if (!nl.equals("\n")) { + int r = 0; + while (r < sb.length()) { + int i = sb.indexOf(nl, r); + if (i == -1) { + break; + } + sb.replace(i, i + nl.length(), "\n"); + r = i + 1; + } + } + return sb; + } + + /** Convert a \n string to a platform encoding. This uses a default + * {@link Charset UTF-8} charset. + * + * @param file where to write the converted bytes to + * @param value the value to write + */ + public static void writeString(File file, String value) throws IOException { + writeString(new FileOutputStream(file), UTF8, value); + } + + /** Convert a \n string to a platform encoding. This uses a default + * {@link Charset UTF-8} charset. + * + * @param out where to write the converted bytes to + * @param value the value to write + */ + public static void writeString(OutputStream out, String value) throws IOException { + writeString(out, UTF8, value); + } + + /** Convert a \n string to a platform encoding. This uses the + * specified charset to extract the raw bytes. + * + * @param out where to write the converted bytes to + * @param charset the charset to use to convert the raw bytes + * @param value the value to write + */ + public static void writeString(OutputStream out, String charset, String value) throws IOException { + writeString(out, Charset.forName(charset), value); + } + + /** Convert a \n string to a platform encoding. This uses the + * specified charset to extract the raw bytes. + * + * @param out where to write the converted bytes to + * @param charset the charset to use to convert the raw bytes + * @param value the value to write + */ + public static void writeString(OutputStream out, Charset charset, String value) throws IOException { + Writer writer = new OutputStreamWriter(out, charset); + String nl = System.getProperty("line.separator"); + int r = 0; + while (r < value.length()) { + int i = value.indexOf("\n", r); + if (i == -1) { + break; + } + writer.write(value.substring(r, i)); + writer.write(nl); + r = i + 1; + } + writer.write(value.substring(r)); + writer.close(); + } +} Propchange: ofbiz/trunk/framework/base/src/org/ofbiz/base/util/UtilIO.java ('svn:eol-style' removed) |
Free forum by Nabble | Edit this page |