org.apache.brooklyn.api.sensor.SensorEventListener Java Examples

The following examples show how to use org.apache.brooklyn.api.sensor.SensorEventListener. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: CouchbaseNodeImpl.java    From brooklyn-library with Apache License 2.0 6 votes vote down vote up
@Override
public void init() {
    super.init();

    subscriptions().subscribe(this, Attributes.SERVICE_UP, new SensorEventListener<Boolean>() {
        @Override
        public void onEvent(SensorEvent<Boolean> booleanSensorEvent) {
            if (Boolean.TRUE.equals(booleanSensorEvent.getValue())) {
                Integer webPort = getAttribute(CouchbaseNode.COUCHBASE_WEB_ADMIN_PORT);
                Preconditions.checkNotNull(webPort, CouchbaseNode.COUCHBASE_WEB_ADMIN_PORT+" not set for %s; is an acceptable port available?", this);
                String hostAndPort = BrooklynAccessUtils.getBrooklynAccessibleAddress(CouchbaseNodeImpl.this, webPort).toString();
                sensors().set(CouchbaseNode.COUCHBASE_WEB_ADMIN_URL, URI.create(format("http://%s", hostAndPort)));
            }
        }
    });

    getMutableEntityType().addEffector(ADD_REPLICATION_RULE, new EffectorBody<Void>() {
        @Override
        public Void call(ConfigBag parameters) {
            addReplicationRule(parameters);
            return null;
        }
    });
}
 
Example #2
Source File: AsyncApplicationImpl.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@Override
public void setEntity(EntityLocal entity) {
    if (!(entity instanceof AsyncApplicationImpl)) {
        throw new IllegalArgumentException("enricher designed to work only with async-apps");
    }
    if (!isRebinding() && Boolean.FALSE.equals(config().get(SUPPRESS_DUPLICATES))) {
        throw new IllegalArgumentException("Must not set "+SUPPRESS_DUPLICATES+" to false when using "+this);
    }
    super.setEntity(entity);
    if (suppressDuplicates==null) {
        // only publish on changes, unless it is configured otherwise
        suppressDuplicates = true;
    }
    
    // Need to update again, e.g. if stop() effector marks this as expected=stopped.
    // There'd be a risk of infinite loop if we didn't suppressDuplicates!
    subscriptions().subscribe(entity, Attributes.SERVICE_STATE_EXPECTED, new SensorEventListener<Lifecycle.Transition>() {
        @Override public void onEvent(SensorEvent<Lifecycle.Transition> event) {
            onUpdated();
        }});
}
 
Example #3
Source File: DynamicMultiGroupTest.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@Test
public void testBucketDistributionFromSubscription() {
    Group group = app.createAndManageChild(EntitySpec.create(BasicGroup.class));
    final DynamicMultiGroup dmg = app.createAndManageChild(
            EntitySpec.create(DynamicMultiGroup.class)
                    .configure(ENTITY_FILTER, instanceOf(TestEntity.class))
                    .configure(BUCKET_FUNCTION, bucketFromAttribute(SENSOR))
    );
    app.subscriptions().subscribeToChildren(group, SENSOR, new SensorEventListener<String>() {
        @Override
        public void onEvent(SensorEvent<String> event) { dmg.rescanEntities(); }
    });

    EntitySpec<TestEntity> childSpec = EntitySpec.create(TestEntity.class);
    TestEntity child1 = group.addChild(EntitySpec.create(childSpec).displayName("child1"));
    TestEntity child2 = group.addChild(EntitySpec.create(childSpec).displayName("child2"));

    checkDistribution(group, dmg, childSpec, child1, child2);
}
 
