Modified: ofbiz/trunk/framework/base/src/org/ofbiz/base/util/test/StringUtilTests.java
URL: http://svn.apache.org/viewvc/ofbiz/trunk/framework/base/src/org/ofbiz/base/util/test/StringUtilTests.java?rev=1695126&r1=1695125&r2=1695126&view=diff ============================================================================== --- ofbiz/trunk/framework/base/src/org/ofbiz/base/util/test/StringUtilTests.java (original) +++ ofbiz/trunk/framework/base/src/org/ofbiz/base/util/test/StringUtilTests.java Mon Aug 10 16:15:37 2015 @@ -1,327 +1,327 @@ -/******************************************************************************* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR 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.test; - -import java.util.Collections; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import org.ofbiz.base.lang.Appender; -import org.ofbiz.base.lang.SourceMonitored; -import org.ofbiz.base.util.GeneralRuntimeException; -import org.ofbiz.base.util.StringUtil; -import org.ofbiz.base.util.UtilGenerics; -import org.ofbiz.base.test.GenericTestCaseBase; - -@SourceMonitored -public class StringUtilTests extends GenericTestCaseBase { - public StringUtilTests(String name) { - super(name); - } - - @Override - protected void setUp() throws Exception { - super.setUp(); - } - - @Override - protected void tearDown() throws Exception { - super.tearDown(); - } - - public void testStringUtil() throws Exception { - assertStaticHelperClass(StringUtil.class); - assertTrue("correct INSTANCE", StringUtil.INSTANCE instanceof StringUtil); - } - - public void testInternString() { - assertSame("intern-constant", StringUtil.internString("foo"), StringUtil.internString("foo")); - assertSame("intern-new", StringUtil.internString("foo"), StringUtil.internString(new String("foo"))); - assertSame("intern-char", StringUtil.internString("foo"), StringUtil.internString(new String(new char[] {'f', 'o', 'o'}))); - assertSame("intern-null", StringUtil.internString(null), StringUtil.internString(null)); - } - - public void testReplaceString() { - assertNull("null", StringUtil.replaceString(null, "old", "new")); - assertEquals("empty old", "the old dog jumped over the old fence", StringUtil.replaceString("the old dog jumped over the old fence", "", "new")); - assertEquals("replace", "the new dog jumped over the new fence", StringUtil.replaceString("the old dog jumped over the old fence", "old", "new")); - assertEquals("replace-null", "the dog jumped over the fence", StringUtil.replaceString("the old dog jumped over the old fence", "old", null)); - assertEquals("replace-not-found", "the old dog jumped over the old fence", StringUtil.replaceString("the old dog jumped over the old fence", "cat", "feline")); - } - - public void testJoin() { - assertNull("null-list", StringUtil.join(null, ",")); - assertNull("empty-list", StringUtil.join(Collections.emptyList(), ",")); - assertEquals("single", "1", StringUtil.join(list("1"), ",")); - assertEquals("double", "1,2", StringUtil.join(list("1", "2"), ",")); - } - - public void testSplit() { - assertNull("null-string", StringUtil.split(null, ",")); - assertEquals("single", list("1"), StringUtil.split("1", ",")); - assertEquals("double", list("1", "2"), StringUtil.split("1,2", ",")); - assertEquals("no-sep", list("1", "2", "3", "4", "5", "6"), StringUtil.split("1 2\t3\n4\r5\f6", null)); - } - - public void testQuoteStrList() { - assertEquals("single", list("'1'"), StringUtil.quoteStrList(list("1"))); - assertEquals("double", list("'1'", "'2'"), StringUtil.quoteStrList(list("1", "2"))); - } - - public void testStrToMap() { - assertNull("null-string", StringUtil.strToMap(null, false)); - //assertEquals("empty", Collections.emptyMap(), StringUtil.strToMap("", false)); - assertEquals("missing =", Collections.emptyMap(), StringUtil.strToMap("1", false)); - assertEquals("single", map("1", "one"), StringUtil.strToMap("1=one")); - assertEquals("double", map("2", "two", "1", "one"), StringUtil.strToMap("1=one|2=two")); - assertEquals("double-no-trim", map(" 2 ", " two ", " 1 ", " one "), StringUtil.strToMap(" 1 = one | 2 = two ")); - assertEquals("double-trim", map("2", "two", "1", "one"), StringUtil.strToMap(" 1 = one | 2 = two ", true)); - } - - public void testMapToStr() { - assertNull("null-map", StringUtil.mapToStr(null)); - assertEquals("empty", "", StringUtil.mapToStr(Collections.emptyMap())); - assertEquals("single", "1=one", StringUtil.mapToStr(map("1", "one"))); - assertEquals("double", "1=one|2=two", StringUtil.mapToStr(map("1", "one", "2", "two"))); - assertEquals("double-with-non-string", "1=one|2=two", StringUtil.mapToStr(map("a", this, "1", "one", "2", "two", this, "a"))); - } - - public void testToMap() { - for (String s: new String[] {"", "{", "}", "}{"}) { - IllegalArgumentException caught = null; - try { - StringUtil.toMap(s); - } catch (IllegalArgumentException e) { - caught = e; - } finally { - assertNotNull("bad(" + s + ")", caught); - } - } - //assertEquals("empty", Collections.emptyMap(), StringUtil.toMap("{}")); - assertEquals("single", map("1", "one"), StringUtil.toMap("{1=one}")); - assertEquals("double", map("2", "two", "1", "one"), StringUtil.toMap("{1=one, 2=two}")); - assertEquals("double-space", map("2", "two ", " 1", "one"), StringUtil.toMap("{ 1=one, 2=two }")); - } - - public void testToList() { - for (String s: new String[] {"", "[", "]", "]["}) { - IllegalArgumentException caught = null; - try { - StringUtil.toList(s); - } catch (IllegalArgumentException e) { - caught = e; - } finally { - assertNotNull("bad(" + s + ")", caught); - } - } - //assertEquals("empty", Collections.emptyList(), StringUtil.toList("[]")); - assertEquals("single", list("1"), StringUtil.toList("[1]")); - assertEquals("double", list("1", "2"), StringUtil.toList("[1, 2]")); - assertEquals("double-space", list(" 1", "2 "), StringUtil.toList("[ 1, 2 ]")); - } - - public void testToSet() { - for (String s: new String[] {"", "[", "]", "]["}) { - IllegalArgumentException caught = null; - try { - StringUtil.toSet(s); - } catch (IllegalArgumentException e) { - caught = e; - } finally { - assertNotNull("bad(" + s + ")", caught); - } - } - //assertEquals("empty", Collections.emptySet(), StringUtil.toSet("[]")); - assertEquals("single", set("1"), StringUtil.toSet("[1]")); - assertEquals("double", set("1", "2"), StringUtil.toSet("[1, 2]")); - assertEquals("double-space", set(" 1", "2 "), StringUtil.toSet("[ 1, 2 ]")); - } - - public void testCreateMap() { - List<String>[] badKeys = UtilGenerics.cast(new List[] {null, list("1"), list("2")}); - List<String>[] badValues = UtilGenerics.cast(new List[] {list("one"), null, list("two", "extra")}); - for (int i = 0; i < badKeys.length; i++) { - IllegalArgumentException caught = null; - try { - StringUtil.createMap(badKeys[i], badValues[i]); - } catch (IllegalArgumentException e) { - caught = e; - } finally { - assertNotNull("bad(" + i + ")", caught); - } - } - assertEquals("parse", map("1", "one", "2", "two"), StringUtil.createMap(list("1", "2"), list("one", "two"))); - } - - public void testCleanUpPathPrefix() { - assertEquals("null", "", StringUtil.cleanUpPathPrefix(null)); - assertEquals("empty", "", StringUtil.cleanUpPathPrefix("")); - for (String s: new String[] {"\\a\\b\\c", "\\a\\b\\c\\", "a\\b\\c\\", "a\\b\\c", "/a/b/c", "/a/b/c/", "a/b/c/", "a/b/c"}) { - assertEquals("cleanup(" + s + ")", "/a/b/c", StringUtil.cleanUpPathPrefix(s)); - } - } - - public void testRemoveSpaces() { - assertEquals("", StringUtil.removeSpaces("")); - assertEquals("abcd", StringUtil.removeSpaces(" a b c d ")); - assertEquals("a\\cd", StringUtil.removeSpaces(" a \\ c d ")); - } - - public void testToHexString() { - assertEquals("16 bytes", "000102030405060708090a0b0c0d0e0f", StringUtil.toHexString(new byte[] {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15})); - } - - public void testCleanHexString() { - assertEquals("clean hex", "rtwertetwretw", StringUtil.cleanHexString("rtwer:tetw retw")); - } - - public void testFromHexString() { - assertEquals("16 bytes", new byte[] {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15}, StringUtil.fromHexString("000102030405060708090a0b0c0d0e0f")); - GeneralRuntimeException caught = null; - try { - StringUtil.fromHexString("0-"); - } catch (GeneralRuntimeException e) { - caught = e; - } finally { - assertNotNull("bad-char", caught); - } - } - - public void testConvertChar() { - Map<Character, Integer> conversions = new HashMap<Character, Integer>(); - conversions.put('0', 0); conversions.put('1', 1); conversions.put('2', 2); conversions.put('3', 3); - conversions.put('4', 4); conversions.put('5', 5); conversions.put('6', 6); conversions.put('7', 7); - conversions.put('8', 8); conversions.put('9', 9); - conversions.put('a', 10); conversions.put('b', 11); conversions.put('c', 12); - conversions.put('d', 13); conversions.put('e', 14); conversions.put('f', 15); - conversions.put('A', 10); conversions.put('B', 11); conversions.put('C', 12); - conversions.put('D', 13); conversions.put('E', 14); conversions.put('F', 15); - for (int i = 0; i < 256; i++) { - Integer wanted = conversions.get((char) i); - if (wanted == null) { - Exception caught = null; - try { - StringUtil.convertChar((char) i); - } catch (Exception e) { - caught = e; - } finally { - assertNotNull(Integer.toString(i), caught); - } - } else { - assertEquals(Integer.toString(i), wanted.intValue(), StringUtil.convertChar((char) i)); - } - } - } - - public void testEncodeInt() { - assertEquals("one octet", new char[] {'0', '5'}, StringUtil.encodeInt(5, 0, new char[2])); - assertEquals("two octets", new char[] {'1', '5'}, StringUtil.encodeInt(21, 0, new char[2])); - // these next two are really weird, note the start offset being != 0. - assertEquals("three octets", new char[] {'3', '1', '5'}, StringUtil.encodeInt(789, 1, new char[3])); - assertEquals("four octets", new char[] {'7', '3', '1', '5'}, StringUtil.encodeInt(29461, 2, new char[4])); - } - - public void testRemoveNonNumeric() { - assertEquals("just numbers", "12345", StringUtil.removeNonNumeric("a1'2;3]4!5(")); - } - - public void testRemoveNumeric() { - assertEquals("only numbers", "a';]!(", StringUtil.removeNumeric("a1'2;3]4!5(")); - } - - public void testRemoveRegex() { - } - - public void testAddToNumberString() { - assertNull("null pass-thru", StringUtil.addToNumberString(null, 0)); - assertEquals("no-change", "12345", StringUtil.addToNumberString("12345", 0)); - assertEquals("increase", "112344", StringUtil.addToNumberString("12345", 99999)); - assertEquals("subtract", "00345", StringUtil.addToNumberString("12345", -12000)); - } - - public void testPadNumberString() { - assertEquals("less", "12345", StringUtil.padNumberString("12345", 3)); - assertEquals("same", "12345", StringUtil.padNumberString("12345", 5)); - assertEquals("more", "00012345", StringUtil.padNumberString("12345", 8)); - } - - public void testConvertOperatorSubstitutions() { - assertNull("null pass-thru", StringUtil.convertOperatorSubstitutions(null)); - assertEquals("none", "abc", StringUtil.convertOperatorSubstitutions("abc")); - assertEquals("none", "a'c", StringUtil.convertOperatorSubstitutions("a'c")); - assertEquals("all converions", "one && two || three > four >= five < six <= seven", StringUtil.convertOperatorSubstitutions("one @and two @or three @gt four @gteq five @lt six @lteq seven")); - } - - public void testCollapseNewlines() { - } - - public void testCollapseSpaces() { - } - - public void testCollapseCharacter() { - assertEquals("not-found", "abcdefg", StringUtil.collapseCharacter("abcdefg", '.')); - assertEquals("no-change", "abcdefg", StringUtil.collapseCharacter("abcdefg", 'a')); - assertEquals("duplicate", "abcdefa", StringUtil.collapseCharacter("aabcdefaa", 'a')); - } - - public void testWrapString() { - } - - public void testMakeStringWrapper() { - } - - protected static final class TestAppender implements Appender<StringBuilder> { - private final String s; - - protected TestAppender(String s) { - this.s = s; - } - - public StringBuilder appendTo(StringBuilder sb) { - return sb.append(s); - } - } - - public void testAppendTo() { - assertEquals("111", "[1],[2]", StringUtil.appendTo(new StringBuilder(), list(new TestAppender("1"), new TestAppender("2")), "[", "]", ",").toString()); - assertEquals("011", "1],2]", StringUtil.appendTo(new StringBuilder(), list(new TestAppender("1"), new TestAppender("2")), null, "]", ",").toString()); - assertEquals("101", "[1,[2", StringUtil.appendTo(new StringBuilder(), list(new TestAppender("1"), new TestAppender("2")), "[", null, ",").toString()); - assertEquals("110", "[1][2]", StringUtil.appendTo(new StringBuilder(), list(new TestAppender("1"), new TestAppender("2")), "[", "]", null).toString()); - assertEquals("11111", "[1]<,>[2]", StringUtil.appendTo(new StringBuilder(), list(new TestAppender("1"), new TestAppender("2")), "[", "]", "<", ",", ">").toString()); - assertEquals("01111", "1]<,>2]", StringUtil.appendTo(new StringBuilder(), list(new TestAppender("1"), new TestAppender("2")), null, "]", "<", ",", ">").toString()); - assertEquals("10111", "[1<,>[2", StringUtil.appendTo(new StringBuilder(), list(new TestAppender("1"), new TestAppender("2")), "[", null, "<", ",", ">").toString()); - assertEquals("11011", "[1],>[2]", StringUtil.appendTo(new StringBuilder(), list(new TestAppender("1"), new TestAppender("2")), "[", "]", null, ",", ">").toString()); - assertEquals("11101", "[1][2]", StringUtil.appendTo(new StringBuilder(), list(new TestAppender("1"), new TestAppender("2")), "[", "]", "<", null, ">").toString()); - assertEquals("11110", "[1]<,[2]", StringUtil.appendTo(new StringBuilder(), list(new TestAppender("1"), new TestAppender("2")), "[", "]", "<", ",", null).toString()); - } - - public void testAppend() { - assertEquals("111", "[1],[2]", StringUtil.append(new StringBuilder(), list("1", "2"), "[", "]", ",").toString()); - assertEquals("011", "1],2]", StringUtil.append(new StringBuilder(), list("1", "2"), null, "]", ",").toString()); - assertEquals("101", "[1,[2", StringUtil.append(new StringBuilder(), list("1", "2"), "[", null, ",").toString()); - assertEquals("110", "[1][2]", StringUtil.append(new StringBuilder(), list("1", "2"), "[", "]", null).toString()); - assertEquals("11111", "[1]<,>[2]", StringUtil.append(new StringBuilder(), list("1", "2"), "[", "]", "<", ",", ">").toString()); - assertEquals("01111", "1]<,>2]", StringUtil.append(new StringBuilder(), list("1", "2"), null, "]", "<", ",", ">").toString()); - assertEquals("10111", "[1<,>[2", StringUtil.append(new StringBuilder(), list("1", "2"), "[", null, "<", ",", ">").toString()); - assertEquals("11011", "[1],>[2]", StringUtil.append(new StringBuilder(), list("1", "2"), "[", "]", null, ",", ">").toString()); - assertEquals("11101", "[1][2]", StringUtil.append(new StringBuilder(), list("1", "2"), "[", "]", "<", null, ">").toString()); - assertEquals("11110", "[1]<,[2]", StringUtil.append(new StringBuilder(), list("1", "2"), "[", "]", "<", ",", null).toString()); - } -} +/******************************************************************************* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR 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.test; + +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.ofbiz.base.lang.Appender; +import org.ofbiz.base.lang.SourceMonitored; +import org.ofbiz.base.util.GeneralRuntimeException; +import org.ofbiz.base.util.StringUtil; +import org.ofbiz.base.util.UtilGenerics; +import org.ofbiz.base.test.GenericTestCaseBase; + +@SourceMonitored +public class StringUtilTests extends GenericTestCaseBase { + public StringUtilTests(String name) { + super(name); + } + + @Override + protected void setUp() throws Exception { + super.setUp(); + } + + @Override + protected void tearDown() throws Exception { + super.tearDown(); + } + + public void testStringUtil() throws Exception { + assertStaticHelperClass(StringUtil.class); + assertTrue("correct INSTANCE", StringUtil.INSTANCE instanceof StringUtil); + } + + public void testInternString() { + assertSame("intern-constant", StringUtil.internString("foo"), StringUtil.internString("foo")); + assertSame("intern-new", StringUtil.internString("foo"), StringUtil.internString(new String("foo"))); + assertSame("intern-char", StringUtil.internString("foo"), StringUtil.internString(new String(new char[] {'f', 'o', 'o'}))); + assertSame("intern-null", StringUtil.internString(null), StringUtil.internString(null)); + } + + public void testReplaceString() { + assertNull("null", StringUtil.replaceString(null, "old", "new")); + assertEquals("empty old", "the old dog jumped over the old fence", StringUtil.replaceString("the old dog jumped over the old fence", "", "new")); + assertEquals("replace", "the new dog jumped over the new fence", StringUtil.replaceString("the old dog jumped over the old fence", "old", "new")); + assertEquals("replace-null", "the dog jumped over the fence", StringUtil.replaceString("the old dog jumped over the old fence", "old", null)); + assertEquals("replace-not-found", "the old dog jumped over the old fence", StringUtil.replaceString("the old dog jumped over the old fence", "cat", "feline")); + } + + public void testJoin() { + assertNull("null-list", StringUtil.join(null, ",")); + assertNull("empty-list", StringUtil.join(Collections.emptyList(), ",")); + assertEquals("single", "1", StringUtil.join(list("1"), ",")); + assertEquals("double", "1,2", StringUtil.join(list("1", "2"), ",")); + } + + public void testSplit() { + assertNull("null-string", StringUtil.split(null, ",")); + assertEquals("single", list("1"), StringUtil.split("1", ",")); + assertEquals("double", list("1", "2"), StringUtil.split("1,2", ",")); + assertEquals("no-sep", list("1", "2", "3", "4", "5", "6"), StringUtil.split("1 2\t3\n4\r5\f6", null)); + } + + public void testQuoteStrList() { + assertEquals("single", list("'1'"), StringUtil.quoteStrList(list("1"))); + assertEquals("double", list("'1'", "'2'"), StringUtil.quoteStrList(list("1", "2"))); + } + + public void testStrToMap() { + assertNull("null-string", StringUtil.strToMap(null, false)); + //assertEquals("empty", Collections.emptyMap(), StringUtil.strToMap("", false)); + assertEquals("missing =", Collections.emptyMap(), StringUtil.strToMap("1", false)); + assertEquals("single", map("1", "one"), StringUtil.strToMap("1=one")); + assertEquals("double", map("2", "two", "1", "one"), StringUtil.strToMap("1=one|2=two")); + assertEquals("double-no-trim", map(" 2 ", " two ", " 1 ", " one "), StringUtil.strToMap(" 1 = one | 2 = two ")); + assertEquals("double-trim", map("2", "two", "1", "one"), StringUtil.strToMap(" 1 = one | 2 = two ", true)); + } + + public void testMapToStr() { + assertNull("null-map", StringUtil.mapToStr(null)); + assertEquals("empty", "", StringUtil.mapToStr(Collections.emptyMap())); + assertEquals("single", "1=one", StringUtil.mapToStr(map("1", "one"))); + assertEquals("double", "1=one|2=two", StringUtil.mapToStr(map("1", "one", "2", "two"))); + assertEquals("double-with-non-string", "1=one|2=two", StringUtil.mapToStr(map("a", this, "1", "one", "2", "two", this, "a"))); + } + + public void testToMap() { + for (String s: new String[] {"", "{", "}", "}{"}) { + IllegalArgumentException caught = null; + try { + StringUtil.toMap(s); + } catch (IllegalArgumentException e) { + caught = e; + } finally { + assertNotNull("bad(" + s + ")", caught); + } + } + //assertEquals("empty", Collections.emptyMap(), StringUtil.toMap("{}")); + assertEquals("single", map("1", "one"), StringUtil.toMap("{1=one}")); + assertEquals("double", map("2", "two", "1", "one"), StringUtil.toMap("{1=one, 2=two}")); + assertEquals("double-space", map("2", "two ", " 1", "one"), StringUtil.toMap("{ 1=one, 2=two }")); + } + + public void testToList() { + for (String s: new String[] {"", "[", "]", "]["}) { + IllegalArgumentException caught = null; + try { + StringUtil.toList(s); + } catch (IllegalArgumentException e) { + caught = e; + } finally { + assertNotNull("bad(" + s + ")", caught); + } + } + //assertEquals("empty", Collections.emptyList(), StringUtil.toList("[]")); + assertEquals("single", list("1"), StringUtil.toList("[1]")); + assertEquals("double", list("1", "2"), StringUtil.toList("[1, 2]")); + assertEquals("double-space", list(" 1", "2 "), StringUtil.toList("[ 1, 2 ]")); + } + + public void testToSet() { + for (String s: new String[] {"", "[", "]", "]["}) { + IllegalArgumentException caught = null; + try { + StringUtil.toSet(s); + } catch (IllegalArgumentException e) { + caught = e; + } finally { + assertNotNull("bad(" + s + ")", caught); + } + } + //assertEquals("empty", Collections.emptySet(), StringUtil.toSet("[]")); + assertEquals("single", set("1"), StringUtil.toSet("[1]")); + assertEquals("double", set("1", "2"), StringUtil.toSet("[1, 2]")); + assertEquals("double-space", set(" 1", "2 "), StringUtil.toSet("[ 1, 2 ]")); + } + + public void testCreateMap() { + List<String>[] badKeys = UtilGenerics.cast(new List[] {null, list("1"), list("2")}); + List<String>[] badValues = UtilGenerics.cast(new List[] {list("one"), null, list("two", "extra")}); + for (int i = 0; i < badKeys.length; i++) { + IllegalArgumentException caught = null; + try { + StringUtil.createMap(badKeys[i], badValues[i]); + } catch (IllegalArgumentException e) { + caught = e; + } finally { + assertNotNull("bad(" + i + ")", caught); + } + } + assertEquals("parse", map("1", "one", "2", "two"), StringUtil.createMap(list("1", "2"), list("one", "two"))); + } + + public void testCleanUpPathPrefix() { + assertEquals("null", "", StringUtil.cleanUpPathPrefix(null)); + assertEquals("empty", "", StringUtil.cleanUpPathPrefix("")); + for (String s: new String[] {"\\a\\b\\c", "\\a\\b\\c\\", "a\\b\\c\\", "a\\b\\c", "/a/b/c", "/a/b/c/", "a/b/c/", "a/b/c"}) { + assertEquals("cleanup(" + s + ")", "/a/b/c", StringUtil.cleanUpPathPrefix(s)); + } + } + + public void testRemoveSpaces() { + assertEquals("", StringUtil.removeSpaces("")); + assertEquals("abcd", StringUtil.removeSpaces(" a b c d ")); + assertEquals("a\\cd", StringUtil.removeSpaces(" a \\ c d ")); + } + + public void testToHexString() { + assertEquals("16 bytes", "000102030405060708090a0b0c0d0e0f", StringUtil.toHexString(new byte[] {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15})); + } + + public void testCleanHexString() { + assertEquals("clean hex", "rtwertetwretw", StringUtil.cleanHexString("rtwer:tetw retw")); + } + + public void testFromHexString() { + assertEquals("16 bytes", new byte[] {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15}, StringUtil.fromHexString("000102030405060708090a0b0c0d0e0f")); + GeneralRuntimeException caught = null; + try { + StringUtil.fromHexString("0-"); + } catch (GeneralRuntimeException e) { + caught = e; + } finally { + assertNotNull("bad-char", caught); + } + } + + public void testConvertChar() { + Map<Character, Integer> conversions = new HashMap<Character, Integer>(); + conversions.put('0', 0); conversions.put('1', 1); conversions.put('2', 2); conversions.put('3', 3); + conversions.put('4', 4); conversions.put('5', 5); conversions.put('6', 6); conversions.put('7', 7); + conversions.put('8', 8); conversions.put('9', 9); + conversions.put('a', 10); conversions.put('b', 11); conversions.put('c', 12); + conversions.put('d', 13); conversions.put('e', 14); conversions.put('f', 15); + conversions.put('A', 10); conversions.put('B', 11); conversions.put('C', 12); + conversions.put('D', 13); conversions.put('E', 14); conversions.put('F', 15); + for (int i = 0; i < 256; i++) { + Integer wanted = conversions.get((char) i); + if (wanted == null) { + Exception caught = null; + try { + StringUtil.convertChar((char) i); + } catch (Exception e) { + caught = e; + } finally { + assertNotNull(Integer.toString(i), caught); + } + } else { + assertEquals(Integer.toString(i), wanted.intValue(), StringUtil.convertChar((char) i)); + } + } + } + + public void testEncodeInt() { + assertEquals("one octet", new char[] {'0', '5'}, StringUtil.encodeInt(5, 0, new char[2])); + assertEquals("two octets", new char[] {'1', '5'}, StringUtil.encodeInt(21, 0, new char[2])); + // these next two are really weird, note the start offset being != 0. + assertEquals("three octets", new char[] {'3', '1', '5'}, StringUtil.encodeInt(789, 1, new char[3])); + assertEquals("four octets", new char[] {'7', '3', '1', '5'}, StringUtil.encodeInt(29461, 2, new char[4])); + } + + public void testRemoveNonNumeric() { + assertEquals("just numbers", "12345", StringUtil.removeNonNumeric("a1'2;3]4!5(")); + } + + public void testRemoveNumeric() { + assertEquals("only numbers", "a';]!(", StringUtil.removeNumeric("a1'2;3]4!5(")); + } + + public void testRemoveRegex() { + } + + public void testAddToNumberString() { + assertNull("null pass-thru", StringUtil.addToNumberString(null, 0)); + assertEquals("no-change", "12345", StringUtil.addToNumberString("12345", 0)); + assertEquals("increase", "112344", StringUtil.addToNumberString("12345", 99999)); + assertEquals("subtract", "00345", StringUtil.addToNumberString("12345", -12000)); + } + + public void testPadNumberString() { + assertEquals("less", "12345", StringUtil.padNumberString("12345", 3)); + assertEquals("same", "12345", StringUtil.padNumberString("12345", 5)); + assertEquals("more", "00012345", StringUtil.padNumberString("12345", 8)); + } + + public void testConvertOperatorSubstitutions() { + assertNull("null pass-thru", StringUtil.convertOperatorSubstitutions(null)); + assertEquals("none", "abc", StringUtil.convertOperatorSubstitutions("abc")); + assertEquals("none", "a'c", StringUtil.convertOperatorSubstitutions("a'c")); + assertEquals("all converions", "one && two || three > four >= five < six <= seven", StringUtil.convertOperatorSubstitutions("one @and two @or three @gt four @gteq five @lt six @lteq seven")); + } + + public void testCollapseNewlines() { + } + + public void testCollapseSpaces() { + } + + public void testCollapseCharacter() { + assertEquals("not-found", "abcdefg", StringUtil.collapseCharacter("abcdefg", '.')); + assertEquals("no-change", "abcdefg", StringUtil.collapseCharacter("abcdefg", 'a')); + assertEquals("duplicate", "abcdefa", StringUtil.collapseCharacter("aabcdefaa", 'a')); + } + + public void testWrapString() { + } + + public void testMakeStringWrapper() { + } + + protected static final class TestAppender implements Appender<StringBuilder> { + private final String s; + + protected TestAppender(String s) { + this.s = s; + } + + public StringBuilder appendTo(StringBuilder sb) { + return sb.append(s); + } + } + + public void testAppendTo() { + assertEquals("111", "[1],[2]", StringUtil.appendTo(new StringBuilder(), list(new TestAppender("1"), new TestAppender("2")), "[", "]", ",").toString()); + assertEquals("011", "1],2]", StringUtil.appendTo(new StringBuilder(), list(new TestAppender("1"), new TestAppender("2")), null, "]", ",").toString()); + assertEquals("101", "[1,[2", StringUtil.appendTo(new StringBuilder(), list(new TestAppender("1"), new TestAppender("2")), "[", null, ",").toString()); + assertEquals("110", "[1][2]", StringUtil.appendTo(new StringBuilder(), list(new TestAppender("1"), new TestAppender("2")), "[", "]", null).toString()); + assertEquals("11111", "[1]<,>[2]", StringUtil.appendTo(new StringBuilder(), list(new TestAppender("1"), new TestAppender("2")), "[", "]", "<", ",", ">").toString()); + assertEquals("01111", "1]<,>2]", StringUtil.appendTo(new StringBuilder(), list(new TestAppender("1"), new TestAppender("2")), null, "]", "<", ",", ">").toString()); + assertEquals("10111", "[1<,>[2", StringUtil.appendTo(new StringBuilder(), list(new TestAppender("1"), new TestAppender("2")), "[", null, "<", ",", ">").toString()); + assertEquals("11011", "[1],>[2]", StringUtil.appendTo(new StringBuilder(), list(new TestAppender("1"), new TestAppender("2")), "[", "]", null, ",", ">").toString()); + assertEquals("11101", "[1][2]", StringUtil.appendTo(new StringBuilder(), list(new TestAppender("1"), new TestAppender("2")), "[", "]", "<", null, ">").toString()); + assertEquals("11110", "[1]<,[2]", StringUtil.appendTo(new StringBuilder(), list(new TestAppender("1"), new TestAppender("2")), "[", "]", "<", ",", null).toString()); + } + + public void testAppend() { + assertEquals("111", "[1],[2]", StringUtil.append(new StringBuilder(), list("1", "2"), "[", "]", ",").toString()); + assertEquals("011", "1],2]", StringUtil.append(new StringBuilder(), list("1", "2"), null, "]", ",").toString()); + assertEquals("101", "[1,[2", StringUtil.append(new StringBuilder(), list("1", "2"), "[", null, ",").toString()); + assertEquals("110", "[1][2]", StringUtil.append(new StringBuilder(), list("1", "2"), "[", "]", null).toString()); + assertEquals("11111", "[1]<,>[2]", StringUtil.append(new StringBuilder(), list("1", "2"), "[", "]", "<", ",", ">").toString()); + assertEquals("01111", "1]<,>2]", StringUtil.append(new StringBuilder(), list("1", "2"), null, "]", "<", ",", ">").toString()); + assertEquals("10111", "[1<,>[2", StringUtil.append(new StringBuilder(), list("1", "2"), "[", null, "<", ",", ">").toString()); + assertEquals("11011", "[1],>[2]", StringUtil.append(new StringBuilder(), list("1", "2"), "[", "]", null, ",", ">").toString()); + assertEquals("11101", "[1][2]", StringUtil.append(new StringBuilder(), list("1", "2"), "[", "]", "<", null, ">").toString()); + assertEquals("11110", "[1]<,[2]", StringUtil.append(new StringBuilder(), list("1", "2"), "[", "]", "<", ",", null).toString()); + } +} Propchange: ofbiz/trunk/framework/base/src/org/ofbiz/base/util/test/StringUtilTests.java ('svn:eol-style' removed) Modified: ofbiz/trunk/framework/base/src/org/ofbiz/base/util/test/UtilIOTests.java URL: http://svn.apache.org/viewvc/ofbiz/trunk/framework/base/src/org/ofbiz/base/util/test/UtilIOTests.java?rev=1695126&r1=1695125&r2=1695126&view=diff ============================================================================== --- ofbiz/trunk/framework/base/src/org/ofbiz/base/util/test/UtilIOTests.java (original) +++ ofbiz/trunk/framework/base/src/org/ofbiz/base/util/test/UtilIOTests.java Mon Aug 10 16:15:37 2015 @@ -1,121 +1,121 @@ -/******************************************************************************* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR 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.test; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.IOException; - -import org.ofbiz.base.lang.SourceMonitored; -import org.ofbiz.base.test.GenericTestCaseBase; -import org.ofbiz.base.util.UtilIO; - -@SourceMonitored -public class UtilIOTests extends GenericTestCaseBase { - private static final byte[] trademarkBytes = new byte[] { - (byte) 0xE2, (byte) 0x84, (byte) 0xA2 - }; - public UtilIOTests(String name) { - super(name); - } - - @Override - protected void setUp() throws Exception { - super.setUp(); - } - - @Override - protected void tearDown() throws Exception { - super.tearDown(); - } - - public void testReadString() throws Exception { - readStringTest_0("unix line ending", "\n", new byte[] { 0x0A }); - readStringTest_0("mac line ending", "\r", new byte[] { 0x0D }); - readStringTest_0("windows line ending", "\r\n", new byte[] { 0x0D, 0x0A }); - } - - private static byte[] join(byte[]... parts) { - int count = 0; - for (byte[] part: parts) { - count += part.length; - } - byte[] result = new byte[count]; - int i = 0; - for (byte[] part: parts) { - System.arraycopy(part, 0, result, i, part.length); - i += part.length; - } - return result; - } - - private static void readStringTest_0(String label, String lineSeparator, byte[] extra) throws IOException { - String originalLineSeparator = System.getProperty("line.separator"); - try { - System.getProperties().put("line.separator", lineSeparator); - readStringTest_1(label + ":mark", "\u2122", join(trademarkBytes)); - readStringTest_1(label + ":mark NL", "\u2122\n", join(trademarkBytes, extra)); - readStringTest_1(label + ":NL mark", "\n\u2122", join(extra, trademarkBytes)); - } finally { - System.getProperties().put("line.separator", originalLineSeparator); - } - } - - private static void readStringTest_1(String label, String wanted, byte[] toRead) throws IOException { - assertEquals("readString bytes default:" + label, wanted, UtilIO.readString(toRead)); - assertEquals("readString bytes UTF-8:" + label, wanted, UtilIO.readString(toRead, "UTF-8")); - assertEquals("readString bytes UTF8:" + label, wanted, UtilIO.readString(toRead, UtilIO.UTF8)); - assertEquals("readString bytes offset/length default:" + label, wanted, UtilIO.readString(toRead, 0, toRead.length)); - assertEquals("readString bytes offset/length UTF-8:" + label, wanted, UtilIO.readString(toRead, 0, toRead.length, "UTF-8")); - assertEquals("readString bytes offset/length UTF8:" + label, wanted, UtilIO.readString(toRead, 0, toRead.length, UtilIO.UTF8)); - assertEquals("readString stream default:" + label, wanted, UtilIO.readString(new ByteArrayInputStream(toRead))); - assertEquals("readString stream UTF-8:" + label, wanted, UtilIO.readString(new ByteArrayInputStream(toRead), "UTF-8")); - assertEquals("readString stream UTF8:" + label, wanted, UtilIO.readString(new ByteArrayInputStream(toRead), UtilIO.UTF8)); - } - - public void testWriteString() throws Exception { - writeStringTest_0("unix line ending", "\n", new byte[] { 0x0A }); - writeStringTest_0("mac line ending", "\r", new byte[] { 0x0D }); - writeStringTest_0("windows line ending", "\r\n", new byte[] { 0x0D, 0x0A }); - } - - private static void writeStringTest_0(String label, String lineSeparator, byte[] extra) throws IOException { - String originalLineSeparator = System.getProperty("line.separator"); - try { - System.getProperties().put("line.separator", lineSeparator); - writeStringTest_1(label + ":mark", join(trademarkBytes), "\u2122"); - writeStringTest_1(label + ":mark NL", join(trademarkBytes, extra), "\u2122\n"); - writeStringTest_1(label + ":NL mark", join(extra, trademarkBytes), "\n\u2122"); - } finally { - System.getProperties().put("line.separator", originalLineSeparator); - } - } - - private static void writeStringTest_1(String label, byte[] wanted, String toWrite) throws IOException { - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - UtilIO.writeString(baos, toWrite); - assertEquals("writeString default:" + label, wanted, baos.toByteArray()); - baos = new ByteArrayOutputStream(); - UtilIO.writeString(baos, "UTF-8", toWrite); - assertEquals("writeString UTF-8:" + label, wanted, baos.toByteArray()); - baos = new ByteArrayOutputStream(); - UtilIO.writeString(baos, UtilIO.UTF8, toWrite); - assertEquals("writeString UTF8:" + label, wanted, baos.toByteArray()); - } -} +/******************************************************************************* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR 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.test; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; + +import org.ofbiz.base.lang.SourceMonitored; +import org.ofbiz.base.test.GenericTestCaseBase; +import org.ofbiz.base.util.UtilIO; + +@SourceMonitored +public class UtilIOTests extends GenericTestCaseBase { + private static final byte[] trademarkBytes = new byte[] { + (byte) 0xE2, (byte) 0x84, (byte) 0xA2 + }; + public UtilIOTests(String name) { + super(name); + } + + @Override + protected void setUp() throws Exception { + super.setUp(); + } + + @Override + protected void tearDown() throws Exception { + super.tearDown(); + } + + public void testReadString() throws Exception { + readStringTest_0("unix line ending", "\n", new byte[] { 0x0A }); + readStringTest_0("mac line ending", "\r", new byte[] { 0x0D }); + readStringTest_0("windows line ending", "\r\n", new byte[] { 0x0D, 0x0A }); + } + + private static byte[] join(byte[]... parts) { + int count = 0; + for (byte[] part: parts) { + count += part.length; + } + byte[] result = new byte[count]; + int i = 0; + for (byte[] part: parts) { + System.arraycopy(part, 0, result, i, part.length); + i += part.length; + } + return result; + } + + private static void readStringTest_0(String label, String lineSeparator, byte[] extra) throws IOException { + String originalLineSeparator = System.getProperty("line.separator"); + try { + System.getProperties().put("line.separator", lineSeparator); + readStringTest_1(label + ":mark", "\u2122", join(trademarkBytes)); + readStringTest_1(label + ":mark NL", "\u2122\n", join(trademarkBytes, extra)); + readStringTest_1(label + ":NL mark", "\n\u2122", join(extra, trademarkBytes)); + } finally { + System.getProperties().put("line.separator", originalLineSeparator); + } + } + + private static void readStringTest_1(String label, String wanted, byte[] toRead) throws IOException { + assertEquals("readString bytes default:" + label, wanted, UtilIO.readString(toRead)); + assertEquals("readString bytes UTF-8:" + label, wanted, UtilIO.readString(toRead, "UTF-8")); + assertEquals("readString bytes UTF8:" + label, wanted, UtilIO.readString(toRead, UtilIO.UTF8)); + assertEquals("readString bytes offset/length default:" + label, wanted, UtilIO.readString(toRead, 0, toRead.length)); + assertEquals("readString bytes offset/length UTF-8:" + label, wanted, UtilIO.readString(toRead, 0, toRead.length, "UTF-8")); + assertEquals("readString bytes offset/length UTF8:" + label, wanted, UtilIO.readString(toRead, 0, toRead.length, UtilIO.UTF8)); + assertEquals("readString stream default:" + label, wanted, UtilIO.readString(new ByteArrayInputStream(toRead))); + assertEquals("readString stream UTF-8:" + label, wanted, UtilIO.readString(new ByteArrayInputStream(toRead), "UTF-8")); + assertEquals("readString stream UTF8:" + label, wanted, UtilIO.readString(new ByteArrayInputStream(toRead), UtilIO.UTF8)); + } + + public void testWriteString() throws Exception { + writeStringTest_0("unix line ending", "\n", new byte[] { 0x0A }); + writeStringTest_0("mac line ending", "\r", new byte[] { 0x0D }); + writeStringTest_0("windows line ending", "\r\n", new byte[] { 0x0D, 0x0A }); + } + + private static void writeStringTest_0(String label, String lineSeparator, byte[] extra) throws IOException { + String originalLineSeparator = System.getProperty("line.separator"); + try { + System.getProperties().put("line.separator", lineSeparator); + writeStringTest_1(label + ":mark", join(trademarkBytes), "\u2122"); + writeStringTest_1(label + ":mark NL", join(trademarkBytes, extra), "\u2122\n"); + writeStringTest_1(label + ":NL mark", join(extra, trademarkBytes), "\n\u2122"); + } finally { + System.getProperties().put("line.separator", originalLineSeparator); + } + } + + private static void writeStringTest_1(String label, byte[] wanted, String toWrite) throws IOException { + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + UtilIO.writeString(baos, toWrite); + assertEquals("writeString default:" + label, wanted, baos.toByteArray()); + baos = new ByteArrayOutputStream(); + UtilIO.writeString(baos, "UTF-8", toWrite); + assertEquals("writeString UTF-8:" + label, wanted, baos.toByteArray()); + baos = new ByteArrayOutputStream(); + UtilIO.writeString(baos, UtilIO.UTF8, toWrite); + assertEquals("writeString UTF8:" + label, wanted, baos.toByteArray()); + } +} Propchange: ofbiz/trunk/framework/base/src/org/ofbiz/base/util/test/UtilIOTests.java ('svn:eol-style' removed) Modified: ofbiz/trunk/framework/base/src/org/ofbiz/base/util/test/UtilObjectTests.java URL: http://svn.apache.org/viewvc/ofbiz/trunk/framework/base/src/org/ofbiz/base/util/test/UtilObjectTests.java?rev=1695126&r1=1695125&r2=1695126&view=diff ============================================================================== --- ofbiz/trunk/framework/base/src/org/ofbiz/base/util/test/UtilObjectTests.java (original) +++ ofbiz/trunk/framework/base/src/org/ofbiz/base/util/test/UtilObjectTests.java Mon Aug 10 16:15:37 2015 @@ -1,340 +1,340 @@ -/******************************************************************************* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - *******************************************************************************/ -package org.ofbiz.base.util.test; - -import java.io.ByteArrayInputStream; -import java.io.FilterInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.ObjectInputStream; -import java.io.ObjectOutputStream; -import java.io.Serializable; -import java.util.HashMap; -import java.util.Set; - -import org.ofbiz.base.lang.Factory; -import org.ofbiz.base.lang.SourceMonitored; -import org.ofbiz.base.test.GenericTestCaseBase; -import org.ofbiz.base.util.Debug; -import org.ofbiz.base.util.GroovyUtil; -import org.ofbiz.base.util.UtilObject; - -@SourceMonitored -public class UtilObjectTests extends GenericTestCaseBase { - public UtilObjectTests(String name) { - super(name); - } - - @Override - protected void setUp() throws Exception { - super.setUp(); - } - - @Override - protected void tearDown() throws Exception { - super.tearDown(); - } - - public void testStaticHelperClass() throws Exception { - assertStaticHelperClass(UtilObject.class); - } - - public static final class ErrorInjector extends FilterInputStream { - private int after; - private final boolean onClose; - - public ErrorInjector(InputStream in, boolean onClose) { - this(in, -1, onClose); - } - - public ErrorInjector(InputStream in, int after) { - this(in, after, false); - } - - public ErrorInjector(InputStream in, int after, boolean onClose) { - super(in); - this.after = after; - this.onClose = onClose; - } - - @Override - public int read() throws IOException { - if (after == 0) { - throw new IOException(); - } - if (after > 0) { - after--; - } - return super.read(); - } - - @Override - public int read(byte[] buf) throws IOException { - return read(buf, 0, buf.length); - } - - @Override - public int read(byte[] buf, int offset, int length) throws IOException { - if (after == 0) { - throw new IOException(); - } - if (after > 0) { - if (length > after) { - length = after; - } - int r = super.read(buf, offset, length); - after -= r; - return r; - } else { - return super.read(buf, offset, length); - } - } - - @Override - public void close() throws IOException { - if (onClose) { - throw new IOException(); - } - super.close(); - } - } - - public void testErrorInjector() throws Exception { - byte[] source = new byte[] { 0, 1, 2, 3, 4, 5, 6 }; - InputStream in = new ErrorInjector(new ByteArrayInputStream(source), true); - byte[] result = new byte[source.length]; - int r = in.read(); - assertEquals("onClose, read short length", 2, in.read(new byte[2])); - assertNotSame("onClose, not read/eof", -1, r); - assertEquals("onClose, read length", source.length - 3, in.read(result, 3, result.length - 3)); - Exception caught = null; - try { - in.close(); - } catch (IOException e) { - caught = e; - } finally { - assertNotNull("onClose, exception", caught); - } - in = new ErrorInjector(new ByteArrayInputStream(source), 4); - result = new byte[source.length]; - r = in.read(); - assertNotSame("after, not read/eof", -1, r); - assertEquals("after, read short length", 2, in.read(result, 0, 2)); - assertEquals("after, read long length", 1, in.read(result, 3, result.length - 3)); - caught = null; - try { - in.read(result, 4, result.length - 4); - } catch (IOException e) { - caught = e; - } finally { - assertNotNull("read, buffer exception", caught); - } - caught = null; - try { - in.read(); - } catch (IOException e) { - caught = e; - } finally { - assertNotNull("read, singleton exception", caught); - } - in.close(); - } - - public void testGetBytes_Stream() { - boolean errorOn = Debug.isOn(Debug.ERROR); - try { - Debug.set(Debug.ERROR, false); - byte[] source = new byte[] { 0, 1, 2, 3, 4, 5, 6 }; - byte[] result = UtilObject.getBytes(new ByteArrayInputStream(source)); - assertNotNull("initial result", result); - assertEquals("initial equals", source, result); - assertNull("error after read", UtilObject.getBytes(new ErrorInjector(new ByteArrayInputStream(source), 3))); - byte[] closeResult = UtilObject.getBytes(new ErrorInjector(new ByteArrayInputStream(source), true)); - assertNotNull("error on close", closeResult); - assertEquals("error on close equals", source, result); - Exception caught = null; - try { - UtilObject.getBytes(null); - } catch (NullPointerException e) { - caught = e; - } finally { - assertNotNull("null stream exception", caught); - } - } finally { - Debug.set(Debug.ERROR, errorOn); - } - } - - @SuppressWarnings("serial") - public static class SerializationInjector implements Serializable { - private boolean onRead; - private boolean onWrite; - - public SerializationInjector(boolean onRead, boolean onWrite) { - this.onRead = onRead; - this.onWrite = onWrite; - } - - private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException { - onRead = stream.readBoolean(); - onWrite = stream.readBoolean(); - if (onRead) { - throw new IOException(); - } - } - - private void writeObject(ObjectOutputStream stream) throws IOException { - if (onWrite) { - throw new IOException(); - } - stream.writeBoolean(onRead); - stream.writeBoolean(onWrite); - } - } - - public void testGetBytes_Object() { - assertNotNull("long", UtilObject.getBytes(Long.valueOf(0))); - assertNotNull("injector good", UtilObject.getBytes(new SerializationInjector(false, false))); - boolean errorOn = Debug.isOn(Debug.ERROR); - try { - Debug.set(Debug.ERROR, false); - assertNull("injector bad", UtilObject.getBytes(new SerializationInjector(false, true))); - assertNull("long", UtilObject.getBytes(this)); - } finally { - Debug.set(Debug.ERROR, errorOn); - } - } - - public void testGetObject() { - Long one = Long.valueOf(1); - byte[] oneBytes = UtilObject.getBytes(one); - assertNotNull("oneBytes", oneBytes); - assertEquals("one getObject", one, UtilObject.getObject(oneBytes)); - boolean errorOn = Debug.isOn(Debug.ERROR); - try { - Debug.set(Debug.ERROR, false); - assertNull("parse empty array", UtilObject.getObject(new byte[0])); - - // simulate a ClassNotFoundException - Object groovySerializable = GroovyUtil.eval("class foo implements java.io.Serializable { }; return new foo()", new HashMap<String, Object>()); - byte[] groovySerializableBytes = UtilObject.getBytes(groovySerializable); - assertNotNull("groovySerializableBytes", groovySerializableBytes); - assertNull("groovyDeserializable", UtilObject.getObject(groovySerializableBytes)); - - byte[] injectorBytes = UtilObject.getBytes(new SerializationInjector(false, false)); - assertNotNull("injectorBytes good", injectorBytes); - assertNotNull("injector good", UtilObject.getObject(injectorBytes)); - injectorBytes = UtilObject.getBytes(new SerializationInjector(true, false)); - assertNotNull("injectorBytes bad", injectorBytes); - assertNull("injector bad", UtilObject.getObject(injectorBytes)); - } finally { - Debug.set(Debug.ERROR, errorOn); - } - } - - public void testGetByteCount() throws Exception { - assertNotSame("long", 0, UtilObject.getByteCount(Long.valueOf(0))); - Exception caught = null; - try { - UtilObject.getByteCount(this); - } catch (IOException e) { - caught = e; - } finally { - assertNotNull("exception thrown", caught); - } - } - - public void testEqualsHelper() { - assertTrue("a == a", UtilObject.equalsHelper(this, this)); - assertFalse("null == a", UtilObject.equalsHelper(null, this)); - assertFalse("a == null", UtilObject.equalsHelper(this, null)); - assertTrue("null == null", UtilObject.equalsHelper(null, null)); - assertTrue("map == map", UtilObject.equalsHelper(new HashMap<String, Object>(), new HashMap<String, Object>())); - assertFalse("map == this", UtilObject.equalsHelper(new HashMap<String, Object>(), this)); - assertFalse("this == map", UtilObject.equalsHelper(this, new HashMap<String, Object>())); - } - - public void testCompareToHelper() { - Long one = Long.valueOf(1); - Long two = Long.valueOf(2); - assertComparison("one <-> two", -1, UtilObject.compareToHelper(one, two)); - assertComparison("one <-> one", 0, UtilObject.compareToHelper(one, one)); - assertComparison("two <-> one", 1, UtilObject.compareToHelper(two, one)); - assertComparison("one <-> null", 1, UtilObject.compareToHelper(one, null)); - assertComparison("null <-> one", -1, UtilObject.compareToHelper(null, one)); - } - - public void testDoHashCode() throws Exception { - UtilObject.doHashCode(this); - UtilObject.doHashCode(null); - UtilObject.doHashCode(0); - UtilObject.doHashCode(new Object[] { this, Object.class }); - UtilObject.doHashCode(new Object[] { null, Object.class }); - UtilObject.doHashCode(new int[] { 1, 3 }); - } - - public interface TestFactoryIntf extends Factory<Object, Set<String>> { - } - - public static class FirstTestFactory implements TestFactoryIntf { - public Object getInstance(Set<String> set) { - if (!set.contains("first")) return null; - if (set.contains("one")) return "ONE"; - if (set.contains("two")) return "TWO"; - if (set.contains("three")) return "THREE"; - return null; - } - } - - public static class SecondTestFactory implements TestFactoryIntf { - public Object getInstance(Set<String> set) { - if (!set.contains("second")) return null; - if (set.contains("ONE")) return "1"; - if (set.contains("TWO")) return "2"; - if (set.contains("THREE")) return "3"; - return null; - } - } - - public void testGetObjectFromFactory() throws Exception { - assertEquals("first one", "ONE", UtilObject.getObjectFromFactory(TestFactoryIntf.class, set("first", "one"))); - assertEquals("first two", "TWO", UtilObject.getObjectFromFactory(TestFactoryIntf.class, set("first", "two"))); - assertEquals("first three", "THREE", UtilObject.getObjectFromFactory(TestFactoryIntf.class, set("first", "three"))); - assertEquals("first null", "1", UtilObject.getObjectFromFactory(TestFactoryIntf.class, set("first", "second", "ONE"))); - assertEquals("second one", "1", UtilObject.getObjectFromFactory(TestFactoryIntf.class, set("second", "ONE"))); - assertEquals("second two", "2", UtilObject.getObjectFromFactory(TestFactoryIntf.class, set("second", "TWO"))); - assertEquals("second three", "3", UtilObject.getObjectFromFactory(TestFactoryIntf.class, set("second", "THREE"))); - Exception caught = null; - try { - UtilObject.getObjectFromFactory(TestFactoryIntf.class, set("first")); - } catch (ClassNotFoundException e) { - caught = e; - } finally { - assertNotNull("nothing found first", caught); - } - caught = null; - try { - UtilObject.getObjectFromFactory(TestFactoryIntf.class, set("second")); - } catch (ClassNotFoundException e) { - caught = e; - } finally { - assertNotNull("nothing found second", caught); - } - } -} +/******************************************************************************* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR 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.test; + +import java.io.ByteArrayInputStream; +import java.io.FilterInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.ObjectInputStream; +import java.io.ObjectOutputStream; +import java.io.Serializable; +import java.util.HashMap; +import java.util.Set; + +import org.ofbiz.base.lang.Factory; +import org.ofbiz.base.lang.SourceMonitored; +import org.ofbiz.base.test.GenericTestCaseBase; +import org.ofbiz.base.util.Debug; +import org.ofbiz.base.util.GroovyUtil; +import org.ofbiz.base.util.UtilObject; + +@SourceMonitored +public class UtilObjectTests extends GenericTestCaseBase { + public UtilObjectTests(String name) { + super(name); + } + + @Override + protected void setUp() throws Exception { + super.setUp(); + } + + @Override + protected void tearDown() throws Exception { + super.tearDown(); + } + + public void testStaticHelperClass() throws Exception { + assertStaticHelperClass(UtilObject.class); + } + + public static final class ErrorInjector extends FilterInputStream { + private int after; + private final boolean onClose; + + public ErrorInjector(InputStream in, boolean onClose) { + this(in, -1, onClose); + } + + public ErrorInjector(InputStream in, int after) { + this(in, after, false); + } + + public ErrorInjector(InputStream in, int after, boolean onClose) { + super(in); + this.after = after; + this.onClose = onClose; + } + + @Override + public int read() throws IOException { + if (after == 0) { + throw new IOException(); + } + if (after > 0) { + after--; + } + return super.read(); + } + + @Override + public int read(byte[] buf) throws IOException { + return read(buf, 0, buf.length); + } + + @Override + public int read(byte[] buf, int offset, int length) throws IOException { + if (after == 0) { + throw new IOException(); + } + if (after > 0) { + if (length > after) { + length = after; + } + int r = super.read(buf, offset, length); + after -= r; + return r; + } else { + return super.read(buf, offset, length); + } + } + + @Override + public void close() throws IOException { + if (onClose) { + throw new IOException(); + } + super.close(); + } + } + + public void testErrorInjector() throws Exception { + byte[] source = new byte[] { 0, 1, 2, 3, 4, 5, 6 }; + InputStream in = new ErrorInjector(new ByteArrayInputStream(source), true); + byte[] result = new byte[source.length]; + int r = in.read(); + assertEquals("onClose, read short length", 2, in.read(new byte[2])); + assertNotSame("onClose, not read/eof", -1, r); + assertEquals("onClose, read length", source.length - 3, in.read(result, 3, result.length - 3)); + Exception caught = null; + try { + in.close(); + } catch (IOException e) { + caught = e; + } finally { + assertNotNull("onClose, exception", caught); + } + in = new ErrorInjector(new ByteArrayInputStream(source), 4); + result = new byte[source.length]; + r = in.read(); + assertNotSame("after, not read/eof", -1, r); + assertEquals("after, read short length", 2, in.read(result, 0, 2)); + assertEquals("after, read long length", 1, in.read(result, 3, result.length - 3)); + caught = null; + try { + in.read(result, 4, result.length - 4); + } catch (IOException e) { + caught = e; + } finally { + assertNotNull("read, buffer exception", caught); + } + caught = null; + try { + in.read(); + } catch (IOException e) { + caught = e; + } finally { + assertNotNull("read, singleton exception", caught); + } + in.close(); + } + + public void testGetBytes_Stream() { + boolean errorOn = Debug.isOn(Debug.ERROR); + try { + Debug.set(Debug.ERROR, false); + byte[] source = new byte[] { 0, 1, 2, 3, 4, 5, 6 }; + byte[] result = UtilObject.getBytes(new ByteArrayInputStream(source)); + assertNotNull("initial result", result); + assertEquals("initial equals", source, result); + assertNull("error after read", UtilObject.getBytes(new ErrorInjector(new ByteArrayInputStream(source), 3))); + byte[] closeResult = UtilObject.getBytes(new ErrorInjector(new ByteArrayInputStream(source), true)); + assertNotNull("error on close", closeResult); + assertEquals("error on close equals", source, result); + Exception caught = null; + try { + UtilObject.getBytes(null); + } catch (NullPointerException e) { + caught = e; + } finally { + assertNotNull("null stream exception", caught); + } + } finally { + Debug.set(Debug.ERROR, errorOn); + } + } + + @SuppressWarnings("serial") + public static class SerializationInjector implements Serializable { + private boolean onRead; + private boolean onWrite; + + public SerializationInjector(boolean onRead, boolean onWrite) { + this.onRead = onRead; + this.onWrite = onWrite; + } + + private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException { + onRead = stream.readBoolean(); + onWrite = stream.readBoolean(); + if (onRead) { + throw new IOException(); + } + } + + private void writeObject(ObjectOutputStream stream) throws IOException { + if (onWrite) { + throw new IOException(); + } + stream.writeBoolean(onRead); + stream.writeBoolean(onWrite); + } + } + + public void testGetBytes_Object() { + assertNotNull("long", UtilObject.getBytes(Long.valueOf(0))); + assertNotNull("injector good", UtilObject.getBytes(new SerializationInjector(false, false))); + boolean errorOn = Debug.isOn(Debug.ERROR); + try { + Debug.set(Debug.ERROR, false); + assertNull("injector bad", UtilObject.getBytes(new SerializationInjector(false, true))); + assertNull("long", UtilObject.getBytes(this)); + } finally { + Debug.set(Debug.ERROR, errorOn); + } + } + + public void testGetObject() { + Long one = Long.valueOf(1); + byte[] oneBytes = UtilObject.getBytes(one); + assertNotNull("oneBytes", oneBytes); + assertEquals("one getObject", one, UtilObject.getObject(oneBytes)); + boolean errorOn = Debug.isOn(Debug.ERROR); + try { + Debug.set(Debug.ERROR, false); + assertNull("parse empty array", UtilObject.getObject(new byte[0])); + + // simulate a ClassNotFoundException + Object groovySerializable = GroovyUtil.eval("class foo implements java.io.Serializable { }; return new foo()", new HashMap<String, Object>()); + byte[] groovySerializableBytes = UtilObject.getBytes(groovySerializable); + assertNotNull("groovySerializableBytes", groovySerializableBytes); + assertNull("groovyDeserializable", UtilObject.getObject(groovySerializableBytes)); + + byte[] injectorBytes = UtilObject.getBytes(new SerializationInjector(false, false)); + assertNotNull("injectorBytes good", injectorBytes); + assertNotNull("injector good", UtilObject.getObject(injectorBytes)); + injectorBytes = UtilObject.getBytes(new SerializationInjector(true, false)); + assertNotNull("injectorBytes bad", injectorBytes); + assertNull("injector bad", UtilObject.getObject(injectorBytes)); + } finally { + Debug.set(Debug.ERROR, errorOn); + } + } + + public void testGetByteCount() throws Exception { + assertNotSame("long", 0, UtilObject.getByteCount(Long.valueOf(0))); + Exception caught = null; + try { + UtilObject.getByteCount(this); + } catch (IOException e) { + caught = e; + } finally { + assertNotNull("exception thrown", caught); + } + } + + public void testEqualsHelper() { + assertTrue("a == a", UtilObject.equalsHelper(this, this)); + assertFalse("null == a", UtilObject.equalsHelper(null, this)); + assertFalse("a == null", UtilObject.equalsHelper(this, null)); + assertTrue("null == null", UtilObject.equalsHelper(null, null)); + assertTrue("map == map", UtilObject.equalsHelper(new HashMap<String, Object>(), new HashMap<String, Object>())); + assertFalse("map == this", UtilObject.equalsHelper(new HashMap<String, Object>(), this)); + assertFalse("this == map", UtilObject.equalsHelper(this, new HashMap<String, Object>())); + } + + public void testCompareToHelper() { + Long one = Long.valueOf(1); + Long two = Long.valueOf(2); + assertComparison("one <-> two", -1, UtilObject.compareToHelper(one, two)); + assertComparison("one <-> one", 0, UtilObject.compareToHelper(one, one)); + assertComparison("two <-> one", 1, UtilObject.compareToHelper(two, one)); + assertComparison("one <-> null", 1, UtilObject.compareToHelper(one, null)); + assertComparison("null <-> one", -1, UtilObject.compareToHelper(null, one)); + } + + public void testDoHashCode() throws Exception { + UtilObject.doHashCode(this); + UtilObject.doHashCode(null); + UtilObject.doHashCode(0); + UtilObject.doHashCode(new Object[] { this, Object.class }); + UtilObject.doHashCode(new Object[] { null, Object.class }); + UtilObject.doHashCode(new int[] { 1, 3 }); + } + + public interface TestFactoryIntf extends Factory<Object, Set<String>> { + } + + public static class FirstTestFactory implements TestFactoryIntf { + public Object getInstance(Set<String> set) { + if (!set.contains("first")) return null; + if (set.contains("one")) return "ONE"; + if (set.contains("two")) return "TWO"; + if (set.contains("three")) return "THREE"; + return null; + } + } + + public static class SecondTestFactory implements TestFactoryIntf { + public Object getInstance(Set<String> set) { + if (!set.contains("second")) return null; + if (set.contains("ONE")) return "1"; + if (set.contains("TWO")) return "2"; + if (set.contains("THREE")) return "3"; + return null; + } + } + + public void testGetObjectFromFactory() throws Exception { + assertEquals("first one", "ONE", UtilObject.getObjectFromFactory(TestFactoryIntf.class, set("first", "one"))); + assertEquals("first two", "TWO", UtilObject.getObjectFromFactory(TestFactoryIntf.class, set("first", "two"))); + assertEquals("first three", "THREE", UtilObject.getObjectFromFactory(TestFactoryIntf.class, set("first", "three"))); + assertEquals("first null", "1", UtilObject.getObjectFromFactory(TestFactoryIntf.class, set("first", "second", "ONE"))); + assertEquals("second one", "1", UtilObject.getObjectFromFactory(TestFactoryIntf.class, set("second", "ONE"))); + assertEquals("second two", "2", UtilObject.getObjectFromFactory(TestFactoryIntf.class, set("second", "TWO"))); + assertEquals("second three", "3", UtilObject.getObjectFromFactory(TestFactoryIntf.class, set("second", "THREE"))); + Exception caught = null; + try { + UtilObject.getObjectFromFactory(TestFactoryIntf.class, set("first")); + } catch (ClassNotFoundException e) { + caught = e; + } finally { + assertNotNull("nothing found first", caught); + } + caught = null; + try { + UtilObject.getObjectFromFactory(TestFactoryIntf.class, set("second")); + } catch (ClassNotFoundException e) { + caught = e; + } finally { + assertNotNull("nothing found second", caught); + } + } +} Propchange: ofbiz/trunk/framework/base/src/org/ofbiz/base/util/test/UtilObjectTests.java ('svn:eol-style' removed) Modified: ofbiz/trunk/framework/common/src/org/ofbiz/common/authentication/AuthHelper.java URL: http://svn.apache.org/viewvc/ofbiz/trunk/framework/common/src/org/ofbiz/common/authentication/AuthHelper.java?rev=1695126&r1=1695125&r2=1695126&view=diff ============================================================================== --- ofbiz/trunk/framework/common/src/org/ofbiz/common/authentication/AuthHelper.java (original) +++ ofbiz/trunk/framework/common/src/org/ofbiz/common/authentication/AuthHelper.java Mon Aug 10 16:15:37 2015 @@ -1,129 +1,129 @@ -/******************************************************************************* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - *******************************************************************************/ - -package org.ofbiz.common.authentication; - -import java.security.AccessController; -import java.security.PrivilegedAction; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; -import java.util.Iterator; -import java.util.ServiceLoader; - -import org.ofbiz.base.util.Debug; -import org.ofbiz.common.authentication.api.Authenticator; -import org.ofbiz.common.authentication.api.AuthenticatorException; -import org.ofbiz.service.LocalDispatcher; - -/** - * AuthHelper - */ -public class AuthHelper { - - private static final String module = AuthHelper.class.getName(); - protected static List<Authenticator> authenticators = new ArrayList<Authenticator>(); - protected static boolean authenticatorsLoaded = false; - - - public static boolean authenticate(String username, String password, boolean isServiceAuth) throws AuthenticatorException { - if (!authenticatorsLoaded) throw new AuthenticatorException("Authenticators never loaded; be sure to call AuthHelper.loadAuthenticators()"); - for (Authenticator auth : authenticators) { - boolean pass = auth.authenticate(username, password, isServiceAuth); - if (pass) { - return true; - } else if (auth.isSingleAuthenticator()) { - throw new AuthenticatorException(); - } - } - return false; - } - - public static void logout(String username) throws AuthenticatorException { - if (!authenticatorsLoaded) throw new AuthenticatorException("Authenticators never loaded; be sure to call AuthHelper.loadAuthenticators()"); - for (Authenticator auth : authenticators) { - auth.logout(username); - } - } - - public static void syncUser(String username) throws AuthenticatorException { - if (!authenticatorsLoaded) throw new AuthenticatorException("Authenticators never loaded; be sure to call AuthHelper.loadAuthenticators()"); - for (Authenticator auth : authenticators) { - if (auth.isUserSynchronized()) { - auth.syncUser(username); - } - } - } - - public static void updatePassword(String username, String password, String newPassword) throws AuthenticatorException { - if (!authenticatorsLoaded) throw new AuthenticatorException("Authenticators never loaded; be sure to call AuthHelper.loadAuthenticators()"); - for (Authenticator auth : authenticators) { - auth.updatePassword(username, password, newPassword); - } - } - - public static boolean authenticatorsLoaded() { - return authenticatorsLoaded; - } - - public static void loadAuthenticators(LocalDispatcher dispatcher) { - if (!authenticatorsLoaded) { - loadAuthenticators_internal(dispatcher); - } - } - - private synchronized static void loadAuthenticators_internal(LocalDispatcher dispatcher) { - if (!authenticatorsLoaded) { - Iterator<Authenticator> it = ServiceLoader.load(Authenticator.class, getContextClassLoader()).iterator(); - while (it.hasNext()) { - try { - Authenticator auth = it.next(); - if (auth.isEnabled()) { - auth.initialize(dispatcher); - authenticators.add(auth); - } - } catch (ClassCastException e) { - Debug.logError(e, module); - } - } - - Collections.sort(authenticators, new AuthenticationComparator()); - authenticatorsLoaded = true; - } - } - - /* Do not move this into a shared global util class; doing so - * would mean the method would have to be public, and then it - * could be called by any other non-secure source. - */ - private static ClassLoader getContextClassLoader() { - return AccessController.doPrivileged( - new PrivilegedAction<ClassLoader>() { - public ClassLoader run() { - ClassLoader cl = null; - try { - cl = Thread.currentThread().getContextClassLoader(); - } catch (SecurityException e) { - Debug.logError(e, e.getMessage(), module); - } - return cl; - } - }); - } -} +/******************************************************************************* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR 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.common.authentication; + +import java.security.AccessController; +import java.security.PrivilegedAction; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.Iterator; +import java.util.ServiceLoader; + +import org.ofbiz.base.util.Debug; +import org.ofbiz.common.authentication.api.Authenticator; +import org.ofbiz.common.authentication.api.AuthenticatorException; +import org.ofbiz.service.LocalDispatcher; + +/** + * AuthHelper + */ +public class AuthHelper { + + private static final String module = AuthHelper.class.getName(); + protected static List<Authenticator> authenticators = new ArrayList<Authenticator>(); + protected static boolean authenticatorsLoaded = false; + + + public static boolean authenticate(String username, String password, boolean isServiceAuth) throws AuthenticatorException { + if (!authenticatorsLoaded) throw new AuthenticatorException("Authenticators never loaded; be sure to call AuthHelper.loadAuthenticators()"); + for (Authenticator auth : authenticators) { + boolean pass = auth.authenticate(username, password, isServiceAuth); + if (pass) { + return true; + } else if (auth.isSingleAuthenticator()) { + throw new AuthenticatorException(); + } + } + return false; + } + + public static void logout(String username) throws AuthenticatorException { + if (!authenticatorsLoaded) throw new AuthenticatorException("Authenticators never loaded; be sure to call AuthHelper.loadAuthenticators()"); + for (Authenticator auth : authenticators) { + auth.logout(username); + } + } + + public static void syncUser(String username) throws AuthenticatorException { + if (!authenticatorsLoaded) throw new AuthenticatorException("Authenticators never loaded; be sure to call AuthHelper.loadAuthenticators()"); + for (Authenticator auth : authenticators) { + if (auth.isUserSynchronized()) { + auth.syncUser(username); + } + } + } + + public static void updatePassword(String username, String password, String newPassword) throws AuthenticatorException { + if (!authenticatorsLoaded) throw new AuthenticatorException("Authenticators never loaded; be sure to call AuthHelper.loadAuthenticators()"); + for (Authenticator auth : authenticators) { + auth.updatePassword(username, password, newPassword); + } + } + + public static boolean authenticatorsLoaded() { + return authenticatorsLoaded; + } + + public static void loadAuthenticators(LocalDispatcher dispatcher) { + if (!authenticatorsLoaded) { + loadAuthenticators_internal(dispatcher); + } + } + + private synchronized static void loadAuthenticators_internal(LocalDispatcher dispatcher) { + if (!authenticatorsLoaded) { + Iterator<Authenticator> it = ServiceLoader.load(Authenticator.class, getContextClassLoader()).iterator(); + while (it.hasNext()) { + try { + Authenticator auth = it.next(); + if (auth.isEnabled()) { + auth.initialize(dispatcher); + authenticators.add(auth); + } + } catch (ClassCastException e) { + Debug.logError(e, module); + } + } + + Collections.sort(authenticators, new AuthenticationComparator()); + authenticatorsLoaded = true; + } + } + + /* Do not move this into a shared global util class; doing so + * would mean the method would have to be public, and then it + * could be called by any other non-secure source. + */ + private static ClassLoader getContextClassLoader() { + return AccessController.doPrivileged( + new PrivilegedAction<ClassLoader>() { + public ClassLoader run() { + ClassLoader cl = null; + try { + cl = Thread.currentThread().getContextClassLoader(); + } catch (SecurityException e) { + Debug.logError(e, e.getMessage(), module); + } + return cl; + } + }); + } +} Propchange: ofbiz/trunk/framework/common/src/org/ofbiz/common/authentication/AuthHelper.java ('svn:eol-style' removed) |
Free forum by Nabble | Edit this page |