Java Code Examples for org.apache.brooklyn.core.sensor.Sensors#newSensor()

The following examples show how to use org.apache.brooklyn.core.sensor.Sensors#newSensor() . 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: SoftwareProcessEntityLatchTest.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
public void doTestLatchBlocks(ConfigKey<Boolean> latch, List<String> preLatchEvents, Object latchValue, Function<? super MyService, Void> customAssertFn) throws Exception {
    final AttributeSensor<Object> latchSensor = Sensors.newSensor(Object.class, "latch");
    final MyService entity = app.createAndManageChild(EntitySpec.create(MyService.class)
            .configure(ConfigKeys.newConfigKey(Object.class, latch.getName()), (Object)DependentConfiguration.attributeWhenReady(app, latchSensor)));

    final Task<Void> task;
    final Task<Void> startTask = Entities.invokeEffector(app, app, MyService.START, ImmutableMap.of("locations", ImmutableList.of(loc)));
    if (latch != SoftwareProcess.STOP_LATCH) {
        task = startTask;
    } else {
        startTask.get(Duration.THIRTY_SECONDS);
        task = Entities.invokeEffector(app, app, MyService.STOP);
    }

    assertEffectorBlockingDetailsEventually(entity, task.getDisplayName(), "Waiting for config " + latch.getName());
    assertDriverEventsEquals(entity, preLatchEvents);
    assertFalse(task.isDone());

    app.sensors().set(latchSensor, latchValue);

    customAssertFn.apply(entity);

    task.get(Duration.THIRTY_SECONDS);
    assertDriverEventsEquals(entity, getLatchPostTasks(latch));
}
 
Example 2
Source File: ServiceStateLogicTest.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@Test
public void testQuorumWithStringStates() {
    final DynamicCluster cluster = app.createAndManageChild(EntitySpec.create(DynamicCluster.class)
            .configure(DynamicCluster.MEMBER_SPEC, EntitySpec.create(TestEntityWithoutEnrichers.class))
            .configure(DynamicCluster.INITIAL_SIZE, 1));

    cluster.start(ImmutableList.of(app.newSimulatedLocation()));
    EntityAsserts.assertGroupSizeEqualsEventually(cluster, 1);

    //manually set state to healthy as enrichers are disabled
    EntityInternal child = (EntityInternal) cluster.getMembers().iterator().next();
    child.sensors().set(Attributes.SERVICE_STATE_ACTUAL, Lifecycle.RUNNING);
    child.sensors().set(Attributes.SERVICE_UP, Boolean.TRUE);

    EntityAsserts.assertAttributeEqualsEventually(cluster, Attributes.SERVICE_STATE_ACTUAL, Lifecycle.RUNNING);

    //set untyped service state, the quorum check should be able to handle coercion
    AttributeSensor<Object> stateSensor = Sensors.newSensor(Object.class, Attributes.SERVICE_STATE_ACTUAL.getName());
    child.sensors().set(stateSensor, "running");

    EntityAsserts.assertAttributeEqualsContinually(cluster, Attributes.SERVICE_STATE_ACTUAL, Lifecycle.RUNNING);
}
 
