http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/cf2f7a93/utils/common/src/test/java/org/apache/brooklyn/util/internal/CommandLineUtilTest.java ---------------------------------------------------------------------- diff --git a/utils/common/src/test/java/org/apache/brooklyn/util/internal/CommandLineUtilTest.java b/utils/common/src/test/java/org/apache/brooklyn/util/internal/CommandLineUtilTest.java new file mode 100644 index 0000000..811e636 --- /dev/null +++ b/utils/common/src/test/java/org/apache/brooklyn/util/internal/CommandLineUtilTest.java @@ -0,0 +1,64 @@ +/* + * 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.internal; + +import static org.testng.Assert.assertEquals; + +import java.util.Arrays; +import java.util.List; + +import org.apache.brooklyn.util.CommandLineUtil; +import org.testng.annotations.Test; + +import com.google.common.collect.Lists; + +public class CommandLineUtilTest { + + @Test + public void testGetCommandReturnsDefaultIfNotPresent() throws Exception { + List<String> args = Lists.newArrayList("k1", "v1"); + String result = CommandLineUtil.getCommandLineOption(args, "notthere", "mydefault"); + assertEquals(result, "mydefault"); + assertEquals(args, Arrays.asList("k1", "v1")); + } + + @Test + public void testGetCommandReturnsParamAndRemovesIt() throws Exception { + List<String> args = Lists.newArrayList("k1", "v1"); + String result = CommandLineUtil.getCommandLineOption(args, "k1"); + assertEquals(result, "v1"); + assertEquals(args, Arrays.asList()); + } + + @Test + public void testGetCommandReturnsParamAndRemovesItButLeavesOtherVals() throws Exception { + List<String> args = Lists.newArrayList("k1", "v1", "k2", "v2"); + String result = CommandLineUtil.getCommandLineOption(args, "k1"); + assertEquals(result, "v1"); + assertEquals(args, Arrays.asList("k2", "v2")); + } + + @Test + public void testGetCommandReturnsParamAndRemovesItButLeavesOtherValsWhenDuplicateVals() throws Exception { + List<String> args = Lists.newArrayList("k1", "vdup", "k2", "v2", "k3", "vdup"); + String result = CommandLineUtil.getCommandLineOption(args, "k3"); + assertEquals(result, "vdup"); + assertEquals(args, Arrays.asList("k1", "vdup", "k2", "v2")); + } +}
http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/cf2f7a93/utils/common/src/test/java/org/apache/brooklyn/util/internal/JavaClassNamesCallerTest.java ---------------------------------------------------------------------- diff --git a/utils/common/src/test/java/org/apache/brooklyn/util/internal/JavaClassNamesCallerTest.java b/utils/common/src/test/java/org/apache/brooklyn/util/internal/JavaClassNamesCallerTest.java new file mode 100644 index 0000000..93da625 --- /dev/null +++ b/utils/common/src/test/java/org/apache/brooklyn/util/internal/JavaClassNamesCallerTest.java @@ -0,0 +1,45 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.brooklyn.util.internal; + +import org.apache.brooklyn.util.javalang.JavaClassNames; +import org.testng.Assert; +import org.testng.annotations.Test; + +/** test must not be in {@link JavaClassNames} directory due to exclusion! */ +public class JavaClassNamesCallerTest { + + @Test + public void testCallerIsMe() { + String result = JavaClassNames.niceClassAndMethod(); + Assert.assertEquals(result, "JavaClassNamesCallerTest.testCallerIsMe"); + } + + @Test + public void testCallerIsYou() { + other(); + } + + public void other() { + String result = JavaClassNames.callerNiceClassAndMethod(1); + Assert.assertEquals(result, "JavaClassNamesCallerTest.testCallerIsYou"); + } + + +} http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/cf2f7a93/utils/common/src/test/java/org/apache/brooklyn/util/io/FileUtilTest.java ---------------------------------------------------------------------- diff --git a/utils/common/src/test/java/org/apache/brooklyn/util/io/FileUtilTest.java b/utils/common/src/test/java/org/apache/brooklyn/util/io/FileUtilTest.java new file mode 100644 index 0000000..be8a33c --- /dev/null +++ b/utils/common/src/test/java/org/apache/brooklyn/util/io/FileUtilTest.java @@ -0,0 +1,118 @@ +/* + * 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.io; + +import static org.testng.Assert.assertEquals; +import static org.testng.Assert.assertFalse; + +import java.io.File; + +import org.apache.brooklyn.util.io.FileUtil; +import org.apache.brooklyn.util.os.Os; +import org.testng.annotations.AfterMethod; +import org.testng.annotations.BeforeMethod; +import org.testng.annotations.Test; + +import com.google.common.base.Charsets; +import com.google.common.collect.ImmutableList; +import com.google.common.io.Files; + +public class FileUtilTest { + + private File file; + private File dir; + + @BeforeMethod(alwaysRun=true) + public void setUp() throws Exception { + file = File.createTempFile("fileUtilsTest", ".tmp"); + dir = Files.createTempDir(); + } + + @AfterMethod(alwaysRun=true) + public void tearDown() throws Exception { + if (file != null) file.delete(); + if (dir != null) Os.deleteRecursively(dir); + } + + @Test(groups="Integration") + public void testSetFilePermission600() throws Exception { + FileUtil.setFilePermissionsTo600(file); + String permissions = FileUtil.getFilePermissions(file).get(); + assertEquals(permissions, "-rw-------"); + } + + @Test(groups="Integration") + public void testSetFilePermission700() throws Exception { + FileUtil.setFilePermissionsTo700(file); + String permissions = FileUtil.getFilePermissions(file).get(); + assertEquals(permissions, "-rwx------"); + } + + @Test(groups="Integration") + public void testSetDirPermission700() throws Exception { + FileUtil.setFilePermissionsTo700(dir); + String permissions = FileUtil.getFilePermissions(dir).get(); + assertEquals(permissions, "drwx------"); + } + + @Test(groups="Integration") + public void testMoveDir() throws Exception { + File destParent = Files.createTempDir(); + try { + Files.write("abc", new File(dir, "afile"), Charsets.UTF_8); + File destDir = new File(destParent, "dest"); + + FileUtil.moveDir(dir, destDir); + + assertEquals(Files.readLines(new File(destDir, "afile"), Charsets.UTF_8), ImmutableList.of("abc")); + assertFalse(dir.exists()); + } finally { + if (destParent != null) Os.deleteRecursively(destParent); + } + } + + @Test(groups="Integration") + public void testCopyDir() throws Exception { + File destParent = Files.createTempDir(); + try { + Files.write("abc", new File(dir, "afile"), Charsets.UTF_8); + File destDir = new File(destParent, "dest"); + + FileUtil.copyDir(dir, destDir); + + assertEquals(Files.readLines(new File(destDir, "afile"), Charsets.UTF_8), ImmutableList.of("abc")); + assertEquals(Files.readLines(new File(dir, "afile"), Charsets.UTF_8), ImmutableList.of("abc")); + } finally { + if (destParent != null) Os.deleteRecursively(destParent); + } + } + + // Never run this as root! You really don't want to mess with permissions of these files! + // Visual inspection test that we get the log message just once saying: + // WARN Failed to set permissions to 600 for file /etc/hosts: setRead=false, setWrite=false, setExecutable=false; subsequent failures (on any file) will be logged at trace + // Disabled because really don't want to mess up anyone's system, and also no automated assertions about log messages. + @Test(groups="Integration", enabled=false) + public void testLogsWarningOnceIfCannotSetPermission() throws Exception { + File file = new File("/etc/hosts"); + FileUtil.setFilePermissionsTo600(file); + FileUtil.setFilePermissionsTo600(file); + FileUtil.setFilePermissionsTo700(file); + FileUtil.setFilePermissionsTo700(file); + } +} http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/cf2f7a93/utils/common/src/test/java/org/apache/brooklyn/util/javalang/BoxingTest.java ---------------------------------------------------------------------- diff --git a/utils/common/src/test/java/org/apache/brooklyn/util/javalang/BoxingTest.java b/utils/common/src/test/java/org/apache/brooklyn/util/javalang/BoxingTest.java new file mode 100644 index 0000000..8b5a362 --- /dev/null +++ b/utils/common/src/test/java/org/apache/brooklyn/util/javalang/BoxingTest.java @@ -0,0 +1,38 @@ +/* + * 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.javalang; + +import org.apache.brooklyn.util.javalang.Boxing; +import org.testng.Assert; +import org.testng.annotations.Test; + +public class BoxingTest { + + @Test + public static void testIntPrimitiveAndBoxed() { + Assert.assertEquals(Integer.TYPE.getName(), "int"); + + Class<?> t = Boxing.getPrimitiveType("int").get(); + Assert.assertEquals(t, Integer.TYPE); + + Class<?> bt = Boxing.boxedType(t); + Assert.assertEquals(bt, Integer.class); + } + +} http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/cf2f7a93/utils/common/src/test/java/org/apache/brooklyn/util/javalang/EnumsTest.java ---------------------------------------------------------------------- diff --git a/utils/common/src/test/java/org/apache/brooklyn/util/javalang/EnumsTest.java b/utils/common/src/test/java/org/apache/brooklyn/util/javalang/EnumsTest.java new file mode 100644 index 0000000..19607ce --- /dev/null +++ b/utils/common/src/test/java/org/apache/brooklyn/util/javalang/EnumsTest.java @@ -0,0 +1,67 @@ +/* + * 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.javalang; + +import org.apache.brooklyn.util.javalang.Enums; +import org.testng.Assert; +import org.testng.annotations.Test; + +public class EnumsTest { + + private static enum SomeENum { E_300, E_624, WORD_UP, aliceTheCamel } + + @Test + public static void testValueOf() { + Assert.assertEquals(Enums.valueOfIgnoreCase(SomeENum.class, "e_300").get(), SomeENum.E_300); + Assert.assertEquals(Enums.valueOfIgnoreCase(SomeENum.class, "e_624").get(), SomeENum.E_624); + Assert.assertEquals(Enums.valueOfIgnoreCase(SomeENum.class, "ALICE_THE_CAMEL").get(), SomeENum.aliceTheCamel); + Assert.assertEquals(Enums.valueOfIgnoreCase(SomeENum.class, "alice_the_camel").get(), SomeENum.aliceTheCamel); + Assert.assertEquals(Enums.valueOfIgnoreCase(SomeENum.class, "wordUp").get(), SomeENum.WORD_UP); + Assert.assertEquals(Enums.valueOfIgnoreCase(SomeENum.class, "wordup").get(), SomeENum.WORD_UP); + Assert.assertFalse(Enums.valueOfIgnoreCase(SomeENum.class, "MSG").isPresent()); + Assert.assertFalse(Enums.valueOfIgnoreCase(SomeENum.class, "alice_thecamel").isPresent()); + Assert.assertFalse(Enums.valueOfIgnoreCase(SomeENum.class, "_word_up").isPresent()); + } + + @Test + public static void testAllValuesEnumerated() { + Enums.checkAllEnumeratedIgnoreCase(SomeENum.class, "e_300", "E_624", "WORD_UP", "aliceTheCamel"); + } + + @Test(expectedExceptions=IllegalStateException.class, expectedExceptionsMessageRegExp = ".*leftover values.*vitamin.*") + public static void testAllValuesEnumeratedExtra() { + Enums.checkAllEnumeratedIgnoreCase(SomeENum.class, "e_300", "E_624", "Vitamin C", "wordUp", "alice_the_camel"); + } + + @Test(expectedExceptions=IllegalStateException.class, expectedExceptionsMessageRegExp = ".*leftover enums.*E_624.*leftover values.*") + public static void testAllValuesEnumeratedMissing() { + Enums.checkAllEnumeratedIgnoreCase(SomeENum.class, "e_300", "word_UP", "aliceTheCamel"); + } + + @Test(expectedExceptions=IllegalStateException.class, expectedExceptionsMessageRegExp = ".*leftover enums.*E_624.*leftover values.*msg.*") + public static void testAllValuesEnumeratedMissingAndExtra() { + Enums.checkAllEnumeratedIgnoreCase(SomeENum.class, "e_300", "MSG", "WORD_UP", "aliceTheCamel"); + } + + @Test(expectedExceptions=IllegalStateException.class, expectedExceptionsMessageRegExp = ".*leftover enums.*\\[aliceTheCamel\\].*leftover values.*alice_thecamel.*") + public static void testAllValuesEnumeratedNoMatchBadCamel() { + Enums.checkAllEnumeratedIgnoreCase(SomeENum.class, "e_300", "E_624", "WORD_UP", "alice_TheCamel"); + } + +} http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/cf2f7a93/utils/common/src/test/java/org/apache/brooklyn/util/javalang/JavaClassNamesTest.java ---------------------------------------------------------------------- diff --git a/utils/common/src/test/java/org/apache/brooklyn/util/javalang/JavaClassNamesTest.java b/utils/common/src/test/java/org/apache/brooklyn/util/javalang/JavaClassNamesTest.java new file mode 100644 index 0000000..71174b3 --- /dev/null +++ b/utils/common/src/test/java/org/apache/brooklyn/util/javalang/JavaClassNamesTest.java @@ -0,0 +1,76 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.brooklyn.util.javalang; + +import org.apache.brooklyn.util.javalang.JavaClassNames; +import org.testng.Assert; +import org.testng.annotations.Test; + +import com.google.common.reflect.TypeToken; + +public class JavaClassNamesTest { + + @Test + public void testType() { + Assert.assertEquals(JavaClassNames.type(this), JavaClassNamesTest.class); + Assert.assertEquals(JavaClassNames.type(JavaClassNamesTest.class), JavaClassNamesTest.class); + } + + @Test + public void testPackage() { + Assert.assertEquals(JavaClassNames.packageName(JavaClassNamesTest.class), "org.apache.brooklyn.util.javalang"); + Assert.assertEquals(JavaClassNames.packagePath(JavaClassNamesTest.class), "/org/apache/brooklyn/util/javalang/"); + } + + @Test + public void testResolveName() { + Assert.assertEquals(JavaClassNames.resolveName(this, "foo.txt"), "/org/apache/brooklyn/util/javalang/foo.txt"); + Assert.assertEquals(JavaClassNames.resolveName(JavaClassNamesTest.class, "foo.txt"), "/org/apache/brooklyn/util/javalang/foo.txt"); + Assert.assertEquals(JavaClassNames.resolveName(this, "/foo.txt"), "/foo.txt"); + Assert.assertEquals(JavaClassNames.resolveName(this, "/bar/foo.txt"), "/bar/foo.txt"); + Assert.assertEquals(JavaClassNames.resolveName(this, "bar/foo.txt"), "/org/apache/brooklyn/util/javalang/bar/foo.txt"); + } + + @Test + public void testResolveClasspathUrls() { + Assert.assertEquals(JavaClassNames.resolveClasspathUrl(this, "foo.txt"), "classpath://org/apache/brooklyn/util/javalang/foo.txt"); + Assert.assertEquals(JavaClassNames.resolveClasspathUrl(JavaClassNamesTest.class, "/foo.txt"), "classpath://foo.txt"); + Assert.assertEquals(JavaClassNames.resolveClasspathUrl(JavaClassNamesTest.class, "http://localhost/foo.txt"), "http://localhost/foo.txt"); + } + + @Test + public void testSimpleClassNames() { + Assert.assertEquals(JavaClassNames.simpleClassName(this), "JavaClassNamesTest"); + Assert.assertEquals(JavaClassNames.simpleClassName(JavaClassNames.class), JavaClassNames.class.getSimpleName()); + Assert.assertEquals(JavaClassNames.simpleClassName(TypeToken.of(JavaClassNames.class)), JavaClassNames.class.getSimpleName()); + + Assert.assertEquals(JavaClassNames.simpleClassName(JavaClassNames.class.getSimpleName()), "String"); + Assert.assertEquals(JavaClassNames.simplifyClassName(JavaClassNames.class.getSimpleName()), JavaClassNames.class.getSimpleName()); + + Assert.assertEquals(JavaClassNames.simpleClassName(1), "Integer"); + Assert.assertEquals(JavaClassNames.simpleClassName(new String[][] { }), "String[][]"); + + // primitives? + Assert.assertEquals(JavaClassNames.simpleClassName(new int[] { 1, 2, 3 }), "int[]"); + + // anonymous + String anon1 = JavaClassNames.simpleClassName(new Object() {}); + Assert.assertTrue(anon1.startsWith(JavaClassNamesTest.class.getName()+"$"), "anon class is: "+anon1); + } +} http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/cf2f7a93/utils/common/src/test/java/org/apache/brooklyn/util/javalang/MemoryUsageTrackerTest.java ---------------------------------------------------------------------- diff --git a/utils/common/src/test/java/org/apache/brooklyn/util/javalang/MemoryUsageTrackerTest.java b/utils/common/src/test/java/org/apache/brooklyn/util/javalang/MemoryUsageTrackerTest.java new file mode 100644 index 0000000..80e4e7f --- /dev/null +++ b/utils/common/src/test/java/org/apache/brooklyn/util/javalang/MemoryUsageTrackerTest.java @@ -0,0 +1,89 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.brooklyn.util.javalang; + +import java.util.List; + +import org.apache.brooklyn.test.Asserts; +import org.apache.brooklyn.util.collections.MutableList; +import org.apache.brooklyn.util.guava.Maybe; +import org.apache.brooklyn.util.javalang.MemoryUsageTracker; +import org.apache.brooklyn.util.text.Strings; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.testng.Assert; +import org.testng.annotations.Test; + +public class MemoryUsageTrackerTest { + + private static final Logger LOG = LoggerFactory.getLogger(MemoryUsageTrackerTest.class); + + @Test(groups="Integration") + public void testBigUsage() { + final int ALLOCATION_CHUNK_SIZE = 10*1000*1000; // 10MB + + // Don't just use runtime.maxMemory()*2; javadoc says: + // If there is no inherent limit then the value java.lang.Long.MAX_VALUE will be returned. + // Therefore cap at 10GB. + final long MAX_MEMORY_CAP = 10*1024*1024*1024L; // 10GB + final long maxMemory = Math.min(Runtime.getRuntime().maxMemory(), MAX_MEMORY_CAP); + + List<Maybe<byte[]>> references = MutableList.of(); + long created = 0; + while (created < 2*maxMemory) { + byte d[] = new byte[ALLOCATION_CHUNK_SIZE]; + references.add(Maybe.soft(d)); + MemoryUsageTracker.SOFT_REFERENCES.track(d, d.length); + created += d.length; + + long totalMemory = Runtime.getRuntime().totalMemory(); + long freeMemory = Runtime.getRuntime().freeMemory(); + + LOG.info("created "+Strings.makeSizeString(created) + + " ... in use: "+Strings.makeSizeString(totalMemory - freeMemory)+" / " + + Strings.makeSizeString(totalMemory) + + " ... reclaimable: "+Strings.makeSizeString(MemoryUsageTracker.SOFT_REFERENCES.getBytesUsed()) + + " ... live refs: "+Strings.makeSizeString(sizeOfActiveReferences(references)) + + " ... maxMem="+maxMemory+"; totalMem="+totalMemory+"; usedMem="+(totalMemory-freeMemory)); + } + + Asserts.succeedsEventually(new Runnable() { + public void run() { + long totalMemory = Runtime.getRuntime().totalMemory(); + long freeMemory = Runtime.getRuntime().freeMemory(); + assertLessThan(MemoryUsageTracker.SOFT_REFERENCES.getBytesUsed(), maxMemory); + assertLessThan(MemoryUsageTracker.SOFT_REFERENCES.getBytesUsed(), totalMemory); + assertLessThan(MemoryUsageTracker.SOFT_REFERENCES.getBytesUsed(), totalMemory - freeMemory); + }}); + } + + private long sizeOfActiveReferences(List<Maybe<byte[]>> references) { + long size = 0; + for (Maybe<byte[]> ref: references) { + byte[] deref = ref.orNull(); + if (deref!=null) size += deref.length; + } + return size; + } + + private static void assertLessThan(long lhs, long rhs) { + Assert.assertTrue(lhs<rhs, "Expected "+lhs+" < "+rhs); + } + +} http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/cf2f7a93/utils/common/src/test/java/org/apache/brooklyn/util/javalang/ReflectionsTest.java ---------------------------------------------------------------------- diff --git a/utils/common/src/test/java/org/apache/brooklyn/util/javalang/ReflectionsTest.java b/utils/common/src/test/java/org/apache/brooklyn/util/javalang/ReflectionsTest.java new file mode 100644 index 0000000..7f16351 --- /dev/null +++ b/utils/common/src/test/java/org/apache/brooklyn/util/javalang/ReflectionsTest.java @@ -0,0 +1,148 @@ +/* + * 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.javalang; + +import static org.testng.Assert.assertEquals; +import static org.testng.Assert.assertTrue; + +import java.lang.reflect.Field; +import java.lang.reflect.Method; +import java.util.Arrays; +import java.util.List; + +import org.apache.brooklyn.util.javalang.Reflections; +import org.testng.Assert; +import org.testng.annotations.Test; + +import com.google.common.collect.ImmutableList; +import com.google.common.collect.Lists; +import com.google.common.collect.Sets; + +public class ReflectionsTest { + + @Test + public void testFindPublicMethodsOrderedBySuper() throws Exception { + List<Method> methods = Reflections.findPublicMethodsOrderedBySuper(MySubClass.class); + assertContainsInOrder(methods, ImmutableList.of( + MyInterface.class.getMethod("mymethod"), + MySuperClass.class.getMethod("mymethod"), + MySubClass.class.getMethod("mymethod"))); + assertNoDuplicates(methods); + } + + @Test + public void testFindPublicFieldsOrdereBySuper() throws Exception { + List<Field> fields = Reflections.findPublicFieldsOrderedBySuper(MySubClass.class); + assertContainsInOrder(fields, ImmutableList.of( + MyInterface.class.getField("MY_FIELD"), + MySuperClass.class.getField("MY_FIELD"), + MySubClass.class.getField("MY_FIELD"))); + assertNoDuplicates(fields); + } + + public static interface MyInterface { + public static final int MY_FIELD = 0; + public void mymethod(); + } + public static class MySuperClass implements MyInterface { + public static final int MY_FIELD = 0; + + @Override public void mymethod() {} + } + public static class MySubClass extends MySuperClass implements MyInterface { + public static final int MY_FIELD = 0; + @Override public void mymethod() {} + } + + private void assertContainsInOrder(List<?> actual, List<?> subsetExpected) { + int lastIndex = -1; + for (Object e : subsetExpected) { + int index = actual.indexOf(e); + assertTrue(index >= 0 && index > lastIndex, "actual="+actual); + lastIndex = index; + } + } + + private void assertNoDuplicates(List<?> actual) { + assertEquals(actual.size(), Sets.newLinkedHashSet(actual).size(), "actual="+actual); + } + + public static class CI1 { + public final List<Object> constructorArgs; + + public CI1() { + constructorArgs = ImmutableList.of(); + } + public CI1(String x, int y) { + constructorArgs = ImmutableList.<Object>of(x, y); + } + public CI1(String x, int y0, int y1, int ...yy) { + constructorArgs = Lists.newArrayList(); + constructorArgs.addAll(ImmutableList.of(x, y0, y1)); + for (int yi: yy) constructorArgs.add((Integer)yi); + } + public static String m1(String x, int y) { + return x+y; + } + public static String m1(String x, int y0, int y1, int ...yy) { + int Y = y0 + y1;; + for (int yi: yy) Y += yi; + return x+Y; + } + } + + @Test + public void testTypesMatch() throws Exception { + Assert.assertTrue(Reflections.typesMatch(new Object[] { 3 }, new Class[] { Integer.class } )); + Assert.assertTrue(Reflections.typesMatch(new Object[] { 3 }, new Class[] { int.class } ), "auto-boxing failure"); + } + + @Test + public void testInvocation() throws Exception { + Method m = CI1.class.getMethod("m1", String.class, int.class, int.class, int[].class); + Assert.assertEquals(m.invoke(null, "hello", 1, 2, new int[] { 3, 4}), "hello10"); + + Assert.assertEquals(Reflections.invokeMethodWithArgs(CI1.class, "m1", Arrays.<Object>asList("hello", 3)).get(), "hello3"); + Assert.assertEquals(Reflections.invokeMethodWithArgs(CI1.class, "m1", Arrays.<Object>asList("hello", 3, 4, 5)).get(), "hello12"); + } + + @Test + public void testConstruction() throws Exception { + Assert.assertEquals(Reflections.invokeConstructorWithArgs(CI1.class, new Object[] {"hello", 3}).get().constructorArgs, ImmutableList.of("hello", 3)); + Assert.assertEquals(Reflections.invokeConstructorWithArgs(CI1.class, new Object[] {"hello", 3, 4, 5}).get().constructorArgs, ImmutableList.of("hello", 3, 4, 5)); + Assert.assertFalse(Reflections.invokeConstructorWithArgs(CI1.class, new Object[] {"wrong", "args"}).isPresent()); + } + + interface I { }; + interface J extends I { }; + interface K extends I, J { }; + interface L { }; + interface M { }; + class A implements I { }; + class B extends A implements L { }; + class C extends B implements M, K { }; + + @Test + public void testGetAllInterfaces() throws Exception { + Assert.assertEquals(Reflections.getAllInterfaces(A.class), ImmutableList.of(I.class)); + Assert.assertEquals(Reflections.getAllInterfaces(B.class), ImmutableList.of(L.class, I.class)); + Assert.assertEquals(Reflections.getAllInterfaces(C.class), ImmutableList.of(M.class, K.class, I.class, J.class, L.class)); + } + +} http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/cf2f7a93/utils/common/src/test/java/org/apache/brooklyn/util/javalang/StackTraceSimplifierTest.java ---------------------------------------------------------------------- diff --git a/utils/common/src/test/java/org/apache/brooklyn/util/javalang/StackTraceSimplifierTest.java b/utils/common/src/test/java/org/apache/brooklyn/util/javalang/StackTraceSimplifierTest.java new file mode 100644 index 0000000..b069348 --- /dev/null +++ b/utils/common/src/test/java/org/apache/brooklyn/util/javalang/StackTraceSimplifierTest.java @@ -0,0 +1,82 @@ +/* + * 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.javalang; + +import org.apache.brooklyn.util.exceptions.Exceptions; +import org.apache.brooklyn.util.javalang.StackTraceSimplifier; +import org.testng.Assert; +import org.testng.annotations.Test; + +public class StackTraceSimplifierTest { + + @Test + public void isStackTraceElementUsefulRejectsABlacklistedPackage() { + StackTraceElement el = new StackTraceElement("groovy.lang.Foo", "bar", "groovy/lang/Foo.groovy", 42); + Assert.assertFalse(StackTraceSimplifier.isStackTraceElementUseful(el)); + } + + @Test + public void isStackTraceElementUsefulAcceptsANonBlacklistedPackage() { + StackTraceElement el = new StackTraceElement( + "brooklyn.util.task", "StackTraceSimplifierTest", "StackTraceSimplifierTest.groovy", 42); + Assert.assertTrue(StackTraceSimplifier.isStackTraceElementUseful(el)); + } + + @Test + public void cleanTestTrace() { + RuntimeException t = StackTraceSimplifier.newInstance(StackTraceSimplifierTest.class.getName()) + .cleaned(new RuntimeException("sample")); + // should exclude *this* class also + Assert.assertTrue(t.getStackTrace()[0].getClassName().startsWith("org.testng"), + "trace was: "+t.getStackTrace()[0]); + } + + private int m1(int x) { + int count = StackTraceSimplifier.getRecursiveCallCount(); + if (count>100) throw new RuntimeException("expected"); + if (x<=0) { + return count; + } + return m2(x-1); + } + private int m2(int x) { + if (x<=0) return -1; + return m1(x-1); + } + @Test + public void testIsRecursiveCallToSelf() { + Assert.assertEquals(m1(1), -1); + Assert.assertEquals(m2(1), 0); + Assert.assertEquals(m1(2), 1); + Assert.assertEquals(m2(2), -1); + Assert.assertEquals(m1(3), -1); + Assert.assertEquals(m1(4), 2); + Assert.assertEquals(m1(20), 10); + + try { + m1(500); + Assert.fail("should have failed on recursive call"); + } catch (Exception e) { + Exceptions.propagateIfFatal(e); + if (!e.getMessage().equals("expected")) + throw Exceptions.propagate(e); + } + } + +} http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/cf2f7a93/utils/common/src/test/java/org/apache/brooklyn/util/math/BitListTest.java ---------------------------------------------------------------------- diff --git a/utils/common/src/test/java/org/apache/brooklyn/util/math/BitListTest.java b/utils/common/src/test/java/org/apache/brooklyn/util/math/BitListTest.java new file mode 100644 index 0000000..6361751 --- /dev/null +++ b/utils/common/src/test/java/org/apache/brooklyn/util/math/BitListTest.java @@ -0,0 +1,123 @@ +/* + * 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.math; + +import java.math.BigInteger; +import java.util.BitSet; + +import org.apache.brooklyn.util.math.BitList; +import org.apache.brooklyn.util.math.BitUtils; +import org.testng.Assert; +import org.testng.annotations.Test; + +import com.google.common.primitives.Booleans; + +public class BitListTest { + + @Test + public void checkBitListToNumber() { + BitList bl; + bl = BitList.newInstance(true); + Assert.assertEquals(bl.asBytes(), new byte[] { 1 }); + Assert.assertEquals(bl.asBigInteger(), BigInteger.valueOf(1)); + + Assert.assertEquals(BitList.newInstance(new boolean[0]).asBigInteger(), BigInteger.valueOf(0)); + + bl = BitList.newInstance(false, false, false, false, + false, false, false, false, + true, false); + Assert.assertEquals(bl.asBytes(), new byte[] { 0, 1 }); + Assert.assertEquals(bl.intValue(), 256); + Assert.assertEquals(bl.longValue(), 256); + Assert.assertEquals(bl.byteValue(), 0); + + Assert.assertEquals(BitList.newInstanceFromBytes(0, 1).resized(10), bl); + + Assert.assertEquals(""+bl, "00000000:10"); + } + + @Test + public void checkSimpleBitsToBytesAndBack() { + BitSet bs = new BitSet(); + bs.set(0); bs.set(2); //5 + bs.set(8); bs.set(15); //129 (unsigned) + bs.set(17); // 2 + byte[] bytes = BitList.newInstance(bs, 24).asBytes(); + + Assert.assertEquals(bytes.length, 3); + Assert.assertEquals(bytes[0], (byte)5); + Assert.assertEquals(bytes[1], (byte)129); + Assert.assertEquals(bytes[2], (byte)2); + + BitList bs2 = BitList.newInstance(bytes); + Assert.assertEquals(bs2.asBitSet(), bs); + } + + @Test + public void checkBitsToUnsignedBytesAndBack() { + BitSet bs = new BitSet(); + bs.set(0); bs.set(2); //5 + bs.set(8); bs.set(15); //129 (unsigned) + bs.set(17); // 2 + int[] bytes = BitList.newInstance(bs, 24).asUnsignedBytes(); + + Assert.assertEquals(bytes.length, 3); + Assert.assertEquals(bytes[0], 5); + Assert.assertEquals(bytes[1], 129); + Assert.assertEquals(bytes[2], 2); + + BitList bs2 = BitList.newInstanceFromBytes(bytes); + Assert.assertEquals(bs2.asBitSet(), bs); + } + + @Test + public void checkAsList() { + BitList bl = BitList.newInstanceFromBytes(2, 129, 5); + Assert.assertEquals(BitList.newInstance(bl.asBitSet(), bl.length), bl); + Assert.assertEquals(BitList.newInstance(bl.asBytes()), bl); + Assert.assertEquals(BitList.newInstance(bl.asArray()), bl); + Assert.assertEquals(BitList.newInstance(bl.asList()), bl); + Assert.assertEquals(BitList.newInstance(bl.asBigInteger()).resized(24), bl); + } + + @Test + public void checkReverseTiny() { + BitList bl = BitList.newInstance(true, false); + Assert.assertEquals(Booleans.asList(bl.reversed().asArray()), Booleans.asList(false, true)); + Assert.assertEquals(bl.intValue(), 1); + Assert.assertEquals(bl.reversed().intValue(), 2); + Assert.assertEquals(bl.reversed().reversed(), bl); + } + + @Test + public void checkReverseNumbers() { + BitList bl = BitList.newInstanceFromBytes(2, 129, 5); + Assert.assertEquals(bl.reversed().asBytes(), new byte[] { (byte)160, (byte)129, (byte)64 }); + Assert.assertEquals(BitUtils.reverseBitSignificance( bl.reversed().asBytes() ), new byte[] { 5, (byte)129, 2 }); + } + + @Test + public void checkCommonPrefixLength() { + Assert.assertEquals(BitList.newInstance(false, true, false).commonPrefixLength(BitList.newInstance(true, false, false)), 0); + Assert.assertEquals(BitList.newInstance(false, true, false).commonPrefixLength(BitList.newInstance(false, false, false)), 1); + Assert.assertEquals(BitList.newInstance(false, true, false).commonPrefixLength(BitList.newInstance(false, true, true)), 2); + Assert.assertEquals(BitList.newInstance(false, true, false).commonPrefixLength(BitList.newInstance(false, true, false)), 3); + } + +} \ No newline at end of file http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/cf2f7a93/utils/common/src/test/java/org/apache/brooklyn/util/math/BitUtilsTest.java ---------------------------------------------------------------------- diff --git a/utils/common/src/test/java/org/apache/brooklyn/util/math/BitUtilsTest.java b/utils/common/src/test/java/org/apache/brooklyn/util/math/BitUtilsTest.java new file mode 100644 index 0000000..bc9d5cb --- /dev/null +++ b/utils/common/src/test/java/org/apache/brooklyn/util/math/BitUtilsTest.java @@ -0,0 +1,50 @@ +/* + * 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.math; + +import org.apache.brooklyn.util.math.BitUtils; +import org.testng.Assert; +import org.testng.annotations.Test; + +public class BitUtilsTest { + + @Test + public void checkReverseBitSignificance() { + Assert.assertEquals(BitUtils.reverseBitSignificanceInByte(1), (byte)128); + Assert.assertEquals(BitUtils.reverseBitSignificanceInByte(2), 64); + Assert.assertEquals(BitUtils.reverseBitSignificanceInByte(8), 16); + Assert.assertEquals(BitUtils.reverseBitSignificanceInByte(16), 8); + Assert.assertEquals(BitUtils.reverseBitSignificanceInByte(128), 1); + Assert.assertEquals(BitUtils.reverseBitSignificanceInByte(160), 5); + Assert.assertEquals(BitUtils.reverseBitSignificanceInByte(-96), 5); + Assert.assertEquals(BitUtils.reverseBitSignificanceInByte(3), (byte)192); + Assert.assertEquals(BitUtils.reverseBitSignificanceInBytes(1, 2), new byte[] { (byte)128, 64 }); + Assert.assertEquals(BitUtils.reverseBitSignificanceInBytes(3, 8, 16, 192, 255), new byte[] { (byte)192, 16, 8, 3, (byte)255 }); + } + + @Test + public void checkUnsigned() { + Assert.assertEquals(BitUtils.unsigned((byte)-96), 160); + Assert.assertEquals(BitUtils.unsigned((byte)160), 160); + Assert.assertEquals(BitUtils.unsignedByte(-96), 160); + Assert.assertEquals(BitUtils.unsignedByte(-96-256-256), 160); + Assert.assertEquals(BitUtils.unsignedByte(-96+256), 160); + Assert.assertEquals(BitUtils.unsignedByte(-96+256+256), 160); + } +} http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/cf2f7a93/utils/common/src/test/java/org/apache/brooklyn/util/math/MathFunctionsTest.java ---------------------------------------------------------------------- diff --git a/utils/common/src/test/java/org/apache/brooklyn/util/math/MathFunctionsTest.java b/utils/common/src/test/java/org/apache/brooklyn/util/math/MathFunctionsTest.java new file mode 100644 index 0000000..31ed402 --- /dev/null +++ b/utils/common/src/test/java/org/apache/brooklyn/util/math/MathFunctionsTest.java @@ -0,0 +1,44 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.brooklyn.util.math; + +import org.apache.brooklyn.test.FixedLocaleTest; +import org.apache.brooklyn.util.math.MathFunctions; +import org.testng.Assert; +import org.testng.annotations.Test; + +public class MathFunctionsTest extends FixedLocaleTest { + + @Test + public void testAdd() { + Assert.assertEquals(MathFunctions.plus(3).apply(4), (Integer)7); + Assert.assertEquals(MathFunctions.plus(0.3).apply(0.4).doubleValue(), 0.7, 0.00000001); + } + + @Test + public void testReadableString() { + Assert.assertEquals(MathFunctions.readableString(3, 5).apply(0.0123456), "1.23E-2"); + } + + @Test + public void testPercent() { + Assert.assertEquals(MathFunctions.percent(3).apply(0.0123456), "1.23%"); + } + +} http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/cf2f7a93/utils/common/src/test/java/org/apache/brooklyn/util/math/MathPredicatesTest.java ---------------------------------------------------------------------- diff --git a/utils/common/src/test/java/org/apache/brooklyn/util/math/MathPredicatesTest.java b/utils/common/src/test/java/org/apache/brooklyn/util/math/MathPredicatesTest.java new file mode 100644 index 0000000..3eb2802 --- /dev/null +++ b/utils/common/src/test/java/org/apache/brooklyn/util/math/MathPredicatesTest.java @@ -0,0 +1,56 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.brooklyn.util.math; + +import static org.testng.Assert.assertFalse; +import static org.testng.Assert.assertTrue; + +import org.apache.brooklyn.util.math.MathPredicates; +import org.testng.annotations.Test; + +public class MathPredicatesTest { + + @Test + public void testGreaterThan() throws Exception { + assertTrue(MathPredicates.greaterThan(2d).apply(3)); + assertFalse(MathPredicates.greaterThan(2d).apply(1)); + assertFalse(MathPredicates.greaterThan(2d).apply(2)); + } + + @Test + public void testGreaterThanOrEqual() throws Exception { + assertTrue(MathPredicates.greaterThanOrEqual(2d).apply(3)); + assertFalse(MathPredicates.greaterThanOrEqual(2d).apply(1)); + assertTrue(MathPredicates.greaterThanOrEqual(2d).apply(2)); + } + + @Test + public void testLessThan() throws Exception { + assertFalse(MathPredicates.lessThanOrEqual(2d).apply(3)); + assertTrue(MathPredicates.lessThan(2d).apply(1)); + assertFalse(MathPredicates.lessThan(2d).apply(2)); + } + + @Test + public void testLessThanOrEqual() throws Exception { + assertFalse(MathPredicates.lessThanOrEqual(2d).apply(3)); + assertTrue(MathPredicates.lessThanOrEqual(2d).apply(1)); + assertTrue(MathPredicates.lessThanOrEqual(2d).apply(2)); + } +} http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/cf2f7a93/utils/common/src/test/java/org/apache/brooklyn/util/maven/MavenArtifactTest.java ---------------------------------------------------------------------- diff --git a/utils/common/src/test/java/org/apache/brooklyn/util/maven/MavenArtifactTest.java b/utils/common/src/test/java/org/apache/brooklyn/util/maven/MavenArtifactTest.java new file mode 100644 index 0000000..dae6d9d --- /dev/null +++ b/utils/common/src/test/java/org/apache/brooklyn/util/maven/MavenArtifactTest.java @@ -0,0 +1,217 @@ +/* + * 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.maven; + +import java.io.File; +import java.io.InputStream; +import java.net.HttpURLConnection; +import java.net.URL; +import java.net.URLClassLoader; + +import org.apache.brooklyn.util.exceptions.Exceptions; +import org.apache.brooklyn.util.maven.MavenArtifact; +import org.apache.brooklyn.util.maven.MavenArtifactTest; +import org.apache.brooklyn.util.maven.MavenRetriever; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.testng.Assert; +import org.testng.annotations.Test; + +@Test +public class MavenArtifactTest { + + private static final Logger log = LoggerFactory.getLogger(MavenArtifactTest.class); + + // only *integration* tests require these to be *installed*; + // note this may vary from machine to machine so version should be aligned with that in parent pom + final static String MAVEN_JAR_PLUGIN_COORDINATE = "org.apache.maven.plugins:maven-jar-plugin:jar:2.6"; + final static String THIS_PROJECT_COORDINATE = "org.apache.brooklyn:brooklyn-utils-common:jar:0.8.0-SNAPSHOT"; // BROOKLYN_VERSION + + // Don't need to be installed, only used as examples + final static String RELEASED_SOURCES_COORDINATE = "io.brooklyn:brooklyn-core:jar:sources:0.6.0"; + final static String EXAMPLE_BZIP_COORDINATE = "com.example:example-artifact:tar.bz2:server-windows:2.0.1"; + + @Test + public void testArtifact() throws Exception { + MavenArtifact m = MavenArtifact.fromCoordinate(MAVEN_JAR_PLUGIN_COORDINATE); + + Assert.assertEquals(m.getGroupId(), "org.apache.maven.plugins"); + Assert.assertEquals(m.getArtifactId(), "maven-jar-plugin"); + Assert.assertEquals(m.getVersion(), "2.6"); + Assert.assertEquals(m.getPackaging(), "jar"); + Assert.assertEquals(m.getClassifier(), null); + + Assert.assertEquals(m.getCoordinate(), MAVEN_JAR_PLUGIN_COORDINATE); + + Assert.assertEquals(m.getFilename(), "maven-jar-plugin-2.6.jar"); + Assert.assertEquals(m.isSnapshot(), false); + } + + @Test + public void testArtifactWithClassifier() throws Exception { + MavenArtifact m = MavenArtifact.fromCoordinate(RELEASED_SOURCES_COORDINATE); + + Assert.assertEquals(m.getGroupId(), "io.brooklyn"); + Assert.assertEquals(m.getArtifactId(), "brooklyn-core"); + Assert.assertEquals(m.getVersion(), "0.6.0"); + Assert.assertEquals(m.getPackaging(), "jar"); + Assert.assertEquals(m.getClassifier(), "sources"); + + Assert.assertEquals(m.getCoordinate(), RELEASED_SOURCES_COORDINATE); + + } + + @Test + public void testRetrieval() throws Exception { + MavenArtifact m = MavenArtifact.fromCoordinate(MAVEN_JAR_PLUGIN_COORDINATE); + + String hostedUrl = new MavenRetriever().getHostedUrl(m); + Assert.assertTrue(hostedUrl.startsWith("http://search.maven.org/")); + + String localPath = new MavenRetriever().getLocalPath(m); + Assert.assertTrue(localPath.endsWith( + "/repository/org/apache/maven/plugins/maven-jar-plugin/2.6/maven-jar-plugin-2.6.jar"), + localPath); + } + + @Test + public void testRetrievalWithClassifier() throws Exception { + MavenArtifact m = MavenArtifact.fromCoordinate(RELEASED_SOURCES_COORDINATE); + + String localPath = new MavenRetriever().getLocalPath(m); + Assert.assertTrue(localPath.endsWith( + "/repository/io/brooklyn/brooklyn-core/0.6.0/brooklyn-core-0.6.0-sources.jar"), + localPath); + } + + @Test + public void testRetrievalWithUnusualClassifier() throws Exception { + MavenArtifact m = MavenArtifact.fromCoordinate(EXAMPLE_BZIP_COORDINATE); + + String localPath = new MavenRetriever().getLocalPath(m); + Assert.assertTrue(localPath.endsWith( + "/repository/com/example/example-artifact/2.0.1/example-artifact-2.0.1-server-windows.tar.bz2"), + localPath); + } + + @Test + public void testSnapshotRetrieval() throws Exception { + MavenArtifact m = MavenArtifact.fromCoordinate(THIS_PROJECT_COORDINATE); + + if (!m.isSnapshot()) { + log.info("Skipping SNAPSHOT testing as this is not a snapshot project"); + return; + } + + String hostedUrl = new MavenRetriever().getHostedUrl(m); + Assert.assertTrue(hostedUrl.contains("repository.apache.org"), hostedUrl); + + String localPath = new MavenRetriever().getLocalPath(m); + Assert.assertTrue(localPath.contains( + "/repository/org/apache/brooklyn")); + } + + @Test(groups="Integration") + public void testRetrievalLocalIntegration() throws Exception { + MavenArtifact m = MavenArtifact.fromCoordinate(MAVEN_JAR_PLUGIN_COORDINATE); + + String localPath = new MavenRetriever().getLocalPath(m); + File f = new File(localPath); + if (!f.exists()) + Assert.fail("Could not load "+localPath+" when testing MavenRetriever: do a maven build with no integration tests first to ensure this is installed, then rerun"); + + checkValidMavenJarUrl(MavenRetriever.localUrl(m), "org/apache/maven/plugin/jar/JarMojo.class"); + } + + @Test(groups="Integration") + public void testRetrievalHostedReleaseIntegration() throws Exception { + MavenArtifact m = MavenArtifact.fromCoordinate(MAVEN_JAR_PLUGIN_COORDINATE); + + checkValidMavenJarUrl(new MavenRetriever().getHostedUrl(m), "org/apache/maven/plugin/jar/JarMojo.class"); + } + + protected void checkAvailableUrl(String url) throws Exception { + try { + InputStream stream = new URL(url).openStream(); + stream.read(); + stream.close(); + } catch (Exception e) { + throw Exceptions.propagate(e); + } + } + protected void checkValidMavenJarUrl(String url, String resource) throws Exception { + // URLClassLoader doesn't follow redirects; find out the real URL + // Note URLClassLoader.close was only added in Java 7; do not call it until Java 6 support is not needed! + URL realUrl = followRedirects(new URL(url)); + URLClassLoader classLoader = new URLClassLoader(new URL[] { realUrl }); + URL innerU = classLoader.findResource(resource); + InputStream innerUin = innerU.openConnection().getInputStream(); + innerUin.close(); + } + + @Test(groups="Integration") + public void testRetrievalHostedSnapshotIntegration() throws Exception { + MavenArtifact m = MavenArtifact.fromCoordinate( + "org.apache.brooklyn:brooklyn-utils-common:jar:0.8.0-SNAPSHOT"); // BROOKLYN_VERSION + + String localPath = new MavenRetriever().getLocalPath(m); + File f = new File(localPath); + if (!f.exists()) + Assert.fail("Could not load "+localPath+" when testing MavenRetriever: do a maven build with no integration tests first to ensure this is installed, then rerun"); + + String l = new MavenRetriever().getLocalUrl(m); + Assert.assertEquals(new URL(l), new URL("file://"+localPath)); + + checkAvailableUrl(l); + + String h = new MavenRetriever().getHostedUrl(m); + if (!m.isSnapshot()) { + log.info("Skipping SNAPSHOT testing as this is not a snapshot build"); + } else { + Assert.assertTrue(h.contains("repository.apache.org"), "h="+h); + } + + try { + checkAvailableUrl(h); + } catch (Exception e) { + // don't fail for now, just warn + log.warn("Could not download SNAPSHOT build for "+h+": is it installed to sonatype?", e); + } + } + + private URL followRedirects(URL url) throws Exception { + if ("file".equalsIgnoreCase(url.getProtocol())) return url; + + HttpURLConnection conn = (HttpURLConnection) url.openConnection(); + conn.setReadTimeout(5000); + + // normally, 3xx is redirect + int status = conn.getResponseCode(); + boolean redirect = (status == HttpURLConnection.HTTP_MOVED_TEMP || status == HttpURLConnection.HTTP_MOVED_PERM || status == HttpURLConnection.HTTP_SEE_OTHER); + + if (redirect) { + // get redirect url from "location" header field + String newUrl = conn.getHeaderField("Location"); + log.debug("Following redirect for "+url+", to "+newUrl); + return followRedirects(new URL(newUrl)); + } else { + return url; + } + } +} http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/cf2f7a93/utils/common/src/test/java/org/apache/brooklyn/util/net/CidrTest.java ---------------------------------------------------------------------- diff --git a/utils/common/src/test/java/org/apache/brooklyn/util/net/CidrTest.java b/utils/common/src/test/java/org/apache/brooklyn/util/net/CidrTest.java new file mode 100644 index 0000000..c5bd36d --- /dev/null +++ b/utils/common/src/test/java/org/apache/brooklyn/util/net/CidrTest.java @@ -0,0 +1,176 @@ +/* + * 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.net; + +import java.util.Arrays; + +import org.apache.brooklyn.util.net.Cidr; +import org.testng.Assert; +import org.testng.annotations.Test; + +public class CidrTest { + + public static void assertBytesEquals(int[] actual, int[] expected) { + if (actual.length != expected.length) + Assert.fail("Arrays of different length: "+Arrays.toString(actual)+" actual, "+Arrays.toString(expected)+" expected"); + for (int i=0; i<actual.length; i++) + if (actual[i]!=expected[i]) + Assert.fail("Arrays differ in element "+i+": "+Arrays.toString(actual)+" actual, "+Arrays.toString(expected)+" expected"); + } + + @Test + public void test_10_0_0_0_String() { + Cidr c = new Cidr("10.0.0.0/8"); + Assert.assertEquals(c.toString(), "10.0.0.0/8"); + assertBytesEquals(c.getBytes(), new int[] { 10, 0, 0, 0 }); + Assert.assertEquals(c.getLength(), 8); + } + + @Test + public void test_10_0_0_0_Byte() { + Cidr c = new Cidr(10); + Assert.assertEquals(c.toString(), "10.0.0.0/8"); + assertBytesEquals(c.getBytes(), new int[] { 10, 0, 0, 0 }); + Assert.assertEquals(c.getLength(), 8); + } + + @Test + public void test_10_0_0_0_ExtraBytes() { + Cidr c = new Cidr(10, 0); + Assert.assertEquals(c.toString(), "10.0.0.0/16"); + assertBytesEquals(c.getBytes(), new int[] { 10, 0, 0, 0 }); + Assert.assertEquals(c.getLength(), 16); + } + + @Test + public void test_0_0_0_0_Bytes() { + Cidr c = new Cidr(); + Assert.assertEquals(c.toString(), "0.0.0.0/0"); + assertBytesEquals(c.getBytes(), new int[] { 0, 0, 0, 0 }); + Assert.assertEquals(c.getLength(), 0); + } + + @Test + public void test_0_0_0_0_32_Bytes() { + Cidr c = new Cidr(0, 0, 0, 0); + Assert.assertEquals(c.toString(), "0.0.0.0/32"); + assertBytesEquals(c.getBytes(), new int[] { 0, 0, 0, 0 }); + Assert.assertEquals(c.getLength(), 32); + } + + @Test + public void test_0_0_0_0_String() { + Cidr c = new Cidr("0.0.0.0/0"); + Assert.assertEquals(c.toString(), "0.0.0.0/0"); + assertBytesEquals(c.getBytes(), new int[] { 0, 0, 0, 0 }); + Assert.assertEquals(c.getLength(), 0); + } + + @Test + public void test_0_0_0_0_32_String() { + Cidr c = new Cidr("0.0.0.0/32"); + Assert.assertEquals(c.toString(), "0.0.0.0/32"); + assertBytesEquals(c.getBytes(), new int[] { 0, 0, 0, 0 }); + Assert.assertEquals(c.getLength(), 32); + } + + @Test + public void test_10_0_0_0_7_LessABit() { + Cidr c = new Cidr("10.0.0.0/7"); + Assert.assertEquals(c.toString(), "10.0.0.0/7"); + assertBytesEquals(c.getBytes(), new int[] { 10, 0, 0, 0 }); + Assert.assertEquals(c.getLength(), 7); + } + + @Test + public void test_10_0_0_0_6_LessTwoBitsOneIsSignificant() { + Cidr c = new Cidr("10.0.0.1/6"); + Assert.assertEquals(c.toString(), "8.0.0.0/6"); + assertBytesEquals(c.getBytes(), new int[] { 8, 0, 0, 0 }); + Assert.assertEquals(c.getLength(), 6); + } + + @Test + public void test_10_0_blah_6() { + Cidr c = new Cidr("10.0../6"); + Assert.assertEquals(c.toString(), "8.0.0.0/6"); + assertBytesEquals(c.getBytes(), new int[] { 8, 0, 0, 0 }); + Assert.assertEquals(c.getLength(), 6); + } + + @Test + public void testSubnet() { + Cidr c = new Cidr("0.0.0.0/0"); + Cidr c10 = c.subnet(10); + Assert.assertEquals(c10, new Cidr(10)); + Assert.assertEquals(c10.subnet(88, 1), new Cidr(10, 88, 1)); + } + + @Test + public void testNetmask() { + Cidr c = new Cidr(10, 0); + Assert.assertEquals(c.netmask().getHostAddress(), "255.255.0.0"); + } + + @Test + public void testNetmaskOdd() { + Cidr c = new Cidr("10.0/13"); + Assert.assertEquals(c.netmask().getHostAddress(), "255.31.0.0"); + } + + @Test + public void testAddressAtOffset() { + Cidr c = new Cidr(10, 0); + Assert.assertEquals(c.addressAtOffset(3).getHostAddress(), "10.0.0.3"); + Assert.assertEquals(c.addressAtOffset(256*256*8+1).getHostAddress(), "10.8.0.1"); + } + + @Test + public void testCommonPrefixLength() { + Cidr c1 = new Cidr("10.0.0.0/8"); + Cidr c2 = new Cidr("11.0.0.0/8"); + Assert.assertEquals(c1.commonPrefixLength(c2), 7); + Assert.assertEquals(c2.commonPrefixLength(c1), 7); + Assert.assertEquals(c2.commonPrefix(c1), c1.commonPrefix(c2)); + Assert.assertEquals(c2.commonPrefix(c1), new Cidr("10.0../7")); + Cidr c1s = new Cidr("10.0../6"); + Assert.assertEquals(c2.commonPrefixLength(c1s), 6); + + Assert.assertTrue(c1s.contains(c1)); + Assert.assertTrue(c1s.contains(c2)); + Assert.assertFalse(c1.contains(c2)); + Assert.assertFalse(c2.contains(c1)); + } + + @Test + public void testContains() { + Assert.assertTrue(Cidr._172_16.contains(new Cidr("172.17.0.1/32"))); + Assert.assertFalse(Cidr._172_16.contains(new Cidr("172.144.0.1/32"))); + } + + @Test + public void testIsCanonical() { + Assert.assertTrue(Cidr.isCanonical("10.0.0.0/8")); + Assert.assertTrue(Cidr.isCanonical("10.0.0.0/16")); + Assert.assertTrue(Cidr.isCanonical(Cidr._172_16.toString())); + Assert.assertFalse(Cidr.isCanonical("10.0.0.1/8")); + Assert.assertFalse(Cidr.isCanonical("/0")); + Assert.assertFalse(Cidr.isCanonical("10.0.0.0/33")); + } +} http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/cf2f7a93/utils/common/src/test/java/org/apache/brooklyn/util/net/NetworkingUtilsTest.java ---------------------------------------------------------------------- diff --git a/utils/common/src/test/java/org/apache/brooklyn/util/net/NetworkingUtilsTest.java b/utils/common/src/test/java/org/apache/brooklyn/util/net/NetworkingUtilsTest.java new file mode 100644 index 0000000..788b574 --- /dev/null +++ b/utils/common/src/test/java/org/apache/brooklyn/util/net/NetworkingUtilsTest.java @@ -0,0 +1,229 @@ +/* + * 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.net; + +import static org.testng.Assert.assertEquals; +import static org.testng.Assert.assertFalse; +import static org.testng.Assert.assertNotEquals; +import static org.testng.Assert.assertNotNull; +import static org.testng.Assert.assertTrue; +import static org.testng.Assert.fail; + +import java.io.IOException; +import java.net.InetAddress; +import java.net.InetSocketAddress; +import java.net.ServerSocket; +import java.net.UnknownHostException; +import java.util.concurrent.TimeUnit; + +import org.apache.brooklyn.test.Asserts; +import org.apache.brooklyn.util.exceptions.Exceptions; +import org.apache.brooklyn.util.javalang.JavaClassNames; +import org.apache.brooklyn.util.net.Networking; +import org.apache.brooklyn.util.text.Identifiers; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.testng.Assert; +import org.testng.annotations.Test; + +import com.google.common.base.Stopwatch; +import com.google.common.net.HostAndPort; + +public class NetworkingUtilsTest { + + private static final Logger log = LoggerFactory.getLogger(NetworkingUtilsTest.class); + + @Test + public void testValidIp() throws Exception { + assertTrue(Networking.isValidIp4("127.0.0.1")); + assertTrue(Networking.isValidIp4("0.0.0.0")); + assertFalse(Networking.isValidIp4("foo")); + assertTrue(Networking.isValidIp4(Networking.LOOPBACK.getHostName())); + assertTrue(Networking.isValidIp4("0.0.0.00")); + assertTrue(Networking.isValidIp4("127.0.0.000001")); + assertFalse(Networking.isValidIp4("127.0.0.256")); + assertFalse(Networking.isValidIp4("127.0.0.")); + assertFalse(Networking.isValidIp4("127.0.0.9f")); + assertFalse(Networking.isValidIp4("127.0.0.1.")); + } + + @Test + public void testGetInetAddressWithFixedNameByIpBytes() throws Exception { + InetAddress addr = Networking.getInetAddressWithFixedName(new byte[] {1,2,3,4}); + assertEquals(addr.getAddress(), new byte[] {1,2,3,4}); + assertEquals(addr.getHostName(), "1.2.3.4"); + } + + @Test + public void testGetInetAddressWithFixedNameByIp() throws Exception { + InetAddress addr = Networking.getInetAddressWithFixedName("1.2.3.4"); + assertEquals(addr.getAddress(), new byte[] {1,2,3,4}); + assertEquals(addr.getHostName(), "1.2.3.4"); + + InetAddress addr2 = Networking.getInetAddressWithFixedName("255.255.255.255"); + assertEquals(addr2.getAddress(), new byte[] {(byte)(int)255,(byte)(int)255,(byte)(int)255,(byte)(int)255}); + assertEquals(addr2.getHostName(), "255.255.255.255"); + + InetAddress addr3 = Networking.getInetAddressWithFixedName("localhost"); + assertEquals(addr3.getHostName(), "localhost"); + + } + + @Test(groups="Integration") + public void testGetInetAddressWithFixedNameButInvalidIpThrowsException() throws Exception { + // as with ByonLocationResolverTest.testNiceError + // some DNS servers give an IP for this "hostname" + // so test is marked as integration now + try { + Networking.getInetAddressWithFixedName("1.2.3.400"); + fail(); + } catch (Exception e) { + if (Exceptions.getFirstThrowableOfType(e, UnknownHostException.class) == null) throw e; + } + } + + @Test + public void testIsPortAvailableReportsTrueWhenPortIsFree() throws Exception { + int port = 58769; + int numFree = 0; + for (int i = 0; i < 10; i++) { + if (Networking.isPortAvailable(port)) + numFree++; + } + if (numFree<=5) + fail("This test requires that at least some ports near 58769+ not be in use."); + } + + @Test + public void testIsPortAvailableReportsFalseWhenPortIsInUse() throws Exception { + int port = 58767; + ServerSocket ss = null; + do { + port ++; + if (Networking.isPortAvailable(port)) { + try { + ss = new ServerSocket(port); + log.info("acquired port on "+port+" for test "+JavaClassNames.niceClassAndMethod()); + assertFalse(Networking.isPortAvailable(port), "port mistakenly reported as available"); + } finally { + if (ss != null) { + ss.close(); + } + } + } + // repeat until we can get a port + } while (ss == null && port < 60000); + Assert.assertNotNull(ss, "could not get a port"); + + final int portF = port; + Asserts.succeedsEventually(new Runnable() { + @Override public void run() { + assertTrue(Networking.isPortAvailable(portF), "port "+portF+" not made available afterwards"); + }}); + } + + @Test + public void testIsPortAvailableReportsPromptly() throws Exception { + // repeat until we can get an available port + int port = 58767; + boolean available = false; + do { + port++; + Stopwatch watch = Stopwatch.createStarted(); + if (Networking.isPortAvailable(null, port)) { + available = true; + } + long elapsedMillis = watch.elapsed(TimeUnit.MILLISECONDS); + assertTrue(elapsedMillis < 5000, "elapsedMillis="+elapsedMillis+" for isPortAvailable(null, "+port+")"); + } while (!available && port < 60000); + + Assert.assertTrue(available); + } + + @Test + public void testIsPortAvailableValidatesAddress() throws Exception { + ServerSocket ss = new ServerSocket(); + ss.bind(new InetSocketAddress(InetAddress.getLocalHost(), 0)); + int boundPort = ss.getLocalPort(); + assertTrue(ss.isBound()); + assertNotEquals(boundPort, 0); + //will run isAddressValid before returning + assertFalse(Networking.isPortAvailable(boundPort)); + ss.close(); + } + + //just some system health-checks... localhost may not resolve properly elsewhere + //(e.g. in geobytes, AddressableLocation, etc) if this does not work + + @Test + public void testLocalhostIpLookup() throws UnknownHostException { + InetAddress address = InetAddress.getByName("127.0.0.1"); + Assert.assertEquals(127, address.getAddress()[0]); + Assert.assertTrue(Networking.isPrivateSubnet(address)); + } + + @Test + public void testLocalhostLookup() throws UnknownHostException { + InetAddress address = InetAddress.getByName("localhost"); + Assert.assertEquals(127, address.getAddress()[0]); + Assert.assertTrue(Networking.isPrivateSubnet(address)); + Assert.assertEquals("127.0.0.1", address.getHostAddress()); + } + + @Test + public void test10_x_x_xSubnetPrivate() throws UnknownHostException { + InetAddress address = InetAddress.getByAddress(new byte[] { 10, 0, 0, 1 }); + Assert.assertTrue(Networking.isPrivateSubnet(address)); + } + + @Test + public void test172_16_x_xSubnetPrivate() throws UnknownHostException { + InetAddress address = InetAddress.getByAddress(new byte[] { (byte)172, 31, (byte)255, (byte)255 }); + Assert.assertTrue(Networking.isPrivateSubnet(address)); + } + + @Test(groups="Integration") + public void testBogusHostnameUnresolvable() { + Assert.assertEquals(Networking.resolve("bogus-hostname-"+Identifiers.makeRandomId(8)), null); + } + + @Test(groups="Integration") + public void testIsReachable() throws Exception { + ServerSocket serverSocket = null; + for (int i = 40000; i < 40100; i++) { + try { + serverSocket = new ServerSocket(i); + } catch (IOException e) { + // try next number + } + } + assertNotNull(serverSocket, "No ports available in range!"); + + try { + HostAndPort hostAndPort = HostAndPort.fromParts(serverSocket.getInetAddress().getHostAddress(), serverSocket.getLocalPort()); + assertTrue(Networking.isReachable(hostAndPort)); + + serverSocket.close(); + assertFalse(Networking.isReachable(hostAndPort)); + + } finally { + serverSocket.close(); + } + } +} http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/cf2f7a93/utils/common/src/test/java/org/apache/brooklyn/util/net/UrlsTest.java ---------------------------------------------------------------------- diff --git a/utils/common/src/test/java/org/apache/brooklyn/util/net/UrlsTest.java b/utils/common/src/test/java/org/apache/brooklyn/util/net/UrlsTest.java new file mode 100644 index 0000000..d5851e5 --- /dev/null +++ b/utils/common/src/test/java/org/apache/brooklyn/util/net/UrlsTest.java @@ -0,0 +1,84 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.brooklyn.util.net; + +import static org.testng.Assert.assertEquals; + +import org.apache.brooklyn.util.net.Urls; +import org.testng.Assert; +import org.testng.annotations.Test; + +public class UrlsTest { + + @Test + public void testUrlToUriToStringAndBack() { + String u = "http://localhost:8080/sample"; + Assert.assertEquals(Urls.toUrl(u).toString(), u); + Assert.assertEquals(Urls.toUri(u).toString(), u); + Assert.assertEquals(Urls.toUri(Urls.toUrl(u)).toString(), u); + Assert.assertEquals(Urls.toUrl(Urls.toUri(u)).toString(), u); + } + + @Test + public void testMergePaths() throws Exception { + assertEquals(Urls.mergePaths("a","b"), "a/b"); + assertEquals(Urls.mergePaths("/a//","/b/"), "/a/b/"); + assertEquals(Urls.mergePaths("foo://","/b/"), "foo:///b/"); + assertEquals(Urls.mergePaths("/","a","b","/"), "/a/b/"); + } + + @Test(expectedExceptions = NullPointerException.class) + public void testMergePathsNPEsOnNulls() { + Urls.mergePaths(null, "too"); + } + + @Test + public void testPathEncode() throws Exception { + assertEquals(Urls.encode("name_with/%!"), "name_with%2F%25%21"); + } + + @Test + public void testIsUrlWithProtocol() { + Assert.assertTrue(Urls.isUrlWithProtocol("http://localhost/")); + Assert.assertTrue(Urls.isUrlWithProtocol("protocol:")); + Assert.assertFalse(Urls.isUrlWithProtocol("protocol")); + Assert.assertFalse(Urls.isUrlWithProtocol(":/")); + Assert.assertFalse(Urls.isUrlWithProtocol("1:/")); + Assert.assertFalse(Urls.isUrlWithProtocol(null)); + } + + @Test + public void testGetBasename() { + assertEquals(Urls.getBasename("http://somewhere.com/path/to/file.txt"), "file.txt"); + assertEquals(Urls.getBasename("http://somewhere.com/path/to/dir/"), "dir"); + assertEquals(Urls.getBasename("http://somewhere.com/path/to/file.txt?with/optional/suffice"), "file.txt"); + assertEquals(Urls.getBasename("filewith?.txt"), "filewith?.txt"); + assertEquals(Urls.getBasename(""), ""); + assertEquals(Urls.getBasename(null), null); + } + + @Test + public void testDataUrl() throws Exception { + String input = "hello world"; + String url = Urls.asDataUrlBase64(input); + Assert.assertEquals(url, "data:text/plain;base64,aGVsbG8gd29ybGQ="); + // tests for parsing are in core in ResourceUtilsTest + } + +} http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/cf2f7a93/utils/common/src/test/java/org/apache/brooklyn/util/net/UserAndHostAndPortTest.java ---------------------------------------------------------------------- diff --git a/utils/common/src/test/java/org/apache/brooklyn/util/net/UserAndHostAndPortTest.java b/utils/common/src/test/java/org/apache/brooklyn/util/net/UserAndHostAndPortTest.java new file mode 100644 index 0000000..51df8b2 --- /dev/null +++ b/utils/common/src/test/java/org/apache/brooklyn/util/net/UserAndHostAndPortTest.java @@ -0,0 +1,51 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.brooklyn.util.net; + +import static org.testng.Assert.assertEquals; + +import org.apache.brooklyn.util.net.UserAndHostAndPort; +import org.testng.annotations.Test; + +import com.google.common.net.HostAndPort; + +public class UserAndHostAndPortTest { + + @Test + public void testFromParts() throws Exception { + assertIt(UserAndHostAndPort.fromParts("myuser", "myhost", 1234), "myuser", HostAndPort.fromParts("myhost", 1234)); + } + + @Test + public void testFromString() throws Exception { + assertIt(UserAndHostAndPort.fromString("myuser@myhost:1234"), "myuser", HostAndPort.fromParts("myhost", 1234)); + assertIt(UserAndHostAndPort.fromString("myuser @ myhost:1234"), "myuser", HostAndPort.fromParts("myhost", 1234)); + assertIt(UserAndHostAndPort.fromString("myuser @ myhost"), "myuser", HostAndPort.fromString("myhost")); + } + + private void assertIt(UserAndHostAndPort actual, String user, HostAndPort hostAndPort) { + assertEquals(actual.getUser(), user); + assertEquals(actual.getHostAndPort(), hostAndPort); + if (hostAndPort.hasPort()) { + assertEquals(actual.toString(), user + "@" + hostAndPort.getHostText() + ":" + hostAndPort.getPort()); + } else { + assertEquals(actual.toString(), user + "@" + hostAndPort.getHostText()); + } + } +} http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/cf2f7a93/utils/common/src/test/java/org/apache/brooklyn/util/os/OsTest.java ---------------------------------------------------------------------- diff --git a/utils/common/src/test/java/org/apache/brooklyn/util/os/OsTest.java b/utils/common/src/test/java/org/apache/brooklyn/util/os/OsTest.java new file mode 100644 index 0000000..e3792a0 --- /dev/null +++ b/utils/common/src/test/java/org/apache/brooklyn/util/os/OsTest.java @@ -0,0 +1,168 @@ +/* + * 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.os; + +import static org.testng.Assert.assertEquals; +import static org.testng.Assert.assertFalse; +import static org.testng.Assert.assertTrue; + +import java.io.File; +import java.util.ArrayList; +import java.util.Collection; + +import org.apache.brooklyn.util.exceptions.Exceptions; +import org.apache.brooklyn.util.os.Os; +import org.apache.brooklyn.util.os.OsTest; +import org.apache.brooklyn.util.os.Os.DeletionResult; +import org.apache.brooklyn.util.text.Identifiers; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.testng.Assert; +import org.testng.annotations.Test; + +import com.google.common.collect.ImmutableSet; +import com.google.common.io.Files; + +@Test +public class OsTest { + + private static final Logger log = LoggerFactory.getLogger(OsTest.class); + + public void testTmp() { + log.info("tmp dir is: "+Os.tmp()); + Assert.assertNotNull(Os.tmp()); + } + + public void testHome() { + log.info("home dir is: "+Os.home()); + Assert.assertNotNull(Os.home()); + } + + public void testUser() { + log.info("user name is: "+Os.user()); + Assert.assertNotNull(Os.user()); + } + + public void testTidyPathCanonicalize() throws Exception { + for (String path : ImmutableSet.of("/a/b", "//a///b", "/a/b/", "/a/b/.", "/q/../a/b")) { + assertEquals(Os.tidyPath(path), "/a/b"); + } + } + + public void testTidyPathSimplify() throws Exception { + assertEquals(Os.tidyPath("x/y/z"), "x/y/z"); + assertEquals(Os.tidyPath(""), "."); + assertEquals(Os.tidyPath("."), "."); + assertEquals(Os.tidyPath(".."), ".."); + assertEquals(Os.tidyPath("./x"), "x"); + assertEquals(Os.tidyPath("../x"), "../x"); + assertEquals(Os.tidyPath("/.."), "/"); + assertEquals(Os.tidyPath("x"), "x"); + assertEquals(Os.tidyPath("/"), "/"); + assertEquals(Os.tidyPath("///"), "/"); + assertEquals(Os.tidyPath("/x\\"), "/x\\"); + assertEquals(Os.tidyPath("/x\\y/.."), "/"); + } + + public void testTidyPathHome() throws Exception { + String userhome = System.getProperty("user.home"); + assertEquals(Os.tidyPath("~/a/b"), userhome+"/a/b"); + assertEquals(Os.tidyPath("~"), userhome); + assertEquals(Os.tidyPath("/a/~/b"), "/a/~/b"); + } + + public void testMergePaths() throws Exception { + assertEquals(Os.mergePaths("a"), "a"); + assertEquals(Os.mergePaths("a", "b"), "a/b"); + assertEquals(Os.mergePaths("a/", "b"), "a/b"); + assertEquals(Os.mergePaths("a", "b/"), "a/b/"); + assertEquals(Os.mergePaths("/a", "b"), "/a/b"); + } + + @Test(groups="Integration") + public void testNewTempFile() { + int CREATE_CNT = 5000; + Collection<File> folders = new ArrayList<File>(CREATE_CNT); + + try { + for (int i = 0; i < CREATE_CNT; i++) { + try { + folders.add(Os.newTempFile(OsTest.class, "test")); + } catch (IllegalStateException e) { + log.warn("testNewTempFile failed at " + i + " iteration."); + Exceptions.propagate(e); + } + } + } finally { + //cleanup + for (File folder : folders) { + folder.delete(); + } + } + } + + @Test(groups="Integration") + public void testNewTempDir() { + int CREATE_CNT = 5000; + Collection<File> folders = new ArrayList<File>(CREATE_CNT); + + try { + for (int i = 0; i < CREATE_CNT; i++) { + try { + folders.add(Os.newTempDir(OsTest.class)); + } catch (IllegalStateException e) { + log.warn("testNewTempDir failed at " + i + " iteration."); + Exceptions.propagate(e); + } + } + } finally { + //cleanup + for (File folder : folders) { + folder.delete(); + } + } + } + + @Test + public void testDeleteRecursivelyNonExistantDir() throws Exception { + DeletionResult result = Os.deleteRecursively(Os.mergePaths(Os.tmp(), Identifiers.makeRandomId(8))); + assertTrue(result.wasSuccessful()); + } + + @Test + public void testDeleteRecursivelyEmptyDir() throws Exception { + File dir = Os.newTempDir(OsTest.class); + DeletionResult result = Os.deleteRecursively(dir); + assertTrue(result.wasSuccessful()); + assertFalse(dir.exists()); + } + + @Test + public void testDeleteRecursivelySubDirs() throws Exception { + File dir = Os.newTempDir(OsTest.class); + File subdir = new File(dir, "mysubdir"); + File subfile = new File(subdir, "mysubfile"); + subdir.mkdirs(); + Files.write("abc".getBytes(), subfile); + + DeletionResult result = Os.deleteRecursively(dir); + assertTrue(result.wasSuccessful()); + assertFalse(dir.exists()); + } +}
