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/17 21:17:49 UTC
[18/42] incubator-brooklyn git commit: [BROOKLYN-162] Refactor
package in ./core/util
http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a4c0e5fd/core/src/test/java/brooklyn/qa/performance/TaskPerformanceTest.java
----------------------------------------------------------------------
diff --git a/core/src/test/java/brooklyn/qa/performance/TaskPerformanceTest.java b/core/src/test/java/brooklyn/qa/performance/TaskPerformanceTest.java
index 6e4a0d0..c940a36 100644
--- a/core/src/test/java/brooklyn/qa/performance/TaskPerformanceTest.java
+++ b/core/src/test/java/brooklyn/qa/performance/TaskPerformanceTest.java
@@ -26,6 +26,8 @@ import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
+import org.apache.brooklyn.core.util.task.BasicExecutionManager;
+import org.apache.brooklyn.core.util.task.SingleThreadedScheduler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.testng.annotations.BeforeMethod;
@@ -33,8 +35,6 @@ import org.testng.annotations.Test;
import brooklyn.util.collections.MutableMap;
import brooklyn.util.exceptions.Exceptions;
-import brooklyn.util.task.BasicExecutionManager;
-import brooklyn.util.task.SingleThreadedScheduler;
import brooklyn.util.time.Time;
import com.google.common.collect.ImmutableList;
http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a4c0e5fd/core/src/test/java/brooklyn/test/HttpService.java
----------------------------------------------------------------------
diff --git a/core/src/test/java/brooklyn/test/HttpService.java b/core/src/test/java/brooklyn/test/HttpService.java
index 2710211..80f63f0 100644
--- a/core/src/test/java/brooklyn/test/HttpService.java
+++ b/core/src/test/java/brooklyn/test/HttpService.java
@@ -40,10 +40,10 @@ import org.eclipse.jetty.webapp.WebAppContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.apache.brooklyn.api.location.PortRange;
+import org.apache.brooklyn.core.util.ResourceUtils;
+import org.apache.brooklyn.core.util.crypto.SecureKeys;
import org.apache.brooklyn.location.basic.LocalhostMachineProvisioningLocation;
-import brooklyn.util.ResourceUtils;
-import brooklyn.util.crypto.SecureKeys;
import brooklyn.util.javalang.Threads;
import brooklyn.util.os.Os;
http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a4c0e5fd/core/src/test/java/brooklyn/test/policy/TestEnricher.java
----------------------------------------------------------------------
diff --git a/core/src/test/java/brooklyn/test/policy/TestEnricher.java b/core/src/test/java/brooklyn/test/policy/TestEnricher.java
index c204c8b..88cc362 100644
--- a/core/src/test/java/brooklyn/test/policy/TestEnricher.java
+++ b/core/src/test/java/brooklyn/test/policy/TestEnricher.java
@@ -23,6 +23,7 @@ import java.util.Map;
import org.apache.brooklyn.api.entity.Entity;
import org.apache.brooklyn.api.event.AttributeSensor;
+import org.apache.brooklyn.core.util.flags.SetFromFlag;
import com.google.common.reflect.TypeToken;
@@ -30,7 +31,6 @@ import brooklyn.config.ConfigKey;
import brooklyn.enricher.basic.AbstractEnricher;
import brooklyn.entity.basic.ConfigKeys;
import brooklyn.event.basic.BasicConfigKey;
-import brooklyn.util.flags.SetFromFlag;
public class TestEnricher extends AbstractEnricher {
@SetFromFlag("confName")
http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a4c0e5fd/core/src/test/java/brooklyn/test/policy/TestPolicy.java
----------------------------------------------------------------------
diff --git a/core/src/test/java/brooklyn/test/policy/TestPolicy.java b/core/src/test/java/brooklyn/test/policy/TestPolicy.java
index b93450c..184eb4e 100644
--- a/core/src/test/java/brooklyn/test/policy/TestPolicy.java
+++ b/core/src/test/java/brooklyn/test/policy/TestPolicy.java
@@ -22,12 +22,12 @@ import java.util.Collections;
import java.util.Map;
import org.apache.brooklyn.api.event.AttributeSensor;
+import org.apache.brooklyn.core.util.flags.SetFromFlag;
import brooklyn.config.ConfigKey;
import brooklyn.entity.basic.ConfigKeys;
import brooklyn.event.basic.BasicConfigKey;
import brooklyn.policy.basic.AbstractPolicy;
-import brooklyn.util.flags.SetFromFlag;
import com.google.common.reflect.TypeToken;
http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a4c0e5fd/core/src/test/java/brooklyn/util/BrooklynMavenArtifactsTest.java
----------------------------------------------------------------------
diff --git a/core/src/test/java/brooklyn/util/BrooklynMavenArtifactsTest.java b/core/src/test/java/brooklyn/util/BrooklynMavenArtifactsTest.java
deleted file mode 100644
index 0fcfdf7..0000000
--- a/core/src/test/java/brooklyn/util/BrooklynMavenArtifactsTest.java
+++ /dev/null
@@ -1,96 +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;
-
-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.maven.MavenArtifact;
-import brooklyn.util.maven.MavenRetriever;
-import brooklyn.util.stream.Streams;
-import brooklyn.util.text.Strings;
-import brooklyn.util.time.Duration;
-import brooklyn.util.time.Time;
-
-@Test
-public class BrooklynMavenArtifactsTest {
-
- private static final Logger log = LoggerFactory.getLogger(BrooklynMavenArtifactsTest.class);
-
- @Test(groups="Integration")
- public void testUtilsCommon() {
- ResourceUtils.create(this).checkUrlExists(BrooklynMavenArtifacts.localUrlForJar("brooklyn-utils-common"));
- }
-
- @Test(groups="Integration")
- public void testExampleWar() {
- String url = BrooklynMavenArtifacts.localUrl("example", "brooklyn-example-hello-world-sql-webapp", "war");
- ResourceUtils.create(this).checkUrlExists(url);
- log.info("found example war at: "+url);
- }
-
- @Test(groups="Integration")
- // runs without internet but doesn't assert what it should, and can take a long time, so integration
- public void testBadExampleWar() {
- String url = BrooklynMavenArtifacts.localUrl("example", "brooklyn-example-GOODBYE-world-sql-webapp", "war");
- Assert.assertFalse(ResourceUtils.create(this).doesUrlExist(url), "should not exist: "+url);
- }
-
- public void testHostedIsHttp() {
- String common = BrooklynMavenArtifacts.hostedUrlForJar("brooklyn-utils-common");
- log.info("online should be at: "+common);
- Assert.assertTrue(common.startsWith("http"));
- }
-
- @Test(groups="Integration")
- public void testHistoricHosted() {
- // NB: this should be a version known to be up at sonatype or maven central, NOT necessarily the current version!
- String snapshot = MavenRetriever.hostedUrl(MavenArtifact.fromCoordinate("org.apache.brooklyn:brooklyn-utils-common:jar:0.7.0-SNAPSHOT"));
- log.info("Sample snapshot URL is: "+snapshot);
- checkValidArchive(snapshot);
- ResourceUtils.create(this).checkUrlExists(snapshot);
-
- // NB: this should be a version known to be up at sonatype or maven central, NOT necessarily the current version!
- String release = MavenRetriever.hostedUrl(MavenArtifact.fromCoordinate("io.brooklyn:brooklyn-utils-common:jar:0.6.0"));
- log.info("Sample release URL is: "+release);
- checkValidArchive(release);
- }
-
- private void checkValidArchive(final String url) {
- // Note have seen response code 500 from repository.apache.org, for
- // https://repository.apache.org/service/local/artifact/maven/redirect?r=snapshots&v=0.7.0-SNAPSHOT&g=org.apache.brooklyn&a=brooklyn-utils-common&e=jar
- // Therefore willing to retry, rather than failing immediately.
- Asserts.succeedsEventually(new Runnable() {
- @Override public void run() {
- try {
- byte[] bytes = Streams.readFully(ResourceUtils.create(this).getResourceFromUrl(url));
- // confirm this follow redirects!
- Assert.assertTrue(bytes.length > 100*1000, "download of "+url+" is suspect ("+Strings.makeSizeString(bytes.length)+")");
- // (could also check it is a zip etc)
- } catch (Exception e) {
- throw Exceptions.propagate(e);
- }
- }});
- }
-
-}
http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a4c0e5fd/core/src/test/java/brooklyn/util/ResourceUtilsHttpTest.java
----------------------------------------------------------------------
diff --git a/core/src/test/java/brooklyn/util/ResourceUtilsHttpTest.java b/core/src/test/java/brooklyn/util/ResourceUtilsHttpTest.java
deleted file mode 100644
index daac00a..0000000
--- a/core/src/test/java/brooklyn/util/ResourceUtilsHttpTest.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;
-
-import static org.testng.Assert.assertEquals;
-import static org.testng.Assert.assertFalse;
-
-import java.io.IOException;
-import java.io.InputStream;
-
-import org.apache.http.HttpException;
-import org.apache.http.HttpRequest;
-import org.apache.http.HttpResponse;
-import org.apache.http.HttpStatus;
-import org.apache.http.entity.StringEntity;
-import org.apache.http.localserver.RequestBasicAuth;
-import org.apache.http.localserver.ResponseBasicUnauthorized;
-import org.apache.http.protocol.HttpContext;
-import org.apache.http.protocol.HttpRequestHandler;
-import org.apache.http.protocol.ResponseServer;
-import org.testng.annotations.AfterClass;
-import org.testng.annotations.BeforeClass;
-import org.testng.annotations.Test;
-
-import brooklyn.test.TestHttpRequestHandler;
-import brooklyn.test.TestHttpServer;
-import brooklyn.util.stream.Streams;
-import brooklyn.util.text.Strings;
-
-public class ResourceUtilsHttpTest {
- private ResourceUtils utils;
- private TestHttpServer server;
- private String baseUrl;
-
- @BeforeClass(alwaysRun=true)
- public void setUp() throws Exception {
- utils = ResourceUtils.create(this, "mycontext");
- server = new TestHttpServer()
- .interceptor(new ResponseServer())
- .interceptor(new ResponseBasicUnauthorized())
- .interceptor(new RequestBasicAuth())
- .handler("/simple", new TestHttpRequestHandler().response("OK"))
- .handler("/empty", new TestHttpRequestHandler().code(HttpStatus.SC_NO_CONTENT))
- .handler("/missing", new TestHttpRequestHandler().code(HttpStatus.SC_NOT_FOUND).response("Missing"))
- .handler("/redirect", new TestHttpRequestHandler().code(HttpStatus.SC_MOVED_TEMPORARILY).response("Redirect").header("Location", "/simple"))
- .handler("/cycle", new TestHttpRequestHandler().code(HttpStatus.SC_MOVED_TEMPORARILY).response("Redirect").header("Location", "/cycle"))
- .handler("/secure", new TestHttpRequestHandler().code(HttpStatus.SC_MOVED_TEMPORARILY).response("Redirect").header("Location", "https://0.0.0.0/"))
- .handler("/auth", new AuthHandler("test", "test", "OK"))
- .handler("/auth_escape", new AuthHandler("test@me:/", "test", "OK"))
- .handler("/auth_escape2", new AuthHandler("test@me:test", "", "OK"))
- .handler("/no_credentials", new CheckNoCredentials())
- .start();
- baseUrl = server.getUrl();
- }
-
- @AfterClass(alwaysRun=true)
- public void tearDown() throws Exception {
- server.stop();
- }
-
- @Test
- public void testGet() throws Exception {
- InputStream stream = utils.getResourceFromUrl(baseUrl + "/simple");
- assertEquals(Streams.readFullyString(stream), "OK");
- }
-
- @Test
- public void testGetEmpty() throws Exception {
- InputStream stream = utils.getResourceFromUrl(baseUrl + "/empty");
- assertEquals(Streams.readFullyString(stream), "");
- }
-
- @Test
- public void testGetProtected() throws Exception {
- String url = baseUrl.replace("http://", "http://test:test@") + "/auth";
- InputStream stream = utils.getResourceFromUrl(url);
- assertEquals(Streams.readFullyString(stream), "OK");
- }
-
- @Test
- public void testGetProtectedEscape() throws Exception {
- String url = baseUrl.replace("http://", "http://test%40me%3A%2F:test@") + "/auth_escape";
- InputStream stream = utils.getResourceFromUrl(url);
- assertEquals(Streams.readFullyString(stream), "OK");
- }
-
- @Test
- public void testGetProtectedEscape2() throws Exception {
- String url = baseUrl.replace("http://", "http://test%40me%3Atest@") + "/auth_escape2";
- InputStream stream = utils.getResourceFromUrl(url);
- assertEquals(Streams.readFullyString(stream), "OK");
- }
-
- @Test(expectedExceptions = RuntimeException.class)
- public void testProtectedFailsWithoutCredentials() throws Exception {
- utils.getResourceFromUrl(baseUrl + "/auth");
- }
-
- @Test
- public void testInvalidCredentialsNotPassed() throws Exception {
- String url = baseUrl + "/no_credentials?no:auth@needed";
- InputStream stream = utils.getResourceFromUrl(url);
- assertEquals(Streams.readFullyString(stream), "OK");
- }
-
- @Test
- public void testRedirect() throws Exception {
- InputStream stream = utils.getResourceFromUrl(baseUrl + "/redirect");
- assertEquals(Streams.readFullyString(stream), "OK");
- }
-
- @Test(expectedExceptions = RuntimeException.class)
- public void testCycleRedirect() throws Exception {
- InputStream stream = utils.getResourceFromUrl(baseUrl + "/cycle");
- assertEquals(Streams.readFullyString(stream), "OK");
- }
-
- @Test(expectedExceptions = RuntimeException.class)
- public void testGetMissing() throws Exception {
- utils.getResourceFromUrl(baseUrl + "/missing");
- }
-
- @Test(expectedExceptions = RuntimeException.class)
- public void testFollowsProtoChange() throws Exception {
- utils.getResourceFromUrl(baseUrl + "/secure");
- }
-
- // See https://github.com/brooklyncentral/brooklyn/issues/1338
- @Test(groups={"Integration"})
- public void testResourceFromUrlFollowsRedirect() throws Exception {
- String contents = new ResourceUtils(this).getResourceAsString("http://bit.ly/brooklyn-visitors-creation-script");
- assertFalse(contents.contains("bit.ly"), "contents="+contents);
- }
-
- private static class AuthHandler implements HttpRequestHandler {
- private String username;
- private String password;
- private String responseBody;
-
- public AuthHandler(String username, String password, String response) {
- this.username = username;
- this.password = password;
- this.responseBody = response;
- }
-
- @Override
- public void handle(HttpRequest request, HttpResponse response, HttpContext context) throws HttpException, IOException {
- String creds = (String) context.getAttribute("creds");
- if (creds == null || !creds.equals(getExpectedCredentials())) {
- response.setStatusCode(HttpStatus.SC_UNAUTHORIZED);
- } else {
- response.setEntity(new StringEntity(responseBody));
- }
- }
-
- private String getExpectedCredentials() {
- if (Strings.isEmpty(password)) {
- return username;
- } else {
- return username + ":" + password;
- }
- }
-
- }
-
- private static class CheckNoCredentials implements HttpRequestHandler {
-
- @Override
- public void handle(HttpRequest request, HttpResponse response,
- HttpContext context) throws HttpException, IOException {
- String creds = (String) context.getAttribute("creds");
- if (creds == null) {
- response.setEntity(new StringEntity("OK"));
- } else {
- response.setStatusCode(HttpStatus.SC_BAD_REQUEST);
- }
- }
-
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a4c0e5fd/core/src/test/java/brooklyn/util/ResourceUtilsTest.java
----------------------------------------------------------------------
diff --git a/core/src/test/java/brooklyn/util/ResourceUtilsTest.java b/core/src/test/java/brooklyn/util/ResourceUtilsTest.java
deleted file mode 100644
index de54ebb..0000000
--- a/core/src/test/java/brooklyn/util/ResourceUtilsTest.java
+++ /dev/null
@@ -1,189 +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;
-
-import static org.testng.Assert.assertEquals;
-import static org.testng.Assert.assertFalse;
-import static org.testng.Assert.assertNotNull;
-import static org.testng.Assert.assertTrue;
-
-import java.io.ByteArrayInputStream;
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.InputStream;
-import java.net.URL;
-import java.util.List;
-import java.util.NoSuchElementException;
-import java.util.Properties;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.testng.annotations.AfterClass;
-import org.testng.annotations.BeforeClass;
-import org.testng.annotations.Test;
-
-import brooklyn.util.net.Urls;
-import brooklyn.util.os.Os;
-import brooklyn.util.stream.Streams;
-import brooklyn.util.text.Identifiers;
-
-import com.google.common.base.Charsets;
-import com.google.common.collect.ImmutableList;
-import com.google.common.collect.Iterables;
-import com.google.common.io.Files;
-
-public class ResourceUtilsTest {
-
- private static final Logger log = LoggerFactory.getLogger(ResourceUtilsTest.class);
-
- private String tempFileContents = "abc";
- private ResourceUtils utils;
- private File tempFile;
-
- @BeforeClass(alwaysRun=true)
- public void setUp() throws Exception {
- utils = ResourceUtils.create(this, "mycontext");
- tempFile = Os.writeToTempFile(new ByteArrayInputStream(tempFileContents.getBytes()), "resourceutils-test", ".txt");
- }
-
- @AfterClass(alwaysRun=true)
- public void tearDown() throws Exception {
- if (tempFile != null) tempFile.delete();
- }
-
- @Test
- public void testWriteStreamToTempFile() throws Exception {
- File tempFileLocal = Os.writeToTempFile(new ByteArrayInputStream("mycontents".getBytes()), "resourceutils-test", ".txt");
- try {
- List<String> lines = Files.readLines(tempFileLocal, Charsets.UTF_8);
- assertEquals(lines, ImmutableList.of("mycontents"));
- } finally {
- tempFileLocal.delete();
- }
- }
-
- @Test
- public void testPropertiesStreamToTempFile() throws Exception {
- Properties props = new Properties();
- props.setProperty("mykey", "myval");
- File tempFileLocal = Os.writePropertiesToTempFile(props, "resourceutils-test", ".txt");
- FileInputStream fis = null;
- try {
- fis = new FileInputStream(tempFileLocal);
- Properties props2 = new Properties();
- props2.load(fis);
- assertEquals(props2.getProperty("mykey"), "myval");
- } finally {
- Streams.closeQuietly(fis);
- tempFileLocal.delete();
- }
- }
-
- @Test
- public void testGetResourceViaClasspathWithPrefix() throws Exception {
- InputStream stream = utils.getResourceFromUrl("classpath://brooklyn/config/sample.properties");
- assertNotNull(stream);
- }
-
- @Test
- public void testGetResourceViaClasspathWithoutPrefix() throws Exception {
- InputStream stream = utils.getResourceFromUrl("/brooklyn/config/sample.properties");
- assertNotNull(stream);
- }
-
- @Test
- public void testGetResourceViaFileWithPrefix() throws Exception {
- // The correct format for file URLs is file:///<absolute path>.
- // On UNIX file:///tmp.
- // On Windows both file:/C:/temp and file:///C:/temp are supported by Java,
- // while Windows itself supports the latter only.
- // Note that file://C:/temp is *wrong*, because C: is interpreted as the host
- InputStream stream = utils.getResourceFromUrl(tempFile.toURI().toURL().toString());
- assertEquals(Streams.readFullyString(stream), tempFileContents);
- }
-
- @Test
- public void testGetResourceViaFileWithoutPrefix() throws Exception {
- InputStream stream = utils.getResourceFromUrl(tempFile.getAbsolutePath());
- assertEquals(Streams.readFullyString(stream), tempFileContents);
- }
-
- @Test
- public void testClassLoaderDir() throws Exception {
- String d = utils.getClassLoaderDir();
- log.info("Found resource "+this+" in: "+d);
- assertTrue(new File(d, "brooklyn/util/").exists());
- }
-
- @Test
- public void testClassLoaderDirFromJar() throws Exception {
- String d = utils.getClassLoaderDir("java/lang/Object.class");
- log.info("Found Object in: "+d);
- assertTrue(d.toLowerCase().endsWith(".jar"));
- }
-
- @Test
- public void testClassLoaderDirFromJarWithSlash() throws Exception {
- String d = utils.getClassLoaderDir("/java/lang/Object.class");
- log.info("Found Object in: "+d);
- assertTrue(d.toLowerCase().endsWith(".jar"));
- }
-
- @Test(expectedExceptions={NoSuchElementException.class})
- public void testClassLoaderDirNotFound() throws Exception {
- String d = utils.getClassLoaderDir("/somewhere/not/found/XXX.xxx");
- // above should fail
- log.warn("Uh oh found imaginary resource in: "+d);
- }
-
- @Test(groups="Integration")
- public void testGetResourceViaSftp() throws Exception {
- InputStream stream = utils.getResourceFromUrl("sftp://localhost:"+tempFile.getAbsolutePath());
- assertEquals(Streams.readFullyString(stream), tempFileContents);
- }
-
- @Test(groups="Integration")
- public void testGetResourceViaSftpWithUsername() throws Exception {
- String user = System.getProperty("user.name");
- InputStream stream = utils.getResourceFromUrl("sftp://"+user+"@localhost:"+tempFile.getAbsolutePath());
- assertEquals(Streams.readFullyString(stream), tempFileContents);
- }
-
- @Test
- public void testDataUrl() throws Exception {
- assertEquals(utils.getResourceAsString("data:,hello"), "hello");
- assertEquals(utils.getResourceAsString("data:,hello%20world"), "hello world");
- // above is correct. below are not valid ... but we accept them anyway
- assertEquals(utils.getResourceAsString("data:hello"), "hello");
- assertEquals(utils.getResourceAsString("data://hello"), "hello");
- assertEquals(utils.getResourceAsString("data:hello world"), "hello world");
- assertEquals(utils.getResourceAsString(Urls.asDataUrlBase64("hello world")), "hello world");
-
- String longString = Identifiers.makeRandomId(256);
- for (int a=32; a<128; a++) longString += (char)a;
- assertEquals(utils.getResourceAsString(Urls.asDataUrlBase64(longString)), longString);
- }
-
- @Test
- public void testGetResources() {
- Iterable<URL> manifests = ResourceUtils.create().getResources("META-INF/MANIFEST.MF");
- assertFalse(Iterables.isEmpty(manifests));
- }
-
-}
http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a4c0e5fd/core/src/test/java/brooklyn/util/config/ConfigBagTest.java
----------------------------------------------------------------------
diff --git a/core/src/test/java/brooklyn/util/config/ConfigBagTest.java b/core/src/test/java/brooklyn/util/config/ConfigBagTest.java
deleted file mode 100644
index 93cf6ed..0000000
--- a/core/src/test/java/brooklyn/util/config/ConfigBagTest.java
+++ /dev/null
@@ -1,191 +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.config;
-
-import static org.testng.Assert.assertEquals;
-
-import java.util.List;
-import java.util.Map;
-import java.util.concurrent.ConcurrentHashMap;
-import java.util.concurrent.atomic.AtomicInteger;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.testng.Assert;
-import org.testng.annotations.Test;
-
-import brooklyn.config.ConfigKey;
-import brooklyn.entity.basic.ConfigKeys;
-import brooklyn.util.collections.MutableList;
-import brooklyn.util.collections.MutableMap;
-import brooklyn.util.exceptions.Exceptions;
-import brooklyn.util.time.Duration;
-
-public class ConfigBagTest {
-
- @SuppressWarnings("unused")
- private static final Logger log = LoggerFactory.getLogger(ConfigBagTest.class);
-
- private static final ConfigKey<String> K1 = ConfigKeys.newStringConfigKey("k1");
- private static final ConfigKey<String> K2 = ConfigKeys.newStringConfigKey("k2");
- private static final ConfigKey<String> K3 = ConfigKeys.newStringConfigKey("k3");
-
- @Test
- public void testPutAndGet() {
- ConfigBag bag = ConfigBag.newInstance();
- bag.put(K1, "v1");
- assertEquals(bag.get(K1), "v1");
- }
-
- @Test
- public void testPutStringAndGet() {
- ConfigBag bag = ConfigBag.newInstance();
- bag.putAsStringKey(K1.getName(), "v1");
- assertEquals(bag.get(K1), "v1");
- }
-
- @Test
- public void testUnused() {
- ConfigBag bag = ConfigBag.newInstance();
- bag.put(K1, "v1");
- bag.put(K2, "v2a");
- assertEquals(bag.get(K1), "v1");
- assertEquals(bag.getUnusedConfig().size(), 1);
- assertEquals(bag.peek(K2), "v2a");
- assertEquals(bag.getUnusedConfig().size(), 1);
- assertEquals(bag.get(K2), "v2a");
- Assert.assertTrue(bag.getUnusedConfig().isEmpty());
- }
-
- @Test
- public void testOrder() {
- ConfigBag bag = ConfigBag.newInstance();
- bag.put(K1, "v1");
- bag.put(K2, "v2");
- bag.put(K3, "v3");
- Assert.assertEquals(MutableList.copyOf(bag.getAllConfig().keySet()), MutableList.of(K1.getName(), K2.getName(), K3.getName()));
- Assert.assertEquals(MutableList.copyOf(bag.getAllConfig().values()), MutableList.of("v1", "v2", "v3"));
- }
-
- @Test
- public void testCopyOverwriteAndGet() {
- ConfigBag bag1 = ConfigBag.newInstance();
- bag1.put(K1, "v1");
- bag1.put(K2, "v2a");
- bag1.put(K3, "v3");
- assertEquals(bag1.get(K1), "v1");
-
- ConfigBag bag2 = ConfigBag.newInstanceCopying(bag1).putAll(MutableMap.of(K2, "v2b"));
- assertEquals(bag1.getUnusedConfig().size(), 2);
- assertEquals(bag2.getUnusedConfig().size(), 2);
-
- assertEquals(bag2.get(K1), "v1");
- assertEquals(bag1.get(K2), "v2a");
- assertEquals(bag1.getUnusedConfig().size(), 1);
- assertEquals(bag2.getUnusedConfig().size(), 2);
-
- assertEquals(bag2.get(K2), "v2b");
- assertEquals(bag2.getUnusedConfig().size(), 1);
-
- assertEquals(bag2.get(K3), "v3");
- assertEquals(bag2.getUnusedConfig().size(), 0);
- assertEquals(bag1.getUnusedConfig().size(), 1);
- }
-
- @Test
- public void testCopyExtendingAndGet() {
- ConfigBag bag1 = ConfigBag.newInstance();
- bag1.put(K1, "v1");
- bag1.put(K2, "v2a");
- bag1.put(K3, "v3");
- assertEquals(bag1.get(K1), "v1");
-
- ConfigBag bag2 = ConfigBag.newInstanceExtending(bag1, null).putAll(MutableMap.of(K2, "v2b"));
- assertEquals(bag1.getUnusedConfig().size(), 2);
- assertEquals(bag2.getUnusedConfig().size(), 2, "unused are: "+bag2.getUnusedConfig());
-
- assertEquals(bag2.get(K1), "v1");
- assertEquals(bag1.get(K2), "v2a");
- assertEquals(bag1.getUnusedConfig().size(), 1);
- assertEquals(bag2.getUnusedConfig().size(), 2);
-
- assertEquals(bag2.get(K2), "v2b");
- assertEquals(bag2.getUnusedConfig().size(), 1);
-
- assertEquals(bag2.get(K3), "v3");
- assertEquals(bag2.getUnusedConfig().size(), 0);
- // when extended, the difference is that parent is also marked
- assertEquals(bag1.getUnusedConfig().size(), 0);
- }
-
- @Test
- public void testConcurrent() throws InterruptedException {
- ConfigBag bag = ConfigBag.newInstance();
- bag.put(K1, "v1");
- bag.put(K2, "v2");
- bag.put(K3, "v3");
- runConcurrentTest(bag, 10, Duration.millis(50));
- }
-
- @Test(groups="Integration")
- public void testConcurrentBig() throws InterruptedException {
- ConfigBag bag = ConfigBag.newInstance();
- bag.put(K1, "v1");
- bag.put(K2, "v2");
- bag.put(K3, "v3");
- runConcurrentTest(bag, 20, Duration.seconds(5));
- }
-
- private void runConcurrentTest(final ConfigBag bag, int numThreads, Duration time) throws InterruptedException {
- List<Thread> threads = MutableList.of();
- final Map<Thread,Exception> exceptions = new ConcurrentHashMap<Thread,Exception>();
- final AtomicInteger successes = new AtomicInteger();
- for (int i=0; i<numThreads; i++) {
- Thread t = new Thread() {
- @Override
- public void run() {
- try {
- while (!interrupted()) {
- if (Math.random()<0.9)
- bag.put(ConfigKeys.newStringConfigKey("k"+((int)(10*Math.random()))), "v"+((int)(10*Math.random())));
- if (Math.random()<0.8)
- bag.get(ConfigKeys.newStringConfigKey("k"+((int)(10*Math.random()))));
- if (Math.random()<0.2)
- bag.copy(bag);
- if (Math.random()<0.6)
- bag.remove(ConfigKeys.newStringConfigKey("k"+((int)(10*Math.random()))));
- successes.incrementAndGet();
- }
- } catch (Exception e) {
- exceptions.put(Thread.currentThread(), e);
- Exceptions.propagateIfFatal(e);
- }
- }
- };
- t.setName("ConfigBagTest-concurrent-thread-"+i);
- threads.add(t);
- }
- for (Thread t: threads) t.start();
- time.countdownTimer().waitForExpiry();
- for (Thread t: threads) t.interrupt();
- for (Thread t: threads) t.join();
- Assert.assertTrue(exceptions.isEmpty(), "Got "+exceptions.size()+"/"+numThreads+" exceptions ("+successes.get()+" successful): "+exceptions);
- }
-
-}
http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a4c0e5fd/core/src/test/java/brooklyn/util/crypto/SecureKeysAndSignerTest.java
----------------------------------------------------------------------
diff --git a/core/src/test/java/brooklyn/util/crypto/SecureKeysAndSignerTest.java b/core/src/test/java/brooklyn/util/crypto/SecureKeysAndSignerTest.java
deleted file mode 100644
index 1bdb0a3..0000000
--- a/core/src/test/java/brooklyn/util/crypto/SecureKeysAndSignerTest.java
+++ /dev/null
@@ -1,166 +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.crypto;
-
-import java.io.File;
-import java.io.FileInputStream;
-import java.nio.charset.Charset;
-import java.security.KeyPair;
-import java.security.PublicKey;
-import java.security.cert.CertificateException;
-import java.security.cert.X509Certificate;
-
-import org.testng.Assert;
-import org.testng.annotations.Test;
-
-import brooklyn.util.ResourceUtils;
-import brooklyn.util.crypto.SecureKeys.PassphraseProblem;
-import brooklyn.util.os.Os;
-
-import com.google.common.io.Files;
-
-public class SecureKeysAndSignerTest {
-
- // a bit slow, so marked as integration (but possibly due to leftover rebind-cleanup, benign failures writing to /tmp/xx)
- @Test(groups="Integration")
- public void testGenerateSignedKeys() throws Exception {
- FluentKeySigner signer = new FluentKeySigner("the-root").
- validForYears(2).
- selfsign();
- X509Certificate signerCert = signer.getAuthorityCertificate();
-
- KeyPair aKey = SecureKeys.newKeyPair();
- X509Certificate aCert = signer.newCertificateFor("A", aKey);
-
- KeyPair bKey = SecureKeys.newKeyPair();
- X509Certificate bCert = signer.newCertificateFor("B", bKey);
-
- FluentKeySigner selfSigner1 = new FluentKeySigner("self1").selfsign();
- X509Certificate selfCert1 = selfSigner1.getAuthorityCertificate();
-
- SecureKeys.getTrustManager(aCert).checkClientTrusted(new X509Certificate[] { aCert }, "RSA");
- SecureKeys.getTrustManager(signerCert).checkClientTrusted(new X509Certificate[] { signerCert }, "RSA");
-
- try {
- SecureKeys.getTrustManager(aCert).checkClientTrusted(new X509Certificate[] { bCert }, "RSA");
- Assert.fail("Trust manager for A should not accept B");
- } catch (CertificateException e) { /* expected */ }
-
-// SecureKeys.getTrustManager(signerCert).checkClientTrusted(new X509Certificate[] { aCert }, "RSA");
- // NB, the above failes; we have to convert to a canonical implementation, handled by the following
-
- Assert.assertTrue(SecureKeys.isCertificateAuthorizedBy(signerCert, signerCert));
- Assert.assertTrue(SecureKeys.isCertificateAuthorizedBy(aCert, signerCert));
- Assert.assertTrue(SecureKeys.isCertificateAuthorizedBy(bCert, signerCert));
- Assert.assertFalse(SecureKeys.isCertificateAuthorizedBy(signerCert, aCert));
- Assert.assertFalse(SecureKeys.isCertificateAuthorizedBy(bCert, aCert));
-
- Assert.assertTrue(SecureKeys.isCertificateAuthorizedBy(selfCert1, selfCert1));
- Assert.assertFalse(SecureKeys.isCertificateAuthorizedBy(selfCert1, signerCert));
- }
-
- @Test
- public void testInjectCertificateAuthority() throws Exception {
- KeyPair caKey = SecureKeys.newKeyPair();
- X509Certificate caCert = new FluentKeySigner("the-root", caKey).selfsign().getAuthorityCertificate();
-
- FluentKeySigner signer = new FluentKeySigner(caCert, caKey);
- Assert.assertEquals("the-root", signer.getCommonName());
-
- KeyPair aKey = SecureKeys.newKeyPair();
- X509Certificate aCert = signer.newCertificateFor("A", aKey);
-
- Assert.assertTrue(SecureKeys.isCertificateAuthorizedBy(aCert, caCert));
- }
-
- @Test
- public void testReadRsaKey() throws Exception {
- KeyPair key = SecureKeys.readPem(ResourceUtils.create(this).getResourceFromUrl("classpath://brooklyn/util/crypto/sample_rsa.pem"), null);
- checkNonTrivial(key);
- }
-
- @Test(expectedExceptions=IllegalStateException.class)
- public void testReadRsaPublicKeyAsPemFails() throws Exception {
- // should fail; see next test
- SecureKeys.readPem(ResourceUtils.create(this).getResourceFromUrl("classpath://brooklyn/util/crypto/sample_rsa.pem.pub"), null);
- }
-
- @Test
- public void testReadRsaPublicKeyAsAuthKeysWorks() throws Exception {
- PublicKey key = AuthorizedKeysParser.decodePublicKey(
- ResourceUtils.create(this).getResourceAsString("classpath://brooklyn/util/crypto/sample_rsa.pem.pub"));
- KeyPair fromPem = SecureKeys.readPem(ResourceUtils.create(this).getResourceFromUrl("classpath://brooklyn/util/crypto/sample_rsa.pem"), null);
- Assert.assertEquals(key, fromPem.getPublic());
- }
-
- @Test
- public void testEncodeDecodeRsaPublicKey() throws Exception {
- String data = ResourceUtils.create(this).getResourceAsString("classpath://brooklyn/util/crypto/sample_rsa.pem.pub");
- PublicKey key = AuthorizedKeysParser.decodePublicKey(data);
- String data2 = AuthorizedKeysParser.encodePublicKey(key);
- Assert.assertTrue(data.contains(data2), "Expected to find '"+data2+"' in '"+data+"'");
- PublicKey key2 = AuthorizedKeysParser.decodePublicKey(data2);
- Assert.assertEquals(key2, key);
- }
-
- @Test
- public void testEncodeDecodeDsaPublicKey() throws Exception {
- String data = ResourceUtils.create(this).getResourceAsString("classpath://brooklyn/util/crypto/sample_dsa.pem.pub");
- PublicKey key = AuthorizedKeysParser.decodePublicKey(data);
- String data2 = AuthorizedKeysParser.encodePublicKey(key);
- Assert.assertTrue(data.contains(data2), "Expected to find '"+data2+"' in '"+data+"'");
- PublicKey key2 = AuthorizedKeysParser.decodePublicKey(data2);
- Assert.assertEquals(key2, key);
- }
-
- @Test
- public void testReadDsaKey() throws Exception {
- KeyPair key = SecureKeys.readPem(ResourceUtils.create(this).getResourceFromUrl("classpath://brooklyn/util/crypto/sample_dsa.pem"), null);
- checkNonTrivial(key);
- }
-
- @Test(expectedExceptions=Exception.class)
- public void testCantReadRsaPassphraseKeyWithoutPassphrase() throws Exception {
- KeyPair key = SecureKeys.readPem(ResourceUtils.create(this).getResourceFromUrl("classpath://brooklyn/util/crypto/sample_rsa_passphrase.pem"), null);
- checkNonTrivial(key);
- }
-
- @Test(expectedExceptions=PassphraseProblem.class)
- public void testReadRsaPassphraseWithoutKeyFails() throws Exception {
- SecureKeys.readPem(ResourceUtils.create(this).getResourceFromUrl("classpath://brooklyn/util/crypto/sample_rsa_passphrase.pem"), null);
- }
-
- @Test
- public void testReadRsaPassphraseKeyAndWriteWithoutPassphrase() throws Exception {
- KeyPair key = SecureKeys.readPem(ResourceUtils.create(this).getResourceFromUrl("classpath://brooklyn/util/crypto/sample_rsa_passphrase.pem"), "passphrase");
- checkNonTrivial(key);
- File f = Os.newTempFile(getClass(), "brooklyn-sample_rsa_passphrase_without_passphrase.pem");
- Files.write(SecureKeys.stringPem(key), f, Charset.defaultCharset());
- KeyPair key2 = SecureKeys.readPem(new FileInputStream(f), null);
- checkNonTrivial(key2);
- Assert.assertEquals(key2.getPrivate().getEncoded(), key.getPrivate().getEncoded());
- Assert.assertEquals(key2.getPublic().getEncoded(), key.getPublic().getEncoded());
- }
-
- private void checkNonTrivial(KeyPair key) {
- Assert.assertNotEquals(key.getPrivate().getEncoded().length, 0);
- Assert.assertNotEquals(key.getPublic().getEncoded().length, 0);
- }
-
-}
http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a4c0e5fd/core/src/test/java/brooklyn/util/file/ArchiveBuilderTest.java
----------------------------------------------------------------------
diff --git a/core/src/test/java/brooklyn/util/file/ArchiveBuilderTest.java b/core/src/test/java/brooklyn/util/file/ArchiveBuilderTest.java
deleted file mode 100644
index 6469f5a..0000000
--- a/core/src/test/java/brooklyn/util/file/ArchiveBuilderTest.java
+++ /dev/null
@@ -1,193 +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.file;
-
-import static org.testng.Assert.assertEquals;
-import static org.testng.Assert.assertFalse;
-import static org.testng.Assert.assertTrue;
-
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.IOException;
-import java.util.Arrays;
-import java.util.List;
-import java.util.Set;
-import java.util.zip.ZipEntry;
-import java.util.zip.ZipInputStream;
-
-import javax.annotation.Nullable;
-
-import org.testng.annotations.BeforeClass;
-import org.testng.annotations.Test;
-
-import brooklyn.util.collections.MutableSet;
-import brooklyn.util.os.Os;
-import brooklyn.util.text.Identifiers;
-
-import com.google.common.base.Charsets;
-import com.google.common.base.Predicate;
-import com.google.common.base.Predicates;
-import com.google.common.collect.Iterables;
-import com.google.common.collect.Lists;
-import com.google.common.io.Files;
-
-/**
- * Test the operation of the {@link ArchiveBuilder} class.
- */
-@Test
-public class ArchiveBuilderTest {
-
- private File parentDir, tmpDir, tmpDir2;
- private Predicate<ZipEntry> isDirectory = new Predicate<ZipEntry>() {
- @Override
- public boolean apply(@Nullable ZipEntry input) {
- return input.isDirectory();
- }
- };
-
- @BeforeClass
- public void createTmpDirAndFiles() throws IOException {
- parentDir = Os.newTempDir(getClass().getSimpleName());
- Os.deleteOnExitRecursively(parentDir);
- tmpDir = new File(parentDir, Identifiers.makeRandomId(4));
- Os.mkdirs(tmpDir);
- Files.write("abcdef", new File(tmpDir, "data01.txt"), Charsets.US_ASCII);
- Files.write("123456", new File(tmpDir, "data02.txt"), Charsets.US_ASCII);
- Files.write("qqqqqq", new File(tmpDir, "data03.txt"), Charsets.US_ASCII);
-
- tmpDir2 = new File(parentDir, Identifiers.makeRandomId(4));
- Os.mkdirs(tmpDir2);
- Files.write("zzzzzz", new File(tmpDir2, "data04.txt"), Charsets.US_ASCII);
- }
-
- @Test
- public void testCreateZipFromDir() throws Exception {
- File archive = ArchiveBuilder.zip().addDirContentsAt(tmpDir, ".").create();
- archive.deleteOnExit();
-
- List<ZipEntry> entries = Lists.newArrayList();
- ZipInputStream input = new ZipInputStream(new FileInputStream(archive));
- ZipEntry entry = input.getNextEntry();
- while (entry != null) {
- entries.add(entry);
- entry = input.getNextEntry();
- }
- assertEquals(entries.size(), 4);
- Iterable<ZipEntry> directories = Iterables.filter(entries, isDirectory);
- Iterable<ZipEntry> files = Iterables.filter(entries, Predicates.not(isDirectory));
- assertEquals(Iterables.size(directories), 1);
- assertEquals(Iterables.size(files), 3);
- String dirName = Iterables.getOnlyElement(directories).getName();
- assertEquals(dirName, "./");
-
- Set<String> names = MutableSet.of();
- for (ZipEntry file : files) {
- assertTrue(file.getName().startsWith(dirName));
- names.add(file.getName());
- }
- assertTrue(names.contains("./data01.txt"));
- assertFalse(names.contains("./data04.txt"));
- input.close();
- }
-
- @Test
- public void testCreateZipFromTwoDirs() throws Exception {
- File archive = ArchiveBuilder.zip().addDirContentsAt(tmpDir, ".").addDirContentsAt(tmpDir2, ".").create();
- archive.deleteOnExit();
-
- List<ZipEntry> entries = Lists.newArrayList();
- ZipInputStream input = new ZipInputStream(new FileInputStream(archive));
- ZipEntry entry = input.getNextEntry();
- while (entry != null) {
- entries.add(entry);
- entry = input.getNextEntry();
- }
- assertEquals(entries.size(), 5);
- Iterable<ZipEntry> directories = Iterables.filter(entries, isDirectory);
- Iterable<ZipEntry> files = Iterables.filter(entries, Predicates.not(isDirectory));
- assertEquals(Iterables.size(directories), 1);
- assertEquals(Iterables.size(files), 4);
- String dirName = Iterables.getOnlyElement(directories).getName();
- assertEquals(dirName, "./");
-
- Set<String> names = MutableSet.of();
- for (ZipEntry file : files) {
- assertTrue(file.getName().startsWith(dirName));
- names.add(file.getName());
- }
- assertTrue(names.contains("./data01.txt"));
- assertTrue(names.contains("./data04.txt"));
- input.close();
- }
- @Test
- public void testCreateZipFromFiles() throws Exception {
- ArchiveBuilder builder = ArchiveBuilder.zip();
- for (String fileName : Arrays.asList("data01.txt", "data02.txt", "data03.txt")) {
- builder.addAt(new File(tmpDir, fileName), ".");
- }
- File archive = builder.create();
- archive.deleteOnExit();
-
- List<ZipEntry> entries = Lists.newArrayList();
- ZipInputStream input = new ZipInputStream(new FileInputStream(archive));
- ZipEntry entry = input.getNextEntry();
- while (entry != null) {
- entries.add(entry);
- entry = input.getNextEntry();
- }
- assertEquals(entries.size(), 3);
- Iterable<ZipEntry> directories = Iterables.filter(entries, isDirectory);
- Iterable<ZipEntry> files = Iterables.filter(entries, Predicates.not(isDirectory));
- assertTrue(Iterables.isEmpty(directories));
- assertEquals(Iterables.size(files), 3);
- for (ZipEntry file : files) {
- assertTrue(file.getName().startsWith(Os.mergePathsUnix(".", "data")));
- }
- input.close();
- }
-
- @Test
- public void testCreateZipFromFilesWithBaseDir() throws Exception {
- ArchiveBuilder builder = ArchiveBuilder.zip();
- String baseDir = tmpDir.getName();
- for (String fileName : Arrays.asList("data01.txt", "data02.txt", "data03.txt")) {
- builder.addFromLocalBaseDir(parentDir, Os.mergePaths(baseDir, fileName));
- }
- File archive = builder.create();
- archive.deleteOnExit();
-
- List<ZipEntry> entries = Lists.newArrayList();
- ZipInputStream input = new ZipInputStream(new FileInputStream(archive));
- ZipEntry entry = input.getNextEntry();
- while (entry != null) {
- entries.add(entry);
- entry = input.getNextEntry();
- }
- assertEquals(entries.size(), 3);
- Iterable<ZipEntry> directories = Iterables.filter(entries, isDirectory);
- Iterable<ZipEntry> files = Iterables.filter(entries, Predicates.not(isDirectory));
- assertTrue(Iterables.isEmpty(directories));
- assertEquals(Iterables.size(files), 3);
- for (ZipEntry file : files) {
- assertTrue(file.getName().startsWith(Os.mergePathsUnix(".", baseDir)));
- }
- input.close();
- }
-
-}
http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a4c0e5fd/core/src/test/java/brooklyn/util/file/ArchiveUtilsTest.java
----------------------------------------------------------------------
diff --git a/core/src/test/java/brooklyn/util/file/ArchiveUtilsTest.java b/core/src/test/java/brooklyn/util/file/ArchiveUtilsTest.java
deleted file mode 100644
index 6715444..0000000
--- a/core/src/test/java/brooklyn/util/file/ArchiveUtilsTest.java
+++ /dev/null
@@ -1,135 +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.file;
-
-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.Map;
-
-import org.testng.annotations.AfterClass;
-import org.testng.annotations.AfterMethod;
-import org.testng.annotations.BeforeClass;
-import org.testng.annotations.BeforeMethod;
-import org.testng.annotations.Test;
-
-import brooklyn.entity.BrooklynAppUnitTestSupport;
-import org.apache.brooklyn.location.basic.SshMachineLocation;
-import brooklyn.util.ResourceUtils;
-import brooklyn.util.os.Os;
-
-import com.google.api.client.repackaged.com.google.common.base.Joiner;
-import com.google.common.base.Charsets;
-import com.google.common.collect.ImmutableMap;
-import com.google.common.io.Files;
-
-// Test are integration, because relies on ssh/scp via SshMachineLocation
-public class ArchiveUtilsTest extends BrooklynAppUnitTestSupport {
-
- private SshMachineLocation machine;
- private ResourceUtils resourceUtils;
-
- private Map<String, String> archiveContents = ImmutableMap.of("a.txt", "mya");
- private File destDir;
- private File origZip;
- private File origJar;
-
- @BeforeClass(alwaysRun=true)
- public void setUpClass() throws Exception {
- origZip = newZip(archiveContents);
- origJar = Os.newTempFile(ArchiveUtilsTest.class, ".jar");
- Files.copy(origZip, origJar);
- }
-
- @AfterClass(alwaysRun=true)
- public void tearDownClass() throws Exception {
- if (origZip != null) origZip.delete();
- if (origJar != null) origJar.delete();
- }
-
- @BeforeMethod(alwaysRun=true)
- @Override
- public void setUp() throws Exception {
- super.setUp();
- machine = app.newLocalhostProvisioningLocation().obtain();
- resourceUtils = ResourceUtils.create(ArchiveUtilsTest.class);
- destDir = Os.newTempDir(getClass().getSimpleName());
- }
-
- @AfterMethod(alwaysRun=true)
- @Override
- public void tearDown() throws Exception {
- super.tearDown();
- if (destDir != null) Os.deleteRecursively(destDir);
- }
-
- @Test(groups="Integration")
- public void testDeployZipWithNoOptionalArgsSupplied() throws Exception {
- boolean result = ArchiveUtils.deploy(resourceUtils, ImmutableMap.<String, Object>of(), origZip.getAbsolutePath(), machine, destDir.getAbsolutePath(), true, null, null);
- assertTrue(result);
- assertFilesEqual(new File(destDir, origZip.getName()), origZip);
- assertSubFilesEqual(destDir, archiveContents);
- }
-
- @Test(groups="Integration")
- public void testDeployZipDeletingArchiveAfterUnpack() throws Exception {
- boolean result = ArchiveUtils.deploy(resourceUtils, ImmutableMap.<String, Object>of(), origZip.getAbsolutePath(), machine, destDir.getAbsolutePath(), false, null, null);
- assertTrue(result);
- assertFalse(new File(destDir, origZip.getName()).exists());
- assertSubFilesEqual(destDir, archiveContents);
- }
-
- @Test(groups="Integration")
- public void testDeployJarNotUnpacked() throws Exception {
- ArchiveUtils.deploy(origJar.getAbsolutePath(), machine, destDir.getAbsolutePath());
- assertFilesEqual(new File(destDir, origJar.getName()), origJar);
- }
-
- @Test(groups="Integration")
- public void testDeployExplicitDestFile() throws Exception {
- String destFile = "custom-destFile.jar";
- ArchiveUtils.deploy(origJar.getAbsolutePath(), machine, destDir.getAbsolutePath(), destFile);
- assertFilesEqual(new File(destDir, destFile), origJar);
- }
-
- private File newZip(Map<String, String> files) throws Exception {
- File parentDir = Os.newTempDir(getClass().getSimpleName()+"-archive");
- for (Map.Entry<String, String> entry : files.entrySet()) {
- File subFile = new File(Os.mergePaths(parentDir.getAbsolutePath(), entry.getKey()));
- subFile.getParentFile().mkdirs();
- Files.write(entry.getValue(), subFile, Charsets.UTF_8);
- }
- return ArchiveBuilder.zip().addDirContentsAt(parentDir, ".").create();
- }
-
- private void assertFilesEqual(File f1, File f2) throws Exception {
- byte[] bytes1 = Files.asByteSource(f1).read();
- byte[] bytes2 = Files.asByteSource(f1).read();
- assertEquals(bytes1, bytes2, "f1="+f1+"; f2="+f2);
- }
-
- private void assertSubFilesEqual(File parentDir, Map<String, String> files) throws Exception {
- for (Map.Entry<String, String> entry : archiveContents.entrySet()) {
- File subFile = new File(Os.mergePaths(parentDir.getAbsolutePath(), entry.getKey()));
- assertEquals(Joiner.on("\n").join(Files.readLines(subFile, Charsets.UTF_8)), entry.getValue());
- }
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a4c0e5fd/core/src/test/java/brooklyn/util/flags/MethodCoercionsTest.java
----------------------------------------------------------------------
diff --git a/core/src/test/java/brooklyn/util/flags/MethodCoercionsTest.java b/core/src/test/java/brooklyn/util/flags/MethodCoercionsTest.java
deleted file mode 100644
index 4d06ca4..0000000
--- a/core/src/test/java/brooklyn/util/flags/MethodCoercionsTest.java
+++ /dev/null
@@ -1,146 +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.flags;
-
-import brooklyn.util.exceptions.Exceptions;
-import brooklyn.util.guava.Maybe;
-import com.google.common.base.Predicate;
-import com.google.common.collect.ImmutableList;
-import org.testng.annotations.BeforeClass;
-import org.testng.annotations.Test;
-
-import java.lang.reflect.Method;
-import java.util.List;
-
-import static org.testng.Assert.*;
-
-public class MethodCoercionsTest {
-
- private Method singleParameterMethod;
- private Method multiParameterMethod;
- private Method singleCollectionParameterMethod;
-
- @BeforeClass
- public void testFixtureSetUp() {
- try {
- singleParameterMethod = TestClass.class.getMethod("singleParameterMethod", int.class);
- multiParameterMethod = TestClass.class.getMethod("multiParameterMethod", boolean.class, int.class);
- singleCollectionParameterMethod = TestClass.class.getMethod("singleCollectionParameterMethod", List.class);
- } catch (NoSuchMethodException e) {
- throw Exceptions.propagate(e);
- }
- }
-
- @Test
- public void testMatchSingleParameterMethod() throws Exception {
- Predicate<Method> predicate = MethodCoercions.matchSingleParameterMethod("singleParameterMethod", "42");
- assertTrue(predicate.apply(singleParameterMethod));
- assertFalse(predicate.apply(multiParameterMethod));
- assertFalse(predicate.apply(singleCollectionParameterMethod));
- }
-
- @Test
- public void testTryFindAndInvokeSingleParameterMethod() throws Exception {
- TestClass instance = new TestClass();
- Maybe<?> maybe = MethodCoercions.tryFindAndInvokeSingleParameterMethod(instance, "singleParameterMethod", "42");
- assertTrue(maybe.isPresent());
- assertTrue(instance.wasSingleParameterMethodCalled());
- }
-
- @Test
- public void testMatchMultiParameterMethod() throws Exception {
- Predicate<Method> predicate = MethodCoercions.matchMultiParameterMethod("multiParameterMethod", ImmutableList.of("true", "42"));
- assertFalse(predicate.apply(singleParameterMethod));
- assertTrue(predicate.apply(multiParameterMethod));
- assertFalse(predicate.apply(singleCollectionParameterMethod));
- }
-
- @Test
- public void testTryFindAndInvokeMultiParameterMethod() throws Exception {
- TestClass instance = new TestClass();
- Maybe<?> maybe = MethodCoercions.tryFindAndInvokeMultiParameterMethod(instance, "multiParameterMethod", ImmutableList.of("true", "42"));
- assertTrue(maybe.isPresent());
- assertTrue(instance.wasMultiParameterMethodCalled());
- }
-
- @Test
- public void testTryFindAndInvokeBestMatchingMethod() throws Exception {
- TestClass instance = new TestClass();
- Maybe<?> maybe = MethodCoercions.tryFindAndInvokeBestMatchingMethod(instance, "singleParameterMethod", "42");
- assertTrue(maybe.isPresent());
- assertTrue(instance.wasSingleParameterMethodCalled());
-
- instance = new TestClass();
- maybe = MethodCoercions.tryFindAndInvokeBestMatchingMethod(instance, "multiParameterMethod", ImmutableList.of("true", "42"));
- assertTrue(maybe.isPresent());
- assertTrue(instance.wasMultiParameterMethodCalled());
-
- instance = new TestClass();
- maybe = MethodCoercions.tryFindAndInvokeBestMatchingMethod(instance, "singleCollectionParameterMethod", ImmutableList.of("fred", "joe"));
- assertTrue(maybe.isPresent());
- assertTrue(instance.wasSingleCollectionParameterMethodCalled());
- }
-/*
- @Test
- public void testMatchSingleCollectionParameterMethod() throws Exception {
- Predicate<Method> predicate = MethodCoercions.matchSingleCollectionParameterMethod("singleCollectionParameterMethod", ImmutableList.of("42"));
- assertFalse(predicate.apply(singleParameterMethod));
- assertFalse(predicate.apply(multiParameterMethod));
- assertTrue(predicate.apply(singleCollectionParameterMethod));
- }
-
- @Test
- public void testTryFindAndInvokeSingleCollectionParameterMethod() throws Exception {
- TestClass instance = new TestClass();
- Maybe<?> maybe = MethodCoercions.tryFindAndInvokeSingleCollectionParameterMethod(instance, "singleCollectionParameterMethod", ImmutableList.of("42"));
- assertTrue(maybe.isPresent());
- assertTrue(instance.wasSingleCollectionParameterMethodCalled());
- }
-*/
- public static class TestClass {
-
- private boolean singleParameterMethodCalled;
- private boolean multiParameterMethodCalled;
- private boolean singleCollectionParameterMethodCalled;
-
- public void singleParameterMethod(int parameter) {
- singleParameterMethodCalled = true;
- }
-
- public void multiParameterMethod(boolean parameter1, int parameter2) {
- multiParameterMethodCalled = true;
- }
-
- public void singleCollectionParameterMethod(List<String> parameter) {
- singleCollectionParameterMethodCalled = true;
- }
-
- public boolean wasSingleParameterMethodCalled() {
- return singleParameterMethodCalled;
- }
-
- public boolean wasMultiParameterMethodCalled() {
- return multiParameterMethodCalled;
- }
-
- public boolean wasSingleCollectionParameterMethodCalled() {
- return singleCollectionParameterMethodCalled;
- }
- }
-}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a4c0e5fd/core/src/test/java/brooklyn/util/http/BetterMockWebServer.java
----------------------------------------------------------------------
diff --git a/core/src/test/java/brooklyn/util/http/BetterMockWebServer.java b/core/src/test/java/brooklyn/util/http/BetterMockWebServer.java
deleted file mode 100644
index fb76903..0000000
--- a/core/src/test/java/brooklyn/util/http/BetterMockWebServer.java
+++ /dev/null
@@ -1,138 +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.http;
-
-import java.io.IOException;
-import java.net.MalformedURLException;
-import java.net.Proxy;
-import java.net.URL;
-
-import javax.net.ssl.SSLSocketFactory;
-
-import com.google.common.base.Throwables;
-import com.google.mockwebserver.Dispatcher;
-import com.google.mockwebserver.MockResponse;
-import com.google.mockwebserver.MockWebServer;
-import com.google.mockwebserver.RecordedRequest;
-
-/** like MockWebServer (and delegating) but:
- * <li> allows subclassing
- * <li> easy way to create instance which returns localhost for {@link #getHostName()}
- * (since otherwise you can get failures on networks which misconfigure hostname)
- * */
-public class BetterMockWebServer {
-
- final MockWebServer delegate = new MockWebServer();
- String hostname = null;
- boolean isHttps = false;
-
- public static BetterMockWebServer newInstanceLocalhost() {
- return new BetterMockWebServer().setHostName("localhost");
- }
-
- /** use {@link #newInstanceLocalhost()} or subclass */
- protected BetterMockWebServer() {}
-
- public BetterMockWebServer setHostName(String hostname) {
- this.hostname = hostname;
- return this;
- }
-
-
- // --- delegate methods (unchanged)
-
- public void enqueue(MockResponse response) {
- delegate.enqueue(response);
- }
-
- public boolean equals(Object obj) {
- return delegate.equals(obj);
- }
-
- public String getCookieDomain() {
- return delegate.getCookieDomain();
- }
-
- public String getHostName() {
- if (hostname!=null) return hostname;
- return delegate.getHostName();
- }
-
- public int getPort() {
- return delegate.getPort();
- }
-
- public int getRequestCount() {
- return delegate.getRequestCount();
- }
-
- public URL getUrl(String path) {
- try {
- return isHttps
- ? new URL("https://" + getHostName() + ":" + getPort() + path)
- : new URL("http://" + getHostName() + ":" + getPort() + path);
- } catch (MalformedURLException e) {
- throw Throwables.propagate(e);
- }
- }
-
- public int hashCode() {
- return delegate.hashCode();
- }
-
- public void play() throws IOException {
- delegate.play();
- }
-
- public void play(int port) throws IOException {
- delegate.play(port);
- }
-
- public void setBodyLimit(int maxBodyLength) {
- delegate.setBodyLimit(maxBodyLength);
- }
-
- public void setDispatcher(Dispatcher dispatcher) {
- delegate.setDispatcher(dispatcher);
- }
-
- public void shutdown() throws IOException {
- delegate.shutdown();
- }
-
- public RecordedRequest takeRequest() throws InterruptedException {
- return delegate.takeRequest();
- }
-
- public Proxy toProxyAddress() {
- return delegate.toProxyAddress();
- }
-
- public String toString() {
- return delegate.toString();
- }
-
- public void useHttps(SSLSocketFactory sslSocketFactory, boolean tunnelProxy) {
- isHttps = true;
- delegate.useHttps(sslSocketFactory, tunnelProxy);
- }
-
-
-
-}
http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a4c0e5fd/core/src/test/java/brooklyn/util/http/HttpToolIntegrationTest.java
----------------------------------------------------------------------
diff --git a/core/src/test/java/brooklyn/util/http/HttpToolIntegrationTest.java b/core/src/test/java/brooklyn/util/http/HttpToolIntegrationTest.java
deleted file mode 100644
index dc9fc31..0000000
--- a/core/src/test/java/brooklyn/util/http/HttpToolIntegrationTest.java
+++ /dev/null
@@ -1,98 +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.http;
-
-import static org.testng.Assert.assertTrue;
-
-import java.net.URI;
-
-import org.apache.http.client.HttpClient;
-import org.testng.annotations.AfterMethod;
-import org.testng.annotations.BeforeMethod;
-import org.testng.annotations.Test;
-
-import org.apache.brooklyn.location.basic.PortRanges;
-import brooklyn.test.HttpService;
-
-import com.google.common.collect.ImmutableMap;
-
-public class HttpToolIntegrationTest {
-
- // TODO Expand test coverage for credentials etc
-
- private HttpService httpService;
- private HttpService httpsService;
-
- @BeforeMethod(alwaysRun=true)
- public void setUp() throws Exception {
- httpService = new HttpService(PortRanges.fromString("9000+"), false).start();
- httpsService = new HttpService(PortRanges.fromString("9000+"), true).start();
- }
-
- @AfterMethod(alwaysRun=true)
- public void tearDown() throws Exception {
- if (httpService != null) httpService.shutdown();
- if (httpsService != null) httpsService.shutdown();
- }
-
- @Test(groups = {"Integration"})
- public void testHttpGet() throws Exception {
- URI baseUri = new URI(httpService.getUrl());
-
- HttpClient client = HttpTool.httpClientBuilder().build();
- HttpToolResponse result = HttpTool.httpGet(client, baseUri, ImmutableMap.<String,String>of());
- assertTrue(new String(result.getContent()).contains("Hello, World"), "val="+new String(result.getContent()));
- }
-
- @Test(groups = {"Integration"})
- public void testHttpRedirect() throws Exception {
- URI baseUri = new URI(httpService.getUrl() + "hello/redirectAbsolute");
-
- HttpClient client = HttpTool.httpClientBuilder().laxRedirect(true).build();
- HttpToolResponse result = HttpTool.httpGet(client, baseUri, ImmutableMap.<String,String>of());
- assertTrue(new String(result.getContent()).contains("Hello, World"), "val="+new String(result.getContent()));
- }
-
- @Test(groups = {"Integration"})
- public void testHttpPost() throws Exception {
- URI baseUri = new URI(httpService.getUrl());
-
- HttpClient client = HttpTool.httpClientBuilder().build();
- HttpToolResponse result = HttpTool.httpPost(client, baseUri, ImmutableMap.<String,String>of(), new byte[0]);
- assertTrue(new String(result.getContent()).contains("Hello, World"), "val="+new String(result.getContent()));
- }
-
- @Test(groups = {"Integration"})
- public void testHttpsGetWithTrustAll() throws Exception {
- URI baseUri = new URI(httpsService.getUrl());
-
- HttpClient client = HttpTool.httpClientBuilder().https(true).trustAll().build();
- HttpToolResponse result = HttpTool.httpGet(client, baseUri, ImmutableMap.<String,String>of());
- assertTrue(new String(result.getContent()).contains("Hello, World"), "val="+new String(result.getContent()));
- }
-
- @Test(groups = {"Integration"})
- public void testHttpsPostWithTrustSelfSigned() throws Exception {
- URI baseUri = new URI(httpsService.getUrl());
-
- HttpClient client = HttpTool.httpClientBuilder().https(true).trustSelfSigned().build();
- HttpToolResponse result = HttpTool.httpPost(client, baseUri, ImmutableMap.<String,String>of(), new byte[0]);
- assertTrue(new String(result.getContent()).contains("Hello, World"), "val="+new String(result.getContent()));
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a4c0e5fd/core/src/test/java/brooklyn/util/internal/FlagUtilsTest.java
----------------------------------------------------------------------
diff --git a/core/src/test/java/brooklyn/util/internal/FlagUtilsTest.java b/core/src/test/java/brooklyn/util/internal/FlagUtilsTest.java
deleted file mode 100644
index ed98dba..0000000
--- a/core/src/test/java/brooklyn/util/internal/FlagUtilsTest.java
+++ /dev/null
@@ -1,314 +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.internal;
-
-import static org.testng.Assert.assertEquals;
-import static org.testng.Assert.assertFalse;
-import static org.testng.Assert.assertTrue;
-
-import java.lang.reflect.Field;
-import java.net.InetAddress;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-
-import org.apache.brooklyn.api.entity.trait.Configurable;
-import org.apache.brooklyn.api.management.Task;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.testng.annotations.Test;
-
-import brooklyn.config.ConfigKey;
-import brooklyn.config.ConfigKey.HasConfigKey;
-import brooklyn.entity.basic.ConfigKeys;
-import brooklyn.event.basic.BasicConfigKey;
-import brooklyn.util.collections.MutableMap;
-import brooklyn.util.config.ConfigBag;
-import brooklyn.util.flags.FlagUtils;
-import brooklyn.util.flags.SetFromFlag;
-
-import com.google.common.base.Function;
-import com.google.common.collect.ImmutableList;
-import com.google.common.collect.ImmutableMap;
-import com.google.common.collect.ImmutableSet;
-import com.google.common.collect.Iterables;
-
-public class FlagUtilsTest {
-
- public static final Logger log = LoggerFactory.getLogger(FlagUtilsTest.class);
-
- @Test
- public void testGetAllFields() {
- log.info("types {}", FlagUtils.getAllAssignableTypes(Baz.class));
- assertEquals(FlagUtils.getAllAssignableTypes(Baz.class), ImmutableList.of(Baz.class, Foo.class, Bar.class));
- List<Field> fs = FlagUtils.getAllFields(Baz.class);
- for (Field f : fs) {
- log.info("field {} {}", f.getName(), f);
- }
- List<String> fsn = ImmutableList.copyOf(Iterables.transform(fs, new Function<Field, String>() {
- @Override public String apply(Field f) {
- return f.getName();
- }}));
- assertTrue(fsn.indexOf("A") >= 0);
- assertTrue(fsn.indexOf("w") > fsn.indexOf("A"));
- assertTrue(fsn.indexOf("x") > fsn.indexOf("A") );
- assertTrue(fsn.indexOf("yNotY") > fsn.indexOf("A"));
- assertTrue(fsn.indexOf("Z") > fsn.indexOf("yNotY") );
- }
-
- @Test
- public void testSetFieldsFromFlags() {
- Foo f = new Foo();
- Map<?,?> m = MutableMap.of("w", 3, "x", 1, "y", 7, "z", 9);
- Map<?, ?> unused = FlagUtils.setFieldsFromFlags(m, f);
- assertEquals(f.w, 3);
- assertEquals(f.x, 1);
- assertEquals(f.yNotY, 7);
- assertEquals(unused, ImmutableMap.of("z", 9));
- Map<?,?> m2 = FlagUtils.getFieldsWithValues(f);
- m.remove("z");
- assertEquals(m2, m);
- }
-
- @Test
- public void testCollectionCoercionOnSetFromFlags() {
- WithSpecialFieldTypes s = new WithSpecialFieldTypes();
- Map<?,?> m = ImmutableMap.of("set", ImmutableSet.of(1));
- FlagUtils.setFieldsFromFlags(m, s);
- assertEquals(s.set, ImmutableSet.of(1));
- }
-
- @Test
- public void testInetAddressCoercionOnSetFromFlags() {
- WithSpecialFieldTypes s = new WithSpecialFieldTypes();
- Map<?,?> m = ImmutableMap.of("inet", "127.0.0.1");
- FlagUtils.setFieldsFromFlags(m, s);
- assertEquals(s.inet.getHostAddress(), "127.0.0.1");
- }
-
- @Test
- public void testNonImmutableField() {
- Foo f = new Foo();
- FlagUtils.setFieldsFromFlags(ImmutableMap.of("w", 8), f);
- assertEquals(f.w, 8);
- FlagUtils.setFieldsFromFlags(ImmutableMap.of("w", 9), f);
- assertEquals(f.w, 9);
- }
-
- @Test
- public void testImmutableIntField() {
- Foo f = new Foo();
- FlagUtils.setFieldsFromFlags(ImmutableMap.of("x", 8), f);
- assertEquals(f.x, 8);
- boolean succeededWhenShouldntHave = false;
- try {
- FlagUtils.setFieldsFromFlags(ImmutableMap.of("x", 9), f);
- succeededWhenShouldntHave = true;
- } catch (IllegalStateException e) {
- //expected
- }
- assertFalse(succeededWhenShouldntHave);
- assertEquals(f.x, 8);
- }
-
- @Test
- public void testImmutableObjectField() {
- WithImmutableNonNullableObject o = new WithImmutableNonNullableObject();
- FlagUtils.setFieldsFromFlags(ImmutableMap.of("a", "a", "b", "b"), o);
- assertEquals(o.a, "a");
- assertEquals(o.b, "b");
-
- FlagUtils.setFieldsFromFlags(ImmutableMap.of("a", "a2"), o);
- assertEquals(o.a, "a2");
-
- boolean succeededWhenShouldntHave = false;
- try {
- FlagUtils.setFieldsFromFlags(ImmutableMap.of("b", "b2"), o);
- succeededWhenShouldntHave = true;
- } catch (IllegalStateException e) {
- //expected
- }
- assertFalse(succeededWhenShouldntHave);
- assertEquals(o.b, "b");
- }
-
- @Test
- public void testNonNullable() {
- WithImmutableNonNullableObject o = new WithImmutableNonNullableObject();
- //allowed
- FlagUtils.setFieldsFromFlags(MutableMap.of("a", null), o);
- assertEquals(o.a, null);
- assertEquals(o.b, null);
- //not allowed
- boolean succeededWhenShouldntHave = false;
- try {
- FlagUtils.setFieldsFromFlags(MutableMap.of("b", null), o);
- succeededWhenShouldntHave = true;
- } catch (IllegalArgumentException e) {
- //expected
- }
- assertFalse(succeededWhenShouldntHave);
- assertEquals(o.b, null);
- }
-
- @Test
- public void testGetAnnotatedFields() throws Exception {
- Map<Field, SetFromFlag> fm = FlagUtils.getAnnotatedFields(WithImmutableNonNullableObject.class);
- assertEquals(fm.keySet().size(), 2);
- assertTrue(fm.get(WithImmutableNonNullableObject.class.getDeclaredField("b")).immutable());
- }
-
- @Test
- public void testCheckRequired() {
- WithImmutableNonNullableObject f = new WithImmutableNonNullableObject();
- FlagUtils.setFieldsFromFlags(ImmutableMap.of("a", "a is a"), f);
- assertEquals(f.a, "a is a");
- assertEquals(f.b, null);
- int exceptions = 0;
- try {
- FlagUtils.checkRequiredFields(f);
- } catch (IllegalStateException e) {
- exceptions++;
- }
- assertEquals(exceptions, 1);
- }
-
- @Test
- public void testSetConfigKeys() {
- FooCK f = new FooCK();
- Map<?,?> unused = FlagUtils.setFieldsFromFlags(ImmutableMap.of("f1", 9, "ck1", "do-set", "ck2", "dont-set", "c3", "do-set"), f);
- assertEquals(f.bag.get(FooCK.CK1), "do-set");
- assertEquals(f.bag.get(FooCK.CK3), "do-set");
- assertEquals(f.f1, 9);
- assertEquals(f.bag.containsKey(FooCK.CK2), false);
- assertEquals(unused, ImmutableMap.of("ck2", "dont-set"));
- }
-
- @Test
- public void testSetAllConfigKeys() {
- FooCK f = new FooCK();
- Map<?,?> unused = FlagUtils.setAllConfigKeys(ImmutableMap.of("f1", 9, "ck1", "do-set", "ck2", "do-set-2", "c3", "do-set"), f, true);
- assertEquals(f.bag.get(FooCK.CK1), "do-set");
- assertEquals(f.bag.get(FooCK.CK3), "do-set");
- assertEquals(f.bag.containsKey(FooCK.CK2), true);
- assertEquals(f.bag.get(FooCK.CK2), "do-set-2");
- assertEquals(unused, ImmutableMap.of("f1", 9));
- }
-
- @Test
- public void testSetFromConfigKeys() {
- FooCK f = new FooCK();
- Map<?, ?> unused = FlagUtils.setFieldsFromFlags(ImmutableMap.of(new BasicConfigKey<Integer>(Integer.class, "f1"), 9, "ck1", "do-set", "ck2", "dont-set"), f);
- assertEquals(f.bag.get(FooCK.CK1), "do-set");
- assertEquals(f.f1, 9);
- assertEquals(f.bag.containsKey(FooCK.CK2), false);
- assertEquals(unused, ImmutableMap.of("ck2", "dont-set"));
- }
-
- public static class Foo {
- @SetFromFlag
- int w;
-
- @SetFromFlag(immutable=true)
- private int x;
-
- @SetFromFlag("y")
- public int yNotY;
- }
-
- public static interface Bar {
- static final String Z = "myzval";
- }
-
- public static class Baz extends Foo implements Bar {
- @SuppressWarnings("unused") //inspected by reflection
- private static int A;
- }
-
- public static class WithImmutableNonNullableObject {
- @SetFromFlag
- Object a;
- @SetFromFlag(immutable=true, nullable=false)
- public Object b;
- }
-
- public static class WithSpecialFieldTypes {
- @SetFromFlag Set<?> set;
- @SetFromFlag InetAddress inet;
- }
-
- public static class FooCK implements Configurable {
- @SetFromFlag
- public static ConfigKey<String> CK1 = ConfigKeys.newStringConfigKey("ck1");
-
- public static ConfigKey<String> CK2 = ConfigKeys.newStringConfigKey("ck2");
-
- @SetFromFlag("c3")
- public static ConfigKey<String> CK3 = ConfigKeys.newStringConfigKey("ck3");
-
- @SetFromFlag
- int f1;
-
- ConfigBag bag = new ConfigBag();
- BasicConfigurationSupport configSupport = new BasicConfigurationSupport();
-
- @Override
- public ConfigurationSupport config() {
- return configSupport;
- }
-
- public <T> T setConfig(ConfigKey<T> key, T val) {
- return config().set(key, val);
- }
-
- private class BasicConfigurationSupport implements ConfigurationSupport {
- @Override
- public <T> T get(ConfigKey<T> key) {
- return bag.get(key);
- }
-
- @Override
- public <T> T get(HasConfigKey<T> key) {
- return get(key.getConfigKey());
- }
-
- @Override
- public <T> T set(ConfigKey<T> key, T val) {
- T old = bag.get(key);
- bag.configure(key, val);
- return old;
- }
-
- @Override
- public <T> T set(HasConfigKey<T> key, T val) {
- return set(key.getConfigKey(), val);
- }
-
- @Override
- public <T> T set(ConfigKey<T> key, Task<T> val) {
- throw new UnsupportedOperationException();
- }
-
- @Override
- public <T> T set(HasConfigKey<T> key, Task<T> val) {
- return set(key.getConfigKey(), val);
- }
- }
- }
-}
\ No newline at end of file