Java Code Examples for org.apache.brooklyn.util.core.config.ConfigBag#newInstance()

The following examples show how to use org.apache.brooklyn.util.core.config.ConfigBag#newInstance() . 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: KubernetesCertsTest.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@Test
public void testCertsWarnsIfConflictingConfig() throws Exception {
    ConfigBag config = ConfigBag.newInstance(ImmutableMap.builder()
            .put(KubernetesLocationConfig.CA_CERT_DATA, "myCaCertData")
            .put(KubernetesLocationConfig.CA_CERT_FILE, newTempFile("myCaCertData").getAbsolutePath())
            .build());

    String loggerName = KubernetesCerts.class.getName();
    ch.qos.logback.classic.Level logLevel = ch.qos.logback.classic.Level.WARN;
    Predicate<ILoggingEvent> filter = EventPredicates.containsMessage("Duplicate (matching) configuration for "
            + "caCertData and caCertFile (continuing)");
    LogWatcher watcher = new LogWatcher(loggerName, logLevel, filter);

    watcher.start();
    KubernetesCerts certs;
    try {
        certs = new KubernetesCerts(config);
        watcher.assertHasEvent();
    } finally {
        watcher.close();
    }

    assertEquals(certs.caCertData.get(), "myCaCertData");
}
 
Example 2
Source File: BrooklynDslCommon.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
public static Object create(Class<?> type, String factoryMethodName, List<?> factoryMethodArgs, Map<String,?> fields, Map<String,?> config) {
    try {
        Optional<TypeCoercer> coercer = Optional.of(TypeCoercions.asTypeCoercer());
        Object bean = Reflections.invokeMethodFromArgs(type, factoryMethodName, factoryMethodArgs, false, coercer).get();
        BeanUtils.populate(bean, fields);

        if (config.size() > 0) {
            if (bean instanceof Configurable) {
                ConfigBag configBag = ConfigBag.newInstance(config);
                FlagUtils.setFieldsFromFlags(bean, configBag);
                FlagUtils.setAllConfigKeys((Configurable) bean, configBag, true);
            } else {
                LOG.warn("While building object via factory method '"+factoryMethodName+"', type "
                        + (bean == null ? "<null>" : bean.getClass())+" is not 'Configurable'; cannot apply "
                        + "supplied config (continuing)");
            }
        }
        return bean;
    } catch (Exception e) {
        throw Exceptions.propagate(e);
    }
}
 
Example 3
Source File: BasicPolicyRebindSupport.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@Override
protected void addConfig(RebindContext rebindContext, PolicyMemento memento) {
    // TODO entity does config-lookup differently; the memento contains the config keys.
    // BasicEntityMemento.postDeserialize uses the injectTypeClass to call EntityTypes.getDefinedConfigKeys(clazz)
    
    Collection<ConfigKey<?>> configKeys = policy.getAdjunctType().getConfigKeys();
    
    Map<?, ?> flags = memento.getConfig();
    
    // First set the config keys that are known explicitly (including with deprecated names).
    flags = ConfigUtilsInternal.setAllConfigKeys(flags, configKeys, policy);

    // Note that the flags may have been set in the constructor; but non-legacy policies should have no-arg constructors
    if (!flags.isEmpty()) {
        ConfigBag configBag = ConfigBag.newInstance(flags);
        FlagUtils.setFieldsFromFlags(policy, configBag);
        FlagUtils.setAllConfigKeys(policy, configBag, false);
    }
}
 
Example 4
Source File: KubernetesCertsTest.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@Test
public void testCertsFromData() throws Exception {
    ConfigBag config = ConfigBag.newInstance(ImmutableMap.builder()
            .put(KubernetesLocationConfig.CA_CERT_DATA, "myCaCertData")
            .put(KubernetesLocationConfig.CLIENT_CERT_DATA, "myClientCertData")
            .put(KubernetesLocationConfig.CLIENT_KEY_DATA, "myClientKeyData")
            .put(KubernetesLocationConfig.CLIENT_KEY_ALGO, "myClientKeyAlgo")
            .put(KubernetesLocationConfig.CLIENT_KEY_PASSPHRASE, "myClientKeyPassphrase")
            .build());
    KubernetesCerts certs = new KubernetesCerts(config);

    assertEquals(certs.caCertData.get(), "myCaCertData");
    assertEquals(certs.clientCertData.get(), "myClientCertData");
    assertEquals(certs.clientKeyData.get(), "myClientKeyData");
    assertEquals(certs.clientKeyAlgo.get(), "myClientKeyAlgo");
    assertEquals(certs.clientKeyPassphrase.get(), "myClientKeyPassphrase");
}
 