Example #4
Source File: SensorPropagatingEnricherTest.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@Test
public void testPropagatesAllStaticSensors() {
    app.enrichers().add(Enrichers.builder()
            .propagatingAll()
            .from(entity)
            .build());

    // all attributes propagated
    entity.sensors().set(TestEntity.NAME, "foo");
    entity.sensors().set(TestEntity.SEQUENCE, 2);
    
    EntityAsserts.assertAttributeEqualsEventually(app, TestEntity.NAME, "foo");
    EntityAsserts.assertAttributeEqualsEventually(app, TestEntity.SEQUENCE, 2);
    
    // notification-sensor propagated
    final AtomicReference<Integer> notif = new AtomicReference<Integer>();
    app.subscriptions().subscribe(app, TestEntity.MY_NOTIF, new SensorEventListener<Integer>() {
            @Override public void onEvent(SensorEvent<Integer> event) {
                notif.set(event.getValue());
            }});
    entity.sensors().emit(TestEntity.MY_NOTIF, 7);
    Asserts.eventually(AtomicReferences.supplier(notif), Predicates.equalTo(7));
}
 
Example #5
Source File: SensorPropagatingEnricherTest.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@Test
public void testPropagatesAllSensorsIncludesDynamicallyAdded() {
    AttributeSensor<String> dynamicAttribute = Sensors.newStringSensor("test.dynamicsensor.strattrib");
    BasicNotificationSensor<String> dynamicNotificationSensor = new BasicNotificationSensor<String>(String.class, "test.dynamicsensor.strnotif");
    
    app.enrichers().add(Enrichers.builder()
            .propagatingAll()
            .from(entity)
            .build());

    entity.sensors().set(dynamicAttribute, "foo");
    
    EntityAsserts.assertAttributeEqualsEventually(app, dynamicAttribute, "foo");
    
    // notification-sensor propagated
    final AtomicReference<String> notif = new AtomicReference<String>();
    app.subscriptions().subscribe(app, dynamicNotificationSensor, new SensorEventListener<String>() {
            @Override public void onEvent(SensorEvent<String> event) {
                notif.set(event.getValue());
            }});
    entity.sensors().emit(dynamicNotificationSensor, "mynotifval");
    Asserts.eventually(AtomicReferences.supplier(notif), Predicates.equalTo("mynotifval"));
}
 
Example #6
Source File: ServiceFailureDetectorTest.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@BeforeMethod(alwaysRun=true)
@Override
public void setUp() throws Exception {
    super.setUp();
    
    events = new CopyOnWriteArrayList<SensorEvent<FailureDescriptor>>();
    eventListener = new SensorEventListener<FailureDescriptor>() {
        @Override public void onEvent(SensorEvent<FailureDescriptor> event) {
            events.add(event);
        }
    };
    
    e1 = app.createAndManageChild(EntitySpec.create(TestEntity.class));
    e1.enrichers().add(ServiceStateLogic.newEnricherForServiceStateFromProblemsAndUp());
    
    app.getManagementContext().getSubscriptionManager().subscribe(e1, HASensors.ENTITY_FAILED, eventListener);
    app.getManagementContext().getSubscriptionManager().subscribe(e1, HASensors.ENTITY_RECOVERED, eventListener);
}
 
Example #7
Source File: RebindEntityTest.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
private void onReconstruct() {
    if (getConfig(SUBSCRIBE) != null) {
        subscriptions().getSubscriptionContext().subscribe(null, getConfig(SUBSCRIBE), new SensorEventListener<Object>() {
                @Override public void onEvent(SensorEvent<Object> event) {
                    events.add(event.getValue());
                }});
    }

    if (getConfig(PUBLISH) != null) {
        sensors().set(MY_SENSOR, getConfig(PUBLISH));
    }

    if (latching) {
        reconstructStartedLatch.countDown();
        try {
            reconstructContinuesLatch.await();
        } catch (InterruptedException e) {
            throw new RuntimeInterruptedException(e);
        }
    }
}
 
Example #8
Source File: LocalSubscriptionManagerTest.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@Test
public void testSubscribeToMemberAttributeChange() throws Exception {
    BasicGroup group = app.createAndManageChild(EntitySpec.create(BasicGroup.class));
    TestEntity member = app.createAndManageChild(EntitySpec.create(TestEntity.class));
    
    group.addMember(member);

    final List<SensorEvent<Integer>> events = new CopyOnWriteArrayList<SensorEvent<Integer>>();
    final CountDownLatch latch = new CountDownLatch(1);
    app.subscriptions().subscribeToMembers(group, TestEntity.SEQUENCE, new SensorEventListener<Integer>() {
        @Override public void onEvent(SensorEvent<Integer> event) {
            events.add(event);
            latch.countDown();
        }});
    member.sensors().set(TestEntity.SEQUENCE, 123);

    if (!latch.await(TIMEOUT_MS, TimeUnit.MILLISECONDS)) {
        fail("Timeout waiting for Event on parent TestEntity listener");
    }
    assertEquals(events.size(), 1);
    assertEquals(events.get(0).getValue(), (Integer)123);
    assertEquals(events.get(0).getSensor(), TestEntity.SEQUENCE);
    assertEquals(events.get(0).getSource().getId(), member.getId());
}
 
