Repository: incubator-brooklyn Updated Branches: refs/heads/master fefaad633 -> 8a0a361ba
http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/cf2f7a93/utils/common/src/test/java/org/apache/brooklyn/util/text/StringsTest.java ---------------------------------------------------------------------- diff --git a/utils/common/src/test/java/org/apache/brooklyn/util/text/StringsTest.java b/utils/common/src/test/java/org/apache/brooklyn/util/text/StringsTest.java new file mode 100644 index 0000000..85ba659 --- /dev/null +++ b/utils/common/src/test/java/org/apache/brooklyn/util/text/StringsTest.java @@ -0,0 +1,366 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.brooklyn.util.text; + +import static org.testng.Assert.assertEquals; +import static org.testng.Assert.assertFalse; +import static org.testng.Assert.assertTrue; + +import java.util.Arrays; + +import org.apache.brooklyn.test.FixedLocaleTest; +import org.apache.brooklyn.util.collections.MutableMap; +import org.apache.brooklyn.util.text.FormattedString; +import org.apache.brooklyn.util.text.StringFunctions; +import org.apache.brooklyn.util.text.Strings; +import org.testng.Assert; +import org.testng.annotations.Test; + +@Test +public class StringsTest extends FixedLocaleTest { + + public void isBlankOrEmpty() { + assertTrue(Strings.isEmpty(null)); + assertTrue(Strings.isEmpty("")); + assertFalse(Strings.isEmpty(" \t ")); + assertFalse(Strings.isEmpty("abc")); + assertFalse(Strings.isEmpty(" abc ")); + + assertFalse(Strings.isNonEmpty(null)); + assertFalse(Strings.isNonEmpty("")); + assertTrue(Strings.isNonEmpty(" \t ")); + assertTrue(Strings.isNonEmpty("abc")); + assertTrue(Strings.isNonEmpty(" abc ")); + + assertTrue(Strings.isBlank(null)); + assertTrue(Strings.isBlank("")); + assertTrue(Strings.isBlank(" \t ")); + assertFalse(Strings.isBlank("abc")); + assertFalse(Strings.isBlank(" abc ")); + + assertFalse(Strings.isNonBlank(null)); + assertFalse(Strings.isNonBlank("")); + assertFalse(Strings.isNonBlank(" \t ")); + assertTrue(Strings.isNonBlank("abc")); + assertTrue(Strings.isNonBlank(" abc ")); + } + + public void testMakeValidFilename() { + assertEquals("abcdef", Strings.makeValidFilename("abcdef")); + assertEquals("abc_def", Strings.makeValidFilename("abc$$$def")); + assertEquals("abc_def", Strings.makeValidFilename("$$$abc$$$def$$$")); + assertEquals("a_b_c", Strings.makeValidFilename("a b c")); + assertEquals("a.b.c", Strings.makeValidFilename("a.b.c")); + } + @Test(expectedExceptions = { NullPointerException.class }) + public void testMakeValidFilenameNull() { + Strings.makeValidFilename(null); + } + @Test(expectedExceptions = { IllegalArgumentException.class }) + public void testMakeValidFilenameEmpty() { + Strings.makeValidFilename(""); + } + @Test(expectedExceptions = { IllegalArgumentException.class }) + public void testMakeValidFilenameBlank() { + Strings.makeValidFilename(" \t "); + } + + public void makeValidJavaName() { + assertEquals(Strings.makeValidJavaName(null), "__null"); + assertEquals(Strings.makeValidJavaName(""), "__empty"); + assertEquals(Strings.makeValidJavaName("abcdef"), "abcdef"); + assertEquals(Strings.makeValidJavaName("a'b'c'd'e'f"), "abcdef"); + assertEquals(Strings.makeValidJavaName("12345"), "_12345"); + } + + public void makeValidUniqueJavaName() { + assertEquals(Strings.makeValidUniqueJavaName(null), "__null"); + assertEquals(Strings.makeValidUniqueJavaName(""), "__empty"); + assertEquals(Strings.makeValidUniqueJavaName("abcdef"), "abcdef"); + assertEquals(Strings.makeValidUniqueJavaName("12345"), "_12345"); + } + + public void testRemoveFromEnd() { + assertEquals(Strings.removeFromEnd("", "bar"), ""); + assertEquals(Strings.removeFromEnd(null, "bar"), null); + + assertEquals(Strings.removeFromEnd("foobar", "bar"), "foo"); + assertEquals(Strings.removeFromEnd("foo", "bar"), "foo"); + assertEquals(Strings.removeFromEnd("foobar", "foo", "bar"), "foo"); + // test they are applied in order + assertEquals(Strings.removeFromEnd("foobar", "ar", "bar", "b"), "foob"); + } + + public void testRemoveAllFromEnd() { + assertEquals(Strings.removeAllFromEnd("", "bar"), ""); + assertEquals(Strings.removeAllFromEnd(null, "bar"), null); + assertEquals(Strings.removeAllFromEnd("foo", ""), "foo"); + + assertEquals(Strings.removeAllFromEnd("foobar", "foo", "bar"), ""); + assertEquals(Strings.removeAllFromEnd("foobar", "ar", "car", "b", "o"), "f"); + // test they are applied in order + assertEquals(Strings.removeAllFromEnd("foobar", "ar", "car", "b", "ob"), "foo"); + assertEquals(Strings.removeAllFromEnd("foobar", "zz", "x"), "foobar"); + assertEquals(Strings.removeAllFromEnd("foobarbaz", "bar", "baz"), "foo"); + assertEquals(Strings.removeAllFromEnd("foobarbaz", "baz", "", "foo", "bar", "baz"), ""); + } + + public void testRemoveFromStart() { + assertEquals(Strings.removeFromStart("", "foo"), ""); + assertEquals(Strings.removeFromStart(null, "foo"), null); + + assertEquals(Strings.removeFromStart("foobar", "foo"), "bar"); + assertEquals(Strings.removeFromStart("foo", "bar"), "foo"); + assertEquals(Strings.removeFromStart("foobar", "foo", "bar"), "bar"); + assertEquals(Strings.removeFromStart("foobar", "ob", "fo", "foo", "o"), "obar"); + } + + public void testRemoveAllFromStart() { + assertEquals(Strings.removeAllFromStart("", "foo"), ""); + assertEquals(Strings.removeAllFromStart(null, "foo"), null); + assertEquals(Strings.removeAllFromStart("foo", ""), "foo"); + + assertEquals(Strings.removeAllFromStart("foobar", "foo"), "bar"); + assertEquals(Strings.removeAllFromStart("foo", "bar"), "foo"); + assertEquals(Strings.removeAllFromStart("foobar", "foo", "bar"), ""); + + assertEquals(Strings.removeAllFromStart("foobar", "fo", "ob", "o"), "ar"); + assertEquals(Strings.removeAllFromStart("foobar", "ob", "fo", "o"), "ar"); + // test they are applied in order, "ob" doesn't match because "o" eats the o + assertEquals(Strings.removeAllFromStart("foobar", "o", "fo", "ob"), "bar"); + assertEquals(Strings.removeAllFromStart("foobarbaz", "bar", "foo"), "baz"); + assertEquals(Strings.removeAllFromStart("foobarbaz", "baz", "bar", "foo"), ""); + } + + public void testRemoveFromStart2() { + assertEquals(Strings.removeFromStart("xyz", "x"), "yz"); + assertEquals(Strings.removeFromStart("xyz", "."), "xyz"); + assertEquals(Strings.removeFromStart("http://foo.com", "http://"), "foo.com"); + } + + public void testRemoveFromEnd2() { + assertEquals(Strings.removeFromEnd("xyz", "z"), "xy"); + assertEquals(Strings.removeFromEnd("xyz", "."), "xyz"); + assertEquals(Strings.removeFromEnd("http://foo.com/", "/"), "http://foo.com"); + } + + public void testReplaceAll() { + assertEquals(Strings.replaceAll("xyz", "x", ""), "yz"); + assertEquals(Strings.replaceAll("xyz", ".", ""), "xyz"); + assertEquals(Strings.replaceAll("http://foo.com/", "/", ""), "http:foo.com"); + assertEquals(Strings.replaceAll("http://foo.com/", "http:", "https:"), "https://foo.com/"); + } + + public void testReplaceAllNonRegex() { + assertEquals(Strings.replaceAllNonRegex("xyz", "x", ""), "yz"); + assertEquals(Strings.replaceAllNonRegex("xyz", ".", ""), "xyz"); + assertEquals(Strings.replaceAllNonRegex("http://foo.com/", "/", ""), "http:foo.com"); + assertEquals(Strings.replaceAllNonRegex("http://foo.com/", "http:", "https:"), "https://foo.com/"); + } + + public void testReplaceAllRegex() { + assertEquals(Strings.replaceAllRegex("xyz", "x", ""), "yz"); + assertEquals(Strings.replaceAllRegex("xyz", ".", ""), ""); + assertEquals(Strings.replaceAllRegex("http://foo.com/", "/", ""), "http:foo.com"); + assertEquals(Strings.replaceAllRegex("http://foo.com/", "http:", "https:"), "https://foo.com/"); + } + + public void testReplaceMap() { + assertEquals(Strings.replaceAll("xyz", MutableMap.builder().put("x","a").put("y","").build()), "az"); + } + + public void testContainsLiteral() { + assertTrue(Strings.containsLiteral("hello", "ell")); + assertTrue(Strings.containsLiteral("hello", "h")); + assertFalse(Strings.containsLiteral("hello", "H")); + assertFalse(Strings.containsLiteral("hello", "O")); + assertFalse(Strings.containsLiteral("hello", "x")); + assertFalse(Strings.containsLiteral("hello", "ELL")); + assertTrue(Strings.containsLiteral("hello", "hello")); + assertTrue(Strings.containsLiteral("hELlo", "ELl")); + assertFalse(Strings.containsLiteral("hello", "!")); + } + + public void testContainsLiteralIgnoreCase() { + assertTrue(Strings.containsLiteralIgnoreCase("hello", "ell")); + assertTrue(Strings.containsLiteralIgnoreCase("hello", "H")); + assertTrue(Strings.containsLiteralIgnoreCase("hello", "O")); + assertFalse(Strings.containsLiteralIgnoreCase("hello", "X")); + assertTrue(Strings.containsLiteralIgnoreCase("hello", "ELL")); + assertTrue(Strings.containsLiteralIgnoreCase("hello", "hello")); + assertTrue(Strings.containsLiteralIgnoreCase("hELlo", "Hello")); + assertFalse(Strings.containsLiteralIgnoreCase("hello", "!")); + } + + @Test + public void testDeferredFormat() { + ToStringCounter c = new ToStringCounter(); + FormattedString x = Strings.format("hello %s", c); + Assert.assertEquals(c.count, 0); + Assert.assertEquals(x.toString(), "hello world"); + Assert.assertEquals(c.count, 1); + } + + @Test + public void testToStringSupplier() { + ToStringCounter c = new ToStringCounter(true); + Assert.assertEquals(Strings.toStringSupplier(c).get(), "world1"); + FormattedString x = Strings.format("hello %s", c); + Assert.assertEquals(x.toString(), "hello world2"); + Assert.assertEquals(x.toString(), "hello world3"); + } + + private static class ToStringCounter { + private int count = 0; + private boolean appendCount = false; + private ToStringCounter() {} + private ToStringCounter(boolean append) { this.appendCount = append; } + @Override + public String toString() { + count++; + return "world"+(appendCount?""+count:""); + } + } + + @Test + public void testFormatter() { + Assert.assertEquals(StringFunctions.formatter("hello %s").apply("world"), "hello world"); + Assert.assertEquals(StringFunctions.formatterForArray("%s %s").apply(new String[] { "hello", "world" }), "hello world"); + } + + @Test + public void testJoiner() { + Assert.assertEquals(StringFunctions.joiner(" ").apply(Arrays.asList("hello", "world")), "hello world"); + Assert.assertEquals(StringFunctions.joinerForArray(" ").apply(new String[] { "hello", "world" }), "hello world"); + } + + @Test + public void testSurround() { + Assert.assertEquals(StringFunctions.surround("hello ", " world").apply("new"), "hello new world"); + } + + @Test + public void testFirstWord() { + Assert.assertEquals(Strings.getFirstWord("hello world"), "hello"); + Assert.assertEquals(Strings.getFirstWord(" hello world"), "hello"); + Assert.assertEquals(Strings.getFirstWord(" hello "), "hello"); + Assert.assertEquals(Strings.getFirstWord("hello"), "hello"); + Assert.assertEquals(Strings.getFirstWord(" "), null); + Assert.assertEquals(Strings.getFirstWord(""), null); + Assert.assertEquals(Strings.getFirstWord(null), null); + } + + @Test + public void testLastWord() { + Assert.assertEquals(Strings.getLastWord("hello world"), "world"); + Assert.assertEquals(Strings.getLastWord(" hello world "), "world"); + Assert.assertEquals(Strings.getLastWord(" hello "), "hello"); + Assert.assertEquals(Strings.getLastWord("hello"), "hello"); + Assert.assertEquals(Strings.getLastWord(" "), null); + Assert.assertEquals(Strings.getLastWord(""), null); + Assert.assertEquals(Strings.getLastWord(null), null); + } + + @Test + public void testFirstWordAfter() { + Assert.assertEquals(Strings.getFirstWordAfter("hello world", "hello"), "world"); + Assert.assertEquals(Strings.getFirstWordAfter(" hello world", "hello"), "world"); + Assert.assertEquals(Strings.getFirstWordAfter(" hello world: is not enough", "world:"), "is"); + Assert.assertEquals(Strings.getFirstWordAfter(" hello world: is not enough", "world"), ":"); + Assert.assertEquals(Strings.getFirstWordAfter(" hello ", "hello"), null); + Assert.assertEquals(Strings.getFirstWordAfter("hello", "hello"), null); + Assert.assertEquals(Strings.getFirstWordAfter(" ", "x"), null); + Assert.assertEquals(Strings.getFirstWordAfter("", "x"), null); + Assert.assertEquals(Strings.getFirstWordAfter(null, "x"), null); + } + + @Test + public void testFragmentBetween() { + Assert.assertEquals("ooba", Strings.getFragmentBetween("foobar", "f", "r")); + Assert.assertEquals("oobar", Strings.getFragmentBetween("foobar", "f", "z")); + Assert.assertEquals("oobar", Strings.getFragmentBetween("foobar", "f", null)); + Assert.assertEquals("oba", Strings.getFragmentBetween("foobar", "o", "r")); + Assert.assertEquals("\nba", Strings.getFragmentBetween("foo\nbar", "foo", "r")); + Assert.assertEquals("fooba", Strings.getFragmentBetween("foobar", null, "r")); + Assert.assertEquals(null, Strings.getFragmentBetween("foobar", "z", "r")); + } + + @Test + public void testWordCount() { + Assert.assertEquals(Strings.getWordCount("hello", true), 1); + Assert.assertEquals(Strings.getWordCount("hello world", true), 2); + Assert.assertEquals(Strings.getWordCount("hello\nworld", true), 2); + Assert.assertEquals(Strings.getWordCount("hello world \nit is me!\n", true), 5); + Assert.assertEquals(Strings.getWordCount("", true), 0); + Assert.assertEquals(Strings.getWordCount(null, true), 0); + Assert.assertEquals(Strings.getWordCount("\"hello world\" ", true), 1); + Assert.assertEquals(Strings.getWordCount("\"hello world\" ", false), 2); + Assert.assertEquals(Strings.getWordCount("hello world \nit's me!\n", true), 3); + Assert.assertEquals(Strings.getWordCount("hello world \nit's me!\n", false), 4); + } + + @Test + public void testMakeRealString() { + // less precision = less length + Assert.assertEquals(Strings.makeRealString(1.23456d, 4, 2, 0), "1.2"); + // precision trumps length, and rounds + Assert.assertEquals(Strings.makeRealString(1.23456d, 4, 5, 0), "1.2346"); + // uses E notation when needed + Assert.assertEquals(Strings.makeRealString(123456, 2, 2, 0), "1.2E5"); + // and works with negatives + Assert.assertEquals(Strings.makeRealString(-123456, 2, 2, 0), "-1.2E5"); + // and very small negatives + Assert.assertEquals(Strings.makeRealString(-0.000000000123456, 2, 2, 0), "-1.2E-10"); + // and 0 + Assert.assertEquals(Strings.makeRealString(0.0d, 4, 2, 0), "0"); + // skips E notation and gives extra precision when it's free + Assert.assertEquals(Strings.makeRealString(123456, 8, 2, 0), "123456"); + } + + @Test + public void testCollapseWhitespace() { + Assert.assertEquals(Strings.collapseWhitespace(" x\n y\n", ""), "xy"); + Assert.assertEquals(Strings.collapseWhitespace(" x\n y\n", " "), " x y "); + Assert.assertEquals(Strings.collapseWhitespace(" x\n y\n", "\n").trim(), "x\ny"); + } + + @Test + public void testMaxlen() { + Assert.assertEquals(Strings.maxlen("hello world", 5), "hello"); + Assert.assertEquals(Strings.maxlenWithEllipsis("hello world", 9), "hello ..."); + Assert.assertEquals(Strings.maxlenWithEllipsis("hello world", 7, "--"), "hello--"); + } + + @Test + public void testGetRemainderOfLineAfter() { + // Basic test (also tests start is trimmed) + Assert.assertEquals(Strings.getRemainderOfLineAfter("the message is hello", "is"), " hello"); + Assert.assertEquals(Strings.getRemainderOfLineAfter("the message is is hello", "is"), " is hello"); + // Trim spaces from end + Assert.assertEquals(Strings.getRemainderOfLineAfter("the message is is hello ", "is"), " is hello "); + // Trim non-matching lines from start + Assert.assertEquals(Strings.getRemainderOfLineAfter("one\ntwo\nthree\nthe message is is hello ", "is"), " is hello "); + // Trim lines from end + Assert.assertEquals(Strings.getRemainderOfLineAfter("one\ntwo\nthree\nthe message is is hello \nfour\nfive\nsix\nis not seven", "is"), " is hello "); + // Play nicely with null / non-match + Assert.assertEquals(Strings.getRemainderOfLineAfter(null, "is"), null); + Assert.assertEquals(Strings.getRemainderOfLineAfter("the message is hello", null), null); + Assert.assertEquals(Strings.getRemainderOfLineAfter("the message is hello", "foo"), null); + } +} http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/cf2f7a93/utils/common/src/test/java/org/apache/brooklyn/util/text/WildcardGlobsTest.java ---------------------------------------------------------------------- diff --git a/utils/common/src/test/java/org/apache/brooklyn/util/text/WildcardGlobsTest.java b/utils/common/src/test/java/org/apache/brooklyn/util/text/WildcardGlobsTest.java new file mode 100644 index 0000000..5d7a39c --- /dev/null +++ b/utils/common/src/test/java/org/apache/brooklyn/util/text/WildcardGlobsTest.java @@ -0,0 +1,236 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.brooklyn.util.text; + +import java.util.Arrays; +import java.util.List; + +import org.apache.brooklyn.util.text.WildcardGlobs; +import org.apache.brooklyn.util.text.WildcardGlobs.InvalidPatternException; +import org.apache.brooklyn.util.text.WildcardGlobs.PhraseTreatment; +import org.apache.brooklyn.util.text.WildcardGlobs.SpecialistGlobExpander; +import org.testng.Assert; +import org.testng.annotations.Test; + +@Test +public class WildcardGlobsTest extends Assert { + + @Test + public void testBasic() throws InvalidPatternException { + assertTrue(WildcardGlobs.isGlobMatched("a?{ex,in}", "akin")); + assertTrue(WildcardGlobs.isGlobMatched("a?{ex,in}", "alex")); + assertFalse(WildcardGlobs.isGlobMatched("a?{ex,in}", "appin")); + } + + @Test + public void testEmpty() throws InvalidPatternException { + assertTrue(WildcardGlobs.isGlobMatched("a{,?}{,b}", "a")); + assertTrue(WildcardGlobs.isGlobMatched("a{,?}{,b}", "ab")); + assertTrue(WildcardGlobs.isGlobMatched("a{,?}{,b}", "ac")); + assertTrue(WildcardGlobs.isGlobMatched("a{,?}{,b}", "acb")); + assertFalse(WildcardGlobs.isGlobMatched("a{,?}{,b}", "abc")); + assertFalse(WildcardGlobs.isGlobMatched("a{,?}{,b}", "accb")); + } + + @Test + public void testNum() throws InvalidPatternException { + assertTrue(newGlobExpander().isGlobMatchedNumeric("{1-3}", "1")); + assertTrue(newGlobExpander().isGlobMatchedNumeric("a{1-3}", "a1")); + assertTrue(newGlobExpander().isGlobMatchedNumeric("a{1-3,5}", "a1")); + assertTrue(newGlobExpander().isGlobMatchedNumeric("a{1-3,5}", "a3")); + assertTrue(newGlobExpander().isGlobMatchedNumeric("a{1-3,5}", "a5")); + assertFalse(newGlobExpander().isGlobMatchedNumeric("a{1-3,5}", "a4")); + assertFalse(newGlobExpander().isGlobMatchedNumeric("a{1-3,5}", "a01")); + } + + @Test + public void testNumLeadZero() throws InvalidPatternException { + assertTrue(newGlobExpander().isGlobMatchedNumeric("a{01-03,05}", "a01")); + assertTrue(newGlobExpander().isGlobMatchedNumeric("a{ 01 - 03 , 05 }", "a01")); + assertTrue(newGlobExpander().isGlobMatchedNumeric("a{ 01 - 03 , 05 }", "a02")); + assertTrue(newGlobExpander().isGlobMatchedNumeric("a{ 01 - 03 , 05 }", "a03")); + assertTrue(newGlobExpander().isGlobMatchedNumeric("a{ 01 - 03 , 05 }", "a 05 ")); + assertTrue(newGlobExpander().isGlobMatchedNumeric("a{01-03,05}", "a05")); + assertFalse(newGlobExpander().isGlobMatchedNumeric("a{01-03,05}", "a04")); + assertFalse(newGlobExpander().isGlobMatchedNumeric("a{01-03,05}", "a3")); + } + + @Test + public void testOrder() throws InvalidPatternException { + List<String> result; + result = newGlobExpander().expand("{a,b}"); + assertEquals(result, Arrays.asList("a","b"), "Expansion was "+result); + result = newGlobExpander().expand("{{a},b}"); + assertEquals(result, Arrays.asList("a","b"), "Expansion was "+result); + result = newGlobExpander().expand("{a,b}{1,2}"); + assertEquals(result, Arrays.asList("a1","a2","b1","b2"), "Expansion was "+result); + result = newGlobExpander().expand("{80{8{1,2},90},8000+}"); + assertEquals(result, Arrays.asList("8081","8082","8090","8000+"), "Expansion was "+result); + } + + @Test + public void testQuotes() throws InvalidPatternException { + List<String> result; + SpecialistGlobExpander notSpecial = new SpecialistGlobExpander(true, PhraseTreatment.NOT_A_SPECIAL_CHAR, PhraseTreatment.NOT_A_SPECIAL_CHAR); + result = notSpecial.expand("hello \"{1-3}\""); + assertEquals(3, result.size()); + assertEquals("hello \"1\"", result.get(0)); + + SpecialistGlobExpander expanding = new SpecialistGlobExpander(true, PhraseTreatment.INTERIOR_EXPANDABLE, PhraseTreatment.NOT_A_SPECIAL_CHAR); + result = expanding.expand("hello \"{1-3}\""); + assertEquals(3, result.size()); + assertEquals("hello \"1\"", result.get(0)); + result = expanding.expand("hello \"{1,2-3}\""); + assertEquals(3, result.size()); + assertEquals("hello \"2\"", result.get(1)); + + SpecialistGlobExpander notExpanding = new SpecialistGlobExpander(true, PhraseTreatment.INTERIOR_NOT_EXPANDABLE, PhraseTreatment.NOT_A_SPECIAL_CHAR); + result = notExpanding.expand("hello \"{1,2-3}\""); + assertEquals(1, result.size()); + assertEquals("hello \"{1,2-3}\"", result.get(0)); + + + result = notSpecial.expand("hello {\"1,2,3\"}"); + assertEquals(3, result.size()); + assertEquals("hello \"1", result.get(0)); + + result = expanding.expand("hello {\"1,2,3\"}"); + assertEquals(1, result.size()); + assertEquals("hello \"1,2,3\"", result.get(0)); + + result = notExpanding.expand("hello {\"1,2,3\"}"); + assertEquals(1, result.size()); + assertEquals("hello \"1,2,3\"", result.get(0)); + + + result = notSpecial.expand("hello {\"1,{02-03,04}\"}"); + assertEquals(4, result.size()); + assertEquals("hello \"1", result.get(0)); + assertEquals("hello 03\"", result.get(2)); + + result = expanding.expand("hello {\"1,{02-03,04}\"}"); + assertEquals(3, result.size()); + assertEquals("hello \"1,02\"", result.get(0)); + + result = notExpanding.expand("hello {\"1,{02-03,04}\"}"); + assertEquals(1, result.size()); + assertEquals("hello \"1,{02-03,04}\"", result.get(0)); + + //no exception + notSpecial.expand("{\"}"); + notSpecial.expand("\"{\"}"); + //exceptions + try { + expanding.expand("\""); + fail("exception expected"); + } catch (InvalidPatternException e) { /* expected */ } + try { + expanding.expand("{\"}"); + fail("exception expected"); + } catch (InvalidPatternException e) { /* expected */ } + try { + expanding.expand("\"{\""); + fail("exception expected"); + } catch (InvalidPatternException e) { /* expected */ } + try { + notExpanding.expand("\""); + fail("exception expected"); + } catch (InvalidPatternException e) { /* expected */ } + try { + notExpanding.expand("{\"}"); + fail("exception expected"); + } catch (InvalidPatternException e) { /* expected */ } + //no exception + notExpanding.expand("\"{\""); + } + + @Test + public void testParen() throws InvalidPatternException { + List<String> result; + SpecialistGlobExpander notSpecial = new SpecialistGlobExpander(true, PhraseTreatment.NOT_A_SPECIAL_CHAR, PhraseTreatment.NOT_A_SPECIAL_CHAR); + result = notSpecial.expand("hello ({1-3})"); + assertEquals(3, result.size()); + assertEquals("hello (1)", result.get(0)); + + SpecialistGlobExpander expanding = new SpecialistGlobExpander(true, PhraseTreatment.INTERIOR_NOT_EXPANDABLE, PhraseTreatment.INTERIOR_EXPANDABLE); + result = expanding.expand("hello ({1-3})"); + assertEquals(3, result.size()); + assertEquals("hello (1)", result.get(0)); + result = expanding.expand("hello ({1,2-3})"); + assertEquals(3, result.size()); + assertEquals("hello (2)", result.get(1)); + + SpecialistGlobExpander notExpanding = new SpecialistGlobExpander(true, PhraseTreatment.INTERIOR_EXPANDABLE, PhraseTreatment.INTERIOR_NOT_EXPANDABLE); + result = notExpanding.expand("hello ({1,2-3})"); + assertEquals(1, result.size()); + assertEquals("hello ({1,2-3})", result.get(0)); + + result = notSpecial.expand("hello {(1,2,3)}"); + assertEquals(3, result.size()); + assertEquals("hello (1", result.get(0)); + + result = expanding.expand("hello {(1,2,3)}"); + assertEquals(1, result.size()); + assertEquals("hello (1,2,3)", result.get(0)); + + result = notExpanding.expand("hello {(1,2,3)}"); + assertEquals(1, result.size()); + assertEquals("hello (1,2,3)", result.get(0)); + + + result = notSpecial.expand("hello {(1,{02-03,04})}"); + assertEquals(4, result.size()); + assertEquals("hello (1", result.get(0)); + assertEquals("hello 03)", result.get(2)); + + result = expanding.expand("hello {(1,{02-03,04})}"); + assertEquals(3, result.size()); + assertEquals("hello (1,02)", result.get(0)); + + result = notExpanding.expand("hello {(1,{02-03,04})}"); + assertEquals(1, result.size()); + assertEquals("hello (1,{02-03,04})", result.get(0)); + + try { + notExpanding.expand("{(}"); + fail("exception expected"); + } catch (InvalidPatternException e) { /* expected */ } + try { + notExpanding.expand("(()"); + fail("exception expected"); + } catch (InvalidPatternException e) { /* expected */ } + notExpanding.expand("({())"); + } + + @Test + public void testQuotesAndParen() throws InvalidPatternException { + List<String> result; + SpecialistGlobExpander special = new SpecialistGlobExpander(true, PhraseTreatment.INTERIOR_EXPANDABLE, PhraseTreatment.INTERIOR_NOT_EXPANDABLE); + result = special.expand("\"{hello,goodbye}{1-2,({3-4}),(\")}\""); + assertEquals(8, result.size()); + assertTrue(result.contains("\"goodbye2\"")); + assertTrue(result.contains("\"hello({3-4})\"")); + assertTrue(result.contains("\"goodbye(\")\"")); + } + + private SpecialistGlobExpander newGlobExpander() { + return new SpecialistGlobExpander(true, PhraseTreatment.NOT_A_SPECIAL_CHAR, PhraseTreatment.NOT_A_SPECIAL_CHAR); + } + +} http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/cf2f7a93/utils/common/src/test/java/org/apache/brooklyn/util/time/CountdownTimerTest.java ---------------------------------------------------------------------- diff --git a/utils/common/src/test/java/org/apache/brooklyn/util/time/CountdownTimerTest.java b/utils/common/src/test/java/org/apache/brooklyn/util/time/CountdownTimerTest.java new file mode 100644 index 0000000..5541caa --- /dev/null +++ b/utils/common/src/test/java/org/apache/brooklyn/util/time/CountdownTimerTest.java @@ -0,0 +1,95 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.brooklyn.util.time; + +import static org.testng.Assert.assertFalse; +import static org.testng.Assert.assertTrue; + +import java.util.Arrays; +import java.util.concurrent.Semaphore; +import java.util.concurrent.TimeUnit; + +import org.apache.brooklyn.util.exceptions.Exceptions; +import org.apache.brooklyn.util.time.CountdownTimer; +import org.apache.brooklyn.util.time.Duration; +import org.apache.brooklyn.util.time.Time; +import org.testng.annotations.Test; + +import com.google.common.base.Stopwatch; + +@Test +public class CountdownTimerTest { + + // Test failed on jenkins when using 1 second, sleeping for 500ms; + // hence relaxing time constraints so is less time-sensitive at the expense of being a slower test. + @Test(groups="Integration") + public void testSimpleExpiry() { + final int TOTAL_TIME_MS = 5*1000; + final int OVERHEAD_MS = 2000; + final int EARLY_RETURN_GRACE_MS = 30; + final int FIRST_SLEEP_TIME_MS = 2500; + final int SECOND_SLEEP_TIME_MS = TOTAL_TIME_MS - FIRST_SLEEP_TIME_MS + EARLY_RETURN_GRACE_MS*2; + + final Duration SIMPLE_DURATION = Duration.millis(TOTAL_TIME_MS); + + CountdownTimer timer = SIMPLE_DURATION.countdownTimer(); + assertFalse(timer.isExpired()); + assertTrue(timer.getDurationElapsed().toMilliseconds() <= OVERHEAD_MS, "elapsed="+timer.getDurationElapsed().toMilliseconds()); + assertTrue(timer.getDurationRemaining().toMilliseconds() >= TOTAL_TIME_MS - OVERHEAD_MS, "remaining="+timer.getDurationElapsed().toMilliseconds()); + + Time.sleep(Duration.millis(FIRST_SLEEP_TIME_MS)); + assertFalse(timer.isExpired()); + assertOrdered(FIRST_SLEEP_TIME_MS - EARLY_RETURN_GRACE_MS, timer.getDurationElapsed().toMilliseconds(), FIRST_SLEEP_TIME_MS + OVERHEAD_MS); + assertOrdered(TOTAL_TIME_MS - FIRST_SLEEP_TIME_MS - OVERHEAD_MS, timer.getDurationRemaining().toMilliseconds(), TOTAL_TIME_MS - FIRST_SLEEP_TIME_MS + EARLY_RETURN_GRACE_MS); + + Time.sleep(Duration.millis(SECOND_SLEEP_TIME_MS)); + assertTrue(timer.isExpired()); + } + + public void testNotify() throws InterruptedException { + CountdownTimer timer = Duration.FIVE_SECONDS.countdownTimer(); + final Object mutex = new Object(); + final Semaphore gun = new Semaphore(0); + Stopwatch watch = Stopwatch.createStarted(); + new Thread(new Runnable() { + @Override + public void run() { + try { gun.acquire(); } catch (Exception e) { throw Exceptions.propagate(e); } + synchronized (mutex) { + mutex.notifyAll(); + } + } + }).start(); + synchronized (mutex) { + gun.release(); + assertTrue(timer.waitOnForExpiry(mutex)); + } + assertTrue(watch.elapsed(TimeUnit.MILLISECONDS) < 3000, "took too long: "+watch); + } + + private void assertOrdered(long... vals) { + String errmsg = "vals="+Arrays.toString(vals); + long prevVal = Long.MIN_VALUE; + for (long val : vals) { + assertTrue(val >= prevVal, errmsg); + prevVal = val; + } + } + +} http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/cf2f7a93/utils/common/src/test/java/org/apache/brooklyn/util/time/DurationTest.java ---------------------------------------------------------------------- diff --git a/utils/common/src/test/java/org/apache/brooklyn/util/time/DurationTest.java b/utils/common/src/test/java/org/apache/brooklyn/util/time/DurationTest.java new file mode 100644 index 0000000..1296f46 --- /dev/null +++ b/utils/common/src/test/java/org/apache/brooklyn/util/time/DurationTest.java @@ -0,0 +1,108 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.brooklyn.util.time; + +import java.util.concurrent.TimeUnit; + +import org.apache.brooklyn.util.time.Duration; +import org.testng.Assert; +import org.testng.annotations.Test; + +@Test +public class DurationTest { + + public void testMinutes() { + Assert.assertEquals(3*60*1000, new Duration(3, TimeUnit.MINUTES).toMilliseconds()); + } + + public void testAdd() { + Assert.assertEquals((((4*60+3)*60)+30)*1000, + new Duration(3, TimeUnit.MINUTES). + add(new Duration(4, TimeUnit.HOURS)). + add(new Duration(30, TimeUnit.SECONDS)). + toMilliseconds()); + } + + public void testStatics() { + Assert.assertEquals((((4*60+3)*60)+30)*1000, + Duration.ONE_MINUTE.times(3). + add(Duration.ONE_HOUR.times(4)). + add(Duration.THIRTY_SECONDS). + toMilliseconds()); + } + + public void testParse() { + Assert.assertEquals((((4*60+3)*60)+30)*1000, + Duration.of("4h 3m 30s").toMilliseconds()); + } + + public void testConvesion() { + Assert.assertEquals(1, Duration.nanos(1).toNanoseconds()); + Assert.assertEquals(1, Duration.nanos(1.1).toNanoseconds()); + Assert.assertEquals(1, Duration.millis(1).toMilliseconds()); + Assert.assertEquals(1, Duration.millis(1.0).toMilliseconds()); + Assert.assertEquals(1, Duration.millis(1.1).toMilliseconds()); + Assert.assertEquals(1100000, Duration.millis(1.1).toNanoseconds()); + Assert.assertEquals(500, Duration.seconds(0.5).toMilliseconds()); + } + + public void testToString() { + Assert.assertEquals("4h 3m 30s", + Duration.of("4h 3m 30s").toString()); + } + + public void testToStringRounded() { + Assert.assertEquals("4h 3m", + Duration.of("4h 3m 30s").toStringRounded()); + } + + public void testParseToString() { + Assert.assertEquals(Duration.of("4h 3m 30s"), + Duration.parse(Duration.of("4h 3m 30s").toString())); + } + + public void testRoundUp() { + Assert.assertEquals(Duration.nanos(1).toMillisecondsRoundingUp(), 1); + } + + public void testRoundZero() { + Assert.assertEquals(Duration.ZERO.toMillisecondsRoundingUp(), 0); + } + + public void testRoundUpNegative() { + Assert.assertEquals(Duration.nanos(-1).toMillisecondsRoundingUp(), -1); + } + + public void testNotRounding() { + Assert.assertEquals(Duration.nanos(-1).toMilliseconds(), 0); + } + + public void testNotRoundingNegative() { + Assert.assertEquals(Duration.nanos(-1).toMillisecondsRoundingUp(), -1); + } + + public void testComparison() { + Assert.assertTrue(Duration.seconds(1.8).isLongerThan(Duration.millis(1600))); + Assert.assertTrue(Duration.millis(1600).isShorterThan(Duration.seconds(1.8))); + + Assert.assertTrue(Duration.seconds(1).isLongerThan(Duration.ZERO)); + Assert.assertFalse(Duration.seconds(-1).isLongerThan(Duration.ZERO)); + } + +} http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/cf2f7a93/utils/common/src/test/java/org/apache/brooklyn/util/time/TimeTest.java ---------------------------------------------------------------------- diff --git a/utils/common/src/test/java/org/apache/brooklyn/util/time/TimeTest.java b/utils/common/src/test/java/org/apache/brooklyn/util/time/TimeTest.java new file mode 100644 index 0000000..2cce436 --- /dev/null +++ b/utils/common/src/test/java/org/apache/brooklyn/util/time/TimeTest.java @@ -0,0 +1,340 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.brooklyn.util.time; + +import java.util.Date; +import java.util.TimeZone; + +import org.apache.brooklyn.util.time.Duration; +import org.apache.brooklyn.util.time.Time; +import org.testng.Assert; +import org.testng.annotations.Test; + +@Test +public class TimeTest { + + public void testMakeStringExact_secondsAndMillis() { + check(1, "1ms"); + check(1000, "1s"); + check(1001, "1s 1ms"); + check(1011, "1s 11ms"); + check(3*1000, "3s"); + check(3*1000+1, "3s 1ms"); + check(3*1000+10, "3s 10ms"); + check(3*1000+100, "3s 100ms"); + check(30*1000, "30s"); + check(30*1000+1, "30s 1ms"); + check(30*1000+100, "30s 100ms"); + } + + public void testMakeStringRounded_secondsAndMillis() { + checkR(1, "1ms"); + checkR(1000, "1s"); + checkR(1001, "1.00s"); + checkR(1011, "1.01s"); + checkR(3*1000, "3s"); + checkR(3*1000+1, "3.00s"); + checkR(3*1000+10, "3.01s"); + checkR(3*1000+100, "3.10s"); + checkR(30*1000, "30s"); + checkR(30*1000+1, "30.0s"); + checkR(30*1000+10, "30.0s"); + checkR(30*1000+100, "30.1s"); + } + + public void testMakeStringExact_days() { + check(3*Time.MILLIS_IN_DAY, "3d"); + check(3*Time.MILLIS_IN_DAY + 2*Time.MILLIS_IN_HOUR + 30*Time.MILLIS_IN_MINUTE + 1001, "3d 2h 30m 1s 1ms"); + } + + public void testMakeStringRounded_days() { + checkR(3*Time.MILLIS_IN_DAY, "3d"); + checkR(3*Time.MILLIS_IN_DAY + 2*Time.MILLIS_IN_HOUR + 30*Time.MILLIS_IN_MINUTE + 1001, "3d 2h"); + checkR(3*Time.MILLIS_IN_DAY + 30*Time.MILLIS_IN_MINUTE + 1001, "3d 30m"); + checkR(3*Time.MILLIS_IN_DAY + 1001, "3d"); + + checkR(30*Time.MILLIS_IN_MINUTE + 1111, "30m 1s"); + } + + public void testMakeStringExact_nanos() { + checkN(1001, "1us 1ns"); + checkN(123000+456, "123us 456ns"); + checkN(3*Time.MILLIS_IN_DAY*1000*1000, "3d"); + checkN(3*Time.MILLIS_IN_DAY*1000*1000 + 1, "3d 1ns"); + checkN(3*Time.MILLIS_IN_DAY*1000*1000 + 1001, "3d 1us 1ns"); + checkN((3*Time.MILLIS_IN_DAY + 2*Time.MILLIS_IN_HOUR + 30*Time.MILLIS_IN_MINUTE + 1001)*1000*1000+123000+456, + "3d 2h 30m 1s 1ms 123us 456ns"); + } + + public void testMakeStringRounded_nanos() { + checkRN(3*Time.MILLIS_IN_DAY*1000*1000, "3d"); + checkRN((3*Time.MILLIS_IN_DAY + 2*Time.MILLIS_IN_HOUR + 30*Time.MILLIS_IN_MINUTE + 1001)*1000*1000+1001, "3d 2h"); + checkRN((3*Time.MILLIS_IN_DAY + 30*Time.MILLIS_IN_MINUTE + 1001)*1000*1000+1001, "3d 30m"); + checkRN((3*Time.MILLIS_IN_DAY + 1001)*1000*1000+1001, "3d"); + + checkRN((30*Time.MILLIS_IN_MINUTE + 1111)*1000*1000+1001, "30m 1s"); + checkRN((30*Time.MILLIS_IN_MINUTE)*1000*1000+1001, "30m"); + checkRN((31000L)*1000*1000, "31s"); + checkRN((31000L)*1000*1000+1001, "31.0s"); + checkRN(1001, "1.001us"); + checkRN(10101, "10.10us"); + checkRN(101001, "101.0us"); + checkRN(123000+456, "123.5us"); + } + + + private void check(long millis, String expected) { + Assert.assertEquals(Time.makeTimeStringExact(millis), expected); + } + + private void checkR(long millis, String expected) { + Assert.assertEquals(Time.makeTimeStringRounded(millis), expected); + } + + private void checkN(long nanos, String expected) { + Assert.assertEquals(Time.makeTimeStringNanoExact(nanos), expected); + } + + private void checkRN(long nanos, String expected) { + Assert.assertEquals(Time.makeTimeStringNanoRounded(nanos), expected); + } + + @Test + public void testDateRounding() { + long x = System.currentTimeMillis(); + Date d1 = Time.dropMilliseconds(new Date(x)); + Date d2 = new Date(x - (x%1000)); + Date d3 = new Date( (x/1000)*1000 ); + Assert.assertEquals(d1.getTime() % 1000, 0); + Assert.assertEquals(d1, d2); + Assert.assertEquals(d1, d3); + } + + @Test + public void testDateRoundingNull() { + Assert.assertNull(Time.dropMilliseconds(null)); + } + + @Test + public void testMakeStringExactZero() { check(0, "0ms"); } + @Test + public void testMakeStringExactNegative() { check(-1, "-1ms"); } + @Test + public void testMakeStringRoundedZero() { checkR(0, "0ms"); } + @Test + public void testMakeStringRoundedNegative() { checkR(-1, "-1ms"); } + + @Test + public void testElapsedSince() { + long aFewSecondsAgo = System.currentTimeMillis() - 7*1000; + + Duration aFewSeconds = Time.elapsedSince(aFewSecondsAgo); + Assert.assertTrue(aFewSeconds.toMilliseconds() > 5*1000); + Assert.assertTrue(10*1000 > aFewSeconds.toMilliseconds()); + + Assert.assertTrue(Time.hasElapsedSince(aFewSecondsAgo, Duration.FIVE_SECONDS)); + Assert.assertFalse(Time.hasElapsedSince(aFewSecondsAgo, Duration.TEN_SECONDS)); + Assert.assertTrue(Time.hasElapsedSince(-1, Duration.TEN_SECONDS)); + } + + @Test + public void testMakeDateString() { + String in1 = "2015-06-15T12:34:56"; + Date d1 = Time.parseDate(in1); + Assert.assertEquals(Time.makeDateString(d1), in1.replace('T', ' ')+".000"); + + String in2 = "2015-06-15T12:34:56Z"; + Date d2 = Time.parseDate(in2); + Assert.assertEquals(Time.makeDateString(d2, Time.DATE_FORMAT_ISO8601, Time.getTimeZone("UTC")), in1+".000+0000"); + } + + @Test(groups="Integration") //because it depends on TZ's set up and parsing months + public void testTimeZones() { + // useful to debug, if new special time zones needed +// for (String id: TimeZone.getAvailableIDs()) { +// TimeZone tz = TimeZone.getTimeZone(id); +// System.out.println(id+": "+tz.getDisplayName()+" "+tz.getDisplayName(true, TimeZone.SHORT)+" "+tz); +// } + + Assert.assertEquals("+0100", Time.getTimeZoneOffsetString("Europe/London", 2015, 6, 4).get()); + + Assert.assertEquals("-0500", Time.getTimeZoneOffsetString("EST", 2015, 1, 4).get()); + Assert.assertEquals("-0400", Time.getTimeZoneOffsetString("America/New_York", 2015, 6, 4).get()); + Assert.assertEquals("-0500", Time.getTimeZoneOffsetString("America/New_York", 2015, 1, 4).get()); + + // BST treated as British Time (not Bangladesh) + Assert.assertEquals("+0000", Time.getTimeZoneOffsetString("BST", 2015, 1, 4).get()); + Assert.assertEquals("+0100", Time.getTimeZoneOffsetString("BST", 2015, 6, 4).get()); + + // EST treated as EDT not fixed -0500 + Assert.assertEquals("-0400", Time.getTimeZoneOffsetString("EST", 2015, 6, 4).get()); + + // these normally not recognized + Assert.assertEquals("-0400", Time.getTimeZoneOffsetString("EDT", 2015, 6, 4).get()); + Assert.assertEquals("-0500", Time.getTimeZoneOffsetString("EDT", 2015, 1, 4).get()); + + Assert.assertEquals("-0600", Time.getTimeZoneOffsetString("CST", 2015, 1, 4).get()); + Assert.assertEquals("-0700", Time.getTimeZoneOffsetString("MST", 2015, 1, 4).get()); + Assert.assertEquals("-0800", Time.getTimeZoneOffsetString("PST", 2015, 1, 4).get()); + + Assert.assertEquals("+0530", Time.getTimeZoneOffsetString("IST", 2015, 1, 4).get()); + } + + @Test + public void testParseDate() { + doTestParseDate(false); + } + + @Test(groups="Integration") //because it depends on TZ's set up and parsing months + public void testParseDateIntegration() { + doTestParseDate(true); + } + + private void doTestParseDate(boolean integration) { + // explicit TZ inclusion + assertDatesParseToEqual("2015.6.4.0000 +0100", "2015-06-04-0000 +0100"); + assertDatesParseToEqual("2015.6.4.0100 +0100", "2015-06-04-0000 +0000"); + assertDatesParseToEqual("2015.6.4.0100 -0100", "2015-06-04-0200 +0000"); + if (integration) assertDatesParseToEqual("20150604 BST", "2015-06-04 +0100"); + + // no TZ uses server default + assertDatesParseToEqual("2015.6.4.0000", "2015-06-04-0000 "+Time.getTimeZoneOffsetString(TimeZone.getDefault(), 2015, 6, 4)); + assertDatesParseToEqual("20150604", "2015-06-04-0000"); + + // parse TZ + if (integration) { + assertDatesParseToEqual("20150604 +BST", "2015-06-04 +0100"); + assertDatesParseToEqual("20150604 - - - BST", "2015-06-04 +0100"); + assertDatesParseToEqual("20150604--BST", "2015-06-04 +0100"); + assertDatesParseToEqual("20150604-//-BST", "2015-06-04 +0100"); + } + assertDatesParseToEqual("2015.6.4+0100", "2015-06-04-0000+0100"); + assertDatesParseToEqual("20150604-+0100", "2015-06-04 +0100"); + assertDatesParseToEqual("20150604, +0100", "2015-06-04 +0100"); + assertDatesParseToEqual("201506040000, 0100", "2015-06-04 +0100"); + assertDatesParseToEqual("20150604 , 0000 , 0100", "2015-06-04 +0100"); + assertDatesParseToEqual("2015-6-4 +0100", "2015-06-04-0000 +0100"); + assertDatesParseToEqual("2015-6-4 -0100", "2015-06-04-0000 -0100"); + assertDatesParseToEqual("20150604-0000//-0100", "2015-06-04 -0100"); + // ambiguous TZ/hours parse prefers hours + assertDatesParseToEqual("2015-6-4-0100", "2015-06-04-0100"); + assertDatesParseToEqual("2015-6-4--0100", "2015-06-04-0100"); + + // formats without spaces + assertDatesParseToEqual("20150604080012", "2015-06-04-080012"); + assertDatesParseToEqual("20150604080012 +1000", "2015-06-03-220012 +0000"); + assertDatesParseToEqual("20150604080012 -1000", "2015-06-04-180012 +0000"); + assertDatesParseToEqual("20150604080012.345 +1000", "2015-06-03-220012.345 +0000"); + if (integration) { + assertDatesParseToEqual("20150604 BST", "2015-06-04 +0100"); + assertDatesParseToEqual("20150604 Europe/London", "2015-06-04 +0100"); + } + + // more misc tests + assertDatesParseToEqual("20150604 08:00:12.345", "2015-06-04-080012.345"); + assertDatesParseToEqual("20150604-080012.345", "2015-06-04-080012.345"); + assertDatesParseToEqual("2015-12-1", "2015-12-01-0000"); + assertDatesParseToEqual("1066-12-1", "1066-12-01-0000"); + + assertDatesParseToEqual("20150604T080012.345", "2015-06-04-080012.345"); + assertDatesParseToEqual("20150604T080012.345Z", "2015-06-04-080012.345+0000"); + assertDatesParseToEqual("20150604t080012.345 Z", "2015-06-04-080012.345+0000"); + + // millis parse, and zero is epoch, but numbers which look like a date or datetime take priority + assertDatesParseToEqual("0", "1970-1-1 UTC"); + assertDatesParseToEqual("20150604", "2015-06-04"); + assertDatesParseToEqual(""+Time.parseDate("20150604").getTime(), "2015-06-04"); + assertDatesParseToEqual("20150604080012", "2015-06-04-080012"); + assertDatesParseToEqual("0", "1970-1-1 UTC"); + + // leap year + Assert.assertEquals(Time.parseDate("2012-2-29").getTime(), Time.parseDate("2012-3-1").getTime() - 24*60*60*1000); + // perverse, but accepted for the time being: + Assert.assertEquals(Time.parseDate("2013-2-29").getTime(), Time.parseDate("2013-3-1").getTime()); + + // accept am and pm + assertDatesParseToEqual("20150604 08:00:12.345a", "2015-06-04-080012.345"); + assertDatesParseToEqual("20150604 08:00:12.345 PM", "2015-06-04-200012.345"); + if (integration) assertDatesParseToEqual("20150604 08:00:12.345 am BST", "2015-06-04-080012.345 +0100"); + + // *calendar* parse includes time zone + Assert.assertEquals(Time.makeDateString(Time.parseCalendar("20150604 08:00:12.345a +0100"), + Time.DATE_FORMAT_ISO8601), "2015-06-04T08:00:12.345+0100"); + Assert.assertEquals(Time.makeDateString(Time.parseCalendar("20150604 08:00:12.345a "+Time.TIME_ZONE_UTC.getID()), + Time.DATE_FORMAT_ISO8601), "2015-06-04T08:00:12.345+0000"); + + // accept month in words + if (integration) { + assertDatesParseToEqual("2015-Dec-1", "2015-12-01-0000"); + assertDatesParseToEqual("2015 Dec 1", "2015-12-01-0000"); + assertDatesParseToEqual("2015-DEC-1", "2015-12-01-0000"); + assertDatesParseToEqual("2015 December 1", "2015-12-01-0000"); + assertDatesParseToEqual("2015 December 1", "2015-12-01-0000"); + assertDatesParseToEqual("2015-Mar-1", "2015-03-01-0000"); + assertDatesParseToEqual("2015 Mar 1", "2015-03-01-0000"); + assertDatesParseToEqual("2015-MAR-1", "2015-03-01-0000"); + assertDatesParseToEqual("2015 March 1", "2015-03-01-0000"); + assertDatesParseToEqual("2015 March 1", "2015-03-01-0000"); + } + + // for month in words, allow selected other orders also + if (integration) { + assertDatesParseToEqual("1-Jun-2015", "2015-06-01-0000"); + assertDatesParseToEqual("Jun 1, 2015", "2015-06-01-0000"); + assertDatesParseToEqual("June 1, 2015, 4pm", "2015-06-01-1600"); + } + + // also allow time first if separators are used + assertDatesParseToEqual("16:00, 2015-12-30", "2015-12-30-1600"); + if (integration) { + assertDatesParseToEqual("4pm, Dec 1, 2015", "2015-12-01-1600"); + assertDatesParseToEqual("16:00 30-Dec-2015", "2015-12-30-1600"); + } + + // and if time comes first, TZ can be before or after date + assertDatesParseToEqual("4pm +0100, 2015-12-30", "2015-12-30-1600 +0100"); + assertDatesParseToEqual("4pm, 2015-12-30, +0100", "2015-12-30-1600 +0100"); + + // these ambiguous ones are accepted (maybe we'd rather not), + // but they are interpreted sensibly, preferring the more sensible interpretation + if (integration) assertDatesParseToEqual("16 Dec 1 2015", "2015-12-01-1600"); + if (integration) assertDatesParseToEqual("16:30 1067 Dec 1 1066", "1067-12-01-1630 +1066"); + assertDatesParseToEqual("1040 1045 12 1", "1045-12-01-1040"); + assertDatesParseToEqual("1040 1045 12 1 +0", "1045-12-01-1040Z"); + if (integration) assertDatesParseToEqual("1045 Dec 1 1040", "1045-12-01-1040"); + if (integration) assertDatesParseToEqual("10:40 Dec 1 1045", "1045-12-01-1040"); + assertDatesParseToEqual("10.11-2020-12.01", "2020-12-01-1011"); + if (integration) assertDatesParseToEqual("Oct.11 1045 12.01", "1045-10-11-1201"); + if (integration) assertDatesParseToEqual("1040 1045 Dec 1 1030", "1045-12-01-1040 +1030"); + assertDatesParseToEqual("1040 +02 2015 12 1", "2015-12-01-1040 +0200"); + assertDatesParseToEqual("10:40:+02 2015 12 1", "2015-12-01-1040 +0200"); + } + + @Test + public void testParseDateToStringWithMillisecond() { + Date d = new Date(); + // clear seconds, but add a milli - to ensure not just toString formatting but also seconds computation + d.setTime(d.getTime() - (d.getTime() % 60000) + 1); + assertDatesParseToEqual(d.toString(), Time.makeDateStampString(d.getTime())); + } + + private void assertDatesParseToEqual(String input, String expected) { + Assert.assertEquals(Time.parseDate(input).toString(), Time.parseDate(expected).toString(), "for: "+input+" ("+expected+")"); + } +} http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/cf2f7a93/utils/common/src/test/java/org/apache/brooklyn/util/yaml/YamlsTest.java ---------------------------------------------------------------------- diff --git a/utils/common/src/test/java/org/apache/brooklyn/util/yaml/YamlsTest.java b/utils/common/src/test/java/org/apache/brooklyn/util/yaml/YamlsTest.java new file mode 100644 index 0000000..bd701d5 --- /dev/null +++ b/utils/common/src/test/java/org/apache/brooklyn/util/yaml/YamlsTest.java @@ -0,0 +1,195 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.brooklyn.util.yaml; + +import static org.testng.Assert.assertEquals; + +import java.util.Iterator; +import java.util.List; + +import org.apache.brooklyn.util.collections.MutableList; +import org.apache.brooklyn.util.exceptions.UserFacingException; +import org.apache.brooklyn.util.yaml.Yamls; +import org.apache.brooklyn.util.yaml.YamlsTest; +import org.apache.brooklyn.util.yaml.Yamls.YamlExtract; +import org.testng.Assert; +import org.testng.TestNG; +import org.testng.annotations.Test; + +import com.google.common.collect.ImmutableList; +import com.google.common.collect.ImmutableMap; + +public class YamlsTest { + + @Test + public void testGetAs() throws Exception { + MutableList<String> list = MutableList.of("x"); + assertEquals(Yamls.getAs(list.iterator(), List.class), list); + assertEquals(Yamls.getAs(list.iterator(), Iterable.class), list); + assertEquals(Yamls.getAs(list.iterator(), Iterator.class), list.iterator()); + assertEquals(Yamls.getAs(list.iterator(), String.class), "x"); + } + + @Test + public void testGetAt() throws Exception { + // leaf of map + assertEquals(Yamls.getAt("k1: v", ImmutableList.of("k1")), "v"); + assertEquals(Yamls.getAt("k1: {k2: v}", ImmutableList.of("k1", "k2")), "v"); + + // get list + assertEquals(Yamls.getAt("k1: [v1, v2]", ImmutableList.<String>of("k1")), ImmutableList.of("v1", "v2")); + + // get map + assertEquals(Yamls.getAt("k1: v", ImmutableList.<String>of()), ImmutableMap.of("k1", "v")); + assertEquals(Yamls.getAt("k1: {k2: v}", ImmutableList.of("k1")), ImmutableMap.of("k2", "v")); + + // get array index + assertEquals(Yamls.getAt("k1: [v1, v2]", ImmutableList.<String>of("k1", "[0]")), "v1"); + assertEquals(Yamls.getAt("k1: [v1, v2]", ImmutableList.<String>of("k1", "[1]")), "v2"); + } + + + @Test + public void testExtractMap() { + String sample = "#before\nk1:\n- v1\nk2:\n # comment\n k21: v21\nk3: v3\n#after\n"; + + Assert.assertEquals(Yamls.getTextOfYamlAtPath(sample, "k1").withKeyIncluded(true).getMatchedYamlText(), + sample.substring(0, sample.indexOf("k2"))); + Assert.assertEquals(Yamls.getTextOfYamlAtPath(sample, "k3").withKeyIncluded(true).getMatchedYamlText(), + sample.substring(sample.indexOf("k3"))); + + // comments and no key, outdented - the default + Assert.assertEquals(Yamls.getTextOfYamlAtPath(sample, "k2", "k21").getMatchedYamlText(), + "# comment\nv21"); + Assert.assertEquals(Yamls.getTextOfYamlAtPath(sample, "k2", "k21").getMatchedYamlText(), + "# comment\nv21"); + // comments and key + Assert.assertEquals(Yamls.getTextOfYamlAtPath(sample, "k2", "k21").withKeyIncluded(true).getMatchedYamlText(), + "# comment\nk21: v21"); + // no comments + Assert.assertEquals(Yamls.getTextOfYamlAtPath(sample, "k2", "k21").withKeyIncluded(true).withPrecedingCommentsIncluded(false).getMatchedYamlText(), + "k21: v21"); + // no comments and no key + Assert.assertEquals(Yamls.getTextOfYamlAtPath(sample, "k2", "k21").withPrecedingCommentsIncluded(false).getMatchedYamlText(), + "v21"); + + // comments and no key, not outdented + Assert.assertEquals(Yamls.getTextOfYamlAtPath(sample, "k2", "k21").withOriginalIndentation(true).getMatchedYamlText(), + " # comment\n v21"); + // comments and key + Assert.assertEquals(Yamls.getTextOfYamlAtPath(sample, "k2", "k21").withKeyIncluded(true).withOriginalIndentation(true).getMatchedYamlText(), + " # comment\n k21: v21"); + // no comments + Assert.assertEquals(Yamls.getTextOfYamlAtPath(sample, "k2", "k21").withKeyIncluded(true).withPrecedingCommentsIncluded(false).withOriginalIndentation(true).getMatchedYamlText(), + " k21: v21"); + // no comments and no key + Assert.assertEquals(Yamls.getTextOfYamlAtPath(sample, "k2", "k21").withPrecedingCommentsIncluded(false).withOriginalIndentation(true).getMatchedYamlText(), + " v21"); + } + + @Test + public void testExtractInList() { + String sample = + "- a\n" + + "- b: 2\n" + + "- # c\n" + + " c1:\n" + + " 1\n" + + " c2:\n" + + " 2\n" + + "-\n" + + " - a # for a\n" + + " # for b\n" + + " - b\n"; + + Assert.assertEquals(Yamls.getTextOfYamlAtPath(sample, 0).getMatchedYamlText(), "a"); + Assert.assertEquals(Yamls.getTextOfYamlAtPath(sample, 1, "b").getMatchedYamlText(), "2"); + Assert.assertEquals(Yamls.getTextOfYamlAtPath(sample, 3, 0).getMatchedYamlText(), + "a" + // TODO comments after on same line not yet included - would be nice to add +// "a # for a" + ); + + // out-dent + Assert.assertEquals(Yamls.getTextOfYamlAtPath(sample, 2).getMatchedYamlText(), "c1:\n 1\nc2:\n 2\n"); + // don't outdent + Assert.assertEquals(Yamls.getTextOfYamlAtPath(sample, 2).withOriginalIndentation(true).getMatchedYamlText(), " c1:\n 1\n c2:\n 2\n"); + Assert.assertEquals(Yamls.getTextOfYamlAtPath(sample, 3, 0).withOriginalIndentation(true).getMatchedYamlText(), + " a" + // as above, comments after not included +// " a # for a" + ); + + // with preceding comments + // TODO final item includes newline (and comments) after - this behaviour might change, it's inconsistent, + // but it means the final comments aren't lost + Assert.assertEquals(Yamls.getTextOfYamlAtPath(sample, 3, 1).getMatchedYamlText(), "# for b\nb\n"); + + // exclude preceding comments + Assert.assertEquals(Yamls.getTextOfYamlAtPath(sample, 3, 1).withPrecedingCommentsIncluded(false).getMatchedYamlText(), "b\n"); + } + + @Test + public void testExtractMapIgnoringPreviousComments() { + String sample = "a: 1 # one\n" + + "b: 2 # two"; + Assert.assertEquals(Yamls.getTextOfYamlAtPath(sample, "b").getMatchedYamlText(), + "2 # two"); + } + + @Test + public void testExtractMapWithOddWhitespace() { + Assert.assertEquals(Yamls.getTextOfYamlAtPath("x: a\n bc", "x").getMatchedYamlText(), + "a\n bc"); + } + + @Test + public void testReplace() { + Assert.assertEquals(Yamls.getTextOfYamlAtPath("x: a\n bc", "x").getFullYamlTextWithExtractReplaced("\nc: 1\nd: 2"), + "x: \n c: 1\n d: 2"); + } + + @Test + public void testExtractNoOOBE() { + // this might log a warning, as item not found, but won't throw + YamlExtract r1 = Yamls.getTextOfYamlAtPath( + "items:\n- id: sample2\n itemType: location\n item:\n type: jclouds:aws-ec2\n brooklyn.config:\n key2: value2\n\n", + "item"); + + // won't throw + r1.getMatchedYamlTextOrWarn(); + // will throw + try { + r1.getMatchedYamlText(); + Assert.fail(); + } catch (UserFacingException e) { + // expected, it should give a vaguely explanatory exception and no trace + } + } + + // convenience, since running with older TestNG IDE plugin will fail (older snakeyaml dependency); + // if you run as a java app it doesn't bring in the IDE TestNG jar version, and it works + public static void main(String[] args) { + TestNG testng = new TestNG(); + testng.setTestClasses(new Class[] { YamlsTest.class }); +// testng.setVerbose(9); + testng.run(); + } + +} http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/cf2f7a93/utils/groovy/src/main/java/brooklyn/util/GroovyJavaMethods.groovy ---------------------------------------------------------------------- diff --git a/utils/groovy/src/main/java/brooklyn/util/GroovyJavaMethods.groovy b/utils/groovy/src/main/java/brooklyn/util/GroovyJavaMethods.groovy index 199f6a5..a62ba87 100644 --- a/utils/groovy/src/main/java/brooklyn/util/GroovyJavaMethods.groovy +++ b/utils/groovy/src/main/java/brooklyn/util/GroovyJavaMethods.groovy @@ -22,7 +22,7 @@ import static brooklyn.util.GroovyJavaMethods.truth import java.util.concurrent.Callable -import brooklyn.util.concurrent.CallableFromRunnable; +import org.apache.brooklyn.util.concurrent.CallableFromRunnable; import com.google.common.base.Function import com.google.common.base.Predicate http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/cf2f7a93/utils/groovy/src/main/java/brooklyn/util/internal/LanguageUtils.groovy ---------------------------------------------------------------------- diff --git a/utils/groovy/src/main/java/brooklyn/util/internal/LanguageUtils.groovy b/utils/groovy/src/main/java/brooklyn/util/internal/LanguageUtils.groovy index d59387c..579f23d 100644 --- a/utils/groovy/src/main/java/brooklyn/util/internal/LanguageUtils.groovy +++ b/utils/groovy/src/main/java/brooklyn/util/internal/LanguageUtils.groovy @@ -24,8 +24,8 @@ import java.lang.reflect.Modifier import java.util.Collection; import java.util.concurrent.atomic.AtomicLong -import brooklyn.util.javalang.Reflections; -import brooklyn.util.text.Identifiers +import org.apache.brooklyn.util.javalang.Reflections; +import org.apache.brooklyn.util.text.Identifiers import com.google.common.annotations.Beta import com.google.common.base.Function; http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/cf2f7a93/utils/groovy/src/main/java/brooklyn/util/internal/TimeExtras.groovy ---------------------------------------------------------------------- diff --git a/utils/groovy/src/main/java/brooklyn/util/internal/TimeExtras.groovy b/utils/groovy/src/main/java/brooklyn/util/internal/TimeExtras.groovy index 09fa5ff..1cf9f07 100644 --- a/utils/groovy/src/main/java/brooklyn/util/internal/TimeExtras.groovy +++ b/utils/groovy/src/main/java/brooklyn/util/internal/TimeExtras.groovy @@ -25,7 +25,7 @@ import java.util.concurrent.TimeUnit import org.slf4j.Logger import org.slf4j.LoggerFactory -import brooklyn.util.time.Time +import org.apache.brooklyn.util.time.Time /** http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/cf2f7a93/utils/jmx/jmxmp-ssl-agent/src/test/java/brooklyn/util/jmx/jmxmp/JmxmpClient.java ---------------------------------------------------------------------- diff --git a/utils/jmx/jmxmp-ssl-agent/src/test/java/brooklyn/util/jmx/jmxmp/JmxmpClient.java b/utils/jmx/jmxmp-ssl-agent/src/test/java/brooklyn/util/jmx/jmxmp/JmxmpClient.java index 3896631..dbad7b8 100644 --- a/utils/jmx/jmxmp-ssl-agent/src/test/java/brooklyn/util/jmx/jmxmp/JmxmpClient.java +++ b/utils/jmx/jmxmp-ssl-agent/src/test/java/brooklyn/util/jmx/jmxmp/JmxmpClient.java @@ -41,8 +41,7 @@ import javax.net.ssl.SSLSocketFactory; import javax.net.ssl.TrustManager; import org.apache.brooklyn.core.util.crypto.SecureKeys; - -import brooklyn.util.crypto.SslTrustUtils; +import org.apache.brooklyn.util.crypto.SslTrustUtils; @SuppressWarnings({"rawtypes","unchecked"}) public class JmxmpClient {