Example 5
Source File: LocalhostPropertiesFromBrooklynProperties.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@Override
public Map<String, Object> getLocationProperties(String provider, String namedLocation, Map<String, ?> properties) {
    if (Strings.isNullOrEmpty(namedLocation) && Strings.isNullOrEmpty(provider)) {
        throw new IllegalArgumentException("Neither cloud provider/API nor location name have been specified correctly");
    }

    ConfigBag result = ConfigBag.newInstance();
    
    result.putAll(transformDeprecated(getGenericLocationSingleWordProperties(properties)));
    result.putAll(transformDeprecated(getMatchingSingleWordProperties("brooklyn.location.", properties)));
    result.putAll(transformDeprecated(getMatchingProperties("brooklyn.location.localhost.", "brooklyn.localhost.", properties)));
    if (!Strings.isNullOrEmpty(namedLocation)) result.putAll(transformDeprecated(getNamedLocationProperties(namedLocation, properties)));
    setLocalTempDir(properties, result);
    
    return result.getAllConfigRaw();
}
 
Example 6
Source File: DefaultAzureArmNetworkCreatorTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Test
public void testNetworkInConfig() throws Exception {
    ConfigBag configBag = ConfigBag.newInstance();
    configBag.put(CLOUD_REGION_ID, TEST_LOCATION);
    configBag.put(NETWORK_NAME, TEST_NETWORK_NAME);

    runAssertingNoInteractions(configBag);
}
 
Example 7
Source File: SoftwareProcessImpl.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
protected Map<String,Object> obtainProvisioningFlags(MachineProvisioningLocation location) {
    ConfigBag result = ConfigBag.newInstance(location.getProvisioningFlags(ImmutableList.of(getClass().getName())));

    // copy provisioning properties raw in case they contain deferred values
    // normal case is to have provisioning.properties.xxx in the map, so this is how we get it
    Map<String, Object> raw1 = PROVISIONING_PROPERTIES.rawValue(config().getBag().getAllConfigRaw());
    // do this also, just in case a map is stored at the key itself (not sure this is needed, raw1 may include it already)
    Maybe<Object> raw2 = config().getRaw(PROVISIONING_PROPERTIES);
    if (raw2.isPresentAndNonNull()) {
        Object pp = raw2.get();
        if (!(pp instanceof Map)) {
            LOG.debug("When obtaining provisioning properties for "+this+" to deploy to "+location+", detected that coercion was needed, so coercing sooner than we would otherwise");
            pp = config().get(PROVISIONING_PROPERTIES);
        }
        result.putAll((Map<?,?>)pp);
    }
    // finally write raw1 on top
    result.putAll(raw1);

    if (result.get(CloudLocationConfig.INBOUND_PORTS) == null) {
        Collection<Integer> ports = getRequiredOpenPorts();
        Object requiredPorts = result.get(CloudLocationConfig.ADDITIONAL_INBOUND_PORTS);
        if (requiredPorts instanceof Integer) {
            ports.add((Integer) requiredPorts);
        } else if (requiredPorts instanceof Iterable) {
            for (Object o : (Iterable<?>) requiredPorts) {
                if (o instanceof Integer) ports.add((Integer) o);
            }
        }
        if (ports != null && ports.size() > 0) result.put(CloudLocationConfig.INBOUND_PORTS, ports);
    }
    result.put(LocationConfigKeys.CALLER_CONTEXT, this);
    return result.getAllConfigMutable();
}
 
Example 8
Source File: KubernetesCertsTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Test
public void testCertsFailsIfFileNotFound() throws Exception {
    ConfigBag config = ConfigBag.newInstance(ImmutableMap.builder()
            .put(KubernetesLocationConfig.CA_CERT_FILE, "/path/to/fileDoesNotExist-" + Identifiers.makeRandomId(8))
            .build());
    try {
        new KubernetesCerts(config);
        Asserts.shouldHaveFailedPreviously();
    } catch (Exception e) {
        Asserts.expectedFailureContains(e, "not found on classpath or filesystem");
    }
}
 