Example #9
Source File: LocalEntitiesTest.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@Test
public void testEffectorEmitsTransientSensor() throws Exception {
    HelloEntity h = app.createAndManageChild(EntitySpec.create(HelloEntity.class));
    app.start(ImmutableList.of(loc));
    
    final AtomicReference<SensorEvent<?>> evt = new AtomicReference<SensorEvent<?>>();
    app.subscriptions().subscribe(h, HelloEntity.ITS_MY_BIRTHDAY, new SensorEventListener<Object>() {
        @Override public void onEvent(SensorEvent<Object> event) {
            evt.set(event);
            synchronized (evt) {
                evt.notifyAll();
            }
        }});
    
    long startTime = System.currentTimeMillis();
    synchronized (evt) {
        h.setAge(5);
        evt.wait(5000);
    }
    assertNotNull(evt.get());
    assertEquals(HelloEntity.ITS_MY_BIRTHDAY, evt.get().getSensor());
    assertEquals(h, evt.get().getSource());
    assertNull(evt.get().getValue());
    assertTrue(System.currentTimeMillis() - startTime < 5000);  //shouldn't have blocked for all 5s
}
 
Example #10
Source File: AbstractWebAppFixtureIntegrationTest.java    From brooklyn-library with Apache License 2.0 5 votes vote down vote up
protected <T> SubscriptionHandle recordEvents(Entity entity, AttributeSensor<T> sensor, final List<SensorEvent<T>> events) {
    SensorEventListener<T> listener = new SensorEventListener<T>() {
        @Override public void onEvent(SensorEvent<T> event) {
            log.info("onEvent: {}", event);
            events.add(event);
        }
    };
    return entity.subscriptions().subscribe(entity, sensor, listener);
}
 
Example #11
Source File: CassandraFabricImpl.java    From brooklyn-library with Apache License 2.0 5 votes vote down vote up
protected void connectEnrichers() {
    // TODO Aggregate across sub-clusters

    subscriptions().subscribeToMembers(this, SERVICE_UP, new SensorEventListener<Boolean>() {
        @Override public void onEvent(SensorEvent<Boolean> event) {
            sensors().set(SERVICE_UP, calculateServiceUp());
        }
    });
}
 
Example #12
Source File: ServiceReplacerTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@BeforeMethod(alwaysRun=true)
public void setUp() throws Exception {
    super.setUp();
    
    loc = app.newSimulatedLocation();
    events = Lists.newCopyOnWriteArrayList();
    eventListener = new SensorEventListener<Object>() {
        @Override public void onEvent(SensorEvent<Object> event) {
            events.add(event);
        }
    };
}
 
Example #13
Source File: SubscriptionPerformanceTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Test(groups={"Integration", "Acceptance"})
public void testManyPublishedOneSubscriber() throws Exception {
    int numSubscribers = 1;
    int numIterations = NUM_ITERATIONS;
    double minRatePerSec = 100 * PERFORMANCE_EXPECTATION; // i.e. 100*10 events delivered per sec
    final AtomicInteger iter = new AtomicInteger();
    final int expectedCount = numIterations*numSubscribers;
    
    final AtomicInteger listenerCount = new AtomicInteger();
    final CountDownLatch completionLatch = new CountDownLatch(1);
    
    for (int i = 0; i < numSubscribers; i++) {
        subscriptionManager.subscribe(MutableMap.<String, Object>of("subscriber", i), entity, TestEntity.SEQUENCE, new SensorEventListener<Integer>() {
            @Override
            public void onEvent(SensorEvent<Integer> event) {
                int count = listenerCount.incrementAndGet();
                if (count >= expectedCount) completionLatch.countDown();
            }});
    }
    
    measure(PerformanceTestDescriptor.create()
            .summary("SubscriptionPerformanceTest.testManyPublishedOneSubscriber")
            .iterations(numIterations)
            .minAcceptablePerSecond(minRatePerSec)
            .job(new Runnable() {
                @Override
                public void run() {
                    entity.sensors().set(TestEntity.SEQUENCE, (iter.getAndIncrement()));
                }})
            .completionLatch(completionLatch));
}
 
