org.apache.brooklyn.config.ConfigKey Java Examples

The following examples show how to use org.apache.brooklyn.config.ConfigKey. 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: DslYamlTest.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@Test
public void testDeferredDslChainingOnConfigNoFunction() throws Exception {
    final Entity app = createAndStartApplication(
            "services:",
            "- type: " + BasicApplication.class.getName(),
            "  brooklyn.config:",
            "    dest: $brooklyn:config(\"targetValue\").getNonExistent()");
    ConfigKey<TestDslSupplierValue> targetValueKey = ConfigKeys.newConfigKey(TestDslSupplierValue.class, "targetValue");
    app.config().set(targetValueKey, new TestDslSupplierValue());
    try {
        assertEquals(getConfigEventually(app, DEST), app.getId());
        Asserts.shouldHaveFailedPreviously("Expected to fail because method does not exist");
    } catch (Exception e) {
        Asserts.expectedFailureContains(e, "No such function 'getNonExistent'");
        Asserts.expectedFailureDoesNotContain(e, "$brooklyn:$brooklyn:");
    }
}
 
Example #2
Source File: BasicEntityRebindSupport.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
protected void addConfig(RebindContext rebindContext, EntityMemento memento) {
    ConfigKey<?> key = null;
    for (Map.Entry<ConfigKey<?>, Object> entry : memento.getConfig().entrySet()) {
        try {
            key = entry.getKey();
            Object value = entry.getValue();
            @SuppressWarnings("unused") // just to ensure we can load the declared type? or maybe not needed
                    // In what cases key.getType() will be null?
            Class<?> type = (key.getType() != null) ? key.getType() : rebindContext.loadClass(key.getTypeName());
            entity.config().set((ConfigKey<Object>)key, value);
        } catch (ClassNotFoundException|IllegalArgumentException e) {
            rebindContext.getExceptionHandler().onAddConfigFailed(memento, key, e);
        }
    }
    
    entity.config().putAll(memento.getConfigUnmatched());
    entity.config().refreshInheritedConfig();
}
 
Example #3
Source File: FlagUtils.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings({ "unchecked", "rawtypes" })
public static void setConfig(Object objectOfField, ConfigKey<?> key, Object value, SetFromFlag optionalAnnotation) {
    if (objectOfField instanceof Configurable) {
        ((Configurable)objectOfField).config().set((ConfigKey)key, value);
        return;
    } else {
        if (optionalAnnotation==null) {
            log.warn("Cannot set key "+key.getName()+" on "+objectOfField+": containing class is not Configurable");
        } else if (!key.getName().equals(optionalAnnotation.value())) {
            log.warn("Cannot set key "+key.getName()+" on "+objectOfField+" from flag "+optionalAnnotation.value()+": containing class is not Configurable");
        } else {
            // if key and flag are the same, then it will probably happen automatically
            if (log.isDebugEnabled())
                log.debug("Cannot set key "+key.getName()+" on "+objectOfField+" from flag "+optionalAnnotation.value()+": containing class is not Configurable");
        }
        return;
    }
}
 
Example #4
Source File: SpecParameterUnwrappingTest.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@Test
public void testCatalogConfigOverridesParameters() {
    addCatalogItems(
            "brooklyn.catalog:",
            "  version: " + TEST_VERSION,
            "  items:",
            "  - id: " + SYMBOLIC_NAME,
            "    item:",
            "      type: " + ConfigEntityForTest.class.getName(),
            "      brooklyn.parameters:",
            "      - name: simple",
            "        default: biscuits",
            "      brooklyn.config:",
            "        simple: value");
    final int NUM_CONFIG_KEYS_FROM_TEST_BLUEPRINT = 1;

    AbstractBrooklynObjectSpec<?, ?> spec = peekSpec();
    List<SpecParameter<?>> params = spec.getParameters();
    assertEquals(params.size(), NUM_ENTITY_DEFAULT_CONFIG_KEYS + ConfigEntityForTest.NUM_CONFIG_KEYS_DEFINED_HERE + NUM_CONFIG_KEYS_FROM_TEST_BLUEPRINT);
    assertTrue(Iterables.tryFind(params, nameEqualTo("simple")).isPresent());
    Optional<ConfigKey<?>> config = Iterables.tryFind(spec.getConfig().keySet(), ConfigPredicates.nameEqualTo("simple"));
    assertTrue(config.isPresent());
    Object value = spec.getConfig().get(config.get());
    assertEquals(value, "value");
}
 