Example 9
Source File: LocationConfigUtilsTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Test(groups="Integration")  // requires ~/.ssh/id_rsa
public void testReadsPublicKeyFileWithTildePath() throws Exception {
    ConfigBag config = ConfigBag.newInstance();
    config.put(LocationConfigKeys.PUBLIC_KEY_FILE, SSH_PUBLIC_KEY_FILE_WITH_TILDE);
    
    // don't mind if it has a passphrase
    String data = LocationConfigUtils.getOsCredential(config).doKeyValidation(false).getPublicKeyData();
    assertTrue(data != null && data.length() > 0);
}
 
Example 10
Source File: LocationConfigUtilsTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
public void testPreferPrivateKeyDataOverFile() throws Exception {
    ConfigBag config = ConfigBag.newInstance();
    config.put(LocationConfigKeys.PRIVATE_KEY_DATA, "mydata");
    config.put(LocationConfigKeys.PRIVATE_KEY_FILE, SSH_PRIVATE_KEY_FILE);
    
    LocationConfigUtils.OsCredential creds = LocationConfigUtils.getOsCredential(config).doKeyValidation(false);
    Assert.assertTrue(creds.hasKey());
    // warnings, as it is malformed
    Assert.assertFalse(creds.getWarningMessages().isEmpty());

    String data = creds.getPrivateKeyData();
    assertEquals(data, "mydata");
}
 
Example 11
Source File: BrooklynNodeImpl.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
private void queueShutdownTask() {
    ConfigBag stopParameters = BrooklynTaskTags.getCurrentEffectorParameters();
    ConfigBag shutdownParameters;
    if (stopParameters != null) {
        shutdownParameters = ConfigBag.newInstanceCopying(stopParameters);
    } else {
        shutdownParameters = ConfigBag.newInstance();
    }
    shutdownParameters.putIfAbsent(ShutdownEffector.REQUEST_TIMEOUT, Duration.ONE_MINUTE);
    shutdownParameters.putIfAbsent(ShutdownEffector.FORCE_SHUTDOWN_ON_ERROR, Boolean.TRUE);
    TaskAdaptable<Void> shutdownTask = Effectors.invocation(this, SHUTDOWN, shutdownParameters);
    //Mark inessential so that even if it fails the process stop task will run afterwards to clean up.
    TaskTags.markInessential(shutdownTask);
    DynamicTasks.queue(shutdownTask);
}
 
Example 12
Source File: LocationConfigUtilsTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
public void testPreferPublicKeyDataOverFileAndNoPrivateKeyRequired() throws Exception {
    ConfigBag config = ConfigBag.newInstance();
    config.put(LocationConfigKeys.PUBLIC_KEY_DATA, "mydata");
    config.put(LocationConfigKeys.PUBLIC_KEY_FILE, SSH_PUBLIC_KEY_FILE);
    config.put(LocationConfigKeys.PRIVATE_KEY_FILE, "");
    
    LocationConfigUtils.OsCredential creds = LocationConfigUtils.getOsCredential(config);
    String data = creds.getPublicKeyData();
    assertEquals(data, "mydata");
    Assert.assertNull(creds.getPreferredCredential());
    Assert.assertFalse(creds.hasPassword());
    Assert.assertFalse(creds.hasKey());
    // and not even any warnings here
    Assert.assertTrue(creds.getWarningMessages().isEmpty());
}
 
Example 13
Source File: StopAfterDurationPolicy.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Override
public void onEvent(SensorEvent<Lifecycle> event) {
    synchronized (eventLock) {
        if (!config().get(HAS_STARTED_TIMER) && config().get(STATE).equals(event.getValue())) {
            DurationSinceSensor sensor = new DurationSinceSensor(ConfigBag.newInstance(ImmutableMap.of(
                    DurationSinceSensor.SENSOR_NAME, getSensorName(),
                    DurationSinceSensor.SENSOR_PERIOD, config().get(POLL_PERIOD),
                    DurationSinceSensor.SENSOR_TYPE, Duration.class.getName())));
            sensor.apply(entity);
            config().set(HAS_STARTED_TIMER, true);
        }
    }
}
 
