You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@brooklyn.apache.org by ha...@apache.org on 2015/08/18 17:03:15 UTC
[06/64] [abbrv] incubator-brooklyn git commit: BROOKLYN-162 - apply
org.apache package prefix to utils-common
http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/cf2f7a93/utils/common/src/test/java/brooklyn/util/javalang/StackTraceSimplifierTest.java
----------------------------------------------------------------------
diff --git a/utils/common/src/test/java/brooklyn/util/javalang/StackTraceSimplifierTest.java b/utils/common/src/test/java/brooklyn/util/javalang/StackTraceSimplifierTest.java
deleted file mode 100644
index 1c3c5ca..0000000
--- a/utils/common/src/test/java/brooklyn/util/javalang/StackTraceSimplifierTest.java
+++ /dev/null
@@ -1,82 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package brooklyn.util.javalang;
-
-import org.testng.Assert;
-import org.testng.annotations.Test;
-
-import brooklyn.util.exceptions.Exceptions;
-
-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/brooklyn/util/math/BitListTest.java
----------------------------------------------------------------------
diff --git a/utils/common/src/test/java/brooklyn/util/math/BitListTest.java b/utils/common/src/test/java/brooklyn/util/math/BitListTest.java
deleted file mode 100644
index 8525636..0000000
--- a/utils/common/src/test/java/brooklyn/util/math/BitListTest.java
+++ /dev/null
@@ -1,121 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package brooklyn.util.math;
-
-import java.math.BigInteger;
-import java.util.BitSet;
-
-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/brooklyn/util/math/BitUtilsTest.java
----------------------------------------------------------------------
diff --git a/utils/common/src/test/java/brooklyn/util/math/BitUtilsTest.java b/utils/common/src/test/java/brooklyn/util/math/BitUtilsTest.java
deleted file mode 100644
index e2785ef..0000000
--- a/utils/common/src/test/java/brooklyn/util/math/BitUtilsTest.java
+++ /dev/null
@@ -1,49 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package brooklyn.util.math;
-
-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/brooklyn/util/math/MathFunctionsTest.java
----------------------------------------------------------------------
diff --git a/utils/common/src/test/java/brooklyn/util/math/MathFunctionsTest.java b/utils/common/src/test/java/brooklyn/util/math/MathFunctionsTest.java
deleted file mode 100644
index 2093123..0000000
--- a/utils/common/src/test/java/brooklyn/util/math/MathFunctionsTest.java
+++ /dev/null
@@ -1,44 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package brooklyn.util.math;
-
-import org.testng.Assert;
-import org.testng.annotations.Test;
-
-import brooklyn.test.FixedLocaleTest;
-
-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/brooklyn/util/math/MathPredicatesTest.java
----------------------------------------------------------------------
diff --git a/utils/common/src/test/java/brooklyn/util/math/MathPredicatesTest.java b/utils/common/src/test/java/brooklyn/util/math/MathPredicatesTest.java
deleted file mode 100644
index c884388..0000000
--- a/utils/common/src/test/java/brooklyn/util/math/MathPredicatesTest.java
+++ /dev/null
@@ -1,55 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package brooklyn.util.math;
-
-import static org.testng.Assert.assertFalse;
-import static org.testng.Assert.assertTrue;
-
-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/brooklyn/util/maven/MavenArtifactTest.java
----------------------------------------------------------------------
diff --git a/utils/common/src/test/java/brooklyn/util/maven/MavenArtifactTest.java b/utils/common/src/test/java/brooklyn/util/maven/MavenArtifactTest.java
deleted file mode 100644
index a8851bf..0000000
--- a/utils/common/src/test/java/brooklyn/util/maven/MavenArtifactTest.java
+++ /dev/null
@@ -1,215 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package 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.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.testng.Assert;
-import org.testng.annotations.Test;
-
-import brooklyn.util.exceptions.Exceptions;
-
-@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/brooklyn/util/net/CidrTest.java
----------------------------------------------------------------------
diff --git a/utils/common/src/test/java/brooklyn/util/net/CidrTest.java b/utils/common/src/test/java/brooklyn/util/net/CidrTest.java
deleted file mode 100644
index 07fbe29..0000000
--- a/utils/common/src/test/java/brooklyn/util/net/CidrTest.java
+++ /dev/null
@@ -1,175 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package brooklyn.util.net;
-
-import java.util.Arrays;
-
-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/brooklyn/util/net/NetworkingUtilsTest.java
----------------------------------------------------------------------
diff --git a/utils/common/src/test/java/brooklyn/util/net/NetworkingUtilsTest.java b/utils/common/src/test/java/brooklyn/util/net/NetworkingUtilsTest.java
deleted file mode 100644
index 48202a6..0000000
--- a/utils/common/src/test/java/brooklyn/util/net/NetworkingUtilsTest.java
+++ /dev/null
@@ -1,229 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package 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.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.testng.Assert;
-import org.testng.annotations.Test;
-
-import brooklyn.test.Asserts;
-import brooklyn.util.exceptions.Exceptions;
-import brooklyn.util.javalang.JavaClassNames;
-import brooklyn.util.text.Identifiers;
-
-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/brooklyn/util/net/UrlsTest.java
----------------------------------------------------------------------
diff --git a/utils/common/src/test/java/brooklyn/util/net/UrlsTest.java b/utils/common/src/test/java/brooklyn/util/net/UrlsTest.java
deleted file mode 100644
index fc45f93..0000000
--- a/utils/common/src/test/java/brooklyn/util/net/UrlsTest.java
+++ /dev/null
@@ -1,83 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package brooklyn.util.net;
-
-import static org.testng.Assert.assertEquals;
-
-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/brooklyn/util/net/UserAndHostAndPortTest.java
----------------------------------------------------------------------
diff --git a/utils/common/src/test/java/brooklyn/util/net/UserAndHostAndPortTest.java b/utils/common/src/test/java/brooklyn/util/net/UserAndHostAndPortTest.java
deleted file mode 100644
index cb08064..0000000
--- a/utils/common/src/test/java/brooklyn/util/net/UserAndHostAndPortTest.java
+++ /dev/null
@@ -1,50 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package brooklyn.util.net;
-
-import static org.testng.Assert.assertEquals;
-
-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/brooklyn/util/os/OsTest.java
----------------------------------------------------------------------
diff --git a/utils/common/src/test/java/brooklyn/util/os/OsTest.java b/utils/common/src/test/java/brooklyn/util/os/OsTest.java
deleted file mode 100644
index fbd499f..0000000
--- a/utils/common/src/test/java/brooklyn/util/os/OsTest.java
+++ /dev/null
@@ -1,167 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package 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.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.testng.Assert;
-import org.testng.annotations.Test;
-
-import brooklyn.util.exceptions.Exceptions;
-import brooklyn.util.os.Os.DeletionResult;
-import brooklyn.util.text.Identifiers;
-
-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());
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/cf2f7a93/utils/common/src/test/java/brooklyn/util/pool/BasicPoolTest.java
----------------------------------------------------------------------
diff --git a/utils/common/src/test/java/brooklyn/util/pool/BasicPoolTest.java b/utils/common/src/test/java/brooklyn/util/pool/BasicPoolTest.java
deleted file mode 100644
index 9682566..0000000
--- a/utils/common/src/test/java/brooklyn/util/pool/BasicPoolTest.java
+++ /dev/null
@@ -1,196 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package brooklyn.util.pool;
-
-import static org.testng.Assert.assertEquals;
-import static org.testng.Assert.fail;
-
-import java.util.Collections;
-import java.util.List;
-import java.util.Set;
-import java.util.concurrent.ConcurrentHashMap;
-import java.util.concurrent.CopyOnWriteArrayList;
-import java.util.concurrent.Executors;
-import java.util.concurrent.atomic.AtomicInteger;
-
-import javax.annotation.Nullable;
-
-import org.testng.annotations.AfterMethod;
-import org.testng.annotations.BeforeMethod;
-import org.testng.annotations.Test;
-import org.testng.internal.annotations.Sets;
-
-import com.google.common.base.Function;
-import com.google.common.base.Predicates;
-import com.google.common.base.Supplier;
-import com.google.common.collect.ImmutableList;
-import com.google.common.collect.Lists;
-import com.google.common.util.concurrent.Futures;
-import com.google.common.util.concurrent.ListenableFuture;
-import com.google.common.util.concurrent.ListeningExecutorService;
-import com.google.common.util.concurrent.MoreExecutors;
-
-public class BasicPoolTest {
-
- private List<Integer> closedVals;
- private Supplier<Integer> supplier;
- Function<Integer,Void> closer;
- private ListeningExecutorService executor;
-
- @BeforeMethod(alwaysRun=true)
- public void setUp() throws Exception {
- // Note we use final theCounter variable, rather than just a field, to guarantee
- // that each sequential test run won't be accessing the same field value if a test
- // doesn't tear down and keeps executing in another thread for some reason.
-
- final AtomicInteger theCounter = new AtomicInteger(0);
- closedVals = new CopyOnWriteArrayList<Integer>();
-
- supplier = new Supplier<Integer>() {
- @Override public Integer get() {
- return theCounter.getAndIncrement();
- }
- };
- closer = new Function<Integer,Void>() {
- @Override public Void apply(@Nullable Integer input) {
- closedVals.add(input);
- return null;
- }
- };
- executor = MoreExecutors.listeningDecorator(Executors.newCachedThreadPool());
- }
-
- @AfterMethod(alwaysRun=true)
- public void tearDown() throws Exception {
- if (executor != null) executor.shutdownNow();
- }
-
- @Test
- public void testGeneratesNewValuesWhenRequired() throws Exception {
- Pool<Integer> pool = BasicPool.<Integer>builder().supplier(supplier).build();
-
- Lease<Integer> lease1 = pool.leaseObject();
- assertEquals(lease1.leasedObject(), (Integer)0);
-
- Lease<Integer> lease2 = pool.leaseObject();
- assertEquals(lease2.leasedObject(), (Integer)1);
- }
-
- @Test
- public void testReusesReturnedVals() throws Exception {
- Pool<Integer> pool = BasicPool.<Integer>builder().supplier(supplier).build();
-
- Lease<Integer> lease1 = pool.leaseObject();
- assertEquals(lease1.leasedObject(), (Integer)0);
- lease1.close();
-
- Lease<Integer> lease2 = pool.leaseObject();
- assertEquals(lease2.leasedObject(), (Integer)0);
- }
-
- @Test
- public void testGeneratesNewIfOnlyUnviableValsInPool() throws Exception {
- Pool<Integer> pool = BasicPool.<Integer>builder().supplier(supplier).viabilityChecker(Predicates.alwaysFalse()).closer(closer).build();
-
- Lease<Integer> lease1 = pool.leaseObject();
- assertEquals(lease1.leasedObject(), (Integer)0);
- lease1.close();
-
- Lease<Integer> lease2 = pool.leaseObject();
- assertEquals(lease2.leasedObject(), (Integer)1);
-
- // Expect the "unviable" resource to have been closed
- assertEquals(closedVals, ImmutableList.of(0));
- }
-
- @Test
- public void testReusesOnlyViableVals() throws Exception {
- Pool<Integer> pool = BasicPool.<Integer>builder().supplier(supplier).viabilityChecker(Predicates.equalTo(1)).build();
-
- Lease<Integer> lease1 = pool.leaseObject();
- Lease<Integer> lease2 = pool.leaseObject();
- Lease<Integer> lease3 = pool.leaseObject();
-
- lease1.close();
- lease2.close();
- lease3.close();
-
- Lease<Integer> lease4 = pool.leaseObject();
- assertEquals(lease4.leasedObject(), (Integer)1);
- }
-
- @Test
- public void testClosesResourcesInPool() throws Exception {
- Pool<Integer> pool = BasicPool.<Integer>builder().supplier(supplier).closer(closer).build();
-
- Lease<Integer> lease1 = pool.leaseObject();
- Lease<Integer> lease2 = pool.leaseObject();
- lease1.close();
- lease2.close();
-
- pool.close();
- assertEquals(closedVals, ImmutableList.of(0, 1));
- }
-
- @Test
- public void testClosesResourceReturnedAfterPoolIsClosed() throws Exception {
- Pool<Integer> pool = BasicPool.<Integer>builder().supplier(supplier).closer(closer).build();
-
- Lease<Integer> lease1 = pool.leaseObject();
- pool.close();
- assertEquals(closedVals, ImmutableList.of());
-
- lease1.close();
- assertEquals(closedVals, ImmutableList.of(lease1.leasedObject()));
- }
-
- @Test
- public void testDoesNotReuseUnviableVals() throws Exception {
- Pool<Integer> pool = BasicPool.<Integer>builder().supplier(supplier).viabilityChecker(Predicates.alwaysFalse()).build();
-
- Lease<Integer> lease1 = pool.leaseObject();
- assertEquals(lease1.leasedObject(), (Integer)0);
- lease1.close();
-
- Lease<Integer> lease2 = pool.leaseObject();
- assertEquals(lease2.leasedObject(), (Integer)1);
- }
-
- @Test
- public void testConcurrentCallsNeverHaveSameVal() throws Exception {
- final Pool<Integer> pool = BasicPool.<Integer>builder().supplier(supplier).build();
- final Set<Lease<Integer>> leases = Collections.newSetFromMap(new ConcurrentHashMap<Lease<Integer>, Boolean>());
- List<ListenableFuture<?>> futures = Lists.newArrayList();
-
- for (int i = 0; i < 1000; i++) {
- futures.add(executor.submit(new Runnable() {
- public void run() {
- leases.add(pool.leaseObject());
- }
- }));
- }
- Futures.allAsList(futures).get();
-
- Set<Integer> currentlyLeased = Sets.newLinkedHashSet();
- for (Lease<Integer> lease : leases) {
- boolean val = currentlyLeased.add(lease.leasedObject());
- if (!val) fail("duplicate="+lease.leasedObject()+"; vals="+leases);
- }
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/cf2f7a93/utils/common/src/test/java/brooklyn/util/repeat/RepeaterTest.java
----------------------------------------------------------------------
diff --git a/utils/common/src/test/java/brooklyn/util/repeat/RepeaterTest.java b/utils/common/src/test/java/brooklyn/util/repeat/RepeaterTest.java
deleted file mode 100644
index 1be68dd..0000000
--- a/utils/common/src/test/java/brooklyn/util/repeat/RepeaterTest.java
+++ /dev/null
@@ -1,240 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package brooklyn.util.repeat;
-
-import static org.testng.Assert.assertEquals;
-import static org.testng.Assert.assertFalse;
-import static org.testng.Assert.assertTrue;
-import static org.testng.Assert.fail;
-
-import java.util.concurrent.Callable;
-import java.util.concurrent.TimeUnit;
-import java.util.concurrent.atomic.AtomicInteger;
-
-import org.testng.annotations.Test;
-
-import brooklyn.util.time.Duration;
-
-import com.google.common.base.Stopwatch;
-import com.google.common.util.concurrent.Callables;
-
-public class RepeaterTest {
-
- @Test
- public void sanityTest() {
- new Repeater("Sanity test")
- .until(Callables.returning(true))
- .every(Duration.millis(10));
- }
-
- @Test
- public void sanityTestDescription() {
- new Repeater()
- .until(Callables.returning(true))
- .every(Duration.millis(10));
- }
-
- @Test
- public void sanityTestBuilder() {
- Repeater.create("Sanity test")
- .until(Callables.returning(true))
- .every(Duration.millis(10));
- }
-
- @Test
- public void sanityTestBuilderDescription() {
- Repeater.create()
- .until(Callables.returning(true))
- .every(Duration.millis(10));
- }
-
- @Test
- public void repeatSucceedsIfClosureIsNonNull() {
- new Repeater("repeatSucceedsIfClosureIsNonNull").repeat(Callables.returning(true));
- }
-
- @Test(expectedExceptions = { NullPointerException.class, IllegalArgumentException.class })
- public void untilFailsIfClosureIsNull() {
- new Repeater("untilFailsIfClosureIsNull").until(null);
- fail("Expected exception was not thrown");
- }
-
- @Test
- public void untilSucceedsIfClosureIsNonNull() {
- new Repeater("untilSucceedsIfClosureIsNonNull")
- .until(Callables.returning(true));
- }
-
- @Test(expectedExceptions = { NullPointerException.class, IllegalArgumentException.class })
- public void everyFailsIfPeriodIsZero() {
- new Repeater("everyFailsIfPeriodIsZero").every(Duration.ZERO);
- fail("Expected exception was not thrown");
- }
-
- @Test(expectedExceptions = { NullPointerException.class, IllegalArgumentException.class })
- public void everyFailsIfPeriodIsNegative() {
- new Repeater("everyFailsIfPeriodIsNegative").every(Duration.millis(-1));
- fail("Expected exception was not thrown");
- }
-
- @Test(expectedExceptions = { NullPointerException.class, IllegalArgumentException.class })
- public void everyFailsIfUnitsIsNull() {
- new Repeater("everyFailsIfUnitsIsNull").every(10, null);
- fail("Expected exception was not thrown");
- }
-
- @Test
- public void everySucceedsIfPeriodIsPositiveAndUnitsIsNonNull() {
- new Repeater("repeatSucceedsIfClosureIsNonNull").every(Duration.millis(10));
- }
-
- @Test(expectedExceptions = { NullPointerException.class, IllegalArgumentException.class })
- public void limitTimeToFailsIfPeriodIsZero() {
- new Repeater("limitTimeToFailsIfPeriodIsZero").limitTimeTo(0, TimeUnit.MILLISECONDS);
- fail("Expected exception was not thrown");
- }
-
- @Test(expectedExceptions = { NullPointerException.class, IllegalArgumentException.class })
- public void limitTimeToFailsIfPeriodIsNegative() {
- new Repeater("limitTimeToFailsIfPeriodIsNegative").limitTimeTo(-1, TimeUnit.MILLISECONDS);
- fail("Expected exception was not thrown");
- }
-
- @Test(expectedExceptions = { NullPointerException.class, IllegalArgumentException.class })
- public void limitTimeToFailsIfUnitsIsNull() {
- new Repeater("limitTimeToFailsIfUnitsIsNull").limitTimeTo(10, null);
- fail("Expected exception was not thrown");
- }
-
- @Test
- public void limitTimeToSucceedsIfPeriodIsPositiveAndUnitsIsNonNull() {
- new Repeater("limitTimeToSucceedsIfClosureIsNonNull").limitTimeTo(10, TimeUnit.MILLISECONDS);
- }
-
- @Test
- public void everyAcceptsDuration() {
- new Repeater("everyAcceptsDuration").every(Duration.ONE_SECOND);
- }
-
- @Test
- public void everyAcceptsTimeUnit() {
- new Repeater("everyAcceptsTimeUnit").every(1000000L, TimeUnit.MICROSECONDS);
- }
-
- @Test
- public void runReturnsTrueIfExitConditionIsTrue() {
- assertTrue(new Repeater("runReturnsTrueIfExitConditionIsTrue")
- .every(Duration.millis(1))
- .until(Callables.returning(true))
- .run());
- }
-
- @Test
- public void runRespectsMaximumIterationLimitAndReturnsFalseIfReached() {
- final AtomicInteger iterations = new AtomicInteger();
- assertFalse(new Repeater("runRespectsMaximumIterationLimitAndReturnsFalseIfReached")
- .repeat(new Runnable() { public void run() { iterations.incrementAndGet(); } })
- .every(Duration.millis(1))
- .until(Callables.returning(false))
- .limitIterationsTo(5)
- .run());
- assertEquals(iterations.get(), 5);
- }
-
- /**
- * Check that the {@link Repeater} will stop after a time limit.
- *
- * The repeater is configured to run every 100ms and never stop until the limit is reached.
- * This is given as {@link Repeater#limitTimeTo(groovy.time.Duration)} and the execution time
- * is then checked to ensure it is between 100% and 400% of the specified value. Due to scheduling
- * delays and other factors in a non RTOS system it is expected that the repeater will take much
- * longer to exit occasionally.
- *
- * @see #runRespectsMaximumIterationLimitAndReturnsFalseIfReached()
- */
- @Test(groups="Integration")
- public void runRespectsTimeLimitAndReturnsFalseIfReached() {
- final long LIMIT = 2000l;
- Repeater repeater = new Repeater("runRespectsTimeLimitAndReturnsFalseIfReached")
- .every(Duration.millis(100))
- .until(Callables.returning(false))
- .limitTimeTo(LIMIT, TimeUnit.MILLISECONDS);
-
- Stopwatch stopwatch = Stopwatch.createStarted();
- boolean result = repeater.run();
- stopwatch.stop();
-
- assertFalse(result);
-
- long difference = stopwatch.elapsed(TimeUnit.MILLISECONDS);
- assertTrue(difference >= LIMIT, "Difference was: " + difference);
- assertTrue(difference < 4 * LIMIT, "Difference was: " + difference);
- }
-
- @Test(expectedExceptions = { IllegalStateException.class })
- public void runFailsIfUntilWasNotSet() {
- new Repeater("runFailsIfUntilWasNotSet")
- .every(Duration.millis(10))
- .run();
- fail("Expected exception was not thrown");
- }
-
- @Test(expectedExceptions = { IllegalStateException.class })
- public void runFailsIfEveryWasNotSet() {
- new Repeater("runFailsIfEveryWasNotSet")
- .until(Callables.returning(true))
- .run();
- fail("Expected exception was not thrown");
- }
-
- @Test(expectedExceptions = { UnsupportedOperationException.class })
- public void testRethrowsException() {
- new Repeater("throwRuntimeException")
- .every(Duration.millis(10))
- .until(callableThrowingUnsupportedFail())
- .rethrowException()
- .limitIterationsTo(2)
- .run();
- fail("Expected exception was not thrown");
- }
-
- @Test
- public void testNoRethrowsException() {
- try {
- boolean result = new Repeater("throwRuntimeException")
- .every(Duration.millis(10))
- .until(callableThrowingUnsupportedFail())
- .limitIterationsTo(2)
- .run();
- assertFalse(result);
- } catch (RuntimeException re) {
- fail("Exception should not have been thrown: " + re.getMessage());
- }
- }
-
- private static Callable<Boolean> callableThrowingUnsupportedFail() {
- return new Callable<Boolean>() {
- @Override
- public Boolean call() throws Exception {
- throw new UnsupportedOperationException("fail");
- }
- };
- }
-
-}
http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/cf2f7a93/utils/common/src/test/java/brooklyn/util/ssh/IptablesCommandsFirewalldTest.java
----------------------------------------------------------------------
diff --git a/utils/common/src/test/java/brooklyn/util/ssh/IptablesCommandsFirewalldTest.java b/utils/common/src/test/java/brooklyn/util/ssh/IptablesCommandsFirewalldTest.java
deleted file mode 100644
index f0f6d5c..0000000
--- a/utils/common/src/test/java/brooklyn/util/ssh/IptablesCommandsFirewalldTest.java
+++ /dev/null
@@ -1,104 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package brooklyn.util.ssh;
-
-import org.testng.Assert;
-import org.testng.annotations.Test;
-
-import brooklyn.util.net.Protocol;
-import brooklyn.util.ssh.IptablesCommands.Chain;
-import brooklyn.util.ssh.IptablesCommands.Policy;
-
-public class IptablesCommandsFirewalldTest {
- private static final String addFirewalldRule = "( if test \"$UID\" -eq 0; then "
- + "( ( /usr/bin/firewall-cmd --direct --add-rule ipv4 filter INPUT 0 -p tcp --dport 3306 -j ACCEPT "
- + "&& /usr/bin/firewall-cmd --permanent --direct --add-rule ipv4 filter INPUT 0 -p tcp --dport 3306 -j ACCEPT ) ); "
- + "else echo \"( /usr/bin/firewall-cmd --direct --add-rule ipv4 filter INPUT 0 -p tcp --dport 3306 -j ACCEPT "
- + "&& /usr/bin/firewall-cmd --permanent --direct --add-rule ipv4 filter INPUT 0 -p tcp --dport 3306 -j ACCEPT )\" "
- + "| sudo -E -n -S -s -- bash ; fi )";
-
- private static final String firewalldService = "( if test \"$UID\" -eq 0; then ( ( { "
- + "which systemctl && systemctl status firewalld ; } || /usr/bin/systemctl status firewalld ) ); "
- + "else echo \"( { which systemctl && systemctl status firewalld ; } || "
- + "/usr/bin/systemctl status firewalld )\" | sudo -E -n -S -s -- bash ; fi )";
-
- private static final String firewalldServiceRestart = "( if test \"$UID\" -eq 0; then ( ( { "
- + "which systemctl && systemctl restart firewalld ; } || "
- + "/usr/bin/systemctl restart firewalld ) ); else echo \"( { "
- + "which systemctl && systemctl restart firewalld ; } || /usr/bin/systemctl restart firewalld )\" | "
- + "sudo -E -n -S -s -- bash ; fi )";
-
- private static final String firewalldServiceStart = "( if test \"$UID\" -eq 0; then ( ( { "
- + "which systemctl && systemctl start firewalld ; } "
- + "|| /usr/bin/systemctl start firewalld ) ); "
- + "else echo \"( { which systemctl && systemctl start firewalld ; } || "
- + "/usr/bin/systemctl start firewalld )\" | sudo -E -n -S -s -- bash ; fi )";
-
- private static final String firewalldServiceStatus = "( if test \"$UID\" -eq 0; then ( ( { "
- + "which systemctl && systemctl status firewalld ; "
- + "} || /usr/bin/systemctl status firewalld ) ); else echo \"( { "
- + "which systemctl && systemctl status firewalld ; } || "
- + "/usr/bin/systemctl status firewalld )\" | sudo -E -n -S -s -- bash ; fi )";
-
- private static final String firewalldServiceStop = "( if test \"$UID\" -eq 0; then ( ( { "
- + "which systemctl && systemctl stop firewalld ; } || /usr/bin/systemctl stop firewalld ) ); "
- + "else echo \"( { which systemctl && systemctl stop firewalld ; } || "
- + "/usr/bin/systemctl stop firewalld )\" | sudo -E -n -S -s -- bash ; fi )";
-
- private static final String firewalldServiceIsActive = "( if test \"$UID\" -eq 0; then ( ( { "
- + "which systemctl && systemctl is-active firewalld ; } || /usr/bin/systemctl is-active firewalld ) ); "
- + "else echo \"( { which systemctl && systemctl is-active firewalld ; } || /usr/bin/systemctl is-active firewalld )\" | "
- + "sudo -E -n -S -s -- bash ; fi )";
-
- @Test
- public void testAddFirewalldRule() {
- Assert.assertEquals(IptablesCommands.addFirewalldRule(Chain.INPUT,
- Protocol.TCP, 3306, Policy.ACCEPT), addFirewalldRule);
- }
-
- @Test
- public void testFirewalldService() {
- Assert.assertEquals(IptablesCommands.firewalldService("status"), firewalldService);
- }
-
- @Test
- public void testFirewalldServiceRestart() {
- Assert.assertEquals(IptablesCommands.firewalldServiceRestart(), firewalldServiceRestart);
- }
-
- @Test
- public void testFirewalldServiceStart() {
- Assert.assertEquals(IptablesCommands.firewalldServiceStart(), firewalldServiceStart);
- }
-
- @Test
- public void testFirewalldServiceStatus() {
- Assert.assertEquals(IptablesCommands.firewalldServiceStatus(), firewalldServiceStatus);
- }
-
- @Test
- public void testFirewalldServiceStop() {
- Assert.assertEquals(IptablesCommands.firewalldServiceStop(), firewalldServiceStop);
- }
-
- @Test
- public void testFirewalldServiceIsActive() {
- Assert.assertEquals(IptablesCommands.firewalldServiceIsActive(), firewalldServiceIsActive);
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/cf2f7a93/utils/common/src/test/java/brooklyn/util/ssh/IptablesCommandsTest.java
----------------------------------------------------------------------
diff --git a/utils/common/src/test/java/brooklyn/util/ssh/IptablesCommandsTest.java b/utils/common/src/test/java/brooklyn/util/ssh/IptablesCommandsTest.java
deleted file mode 100644
index 7d90dbf..0000000
--- a/utils/common/src/test/java/brooklyn/util/ssh/IptablesCommandsTest.java
+++ /dev/null
@@ -1,81 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package brooklyn.util.ssh;
-
-import org.testng.Assert;
-import org.testng.annotations.Test;
-
-import brooklyn.util.ssh.IptablesCommands.Chain;
-import brooklyn.util.ssh.IptablesCommands.Policy;
-import brooklyn.util.ssh.IptablesCommands.Protocol;
-
-public class IptablesCommandsTest {
-
- private static final String cleanUptptablesRules = "( if test \"$UID\" -eq 0; then ( /sbin/iptables -F ); else sudo -E -n -S -- /sbin/iptables -F; fi )";
-
- public static final String insertIptablesRule = "( if test \"$UID\" -eq 0; then ( /sbin/iptables -I INPUT -i eth0 -p tcp --dport 3306 -j ACCEPT ); "
- + "else sudo -E -n -S -- /sbin/iptables -I INPUT -i eth0 -p tcp --dport 3306 -j ACCEPT; fi )";
- private static final String appendIptablesRule = "( if test \"$UID\" -eq 0; then ( /sbin/iptables -A INPUT -i eth0 -p tcp --dport 3306 -j ACCEPT ); "
- + "else sudo -E -n -S -- /sbin/iptables -A INPUT -i eth0 -p tcp --dport 3306 -j ACCEPT; fi )";
- private static final String insertIptablesRuleAll = "( if test \"$UID\" -eq 0; then ( /sbin/iptables -I INPUT -p tcp --dport 3306 -j ACCEPT ); "
- + "else sudo -E -n -S -- /sbin/iptables -I INPUT -p tcp --dport 3306 -j ACCEPT; fi )";
- private static final String appendIptablesRuleAll = "( if test \"$UID\" -eq 0; then ( /sbin/iptables -A INPUT -p tcp --dport 3306 -j ACCEPT ); "
- + "else sudo -E -n -S -- /sbin/iptables -A INPUT -p tcp --dport 3306 -j ACCEPT; fi )";
- private static final String saveIptablesRules = "( ( if test \"$UID\" -eq 0; then ( service iptables save ); else sudo -E -n -S -- service iptables save; fi ) || " +
- "( ( { which zypper && { echo zypper exists, doing refresh && (( if test \"$UID\" -eq 0; then ( zypper --non-interactive --no-gpg-checks refresh ); else sudo -E -n -S -- zypper --non-interactive --no-gpg-checks refresh; fi ) || true) && ( if test \"$UID\" -eq 0; then ( zypper --non-interactive --no-gpg-checks install iptables-persistent ); else sudo -E -n -S -- zypper --non-interactive --no-gpg-checks install iptables-persistent; fi ) ; } ; } || " +
- "{ which apt-get && { echo apt-get exists, doing update && export DEBIAN_FRONTEND=noninteractive && (( if test \"$UID\" -eq 0; then ( apt-get update ); else sudo -E -n -S -- apt-get update; fi ) || true) && ( if test \"$UID\" -eq 0; then ( apt-get install -y --allow-unauthenticated iptables-persistent ); else sudo -E -n -S -- apt-get install -y --allow-unauthenticated iptables-persistent; fi ) ; } ; } || " +
- "{ which yum && { echo yum exists, doing update && (( if test \"$UID\" -eq 0; then ( yum check-update ); else sudo -E -n -S -- yum check-update; fi ) || true) && (( if test \"$UID\" -eq 0; then ( yum -y install epel-release ); else sudo -E -n -S -- yum -y install epel-release; fi ) || true) && ( if test \"$UID\" -eq 0; then ( yum -y --nogpgcheck install iptables-persistent ); else sudo -E -n -S -- yum -y --nogpgcheck install iptables-persistent; fi ) ; } ; } || " +
- "{ which brew && brew install iptables-persistent ; } || " +
- "{ which port && ( if test \"$UID\" -eq 0; then ( port install iptables-persistent ); else sudo -E -n -S -- port install iptables-persistent; fi ) ; } || " +
- "(( echo \"WARNING: no known/successful package manager to install iptables-persistent, may fail subsequently\" | tee /dev/stderr ) || true) ) && ( if test \"$UID\" -eq 0; then ( /etc/init.d/iptables-persistent save ); else sudo -E -n -S -- /etc/init.d/iptables-persistent save; fi ) ) )";
-
- @Test
- public void testCleanUpIptablesRules() {
- Assert.assertEquals(IptablesCommands.cleanUpIptablesRules(), cleanUptptablesRules);
- }
-
- @Test
- public void testInsertIptablesRules() {
- Assert.assertEquals(IptablesCommands.insertIptablesRule(Chain.INPUT, "eth0", Protocol.TCP, 3306, Policy.ACCEPT),
- insertIptablesRule);
- }
-
- @Test
- public void testAppendIptablesRules() {
- Assert.assertEquals(IptablesCommands.appendIptablesRule(Chain.INPUT, "eth0", Protocol.TCP, 3306, Policy.ACCEPT),
- appendIptablesRule);
- }
-
- @Test
- public void testInsertIptablesRulesForAllInterfaces() {
- Assert.assertEquals(IptablesCommands.insertIptablesRule(Chain.INPUT, Protocol.TCP, 3306, Policy.ACCEPT),
- insertIptablesRuleAll);
- }
-
- @Test
- public void testAppendIptablesRulesForAllInterfaces() {
- Assert.assertEquals(IptablesCommands.appendIptablesRule(Chain.INPUT, Protocol.TCP, 3306, Policy.ACCEPT),
- appendIptablesRuleAll);
- }
-
- @Test
- public void testSaveIptablesRules() {
- Assert.assertEquals(IptablesCommands.saveIptablesRules(), saveIptablesRules);
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/cf2f7a93/utils/common/src/test/java/brooklyn/util/stream/StreamGobblerTest.java
----------------------------------------------------------------------
diff --git a/utils/common/src/test/java/brooklyn/util/stream/StreamGobblerTest.java b/utils/common/src/test/java/brooklyn/util/stream/StreamGobblerTest.java
deleted file mode 100644
index e0b3885..0000000
--- a/utils/common/src/test/java/brooklyn/util/stream/StreamGobblerTest.java
+++ /dev/null
@@ -1,90 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package brooklyn.util.stream;
-
-import static org.testng.Assert.assertEquals;
-import static org.testng.Assert.assertFalse;
-
-import java.io.ByteArrayInputStream;
-import java.io.ByteArrayOutputStream;
-import java.io.InputStream;
-import java.io.PipedInputStream;
-import java.io.PipedOutputStream;
-
-import org.testng.annotations.Test;
-
-import brooklyn.test.Asserts;
-import brooklyn.util.os.Os;
-
-public class StreamGobblerTest {
- private String NL = Os.LINE_SEPARATOR;
-
- @Test
- public void testGobbleStream() throws Exception {
- byte[] bytes = new byte[] {'a','b','c'};
- InputStream stream = new ByteArrayInputStream(bytes);
- ByteArrayOutputStream out = new ByteArrayOutputStream();
- StreamGobbler gobbler = new StreamGobbler(stream, out, null);
- gobbler.start();
- try {
- gobbler.join(10*1000);
- assertFalse(gobbler.isAlive());
- assertEquals(new String(out.toByteArray()), "abc" + NL);
- } finally {
- gobbler.close();
- gobbler.interrupt();
- }
- }
-
- @Test
- public void testGobbleMultiLineBlockingStream() throws Exception {
- PipedOutputStream pipedOutputStream = new PipedOutputStream();
- PipedInputStream stream = new PipedInputStream(pipedOutputStream);
- ByteArrayOutputStream out = new ByteArrayOutputStream();
- StreamGobbler gobbler = new StreamGobbler(stream, out, null);
- gobbler.start();
- try {
- pipedOutputStream.write("line1\n".getBytes());
- assertEqualsEventually(out, "line1" + NL);
-
- pipedOutputStream.write("line2\n".getBytes());
- assertEqualsEventually(out, "line1" + NL + "line2" + NL);
-
- pipedOutputStream.write("line".getBytes());
- pipedOutputStream.write("3\n".getBytes());
- assertEqualsEventually(out, "line1" + NL + "line2" + NL + "line3" + NL);
-
- pipedOutputStream.close();
-
- gobbler.join(10*1000);
- assertFalse(gobbler.isAlive());
- assertEquals(new String(out.toByteArray()), "line1" + NL + "line2" + NL + "line3" + NL);
- } finally {
- gobbler.close();
- gobbler.interrupt();
- }
- }
-
- private void assertEqualsEventually(final ByteArrayOutputStream out, final String expected) {
- Asserts.succeedsEventually(new Runnable() {
- public void run() {
- assertEquals(new String(out.toByteArray()), expected);
- }});
- }
-}