Example #14
Source File: PrefixAndIdEnricher.java    From brooklyn-library with Apache License 2.0 5 votes vote down vote up
@Override
public void setEntity(final EntityLocal entity) {
    super.setEntity(entity);
    subscriptions().subscribe(entity, getConfig(MONITOR), new SensorEventListener<Object>() {
        @Override
        public void onEvent(SensorEvent<Object> event) {
            entity.sensors().set(SENSOR, getConfig(PREFIX) + entity.getId());
        }
    });
    highlightTriggers(getConfig(MONITOR), null);
}
 
Example #15
Source File: DynamicGroupImpl.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Override
public <T> void addSubscription(Entity producer, Sensor<T> sensor, final Predicate<? super SensorEvent<? super T>> filter) {
    SensorEventListener<T> listener = new SensorEventListener<T>() {
            @Override
            public void onEvent(SensorEvent<T> event) {
                if (filter.apply(event)) onEntityChanged(event.getSource());
            }
        };
    subscriptions().subscribe(producer, sensor, listener);
}
 
Example #16
Source File: EntityPerformanceTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Test(groups={"Integration", "Acceptance"})
public void testUpdateAttributeWithNoopListeners() {
    final int numIterations = numIterations();
    double minRatePerSec = 1000 * PERFORMANCE_EXPECTATION;
    final AtomicInteger i = new AtomicInteger();
    final AtomicInteger lastVal = new AtomicInteger();
    
    app.subscriptions().subscribe(entity, TestEntity.SEQUENCE, new SensorEventListener<Integer>() {
            @Override public void onEvent(SensorEvent<Integer> event) {
                lastVal.set(event.getValue());
            }});
    
    measure(PerformanceTestDescriptor.create()
            .summary("EntityPerformanceTest.testUpdateAttributeWithNoopListeners")
            .iterations(numIterations)
            .minAcceptablePerSecond(minRatePerSec)
            .job(new Runnable() {
                @Override
                public void run() {
                    entity.sensors().set(TestEntity.SEQUENCE, (i.getAndIncrement()));
                }}));
    
    Asserts.succeedsEventually(MutableMap.of("timeout", TIMEOUT_MS), new Runnable() {
        @Override
        public void run() {
            assertTrue(lastVal.get() >= numIterations, "lastVal="+lastVal+"; numIterations="+numIterations);
        }});
}
 
Example #17
Source File: LocalSubscriptionManagerTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Test(groups="Integration")
public void testConcurrentSubscribingAndPublishing() throws Exception {
    final AtomicReference<Exception> threadException = new AtomicReference<Exception>();
    TestEntity entity = app.createAndManageChild(EntitySpec.create(TestEntity.class));
    
    // Repeatedly subscribe and unsubscribe, so listener-set constantly changing while publishing to it.
    // First create a stable listener so it is always the same listener-set object.
    Thread thread = new Thread() {
        @Override
        public void run() {
            try {
                SensorEventListener<Object> noopListener = new SensorEventListener<Object>() {
                    @Override public void onEvent(SensorEvent<Object> event) {
                    }
                };
                app.subscriptions().subscribe(null, TestEntity.SEQUENCE, noopListener);
                while (!Thread.currentThread().isInterrupted()) {
                    SubscriptionHandle handle = app.subscriptions().subscribe(null, TestEntity.SEQUENCE, noopListener);
                    app.subscriptions().unsubscribe(null, handle);
                }
            } catch (Exception e) {
                threadException.set(e);
            }
        }
    };
    
    try {
        thread.start();
        for (int i = 0; i < 10000; i++) {
            entity.sensors().set(TestEntity.SEQUENCE, i);
        }
    } finally {
        thread.interrupt();
    }

    if (threadException.get() != null) throw threadException.get();
}
 