Example 14
Source File: LocationConfigUtilsTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Test(groups="Integration")  // requires ~/.ssh/id_rsa
public void testReadsPrivateKeyFileWithTildePath() throws Exception {
    ConfigBag config = ConfigBag.newInstance();
    config.put(LocationConfigKeys.PRIVATE_KEY_FILE, SSH_PRIVATE_KEY_FILE_WITH_TILDE);

    // don't mind if it has a passphrase
    String data = LocationConfigUtils.getOsCredential(config).doKeyValidation(false).getPreferredCredential();
    assertTrue(data != null && data.length() > 0);
}
 
Example 15
Source File: SshCommandEffector.java    From brooklyn-server with Apache License 2.0 4 votes vote down vote up
public SshCommandEffector(Map<String,String> params) {
    this(ConfigBag.newInstance(params));
}
 
Example 16
Source File: CompositeEffector.java    From brooklyn-server with Apache License 2.0 4 votes vote down vote up
public CompositeEffector(Map<?, ?> params) {
    this(ConfigBag.newInstance(params));
}
 
Example 17
Source File: AbstractLocation.java    From brooklyn-server with Apache License 2.0 4 votes vote down vote up
/**
 * @deprecated since 0.7.0; only used for legacy brooklyn types where constructor is called directly;
 * see overridden method for more info
 */
@SuppressWarnings("serial")
@Override
@Deprecated
public AbstractLocation configure(Map<?,?> properties) {
    assertNotYetManaged();
    
    boolean firstTime = !configured.getAndSet(true);
        
    config().putAll(properties);
    
    if (properties.containsKey(PARENT_LOCATION.getName())) {
        // need to ensure parent's list of children is also updated
        setParent(config().get(PARENT_LOCATION));
        
        // don't include parentLocation in configBag, as breaks rebind
        config().removeKey(PARENT_LOCATION);
    }

    // Allow config keys to be set by name (or deprecated name)
    //
    // The resulting `properties` will no longer contain the keys that we matched;
    // we will not also use them to for `SetFromFlag` etc.
    properties = ConfigUtilsInternal.setAllConfigKeys(properties, getLocationTypeInternal().getConfigKeys().values(), this);

    // NB: flag-setting done here must also be done in BasicLocationRebindSupport
    // Must call setFieldsFromFlagsWithBag, even if properites is empty, so defaults are extracted from annotations
    ConfigBag configBag = ConfigBag.newInstance(properties);
    FlagUtils.setFieldsFromFlagsWithBag(this, properties, configBag, firstTime);
    FlagUtils.setAllConfigKeys(this, configBag, false);

    if (properties.containsKey("displayName")) {
        name.set((String) removeIfPossible(properties, "displayName"));
        displayNameAutoGenerated = false;
    } else if (properties.containsKey("name")) {
        name.set((String) removeIfPossible(properties, "name"));
        displayNameAutoGenerated = false;
    } else if (isLegacyConstruction()) {
        name.set(getClass().getSimpleName()+":"+getId().substring(0, Math.min(getId().length(),4)));
        displayNameAutoGenerated = true;
    }

    // TODO Explicitly dealing with iso3166 here because want custom splitter rule comma-separated string.
    // Is there a better way to do it (e.g. more similar to latitude, where configKey+TypeCoercion is enough)?
    if (groovyTruth(properties.get("iso3166"))) {
        Object rawCodes = removeIfPossible(properties, "iso3166");
        Set<String> codes;
        if (rawCodes instanceof CharSequence) {
            codes = ImmutableSet.copyOf(Splitter.on(",").trimResults().split((CharSequence)rawCodes));
        } else {
            codes = TypeCoercions.coerce(rawCodes, new TypeToken<Set<String>>() {});
        }
        config().set(LocationConfigKeys.ISO_3166, codes);
    }
    
    return this;
}
 
Example 18
Source File: AddChildrenEffector.java    From brooklyn-server with Apache License 2.0 4 votes vote down vote up
public AddChildrenEffector(Map<String,String> params) {
    this(ConfigBag.newInstance(params));
}
 
Example 19
Source File: CreatePasswordSensor.java    From brooklyn-server with Apache License 2.0 4 votes vote down vote up
public CreatePasswordSensor(Map<String, String> params) {
    this(ConfigBag.newInstance(params));
}
 
Example 20
Source File: BasicJcloudsLocationCustomizer.java    From brooklyn-server with Apache License 2.0 4 votes vote down vote up
public BasicJcloudsLocationCustomizer(Map<?, ?> params) {
    this(ConfigBag.newInstance(params));
}