Example 3
Source File: OnPublicNetworkEnricherTest.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@DataProvider(name = "variants")
public Object[][] provideVariants() {
    AttributeSensor<HostAndPort> hostAndPortSensor = Sensors.newSensor(HostAndPort.class, "test.endpoint");
    List<Object[]> result = Lists.newArrayList();
    for (Timing setSensor : Timing.values()) {
        for (Timing createAssociation : Timing.values()) {
            for (Timing addLocation : Timing.values()) {
                result.add(new Object[] {setSensor, createAssociation, addLocation, Attributes.MAIN_URI, 
                        URI.create("http://127.0.0.1:1234/my/path"), "main.uri.mapped.public", "http://mypublichost:5678/my/path"});
                result.add(new Object[] {setSensor, createAssociation, addLocation, TestEntity.NAME, 
                        "http://127.0.0.1:1234/my/path", "test.name.mapped.public", "http://mypublichost:5678/my/path"});
                result.add(new Object[] {setSensor, createAssociation, addLocation, Attributes.HTTP_PORT, 
                        1234, "http.endpoint.mapped.public", "mypublichost:5678"});
                result.add(new Object[] {setSensor, createAssociation, addLocation, TestEntity.NAME, 
                        "1234", "test.name.mapped.public", "mypublichost:5678"});
                result.add(new Object[] {setSensor, createAssociation, addLocation, TestEntity.NAME, 
                        "127.0.0.1:1234", "test.name.mapped.public", "mypublichost:5678"});
                result.add(new Object[] {setSensor, createAssociation, addLocation, hostAndPortSensor, 
                        HostAndPort.fromString("127.0.0.1:1234"), "test.endpoint.mapped.public", "mypublichost:5678"});
            }
        }
    }
    return result.toArray(new Object[result.size()][]);
}
 
Example 4
Source File: OnSubnetNetworkEnricherTest.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@DataProvider(name = "variants")
public Object[][] provideVariants() {
    AttributeSensor<HostAndPort> hostAndPortSensor = Sensors.newSensor(HostAndPort.class, "test.endpoint");
    List<Object[]> result = Lists.newArrayList();
    for (Timing setSensor : Timing.values()) {
        for (Timing addLocation : Timing.values()) {
            result.add(new Object[] {setSensor, addLocation, Attributes.MAIN_URI, 
                    URI.create("http://"+publicIp+":1234/my/path"), "main.uri.mapped.subnet", "http://"+privateIp+":1234/my/path"});
            result.add(new Object[] {setSensor, addLocation, TestEntity.NAME, 
                    "http://"+publicIp+":1234/my/path", "test.name.mapped.subnet", "http://"+privateIp+":1234/my/path"});
            result.add(new Object[] {setSensor, addLocation, Attributes.HTTP_PORT, 
                    1234, "http.endpoint.mapped.subnet", privateIp+":1234"});
            result.add(new Object[] {setSensor, addLocation, TestEntity.NAME, 
                    "1234", "test.name.mapped.subnet", privateIp+":1234"});
            result.add(new Object[] {setSensor, addLocation, TestEntity.NAME, 
                    publicIp+":1234", "test.name.mapped.subnet", privateIp+":1234"});
            result.add(new Object[] {setSensor, addLocation, hostAndPortSensor, 
                    HostAndPort.fromString(publicIp+":1234"), "test.endpoint.mapped.subnet", privateIp+":1234"});
        }
    }
    return result.toArray(new Object[result.size()][]);
}
 
Example 5
Source File: OnPublicNetworkEnricherTest.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@Test
public <T> void testIgnoresNonMatchingSensors() throws Exception {
    AttributeSensor<URI> sensor1 = Sensors.newSensor(URI.class, "my.different");
    AttributeSensor<URL> sensor2 = Sensors.newSensor(URL.class, "my.different2");
    AttributeSensor<String> sensor3 = Sensors.newStringSensor("my.different3");
    AttributeSensor<Integer> sensor4 = Sensors.newIntegerSensor("my.different4");
    AttributeSensor<HostAndPort> sensor5 = Sensors.newSensor(HostAndPort.class, "my.different5");

    entity.sensors().set(Attributes.SUBNET_ADDRESS, "127.0.0.1");
    entity.sensors().set(sensor1, URI.create("http://127.0.0.1:1234/my/path"));
    entity.sensors().set(sensor2, new URL("http://127.0.0.1:1234/my/path"));
    entity.sensors().set(sensor3, "http://127.0.0.1:1234/my/path");
    entity.sensors().set(sensor4, 1234);
    entity.sensors().set(sensor5, HostAndPort.fromParts("127.0.0.1", 1234));
    portForwardManager.associate("myPublicIp", HostAndPort.fromParts("mypublichost", 5678), machine, 1234);
    entity.addLocations(ImmutableList.of(machine));
    
    entity.enrichers().add(EnricherSpec.create(OnPublicNetworkEnricher.class));

    Map<AttributeSensor<?>, Object> allSensors = entity.sensors().getAll();
    String errMsg = "sensors="+allSensors;
    for (AttributeSensor<?> sensor : allSensors.keySet()) {
        String name = sensor.getName();
        assertFalse(name.startsWith("my.different") && sensor.getName().contains("public"), errMsg);
    }
}
 