Example #18
Source File: BasicSubscriptionContext.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
/**
 * @deprecated since 0.11.0; explicit groovy utilities/support will be deleted.
 */
@Deprecated
@SuppressWarnings("rawtypes")
private <T> SensorEventListener<T> toSensorEventListener(final Closure c) {
    return new SensorEventListener<T>() {
        @Override public void onEvent(SensorEvent<T> event) {
            c.call(event);
        }
    };
}
 
Example #19
Source File: EntityCleanupLongevityTestFixture.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
protected TestApplication newApp() {
    final TestApplication result = managementContext.getEntityManager().createEntity(EntitySpec.create(TestApplication.class));
    weakApps.put(result, null);
    TestEntity entity = result.createAndManageChild(EntitySpec.create(TestEntity.class));
    result.subscriptions().subscribe(entity, TestEntity.NAME, new SensorEventListener<String>() {
        @Override public void onEvent(SensorEvent<String> event) {
            result.sensors().set(TestApplication.MY_ATTRIBUTE, event.getValue());
        }});
    entity.sensors().set(TestEntity.NAME, "myname");
    return result;
}
 
Example #20
Source File: SubscriptionTracker.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
public <T> SubscriptionHandle subscribe(Map<String, ?> flags, Entity producer, Sensor<T> sensor, SensorEventListener<? super T> listener) {
    SubscriptionHandle handle = context.subscribe(flags, producer, sensor, listener);
    synchronized (subscriptions) {
        subscriptions.put(producer, handle);
    }
    return handle;
}
 
Example #21
Source File: SubscriptionTracker.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
/** @see SubscriptionContext#subscribeToChildren(Entity, Sensor, SensorEventListener) */
public <T> SubscriptionHandle subscribeToChildren(Entity parent, Sensor<T> sensor, SensorEventListener<? super T> listener) {
    SubscriptionHandle handle = context.subscribeToChildren(parent, sensor, listener);
    synchronized (subscriptions) {
        subscriptions.put(parent, handle);
    }
    return handle;
}
 
Example #22
Source File: SubscriptionTracker.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
/**
 * @see SubscriptionContext#subscribeToMembers(Group, Sensor, SensorEventListener)
 */
public <T> SubscriptionHandle subscribeToMembers(Group parent, Sensor<T> sensor, SensorEventListener<? super T> listener) {
    SubscriptionHandle handle = context.subscribeToMembers(parent, sensor, listener);
    synchronized (subscriptions) {
        subscriptions.put(parent, handle);
    }
    return handle;
}
 
Example #23
Source File: AbstractSubscriptionManager.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
/** @see SubscriptionManager#subscribe(Map, Entity, Sensor, SensorEventListener) */
@Override
public final  <T> SubscriptionHandle subscribeToChildren(Map<String, Object> flags, final Entity parent, Sensor<T> sensor, SensorEventListener<? super T> listener) {
    Predicate<SensorEvent<T>> eventFilter = new Predicate<SensorEvent<T>>() {
        @Override
        public boolean apply(SensorEvent<T> input) {
            return parent != null && input.getSource() != null && parent.equals(input.getSource().getParent());
        }
    };
    flags.put("eventFilter", eventFilter);
    return subscribe(flags, null, sensor, listener);
}
 
Example #24
Source File: AbstractSubscriptionManager.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
/** @see SubscriptionManager#subscribe(Map, Entity, Sensor, SensorEventListener) */
@Override
public final  <T> SubscriptionHandle subscribeToMembers(Map<String, Object> flags, final Group parent, Sensor<T> sensor, SensorEventListener<? super T> listener) {
    Predicate<SensorEvent<T>> eventFilter = new Predicate<SensorEvent<T>>() {
        @Override
        public boolean apply(SensorEvent<T> input) {
            return parent.getMembers().contains(input.getSource());
        }
    };
    flags.put("eventFilter", eventFilter);
    return subscribe(flags, null, sensor, listener);
}
 