Example #5
Source File: JcloudsReachableAddressStubbedTest.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
/**
 * Multiple private addresses; chooses the reachable one;
 * With waitForSshable=true; pollForFirstReachableAddress=true; and custom reachable-predicate
 */
@Test
public void testMachineUsesReachablePrivateAddress() throws Exception {
    List<String> publicAddresses = ImmutableList.of("1.1.1.1");
    List<String> privateAddresses = ImmutableList.of("2.1.1.1", "2.1.1.2", "2.1.1.3");
    reachableIp = "2.1.1.2";
    initNodeCreatorAndJcloudsLocation(newNodeCreator(publicAddresses, privateAddresses), ImmutableMap.of());

    JcloudsSshMachineLocation machine = newMachine(ImmutableMap.<ConfigKey<?>,Object>builder()
            .put(JcloudsLocationConfig.WAIT_FOR_SSHABLE, Duration.millis(50).toString())
            .put(JcloudsLocation.POLL_FOR_FIRST_REACHABLE_ADDRESS, Duration.millis(50).toString())
            .build());

    addressChooser.assertCalled();
    assertEquals(RecordingSshTool.getLastExecCmd().constructorProps.get(SshTool.PROP_HOST.getName()), reachableIp);

    assertEquals(machine.getAddress().getHostAddress(), reachableIp);
    assertEquals(machine.getHostname(), "1.1.1.1"); // prefers public, even if that was not reachable
    assertEquals(machine.getSubnetIp(), "2.1.1.1"); // TODO uses first, rather than "reachable"; is that ok?
}
 
Example #6
Source File: InboundPortsUtilsTest.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@Test
public void testGetRequiredOpenPortsGetsDynamicallyAddedPortBasedKeys() {
    TestEntity entity = app.createAndManageChild(EntitySpec.create(TestEntity.class));

    PortAttributeSensorAndConfigKey newTestConfigKeyPort = ConfigKeys.newPortSensorAndConfigKey("new.test.config.port.string.first", "port", "7777+");
    PortAttributeSensorAndConfigKey newTestConfigKeyPort2 = ConfigKeys.newPortSensorAndConfigKey("new.test.config.port.string.second", "port");

    ConfigKey<Object> newTestConfigKeyObject = ConfigKeys.newConfigKey(Object.class, "new.test.config.object");
    ConfigKey<String> newTestConfigKeyString = ConfigKeys.newStringConfigKey("new.test.config.key.string");
    entity.config().set(newTestConfigKeyPort, PortRanges.fromString("8888+"));
    entity.config().set(newTestConfigKeyPort2, PortRanges.fromInteger(9999));
    entity.config().set(newTestConfigKeyObject, PortRanges.fromInteger(2222));
    entity.config().set(newTestConfigKeyString, "foo.bar");

    Collection<Integer> dynamicRequiredOpenPorts = InboundPortsUtils.getRequiredOpenPorts(entity, ImmutableSet.<ConfigKey<?>>of(), true, null);
    Assert.assertTrue(dynamicRequiredOpenPorts.contains(8888));
    Assert.assertTrue(dynamicRequiredOpenPorts.contains(9999));
    Assert.assertTrue(dynamicRequiredOpenPorts.contains(2222));
}
 
Example #7
Source File: AbstractConfigMapImpl.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
/** finds the value at the given container/key, taking in to account any resolution expected by the key (eg for map keys).
 * the input is the value in the {@link #ownConfig} map taken from {@link #getRawValueAtContainer(BrooklynObject, ConfigKey)}, 
 * but the key may have other plans.
 * current impl just uses the key to extract again which is a little bit wasteful but simpler. 
 * <p>
 * this does not do any resolution with respect to ancestors. */
protected Maybe<Object> resolveRawValueFromContainer(TContainer container, ConfigKey<?> key, Maybe<Object> value) {
    Maybe<Object> result = resolveRawValueFromContainerIgnoringDeprecatedNames(container, key, value);
    if (result.isPresent()) return result;
    
    // See AbstractconfigMapImpl.getConfigRaw(ConfigKey<?> key, boolean includeInherited) for how/why it
    // handles deprecated names
    for (String deprecatedName : key.getDeprecatedNames()) {
        ConfigKey<?> deprecatedKey = ConfigKeys.newConfigKeyRenamed(deprecatedName, key);
        result = resolveRawValueFromContainerIgnoringDeprecatedNames(container, deprecatedKey, value);
        if (result.isPresent()) {
            LOG.warn("Retrieving value with deprecated config key name '"+deprecatedName+"' for key "+key);
            return result;
        }
    }
    return result;
}
 