Example 6
Source File: DslYamlTest.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@Test
public void testDeferredDslAttributeFacadeCrossAppFails() throws Exception {
    final Entity app0 = createAndStartApplication(
            "services:",
            "- type: " + BasicApplication.class.getName());
    final Entity app = createAndStartApplication(
            "services:",
            "- type: " + BasicApplication.class.getName(),
            "  brooklyn.config:",
            "    dest: $brooklyn:attributeWhenReady(\"targetEntity\").attributeWhenReady(\"entity.id\")");
    AttributeSensor<Entity> targetEntitySensor = Sensors.newSensor(Entity.class, "targetEntity");
    app.sensors().set(targetEntitySensor, app0);
    try {
        getConfigEventually(app, DEST);
        Asserts.shouldHaveFailedPreviously("Cross-app DSL not allowed");
    } catch (ExecutionException e) {
        Asserts.expectedFailureContains(e, "not in scope 'global'");
    }
}
 
Example 7
Source File: SensorPropagatingEnricherTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Test
public void testPropagatorDefaultsToProducerAsSelf() throws Exception {
    AttributeSensor<String> sourceSensor = Sensors.newSensor(String.class, "mySensor");
    AttributeSensor<String> targetSensor = Sensors.newSensor(String.class, "myTarget");

    app.enrichers().add(EnricherSpec.create(Propagator.class)
            .configure(Propagator.PRODUCER, app)
            .configure(Propagator.SENSOR_MAPPING, ImmutableMap.of(sourceSensor, targetSensor)));

    app.sensors().set(sourceSensor, "myval");
    EntityAsserts.assertAttributeEqualsEventually(app, targetSensor, "myval");
}
 
Example 8
Source File: TestSensorTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Test
public void testDoesNotAbortIfConditionUnsatisfied() throws Exception {
    final AttributeSensor<Lifecycle> serviceStateSensor = Sensors.newSensor(Lifecycle.class,
            "test.service.state", "Actual lifecycle state of the service (for testing)");

    final TestEntity entity = app.addChild(EntitySpec.create(TestEntity.class));
    
    TestSensor testCase = app.createAndManageChild(EntitySpec.create(TestSensor.class)
            .configure(TestSensor.TIMEOUT, Asserts.DEFAULT_LONG_TIMEOUT)
            .configure(TestSensor.TARGET_ENTITY, entity)
            .configure(TestSensor.SENSOR_NAME, serviceStateSensor.getName())
            .configure(TestSensor.ASSERTIONS, newMapAssertion("equals", Lifecycle.RUNNING))
            .configure(TestSensor.ABORT_CONDITIONS, newMapAssertion("equals", Lifecycle.ON_FIRE)));

    // Set the state to running while we are starting (so that the abort-condition will have
    // been checked).
    entity.sensors().set(serviceStateSensor, Lifecycle.STARTING);
    executor.submit(new Runnable() {
        @Override
        public void run() {
            Time.sleep(Duration.millis(50));
            entity.sensors().set(serviceStateSensor, Lifecycle.RUNNING);
        }});
    
    app.start(locs);
    
    assertTestSensorSucceeds(testCase);
}
 