Example #25
Source File: DynamicMultiGroupTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Test
public void testRemovesEmptyBuckets() {
    Group group = app.createAndManageChild(EntitySpec.create(BasicGroup.class));
    final DynamicMultiGroup dmg = app.createAndManageChild(
            EntitySpec.create(DynamicMultiGroup.class)
                    .configure(ENTITY_FILTER, instanceOf(TestEntity.class))
                    .configure(BUCKET_FUNCTION, bucketFromAttribute(SENSOR))
    );
    app.subscriptions().subscribeToChildren(group, SENSOR, new SensorEventListener<String>() {
        @Override
        public void onEvent(SensorEvent<String> event) { dmg.rescanEntities(); }
    });

    EntitySpec<TestEntity> childSpec = EntitySpec.create(TestEntity.class);
    TestEntity child1 = app.createAndManageChild(EntitySpec.create(childSpec).displayName("child1"));
    TestEntity child2 = app.createAndManageChild(EntitySpec.create(childSpec).displayName("child2"));

    // Expect two buckets: bucketA and bucketB 
    child1.sensors().set(SENSOR, "bucketA");
    child2.sensors().set(SENSOR, "bucketB");
    dmg.rescanEntities();
    Group bucketA = (Group) find(dmg.getChildren(), displayNameEqualTo("bucketA"), null);
    Group bucketB = (Group) find(dmg.getChildren(), displayNameEqualTo("bucketB"), null);
    assertNotNull(bucketA);
    assertNotNull(bucketB);
    
    // Expect second bucket to be removed when empty 
    child1.sensors().set(SENSOR, "bucketA");
    child2.sensors().set(SENSOR, "bucketA");
    dmg.rescanEntities();
    bucketA = (Group) find(dmg.getChildren(), displayNameEqualTo("bucketA"), null);
    bucketB = (Group) find(dmg.getChildren(), displayNameEqualTo("bucketB"), null);
    assertNotNull(bucketA);
    assertNull(bucketB);
}
 
Example #26
Source File: DynamicClusterTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Test
public void defaultRemovalStrategyShutsDownNewestFirstWhenResizing() throws Exception {
    final List<Entity> creationOrder = Lists.newArrayList();
    
    DynamicCluster cluster = app.createAndManageChild(EntitySpec.create(DynamicCluster.class)
            .configure("initialSize", 0)
            .configure("memberSpec", EntitySpec.create(TestEntity.class)));

    cluster.subscriptions().subscribe(cluster, AbstractEntity.CHILD_ADDED, new SensorEventListener<Entity>() {
        @Override public void onEvent(SensorEvent<Entity> event) {
            if (event.getValue() instanceof TestEntity) {
                creationOrder.add(event.getValue());
            }
        }});

    cluster.start(ImmutableList.of(loc));
    cluster.resize(1);
    
    //Prevent the two entities created in the same ms
    //so that the removal strategy can always choose the 
    //entity created next
    Thread.sleep(1);
    
    cluster.resize(2);
    Asserts.eventually(Suppliers.ofInstance(creationOrder), CollectionFunctionals.sizeEquals(2));
    assertEquals(cluster.getCurrentSize(), (Integer)2);
    assertEquals(ImmutableSet.copyOf(cluster.getMembers()), ImmutableSet.copyOf(creationOrder), "actual="+cluster.getMembers());

    // Now stop one
    cluster.resize(1);
    assertEquals(cluster.getCurrentSize(), (Integer)1);
    assertEquals(ImmutableList.copyOf(cluster.getMembers()), creationOrder.subList(0, 1));
}
 
Example #27
Source File: SensorPropagatingEnricherTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
protected void assertAttributeNotRepublished(Entity entity, AttributeSensor<String> sensor) {
    final List<SensorEvent<String>> events = Lists.newCopyOnWriteArrayList();
    app.subscriptions().subscribe(entity, sensor, new SensorEventListener<String>() {
        @Override public void onEvent(SensorEvent<String> event) {
            events.add(event);
        }});

    app.sensors().set(sensor, "myval");
    assertSizeEventually(events, 1);
    assertSizeContinually(events, 1, Duration.millis(100));
}
 