Example #8
Source File: JcloudsReachableAddressStubbedTest.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
/**
 * Similar to {@link #testMachineUsesVanillaPublicAddress()}, except for a windows machine.
 */
@Test
public void testWindowsMachineUsesVanillaPublicAddress() throws Exception {
    List<String> publicAddresses = ImmutableList.of("1.1.1.1");
    List<String> privateAddresses = ImmutableList.of("2.1.1.1");
    reachableIp = "1.1.1.1";
    initNodeCreatorAndJcloudsLocation(newNodeCreator(publicAddresses, privateAddresses), ImmutableMap.of());

    JcloudsWinRmMachineLocation machine = newWinrmMachine(ImmutableMap.<ConfigKey<?>,Object>builder()
            .put(JcloudsLocationConfig.WAIT_FOR_WINRM_AVAILABLE, Duration.millis(50).toString())
            .put(JcloudsLocation.POLL_FOR_FIRST_REACHABLE_ADDRESS, Duration.millis(50).toString())
            .build());

    addressChooser.assertCalled();
    assertEquals(RecordingWinRmTool.getLastExec().constructorProps.get(WinRmTool.PROP_HOST.getName()), reachableIp);

    assertEquals(machine.getAddress().getHostAddress(), reachableIp);
    assertEquals(machine.getHostname(), reachableIp);
    assertEquals(machine.getSubnetIp(), "2.1.1.1");
}
 
Example #9
Source File: PolicyConfigResource.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings({ "unchecked", "rawtypes" })
@Override
public Response set(String application, String entityToken, String policyToken, String configKeyName, Object value) {
    Entity entity = brooklyn().getEntity(application, entityToken);
    if (!Entitlements.isEntitled(mgmt().getEntitlementManager(), Entitlements.MODIFY_ENTITY, entity)) {
        throw WebResourceUtils.forbidden("User '%s' is not authorized to modify entity '%s'",
                Entitlements.getEntitlementContext().user(), entity);
    }

    Policy policy = brooklyn().getPolicy(application, entityToken, policyToken);
    ConfigKey<?> ck = policy.getPolicyType().getConfigKey(configKeyName);
    if (ck == null) throw WebResourceUtils.notFound("Cannot find config key '%s' in policy '%s' of entity '%s'", configKeyName, policy, entityToken);

    policy.config().set((ConfigKey) ck, TypeCoercions.coerce(value, ck.getTypeToken()));

    return Response.status(Response.Status.OK).build();
}
 
Example #10
Source File: LocationConfigUtils.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
private static String getKeyDataFromDataKeyOrFileKey(ConfigBag config, ConfigKey<String> dataKey, ConfigKey<String> fileKey) {
    boolean unused = config.isUnused(dataKey);
    String data = config.get(dataKey);
    if (Strings.isNonBlank(data) && !unused) {
        return data.trim();
    }
    
    String file = config.get(fileKey);
    if (groovyTruth(file)) {
        List<String> files = Arrays.asList(file.split(File.pathSeparator));
        List<String> filesTidied = tidyFilePaths(files);
        String fileData = getFileContents(filesTidied);
        if (fileData == null) {
            log.warn("Invalid file" + (files.size() > 1 ? "s" : "") + " for " + fileKey + " (given " + files + 
                    (files.equals(filesTidied) ? "" : "; converted to " + filesTidied) + ") " +
                    "may fail provisioning " + config.getDescription());
        } else if (groovyTruth(data)) {
            if (!fileData.trim().equals(data.trim()))
                log.warn(dataKey.getName()+" and "+fileKey.getName()+" both specified; preferring the former");
        } else {
            data = fileData;
            config.put(dataKey, data);
            config.get(dataKey);
        }
    }
    
    return data;
}
 