Example 9
Source File: EnrichersYamlTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Test
public void testWithTransformerEventFunctionUsingDsl() throws Exception {
    // See explanation in testWithTransformerValueFunctionUsingDsl (for why this test's DSL 
    // object looks so complicated!)
    
    AttributeSensor<Object> sourceSensor = Sensors.newSensor(Object.class, "mySourceSensor");
    AttributeSensor<Object> targetSensor = Sensors.newSensor(Object.class, "myTargetSensor");
    AttributeSensor<Object> otherSensor = Sensors.newSensor(Object.class, "myOtherSensor");
    
    Entity app = createAndStartApplication(loadYaml("test-entity-basic-template.yaml",
                "  id: parentId",
                "  brooklyn.enrichers:",
                "    - enricherType: org.apache.brooklyn.enricher.stock.Transformer",
                "      brooklyn.config:",
                "        enricher.sourceSensor: $brooklyn:sensor(\""+sourceSensor.getName()+"\")",
                "        enricher.targetSensor: $brooklyn:sensor(\""+targetSensor.getName()+"\")",
                "        enricher.transformation.fromevent:",
                "          $brooklyn:object:",
                "            type: "+EnrichersYamlTest.class.getName(),
                "            factoryMethod.name: constantOfSingletonMapValue",
                "            factoryMethod.args:",
                "            - \"IGNORED\": $brooklyn:attributeWhenReady(\""+otherSensor.getName()+"\")"));
    waitForApplicationTasks(app);
    
    log.info("App started:");
    final TestEntity entity = (TestEntity) app.getChildren().iterator().next();
    Dumper.dumpInfo(app);
    
    entity.sensors().set(otherSensor, "myval");
    entity.sensors().set(sourceSensor, "any-val"); // trigger enricher
    EntityAsserts.assertAttributeEqualsEventually(entity, targetSensor, "myval");
}
 
Example 10
Source File: SensorPropagatingEnricherTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Test
public void testPropagatorAvoidsInfiniteLoopInPropagateAllWithImplicitProducer() throws Exception {
    AttributeSensor<String> mySensor = Sensors.newSensor(String.class, "mySensor");

    EnricherSpec<?> spec = EnricherSpec.create(Propagator.class)
            .configure(Propagator.PROPAGATING_ALL, true);

    assertAddEnricherThrowsIllegalStateException(spec, "when publishing to own entity");
    assertAttributeNotRepublished(app, mySensor);
}
 
Example 11
Source File: DslYamlTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Test
public void testDeferredDslObjectAsFirstArgument() throws Exception {
    final Entity app = createAndStartApplication(
            "services:",
            "- type: " + BasicApplication.class.getName(),
            "  location: localhost",
            "  brooklyn.config:",
            "    dest: $brooklyn:attributeWhenReady(\"targetValue\").config(\"spec.final\")");
    AttributeSensor<Location> targetValueSensor = Sensors.newSensor(Location.class, "targetValue");
    app.sensors().set(targetValueSensor, Iterables.getOnlyElement(app.getLocations()));
    assertEquals(getConfigEventually(app, DEST), "localhost");
}
 
