http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/test/java/brooklyn/entity/software/MachineLifecycleEffectorTasksTest.java ---------------------------------------------------------------------- diff --git a/software/base/src/test/java/brooklyn/entity/software/MachineLifecycleEffectorTasksTest.java b/software/base/src/test/java/brooklyn/entity/software/MachineLifecycleEffectorTasksTest.java deleted file mode 100644 index d746c60..0000000 --- a/software/base/src/test/java/brooklyn/entity/software/MachineLifecycleEffectorTasksTest.java +++ /dev/null @@ -1,140 +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.entity.software; - -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertFalse; -import static org.testng.Assert.assertTrue; - -import java.util.List; - -import org.apache.brooklyn.api.entity.Entity; -import org.apache.brooklyn.api.entity.EntitySpec; -import org.apache.brooklyn.api.internal.EntityLocal; -import org.apache.brooklyn.api.mgmt.Task; -import org.apache.brooklyn.api.sensor.AttributeSensor; -import org.apache.brooklyn.core.mgmt.BrooklynTaskTags; -import org.apache.brooklyn.core.test.entity.TestApplication; -import org.apache.brooklyn.entity.core.BrooklynConfigKeys; -import org.apache.brooklyn.entity.core.Entities; -import org.apache.brooklyn.entity.lifecycle.Lifecycle; -import org.apache.brooklyn.entity.stock.BasicEntity; -import org.apache.brooklyn.entity.stock.BasicEntityImpl; -import org.apache.brooklyn.entity.trait.Startable; -import org.apache.brooklyn.sensor.core.DependentConfiguration; -import org.apache.brooklyn.sensor.core.Sensors; -import org.apache.brooklyn.test.Asserts; -import org.apache.brooklyn.util.core.task.TaskInternal; -import org.apache.brooklyn.util.time.Duration; -import org.testng.annotations.DataProvider; -import org.testng.annotations.Test; - -import com.google.common.collect.ImmutableList; -import com.google.common.collect.ImmutableMap; -import com.google.common.collect.Iterables; -import com.google.common.collect.Lists; - -import brooklyn.entity.basic.EmptySoftwareProcess; -import brooklyn.entity.basic.SoftwareProcess; -import brooklyn.entity.basic.SoftwareProcess.StopSoftwareParameters.StopMode; - -import org.apache.brooklyn.location.jclouds.BailOutJcloudsLocation; - -public class MachineLifecycleEffectorTasksTest { - public static boolean canStop(StopMode stopMode, boolean isEntityStopped) { - BasicEntityImpl entity = new BasicEntityImpl(); - Lifecycle state = isEntityStopped ? Lifecycle.STOPPED : Lifecycle.RUNNING; - entity.setAttribute(SoftwareProcess.SERVICE_STATE_ACTUAL, state); - return MachineLifecycleEffectorTasks.canStop(stopMode, entity); - } - - @DataProvider(name = "canStopStates") - public Object[][] canStopStates() { - return new Object[][] { - { StopMode.ALWAYS, true, true }, - { StopMode.ALWAYS, false, true }, - { StopMode.IF_NOT_STOPPED, true, false }, - { StopMode.IF_NOT_STOPPED, false, true }, - { StopMode.NEVER, true, false }, - { StopMode.NEVER, false, false }, - }; - } - - @Test(dataProvider = "canStopStates") - public void testBasicSonftwareProcessCanStop(StopMode mode, boolean isEntityStopped, boolean expected) { - boolean canStop = canStop(mode, isEntityStopped); - assertEquals(canStop, expected); - } - - @Test - public void testProvisionLatchObeyed() throws Exception { - - AttributeSensor<Boolean> ready = Sensors.newBooleanSensor("readiness"); - - TestApplication app = TestApplication.Factory.newManagedInstanceForTests(); - BasicEntity triggerEntity = app.createAndManageChild(EntitySpec.create(BasicEntity.class)); - - EmptySoftwareProcess entity = app.createAndManageChild(EntitySpec.create(EmptySoftwareProcess.class) - .configure(BrooklynConfigKeys.PROVISION_LATCH, DependentConfiguration.attributeWhenReady(triggerEntity, ready))); - - final Task<Void> task = Entities.invokeEffector(app, app, Startable.START, ImmutableMap.of( - "locations", ImmutableList.of(BailOutJcloudsLocation.newBailOutJcloudsLocation(app.getManagementContext())))); - - assertEffectorBlockingDetailsEventually(entity, "Waiting for config " + BrooklynConfigKeys.PROVISION_LATCH.getName()); - - Asserts.succeedsContinually(new Runnable() { - @Override - public void run() { - assertFalse(task.isDone()); - } - }); - try { - ((EntityLocal) triggerEntity).setAttribute(ready, true); - task.get(Duration.THIRTY_SECONDS); - } catch (Throwable t) { - // BailOut location throws but we don't care. - } finally { - Entities.destroyAll(app.getManagementContext()); - } - } - - private void assertEffectorBlockingDetailsEventually(final Entity entity, final String blockingDetailsSnippet) { - Asserts.succeedsEventually(new Runnable() { - @Override public void run() { - Task<?> entityTask = Iterables.getOnlyElement(entity.getApplication().getManagementContext().getExecutionManager().getTasksWithAllTags( - ImmutableList.of(BrooklynTaskTags.EFFECTOR_TAG, BrooklynTaskTags.tagForContextEntity(entity)))); - String blockingDetails = getBlockingDetails(entityTask); - assertTrue(blockingDetails.contains(blockingDetailsSnippet)); - }}); - } - - private String getBlockingDetails(Task<?> task) { - List<TaskInternal<?>> taskChain = Lists.newArrayList(); - TaskInternal<?> taskI = (TaskInternal<?>) task; - while (taskI != null) { - taskChain.add(taskI); - if (taskI.getBlockingDetails() != null) { - return taskI.getBlockingDetails(); - } - taskI = (TaskInternal<?>) taskI.getBlockingTask(); - } - throw new IllegalStateException("No blocking details for "+task+" (walked task chain "+taskChain+")"); - } - -}
http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/test/java/brooklyn/entity/software/SoftwareEffectorTest.java ---------------------------------------------------------------------- diff --git a/software/base/src/test/java/brooklyn/entity/software/SoftwareEffectorTest.java b/software/base/src/test/java/brooklyn/entity/software/SoftwareEffectorTest.java deleted file mode 100644 index 4c11b4d..0000000 --- a/software/base/src/test/java/brooklyn/entity/software/SoftwareEffectorTest.java +++ /dev/null @@ -1,142 +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.entity.software; - -import java.util.Arrays; - -import org.apache.brooklyn.api.effector.Effector; -import org.apache.brooklyn.api.location.LocationSpec; -import org.apache.brooklyn.api.mgmt.ManagementContext; -import org.apache.brooklyn.api.mgmt.Task; -import org.apache.brooklyn.core.test.entity.TestApplication; -import org.apache.brooklyn.effector.core.Effectors; -import org.apache.brooklyn.entity.core.Entities; -import org.apache.brooklyn.util.core.config.ConfigBag; -import org.apache.brooklyn.util.core.task.system.ProcessTaskWrapper; -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 brooklyn.entity.software.SshEffectorTasks.SshEffectorBody; - -import org.apache.brooklyn.location.basic.LocalhostMachineProvisioningLocation; -import org.apache.brooklyn.location.basic.SshMachineLocation; - -import com.google.common.base.Throwables; - -public class SoftwareEffectorTest { - - private static final Logger log = LoggerFactory.getLogger(SoftwareEffectorTest.class); - - TestApplication app; - ManagementContext mgmt; - - @BeforeMethod(alwaysRun=true) - public void setup() throws Exception { - app = TestApplication.Factory.newManagedInstanceForTests(); - mgmt = app.getManagementContext(); - - LocalhostMachineProvisioningLocation lhc = mgmt.getLocationManager().createLocation(LocationSpec.create(LocalhostMachineProvisioningLocation.class)); - SshMachineLocation lh = lhc.obtain(); - app.start(Arrays.asList(lh)); - } - - @AfterMethod(alwaysRun=true) - public void tearDown() throws Exception { - if (mgmt != null) Entities.destroyAll(mgmt); - mgmt = null; - } - - public static final Effector<String> GET_REMOTE_DATE_1 = Effectors.effector(String.class, "getRemoteDate") - .description("retrieves the date from the remote machine") - .impl(new SshEffectorBody<String>() { - public String call(ConfigBag parameters) { - queue( ssh("date").requiringZeroAndReturningStdout() ); - return last(String.class); - } - }) - .build(); - - public static final Effector<String> GET_REMOTE_DATE_2 = Effectors.effector(GET_REMOTE_DATE_1) - // Just get year to confirm implementation is different - .description("retrieves the year from the remote machine") - .impl(SshEffectorTasks.ssh("date +%Y").requiringZeroAndReturningStdout()) - .build(); - - // TODO revisit next two tests before end 2019 ;) - - @Test(groups="Integration") - public void testSshDateEffector1() { - Task<String> call = Entities.invokeEffector(app, app, GET_REMOTE_DATE_1); - log.info("ssh date 1 gives: "+call.getUnchecked()); - Assert.assertTrue(call.getUnchecked().indexOf("201") > 0); - } - - @Test(groups="Integration") - public void testSshDateEffector2() { - Task<String> call = Entities.invokeEffector(app, app, GET_REMOTE_DATE_2); - log.info("ssh date 2 gives: "+call.getUnchecked()); - Assert.assertTrue(call.getUnchecked().indexOf("201") == 0); - } - - public static final String COMMAND_THAT_DOES_NOT_EXIST = "blah_blah_blah_command_DOES_NOT_EXIST"; - - @Test(groups="Integration") - public void testBadExitCodeCaught() { - Task<Void> call = Entities.invokeEffector(app, app, Effectors.effector(Void.class, "badExitCode") - .impl(new SshEffectorBody<Void>() { - public Void call(ConfigBag parameters) { - queue( ssh(COMMAND_THAT_DOES_NOT_EXIST).requiringZeroAndReturningStdout() ); - return null; - } - }).build() ); - try { - Object result = call.getUnchecked(); - Assert.fail("ERROR: should have failed earlier in this test, instead got successful task result "+result+" from "+call); - } catch (Exception e) { - Throwable root = Throwables.getRootCause(e); - if (!(root instanceof IllegalStateException)) Assert.fail("Should have failed with IAE, but got: "+root); - if (root.getMessage()==null || root.getMessage().indexOf("exit code")<=0) - Assert.fail("Should have failed with 'exit code' message, but got: "+root); - // test passed - return; - } - } - - @Test(groups="Integration") - public void testBadExitCodeCaughtAndStdErrAvailable() { - final ProcessTaskWrapper<?>[] sshTasks = new ProcessTaskWrapper[1]; - - Task<Void> call = Entities.invokeEffector(app, app, Effectors.effector(Void.class, "badExitCode") - .impl(new SshEffectorBody<Void>() { - public Void call(ConfigBag parameters) { - sshTasks[0] = queue( ssh(COMMAND_THAT_DOES_NOT_EXIST).requiringExitCodeZero() ); - return null; - } - }).build() ); - call.blockUntilEnded(); - Assert.assertTrue(call.isError()); - log.info("stderr gives: "+new String(sshTasks[0].getStderr())); - Assert.assertTrue(new String(sshTasks[0].getStderr()).indexOf(COMMAND_THAT_DOES_NOT_EXIST) >= 0); - } - -} http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/test/java/brooklyn/entity/software/SshEffectorTasksTest.java ---------------------------------------------------------------------- diff --git a/software/base/src/test/java/brooklyn/entity/software/SshEffectorTasksTest.java b/software/base/src/test/java/brooklyn/entity/software/SshEffectorTasksTest.java deleted file mode 100644 index c076e56..0000000 --- a/software/base/src/test/java/brooklyn/entity/software/SshEffectorTasksTest.java +++ /dev/null @@ -1,263 +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.entity.software; - -import java.io.File; -import java.io.IOException; -import java.util.Arrays; - -import org.apache.brooklyn.api.location.LocationSpec; -import org.apache.brooklyn.api.mgmt.ManagementContext; -import org.apache.brooklyn.api.mgmt.TaskAdaptable; -import org.apache.brooklyn.api.mgmt.TaskFactory; -import org.apache.brooklyn.core.test.entity.TestApplication; -import org.apache.brooklyn.entity.core.Entities; -import org.apache.brooklyn.util.core.task.ssh.SshFetchTaskWrapper; -import org.apache.brooklyn.util.core.task.ssh.SshPutTaskWrapper; -import org.apache.brooklyn.util.core.task.system.ProcessTaskWrapper; -import org.apache.brooklyn.util.exceptions.PropagatedRuntimeException; -import org.apache.brooklyn.util.net.Urls; -import org.apache.commons.io.FileUtils; -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 org.apache.brooklyn.location.basic.LocalhostMachineProvisioningLocation; -import org.apache.brooklyn.location.basic.SshMachineLocation; - -import com.google.common.io.Files; - -public class SshEffectorTasksTest { - - private static final Logger log = LoggerFactory.getLogger(SshEffectorTasksTest.class); - - TestApplication app; - ManagementContext mgmt; - SshMachineLocation host; - File tempDir; - - boolean failureExpected; - - @BeforeMethod(alwaysRun=true) - public void setup() throws Exception { - app = TestApplication.Factory.newManagedInstanceForTests(); - mgmt = app.getManagementContext(); - - LocalhostMachineProvisioningLocation lhc = mgmt.getLocationManager().createLocation(LocationSpec.create(LocalhostMachineProvisioningLocation.class)); - host = lhc.obtain(); - app.start(Arrays.asList(host)); - clearExpectedFailure(); - tempDir = Files.createTempDir(); - } - - @AfterMethod(alwaysRun=true) - public void tearDown() throws Exception { - if (mgmt != null) Entities.destroyAll(mgmt); - mgmt = null; - FileUtils.deleteDirectory(tempDir); - 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; - } - - public <T extends TaskAdaptable<?>> T submit(final TaskFactory<T> taskFactory) { - return Entities.submit(app, taskFactory); - } - - // ------------------- basic ssh - - @Test(groups="Integration") - public void testSshEchoHello() { - ProcessTaskWrapper<Integer> t = submit(SshEffectorTasks.ssh("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"); - } - - @Test(groups="Integration") - public void testSshPut() throws IOException { - String fn = Urls.mergePaths(tempDir.getPath(), "f1"); - SshPutTaskWrapper t = submit(SshEffectorTasks.put(fn).contents("hello world")); - t.block(); - Assert.assertEquals(FileUtils.readFileToString(new File(fn)), "hello world"); - // and make sure this doesn't throw - Assert.assertTrue(t.isDone()); - Assert.assertTrue(t.isSuccessful()); - Assert.assertEquals(t.get(), null); - Assert.assertEquals(t.getExitCode(), (Integer)0); - } - - @Test(groups="Integration") - public void testSshFetch() throws IOException { - String fn = Urls.mergePaths(tempDir.getPath(), "f2"); - FileUtils.write(new File(fn), "hello fetched world"); - - SshFetchTaskWrapper t = submit(SshEffectorTasks.fetch(fn)); - t.block(); - - Assert.assertTrue(t.isDone()); - Assert.assertEquals(t.get(), "hello fetched world"); - } - - // ----------------- pid stuff - - @Test(groups="Integration") - public void testNonRunningPid() { - ProcessTaskWrapper<Integer> t = submit(SshEffectorTasks.codePidRunning(99999)); - Assert.assertNotEquals(t.getTask().getUnchecked(), (Integer)0); - Assert.assertNotEquals(t.getExitCode(), (Integer)0); - ProcessTaskWrapper<Boolean> t2 = submit(SshEffectorTasks.isPidRunning(99999)); - Assert.assertFalse(t2.getTask().getUnchecked()); - } - - @Test(groups="Integration") - public void testNonRunningPidRequired() { - ProcessTaskWrapper<?> t = submit(SshEffectorTasks.requirePidRunning(99999)); - setExpectingFailure(); - try { - t.getTask().getUnchecked(); - } catch (Exception e) { - log.info("The error if required PID is not found is: "+e); - clearExpectedFailure(); - Assert.assertTrue(e.toString().contains("Process with PID"), "Expected nice clue in error but got: "+e); - } - checkExpectedFailure(); - } - - public static Integer getMyPid() { - try { - java.lang.management.RuntimeMXBean runtime = - java.lang.management.ManagementFactory.getRuntimeMXBean(); - java.lang.reflect.Field jvm = runtime.getClass().getDeclaredField("jvm"); - jvm.setAccessible(true); -// sun.management.VMManagement mgmt = (sun.management.VMManagement) jvm.get(runtime); - Object mgmt = jvm.get(runtime); - java.lang.reflect.Method pid_method = - mgmt.getClass().getDeclaredMethod("getProcessId"); - pid_method.setAccessible(true); - - return (Integer) pid_method.invoke(mgmt); - } catch (Exception e) { - throw new PropagatedRuntimeException("Test depends on (fragile) getMyPid method which does not work here", e); - } - } - - @Test(groups="Integration") - public void testRunningPid() { - ProcessTaskWrapper<Integer> t = submit(SshEffectorTasks.codePidRunning(getMyPid())); - Assert.assertEquals(t.getTask().getUnchecked(), (Integer)0); - ProcessTaskWrapper<Boolean> t2 = submit(SshEffectorTasks.isPidRunning(getMyPid())); - Assert.assertTrue(t2.getTask().getUnchecked()); - } - - @Test(groups="Integration") - public void testRunningPidFromFile() throws IOException { - File f = File.createTempFile("testBrooklynPid", ".pid"); - Files.write( (""+getMyPid()).getBytes(), f ); - ProcessTaskWrapper<Integer> t = submit(SshEffectorTasks.codePidFromFileRunning(f.getPath())); - Assert.assertEquals(t.getTask().getUnchecked(), (Integer)0); - ProcessTaskWrapper<Boolean> t2 = submit(SshEffectorTasks.isPidFromFileRunning(f.getPath())); - Assert.assertTrue(t2.getTask().getUnchecked()); - } - - @Test(groups="Integration") - public void testRequirePidFromFileOnFailure() throws IOException { - File f = File.createTempFile("testBrooklynPid", ".pid"); - Files.write( "99999".getBytes(), f ); - ProcessTaskWrapper<?> t = submit(SshEffectorTasks.requirePidFromFileRunning(f.getPath())); - - setExpectingFailure(); - try { - t.getTask().getUnchecked(); - } catch (Exception e) { - log.info("The error if required PID is not found is: "+e); - clearExpectedFailure(); - Assert.assertTrue(e.toString().contains("Process with PID"), "Expected nice clue in error but got: "+e); - Assert.assertEquals(t.getExitCode(), (Integer)1); - } - checkExpectedFailure(); - } - - @Test(groups="Integration") - public void testRequirePidFromFileOnFailureNoSuchFile() throws IOException { - ProcessTaskWrapper<?> t = submit(SshEffectorTasks.requirePidFromFileRunning("/path/does/not/exist/SADVQW")); - - setExpectingFailure(); - try { - t.getTask().getUnchecked(); - } catch (Exception e) { - log.info("The error if required PID is not found is: "+e); - clearExpectedFailure(); - Assert.assertTrue(e.toString().contains("Process with PID"), "Expected nice clue in error but got: "+e); - Assert.assertEquals(t.getExitCode(), (Integer)1); - } - checkExpectedFailure(); - } - - @Test(groups="Integration") - public void testRequirePidFromFileOnFailureTooManyFiles() throws IOException { - ProcessTaskWrapper<?> t = submit(SshEffectorTasks.requirePidFromFileRunning("/*")); - - setExpectingFailure(); - try { - t.getTask().getUnchecked(); - } catch (Exception e) { - log.info("The error if required PID is not found is: "+e); - clearExpectedFailure(); - Assert.assertTrue(e.toString().contains("Process with PID"), "Expected nice clue in error but got: "+e); - Assert.assertEquals(t.getExitCode(), (Integer)2); - } - checkExpectedFailure(); - } - - @Test(groups="Integration") - public void testRequirePidFromFileOnSuccess() throws IOException { - File f = File.createTempFile("testBrooklynPid", ".pid"); - Files.write( (""+getMyPid()).getBytes(), f ); - ProcessTaskWrapper<?> t = submit(SshEffectorTasks.requirePidFromFileRunning(f.getPath())); - - t.getTask().getUnchecked(); - } - - @Test(groups="Integration") - public void testRequirePidFromFileOnSuccessAcceptsWildcards() throws IOException { - File f = File.createTempFile("testBrooklynPid", ".pid"); - Files.write( (""+getMyPid()).getBytes(), f ); - ProcessTaskWrapper<?> t = submit(SshEffectorTasks.requirePidFromFileRunning(f.getPath()+"*")); - - t.getTask().getUnchecked(); - } - -} http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/test/java/brooklyn/entity/software/StaticSensorTest.java ---------------------------------------------------------------------- diff --git a/software/base/src/test/java/brooklyn/entity/software/StaticSensorTest.java b/software/base/src/test/java/brooklyn/entity/software/StaticSensorTest.java deleted file mode 100644 index 33c4987..0000000 --- a/software/base/src/test/java/brooklyn/entity/software/StaticSensorTest.java +++ /dev/null @@ -1,54 +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.entity.software; - -import org.apache.brooklyn.api.entity.EntitySpec; -import org.apache.brooklyn.core.test.BrooklynAppUnitTestSupport; -import org.apache.brooklyn.entity.stock.BasicEntity; -import org.apache.brooklyn.sensor.core.Sensors; -import org.apache.brooklyn.test.EntityTestUtils; -import org.apache.brooklyn.util.core.config.ConfigBag; -import org.testng.annotations.Test; - -import com.google.common.collect.ImmutableMap; - -public class StaticSensorTest extends BrooklynAppUnitTestSupport { - - @Test - public void testAddsStaticSensorOfTypeString() { - BasicEntity entity = app.createAndManageChild(EntitySpec.create(BasicEntity.class) - .addInitializer(new StaticSensor<String>(ConfigBag.newInstance(ImmutableMap.of( - StaticSensor.SENSOR_NAME, "myname", - StaticSensor.SENSOR_TYPE, String.class.getName(), - StaticSensor.STATIC_VALUE, "myval"))))); - - EntityTestUtils.assertAttributeEquals(entity, Sensors.newSensor(String.class, "myname"), "myval"); - } - - @Test - public void testAddsStaticSensorOfTypeInteger() { - BasicEntity entity = app.createAndManageChild(EntitySpec.create(BasicEntity.class) - .addInitializer(new StaticSensor<Integer>(ConfigBag.newInstance(ImmutableMap.of( - StaticSensor.SENSOR_NAME, "myname", - StaticSensor.SENSOR_TYPE, Integer.class.getName(), - StaticSensor.STATIC_VALUE, "1"))))); - - EntityTestUtils.assertAttributeEquals(entity, Sensors.newSensor(Integer.class, "myname"), 1); - } -} http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/test/java/brooklyn/entity/software/http/HttpRequestSensorTest.java ---------------------------------------------------------------------- diff --git a/software/base/src/test/java/brooklyn/entity/software/http/HttpRequestSensorTest.java b/software/base/src/test/java/brooklyn/entity/software/http/HttpRequestSensorTest.java deleted file mode 100644 index d5367f2..0000000 --- a/software/base/src/test/java/brooklyn/entity/software/http/HttpRequestSensorTest.java +++ /dev/null @@ -1,84 +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.entity.software.http; - -import org.apache.brooklyn.api.entity.EntitySpec; -import org.apache.brooklyn.api.internal.EntityLocal; -import org.apache.brooklyn.api.location.Location; -import org.apache.brooklyn.api.sensor.AttributeSensor; -import org.apache.brooklyn.core.test.TestHttpRequestHandler; -import org.apache.brooklyn.core.test.TestHttpServer; -import org.apache.brooklyn.core.test.entity.TestApplication; -import org.apache.brooklyn.core.test.entity.TestEntity; -import org.apache.brooklyn.entity.core.Attributes; -import org.apache.brooklyn.entity.core.Entities; -import org.apache.brooklyn.sensor.core.Sensors; -import org.apache.brooklyn.test.EntityTestUtils; -import org.apache.brooklyn.util.core.config.ConfigBag; -import org.apache.brooklyn.util.time.Duration; -import org.testng.annotations.AfterMethod; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.Test; - -import com.google.common.collect.ImmutableList; - -public class HttpRequestSensorTest { - final static AttributeSensor<String> SENSOR_STRING = Sensors.newStringSensor("aString"); - final static String TARGET_TYPE = "java.lang.String"; - - private TestApplication app; - private EntityLocal entity; - - private TestHttpServer server; - private String serverUrl; - - @BeforeClass(alwaysRun=true) - public void setUp() throws Exception { - server = new TestHttpServer() - .handler("/myKey/myValue", new TestHttpRequestHandler().header("Content-Type", "application/json").response("{\"myKey\":\"myValue\"}")) - .start(); - serverUrl = server.getUrl(); - - app = TestApplication.Factory.newManagedInstanceForTests(); - entity = app.createAndManageChild(EntitySpec.create(TestEntity.class) - .location(app.newLocalhostProvisioningLocation().obtain())); - app.start(ImmutableList.<Location>of()); - } - - @AfterMethod(alwaysRun=true) - public void tearDown() throws Exception { - if (app != null) Entities.destroyAll(app.getManagementContext()); - server.stop(); - } - - @Test - public void testHttpSensor() throws Exception { - HttpRequestSensor<Integer> sensor = new HttpRequestSensor<Integer>(ConfigBag.newInstance() - .configure(HttpRequestSensor.SENSOR_PERIOD, Duration.millis(100)) - .configure(HttpRequestSensor.SENSOR_NAME, SENSOR_STRING.getName()) - .configure(HttpRequestSensor.SENSOR_TYPE, TARGET_TYPE) - .configure(HttpRequestSensor.JSON_PATH, "$.myKey") - .configure(HttpRequestSensor.SENSOR_URI, serverUrl + "/myKey/myValue")); - sensor.apply(entity); - entity.setAttribute(Attributes.SERVICE_UP, true); - - EntityTestUtils.assertAttributeEqualsEventually(entity, SENSOR_STRING, "myValue"); - } - -} http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/test/java/brooklyn/entity/software/mysql/AbstractToyMySqlEntityTest.java ---------------------------------------------------------------------- diff --git a/software/base/src/test/java/brooklyn/entity/software/mysql/AbstractToyMySqlEntityTest.java b/software/base/src/test/java/brooklyn/entity/software/mysql/AbstractToyMySqlEntityTest.java deleted file mode 100644 index 7a465de..0000000 --- a/software/base/src/test/java/brooklyn/entity/software/mysql/AbstractToyMySqlEntityTest.java +++ /dev/null @@ -1,109 +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.entity.software.mysql; - -import org.apache.brooklyn.api.entity.Entity; -import org.apache.brooklyn.api.location.LocationSpec; -import org.apache.brooklyn.api.location.MachineProvisioningLocation; -import org.apache.brooklyn.core.test.BrooklynAppLiveTestSupport; -import org.apache.brooklyn.entity.core.Attributes; -import org.apache.brooklyn.entity.core.Entities; -import org.apache.brooklyn.entity.lifecycle.Lifecycle; -import org.apache.brooklyn.test.EntityTestUtils; -import org.apache.brooklyn.util.collections.MutableList; -import org.apache.brooklyn.util.collections.MutableMap; -import org.apache.brooklyn.util.core.task.system.ProcessTaskWrapper; -import org.apache.brooklyn.util.time.Duration; -import org.apache.brooklyn.util.time.Time; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.testng.Assert; -import org.testng.annotations.BeforeMethod; - -import brooklyn.entity.software.SshEffectorTasks; - -import org.apache.brooklyn.location.basic.LocalhostMachineProvisioningLocation; -import org.apache.brooklyn.location.basic.SshMachineLocation; - -import com.google.common.base.Predicates; -import com.google.common.collect.Iterables; - - -public abstract class AbstractToyMySqlEntityTest extends BrooklynAppLiveTestSupport { - - private static final Logger log = LoggerFactory.getLogger(AbstractToyMySqlEntityTest.class); - - protected MachineProvisioningLocation<? extends SshMachineLocation> targetLocation; - - @Override - @BeforeMethod(alwaysRun=true) - public void setUp() throws Exception { - super.setUp(); - - targetLocation = createLocation(); - } - - protected MachineProvisioningLocation<? extends SshMachineLocation> createLocation() { - return mgmt.getLocationManager().createLocation(LocationSpec.create( - LocalhostMachineProvisioningLocation.class)); - } - - protected abstract Entity createMysql(); - - // deliberately not marked as a test here so that subclasses mark it correctly (Live v Integration) - public void testMySqlOnProvisioningLocation() throws Exception { - Entity mysql = createMysql(); - app.start(MutableList.of(targetLocation)); - checkStartsRunning(mysql); - checkIsRunningAndStops(mysql, (SshMachineLocation) Iterables.getOnlyElement( mysql.getLocations() )); - } - - protected Integer getPid(Entity mysql) { - return mysql.getAttribute(Attributes.PID); - } - - protected void checkStartsRunning(Entity mysql) { - // should be starting within a few seconds (and almost certainly won't complete in that time) - EntityTestUtils.assertAttributeEventually( - mysql, - Attributes.SERVICE_STATE_ACTUAL, - Predicates.or(Predicates.equalTo(Lifecycle.STARTING), Predicates.equalTo(Lifecycle.RUNNING))); - // should be up and running within 5m - EntityTestUtils.assertAttributeEqualsEventually(MutableMap.of("timeout", Duration.FIVE_MINUTES), - mysql, Attributes.SERVICE_STATE_ACTUAL, Lifecycle.RUNNING); - } - - protected void checkIsRunningAndStops(Entity mysql, SshMachineLocation lh) { - Integer pid = getPid(mysql); - Assert.assertNotNull(pid, "PID should be set as an attribute (or getPid() overridden to supply)"); - Entities.submit(app, SshEffectorTasks.requirePidRunning(pid).machine(lh).newTask() ).get(); - - app.stop(); - - // let the kill -1 take effect - Time.sleep(Duration.ONE_SECOND); - - // and assert it has died - log.info("mysql in pid "+pid+" should be dead now"); - // (app has stopped, so submit on mgmt context) - ProcessTaskWrapper<Integer> t = SshEffectorTasks.codePidRunning(pid).machine(lh).newTask(); - mgmt.getExecutionManager().submit(t); - Assert.assertNotEquals(t.block().getExitCode(), (Integer)0); - } -} http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/test/java/brooklyn/entity/software/mysql/DynamicToyMySqlEntityBuilder.java ---------------------------------------------------------------------- diff --git a/software/base/src/test/java/brooklyn/entity/software/mysql/DynamicToyMySqlEntityBuilder.java b/software/base/src/test/java/brooklyn/entity/software/mysql/DynamicToyMySqlEntityBuilder.java deleted file mode 100644 index 91f402d..0000000 --- a/software/base/src/test/java/brooklyn/entity/software/mysql/DynamicToyMySqlEntityBuilder.java +++ /dev/null @@ -1,191 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package brooklyn.entity.software.mysql; - -import java.io.File; - -import org.apache.brooklyn.api.entity.Entity; -import org.apache.brooklyn.api.entity.EntityInitializer; -import org.apache.brooklyn.api.entity.EntitySpec; -import org.apache.brooklyn.api.internal.EntityLocal; -import org.apache.brooklyn.api.location.MachineLocation; -import org.apache.brooklyn.api.location.OsDetails; -import org.apache.brooklyn.core.mgmt.BrooklynTaskTags; -import org.apache.brooklyn.entity.core.Attributes; -import org.apache.brooklyn.entity.stock.BasicStartable; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import brooklyn.entity.software.MachineLifecycleEffectorTasks; -import brooklyn.entity.software.SshEffectorTasks; - -import org.apache.brooklyn.location.basic.BasicOsDetails.OsVersions; -import org.apache.brooklyn.location.basic.LocalhostMachineProvisioningLocation.LocalhostMachine; -import org.apache.brooklyn.location.basic.SshMachineLocation; -import org.apache.brooklyn.util.core.task.DynamicTasks; -import org.apache.brooklyn.util.core.task.Tasks; -import org.apache.brooklyn.util.core.task.ssh.SshTasks; -import org.apache.brooklyn.util.core.task.system.ProcessTaskWrapper; -import org.apache.brooklyn.util.ssh.BashCommands; -import org.apache.brooklyn.util.text.ComparableVersion; -import org.apache.brooklyn.util.time.Duration; -import org.apache.brooklyn.util.time.Time; - -import com.google.common.base.Predicates; -import com.google.common.base.Splitter; -import com.google.common.base.Supplier; -import com.google.common.base.Suppliers; -import com.google.common.collect.Iterables; - -public class DynamicToyMySqlEntityBuilder { - - private static final Logger log = LoggerFactory.getLogger(DynamicToyMySqlEntityBuilder.class); - - public static EntitySpec<? extends Entity> spec() { - return EntitySpec.create(BasicStartable.class).addInitializer(MySqlEntityInitializer.class); - } - - public static final String downloadUrl(Entity e, boolean isLocalhost) { - if (isLocalhost) { - for (int i=50; i>20; i--) { - String f = System.getProperty("user.home")+"/.brooklyn/repository/MySqlNode/5.5."+i+"/mysql-5.5."+i+"-osx10.6-x86_64.tar.gz"; - if (new File(f).exists()) - return "file://"+f; - } - } - // download - String version = "5.5.37"; - String osTag = getOsTag(e); - String mirrorUrl = "http://www.mirrorservice.org/sites/ftp.mysql.com/"; - return "http://dev.mysql.com/get/Downloads/MySQL-5.5/mysql-"+version+"-"+osTag+".tar.gz/from/"+mirrorUrl; - } - - public static final String installDir(Entity e, boolean isLocalhost) { - String url = downloadUrl(e, isLocalhost); - String archive = Iterables.find(Splitter.on('/').omitEmptyStrings().split(url), Predicates.containsPattern(".tar.gz")); - return archive.replace(".tar.gz", ""); - } - - public static final String dir(Entity e) { - return "/tmp/brooklyn-mysql-"+e.getId(); - } - - // copied from MySqlSshDriver - public static String getOsTag(Entity e) { - // e.g. "osx10.6-x86_64"; see http://www.mysql.com/downloads/mysql/#downloads - OsDetails os = ((SshMachineLocation)Iterables.getOnlyElement(e.getLocations())).getOsDetails(); - if (os == null) return "linux-glibc2.5-x86_64"; - if (os.isMac()) { - String osp1 = os.getVersion()==null ? "osx10.8" //lowest common denominator - : new ComparableVersion(os.getVersion()).isGreaterThanOrEqualTo(OsVersions.MAC_10_9) ? "osx10.9" - : "osx10.8"; //lowest common denominator - if (!os.is64bit()) { - throw new IllegalStateException("Only 64 bit MySQL build is available for OS X"); - } - return osp1+"-x86_64"; - } - //assume generic linux - String osp1 = "linux-glibc2.5"; - String osp2 = os.is64bit() ? "x86_64" : "i686"; - return osp1+"-"+osp2; - } - - public static class MySqlEntityInitializer implements EntityInitializer { - public void apply(final EntityLocal entity) { - new MachineLifecycleEffectorTasks() { - @Override - protected String startProcessesAtMachine(Supplier<MachineLocation> machineS) { - DynamicTasks.queue( - SshEffectorTasks.ssh( - "mkdir "+dir(entity), - "cd "+dir(entity), - BashCommands.downloadToStdout(downloadUrl(entity, isLocalhost(machineS)))+" | tar xvz" - ).summary("download mysql").returning(SshTasks.returningStdoutLoggingInfo(log, true))); - if (isLinux(machineS)) { - DynamicTasks.queue(SshEffectorTasks.ssh(BashCommands.installPackage("libaio1"))); - } - DynamicTasks.queue( - SshEffectorTasks.put(".my.cnf") - .contents(String.format("[mysqld]\nbasedir=%s/%s\n", dir(entity), installDir(entity, isLocalhost(machineS)))), - SshEffectorTasks.ssh( - "cd "+dir(entity)+"/*", - "./scripts/mysql_install_db", - "./support-files/mysql.server start > out.log 2> err.log < /dev/null" - ).summary("setup and run mysql").returning(SshTasks.returningStdoutLoggingInfo(log, true))); - return "submitted start"; - } - protected void postStartCustom() { - // if it's still up after 5s assume we are good - Time.sleep(Duration.FIVE_SECONDS); - if (!DynamicTasks.queue(SshEffectorTasks.isPidFromFileRunning(dir(entity)+"/*/data/*.pid")).get()) { - // but if it's not up add a bunch of other info - log.warn("MySQL did not start: "+dir(entity)); - ProcessTaskWrapper<Integer> info = DynamicTasks.queue(SshEffectorTasks.ssh( - "cd "+dir(entity)+"/*", - "cat out.log", - "cat err.log > /dev/stderr")).block(); - log.info("STDOUT:\n"+info.getStdout()); - log.info("STDERR:\n"+info.getStderr()); - BrooklynTaskTags.addTagsDynamically(Tasks.current(), - BrooklynTaskTags.tagForStream("console (nohup stdout)", Suppliers.ofInstance(info.getStdout()), null), - BrooklynTaskTags.tagForStream("console (nohup stderr)", Suppliers.ofInstance(info.getStderr()), null)); - throw new IllegalStateException("MySQL appears not to be running"); - } - - // and set the PID - entity().setAttribute(Attributes.PID, - Integer.parseInt(DynamicTasks.queue(SshEffectorTasks.ssh("cat "+dir(entity)+"/*/data/*.pid")).block().getStdout().trim())); - - // TODO Without this, tests fail because nothing else sets serviceUp! - // Really should set this with a Feed that checks pid periodically. - // Should this instead be using SERVICE_NOT_UP_INDICATORS? - entity().setAttribute(Attributes.SERVICE_UP, true); - } - - @Override - protected String stopProcessesAtMachine() { - // TODO Where is best place to set? - // Really should set this with a Feed that checks pid periodically. - entity().setAttribute(Attributes.SERVICE_UP, false); - - Integer pid = entity().getAttribute(Attributes.PID); - if (pid==null) { - log.info("mysql not running"); - return "No pid -- is it running?"; - } - - DynamicTasks.queue(SshEffectorTasks.ssh( - "cd "+dir(entity)+"/*", - "./support-files/mysql.server stop" - ).summary("stop mysql")); - return "submitted stop"; - } - }.attachLifecycleEffectors(entity); - } - } - - private static boolean isLocalhost(Supplier<MachineLocation> machineS) { - return machineS.get() instanceof LocalhostMachine; - } - - private static boolean isLinux(Supplier<MachineLocation> machineS) { - return machineS.get().getMachineDetails().getOsDetails().isLinux(); - } - -} http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/test/java/brooklyn/entity/software/mysql/DynamicToyMySqlEntityTest.java ---------------------------------------------------------------------- diff --git a/software/base/src/test/java/brooklyn/entity/software/mysql/DynamicToyMySqlEntityTest.java b/software/base/src/test/java/brooklyn/entity/software/mysql/DynamicToyMySqlEntityTest.java deleted file mode 100644 index 75684f5..0000000 --- a/software/base/src/test/java/brooklyn/entity/software/mysql/DynamicToyMySqlEntityTest.java +++ /dev/null @@ -1,58 +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.entity.software.mysql; - -import java.util.Arrays; - -import org.apache.brooklyn.api.entity.Entity; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.testng.annotations.Test; -import org.apache.brooklyn.location.basic.SshMachineLocation; -import org.apache.brooklyn.util.collections.MutableMap; - - -public class DynamicToyMySqlEntityTest extends AbstractToyMySqlEntityTest { - - private static final Logger log = LoggerFactory.getLogger(DynamicToyMySqlEntityTest.class); - - protected Entity createMysql() { - Entity mysql = app.createAndManageChild(DynamicToyMySqlEntityBuilder.spec()); - log.debug("created "+mysql); - return mysql; - } - - // put right group on test (also help Eclipse IDE pick it up) - @Override - @Test(groups = "Integration") - public void testMySqlOnProvisioningLocation() throws Exception { - super.testMySqlOnProvisioningLocation(); - } - - @Test(groups="Integration") - public void testMySqlOnMachineLocation() throws Exception { - Entity mysql = createMysql(); - SshMachineLocation lh = targetLocation.obtain(MutableMap.of()); - - app.start(Arrays.asList(lh)); - checkStartsRunning(mysql); - checkIsRunningAndStops(mysql, lh); - } - -} http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/test/java/brooklyn/entity/software/ssh/SshCommandIntegrationTest.java ---------------------------------------------------------------------- diff --git a/software/base/src/test/java/brooklyn/entity/software/ssh/SshCommandIntegrationTest.java b/software/base/src/test/java/brooklyn/entity/software/ssh/SshCommandIntegrationTest.java deleted file mode 100644 index 085b737..0000000 --- a/software/base/src/test/java/brooklyn/entity/software/ssh/SshCommandIntegrationTest.java +++ /dev/null @@ -1,124 +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.entity.software.ssh; - -import static org.testng.Assert.assertTrue; - -import java.io.File; - -import org.apache.brooklyn.api.effector.Effector; -import org.apache.brooklyn.api.entity.EntitySpec; -import org.apache.brooklyn.api.internal.EntityLocal; -import org.apache.brooklyn.api.location.Location; -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.effector.core.Effectors; -import org.apache.brooklyn.entity.core.Attributes; -import org.apache.brooklyn.entity.core.Entities; -import org.apache.brooklyn.sensor.core.Sensors; -import org.apache.brooklyn.test.EntityTestUtils; -import org.apache.brooklyn.util.collections.MutableMap; -import org.apache.brooklyn.util.core.config.ConfigBag; -import org.apache.brooklyn.util.time.Duration; -import org.testng.Assert; -import org.testng.annotations.AfterMethod; -import org.testng.annotations.BeforeMethod; -import org.testng.annotations.Test; -import org.apache.brooklyn.location.basic.SshMachineLocation; - -import com.google.common.collect.ImmutableList; - -public class SshCommandIntegrationTest { - - final static AttributeSensor<String> SENSOR_STRING = Sensors.newStringSensor("aString", ""); - final static AttributeSensor<Integer> SENSOR_INT = Sensors.newIntegerSensor("aLong", ""); - final static Effector<String> EFFECTOR_SAY_HI = Effectors.effector(String.class, "sayHi").buildAbstract(); - - private TestApplication app; - private SshMachineLocation machine; - private EntityLocal entity; - - @BeforeMethod(alwaysRun=true) - public void setUp() throws Exception { - app = TestApplication.Factory.newManagedInstanceForTests(); - machine = app.newLocalhostProvisioningLocation().obtain(); - entity = app.createAndManageChild(EntitySpec.create(TestEntity.class).location(machine)); - app.start(ImmutableList.<Location>of()); - } - - @AfterMethod(alwaysRun=true) - public void tearDown() throws Exception { - if (app != null) Entities.destroyAll(app.getManagementContext()); - } - - @Test(groups="Integration") - public void testSshSensor() throws Exception { - File tempFile = File.createTempFile("testSshCommand", "txt"); - tempFile.deleteOnExit(); - new SshCommandSensor<String>(ConfigBag.newInstance() - .configure(SshCommandSensor.SENSOR_PERIOD, Duration.millis(100)) - .configure(SshCommandSensor.SENSOR_NAME, SENSOR_STRING.getName()) - .configure(SshCommandSensor.SENSOR_COMMAND, "echo foo > "+tempFile.getAbsolutePath()+"\n" - + "wc "+tempFile.getAbsolutePath())) - .apply(entity); - entity.setAttribute(Attributes.SERVICE_UP, true); - - String val = EntityTestUtils.assertAttributeEventuallyNonNull(entity, SENSOR_STRING); - assertTrue(val.contains("1"), "val="+val); - String[] counts = val.trim().split("\\s+"); - Assert.assertEquals(counts.length, 4, "val="+val); - Assert.assertEquals(counts[0], "1", "val="+val); - } - - @Test(groups="Integration") - public void testSshEffector() throws Exception { - File tempFile = File.createTempFile("testSshCommand", "txt"); - tempFile.deleteOnExit(); - new SshCommandEffector(ConfigBag.newInstance() - .configure(SshCommandEffector.EFFECTOR_NAME, "sayHi") - .configure(SshCommandEffector.EFFECTOR_COMMAND, "echo hi")) - .apply(entity); - - String val = entity.invoke(EFFECTOR_SAY_HI, MutableMap.<String,String>of()).get(); - Assert.assertEquals(val.trim(), "hi", "val="+val); - } - - @Test(groups="Integration") - public void testSshEffectorWithParameters() throws Exception { - File tempFile = File.createTempFile("testSshCommand", "txt"); - tempFile.deleteOnExit(); - new SshCommandEffector(ConfigBag.newInstance() - .configure(SshCommandEffector.EFFECTOR_NAME, "sayHi") - .configure(SshCommandEffector.EFFECTOR_COMMAND, "echo $foo") - .configure(SshCommandEffector.EFFECTOR_PARAMETER_DEFS, - MutableMap.<String,Object>of("foo", MutableMap.of("defaultValue", "hi")))) - .apply(entity); - - String val; - // explicit value - val = entity.invoke(EFFECTOR_SAY_HI, MutableMap.<String,String>of("foo", "bar")).get(); - Assert.assertEquals(val.trim(), "bar", "val="+val); - - // default value - val = entity.invoke(EFFECTOR_SAY_HI, MutableMap.<String,String>of()).get(); - Assert.assertEquals(val.trim(), "hi", "val="+val); - } - -} http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/test/java/brooklyn/event/basic/PortAttributeSensorAndConfigKeyTest.java ---------------------------------------------------------------------- diff --git a/software/base/src/test/java/brooklyn/event/basic/PortAttributeSensorAndConfigKeyTest.java b/software/base/src/test/java/brooklyn/event/basic/PortAttributeSensorAndConfigKeyTest.java deleted file mode 100644 index 8bcbb67..0000000 --- a/software/base/src/test/java/brooklyn/event/basic/PortAttributeSensorAndConfigKeyTest.java +++ /dev/null @@ -1,88 +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.event.basic; - -import static org.testng.Assert.assertEquals; - -import org.apache.brooklyn.api.entity.EntitySpec; -import org.apache.brooklyn.api.entity.ImplementedBy; -import org.apache.brooklyn.api.location.Location; -import org.apache.brooklyn.core.test.BrooklynAppUnitTestSupport; -import org.apache.brooklyn.entity.core.Entities; -import org.testng.annotations.Test; - -import brooklyn.entity.basic.EmptySoftwareProcess; -import brooklyn.entity.basic.EmptySoftwareProcessImpl; - -import org.apache.brooklyn.location.basic.LocalhostMachineProvisioningLocation; -import org.apache.brooklyn.location.basic.SshMachineLocation; -import org.apache.brooklyn.sensor.core.PortAttributeSensorAndConfigKey; - -import com.google.common.collect.ImmutableList; - -public class PortAttributeSensorAndConfigKeyTest extends BrooklynAppUnitTestSupport { - - /* - * FIXME Fails because port is never released. Nothing calls PortSupplier.releasePort(int). - * The stacktrace below shows where it is obtained: - * - Daemon Thread [brooklyn-execmanager-XwLLLdS4-5] (Suspended (breakpoint at line 244 in LocalhostMachineProvisioningLocation$LocalhostMachine)) - LocalhostMachineProvisioningLocation$LocalhostMachine.obtainPort(PortRange) line: 244 - PortAttributeSensorAndConfigKey.convertConfigToSensor(PortRange, Entity) line: 78 - PortAttributeSensorAndConfigKey.convertConfigToSensor(Object, Entity) line: 1 - PortAttributeSensorAndConfigKey(AttributeSensorAndConfigKey<ConfigType,SensorType>).getAsSensorValue(Entity) line: 93 - ConfigToAttributes.apply(EntityLocal, AttributeSensorAndConfigKey<?,T>) line: 28 - ConfigToAttributes.apply(EntityLocal) line: 17 - SoftwareProcessDriverLifecycleEffectorTasks(MachineLifecycleEffectorTasks).preStartCustom(MachineLocation) line: 343 - SoftwareProcessDriverLifecycleEffectorTasks.preStartCustom(MachineLocation) line: 69 - MachineLifecycleEffectorTasks$6.run() line: 283 - */ - @Test(enabled=false, groups="Integration") // test is slow (for some reason - why?) - public void testStoppingEntityReleasesPortFromMachineForReuse() throws Exception { - LocalhostMachineProvisioningLocation loc = (LocalhostMachineProvisioningLocation) mgmt.getLocationRegistry().resolve("localhost"); - SshMachineLocation machine = loc.obtain(); - runStoppingEntityReleasesPortFromLocalhostForReuse(machine); - } - - @Test(groups="Integration") // test is slow (for some reason - why?) - public void testStoppingEntityReleasesPortFromLocalhostProvisioningLocationForReuse() throws Exception { - LocalhostMachineProvisioningLocation loc = (LocalhostMachineProvisioningLocation) mgmt.getLocationRegistry().resolve("localhost"); - runStoppingEntityReleasesPortFromLocalhostForReuse(loc); - } - - protected void runStoppingEntityReleasesPortFromLocalhostForReuse(Location loc) throws Exception { - MyEntity e1 = app.createAndManageChild(EntitySpec.create(MyEntity.class)); - e1.start(ImmutableList.of(loc)); - assertEquals(e1.getAttribute(MyEntity.MY_PORT), (Integer)47653); - - e1.stop(); - Entities.unmanage(e1); - MyEntity e2 = app.createAndManageChild(EntitySpec.create(MyEntity.class)); - e2.start(ImmutableList.of(loc)); - assertEquals(e2.getAttribute(MyEntity.MY_PORT), (Integer)47653); - } - - @ImplementedBy(MyEntityImpl.class) - public interface MyEntity extends EmptySoftwareProcess { - PortAttributeSensorAndConfigKey MY_PORT = new PortAttributeSensorAndConfigKey("myport", "", "47653"); - } - - public static class MyEntityImpl extends EmptySoftwareProcessImpl implements MyEntity { - } -} http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/test/java/brooklyn/event/feed/jmx/JmxFeedTest.java ---------------------------------------------------------------------- diff --git a/software/base/src/test/java/brooklyn/event/feed/jmx/JmxFeedTest.java b/software/base/src/test/java/brooklyn/event/feed/jmx/JmxFeedTest.java deleted file mode 100644 index f0c51a2..0000000 --- a/software/base/src/test/java/brooklyn/event/feed/jmx/JmxFeedTest.java +++ /dev/null @@ -1,418 +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.event.feed.jmx; - -import static org.apache.brooklyn.test.TestUtils.executeUntilSucceeds; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertTrue; - -import java.util.Collections; -import java.util.List; -import java.util.Map; -import java.util.concurrent.Callable; -import java.util.concurrent.atomic.AtomicInteger; - -import javax.management.MBeanOperationInfo; -import javax.management.MBeanParameterInfo; -import javax.management.Notification; -import javax.management.NotificationListener; -import javax.management.ObjectName; -import javax.management.StandardEmitterMBean; -import javax.management.openmbean.CompositeDataSupport; -import javax.management.openmbean.CompositeType; -import javax.management.openmbean.OpenType; -import javax.management.openmbean.SimpleType; -import javax.management.openmbean.TabularDataSupport; -import javax.management.openmbean.TabularType; - -import org.apache.brooklyn.api.entity.Entity; -import org.apache.brooklyn.api.entity.EntitySpec; -import org.apache.brooklyn.api.sensor.AttributeSensor; -import org.apache.brooklyn.api.sensor.SensorEvent; -import org.apache.brooklyn.api.sensor.SensorEventListener; -import org.apache.brooklyn.core.test.entity.TestApplication; -import org.apache.brooklyn.core.test.entity.TestApplicationImpl; -import org.apache.brooklyn.core.test.entity.TestEntity; -import org.apache.brooklyn.core.test.entity.TestEntityImpl; -import org.apache.brooklyn.entity.core.AbstractEntity; -import org.apache.brooklyn.entity.core.Attributes; -import org.apache.brooklyn.entity.core.Entities; -import org.apache.brooklyn.sensor.core.BasicAttributeSensor; -import org.apache.brooklyn.sensor.core.BasicNotificationSensor; -import org.apache.brooklyn.sensor.core.Sensors; -import org.apache.brooklyn.sensor.feed.ConfigToAttributes; -import org.apache.brooklyn.test.Asserts; -import org.apache.brooklyn.test.TestUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.testng.annotations.AfterMethod; -import org.testng.annotations.BeforeMethod; -import org.testng.annotations.Test; -import org.testng.collections.Lists; - -import brooklyn.entity.java.JmxSupport; -import brooklyn.entity.java.UsesJmx; -import brooklyn.entity.java.UsesJmx.JmxAgentModes; - -import org.apache.brooklyn.location.basic.LocalhostMachineProvisioningLocation; -import org.apache.brooklyn.location.basic.PortRanges; -import org.apache.brooklyn.location.basic.SimulatedLocation; - -import brooklyn.test.GeneralisedDynamicMBean; -import brooklyn.test.JmxService; - -import com.google.common.base.Function; -import com.google.common.collect.ImmutableList; -import com.google.common.collect.ImmutableMap; - -/** - * Test the operation of the {@link JmxFeed} class. - * <p> - * Also confirm some of the JMX setup done by {@link JmxSupport} and {@link JmxHelper}, - * based on ports in {@link UsesJmx}. - * <p> - * TODO tests of other JMX_AGENT_MODE are done in ActiveMqIntegrationTest; - * would be nice to promote some to live here - */ -public class JmxFeedTest { - - // FIXME Move out the JmxHelper tests into the JmxHelperTest class - - // FIXME Also test that setting poll period takes effect - - private static final Logger log = LoggerFactory.getLogger(JmxFeedTest.class); - - private static final int TIMEOUT_MS = 5000; - private static final int SHORT_WAIT_MS = 250; - - private JmxService jmxService; - private TestApplication app; - private TestEntity entity; - private JmxFeed feed; - private JmxHelper jmxHelper; - - private AttributeSensor<Integer> intAttribute = Sensors.newIntegerSensor("brooklyn.test.intAttribute", "Brooklyn testing int attribute"); - private AttributeSensor<String> stringAttribute = Sensors.newStringSensor("brooklyn.test.stringAttribute", "Brooklyn testing string attribute"); - private BasicAttributeSensor<Map> mapAttribute = new BasicAttributeSensor<Map>(Map.class, "brooklyn.test.mapAttribute", "Brooklyn testing map attribute"); - private String objectName = "Brooklyn:type=MyTestMBean,name=myname"; - private ObjectName jmxObjectName; - private String attributeName = "myattrib"; - private String opName = "myop"; - - public static class TestEntityWithJmx extends TestEntityImpl { - @Override public void init() { - setAttribute(Attributes.HOSTNAME, "localhost"); - setAttribute(UsesJmx.JMX_PORT, - LocalhostMachineProvisioningLocation.obtainPort(PortRanges.fromString("40123+"))); - // only supports no-agent, at the moment - setConfig(UsesJmx.JMX_AGENT_MODE, JmxAgentModes.NONE); - setAttribute(UsesJmx.RMI_REGISTRY_PORT, -1); // -1 means to use the JMX_PORT only - ConfigToAttributes.apply(this, UsesJmx.JMX_CONTEXT); - } - } - - @BeforeMethod(alwaysRun=true) - public void setUp() throws Exception { - jmxObjectName = new ObjectName(objectName); - - // Create an entity and configure it with the above JMX service - app = TestApplication.Factory.newManagedInstanceForTests(); - entity = app.createAndManageChild(EntitySpec.create(TestEntity.class).impl(TestEntityWithJmx.class)); - app.start(ImmutableList.of(new SimulatedLocation())); - - jmxHelper = new JmxHelper(entity); - - jmxService = new JmxService(entity); - } - - @AfterMethod(alwaysRun=true) - public void tearDown() throws Exception { - if (feed != null) feed.stop(); - if (jmxHelper != null) jmxHelper.disconnect(); - if (jmxService != null) jmxService.shutdown(); - if (app != null) Entities.destroyAll(app.getManagementContext()); - feed = null; - } - - @Test - public void testJmxAttributePollerReturnsMBeanAttribute() throws Exception { - GeneralisedDynamicMBean mbean = jmxService.registerMBean(ImmutableMap.of(attributeName, 42), objectName); - - feed = JmxFeed.builder() - .entity(entity) - .pollAttribute(new JmxAttributePollConfig<Integer>(intAttribute) - .objectName(objectName) - .period(50) - .attributeName(attributeName)) - .build(); - - // Starts with value defined when registering... - assertSensorEventually(intAttribute, 42, TIMEOUT_MS); - - // Change the value and check it updates - mbean.updateAttributeValue(attributeName, 64); - assertSensorEventually(intAttribute, 64, TIMEOUT_MS); - } - - @Test - public void testJmxAttributeOfTypeTabularDataProviderConvertedToMap() throws Exception { - // Create the CompositeType and TabularData - CompositeType compositeType = new CompositeType( - "typeName", - "description", - new String[] {"myint", "mystring", "mybool"}, // item names - new String[] {"myint", "mystring", "mybool"}, // item descriptions, can't be null or empty string - new OpenType<?>[] {SimpleType.INTEGER, SimpleType.STRING, SimpleType.BOOLEAN} - ); - TabularType tt = new TabularType( - "typeName", - "description", - compositeType, - new String[] {"myint"} - ); - TabularDataSupport tds = new TabularDataSupport(tt); - tds.put(new CompositeDataSupport( - compositeType, - new String[] {"mybool", "myint", "mystring"}, - new Object[] {true, 1234, "on"} - )); - - // Create MBean - GeneralisedDynamicMBean mbean = jmxService.registerMBean(ImmutableMap.of(attributeName, tds), objectName); - - feed = JmxFeed.builder() - .entity(entity) - .pollAttribute(new JmxAttributePollConfig<Map>(mapAttribute) - .objectName(objectName) - .attributeName(attributeName) - .onSuccess((Function)JmxValueFunctions.tabularDataToMap())) - .build(); - - // Starts with value defined when registering... - assertSensorEventually( - mapAttribute, - ImmutableMap.of("myint", 1234, "mystring", "on", "mybool", Boolean.TRUE), - TIMEOUT_MS); - } - - @Test - public void testJmxOperationPolledForSensor() throws Exception { - // This is awful syntax... - final int opReturnVal = 123; - final AtomicInteger invocationCount = new AtomicInteger(); - MBeanOperationInfo opInfo = new MBeanOperationInfo(opName, "my descr", new MBeanParameterInfo[0], Integer.class.getName(), MBeanOperationInfo.ACTION); - GeneralisedDynamicMBean mbean = jmxService.registerMBean( - Collections.emptyMap(), - ImmutableMap.of(opInfo, new Function<Object[], Integer>() { - public Integer apply(Object[] args) { - invocationCount.incrementAndGet(); return opReturnVal; - }}), - objectName); - - feed = JmxFeed.builder() - .entity(entity) - .pollOperation(new JmxOperationPollConfig<Integer>(intAttribute) - .objectName(objectName) - .operationName(opName)) - .build(); - - TestUtils.executeUntilSucceeds(ImmutableMap.of("timeout", TIMEOUT_MS), new Runnable() { - public void run() { - assertTrue(invocationCount.get() > 0, "invocationCount="+invocationCount); - assertEquals(entity.getAttribute(intAttribute), (Integer)opReturnVal); - }}); - } - - @Test - public void testJmxOperationWithArgPolledForSensor() throws Exception { - // This is awful syntax... - MBeanParameterInfo paramInfo = new MBeanParameterInfo("param1", String.class.getName(), "my param1"); - MBeanParameterInfo[] paramInfos = new MBeanParameterInfo[] {paramInfo}; - MBeanOperationInfo opInfo = new MBeanOperationInfo(opName, "my descr", paramInfos, String.class.getName(), MBeanOperationInfo.ACTION); - GeneralisedDynamicMBean mbean = jmxService.registerMBean( - Collections.emptyMap(), - ImmutableMap.of(opInfo, new Function<Object[], String>() { - public String apply(Object[] args) { - return args[0]+"suffix"; - }}), - objectName); - - feed = JmxFeed.builder() - .entity(entity) - .pollOperation(new JmxOperationPollConfig<String>(stringAttribute) - .objectName(objectName) - .operationName(opName) - .operationParams(ImmutableList.of("myprefix"))) - .build(); - - assertSensorEventually(stringAttribute, "myprefix"+"suffix", TIMEOUT_MS); - } - - @Test - public void testJmxNotificationSubscriptionForSensor() throws Exception { - final String one = "notification.one", two = "notification.two"; - final StandardEmitterMBean mbean = jmxService.registerMBean(ImmutableList.of(one, two), objectName); - final AtomicInteger sequence = new AtomicInteger(0); - - feed = JmxFeed.builder() - .entity(entity) - .subscribeToNotification(new JmxNotificationSubscriptionConfig<Integer>(intAttribute) - .objectName(objectName) - .notificationFilter(JmxNotificationFilters.matchesType(one))) - .build(); - - // Notification updates the sensor - // Note that subscription is done async, so can't just send notification immediately during test. - Asserts.succeedsEventually(ImmutableMap.of("timeout", TIMEOUT_MS), new Runnable() { - public void run() { - sendNotification(mbean, one, sequence.getAndIncrement(), 123); - assertEquals(entity.getAttribute(intAttribute), (Integer)123); - }}); - - // But other notification types are ignored - sendNotification(mbean, two, sequence.getAndIncrement(), -1); - - Asserts.succeedsEventually(ImmutableMap.of("timeout", TIMEOUT_MS), new Runnable() { - public void run() { - assertEquals(entity.getAttribute(intAttribute), (Integer)123); - }}); - } - - @Test - public void testJmxNotificationSubscriptionForSensorParsingNotification() throws Exception { - final String one = "notification.one", two = "notification.two"; - final StandardEmitterMBean mbean = jmxService.registerMBean(ImmutableList.of(one, two), objectName); - final AtomicInteger sequence = new AtomicInteger(0); - - feed = JmxFeed.builder() - .entity(entity) - .subscribeToNotification(new JmxNotificationSubscriptionConfig<Integer>(intAttribute) - .objectName(objectName) - .notificationFilter(JmxNotificationFilters.matchesType(one)) - .onNotification(new Function<Notification, Integer>() { - public Integer apply(Notification notif) { - return (Integer) notif.getUserData(); - } - })) - .build(); - - - // Notification updates the sensor - // Note that subscription is done async, so can't just send notification immediately during test. - Asserts.succeedsEventually(ImmutableMap.of("timeout", TIMEOUT_MS), new Runnable() { - public void run() { - sendNotification(mbean, one, sequence.getAndIncrement(), 123); - assertEquals(entity.getAttribute(intAttribute), (Integer)123); - }}); - } - - @Test - public void testJmxNotificationMultipleSubscriptionUsingListener() throws Exception { - final String one = "notification.one"; - final String two = "notification.two"; - final StandardEmitterMBean mbean = jmxService.registerMBean(ImmutableList.of(one, two), objectName); - final AtomicInteger sequence = new AtomicInteger(0); - - feed = JmxFeed.builder() - .entity(entity) - .subscribeToNotification(new JmxNotificationSubscriptionConfig<Integer>(intAttribute) - .objectName(objectName) - .notificationFilter(JmxNotificationFilters.matchesTypes(one, two))) - .build(); - - // Notification updates the sensor - // Note that subscription is done async, so can't just send notification immediately during test. - Asserts.succeedsEventually(ImmutableMap.of("timeout", TIMEOUT_MS), new Runnable() { - public void run() { - sendNotification(mbean, one, sequence.getAndIncrement(), 123); - assertEquals(entity.getAttribute(intAttribute), (Integer)123); - }}); - - // And wildcard means other notifications also received - sendNotification(mbean, two, sequence.getAndIncrement(), 456); - assertSensorEventually(intAttribute, 456, TIMEOUT_MS); - } - - // Test reproduces functionality used in Monterey, for Venue entity being told of requestActor - @Test - public void testSubscribeToJmxNotificationAndEmitCorrespondingNotificationSensor() throws Exception { - TestApplication app2 = new TestApplicationImpl(); - final EntityWithEmitter entity = new EntityWithEmitter(app2); - Entities.startManagement(app2); - try { - app2.start(ImmutableList.of(new SimulatedLocation())); - - final List<SensorEvent<String>> received = Lists.newArrayList(); - app2.subscribe(null, EntityWithEmitter.MY_NOTIF, new SensorEventListener<String>() { - public void onEvent(SensorEvent<String> event) { - received.add(event); - }}); - - final StandardEmitterMBean mbean = jmxService.registerMBean(ImmutableList.of("one"), objectName); - final AtomicInteger sequence = new AtomicInteger(0); - - jmxHelper.connect(TIMEOUT_MS); - jmxHelper.addNotificationListener(jmxObjectName, new NotificationListener() { - public void handleNotification(Notification notif, Object callback) { - if (notif.getType().equals("one")) { - entity.emit(EntityWithEmitter.MY_NOTIF, (String) notif.getUserData()); - } - }}); - - - Asserts.succeedsEventually(ImmutableMap.of("timeout", TIMEOUT_MS), new Runnable() { - public void run() { - sendNotification(mbean, "one", sequence.getAndIncrement(), "abc"); - assertTrue(received.size() > 0, "received size should be bigger than 0"); - assertEquals(received.get(0).getValue(), "abc"); - }}); - } finally { - Entities.destroyAll(app2.getManagementContext()); - } - } - - public static class EntityWithEmitter extends AbstractEntity { - public static final BasicNotificationSensor<String> MY_NOTIF = new BasicNotificationSensor<String>(String.class, "test.myNotif", "My notif"); - - public EntityWithEmitter(Entity owner) { - super(owner); - } - public EntityWithEmitter(Map flags) { - super(flags); - } - public EntityWithEmitter(Map flags, Entity owner) { - super(flags, owner); - } - } - - private Notification sendNotification(StandardEmitterMBean mbean, String type, long seq, Object userData) { - Notification notif = new Notification(type, mbean, seq); - notif.setUserData(userData); - mbean.sendNotification(notif); - return notif; - } - - private <T> void assertSensorEventually(final AttributeSensor<T> sensor, final T expectedVal, long timeout) { - executeUntilSucceeds(ImmutableMap.of("timeout", timeout), new Callable<Void>() { - public Void call() { - assertEquals(entity.getAttribute(sensor), expectedVal); - return null; - }}); - } -}