Example #11
Source File: ConfigParametersYamlTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
protected <T> void assertKeyEquals(Entity entity, String keyName, String expectedDescription, Class<T> expectedType, T expectedDefaultVal, T expectedEntityVal) {
    ConfigKey<?> key = entity.getEntityType().getConfigKey(keyName);
    assertNotNull(key, "No key '"+keyName+"'; keys="+entity.getEntityType().getConfigKeys());

    assertEquals(key.getName(), keyName);
    assertEquals(key.getDescription(), expectedDescription);
    assertEquals(key.getType(), expectedType);
    assertEquals(key.getDefaultValue(), expectedDefaultVal);
    
    assertEquals(entity.config().get(key), expectedEntityVal);
}
 
Example #12
Source File: SoftwareProcessEntityLatchTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Test(dataProvider="latchAndTaskNamesProvider")
public void testReleaseableLatchBlocks(final ConfigKey<Boolean> latch, final List<String> preLatchEvents) throws Exception {
    final ReleaseableLatch latchSemaphore = ReleaseableLatch.Factory.newMaxConcurrencyLatch(0);
    doTestLatchBlocks(latch, preLatchEvents, latchSemaphore, new Function<MyService, Void>() {
        @Override
        public Void apply(MyService entity) {
            String taskName = (latch == SoftwareProcess.STOP_LATCH) ? "stop" : "start";
            assertEffectorBlockingDetailsEventually(entity, taskName, "Acquiring " + latch + " " + latchSemaphore);
            assertDriverEventsEquals(entity, preLatchEvents);
            latchSemaphore.release(entity);
            return null;
        }
    });

}
 
Example #13
Source File: PropagatePrimaryEnricher.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Override
protected <T> void doReconfigureConfig(ConfigKey<T> key, T val) {
    if (CURRENT_PROPAGATED_PRODUCER.equals(key)) return;
    if (CURRENT_PROPAGATOR_ID.equals(key)) return;
    // disallow anything else
    super.doReconfigureConfig(key, val);
}
 
Example #14
Source File: EnrichersYamlTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
private void checkReferences(final Enricher enricher, Map<ConfigKey<Entity>, Entity> keyToEntity) throws Exception {
    for (final ConfigKey<Entity> key : keyToEntity.keySet()) {
        final Entity entity = keyToEntity.get(key); // Grab an entity whose execution context we can use
        Entity fromConfig = ((EntityInternal)entity).getExecutionContext().submit(MutableMap.of(), new Callable<Entity>() {
            @Override
            public Entity call() throws Exception {
                return enricher.getConfig(key);
            }
        }).get();
        Assert.assertEquals(fromConfig, keyToEntity.get(key));
    }
}
 
Example #15
Source File: ConfigKeyConstraintTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Test
public void testIsValidWithBadlyBehavedPredicate() {
    ConfigKey<String> key = ConfigKeys.builder(String.class)
            .name("foo")
            .constraint(new Predicate<String>() {
                @Override
                public boolean apply(String input) {
                    throw new RuntimeException("It's my day off");
                }
            })
            .build();
    // i.e. no exception.
    assertFalse(key.isValueValid("abc"));
}
 
Example #16
Source File: JcloudsPortForwardingStubbedTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Test
public void testReleaseVmDoesNotImpactOtherVms() throws Exception {
    PortForwardManager pfm = new PortForwardManagerImpl();
    RecordingJcloudsPortForwarderExtension portForwarder = new RecordingJcloudsPortForwarderExtension(pfm);
    
    JcloudsSshMachineLocation machine1 = obtainMachine(ImmutableMap.<ConfigKey<?>,Object>of(
            JcloudsLocation.USE_PORT_FORWARDING, true,
            JcloudsLocation.PORT_FORWARDER, portForwarder,
            JcloudsLocation.PORT_FORWARDING_MANAGER, pfm));
    
    JcloudsSshMachineLocation machine2 = obtainMachine(ImmutableMap.<ConfigKey<?>,Object>of(
            JcloudsLocation.USE_PORT_FORWARDING, true,
            JcloudsLocation.PORT_FORWARDER, portForwarder,
            JcloudsLocation.PORT_FORWARDING_MANAGER, pfm));
    
    NodeMetadata node1 = getNodeCreator().created.get(0);

    // Add an association for machine2 - expect that not to be touched when machine1 is released.
    HostAndPort publicHostAndPort = HostAndPort.fromParts("1.2.3.4", 1234);
    pfm.associate("mypublicip", publicHostAndPort, machine2, 80);

    // Release machine1
    releaseMachine(machine1);
    
    // Expect machine2 to still be registered
    assertEquals(pfm.lookup(machine2, 80), publicHostAndPort);
    assertEquals(pfm.lookup("mypublicip", 80), publicHostAndPort);
    
    // And no calls to "close" for machine2; just for machine1's port 22
    assertEquals(portForwarder.closes.size(), 1, "closes="+portForwarder.closes+"; machine1="+machine1);
    assertEquals(portForwarder.closes.get(0).get(0), node1);
    assertEquals(portForwarder.closes.get(0).get(1), 22);
}
 