Example 12
Source File: OnSubnetNetworkEnricherTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Test
public <T> void testTransformsAllMatchingSensors() throws Exception {
    AttributeSensor<URI> stronglyTypedUri = Sensors.newSensor(URI.class, "strongly.typed.uri");
    AttributeSensor<String> stringUri = Sensors.newStringSensor("string.uri");
    AttributeSensor<URL> stronglyTypedUrl = Sensors.newSensor(URL.class, "strongly.typed.url");
    AttributeSensor<String> stringUrl = Sensors.newStringSensor("string.url");
    AttributeSensor<Integer> intPort = Sensors.newIntegerSensor("int.port");
    AttributeSensor<String> stringPort = Sensors.newStringSensor("string.port");
    AttributeSensor<HostAndPort> hostAndPort = Sensors.newSensor(HostAndPort.class, "hostAndPort.endpoint");
    AttributeSensor<String> stringHostAndPort = Sensors.newStringSensor("stringHostAndPort.endpoint");

    entity.sensors().set(Attributes.SUBNET_ADDRESS, privateIp);
    entity.sensors().set(stronglyTypedUri, URI.create("http://"+publicIp+":1234/my/path"));
    entity.sensors().set(stringUri, "http://"+publicIp+":1234/my/path");
    entity.sensors().set(stronglyTypedUrl, new URL("http://"+publicIp+":1234/my/path"));
    entity.sensors().set(stringUrl, "http://"+publicIp+":1234/my/path");
    entity.sensors().set(intPort, 1234);
    entity.sensors().set(stringPort, "1234");
    entity.sensors().set(hostAndPort, HostAndPort.fromParts(""+publicIp+"", 1234));
    entity.sensors().set(stringHostAndPort, ""+publicIp+":1234");
    entity.addLocations(ImmutableList.of(machine));
    
    entity.enrichers().add(EnricherSpec.create(OnSubnetNetworkEnricher.class));

    assertAttributeEqualsEventually("strongly.typed.uri.mapped.subnet", "http://"+privateIp+":1234/my/path");
    assertAttributeEqualsEventually("string.uri.mapped.subnet", "http://"+privateIp+":1234/my/path");
    assertAttributeEqualsEventually("strongly.typed.url.mapped.subnet", "http://"+privateIp+":1234/my/path");
    assertAttributeEqualsEventually("string.url.mapped.subnet", "http://"+privateIp+":1234/my/path");
    assertAttributeEqualsEventually("int.endpoint.mapped.subnet", ""+privateIp+":1234");
    assertAttributeEqualsEventually("string.endpoint.mapped.subnet", ""+privateIp+":1234");
    assertAttributeEqualsEventually("hostAndPort.endpoint.mapped.subnet", ""+privateIp+":1234");
    assertAttributeEqualsEventually("stringHostAndPort.endpoint.mapped.subnet", ""+privateIp+":1234");
}
 
Example 13
Source File: SensorPropagatingEnricherTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Test
public void testPropagatorAvoidsInfiniteLoopInSameSensorMapping() throws Exception {
    AttributeSensor<String> mySensor = Sensors.newSensor(String.class, "mySensor");

    EnricherSpec<?> spec = EnricherSpec.create(Propagator.class)
            .configure(Propagator.PRODUCER, app)
            .configure(Propagator.SENSOR_MAPPING, ImmutableMap.of(mySensor, mySensor));
    
    assertAddEnricherThrowsIllegalStateException(spec, "when publishing to own entity");
    assertAttributeNotRepublished(app, mySensor);
}
 
Example 14
Source File: WindowsPerformanceCounterFeed.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Override
public void onSuccess(WinRmToolResponse val) {
    for (String pollResponse : val.getStdOut().split("\r\n")) {
        if (Strings.isNullOrEmpty(pollResponse)) {
            continue;
        }
        String path = pollResponse.substring(0, OUTPUT_COLUMN_WIDTH - 1);
        // The performance counter output prepends the sensor name with "\\<machinename>" so we need to remove it
        Matcher machineNameLookbackMatcher = MACHINE_NAME_LOOKBACK_PATTERN.matcher(path);
        if (!machineNameLookbackMatcher.find()) {
            continue;
        }
        String name = machineNameLookbackMatcher.group(0).trim();
        String rawValue = pollResponse.substring(OUTPUT_COLUMN_WIDTH).replaceAll("^\\s+", "");
        WindowsPerformanceCounterPollConfig<?> config = getPollConfig(name);
        Class<?> clazz = config.getSensor().getType();
        AttributeSensor<Object> attribute = (AttributeSensor<Object>) Sensors.newSensor(clazz, config.getSensor().getName(), config.getDescription());
        try {
            Object value = TypeCoercions.coerce(rawValue, TypeToken.of(clazz));
            entity.sensors().set(attribute, value);
        } catch (Exception e) {
            Exceptions.propagateIfFatal(e);
            if (failedAttributes.add(attribute)) {
                log.warn("Failed to coerce value '{}' to {} for {} -> {}", new Object[] {rawValue, clazz, entity, attribute});
            } else {
                if (log.isTraceEnabled()) log.trace("Failed (repeatedly) to coerce value '{}' to {} for {} -> {}", new Object[] {rawValue, clazz, entity, attribute});
            }
        }
    }
}
 