Example #28
Source File: InvokeEffectorOnCollectionSensorChangeTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Test
public void testPublishesIsBusySensor() {
    final List<Boolean> isBusyValues = new CopyOnWriteArrayList<>();
    testEntity.subscriptions().subscribe(testEntity, IS_BUSY_SENSOR, new SensorEventListener<Boolean>() {
        @Override
        public void onEvent(SensorEvent<Boolean> event) {
            isBusyValues.add(event.getValue());
        }
    });
    addSetChangePolicy(true, false);
    testEntity.sensors().set(DEFAULT_SENSOR, ImmutableSet.of(1));
    List<Boolean> expected = ImmutableList.of(false, true, false);
    Asserts.eventually(Suppliers.ofInstance(isBusyValues), Predicates.equalTo(expected));
}
 
Example #29
Source File: ApplicationLifecycleStateTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
/**
 * Tests concurrent modifications to a sensor, asserting that the last notification the subscribers 
 * receives equals the last value that sensor has.
 * 
 * Prior to this being fixed (see https://github.com/apache/brooklyn-server/pull/622), it caused 
 * problems in ComputeServiceIndicatorsFromChildrenAndMembers: it saw a child transition 
 * from "running" to "starting", and thus emitted the on-fire event for the parent entity. As asserted
 * by this test, the enricher should now always receive the events in the correct order (e.g. "starting",
 * "running").
 */
@Test
public void testSettingSensorFromThreads() {
    final TestApplication app = mgmt.getEntityManager().createEntity(EntitySpec.create(TestApplication.class));
    final AttributeSensor<String> TEST_SENSOR = Sensors.newStringSensor("test.sensor");

    final AtomicReference<String> lastSeenState = new AtomicReference<>();
    app.subscriptions().subscribe(app, TEST_SENSOR, new SensorEventListener<String>() {
        @Override
        public void onEvent(SensorEvent<String> event) {
            lastSeenState.set(event.getValue());
            log.debug("seen event=" + event);
        }
    });

    Task<?> first = mgmt.getExecutionManager().submit("setting test sensor", () -> {
            app.sensors().set(TEST_SENSOR, "first");
            log.debug("set first");
        });
    Task<?> second = mgmt.getExecutionManager().submit("setting test sensor", () -> {
            app.sensors().set(TEST_SENSOR, "second");
            log.debug("set second");
        });
    first.blockUntilEnded();
    second.blockUntilEnded();

    Asserts.succeedsEventually(new Runnable() {
        @Override
        public void run() {
            EntityAsserts.assertAttributeEquals(app, TEST_SENSOR, lastSeenState.get());
        }
    });
}
 
Example #30
Source File: LocalEntitiesTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Test
public void testEffectorEmitsAttributeSensor() throws Exception {
    final HelloEntity h = app.createAndManageChild(EntitySpec.create(HelloEntity.class));
    app.start(ImmutableList.of(loc));
    
    final AtomicReference<SensorEvent<?>> evt = new AtomicReference<SensorEvent<?>>();
    final CountDownLatch latch = new CountDownLatch(1);
    
    app.subscriptions().subscribe(h, HelloEntity.AGE, new SensorEventListener<Integer>() {
        @Override public void onEvent(SensorEvent<Integer> event) {
            evt.set(event);
            latch.countDown();
        }});
    
    long startTime = System.currentTimeMillis();
    
    h.invoke(HelloEntity.SET_AGE, ImmutableMap.of("age", 5));
    assertTrue(latch.await(5000, TimeUnit.MILLISECONDS));

    // observed intermittent failure 2 May 2012. and 14 Jun "after 2 ms". spurious wakeups.
    // code added above to guard against this. (if problem does not recur, remove these comments!)
    assertNotNull(evt.get(), "null response after "+(System.currentTimeMillis()-startTime)+" ms");
    assertEquals(HelloEntity.AGE, evt.get().getSensor());
    assertEquals(h, evt.get().getSource());
    assertEquals(5, evt.get().getValue());
    assertTrue(System.currentTimeMillis() - startTime < 5000);  //shouldn't have blocked for all 5s
}