Example #17
Source File: ExecWithLoggingHelpers.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
protected static <T> T getOptionalVal(Map<String,?> map, ConfigKey<T> keyC) {
    if (keyC==null) return null;
    String key = keyC.getName();
    if (map!=null && map.containsKey(key)) {
        return TypeCoercions.coerce(map.get(key), keyC.getTypeToken());
    } else {
        return keyC.getDefaultValue();
    }
}
 
Example #18
Source File: Dumper.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings({ "rawtypes", "unchecked" })
static List<ConfigKey<?>> sortConfigKeys(Set<ConfigKey<?>> configs) {
    List result = new ArrayList(configs);
    Collections.sort(result, new Comparator<ConfigKey>() {
                @Override
                public int compare(ConfigKey arg0, ConfigKey arg1) {
                    return arg0.getName().compareTo(arg1.getName());
                }

    });
    return result;
}
 
Example #19
Source File: JcloudsLocationTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Test
public void testCreateWithCustomMachineNamer() {
    final String machineNamerClass = CustomMachineNamer.class.getName();
    BailOutJcloudsLocation jcloudsLocation = BailOutJcloudsLocation.newBailOutJcloudsLocation(
            managementContext, ImmutableMap.<ConfigKey<?>, Object>of(
                    LocationConfigKeys.CLOUD_MACHINE_NAMER_CLASS, machineNamerClass));
    jcloudsLocation.tryObtainAndCheck(ImmutableMap.of(CustomMachineNamer.MACHINE_NAME_TEMPLATE, "ignored"), new Predicate<ConfigBag>() {
        @Override
        public boolean apply(ConfigBag input) {
            Assert.assertEquals(input.get(LocationConfigKeys.CLOUD_MACHINE_NAMER_CLASS), machineNamerClass);
            return true;
        }
    });
}
 
Example #20
Source File: LocationPredicates.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
/** @deprecated since 0.9.0 kept only to allow conversion of anonymous inner classes */
@SuppressWarnings("unused") @Deprecated 
private static <T> Predicate<Location> configEqualToOld(final ConfigKey<T> configKey, final T val) {
    // TODO PERSISTENCE WORKAROUND
    return new Predicate<Location>() {
        @Override
        public boolean apply(@Nullable Location input) {
            return (input != null) && Objects.equal(input.getConfig(configKey), val);
        }
    };
}
 
Example #21
Source File: AsyncApplicationImpl.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Override
protected <T> void doReconfigureConfig(ConfigKey<T> key, T val) {
    if (RECONFIGURABLE_KEYS.contains(key)) {
        return;
    } else {
        super.doReconfigureConfig(key, val);
    }
}
 
Example #22
Source File: BrooklynDslCommon.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Override
public Task<Object> newTask() {
    return Tasks.builder()
            .displayName("retrieving config for "+keyName+" on "+obj)
            .tag(BrooklynTaskTags.TRANSIENT_TASK_TAG)
            .dynamic(false)
            .body(new Callable<Object>() {
                @Override
                public Object call() throws Exception {
                    String keyNameS = resolveKeyName(true);
                    ConfigKey<Object> key = ConfigKeys.newConfigKey(Object.class, keyNameS);
                    return obj.getConfig(key);
                }})
            .build();
}
 
Example #23
Source File: ServiceFailureDetectorYamlTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
protected static void assertEnricherConfig(Enricher enricher, Map<? extends ConfigKey<?>, ?> expectedVals) {
    for (Map.Entry<? extends ConfigKey<?>, ?> entry : expectedVals.entrySet()) {
        ConfigKey<?> key = entry.getKey();
        Object actual = enricher.config().get(key);
        assertEquals(actual, entry.getValue(), "key="+key+"; expected="+entry.getValue()+"; actual="+actual);
    }
}
 