Example 15
Source File: WindowsPerformanceCounterFeed.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Override
public void onFailure(WinRmToolResponse val) {
    if (val == null) {
        log.trace("Windows Performance Counter not executed since there is still now WinRmMachineLocation");
        return;
    }
    log.error("Windows Performance Counter query did not respond as expected. exitcode={} stdout={} stderr={}",
            new Object[]{val.getStatusCode(), val.getStdOut(), val.getStdErr()});
    for (WindowsPerformanceCounterPollConfig<?> config : polls) {
        Class<?> clazz = config.getSensor().getType();
        AttributeSensor<?> attribute = Sensors.newSensor(clazz, config.getSensor().getName(), config.getDescription());
        entity.sensors().set(attribute, null);
    }
}
 
Example 16
Source File: OnSubnetNetworkEnricherTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Test
public <T> void testIgnoresNonMatchingSensors() throws Exception {
    AttributeSensor<URI> sensor1 = Sensors.newSensor(URI.class, "my.different");
    AttributeSensor<URL> sensor2 = Sensors.newSensor(URL.class, "my.different2");
    AttributeSensor<String> sensor3 = Sensors.newStringSensor("my.different3");
    AttributeSensor<Integer> sensor4 = Sensors.newIntegerSensor("my.different4");
    AttributeSensor<HostAndPort> sensor5 = Sensors.newSensor(HostAndPort.class, "my.different5");

    entity.sensors().set(Attributes.SUBNET_ADDRESS, privateIp);
    entity.sensors().set(sensor1, URI.create("http://"+publicIp+":1234/my/path"));
    entity.sensors().set(sensor2, new URL("http://"+publicIp+":1234/my/path"));
    entity.sensors().set(sensor3, "http://"+publicIp+":1234/my/path");
    entity.sensors().set(sensor4, 1234);
    entity.sensors().set(sensor5, HostAndPort.fromParts(publicIp, 1234));
    entity.addLocations(ImmutableList.of(machine));
    
    entity.enrichers().add(EnricherSpec.create(OnSubnetNetworkEnricher.class));

    Asserts.succeedsContinually(ImmutableMap.of("timeout", VERY_SHORT_WAIT), new Runnable() {
        @Override public void run() {
            Map<AttributeSensor<?>, Object> allSensors = entity.sensors().getAll();
            String errMsg = "sensors="+allSensors;
            for (AttributeSensor<?> sensor : allSensors.keySet()) {
                String name = sensor.getName();
                assertFalse(name.startsWith("my.different") && sensor.getName().contains("subnet"), errMsg);
            }
        }});
}
 
Example 17
Source File: SensorPropagatingEnricherTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Test
public void testPropagatorAvoidsInfiniteLoopInPropagateAll() throws Exception {
    AttributeSensor<String> mySensor = Sensors.newSensor(String.class, "mySensor");

    EnricherSpec<?> spec = EnricherSpec.create(Propagator.class)
            .configure(Propagator.PRODUCER, app)
            .configure(Propagator.PROPAGATING_ALL, true);

    assertAddEnricherThrowsIllegalStateException(spec, "when publishing to own entity");
    assertAttributeNotRepublished(app, mySensor);
}
 
Example 18
Source File: EntityPredicates.java    From brooklyn-server with Apache License 2.0 4 votes vote down vote up
public static Predicate<Entity> attributeSatisfies(final String attributeName, final Predicate<Object> condition) {
    return new AttributeSatisfies<Object>(Sensors.newSensor(Object.class, attributeName), condition);
}
 
