http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/699b3f65/core/src/test/java/brooklyn/util/task/system/SystemTasksTest.java ---------------------------------------------------------------------- diff --git a/core/src/test/java/brooklyn/util/task/system/SystemTasksTest.java b/core/src/test/java/brooklyn/util/task/system/SystemTasksTest.java deleted file mode 100644 index e60310d..0000000 --- a/core/src/test/java/brooklyn/util/task/system/SystemTasksTest.java +++ /dev/null @@ -1,134 +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.task.system; - -import java.io.File; - -import org.apache.brooklyn.api.management.ManagementContext; -import org.apache.brooklyn.core.management.internal.LocalManagementContext; -import org.testng.Assert; -import org.testng.annotations.AfterMethod; -import org.testng.annotations.BeforeMethod; -import org.testng.annotations.Test; - -import brooklyn.entity.basic.Entities; -import brooklyn.util.os.Os; -import brooklyn.util.task.ssh.SshTasks; - -/** - * Some tests for {@link SystemTasks}. See {@link SshTasks}. - */ -public class SystemTasksTest { - - ManagementContext mgmt; - File tempDir; - - boolean failureExpected; - - @BeforeMethod(alwaysRun=true) - public void setup() throws Exception { - mgmt = new LocalManagementContext(); - - clearExpectedFailure(); - tempDir = Os.newTempDir(getClass()); - } - - @AfterMethod(alwaysRun=true) - public void tearDown() throws Exception { - if (mgmt != null) Entities.destroyAll(mgmt); - mgmt = null; - tempDir = Os.deleteRecursively(tempDir).asNullOrThrowing(); - checkExpectedFailure(); - } - - protected void checkExpectedFailure() { - if (failureExpected) { - clearExpectedFailure(); - Assert.fail("Test should have thrown an exception but it did not."); - } - } - - protected void clearExpectedFailure() { - failureExpected = false; - } - - protected void setExpectingFailure() { - failureExpected = true; - } - - - protected <T> ProcessTaskWrapper<T> submit(final ProcessTaskFactory<T> tf) { - ProcessTaskWrapper<T> t = tf.newTask(); - mgmt.getExecutionManager().submit(t); - return t; - } - - @Test(groups="Integration") - public void testExecEchoHello() { - ProcessTaskWrapper<Integer> t = submit(SystemTasks.exec("sleep 1 ; echo hello world")); - Assert.assertFalse(t.isDone()); - Assert.assertEquals(t.get(), (Integer)0); - Assert.assertEquals(t.getTask().getUnchecked(), (Integer)0); - Assert.assertEquals(t.getStdout().trim(), "hello world"); - } - - // FIXME Behaviour of Bash shell changes from 3.x to 4.x so test is disabled - @Test(groups="Integration", enabled=false) - public void testSubshellExitScriptDoesNotExit() { - checkSubshellExitDoesNotExit(taskSubshellExit().runAsScript()); - } - - @Test(groups="Integration") - public void testSubshellExitCommandDoesNotExit() { - checkSubshellExitDoesNotExit(taskSubshellExit().runAsCommand()); - } - - public ProcessTaskFactory<Integer> taskSubshellExit() { - return SystemTasks.exec("echo hello", "( exit 1 )", "echo bye code $?"); - } - - public void checkSubshellExitDoesNotExit(ProcessTaskFactory<Integer> task) { - ProcessTaskWrapper<Integer> t = submit(task); - t.block(); - Assert.assertEquals(t.get(), (Integer)0); - Assert.assertTrue(t.getStdout().contains("bye code 1"), "stdout is: "+t.getStdout()); - } - - @Test(groups="Integration") - public void testGroupExitScriptDoesNotExit() { - checkGroupExitDoesExit(taskGroupExit().runAsScript()); - } - - @Test(groups="Integration") - public void testGroupExitCommandDoesNotExit() { - checkGroupExitDoesExit(taskGroupExit().runAsCommand()); - } - - public ProcessTaskFactory<Integer> taskGroupExit() { - return SystemTasks.exec("echo hello", "{ exit 1 ; }", "echo bye code $?"); - } - - public void checkGroupExitDoesExit(ProcessTaskFactory<Integer> task) { - ProcessTaskWrapper<Integer> t = submit(task); - t.block(); - Assert.assertEquals(t.get(), (Integer)1); - Assert.assertFalse(t.getStdout().contains("bye"), "stdout is: "+t.getStdout()); - } - -}
http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/699b3f65/core/src/test/java/brooklyn/util/text/DataUriSchemeParserTest.java ---------------------------------------------------------------------- diff --git a/core/src/test/java/brooklyn/util/text/DataUriSchemeParserTest.java b/core/src/test/java/brooklyn/util/text/DataUriSchemeParserTest.java deleted file mode 100644 index ff2dc9b..0000000 --- a/core/src/test/java/brooklyn/util/text/DataUriSchemeParserTest.java +++ /dev/null @@ -1,52 +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.text; - -import java.io.UnsupportedEncodingException; -import java.net.URLEncoder; - -import org.bouncycastle.util.encoders.Base64; -import org.testng.Assert; -import org.testng.annotations.Test; - -public class DataUriSchemeParserTest { - - @Test - public void testSimple() { - Assert.assertEquals(new DataUriSchemeParser("data:,hello").parse().getDataAsString(), "hello"); - Assert.assertEquals(DataUriSchemeParser.toString("data:,hello"), "hello"); - } - - @Test - public void testMimeType() throws UnsupportedEncodingException { - DataUriSchemeParser p = new DataUriSchemeParser("data:application/json,"+URLEncoder.encode("{ }", "US-ASCII")).parse(); - Assert.assertEquals(p.getMimeType(), "application/json"); - Assert.assertEquals(p.getData(), "{ }".getBytes()); - } - - @Test - public void testBase64() { - Assert.assertEquals(DataUriSchemeParser.toString( - "data:;base64,"+new String(Base64.encode("hello".getBytes()))), - "hello"); - } - - // TODO test pictures, etc - -} http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/699b3f65/core/src/test/java/brooklyn/util/text/TemplateProcessorTest.java ---------------------------------------------------------------------- diff --git a/core/src/test/java/brooklyn/util/text/TemplateProcessorTest.java b/core/src/test/java/brooklyn/util/text/TemplateProcessorTest.java deleted file mode 100644 index bd8ef87..0000000 --- a/core/src/test/java/brooklyn/util/text/TemplateProcessorTest.java +++ /dev/null @@ -1,179 +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.text; - -import static org.testng.Assert.assertEquals; - -import org.apache.brooklyn.api.entity.proxying.EntitySpec; -import org.apache.brooklyn.core.management.internal.ManagementContextInternal; -import org.apache.brooklyn.test.entity.TestApplication; -import org.apache.brooklyn.test.entity.TestEntity; -import org.testng.Assert; -import org.testng.annotations.AfterMethod; -import org.testng.annotations.BeforeMethod; -import org.testng.annotations.Test; - -import brooklyn.entity.BrooklynAppUnitTestSupport; -import brooklyn.event.basic.DependentConfiguration; -import brooklyn.test.FixedLocaleTest; - -import com.google.common.collect.ImmutableMap; - -public class TemplateProcessorTest extends BrooklynAppUnitTestSupport { - private FixedLocaleTest localeFix = new FixedLocaleTest(); - - @BeforeMethod(alwaysRun=true) - public void setUp() throws Exception { - super.setUp(); - localeFix.setUp(); - } - - @AfterMethod(alwaysRun=true) - public void tearDown() throws Exception { - super.tearDown(); - localeFix.tearDown(); - } - - @Test - public void testAdditionalArgs() { - String templateContents = "${mykey}"; - String result = TemplateProcessor.processTemplateContents(templateContents, app, ImmutableMap.of("mykey", "myval")); - assertEquals(result, "myval"); - } - - @Test - public void testEntityConfig() { - TestEntity entity = app.createAndManageChild(EntitySpec.create(TestEntity.class) - .configure(TestEntity.CONF_NAME, "myval")); - String templateContents = "${config['"+TestEntity.CONF_NAME.getName()+"']}"; - String result = TemplateProcessor.processTemplateContents(templateContents, entity, ImmutableMap.<String,Object>of()); - assertEquals(result, "myval"); - } - - @Test - public void testEntityConfigNumber() { - TestEntity entity = app.createAndManageChild(EntitySpec.create(TestEntity.class) - .configure(TestEntity.CONF_OBJECT, 123456)); - String templateContents = "${config['"+TestEntity.CONF_OBJECT.getName()+"']}"; - String result = TemplateProcessor.processTemplateContents(templateContents, entity, ImmutableMap.<String,Object>of()); - assertEquals(result, "123,456"); - } - - @Test - public void testEntityConfigNumberUnadorned() { - // ?c is needed to avoid commas (i always forget this!) - TestEntity entity = app.createAndManageChild(EntitySpec.create(TestEntity.class) - .configure(TestEntity.CONF_OBJECT, 123456)); - String templateContents = "${config['"+TestEntity.CONF_OBJECT.getName()+"']?c}"; - String result = TemplateProcessor.processTemplateContents(templateContents, entity, ImmutableMap.<String,Object>of()); - assertEquals(result, "123456"); - } - - @Test - public void testGetSysProp() { - System.setProperty("testGetSysProp", "myval"); - - String templateContents = "${javaSysProps['testGetSysProp']}"; - String result = TemplateProcessor.processTemplateContents(templateContents, app, ImmutableMap.<String,Object>of()); - assertEquals(result, "myval"); - } - - @Test - public void testEntityGetterMethod() { - String templateContents = "${entity.id}"; - String result = TemplateProcessor.processTemplateContents(templateContents, app, ImmutableMap.<String,Object>of()); - assertEquals(result, app.getId()); - } - - @Test - public void testManagementContextConfig() { - mgmt.getBrooklynProperties().put("globalmykey", "myval"); - String templateContents = "${mgmt.globalmykey}"; - String result = TemplateProcessor.processTemplateContents(templateContents, app, ImmutableMap.<String,Object>of()); - assertEquals(result, "myval"); - } - - @Test - public void testManagementContextDefaultValue() { - String templateContents = "${(missing)!\"defval\"}"; - Object result = TemplateProcessor.processTemplateContents(templateContents, app, ImmutableMap.<String,Object>of()); - assertEquals(result, "defval"); - } - - @Test - public void testManagementContextDefaultValueInDotMissingValue() { - String templateContents = "${(mgmt.missing.more_missing)!\"defval\"}"; - Object result = TemplateProcessor.processTemplateContents(templateContents, app, ImmutableMap.<String,Object>of()); - assertEquals(result, "defval"); - } - - @Test - public void testManagementContextConfigWithDot() { - mgmt.getBrooklynProperties().put("global.mykey", "myval"); - String templateContents = "${mgmt['global.mykey']}"; - String result = TemplateProcessor.processTemplateContents(templateContents, app, ImmutableMap.<String,Object>of()); - assertEquals(result, "myval"); - } - - @Test - public void testManagementContextErrors() { - try { - // NB: dot has special meaning so this should fail; must be accessed using bracket notation as above - mgmt.getBrooklynProperties().put("global.mykey", "myval"); - String templateContents = "${mgmt.global.mykey}"; - TemplateProcessor.processTemplateContents(templateContents, app, ImmutableMap.<String,Object>of()); - Assert.fail("Should not have found value with intermediate dot"); - } catch (Exception e) { - Assert.assertTrue(e.toString().contains("global"), "Should have mentioned missing key 'global' in error"); - } - } - - @Test - public void testApplyTemplatedConfigWithAttributeWhenReady() { - app.setAttribute(TestApplication.MY_ATTRIBUTE, "myval"); - - TestEntity entity = app.createAndManageChild(EntitySpec.create(TestEntity.class) - .configure(TestEntity.CONF_NAME, DependentConfiguration.attributeWhenReady(app, TestApplication.MY_ATTRIBUTE))); - - String templateContents = "${config['"+TestEntity.CONF_NAME.getName()+"']}"; - String result = TemplateProcessor.processTemplateContents(templateContents, entity, ImmutableMap.<String,Object>of()); - assertEquals(result, "myval"); - } - - @Test - public void testDotSeparatedKey() { - String templateContents = "${a.b}"; - String result = TemplateProcessor.processTemplateContents(templateContents, (ManagementContextInternal)null, - ImmutableMap.<String,Object>of("a.b", "myval")); - assertEquals(result, "myval"); - } - - @Test - public void testDotSeparatedKeyCollisionFailure() { - String templateContents = "${aaa.bbb}"; - try { - TemplateProcessor.processTemplateContents(templateContents, (ManagementContextInternal)null, - ImmutableMap.<String,Object>of("aaa.bbb", "myval", "aaa", "blocker")); - Assert.fail("Should not have found value with intermediate dot where prefix is overridden"); - } catch (Exception e) { - Assert.assertTrue(e.toString().contains("aaa"), "Should have mentioned missing key 'aaa' in error"); - } - } - -} http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/699b3f65/core/src/test/java/brooklyn/util/xstream/CompilerCompatibilityTest.java ---------------------------------------------------------------------- diff --git a/core/src/test/java/brooklyn/util/xstream/CompilerCompatibilityTest.java b/core/src/test/java/brooklyn/util/xstream/CompilerCompatibilityTest.java deleted file mode 100644 index 5a1f844..0000000 --- a/core/src/test/java/brooklyn/util/xstream/CompilerCompatibilityTest.java +++ /dev/null @@ -1,154 +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.xstream; - -import static org.testng.Assert.assertTrue; - -import java.io.IOException; -import java.io.InputStream; -import java.lang.reflect.Field; - -import org.testng.annotations.Test; - -import brooklyn.util.xstream.CompilerCompatibilityTest.EnclosingClass.DynamicClass; -import brooklyn.util.xstream.CompilerCompatibilityTest.EnclosingClass.DynamicExtendingClass; -import brooklyn.util.xstream.CompilerCompatibilityTest.EnclosingClass.EnclosingDynamicClass; -import brooklyn.util.xstream.CompilerCompatibilityTest.EnclosingClass.EnclosingDynamicClass.NestedDynamicClass; - -import com.thoughtworks.xstream.XStream; -import com.thoughtworks.xstream.mapper.MapperWrapper; - -// To get the generated synthetic fields use the command: -/* - find core/target/test-classes -name CompilerCompatibilityTest\$EnclosingClass\$* | \ - sed s@core/target/test-classes/@@ | sed '[email protected]$@@' | sed s@/@.@g | \ - xargs javap -classpath core/target/test-classes/ | grep -B1 this -*/ -@SuppressWarnings("unused") -public class CompilerCompatibilityTest { - private EnclosingClass enclosingClass = new EnclosingClass(); - private DynamicClass dynamicClass = enclosingClass.new DynamicClass(); - private DynamicExtendingClass dynamicExtendingClass = enclosingClass.new DynamicExtendingClass(); - private EnclosingDynamicClass enclosingDynamicClass = enclosingClass.new EnclosingDynamicClass(); - private NestedDynamicClass nestedDynamicClass = enclosingDynamicClass.new NestedDynamicClass(); -// NOT SUPPORTED -// private DynamicExtendingClassWithDifferentScope dynamicExtendingClassWithDifferentScope = -// enclosingClass.new DynamicExtendingClassWithDifferentScope(enclosingDynamicClass); - - public static class EnclosingClass { - public class DynamicClass { - //Oracle/OpenJDK/IBM generates - //final EnclosingClass this$0; - - //eclipse-[groovy-]compiler generates - //final EnclosingClass this$1; - } - - public class DynamicExtendingClass extends DynamicClass { - //The field here masks the parent field - - //Oracle/OpenJDK/IBM generates - //final EnclosingClass this$0; - - //eclipse-[groovy-]compiler generates - //final EnclosingClass this$1; - } - - public class EnclosingDynamicClass { - //Oracle/OpenJDK/IBM generates - //final EnclosingClass this$0; - - //eclipse-[groovy-]compiler generates - //final EnclosingClass this$1; - - public class NestedDynamicClass { - //Oracle/OpenJDK/IBM generates - //final EnclosingClass this$1; - - //eclipse-[groovy-]compiler generates - //final EnclosingClass this$2; - } - } - -// WARNING: Combination NOT SUPPORTED. Not enough information in XML to deserialize reliably, -// having in mind that different compilers could be used for parent/child classes. -// If we really need to, we can extend the heuristic to check for field types or assume that -// only one compiler was used for the whole class hierarchy covering some more cases. -// -// The problem is that we have two fields with different names, without relation between the -// indexes in each one. Changing compilers (or combination of compilers) could change the -// indexes independently in each field. This makes it impossible to infer which field in the xml -// maps to which field in the object. -// When having identical field names with parent classes XStream will put a defined-in attribute -// which makes it possible to deserialize, but it can't be forced to put it in each element. -// - public class DynamicExtendingClassWithDifferentScope extends NestedDynamicClass { - //Oracle/OpenJDK/IBM generates - //final EnclosingClass this$0; - - //eclipse-[groovy-]compiler generates - //final EnclosingClass this$1; - - //constructor required to compile - public DynamicExtendingClassWithDifferentScope(EnclosingDynamicClass superEnclosingScope) { - superEnclosingScope.super(); - } - } - } - - @Test - public void testXStreamDeserialize() throws Exception { - deserialize("/brooklyn/entity/rebind/compiler_compatibility_eclipse.xml"); - deserialize("/brooklyn/entity/rebind/compiler_compatibility_oracle.xml"); - } - - private void deserialize(String inputUrl) throws Exception { - XStream xstream = new XStream() { - @Override - protected MapperWrapper wrapMapper(MapperWrapper next) { - return new CompilerIndependentOuterClassFieldMapper(super.wrapMapper(next)); - } - }; - - InputStream in = this.getClass().getResourceAsStream(inputUrl); - try { - Object obj = xstream.fromXML(in); - assertNonNullOuterFields(obj); - } finally { - in.close(); - } - } - - private void assertNonNullOuterFields(Object obj) throws Exception { - Field[] testInstances = obj.getClass().getDeclaredFields(); - for (Field instanceField : testInstances) { - Object instance = instanceField.get(obj); - Class<?> type = instance.getClass(); - do { - for (Field field : type.getDeclaredFields()) { - if (field.getName().startsWith("this$")) { - Object value = field.get(instance); - assertTrue(value != null, field + " should not be null"); - } - } - type = type.getSuperclass(); - } while (type != null); - } - } -} http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/699b3f65/core/src/test/java/brooklyn/util/xstream/ConverterTestFixture.java ---------------------------------------------------------------------- diff --git a/core/src/test/java/brooklyn/util/xstream/ConverterTestFixture.java b/core/src/test/java/brooklyn/util/xstream/ConverterTestFixture.java deleted file mode 100644 index bf566ba..0000000 --- a/core/src/test/java/brooklyn/util/xstream/ConverterTestFixture.java +++ /dev/null @@ -1,40 +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.xstream; - -import org.testng.Assert; - -import com.thoughtworks.xstream.XStream; - -public class ConverterTestFixture { - - protected Object assertX(Object obj, String fmt) { - XStream xstream = new XStream(); - registerConverters(xstream); - String s1 = xstream.toXML(obj); - Assert.assertEquals(s1, fmt); - Object out = xstream.fromXML(s1); - Assert.assertEquals(out, obj); - return out; - } - - protected void registerConverters(XStream xstream) { - } - -} http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/699b3f65/core/src/test/java/brooklyn/util/xstream/EnumCaseForgivingConverterTest.java ---------------------------------------------------------------------- diff --git a/core/src/test/java/brooklyn/util/xstream/EnumCaseForgivingConverterTest.java b/core/src/test/java/brooklyn/util/xstream/EnumCaseForgivingConverterTest.java deleted file mode 100644 index f22f91b..0000000 --- a/core/src/test/java/brooklyn/util/xstream/EnumCaseForgivingConverterTest.java +++ /dev/null @@ -1,52 +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.xstream; - -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.fail; - -import org.testng.annotations.Test; - -public class EnumCaseForgivingConverterTest { - - public enum MyEnum { - FOO, - BaR; - } - - @Test - public void testFindsCaseInsensitive() throws Exception { - assertEquals(EnumCaseForgivingConverter.resolve(MyEnum.class, "FOO"), MyEnum.FOO); - assertEquals(EnumCaseForgivingConverter.resolve(MyEnum.class, "foo"), MyEnum.FOO); - assertEquals(EnumCaseForgivingConverter.resolve(MyEnum.class, "Foo"), MyEnum.FOO); - assertEquals(EnumCaseForgivingConverter.resolve(MyEnum.class, "BAR"), MyEnum.BaR); - assertEquals(EnumCaseForgivingConverter.resolve(MyEnum.class, "bar"), MyEnum.BaR); - assertEquals(EnumCaseForgivingConverter.resolve(MyEnum.class, "Bar"), MyEnum.BaR); - } - - @Test - public void testFailsIfNoMatch() throws Exception { - try { - assertEquals(EnumCaseForgivingConverter.resolve(MyEnum.class, "DoesNotExist"), MyEnum.BaR); - fail(); - } catch (IllegalArgumentException e) { - if (!e.toString().matches(".*No enum.*MyEnum.DOESNOTEXIST")) throw e; - } - } -} http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/699b3f65/core/src/test/java/brooklyn/util/xstream/ImmutableListConverterTest.java ---------------------------------------------------------------------- diff --git a/core/src/test/java/brooklyn/util/xstream/ImmutableListConverterTest.java b/core/src/test/java/brooklyn/util/xstream/ImmutableListConverterTest.java deleted file mode 100644 index f8d8855..0000000 --- a/core/src/test/java/brooklyn/util/xstream/ImmutableListConverterTest.java +++ /dev/null @@ -1,59 +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.xstream; - -import java.net.UnknownHostException; - -import org.testng.Assert; -import org.testng.annotations.Test; - -import com.google.common.collect.ImmutableList; -import com.thoughtworks.xstream.XStream; - -@Test -public class ImmutableListConverterTest extends ConverterTestFixture { - - protected void registerConverters(XStream xstream) { - super.registerConverters(xstream); - xstream.aliasType("ImmutableList", ImmutableList.class); - xstream.registerConverter(new ImmutableListConverter(xstream.getMapper())); - } - - @Test - public void testImmutableEmptyList() throws UnknownHostException { - assertX(ImmutableList.of(), "<ImmutableList/>"); - } - - @Test - public void testImmutableSingletonDoubleList() throws UnknownHostException { - assertX(ImmutableList.of(1.2d), "<ImmutableList>\n <double>1.2</double>\n</ImmutableList>"); - } - - @Test - public void testImmutableTwoValStringList() throws UnknownHostException { - assertX(ImmutableList.of("a","b"), "<ImmutableList>\n <string>a</string>\n <string>b</string>\n</ImmutableList>"); - } - - @Test - public void testImmutableEmptyListStaysImmutable() throws UnknownHostException { - Object x = assertX(ImmutableList.of(), "<ImmutableList/>"); - Assert.assertTrue(x instanceof ImmutableList); - } - -} http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/699b3f65/core/src/test/java/brooklyn/util/xstream/InetAddressConverterTest.java ---------------------------------------------------------------------- diff --git a/core/src/test/java/brooklyn/util/xstream/InetAddressConverterTest.java b/core/src/test/java/brooklyn/util/xstream/InetAddressConverterTest.java deleted file mode 100644 index 237c670..0000000 --- a/core/src/test/java/brooklyn/util/xstream/InetAddressConverterTest.java +++ /dev/null @@ -1,41 +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.xstream; - -import java.net.InetAddress; -import java.net.UnknownHostException; - -import org.testng.annotations.Test; - -import com.thoughtworks.xstream.XStream; - -@Test -public class InetAddressConverterTest extends ConverterTestFixture { - - protected void registerConverters(XStream xstream) { - super.registerConverters(xstream); - xstream.registerConverter(new Inet4AddressConverter()); - } - - public void testFoo1234() throws UnknownHostException { - assertX(InetAddress.getByAddress("foo", new byte[] { 1, 2, 3, 4 }), - "<java.net.Inet4Address>foo/1.2.3.4</java.net.Inet4Address>"); - } - -} http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/699b3f65/core/src/test/java/brooklyn/util/xstream/StringKeyMapConverterTest.java ---------------------------------------------------------------------- diff --git a/core/src/test/java/brooklyn/util/xstream/StringKeyMapConverterTest.java b/core/src/test/java/brooklyn/util/xstream/StringKeyMapConverterTest.java deleted file mode 100644 index 7d30bc2..0000000 --- a/core/src/test/java/brooklyn/util/xstream/StringKeyMapConverterTest.java +++ /dev/null @@ -1,77 +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.xstream; - -import java.net.UnknownHostException; -import java.util.LinkedHashMap; -import java.util.Map; - -import org.testng.annotations.Test; - -import brooklyn.util.collections.MutableMap; - -import com.google.common.collect.Maps; -import com.thoughtworks.xstream.XStream; - -@SuppressWarnings({ "rawtypes", "unchecked" }) -@Test -public class StringKeyMapConverterTest extends ConverterTestFixture { - - protected void registerConverters(XStream xstream) { - super.registerConverters(xstream); - xstream.alias("map", Map.class, LinkedHashMap.class); - xstream.alias("MutableMap", MutableMap.class); - xstream.registerConverter(new StringKeyMapConverter(xstream.getMapper()), /* priority */ 10); - } - - @Test - public void testSimple() throws UnknownHostException { - Map m = Maps.newLinkedHashMap(); - m.put("a", "v"); - assertX(m, "<map>\n <a>v</a>\n</map>"); - } - - @Test - public void testDouble() throws UnknownHostException { - Map m = Maps.newLinkedHashMap(); - m.put("a", "v"); - m.put("x", 1.0d); - assertX(m, "<map>\n <a>v</a>\n <x type=\"double\">1.0</x>\n</map>"); - } - - @Test - public void testEmpty() throws UnknownHostException { - Map m = Maps.newLinkedHashMap(); - assertX(m, "<map/>"); - } - - @Test - public void testBigSpacedKeyInMutableMap() throws UnknownHostException { - Map m = MutableMap.of("a b", "x"); - assertX(m, "<MutableMap>\n <entry key=\"a b\">x</entry>\n</MutableMap>"); - } - - @Test - public void testWithNumericKey() throws UnknownHostException { - Map m = Maps.newLinkedHashMap(); - m.put("123", "v"); - m.put("a", "v2"); - assertX(m, "<map>\n <entry key=\"123\">v</entry>\n <a>v2</a>\n</map>"); - } -} http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/699b3f65/core/src/test/java/brooklyn/util/xstream/XmlUtilTest.java ---------------------------------------------------------------------- diff --git a/core/src/test/java/brooklyn/util/xstream/XmlUtilTest.java b/core/src/test/java/brooklyn/util/xstream/XmlUtilTest.java deleted file mode 100644 index a81e299..0000000 --- a/core/src/test/java/brooklyn/util/xstream/XmlUtilTest.java +++ /dev/null @@ -1,33 +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.xstream; - -import static org.testng.Assert.assertEquals; - -import org.testng.annotations.Test; - - -public class XmlUtilTest { - - @Test - public void testXpath() throws Exception { - String xml = "<a><b>myb</b></a>"; - assertEquals(XmlUtil.xpath(xml, "/a/b[text()]"), "myb"); - } -} http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/699b3f65/core/src/test/java/org/apache/brooklyn/core/catalog/internal/CatalogDtoTest.java ---------------------------------------------------------------------- diff --git a/core/src/test/java/org/apache/brooklyn/core/catalog/internal/CatalogDtoTest.java b/core/src/test/java/org/apache/brooklyn/core/catalog/internal/CatalogDtoTest.java index 90e039d..3229aac 100644 --- a/core/src/test/java/org/apache/brooklyn/core/catalog/internal/CatalogDtoTest.java +++ b/core/src/test/java/org/apache/brooklyn/core/catalog/internal/CatalogDtoTest.java @@ -39,12 +39,12 @@ import org.apache.brooklyn.core.catalog.internal.CatalogUtils; import org.apache.brooklyn.core.catalog.internal.CatalogXmlSerializer; import org.apache.brooklyn.core.catalog.internal.CatalogClasspathDo.CatalogScanningModes; import org.apache.brooklyn.core.management.internal.LocalManagementContext; +import org.apache.brooklyn.core.util.BrooklynMavenArtifacts; import org.apache.brooklyn.test.entity.LocalManagementContextForTests; import org.apache.brooklyn.test.entity.TestApplication; import org.apache.brooklyn.test.entity.TestEntity; import brooklyn.entity.basic.Entities; -import brooklyn.util.BrooklynMavenArtifacts; import brooklyn.util.maven.MavenRetriever; import com.google.common.collect.ImmutableList; http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/699b3f65/core/src/test/java/org/apache/brooklyn/core/catalog/internal/CatalogLoadTest.java ---------------------------------------------------------------------- diff --git a/core/src/test/java/org/apache/brooklyn/core/catalog/internal/CatalogLoadTest.java b/core/src/test/java/org/apache/brooklyn/core/catalog/internal/CatalogLoadTest.java index eea4933..fb28780 100644 --- a/core/src/test/java/org/apache/brooklyn/core/catalog/internal/CatalogLoadTest.java +++ b/core/src/test/java/org/apache/brooklyn/core/catalog/internal/CatalogLoadTest.java @@ -28,8 +28,7 @@ import org.apache.brooklyn.api.catalog.CatalogItem.CatalogBundle; import org.apache.brooklyn.core.catalog.internal.CatalogDto; import org.apache.brooklyn.core.catalog.internal.CatalogItemDtoAbstract; import org.apache.brooklyn.core.catalog.internal.CatalogXmlSerializer; - -import brooklyn.util.ResourceUtils; +import org.apache.brooklyn.core.util.ResourceUtils; import com.google.common.base.Joiner; import com.google.common.collect.Iterables; http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/699b3f65/core/src/test/java/org/apache/brooklyn/core/catalog/internal/CatalogScanTest.java ---------------------------------------------------------------------- diff --git a/core/src/test/java/org/apache/brooklyn/core/catalog/internal/CatalogScanTest.java b/core/src/test/java/org/apache/brooklyn/core/catalog/internal/CatalogScanTest.java index 2d5abad..0ccb709 100644 --- a/core/src/test/java/org/apache/brooklyn/core/catalog/internal/CatalogScanTest.java +++ b/core/src/test/java/org/apache/brooklyn/core/catalog/internal/CatalogScanTest.java @@ -34,11 +34,11 @@ import org.apache.brooklyn.core.catalog.CatalogPredicates; import org.apache.brooklyn.core.catalog.internal.BasicBrooklynCatalog; import org.apache.brooklyn.core.catalog.internal.MyCatalogItems.MySillyAppTemplate; import org.apache.brooklyn.core.management.internal.LocalManagementContext; +import org.apache.brooklyn.core.util.ResourceUtils; import brooklyn.config.BrooklynProperties; import brooklyn.config.BrooklynServerConfig; import brooklyn.entity.basic.Entities; -import brooklyn.util.ResourceUtils; import brooklyn.util.net.Urls; import brooklyn.util.text.Strings; http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/699b3f65/core/src/test/java/org/apache/brooklyn/core/management/entitlement/AcmeEntitlementManagerTestFixture.java ---------------------------------------------------------------------- diff --git a/core/src/test/java/org/apache/brooklyn/core/management/entitlement/AcmeEntitlementManagerTestFixture.java b/core/src/test/java/org/apache/brooklyn/core/management/entitlement/AcmeEntitlementManagerTestFixture.java index 5689da2..24b1a1d 100644 --- a/core/src/test/java/org/apache/brooklyn/core/management/entitlement/AcmeEntitlementManagerTestFixture.java +++ b/core/src/test/java/org/apache/brooklyn/core/management/entitlement/AcmeEntitlementManagerTestFixture.java @@ -30,6 +30,7 @@ import org.apache.brooklyn.core.management.entitlement.NotEntitledException; import org.apache.brooklyn.core.management.entitlement.WebEntitlementContext; import org.apache.brooklyn.core.management.entitlement.Entitlements.EntityAndItem; import org.apache.brooklyn.core.management.entitlement.Entitlements.StringAndArgument; +import org.apache.brooklyn.core.util.config.ConfigBag; import org.apache.brooklyn.test.entity.LocalManagementContextForTests; import org.testng.Assert; import org.testng.annotations.AfterMethod; @@ -42,7 +43,6 @@ import brooklyn.config.BrooklynProperties; import brooklyn.entity.basic.ApplicationBuilder; import brooklyn.entity.basic.BasicApplication; import brooklyn.entity.basic.Entities; -import brooklyn.util.config.ConfigBag; import brooklyn.util.exceptions.Exceptions; public abstract class AcmeEntitlementManagerTestFixture { http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/699b3f65/core/src/test/java/org/apache/brooklyn/core/management/entitlement/EntityEntitlementTest.java ---------------------------------------------------------------------- diff --git a/core/src/test/java/org/apache/brooklyn/core/management/entitlement/EntityEntitlementTest.java b/core/src/test/java/org/apache/brooklyn/core/management/entitlement/EntityEntitlementTest.java index bb25740..7181c99 100644 --- a/core/src/test/java/org/apache/brooklyn/core/management/entitlement/EntityEntitlementTest.java +++ b/core/src/test/java/org/apache/brooklyn/core/management/entitlement/EntityEntitlementTest.java @@ -27,6 +27,7 @@ import org.apache.brooklyn.core.management.entitlement.NotEntitledException; import org.apache.brooklyn.core.management.entitlement.Entitlements.EntityAndItem; import org.apache.brooklyn.core.management.entitlement.Entitlements.StringAndArgument; import org.apache.brooklyn.core.management.internal.LocalManagementContext; +import org.apache.brooklyn.core.util.config.ConfigBag; import org.apache.brooklyn.test.entity.LocalManagementContextForTests; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -40,7 +41,6 @@ import brooklyn.config.BrooklynProperties; import brooklyn.entity.basic.ApplicationBuilder; import brooklyn.entity.basic.BasicApplication; import brooklyn.entity.basic.Entities; -import brooklyn.util.config.ConfigBag; import brooklyn.util.exceptions.Exceptions; public class EntityEntitlementTest { http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/699b3f65/core/src/test/java/org/apache/brooklyn/core/management/internal/EntityExecutionManagerTest.java ---------------------------------------------------------------------- diff --git a/core/src/test/java/org/apache/brooklyn/core/management/internal/EntityExecutionManagerTest.java b/core/src/test/java/org/apache/brooklyn/core/management/internal/EntityExecutionManagerTest.java index 7f35bba..721057d 100644 --- a/core/src/test/java/org/apache/brooklyn/core/management/internal/EntityExecutionManagerTest.java +++ b/core/src/test/java/org/apache/brooklyn/core/management/internal/EntityExecutionManagerTest.java @@ -37,6 +37,10 @@ import org.apache.brooklyn.api.management.Task; import org.apache.brooklyn.core.management.internal.BrooklynGarbageCollector; import org.apache.brooklyn.core.management.internal.LocalManagementContext; import org.apache.brooklyn.core.management.internal.ManagementContextInternal; +import org.apache.brooklyn.core.util.task.BasicExecutionManager; +import org.apache.brooklyn.core.util.task.ExecutionListener; +import org.apache.brooklyn.core.util.task.TaskBuilder; +import org.apache.brooklyn.core.util.task.Tasks; import org.apache.brooklyn.test.entity.LocalManagementContextForTests; import org.apache.brooklyn.test.entity.TestApplication; import org.apache.brooklyn.test.entity.TestEntity; @@ -58,10 +62,6 @@ import brooklyn.test.Asserts; import brooklyn.util.collections.MutableMap; import brooklyn.util.javalang.JavaClassNames; import brooklyn.util.repeat.Repeater; -import brooklyn.util.task.BasicExecutionManager; -import brooklyn.util.task.ExecutionListener; -import brooklyn.util.task.TaskBuilder; -import brooklyn.util.task.Tasks; import brooklyn.util.time.Duration; import brooklyn.util.time.Time; http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/699b3f65/core/src/test/java/org/apache/brooklyn/core/management/osgi/OsgiStandaloneTest.java ---------------------------------------------------------------------- diff --git a/core/src/test/java/org/apache/brooklyn/core/management/osgi/OsgiStandaloneTest.java b/core/src/test/java/org/apache/brooklyn/core/management/osgi/OsgiStandaloneTest.java index 7f1cc48..7180b1b 100644 --- a/core/src/test/java/org/apache/brooklyn/core/management/osgi/OsgiStandaloneTest.java +++ b/core/src/test/java/org/apache/brooklyn/core/management/osgi/OsgiStandaloneTest.java @@ -27,6 +27,9 @@ import java.util.List; import java.util.jar.JarInputStream; import org.apache.brooklyn.api.entity.Entity; +import org.apache.brooklyn.core.util.ResourceUtils; +import org.apache.brooklyn.core.util.osgi.Osgis; +import org.apache.brooklyn.core.util.osgi.Osgis.ManifestHelper; import org.apache.brooklyn.test.TestResourceUnavailableException; import brooklyn.util.exceptions.Exceptions; @@ -43,14 +46,11 @@ import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; -import brooklyn.util.ResourceUtils; import brooklyn.util.collections.MutableSet; import brooklyn.util.maven.MavenArtifact; import brooklyn.util.maven.MavenRetriever; import brooklyn.util.net.Urls; import brooklyn.util.os.Os; -import brooklyn.util.osgi.Osgis; -import brooklyn.util.osgi.Osgis.ManifestHelper; import brooklyn.util.stream.Streams; /** http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/699b3f65/core/src/test/java/org/apache/brooklyn/core/management/osgi/OsgiVersionMoreEntityTest.java ---------------------------------------------------------------------- diff --git a/core/src/test/java/org/apache/brooklyn/core/management/osgi/OsgiVersionMoreEntityTest.java b/core/src/test/java/org/apache/brooklyn/core/management/osgi/OsgiVersionMoreEntityTest.java index 7220e47..edc73d6 100644 --- a/core/src/test/java/org/apache/brooklyn/core/management/osgi/OsgiVersionMoreEntityTest.java +++ b/core/src/test/java/org/apache/brooklyn/core/management/osgi/OsgiVersionMoreEntityTest.java @@ -45,6 +45,7 @@ import org.apache.brooklyn.core.catalog.internal.CatalogTestUtils; import org.apache.brooklyn.core.catalog.internal.CatalogUtils; import org.apache.brooklyn.core.management.internal.LocalManagementContext; import org.apache.brooklyn.core.management.internal.ManagementContextInternal; +import org.apache.brooklyn.core.util.osgi.Osgis; import brooklyn.entity.basic.Entities; import brooklyn.entity.effector.Effectors; @@ -57,7 +58,6 @@ import org.apache.brooklyn.test.entity.TestApplication; import brooklyn.util.guava.Maybe; import brooklyn.util.os.Os; -import brooklyn.util.osgi.Osgis; import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableMap; http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/699b3f65/core/src/test/java/org/apache/brooklyn/core/util/BrooklynMavenArtifactsTest.java ---------------------------------------------------------------------- diff --git a/core/src/test/java/org/apache/brooklyn/core/util/BrooklynMavenArtifactsTest.java b/core/src/test/java/org/apache/brooklyn/core/util/BrooklynMavenArtifactsTest.java new file mode 100644 index 0000000..a86d1e0 --- /dev/null +++ b/core/src/test/java/org/apache/brooklyn/core/util/BrooklynMavenArtifactsTest.java @@ -0,0 +1,98 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.brooklyn.core.util; + +import org.apache.brooklyn.core.util.BrooklynMavenArtifacts; +import org.apache.brooklyn.core.util.ResourceUtils; +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/699b3f65/core/src/test/java/org/apache/brooklyn/core/util/ResourceUtilsHttpTest.java ---------------------------------------------------------------------- diff --git a/core/src/test/java/org/apache/brooklyn/core/util/ResourceUtilsHttpTest.java b/core/src/test/java/org/apache/brooklyn/core/util/ResourceUtilsHttpTest.java new file mode 100644 index 0000000..6ea434d --- /dev/null +++ b/core/src/test/java/org/apache/brooklyn/core/util/ResourceUtilsHttpTest.java @@ -0,0 +1,197 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.brooklyn.core.util; + +import static org.testng.Assert.assertEquals; +import static org.testng.Assert.assertFalse; + +import java.io.IOException; +import java.io.InputStream; + +import org.apache.brooklyn.core.util.ResourceUtils; +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/699b3f65/core/src/test/java/org/apache/brooklyn/core/util/ResourceUtilsTest.java ---------------------------------------------------------------------- diff --git a/core/src/test/java/org/apache/brooklyn/core/util/ResourceUtilsTest.java b/core/src/test/java/org/apache/brooklyn/core/util/ResourceUtilsTest.java new file mode 100644 index 0000000..10cf455 --- /dev/null +++ b/core/src/test/java/org/apache/brooklyn/core/util/ResourceUtilsTest.java @@ -0,0 +1,190 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.brooklyn.core.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.apache.brooklyn.core.util.ResourceUtils; +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/699b3f65/core/src/test/java/org/apache/brooklyn/core/util/config/ConfigBagTest.java ---------------------------------------------------------------------- diff --git a/core/src/test/java/org/apache/brooklyn/core/util/config/ConfigBagTest.java b/core/src/test/java/org/apache/brooklyn/core/util/config/ConfigBagTest.java new file mode 100644 index 0000000..f4db6c2 --- /dev/null +++ b/core/src/test/java/org/apache/brooklyn/core/util/config/ConfigBagTest.java @@ -0,0 +1,193 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.brooklyn.core.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.apache.brooklyn.core.util.config.ConfigBag; +import org.apache.brooklyn.core.util.config.ConfigBagTest; +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/699b3f65/core/src/test/java/org/apache/brooklyn/core/util/crypto/SecureKeysAndSignerTest.java ---------------------------------------------------------------------- diff --git a/core/src/test/java/org/apache/brooklyn/core/util/crypto/SecureKeysAndSignerTest.java b/core/src/test/java/org/apache/brooklyn/core/util/crypto/SecureKeysAndSignerTest.java new file mode 100644 index 0000000..d681b0f --- /dev/null +++ b/core/src/test/java/org/apache/brooklyn/core/util/crypto/SecureKeysAndSignerTest.java @@ -0,0 +1,169 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.brooklyn.core.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.apache.brooklyn.core.util.ResourceUtils; +import org.apache.brooklyn.core.util.crypto.FluentKeySigner; +import org.apache.brooklyn.core.util.crypto.SecureKeys; +import org.apache.brooklyn.core.util.crypto.SecureKeys.PassphraseProblem; +import org.testng.Assert; +import org.testng.annotations.Test; + +import brooklyn.util.crypto.AuthorizedKeysParser; +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); + } + +}