Example #24
Source File: FlagUtils.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
/** sets _all_ accessible _{@link ConfigKey}_ and {@link HasConfigKey} fields on the given object, 
 * using the indicated flags/config-bag */
public static void setAllConfigKeys(Configurable o, ConfigBag bag, boolean includeFlags) {
    for (Field f: getAllFields(o.getClass())) {
        ConfigKey<?> key = getFieldAsConfigKey(o, f);
        if (key!=null) {
            FlagConfigKeyAndValueRecord record = getFlagConfigKeyRecord(f, key, bag);
            if ((includeFlags && record.isValuePresent()) || record.getConfigKeyMaybeValue().isPresent()) {
                setField(o, f, record.getValueOrNullPreferringConfigKey(), null);
            }
        }
    }
}
 
Example #25
Source File: EntityFunctions.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
/** @deprecated since 0.9.0 kept only to allow conversion of non-static inner classes */
@SuppressWarnings("unused") @Deprecated 
private static <T> Function<Entity, T> configOld(final ConfigKey<T> key) {
    // TODO PERSISTENCE WORKAROUND
    class GetEntityConfigFunction implements Function<Entity, T> {
        @Override public T apply(Entity input) {
            return (input == null) ? null : input.getConfig(key);
        }
    }
    return new GetEntityConfigFunction();
}
 
Example #26
Source File: MapListAndOtherStructuredConfigKeyTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Test // ListConfigKey deprecated, as order no longer guaranteed
public void testListConfigKeyClear() throws Exception {
    entity.config().set(TestEntity.CONF_LIST_THING.subKey(), "aval");
    entity.config().set((ConfigKey)TestEntity.CONF_LIST_THING, (Object) ListModifications.clearing());
    // for now defaults to null, but empty list might be better? or whatever the default is?
    assertEquals(entity.getConfig(TestEntity.CONF_LIST_THING), null);
}
 
Example #27
Source File: ConfigKeys.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
public static ConfigKey<?> newInstance(ConfigBag keyDefs) {
    String typeName = Strings.toString(keyDefs.getStringKey("type"));
    if (Strings.isNonBlank(typeName)) {
        // TODO dynamic typing - see TYPE key commented out above; also see AddSensor.getType for type lookup
        log.warn("Setting 'type' is not currently supported for dynamic config keys; ignoring in definition of "+keyDefs);
    }
    
    Class<Object> type = Object.class;
    String name = keyDefs.get(NAME);
    String description = keyDefs.get(DESCRIPTION);
    Object defaultValue = keyDefs.get(DEFAULT_VALUE);
    return newConfigKey(type, name, description, defaultValue);
}
 
Example #28
Source File: DslTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Test
public void testConfigWithDsl() throws Exception {
    ConfigKey<?> configKey = ConfigKeys.newConfigKey(Entity.class, "testConfig");
    BrooklynDslDeferredSupplier<?> dsl = BrooklynDslCommon.config(configKey.getName());
    Supplier<ConfigValuePair> valueSupplier = new Supplier<ConfigValuePair>() {
        @Override public ConfigValuePair get() {
            return new ConfigValuePair(BrooklynDslCommon.root(), app);
        }
    };
    new ConfigTestWorker(app, configKey, valueSupplier, dsl).run();
}
 
Example #29
Source File: ConfigKeys.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
/** creates a new {@link ConfigKey} given a name (e.g. as a key in a larger map) and a map of other definition attributes */
public static ConfigKey<?> newNamedInstance(String name, Map<?,?> keyDefs) {
    ConfigBag defs = ConfigBag.newInstance(keyDefs);
    String oldName = defs.put(NAME, name);
    if (oldName!=null && !oldName.equals(name))
        log.warn("Dynamic key '"+oldName+"' being overridden as key '"+name+"' in "+keyDefs);
    return newInstance(defs);
}
 
Example #30
Source File: ObjectsYamlTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Override
public <T> T set(ConfigKey<T> key, T val) {
    log.info("Detected configuration injection for {}: {}", key.getName(), val);
    configKeys.add(key.getName());
    if ("config.number".equals(key.getName())) number = TypeCoercions.coerce(val, Integer.class);
    if ("config.object".equals(key.getName())) object = val;
    T old = bag.get(key);
    bag.configure(key, val);
    return old;
}