Example 19
Source File: AbstractTransformer.java    From brooklyn-server with Apache License 2.0 4 votes vote down vote up
@SuppressWarnings({ "unchecked", "rawtypes" })
@Override
public void setEntity(EntityLocal entity) {
    super.setEntity(entity);

    this.producer = getConfig(PRODUCER) == null ? entity: getConfig(PRODUCER);
    this.sourceSensor = (Sensor<T>) getConfig(SOURCE_SENSOR);
    Sensor<?> targetSensorSpecified = getConfig(TARGET_SENSOR);
    List<? extends Sensor<?>> triggerSensorsSpecified = getConfig(TRIGGER_SENSORS);
    List<? extends Sensor<?>> triggerSensors = triggerSensorsSpecified != null ? triggerSensorsSpecified : ImmutableList.<Sensor<?>>of();
    this.targetSensor = targetSensorSpecified!=null ? (Sensor<U>) targetSensorSpecified : (Sensor<U>) this.sourceSensor;
    if (targetSensor == null) {
        throw new IllegalArgumentException("Enricher "+JavaClassNames.simpleClassName(this)+" has no "+TARGET_SENSOR.getName()+", and it cannot be inferred as "+SOURCE_SENSOR.getName()+" is also not set");
    }
    if (sourceSensor == null && triggerSensors.isEmpty()) {
        throw new IllegalArgumentException("Enricher "+JavaClassNames.simpleClassName(this)+" has no "+SOURCE_SENSOR.getName()+" and no "+TRIGGER_SENSORS.getName());
    }
    if (producer.equals(entity) && (targetSensor.equals(sourceSensor) || triggerSensors.contains(targetSensor))) {
        boolean allowCyclicPublishing = Boolean.TRUE.equals(getConfig(ALLOW_CYCLIC_PUBLISHING));
        if (allowCyclicPublishing) {
            LOG.debug("Permitting cyclic publishing, though detected enricher will read and publish on the same sensor: "+
                producer+"->"+targetSensor+" (computing transformation with "+JavaClassNames.simpleClassName(this)+")");
        } else {
            // We cannot call getTransformation() here to log the tranformation, as it will attempt
            // to resolve the transformation, which will cause the entity initialization thread to block
            LOG.error("Refusing to add an enricher which reads and publishes on the same sensor: "+
                producer+"->"+targetSensor+" (computing transformation with "+JavaClassNames.simpleClassName(this)+")");
            // we don't throw because this error may manifest itself after a lengthy deployment, 
            // and failing it at that point simply because of an enricher is not very pleasant
            // (at least not until we have good re-run support across the board)
            return;
        }
    }
    
    if (sourceSensor != null) {
        subscriptions().subscribe(MutableMap.of("notifyOfInitialValue", true), producer, sourceSensor, this);
    }
    
    if (triggerSensors.size() > 0) {
        SensorEventListener<Object> triggerListener = new SensorEventListener<Object>() {
            @Override public void onEvent(SensorEvent<Object> event) {
                if (sourceSensor != null) {
                    // Simulate an event, as though our sourceSensor changed
                    Object value = producer.getAttribute((AttributeSensor<?>)sourceSensor);
                    AbstractTransformer.this.onEvent(new BasicSensorEvent(sourceSensor, producer, value, event.getTimestamp()));
                } else {
                    // Assume the transform doesn't care about the value - otherwise it would 
                    // have declared a sourceSensor!
                    AbstractTransformer.this.onEvent(null);
                }
            }
        };
        for (Object sensor : triggerSensors) {
            if (sensor instanceof String) {
                Sensor<?> resolvedSensor = entity.getEntityType().getSensor((String)sensor);
                if (resolvedSensor == null) { 
                    resolvedSensor = Sensors.newSensor(Object.class, (String)sensor);
                }
                sensor = resolvedSensor;
            }
            subscriptions().subscribe(MutableMap.of("notifyOfInitialValue", true), producer, (Sensor<?>)sensor, triggerListener);
        }
    }
    
    highlightTriggers(MutableList.<Sensor<?>>of(sourceSensor).appendAll(triggerSensors), producer);
}
 
Example 20
Source File: AddSensor.java    From brooklyn-server with Apache License 2.0 4 votes vote down vote up
private AttributeSensor<T> newSensor(Entity entity) {
    String className = getFullClassName(type);
    Class<T> clazz = getType(entity, className);
    return Sensors.newSensor(clazz, name);
}