Convert groovy tests to java
Project: http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/repo Commit: http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/commit/f69ade37 Tree: http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/tree/f69ade37 Diff: http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/diff/f69ade37 Branch: refs/heads/master Commit: f69ade37a641e1b1997b71986e8a5731b1dccc59 Parents: 24b0f3e Author: Svetoslav Neykov <[email protected]> Authored: Thu Oct 22 15:48:07 2015 +0300 Committer: Svetoslav Neykov <[email protected]> Committed: Thu Oct 22 16:33:08 2015 +0300 ---------------------------------------------------------------------- ...stomAggregatingEnricherDeprecatedTest.groovy | 368 ----------------- ...CustomAggregatingEnricherDeprecatedTest.java | 405 +++++++++++++++++++ .../TransformingEnricherDeprecatedTest.groovy | 83 ---- .../TransformingEnricherDeprecatedTest.java | 92 +++++ .../util/core/internal/RepeaterTest.groovy | 256 ------------ .../util/core/internal/RepeaterTest.java | 251 ++++++++++++ .../demo/WebClusterDatabaseExampleGroovy.groovy | 92 ----- locations/jclouds/pom.xml | 21 - .../AwsEc2LocationWindowsLiveTest.groovy | 94 ----- .../provider/AwsEc2LocationWindowsLiveTest.java | 95 +++++ .../provider/CarrenzaLocationLiveTest.groovy | 132 ------ .../provider/CarrenzaLocationLiveTest.java | 135 +++++++ .../provider/GoGridLocationLiveTest.groovy | 52 --- .../provider/GoGridLocationLiveTest.java | 52 +++ policy/pom.xml | 25 +- .../policy/enricher/DeltaEnrichersTests.groovy | 123 ------ .../policy/enricher/DeltaEnrichersTests.java | 144 +++++++ .../enricher/RollingMeanEnricherTest.groovy | 105 ----- .../enricher/RollingMeanEnricherTest.java | 106 +++++ .../RollingTimeWindowMeanEnricherTest.groovy | 155 ------- .../RollingTimeWindowMeanEnricherTest.java | 156 +++++++ .../brooklyn/entity/database/Database.groovy | 53 --- .../brooklyn/entity/database/Database.java | 42 ++ .../apache/brooklyn/entity/database/Schema.java | 37 ++ .../Infinispan5ServerIntegrationTest.groovy | 103 ----- .../Infinispan5ServerIntegrationTest.java | 107 +++++ software/webapp/pom.xml | 18 - .../webapp/WebAppLiveIntegrationTest.groovy | 101 ----- .../webapp/WebAppLiveIntegrationTest.java | 91 +++++ usage/cli/pom.xml | 12 - 30 files changed, 1715 insertions(+), 1791 deletions(-) ---------------------------------------------------------------------- http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/f69ade37/core/src/test/java/org/apache/brooklyn/enricher/stock/CustomAggregatingEnricherDeprecatedTest.groovy ---------------------------------------------------------------------- diff --git a/core/src/test/java/org/apache/brooklyn/enricher/stock/CustomAggregatingEnricherDeprecatedTest.groovy b/core/src/test/java/org/apache/brooklyn/enricher/stock/CustomAggregatingEnricherDeprecatedTest.groovy deleted file mode 100644 index 72acb74..0000000 --- a/core/src/test/java/org/apache/brooklyn/enricher/stock/CustomAggregatingEnricherDeprecatedTest.groovy +++ /dev/null @@ -1,368 +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 org.apache.brooklyn.enricher.stock - -import static org.testng.Assert.assertEquals - -import org.apache.brooklyn.api.entity.EntitySpec -import org.apache.brooklyn.api.sensor.AttributeSensor -import org.apache.brooklyn.core.test.entity.TestApplication -import org.apache.brooklyn.core.test.entity.TestEntity -import org.apache.brooklyn.enricher.stock.CustomAggregatingEnricher; -import org.apache.brooklyn.core.entity.Entities -import org.apache.brooklyn.entity.group.BasicGroup -import org.apache.brooklyn.test.Asserts; -import org.apache.brooklyn.core.location.SimulatedLocation -import org.apache.brooklyn.core.sensor.BasicAttributeSensor -import org.slf4j.Logger -import org.slf4j.LoggerFactory -import org.testng.annotations.AfterMethod -import org.testng.annotations.BeforeMethod -import org.testng.annotations.Test - -import com.google.common.base.Function - -class CustomAggregatingEnricherDeprecatedTest { - - public static final Logger log = LoggerFactory.getLogger(CustomAggregatingEnricherDeprecatedTest.class); - - private static final long TIMEOUT_MS = 10*1000 - private static final long SHORT_WAIT_MS = 250 - - TestApplication app - TestEntity producer - - AttributeSensor<Integer> intSensor - AttributeSensor<Integer> target - - @BeforeMethod(alwaysRun=true) - public void setUp() { - app = TestApplication.Factory.newManagedInstanceForTests(); - producer = app.createAndManageChild(EntitySpec.create(TestEntity.class)); - intSensor = new BasicAttributeSensor<Integer>(Integer.class, "int sensor") - target = new BasicAttributeSensor<Integer>(Long.class, "target sensor") - - app.start([new SimulatedLocation()]) - } - - @AfterMethod(alwaysRun=true) - public void tearDown() { - if (app!=null) Entities.destroyAll(app.getManagementContext()); - } - - @Test - public void testEnrichersWithNoProducers() { - CustomAggregatingEnricher<Integer> cae = CustomAggregatingEnricher.<Integer>newSummingEnricher([:], intSensor, target, 11, 40) - producer.enrichers().add(cae) - assertEquals cae.getAggregate(), 40 - } - - @Test - public void testSummingEnricherWhenNoSensorValuesYet() { - CustomAggregatingEnricher<Integer> cae = CustomAggregatingEnricher.<Integer>newSummingEnricher( - intSensor, target, producers:[producer], 11, 40) - producer.enrichers().add(cae) - assertEquals cae.getAggregate(), 11 - } - - @Test - public void testSingleProducerSum() { - CustomAggregatingEnricher<Integer> cae = CustomAggregatingEnricher.<Integer>newSummingEnricher( - intSensor, target, null, null, producers:[producer]) - producer.enrichers().add(cae) - assertEquals cae.getAggregate(), null - cae.onEvent(intSensor.newEvent(producer, 1)) - assertEquals cae.getAggregate(), 1 - } - - @Test - public void testSummingEnricherWhenNoAndNullSensorValue() { - CustomAggregatingEnricher<Integer> cae = CustomAggregatingEnricher.<Integer>newSummingEnricher( - intSensor, target, null, null, producers:[producer]) - producer.enrichers().add(cae) - assertEquals cae.getAggregate(), null - cae.onEvent(intSensor.newEvent(producer, null)) - assertEquals cae.getAggregate(), null - } - - @Test - public void testSummingEnricherWhenNoAndNullSensorValueExplicitValue() { - CustomAggregatingEnricher<Integer> cae = CustomAggregatingEnricher.<Integer>newSummingEnricher( - intSensor, target, 3 /** if null */, 5 /** if none */, producers:[producer]) - producer.enrichers().add(cae) - assertEquals cae.getAggregate(), 3 - cae.onEvent(intSensor.newEvent(producer, null)) - assertEquals cae.getAggregate(), 3 - cae.onEvent(intSensor.newEvent(producer, 1)) - assertEquals cae.getAggregate(), 1 - cae.onEvent(intSensor.newEvent(producer, 7)) - assertEquals cae.getAggregate(), 7 - } - - @Test - public void testMultipleProducersSum() { - List<TestEntity> producers = [ - app.createAndManageChild(EntitySpec.create(TestEntity.class)), - app.createAndManageChild(EntitySpec.create(TestEntity.class)), - app.createAndManageChild(EntitySpec.create(TestEntity.class)) - ] - CustomAggregatingEnricher<Integer> cae = CustomAggregatingEnricher.<Integer>newSummingEnricher( - intSensor, target, null, null, producers:producers) - - producer.enrichers().add(cae) - assertEquals cae.getAggregate(), null - cae.onEvent(intSensor.newEvent(producers[2], 1)) - assertEquals cae.getAggregate(), 1 - cae.onEvent(intSensor.newEvent(producers[0], 3)) - assertEquals cae.getAggregate(), 4 - cae.onEvent(intSensor.newEvent(producers[1], 3)) - assertEquals cae.getAggregate(), 7 - - } - - @Test - public void testAveragingEnricherWhenNoAndNullSensorValues() { - List<TestEntity> producers = [ - app.createAndManageChild(EntitySpec.create(TestEntity.class)) - ] - CustomAggregatingEnricher<Double> cae = CustomAggregatingEnricher.<Double>newAveragingEnricher( - intSensor, new BasicAttributeSensor<Double>(Double.class, "target sensor"), null, null, producers:producers) - producer.enrichers().add(cae) - assertEquals cae.getAggregate(), null - cae.onEvent(intSensor.newEvent(producers[0], null)) - assertEquals cae.getAggregate(), null - } - - @Test - public void testAveragingEnricherWhenNoAndNullSensorValuesExplicit() { - List<TestEntity> producers = [ - app.createAndManageChild(EntitySpec.create(TestEntity.class)) - ] - CustomAggregatingEnricher<Double> cae = CustomAggregatingEnricher.<Double>newAveragingEnricher( - intSensor, new BasicAttributeSensor<Double>(Double.class, "target sensor"), 3 /** if null */, 5 /** if none */, - producers:producers) - producer.enrichers().add(cae) - - assertEquals cae.getAggregate(), 3d - cae.onEvent(intSensor.newEvent(producers[0], null)) - assertEquals cae.getAggregate(), 3d - cae.onEvent(intSensor.newEvent(producers[0], 4)) - assertEquals cae.getAggregate(), 4d - } - - @Test - public void testAveragingEnricherWhenNoSensors() { - List<TestEntity> producers = [ - ] - CustomAggregatingEnricher<Double> cae = CustomAggregatingEnricher.<Double>newAveragingEnricher( - intSensor, new BasicAttributeSensor<Double>(Double.class, "target sensor"), 3 /** if null */, 5 /** if none */, - producers:producers) - producer.enrichers().add(cae) - - assertEquals cae.getAggregate(), 5d - } - - @Test - public void testMultipleProducersAverage() { - List<TestEntity> producers = [ - app.createAndManageChild(EntitySpec.create(TestEntity.class)), - app.createAndManageChild(EntitySpec.create(TestEntity.class)), - app.createAndManageChild(EntitySpec.create(TestEntity.class)) - ] - CustomAggregatingEnricher<Double> cae = CustomAggregatingEnricher.<Double>newAveragingEnricher( - intSensor, new BasicAttributeSensor<Double>(Double.class, "target sensor"), null, null, producers:producers) - - producer.enrichers().add(cae) - - assertEquals cae.getAggregate(), null - cae.onEvent(intSensor.newEvent(producers[0], 3)) - assertEquals cae.getAggregate(), 3d - - cae.onEvent(intSensor.newEvent(producers[1], 3)) - assertEquals cae.getAggregate(), 3d - - cae.onEvent(intSensor.newEvent(producers[2], 6)) - assertEquals cae.getAggregate(), 4d - - // change p2's value to 7.5, average increase of 0.5. - cae.onEvent(intSensor.newEvent(producers[2], 7.5)) - assertEquals cae.getAggregate(), 4.5d - } - - @Test - public void testMultipleProducersAverageDefaultingZero() { - List<TestEntity> producers = [ - app.createAndManageChild(EntitySpec.create(TestEntity.class)), - app.createAndManageChild(EntitySpec.create(TestEntity.class)), - app.createAndManageChild(EntitySpec.create(TestEntity.class)) - ] - CustomAggregatingEnricher<Double> cae = CustomAggregatingEnricher.<Double>newAveragingEnricher( - intSensor, new BasicAttributeSensor<Double>(Double.class, "target sensor"), 0, 0, producers:producers) - - producer.enrichers().add(cae) - - assertEquals cae.getAggregate(), 0d - cae.onEvent(intSensor.newEvent(producers[0], 3)) - assertEquals cae.getAggregate(), 1d - - cae.onEvent(intSensor.newEvent(producers[1], 3)) - assertEquals cae.getAggregate(), 2d - - cae.onEvent(intSensor.newEvent(producers[2], 6)) - assertEquals cae.getAggregate(), 4d - - // change p2's value to 7.5, average increase of 0.5. - cae.onEvent(intSensor.newEvent(producers[2], 7.5)) - assertEquals cae.getAggregate(), 4.5d - } - - @Test - public void testAddingAndRemovingProducers() { - TestEntity p1 = app.createAndManageChild(EntitySpec.create(TestEntity.class)); - TestEntity p2 = app.createAndManageChild(EntitySpec.create(TestEntity.class)); - - CustomAggregatingEnricher<Integer> cae = CustomAggregatingEnricher.<Integer>newSummingEnricher( - intSensor, target, null, null, producers:[p1]) - - producer.enrichers().add(cae) - assertEquals cae.getAggregate(), null - - // Event by initial producer - cae.onEvent(intSensor.newEvent(p1, 1)) - assertEquals cae.getAggregate(), 1 - - // Add producer and fire event - cae.addProducer(p2) - cae.onEvent(intSensor.newEvent(p2, 4)) - assertEquals cae.getAggregate(), 5 - - cae.removeProducer(p2) - assertEquals cae.getAggregate(), 1 - } - - @Test - public void testAggregatesNewMembersOfGroup() { - try { - BasicGroup group = app.createAndManageChild(EntitySpec.create(BasicGroup.class)); - TestEntity p1 = app.createAndManageChild(EntitySpec.create(TestEntity.class)) - TestEntity p2 = app.createAndManageChild(EntitySpec.create(TestEntity.class)) - log.debug("created $group and the entities it will contain $p1 $p2") - - CustomAggregatingEnricher<Integer> cae = CustomAggregatingEnricher.<Integer>newSummingEnricher(intSensor, target, 0, 0, allMembers:true) - group.enrichers().add(cae) - - assertEquals cae.getAggregate(), 0 - - group.addMember(p1) - p1.sensors().set(intSensor, 1) - Asserts.succeedsEventually(timeout:TIMEOUT_MS) { - assertEquals cae.getAggregate(), 1 - } - - group.addMember(p2) - p2.sensors().set(intSensor, 2) - Asserts.succeedsEventually(timeout:TIMEOUT_MS) { - assertEquals cae.getAggregate(), 3 - } - - group.removeMember(p2) - Asserts.succeedsEventually(timeout:TIMEOUT_MS) { - assertEquals cae.getAggregate(), 1 - } - } catch (Exception e) { - log.error("testAggregatesNewMembersOfGroup failed (now cleaning up): "+e) - throw e; - } - } - - @Test(groups = "Integration") - public void testAggregatesGroupMembersFiftyTimes() { - for (int i=0; i<50; i++) { - log.debug "testAggregatesNewMembersOfGroup $i" - testAggregatesNewMembersOfGroup(); - } - } - - @Test - public void testAggregatesExistingMembersOfGroup() { - BasicGroup group = app.addChild(EntitySpec.create(BasicGroup.class)); - TestEntity p1 = app.getManagementContext().getEntityManager().createEntity(EntitySpec.create(TestEntity.class).parent(group)); - TestEntity p2 = app.getManagementContext().getEntityManager().createEntity(EntitySpec.create(TestEntity.class).parent(group)); - group.addMember(p1) - group.addMember(p2) - p1.sensors().set(intSensor, 1) - Entities.manage(group); - - CustomAggregatingEnricher<Integer> cae = CustomAggregatingEnricher.<Integer>newSummingEnricher(intSensor, target, null, null, allMembers:true) - group.enrichers().add(cae) - - assertEquals cae.getAggregate(), 1 - - p2.sensors().set(intSensor, 2) - Asserts.succeedsEventually(timeout:TIMEOUT_MS) { - assertEquals cae.getAggregate(), 3 - } - - group.removeMember(p2) - Asserts.succeedsEventually(timeout:TIMEOUT_MS) { - assertEquals cae.getAggregate(), 1 - } - } - - @Test - public void testAppliesFilterWhenAggregatingMembersOfGroup() { - BasicGroup group = app.createAndManageChild(EntitySpec.create(BasicGroup.class)); - TestEntity p1 = app.createAndManageChild(EntitySpec.create(TestEntity.class)); - TestEntity p2 = app.createAndManageChild(EntitySpec.create(TestEntity.class)); - TestEntity p3 = app.createAndManageChild(EntitySpec.create(TestEntity.class)); - group.addMember(p1) - group.addMember(p2) - p1.sensors().set(intSensor, 1) - p2.sensors().set(intSensor, 2) - p3.sensors().set(intSensor, 4) - - CustomAggregatingEnricher<Integer> cae = CustomAggregatingEnricher.<Integer>newSummingEnricher(intSensor, target, null, null, allMembers:true, filter:{it == p1}) - group.enrichers().add(cae) - - assertEquals cae.getAggregate(), 1 - - group.addMember(p3) - Asserts.succeedsContinually(timeout:SHORT_WAIT_MS) { - assertEquals cae.getAggregate(), 1 - } - } - - @Test - public void testCustomAggregatingFunction() { - TestEntity p1 = app.createAndManageChild(EntitySpec.create(TestEntity.class)); - Function<Collection<Integer>,Integer> aggregator = { Collection c -> - int result = 0; c.each { result += it*it }; return result; - } as Function - - CustomAggregatingEnricher<Integer> cae = CustomAggregatingEnricher.<Integer>newEnricher( - intSensor, target, aggregator, 0, producers:[p1]) - - producer.enrichers().add(cae) - assertEquals cae.getAggregate(), 0 - - // Event by producer - cae.onEvent(intSensor.newEvent(p1, 2)) - assertEquals cae.getAggregate(), 4 - } -} http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/f69ade37/core/src/test/java/org/apache/brooklyn/enricher/stock/CustomAggregatingEnricherDeprecatedTest.java ---------------------------------------------------------------------- diff --git a/core/src/test/java/org/apache/brooklyn/enricher/stock/CustomAggregatingEnricherDeprecatedTest.java b/core/src/test/java/org/apache/brooklyn/enricher/stock/CustomAggregatingEnricherDeprecatedTest.java new file mode 100644 index 0000000..5f3e8b5 --- /dev/null +++ b/core/src/test/java/org/apache/brooklyn/enricher/stock/CustomAggregatingEnricherDeprecatedTest.java @@ -0,0 +1,405 @@ +/* + * 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.enricher.stock; + + +import java.util.Collection; +import java.util.List; +import java.util.Map; + +import org.apache.brooklyn.api.entity.EntitySpec; +import org.apache.brooklyn.api.sensor.AttributeSensor; +import org.apache.brooklyn.core.entity.Entities; +import org.apache.brooklyn.core.location.SimulatedLocation; +import org.apache.brooklyn.core.sensor.BasicAttributeSensor; +import org.apache.brooklyn.core.sensor.Sensors; +import org.apache.brooklyn.core.test.entity.TestApplication; +import org.apache.brooklyn.core.test.entity.TestEntity; +import org.apache.brooklyn.entity.group.BasicGroup; +import org.apache.brooklyn.test.Asserts; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.testng.Assert; +import org.testng.annotations.AfterMethod; +import org.testng.annotations.BeforeMethod; +import org.testng.annotations.Test; + +import com.google.common.base.Function; +import com.google.common.base.Predicates; +import com.google.common.collect.ImmutableList; +import com.google.common.collect.ImmutableMap; + +@SuppressWarnings("deprecation") +public class CustomAggregatingEnricherDeprecatedTest { + + public static final Logger log = LoggerFactory.getLogger(CustomAggregatingEnricherDeprecatedTest.class); + + private static final long TIMEOUT_MS = 10*1000; + private static final long SHORT_WAIT_MS = 250; + + TestApplication app; + TestEntity producer; + Map<String, ?> producersFlags; + + AttributeSensor<Integer> intSensor = Sensors.newIntegerSensor("int sensor"); + AttributeSensor<Double> doubleSensor = Sensors.newDoubleSensor("double sensor"); + AttributeSensor<Integer> target = Sensors.newIntegerSensor("target sensor"); + + @BeforeMethod(alwaysRun=true) + public void setUp() { + app = TestApplication.Factory.newManagedInstanceForTests(); + producer = app.createAndManageChild(EntitySpec.create(TestEntity.class)); + producersFlags = ImmutableMap.of("producers", ImmutableList.of(producer)); + + app.start(ImmutableList.of(new SimulatedLocation())); + } + + @AfterMethod(alwaysRun=true) + public void tearDown() { + if (app!=null) Entities.destroyAll(app.getManagementContext()); + } + + @Test + public void testEnrichersWithNoProducers() { + CustomAggregatingEnricher<Integer, Integer> cae = CustomAggregatingEnricher.<Integer, Integer>newSummingEnricher(ImmutableMap.<String,Object>of(), intSensor, target, 11, 40); + producer.enrichers().add(cae); + assertEquals(cae.getAggregate(), 40); + } + + @Test + public void testSummingEnricherWhenNoSensorValuesYet() { + CustomAggregatingEnricher<Integer, Integer> cae = CustomAggregatingEnricher.<Integer, Integer>newSummingEnricher( + producersFlags, intSensor, target, 11, 40); + producer.enrichers().add(cae); + assertEquals(cae.getAggregate(), 11); + } + + @Test + public void testSingleProducerSum() { + CustomAggregatingEnricher<Integer, Integer> cae = CustomAggregatingEnricher.<Integer, Integer>newSummingEnricher( + producersFlags, intSensor, target, null, null); + producer.enrichers().add(cae); + Assert.assertEquals(cae.getAggregate(), null); + cae.onEvent(intSensor.newEvent(producer, 1)); + assertEquals(cae.getAggregate(), 1); + } + + @Test + public void testSummingEnricherWhenNoAndNullSensorValue() { + CustomAggregatingEnricher<Integer, Integer> cae = CustomAggregatingEnricher.<Integer, Integer>newSummingEnricher( + producersFlags, intSensor, target, null, null); + producer.enrichers().add(cae); + Assert.assertEquals(cae.getAggregate(), null); + cae.onEvent(intSensor.newEvent(producer, null)); + Assert.assertEquals(cae.getAggregate(), null); + } + + @Test + public void testSummingEnricherWhenNoAndNullSensorValueExplicitValue() { + CustomAggregatingEnricher<Integer, Integer> cae = CustomAggregatingEnricher.<Integer, Integer>newSummingEnricher( + producersFlags, intSensor, target, 3 /** if null */, 5 /** if none */); + producer.enrichers().add(cae); + assertEquals(cae.getAggregate(), 3); + cae.onEvent(intSensor.newEvent(producer, null)); + assertEquals(cae.getAggregate(), 3); + cae.onEvent(intSensor.newEvent(producer, 1)); + assertEquals(cae.getAggregate(), 1); + cae.onEvent(intSensor.newEvent(producer, 7)); + assertEquals(cae.getAggregate(), 7); + } + + @Test + public void testMultipleProducersSum() { + List<TestEntity> producers = ImmutableList.of( + app.createAndManageChild(EntitySpec.create(TestEntity.class)), + app.createAndManageChild(EntitySpec.create(TestEntity.class)), + app.createAndManageChild(EntitySpec.create(TestEntity.class)) + ); + CustomAggregatingEnricher<Integer, Integer> cae = CustomAggregatingEnricher.<Integer, Integer>newSummingEnricher( + ImmutableMap.of("producers", producers), intSensor, target, null, null); + + producer.enrichers().add(cae); + Assert.assertEquals(cae.getAggregate(), null); + cae.onEvent(intSensor.newEvent(producers.get(2), 1)); + assertEquals(cae.getAggregate(), 1); + cae.onEvent(intSensor.newEvent(producers.get(0), 3)); + assertEquals(cae.getAggregate(), 4); + cae.onEvent(intSensor.newEvent(producers.get(1), 3)); + assertEquals(cae.getAggregate(), 7); + + } + + @Test + public void testAveragingEnricherWhenNoAndNullSensorValues() { + List<TestEntity> producers = ImmutableList.of( + app.createAndManageChild(EntitySpec.create(TestEntity.class)) + ); + CustomAggregatingEnricher<Integer, Double> cae = CustomAggregatingEnricher.<Integer>newAveragingEnricher( + ImmutableMap.of("producers", producers), intSensor, new BasicAttributeSensor<Double>(Double.class, "target sensor"), null, null); + producer.enrichers().add(cae); + Assert.assertEquals(cae.getAggregate(), null); + cae.onEvent(intSensor.newEvent(producers.get(0), null)); + Assert.assertEquals(cae.getAggregate(), null); + } + + @Test + public void testAveragingEnricherWhenNoAndNullSensorValuesExplicit() { + List<TestEntity> producers = ImmutableList.of( + app.createAndManageChild(EntitySpec.create(TestEntity.class)) + ); + CustomAggregatingEnricher<Integer, Double> cae = CustomAggregatingEnricher.<Integer>newAveragingEnricher( + ImmutableMap.of("producers", producers), intSensor, new BasicAttributeSensor<Double>(Double.class, "target sensor"), 3 /** if null */, 5d /** if none */); + producer.enrichers().add(cae); + + assertEquals(cae.getAggregate(), 3d); + cae.onEvent(intSensor.newEvent(producers.get(0), null)); + assertEquals(cae.getAggregate(), 3d); + cae.onEvent(intSensor.newEvent(producers.get(0), 4)); + assertEquals(cae.getAggregate(), 4d); + } + + @Test + public void testAveragingEnricherWhenNoSensors() { + List<TestEntity> producers = ImmutableList.of( + ); + CustomAggregatingEnricher<Integer, Double> cae = CustomAggregatingEnricher.<Integer>newAveragingEnricher( + ImmutableMap.of("producers", producers), intSensor, new BasicAttributeSensor<Double>(Double.class, "target sensor"), 3 /** if null */, 5d /** if none */); + producer.enrichers().add(cae); + + assertEquals(cae.getAggregate(), 5d); + } + + @Test + public void testMultipleProducersAverage() { + List<TestEntity> producers = ImmutableList.of( + app.createAndManageChild(EntitySpec.create(TestEntity.class)), + app.createAndManageChild(EntitySpec.create(TestEntity.class)), + app.createAndManageChild(EntitySpec.create(TestEntity.class)) + ); + CustomAggregatingEnricher<Double, Double> cae = CustomAggregatingEnricher.<Double>newAveragingEnricher( + ImmutableMap.of("producers", producers), + doubleSensor, new BasicAttributeSensor<Double>(Double.class, "target sensor"), null, null); + + producer.enrichers().add(cae); + + Assert.assertEquals(cae.getAggregate(), null); + cae.onEvent(doubleSensor.newEvent(producers.get(0), 3d)); + assertEquals(cae.getAggregate(), 3d); + + cae.onEvent(doubleSensor.newEvent(producers.get(1), 3d)); + assertEquals(cae.getAggregate(), 3d); + + cae.onEvent(doubleSensor.newEvent(producers.get(2), 6d)); + assertEquals(cae.getAggregate(), 4d); + + // change p2's value to 7.5, average increase of 0.5. + cae.onEvent(doubleSensor.newEvent(producers.get(2), 7.5d)); + assertEquals(cae.getAggregate(), 4.5d); + } + + @Test + public void testMultipleProducersAverageDefaultingZero() { + List<TestEntity> producers = ImmutableList.of( + app.createAndManageChild(EntitySpec.create(TestEntity.class)), + app.createAndManageChild(EntitySpec.create(TestEntity.class)), + app.createAndManageChild(EntitySpec.create(TestEntity.class)) + ); + CustomAggregatingEnricher<Double, Double> cae = CustomAggregatingEnricher.<Double>newAveragingEnricher( + ImmutableMap.of("producers", producers), + doubleSensor, new BasicAttributeSensor<Double>(Double.class, "target sensor"), 0d, 0d); + + producer.enrichers().add(cae); + + assertEquals(cae.getAggregate(), 0d); + cae.onEvent(doubleSensor.newEvent(producers.get(0), 3d)); + assertEquals(cae.getAggregate(), 1d); + + cae.onEvent(doubleSensor.newEvent(producers.get(1), 3d)); + assertEquals(cae.getAggregate(), 2d); + + cae.onEvent(doubleSensor.newEvent(producers.get(2), 6d)); + assertEquals(cae.getAggregate(), 4d); + + // change p2's value to 7.5, average increase of 0.5. + cae.onEvent(doubleSensor.newEvent(producers.get(2), 7.5d)); + assertEquals(cae.getAggregate(), 4.5d); + } + + @Test + public void testAddingAndRemovingProducers() { + TestEntity p1 = app.createAndManageChild(EntitySpec.create(TestEntity.class)); + TestEntity p2 = app.createAndManageChild(EntitySpec.create(TestEntity.class)); + + CustomAggregatingEnricher<Integer, Integer> cae = CustomAggregatingEnricher.<Integer, Integer>newSummingEnricher( + ImmutableMap.of("producers", ImmutableList.of(p1)), + intSensor, target, null, null); + + producer.enrichers().add(cae); + Assert.assertEquals(cae.getAggregate(), null); + + // Event by initial producer + cae.onEvent(intSensor.newEvent(p1, 1)); + assertEquals(cae.getAggregate(), 1); + + // Add producer and fire event + cae.addProducer(p2); + cae.onEvent(intSensor.newEvent(p2, 4)); + assertEquals(cae.getAggregate(), 5); + + cae.removeProducer(p2); + assertEquals(cae.getAggregate(), 1); + } + + @Test + public void testAggregatesNewMembersOfGroup() { + try { + BasicGroup group = app.createAndManageChild(EntitySpec.create(BasicGroup.class)); + TestEntity p1 = app.createAndManageChild(EntitySpec.create(TestEntity.class)); + TestEntity p2 = app.createAndManageChild(EntitySpec.create(TestEntity.class)); + log.debug("created $group and the entities it will contain $p1 $p2"); + + CustomAggregatingEnricher<Integer, Integer> cae = CustomAggregatingEnricher.<Integer, Integer>newSummingEnricher( + ImmutableMap.of("allMembers", true), + intSensor, target, 0, 0); + group.enrichers().add(cae); + + assertEquals(cae.getAggregate(), 0); + + group.addMember(p1); + p1.sensors().set(intSensor, 1); + aggregateIsEventually(cae, 1); + + group.addMember(p2); + p2.sensors().set(intSensor, 2); + aggregateIsEventually(cae, 3); + + group.removeMember(p2); + aggregateIsEventually(cae, 1); + } catch (Exception e) { + log.error("testAggregatesNewMembersOfGroup failed (now cleaning up): "+e); + throw e; + } + } + + @Test(groups = "Integration") + public void testAggregatesGroupMembersFiftyTimes() { + for (int i=0; i<50; i++) { + log.debug("testAggregatesNewMembersOfGroup $i"); + testAggregatesNewMembersOfGroup(); + } + } + + @Test + public void testAggregatesExistingMembersOfGroup() { + BasicGroup group = app.addChild(EntitySpec.create(BasicGroup.class)); + TestEntity p1 = app.getManagementContext().getEntityManager().createEntity(EntitySpec.create(TestEntity.class).parent(group)); + TestEntity p2 = app.getManagementContext().getEntityManager().createEntity(EntitySpec.create(TestEntity.class).parent(group)); + group.addMember(p1); + group.addMember(p2); + p1.sensors().set(intSensor, 1); + Entities.manage(group); + + CustomAggregatingEnricher<Integer, Integer> cae = CustomAggregatingEnricher.<Integer, Integer>newSummingEnricher( + ImmutableMap.of("allMembers", true), + intSensor, target, null, null); + group.enrichers().add(cae); + + assertEquals(cae.getAggregate(), 1); + + p2.sensors().set(intSensor, 2); + aggregateIsEventually(cae, 3); + + group.removeMember(p2); + aggregateIsEventually(cae, 1); + } + + @Test + public void testAppliesFilterWhenAggregatingMembersOfGroup() { + BasicGroup group = app.createAndManageChild(EntitySpec.create(BasicGroup.class)); + TestEntity p1 = app.createAndManageChild(EntitySpec.create(TestEntity.class)); + TestEntity p2 = app.createAndManageChild(EntitySpec.create(TestEntity.class)); + TestEntity p3 = app.createAndManageChild(EntitySpec.create(TestEntity.class)); + group.addMember(p1); + group.addMember(p2); + p1.sensors().set(intSensor, 1); + p2.sensors().set(intSensor, 2); + p3.sensors().set(intSensor, 4); + + final CustomAggregatingEnricher<Integer, Integer> cae = CustomAggregatingEnricher.<Integer, Integer>newSummingEnricher( + ImmutableMap.of("allMembers", true, "filter", Predicates.equalTo(p1)), + intSensor, target, null, null); + group.enrichers().add(cae); + + assertEquals(cae.getAggregate(), 1); + + group.addMember(p3); + Asserts.succeedsContinually(ImmutableMap.of("timeout", SHORT_WAIT_MS), new Runnable() { + @Override + public void run() { + assertEquals(cae.getAggregate(), 1); + } + }); + } + + @Test + public void testCustomAggregatingFunction() { + TestEntity p1 = app.createAndManageChild(EntitySpec.create(TestEntity.class)); + Function<Collection<Integer>,Integer> aggregator = new Function<Collection<Integer>, Integer>() { + @Override + public Integer apply(Collection<Integer> c) { + int result = 0; + for (Integer it : c) { + result += it*it; + } + return result; + } + }; + + CustomAggregatingEnricher<Integer, Integer> cae = CustomAggregatingEnricher.<Integer, Integer>newEnricher( + ImmutableMap.of("producers", ImmutableList.of(p1)), + intSensor, target, aggregator, 0); + + producer.enrichers().add(cae); + assertEquals(cae.getAggregate(), 0); + + // Event by producer + cae.onEvent(intSensor.newEvent(p1, 2)); + assertEquals(cae.getAggregate(), 4); + } + + + private void assertEquals(Integer i1, int i2) { + Assert.assertEquals(i1, (Integer)i2); + } + private void assertEquals(Double i1, double i2) { + Assert.assertEquals(i1, (Double)i2); + } + + private void aggregateIsEventually(final CustomAggregatingEnricher<Integer, Integer> cae, final int avg) { + ImmutableMap<String, Long> timeout = ImmutableMap.of("timeout", TIMEOUT_MS); + + Asserts.succeedsEventually(timeout, new Runnable() { + @Override + public void run() { + assertEquals(cae.getAggregate(), avg); + } + }); + } + +} http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/f69ade37/core/src/test/java/org/apache/brooklyn/enricher/stock/TransformingEnricherDeprecatedTest.groovy ---------------------------------------------------------------------- diff --git a/core/src/test/java/org/apache/brooklyn/enricher/stock/TransformingEnricherDeprecatedTest.groovy b/core/src/test/java/org/apache/brooklyn/enricher/stock/TransformingEnricherDeprecatedTest.groovy deleted file mode 100644 index 9d4952d..0000000 --- a/core/src/test/java/org/apache/brooklyn/enricher/stock/TransformingEnricherDeprecatedTest.groovy +++ /dev/null @@ -1,83 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.apache.brooklyn.enricher.stock - -import java.util.concurrent.Callable - -import org.apache.brooklyn.api.entity.EntitySpec -import org.apache.brooklyn.api.sensor.AttributeSensor -import org.apache.brooklyn.core.test.entity.TestApplication -import org.apache.brooklyn.core.test.entity.TestEntity -import org.apache.brooklyn.enricher.stock.SensorTransformingEnricher; -import org.apache.brooklyn.core.entity.Entities -import org.apache.brooklyn.core.location.SimulatedLocation -import org.apache.brooklyn.core.sensor.BasicAttributeSensor -import org.apache.brooklyn.test.Asserts; -import org.apache.brooklyn.util.collections.MutableMap -import org.slf4j.Logger -import org.slf4j.LoggerFactory -import org.testng.Assert -import org.testng.annotations.AfterMethod -import org.testng.annotations.BeforeMethod -import org.testng.annotations.Test - -public class TransformingEnricherDeprecatedTest { - - public static final Logger log = LoggerFactory.getLogger(TransformingEnricherDeprecatedTest.class); - - private static final long TIMEOUT_MS = 10*1000; -// private static final long SHORT_WAIT_MS = 250; - - TestApplication app; - TestEntity producer; - AttributeSensor<Integer> intSensorA; - AttributeSensor<Long> target; - - @BeforeMethod() - public void before() { - app = TestApplication.Factory.newManagedInstanceForTests(); - producer = app.createAndManageChild(EntitySpec.create(TestEntity.class)); - intSensorA = new BasicAttributeSensor<Integer>(Integer.class, "int.sensor.a"); - target = new BasicAttributeSensor<Long>(Long.class, "long.sensor.target"); - - app.start(Arrays.asList(new SimulatedLocation())); - } - - @AfterMethod(alwaysRun=true) - public void after() { - if (app!=null) Entities.destroyAll(app.getManagementContext()); - } - - @Test - public void testTransformingEnricher() throws InterruptedException { - final SensorTransformingEnricher e1 = new SensorTransformingEnricher<Integer,Long>(intSensorA, target, - { 2*it }); - - producer.sensors().set(intSensorA, 3); - //ensure previous values get picked up - producer.enrichers().add(e1); - - Asserts.succeedsEventually(MutableMap.of("timeout", TIMEOUT_MS), - new Callable<Object>() { public Object call() { - Assert.assertEquals(producer.getAttribute(target), (Long)((long)6)); - return null; - }}); - - } -} http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/f69ade37/core/src/test/java/org/apache/brooklyn/enricher/stock/TransformingEnricherDeprecatedTest.java ---------------------------------------------------------------------- diff --git a/core/src/test/java/org/apache/brooklyn/enricher/stock/TransformingEnricherDeprecatedTest.java b/core/src/test/java/org/apache/brooklyn/enricher/stock/TransformingEnricherDeprecatedTest.java new file mode 100644 index 0000000..e52ff45 --- /dev/null +++ b/core/src/test/java/org/apache/brooklyn/enricher/stock/TransformingEnricherDeprecatedTest.java @@ -0,0 +1,92 @@ +/* + * 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.enricher.stock; + +import java.util.Arrays; +import java.util.concurrent.Callable; + +import org.apache.brooklyn.api.entity.EntitySpec; +import org.apache.brooklyn.api.sensor.AttributeSensor; +import org.apache.brooklyn.core.entity.Entities; +import org.apache.brooklyn.core.location.SimulatedLocation; +import org.apache.brooklyn.core.sensor.BasicAttributeSensor; +import org.apache.brooklyn.core.test.entity.TestApplication; +import org.apache.brooklyn.core.test.entity.TestEntity; +import org.apache.brooklyn.test.Asserts; +import org.apache.brooklyn.util.collections.MutableMap; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.testng.Assert; +import org.testng.annotations.AfterMethod; +import org.testng.annotations.BeforeMethod; +import org.testng.annotations.Test; + +import com.google.common.base.Function; + +@SuppressWarnings("deprecation") +public class TransformingEnricherDeprecatedTest { + + public static final Logger log = LoggerFactory.getLogger(TransformingEnricherDeprecatedTest.class); + + private static final long TIMEOUT_MS = 10*1000; +// private static final long SHORT_WAIT_MS = 250; + + TestApplication app; + TestEntity producer; + AttributeSensor<Integer> intSensorA; + AttributeSensor<Long> target; + + @BeforeMethod() + public void before() { + app = TestApplication.Factory.newManagedInstanceForTests(); + producer = app.createAndManageChild(EntitySpec.create(TestEntity.class)); + intSensorA = new BasicAttributeSensor<Integer>(Integer.class, "int.sensor.a"); + target = new BasicAttributeSensor<Long>(Long.class, "long.sensor.target"); + + app.start(Arrays.asList(new SimulatedLocation())); + } + + @AfterMethod(alwaysRun=true) + public void after() { + if (app!=null) Entities.destroyAll(app.getManagementContext()); + } + + @Test + public void testTransformingEnricher() throws InterruptedException { + final SensorTransformingEnricher<Integer, Long> e1 = new SensorTransformingEnricher<Integer,Long>(intSensorA, target, new DoubleFn()); + + producer.sensors().set(intSensorA, 3); + //ensure previous values get picked up + producer.enrichers().add(e1); + + Asserts.succeedsEventually(MutableMap.of("timeout", TIMEOUT_MS), new Callable<Object>() { + @Override + public Object call() { + Assert.assertEquals(producer.getAttribute(target), (Long)((long)6)); + return null; + }}); + } + + private static class DoubleFn implements Function<Integer, Long> { + @Override + public Long apply(Integer i) { + return ((long)i)*2; + } + } +} http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/f69ade37/core/src/test/java/org/apache/brooklyn/util/core/internal/RepeaterTest.groovy ---------------------------------------------------------------------- diff --git a/core/src/test/java/org/apache/brooklyn/util/core/internal/RepeaterTest.groovy b/core/src/test/java/org/apache/brooklyn/util/core/internal/RepeaterTest.groovy deleted file mode 100644 index 5eae3c9..0000000 --- a/core/src/test/java/org/apache/brooklyn/util/core/internal/RepeaterTest.groovy +++ /dev/null @@ -1,256 +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 org.apache.brooklyn.util.core.internal - -import static java.util.concurrent.TimeUnit.* -import static org.testng.Assert.* - -import java.util.concurrent.Callable; -import java.util.concurrent.TimeUnit - -import org.testng.annotations.Test -import org.apache.brooklyn.util.core.internal.Repeater -import org.apache.brooklyn.util.groovy.TimeExtras; -import org.apache.brooklyn.util.time.Duration; - -import com.google.common.base.Stopwatch - -public class RepeaterTest { - static { TimeExtras.init() } - - @Test - public void sanityTest() { - new Repeater("Sanity test") - .repeat() - .until { true } - .every(10 * MILLISECONDS); - } - - @Test - public void sanityTestDescription() { - new Repeater() - .repeat() - .until { true } - .every(10 * MILLISECONDS); - } - - @Test - public void sanityTestBuilder() { - Repeater.create("Sanity test") - .repeat() - .until { true } - .every(10 * MILLISECONDS); - } - - @Test - public void sanityTestBuilderDescription() { - Repeater.create() - .repeat() - .until { true } - .every(10 * MILLISECONDS); - } - - @Test(expectedExceptions = [ NullPointerException.class ]) - public void repeatFailsIfClosureIsNull() { - new Repeater("repeatFailsIfClosureIsNull").repeat((Callable<?>)null); - fail "Expected exception was not thrown" - } - - @Test - public void repeatSucceedsIfClosureIsNonNull() { - new Repeater("repeatSucceedsIfClosureIsNonNull").repeat { true }; - } - - @Test(expectedExceptions = [ NullPointerException.class ]) - public void untilFailsIfClosureIsNull() { - new Repeater("untilFailsIfClosureIsNull").until(null); - fail "Expected exception was not thrown" - } - - @Test - public void untilSucceedsIfClosureIsNonNull() { - new Repeater("untilSucceedsIfClosureIsNonNull").until { true }; - } - - @Test(expectedExceptions = [ IllegalArgumentException.class ]) - public void everyFailsIfPeriodIsZero() { - new Repeater("everyFailsIfPeriodIsZero").every(0 * MILLISECONDS); - fail "Expected exception was not thrown" - } - - @Test(expectedExceptions = [ IllegalArgumentException.class ]) - public void everyFailsIfPeriodIsNegative() { - new Repeater("everyFailsIfPeriodIsNegative").every(-1 * MILLISECONDS); - fail "Expected exception was not thrown" - } - - @Test(expectedExceptions = [ NullPointerException.class ]) - public void everyFailsIfUnitsIsNull() { - new Repeater("everyFailsIfUnitsIsNull").every(10, null); - fail "Expected exception was not thrown" - } - - @Test - public void everySucceedsIfPeriodIsPositiveAndUnitsIsNonNull() { - new Repeater("repeatSucceedsIfClosureIsNonNull").every(10 * MILLISECONDS); - } - - @Test(expectedExceptions = [ IllegalArgumentException.class ]) - public void limitTimeToFailsIfPeriodIsZero() { - new Repeater("limitTimeToFailsIfPeriodIsZero").limitTimeTo(0, TimeUnit.MILLISECONDS); - fail "Expected exception was not thrown" - } - - @Test(expectedExceptions = [ IllegalArgumentException.class ]) - public void limitTimeToFailsIfPeriodIsNegative() { - new Repeater("limitTimeToFailsIfPeriodIsNegative").limitTimeTo(-1, TimeUnit.MILLISECONDS); - fail "Expected exception was not thrown" - } - - @Test(expectedExceptions = [ NullPointerException.class ]) - public void limitTimeToFailsIfUnitsIsNull() { - new Repeater("limitTimeToFailsIfUnitsIsNull").limitTimeTo(10, null); - fail "Expected exception was not thrown" - } - - @Test - public void limitTimeToSucceedsIfPeriodIsPositiveAndUnitsIsNonNull() { - new Repeater("limitTimeToSucceedsIfClosureIsNonNull").limitTimeTo(10, TimeUnit.MILLISECONDS); - } - - @Test - public void everyAcceptsDuration() { - new Repeater("everyAcceptsDuration").every(Duration.ONE_SECOND); - } - - @Test - public void everyAcceptsLong() { - new Repeater("everyAcceptsLong").every(1000L); - } - - @Test - public void everyAcceptsTimeUnit() { - new Repeater("everyAcceptsTimeUnit").every(1000000L, TimeUnit.MICROSECONDS); - } - - @Test - public void runReturnsTrueIfExitConditionIsTrue() { - assertTrue new Repeater("runReturnsTrueIfExitConditionIsTrue") - .repeat() - .every(1 * MILLISECONDS) - .until { true } - .run(); - } - - @Test - public void runRespectsMaximumIterationLimitAndReturnsFalseIfReached() { - int iterations = 0; - assertFalse new Repeater("runRespectsMaximumIterationLimitAndReturnsFalseIfReached") - .repeat { iterations++ } - .every(1 * MILLISECONDS) - .until { false } - .limitIterationsTo(5) - .run(); - assertEquals 5, iterations; - } - - /** - * Check that the {@link Repeater} will stop after a time limit. - * - * The repeater is configured to run every 100ms and never stop until the limit is reached. - * This is given as {@link Repeater#limitTimeTo(groovy.time.Duration)} and the execution time - * is then checked to ensure it is between 100% and 400% of the specified value. Due to scheduling - * delays and other factors in a non RTOS system it is expected that the repeater will take much - * longer to exit occasionally. - * - * @see #runRespectsMaximumIterationLimitAndReturnsFalseIfReached() - */ - @Test(groups="Integration") - public void runRespectsTimeLimitAndReturnsFalseIfReached() { - final long LIMIT = 2000l; - Repeater repeater = new Repeater("runRespectsTimeLimitAndReturnsFalseIfReached") - .repeat() - .every(100 * MILLISECONDS) - .until { false } - .limitTimeTo(LIMIT, TimeUnit.MILLISECONDS); - - Stopwatch stopwatch = new Stopwatch().start(); - boolean result = repeater.run(); - stopwatch.stop(); - - assertFalse result; - - long difference = stopwatch.elapsed(TimeUnit.MILLISECONDS); - assertTrue(difference >= LIMIT, "Difference was: " + difference); - assertTrue(difference < 4 * LIMIT, "Difference was: " + difference); - } - - @Test(expectedExceptions = [ IllegalStateException.class ]) - public void runFailsIfUntilWasNotSet() { - new Repeater("runFailsIfUntilWasNotSet") - .repeat() - .every(10 * MILLISECONDS) - .run(); - fail "Expected exception was not thrown" - } - - @Test(expectedExceptions = [ IllegalStateException.class ]) - public void runFailsIfEveryWasNotSet() { - new Repeater("runFailsIfEveryWasNotSet") - .repeat() - .until { true } - .run(); - fail "Expected exception was not thrown" - } - - @Test(expectedExceptions = [ UnsupportedOperationException.class ]) - public void testRethrowsException() { - boolean result = new Repeater("throwRuntimeException") - .repeat() - .every(10 * MILLISECONDS) - .until { throw new UnsupportedOperationException("fail") } - .rethrowException() - .limitIterationsTo(2) - .run(); - fail "Expected exception was not thrown" - } - - @Test - public void testNoRethrowsException() { - try { - boolean result = new Repeater("throwRuntimeException") - .repeat() - .every(10 * MILLISECONDS) - .until { throw new UnsupportedOperationException("fail") } - .limitIterationsTo(2) - .run(); - assertFalse result - } catch (RuntimeException re) { - fail "Exception should not have been thrown: " + re.getMessage() - } - } - - public void testFlags() { - int count=0; - new Repeater(period: 5*MILLISECONDS, timeout: 100*MILLISECONDS).repeat({ count++ }).until({ count>100}).run(); - assertTrue count>10 - assertTrue count<30 - } - -} http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/f69ade37/core/src/test/java/org/apache/brooklyn/util/core/internal/RepeaterTest.java ---------------------------------------------------------------------- diff --git a/core/src/test/java/org/apache/brooklyn/util/core/internal/RepeaterTest.java b/core/src/test/java/org/apache/brooklyn/util/core/internal/RepeaterTest.java new file mode 100644 index 0000000..de26857 --- /dev/null +++ b/core/src/test/java/org/apache/brooklyn/util/core/internal/RepeaterTest.java @@ -0,0 +1,251 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.brooklyn.util.core.internal; + +import static org.testng.Assert.assertEquals; +import static org.testng.Assert.assertFalse; +import static org.testng.Assert.assertTrue; +import static org.testng.Assert.fail; + +import java.util.concurrent.Callable; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; + +import org.apache.brooklyn.util.time.Duration; +import org.testng.annotations.Test; + +import com.google.common.base.Stopwatch; +import com.google.common.collect.ImmutableMap; +import com.google.common.util.concurrent.Callables; + +@SuppressWarnings("deprecation") +public class RepeaterTest { + + @Test + public void sanityTest() { + new Repeater("Sanity test") + .repeat() + .until(Callables.returning(true)) + .every(Duration.millis(10)); + } + + @Test + public void sanityTestDescription() { + new Repeater() + .repeat() + .until(Callables.returning(true)) + .every(Duration.millis(10)); + } + + @Test + public void sanityTestBuilder() { + Repeater.create("Sanity test") + .repeat() + .until(Callables.returning(true)) + .every(Duration.millis(10)); + } + + @Test + public void sanityTestBuilderDescription() { + Repeater.create() + .repeat() + .until(Callables.returning(true)) + .every(Duration.millis(10)); + } + + @Test(expectedExceptions = NullPointerException.class) + public void repeatFailsIfClosureIsNull() { + new Repeater("repeatFailsIfClosureIsNull").repeat((Callable<?>)null); + } + + @Test + public void repeatSucceedsIfClosureIsNonNull() { + new Repeater("repeatSucceedsIfClosureIsNonNull").repeat(Callables.returning(true)); + } + + @Test(expectedExceptions = NullPointerException.class) + public void untilFailsIfClosureIsNull() { + new Repeater("untilFailsIfClosureIsNull").until(null); + } + + @Test + public void untilSucceedsIfClosureIsNonNull() { + new Repeater("untilSucceedsIfClosureIsNonNull").until(Callables.returning(true)); + } + + @Test(expectedExceptions = IllegalArgumentException.class) + public void everyFailsIfPeriodIsZero() { + new Repeater("everyFailsIfPeriodIsZero").every(Duration.ZERO); + } + + @Test(expectedExceptions = IllegalArgumentException.class) + public void everyFailsIfPeriodIsNegative() { + new Repeater("everyFailsIfPeriodIsNegative").every(Duration.millis(-1)); + } + + @Test(expectedExceptions = NullPointerException.class) + public void everyFailsIfUnitsIsNull() { + new Repeater("everyFailsIfUnitsIsNull").every(10, null); + } + + @Test + public void everySucceedsIfPeriodIsPositiveAndUnitsIsNonNull() { + new Repeater("repeatSucceedsIfClosureIsNonNull").every(Duration.millis(10)); + } + + @Test(expectedExceptions = IllegalArgumentException.class) + public void limitTimeToFailsIfPeriodIsZero() { + new Repeater("limitTimeToFailsIfPeriodIsZero").limitTimeTo(0, TimeUnit.MILLISECONDS); + } + + @Test(expectedExceptions = IllegalArgumentException.class) + public void limitTimeToFailsIfPeriodIsNegative() { + new Repeater("limitTimeToFailsIfPeriodIsNegative").limitTimeTo(-1, TimeUnit.MILLISECONDS); + } + + @Test(expectedExceptions = NullPointerException.class) + public void limitTimeToFailsIfUnitsIsNull() { + new Repeater("limitTimeToFailsIfUnitsIsNull").limitTimeTo(10, null); + } + + @Test + public void limitTimeToSucceedsIfPeriodIsPositiveAndUnitsIsNonNull() { + new Repeater("limitTimeToSucceedsIfClosureIsNonNull").limitTimeTo(10, TimeUnit.MILLISECONDS); + } + + @Test + public void everyAcceptsDuration() { + new Repeater("everyAcceptsDuration").every(Duration.ONE_SECOND); + } + + @Test + public void everyAcceptsLong() { + new Repeater("everyAcceptsLong").every(1000L); + } + + @Test + public void everyAcceptsTimeUnit() { + new Repeater("everyAcceptsTimeUnit").every(1000000L, TimeUnit.MICROSECONDS); + } + + @Test + public void runReturnsTrueIfExitConditionIsTrue() { + assertTrue(new Repeater("runReturnsTrueIfExitConditionIsTrue") + .repeat() + .every(Duration.millis(1)) + .until(Callables.returning(true)) + .run()); + } + + @Test + public void runRespectsMaximumIterationLimitAndReturnsFalseIfReached() { + final AtomicInteger iterations = new AtomicInteger(); + assertFalse(new Repeater("runRespectsMaximumIterationLimitAndReturnsFalseIfReached") + .repeat(new Runnable() {@Override public void run() {iterations.incrementAndGet();}}) + .every(Duration.millis(1)) + .until(Callables.returning(false)) + .limitIterationsTo(5) + .run()); + assertEquals(iterations.get(), 5); + } + + /** + * Check that the {@link Repeater} will stop after a time limit. + * + * The repeater is configured to run every 100ms and never stop until the limit is reached. + * This is given as {@link Repeater#limitTimeTo(groovy.time.Duration)} and the execution time + * is then checked to ensure it is between 100% and 400% of the specified value. Due to scheduling + * delays and other factors in a non RTOS system it is expected that the repeater will take much + * longer to exit occasionally. + * + * @see #runRespectsMaximumIterationLimitAndReturnsFalseIfReached() + */ + @Test(groups="Integration") + public void runRespectsTimeLimitAndReturnsFalseIfReached() { + final long LIMIT = 2000l; + Repeater repeater = new Repeater("runRespectsTimeLimitAndReturnsFalseIfReached") + .repeat() + .every(Duration.millis(100)) + .until(Callables.returning(false)) + .limitTimeTo(LIMIT, TimeUnit.MILLISECONDS); + + Stopwatch stopwatch = Stopwatch.createStarted(); + boolean result = repeater.run(); + stopwatch.stop(); + + assertFalse(result); + + long difference = stopwatch.elapsed(TimeUnit.MILLISECONDS); + assertTrue(difference >= LIMIT, "Difference was: " + difference); + assertTrue(difference < 4 * LIMIT, "Difference was: " + difference); + } + + @Test(expectedExceptions = IllegalStateException.class) + public void runFailsIfUntilWasNotSet() { + new Repeater("runFailsIfUntilWasNotSet") + .repeat() + .every(Duration.millis(10)) + .run(); + } + + @Test(expectedExceptions = IllegalStateException.class) + public void runFailsIfEveryWasNotSet() { + new Repeater("runFailsIfEveryWasNotSet") + .repeat() + .until(Callables.returning(true)) + .run(); + } + + @Test(expectedExceptions = UnsupportedOperationException.class) + public void testRethrowsException() { + new Repeater("throwRuntimeException") + .repeat() + .every(Duration.millis(10)) + .until(new Callable<Boolean>() {@Override public Boolean call() {throw new UnsupportedOperationException("fail"); }}) + .rethrowException() + .limitIterationsTo(2) + .run(); + } + + @Test + public void testNoRethrowsException() { + try { + boolean result = new Repeater("throwRuntimeException") + .repeat() + .every(Duration.millis(10)) + .until(new Callable<Boolean>() {@Override public Boolean call() {throw new UnsupportedOperationException("fail"); }}) + .limitIterationsTo(2) + .run(); + assertFalse(result); + } catch (RuntimeException re) { + fail("Exception should not have been thrown: " + re.getMessage(), re); + } + } + + public void testFlags() { + final AtomicInteger count = new AtomicInteger(); + new Repeater(ImmutableMap.of("period", Duration.millis(5), "timeout", Duration.millis(100))) + .repeat(new Runnable() {@Override public void run() {count.incrementAndGet();}}) + .until(new Callable<Boolean>() { @Override public Boolean call() {return count.get() > 0;}}) + .run(); + assertTrue(count.get()>10); + assertTrue(count.get()<30); + } + +} http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/f69ade37/examples/simple-web-cluster/src/main/java/org/apache/brooklyn/demo/WebClusterDatabaseExampleGroovy.groovy ---------------------------------------------------------------------- diff --git a/examples/simple-web-cluster/src/main/java/org/apache/brooklyn/demo/WebClusterDatabaseExampleGroovy.groovy b/examples/simple-web-cluster/src/main/java/org/apache/brooklyn/demo/WebClusterDatabaseExampleGroovy.groovy deleted file mode 100644 index c1156b1..0000000 --- a/examples/simple-web-cluster/src/main/java/org/apache/brooklyn/demo/WebClusterDatabaseExampleGroovy.groovy +++ /dev/null @@ -1,92 +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 org.apache.brooklyn.demo; - -import static org.apache.brooklyn.entity.java.JavaEntityMethods.javaSysProp -import static org.apache.brooklyn.core.sensor.DependentConfiguration.attributeWhenReady -import static org.apache.brooklyn.core.sensor.DependentConfiguration.formatString - -import org.apache.brooklyn.api.entity.EntitySpec -import org.apache.brooklyn.core.entity.AbstractApplication -import org.apache.brooklyn.core.entity.Entities -import org.apache.brooklyn.entity.database.mysql.MySqlNode -import org.apache.brooklyn.entity.webapp.ControlledDynamicWebAppCluster -import org.apache.brooklyn.entity.webapp.DynamicWebAppCluster -import org.apache.brooklyn.launcher.BrooklynLauncher -import org.apache.brooklyn.policy.autoscaling.AutoScalerPolicy -import org.apache.brooklyn.util.CommandLineUtil -import org.slf4j.Logger -import org.slf4j.LoggerFactory - -import com.google.common.collect.Lists - -/** - * Launches a 3-tier app with nginx, clustered jboss, and mysql. - * <p> - * This variant of {@link WebClusterDatabaseExample} demonstrates <i>Groovy</i> language conveniences. - **/ -public class WebClusterDatabaseExampleGroovy extends AbstractApplication { - - public static final Logger LOG = LoggerFactory.getLogger(WebClusterDatabaseExampleGroovy.class); - - public static final String DEFAULT_LOCATION = "localhost"; - - public static final String WAR_PATH = "classpath://hello-world-sql-webapp.war"; - - public static final String DB_SETUP_SQL_URL = "classpath://visitors-creation-script.sql"; - - public static final String DB_TABLE = "visitors"; - public static final String DB_USERNAME = "brooklyn"; - public static final String DB_PASSWORD = "br00k11n"; - - @Override - public void initApp() { - MySqlNode mysql = addChild(MySqlNode, - creationScriptUrl: DB_SETUP_SQL_URL); - - ControlledDynamicWebAppCluster web = addChild(ControlledDynamicWebAppCluster, - war: WAR_PATH, - httpPort: "8080+", - (javaSysProp("brooklyn.example.db.url")): - formatString("jdbc:%s%s?user=%s\\&password=%s", - attributeWhenReady(mysql, MySqlNode.DATASTORE_URL), - DB_TABLE, DB_USERNAME, DB_PASSWORD)); - - web.getCluster().policies().add(AutoScalerPolicy.builder(). - metric(DynamicWebAppCluster.REQUESTS_PER_SECOND_LAST_PER_NODE). - sizeRange(1, 5). - metricRange(10, 100). - build()); - } - - public static void main(String[] argv) { - List<String> args = Lists.newArrayList(argv); - String port = CommandLineUtil.getCommandLineOption(args, "--port", "8081+"); - String location = CommandLineUtil.getCommandLineOption(args, "--location", DEFAULT_LOCATION); - - BrooklynLauncher launcher = BrooklynLauncher.newInstance() - .application(EntitySpec.create(WebClusterDatabaseExampleGroovy.class).displayName("Brooklyn WebApp Cluster with Database example")) - .webconsolePort(port) - .location(location) - .start(); - - Entities.dumpInfo(launcher.getApplications()); - } - -} http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/f69ade37/locations/jclouds/pom.xml ---------------------------------------------------------------------- diff --git a/locations/jclouds/pom.xml b/locations/jclouds/pom.xml index ed10132..3338893 100644 --- a/locations/jclouds/pom.xml +++ b/locations/jclouds/pom.xml @@ -85,10 +85,6 @@ <artifactId>httpclient</artifactId> </dependency> <dependency> - <groupId>org.codehaus.groovy</groupId> - <artifactId>groovy-all</artifactId> - </dependency> - <dependency> <groupId>javax.annotation</groupId> <artifactId>jsr250-api</artifactId> </dependency> @@ -199,21 +195,4 @@ <scope>test</scope> </dependency> </dependencies> - - <build> - <plugins> - <plugin> - <artifactId>maven-compiler-plugin</artifactId> - <inherited>true</inherited> - <executions> - <execution> - <id>default-testCompile</id> - <configuration> - <compilerId>groovy-eclipse-compiler</compilerId> - </configuration> - </execution> - </executions> - </plugin> - </plugins> - </build> </project> http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/f69ade37/locations/jclouds/src/test/java/org/apache/brooklyn/location/jclouds/provider/AwsEc2LocationWindowsLiveTest.groovy ---------------------------------------------------------------------- diff --git a/locations/jclouds/src/test/java/org/apache/brooklyn/location/jclouds/provider/AwsEc2LocationWindowsLiveTest.groovy b/locations/jclouds/src/test/java/org/apache/brooklyn/location/jclouds/provider/AwsEc2LocationWindowsLiveTest.groovy deleted file mode 100644 index 6a04784..0000000 --- a/locations/jclouds/src/test/java/org/apache/brooklyn/location/jclouds/provider/AwsEc2LocationWindowsLiveTest.groovy +++ /dev/null @@ -1,94 +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 org.apache.brooklyn.location.jclouds.provider; - -import static org.testng.Assert.* - -import org.apache.brooklyn.api.mgmt.ManagementContext -import org.apache.brooklyn.core.entity.Entities -import org.apache.brooklyn.location.jclouds.JcloudsLocation -import org.apache.brooklyn.location.jclouds.JcloudsSshMachineLocation -import org.apache.brooklyn.location.ssh.SshMachineLocation; -import org.slf4j.Logger -import org.slf4j.LoggerFactory -import org.testng.annotations.AfterMethod -import org.testng.annotations.BeforeMethod -import org.testng.annotations.Test - -import com.google.common.collect.ImmutableMap - -public class AwsEc2LocationWindowsLiveTest { - private static final Logger LOG = LoggerFactory.getLogger(AwsEc2LocationWindowsLiveTest.class) - - private static final String PROVIDER = "aws-ec2" - private static final String EUWEST_REGION_NAME = "eu-west-1" - private static final String EUWEST_IMAGE_ID = EUWEST_REGION_NAME+"/"+"ami-7f0c260b";//"ami-41d3d635" - private static final String LOCATION_ID = "jclouds:"+PROVIDER+":"+EUWEST_REGION_NAME; - - protected JcloudsLocation loc; - protected Collection<SshMachineLocation> machines = [] - protected ManagementContext ctx; - - @BeforeMethod(groups = "Live") - public void setUp() { - ctx = Entities.newManagementContext(ImmutableMap.of("provider", PROVIDER)); - - loc = ctx.locationRegistry.resolve LOCATION_ID - } - - @AfterMethod(groups = "Live") - public void tearDown() { - List<Exception> exceptions = [] - machines.each { - try { - loc?.release(it) - } catch (Exception e) { - LOG.warn("Error releasing machine $it; continuing...", e) - exceptions.add(e) - } - } - if (exceptions) { - throw exceptions.get(0) - } - machines.clear() - } - - // TODO Note careful choice of image due to jclouds 1.4 issue 886 - // TODO Blocks for long time, waiting for IP:22 to be reachable, before falling back to using public IP - // 10*2 minutes per attempt in jclouds 1.4 because done sequentially, and done twice by us so test takes 40 minutes! - @Test(enabled=true, groups = [ "Live" ]) - public void testProvisionWindowsVm() { - JcloudsSshMachineLocation machine = obtainMachine([ imageId:EUWEST_IMAGE_ID ]); - - LOG.info("Provisioned Windows VM {}; checking if has password", machine) - assertNotNull(machine.waitForPassword()) - } - - // Use this utility method to ensure machines are released on tearDown - protected SshMachineLocation obtainMachine(Map flags) { - SshMachineLocation result = loc.obtain(flags) - machines.add(result) - return result - } - - protected SshMachineLocation release(SshMachineLocation machine) { - machines.remove(machine) - loc.release(machine) - } -} http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/f69ade37/locations/jclouds/src/test/java/org/apache/brooklyn/location/jclouds/provider/AwsEc2LocationWindowsLiveTest.java ---------------------------------------------------------------------- diff --git a/locations/jclouds/src/test/java/org/apache/brooklyn/location/jclouds/provider/AwsEc2LocationWindowsLiveTest.java b/locations/jclouds/src/test/java/org/apache/brooklyn/location/jclouds/provider/AwsEc2LocationWindowsLiveTest.java new file mode 100644 index 0000000..7c3618c --- /dev/null +++ b/locations/jclouds/src/test/java/org/apache/brooklyn/location/jclouds/provider/AwsEc2LocationWindowsLiveTest.java @@ -0,0 +1,95 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.brooklyn.location.jclouds.provider; + +import static org.testng.Assert.assertNotNull; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; +import java.util.Map; + +import org.apache.brooklyn.api.location.NoMachinesAvailableException; +import org.apache.brooklyn.api.mgmt.ManagementContext; +import org.apache.brooklyn.core.entity.Entities; +import org.apache.brooklyn.location.jclouds.JcloudsLocation; +import org.apache.brooklyn.location.jclouds.JcloudsSshMachineLocation; +import org.apache.brooklyn.location.ssh.SshMachineLocation; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.testng.annotations.AfterMethod; +import org.testng.annotations.BeforeMethod; +import org.testng.annotations.Test; + +import com.google.common.collect.ImmutableMap; + +public class AwsEc2LocationWindowsLiveTest { + private static final Logger LOG = LoggerFactory.getLogger(AwsEc2LocationWindowsLiveTest.class); + + private static final String PROVIDER = "aws-ec2"; + private static final String EUWEST_REGION_NAME = "eu-west-1"; + private static final String EUWEST_IMAGE_ID = EUWEST_REGION_NAME+"/"+"ami-7f0c260b";//"ami-41d3d635" + private static final String LOCATION_ID = "jclouds:"+PROVIDER+":"+EUWEST_REGION_NAME; + + protected JcloudsLocation loc; + protected Collection<SshMachineLocation> machines = new ArrayList<SshMachineLocation>(); + protected ManagementContext ctx; + + @BeforeMethod(groups = "Live") + public void setUp() { + ctx = Entities.newManagementContext(ImmutableMap.of("provider", PROVIDER)); + + loc = (JcloudsLocation) ctx.getLocationRegistry().resolve(LOCATION_ID); + } + + @AfterMethod(groups = "Live") + public void tearDown() throws Exception { + List<Exception> exceptions = new ArrayList<Exception>(); + for (SshMachineLocation machine : machines) { + try { + loc.release(machine); + } catch (Exception e) { + LOG.warn("Error releasing machine $it; continuing...", e); + exceptions.add(e); + } + } + if (!exceptions.isEmpty()) { + throw exceptions.get(0); + } + machines.clear(); + } + + // TODO Note careful choice of image due to jclouds 1.4 issue 886 + // TODO Blocks for long time, waiting for IP:22 to be reachable, before falling back to using public IP + // 10*2 minutes per attempt in jclouds 1.4 because done sequentially, and done twice by us so test takes 40 minutes! + @Test(enabled=true, groups = "Live") + public void testProvisionWindowsVm() throws NoMachinesAvailableException { + JcloudsSshMachineLocation machine = (JcloudsSshMachineLocation) obtainMachine(ImmutableMap.of("imageId", EUWEST_IMAGE_ID)); + + LOG.info("Provisioned Windows VM {}; checking if has password", machine); + assertNotNull(machine.waitForPassword()); + } + + // Use this utility method to ensure machines are released on tearDown + protected SshMachineLocation obtainMachine(Map<?, ?> flags) throws NoMachinesAvailableException { + JcloudsSshMachineLocation result = (JcloudsSshMachineLocation) loc.obtain(flags); + machines.add(result); + return result; + } +} http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/f69ade37/locations/jclouds/src/test/java/org/apache/brooklyn/location/jclouds/provider/CarrenzaLocationLiveTest.groovy ---------------------------------------------------------------------- diff --git a/locations/jclouds/src/test/java/org/apache/brooklyn/location/jclouds/provider/CarrenzaLocationLiveTest.groovy b/locations/jclouds/src/test/java/org/apache/brooklyn/location/jclouds/provider/CarrenzaLocationLiveTest.groovy deleted file mode 100644 index 0c2197f..0000000 --- a/locations/jclouds/src/test/java/org/apache/brooklyn/location/jclouds/provider/CarrenzaLocationLiveTest.groovy +++ /dev/null @@ -1,132 +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 org.apache.brooklyn.location.jclouds.provider; - -import static org.testng.Assert.* - -import org.apache.brooklyn.core.internal.BrooklynProperties -import org.apache.brooklyn.core.mgmt.internal.LocalManagementContext -import org.apache.brooklyn.location.jclouds.JcloudsLocation -import org.apache.brooklyn.location.jclouds.JcloudsSshMachineLocation -import org.apache.brooklyn.location.ssh.SshMachineLocation; -import org.apache.brooklyn.util.collections.MutableMap -import org.slf4j.Logger -import org.slf4j.LoggerFactory -import org.testng.annotations.AfterMethod -import org.testng.annotations.BeforeMethod -import org.testng.annotations.Test - -import com.google.common.collect.ImmutableList - -/** - * Tests vcloud, with Carrenza. Uses the cloudsoft test account (hard-coding its NAT Mapping, - * and one of its private vApp templates). Note that the template is for a Windows 2008 - * machine with winsshd installed. - * - * TODO Will only work with >= jclouds 1.5, due to jclouds issues 994 and 995. Therefore it - * will not work in brooklyn 0.4.0-M2 etc. - */ -class CarrenzaLocationLiveTest { - private static final Logger LOG = LoggerFactory.getLogger(CarrenzaLocationLiveTest.class) - - private static final String PROVIDER = "vcloud" - private static final String ENDPOINT = "https://myvdc.carrenza.net/api" - private static final String LOCATION_ID = "jclouds:"+PROVIDER+":"+ENDPOINT; - private static final String WINDOWS_IMAGE_ID = "https://myvdc.carrenza.net/api/v1.0/vAppTemplate/vappTemplate-2bd5b0ff-ecd9-405e-8306-2f4f6c092a1b" - - private BrooklynProperties brooklynProperties; - private LocalManagementContext managementContext; - private JcloudsLocation loc; - private Collection<SshMachineLocation> machines = [] - - // TODO Has not been tested since updating ot remove use of deleted LocationRegistry! - @BeforeMethod(groups = "Live") - public void setUp() { - System.out.println("classpath="+System.getProperty("java.class.path")); - - brooklynProperties = BrooklynProperties.Factory.newDefault(); - brooklynProperties.remove("brooklyn.jclouds."+PROVIDER+".image-description-regex"); - brooklynProperties.remove("brooklyn.jclouds."+PROVIDER+".image-name-regex"); - brooklynProperties.remove("brooklyn.jclouds."+PROVIDER+".image-id"); - brooklynProperties.remove("brooklyn.jclouds."+PROVIDER+".inboundPorts"); - brooklynProperties.remove("brooklyn.jclouds."+PROVIDER+".hardware-id"); - - // Also removes scriptHeader (e.g. if doing `. ~/.bashrc` and `. ~/.profile`, then that can cause "stdin: is not a tty") - brooklynProperties.remove("brooklyn.ssh.config.scriptHeader"); - - brooklynProperties.put("brooklyn.jclouds."+PROVIDER+".jclouds.endpoint", ENDPOINT) - brooklynProperties.put("brooklyn.jclouds."+PROVIDER+".imageId", WINDOWS_IMAGE_ID) - brooklynProperties.put("brooklyn.jclouds."+PROVIDER+".noDefaultSshKeys", true) - brooklynProperties.put("brooklyn.jclouds."+PROVIDER+".userName", "Administrator") - brooklynProperties.put("brooklyn.jclouds."+PROVIDER+".dontCreateUser", true) - brooklynProperties.put("brooklyn.jclouds."+PROVIDER+".overrideLoginUser", "Administrator") - brooklynProperties.put("brooklyn.jclouds."+PROVIDER+".waitForSshable", false) - brooklynProperties.put("brooklyn.jclouds."+PROVIDER+".runAsRoot", false) - brooklynProperties.put("brooklyn.jclouds."+PROVIDER+".inboundPorts", [22, 3389]) - brooklynProperties.put("brooklyn.jclouds."+PROVIDER+".natMapping", [("192.168.0.100"):"195.3.186.200", ("192.168.0.101"):"195.3.186.42"]) - - managementContext = new LocalManagementContext(brooklynProperties); - loc = (JcloudsLocation) managementContext.getLocationRegistry().resolve(LOCATION_ID); - } - - @AfterMethod(groups = "Live") - public void tearDown() { - List<Exception> exceptions = [] - machines.each { - try { - loc?.release(it) - } catch (Exception e) { - LOG.warn("Error releasing machine $it; continuing...", e) - exceptions.add(e) - } - } - if (exceptions) { - throw exceptions.get(0) - } - machines.clear() - } - - // FIXME Disabled because of jclouds issues #994 and #995 (fixed in jclouds 1.5, so not in brooklyn 0.4.0-M2 etc) - // Note the careful settings in setUp (e.g. so don't try to install ssh-keys etc - // Also, the windows image used has winsshd installed - @Test(enabled=false, groups = [ "Live" ]) - public void testProvisionWindowsVm() { - JcloudsSshMachineLocation machine = obtainMachine(MutableMap.of( - "imageId", WINDOWS_IMAGE_ID)); - - LOG.info("Provisioned Windows VM {}; checking if has password", machine) - String password = machine.waitForPassword(); - assertNotNull(password); - - LOG.info("Checking can ssh to windows machine {} using password {}", machine, password); - assertEquals(machine.execCommands(MutableMap.of("password", password), "check-reachable", ImmutableList.of("hostname")), 0); - } - - // Use this utility method to ensure machines are released on tearDown - protected SshMachineLocation obtainMachine(Map flags) { - SshMachineLocation result = loc.obtain(flags) - machines.add(result) - return result - } - - protected SshMachineLocation release(SshMachineLocation machine) { - machines.remove(machine) - loc.release(machine) - } -}
