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

The following examples show how to use org.apache.brooklyn.util.core.config.ConfigBag#getStringKey() . 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: JcloudsLocation.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
/**
 * If the ImageChooser is a string, then try instantiating a class with that name (in the same
 * way as we do for {@link #getCloudMachineNamer(ConfigBag)}, for example). Otherwise, assume
 * that convention TypeCoercions will work.
 */
@SuppressWarnings("unchecked")
protected Function<Iterable<? extends Image>, Image> getImageChooser(ComputeService computeService, ConfigBag config) {
    Function<Iterable<? extends Image>, Image> chooser;
    Object rawVal = config.getStringKey(JcloudsLocationConfig.IMAGE_CHOOSER.getName());
    if (rawVal instanceof String && Strings.isNonBlank((String)rawVal)) {
        // Configured with a string: it could be a class that we need to instantiate
        Class<?> clazz;
        try {
            clazz = new ClassLoaderUtils(this.getClass(), getManagementContext()).loadClass((String)rawVal);
        } catch (ClassNotFoundException e) {
            throw new IllegalStateException("Could not load configured ImageChooser " + rawVal, e);
        }
        Maybe<?> instance = Reflections.invokeConstructorFromArgs(clazz);
        if (!instance.isPresent()) {
            throw new IllegalStateException("Failed to create ImageChooser "+rawVal+" for location "+this);
        } else if (!(instance.get() instanceof Function)) {
            throw new IllegalStateException("Failed to create ImageChooser "+rawVal+" for location "+this+"; expected type Function but got "+instance.get().getClass());
        } else {
            chooser = (Function<Iterable<? extends Image>, Image>) instance.get();
        }
    } else {
        chooser = config.get(JcloudsLocationConfig.IMAGE_CHOOSER);
    }
    return BrooklynImageChooser.cloneFor(chooser, computeService, config);
}
 
Example 2
Source File: MachineLifecycleEffectorTasks.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
/**
 * Returns the {@link EffectorBody} which supplies the implementation for the start effector.
 * <p>
 * Calls {@link #start(Collection)} in this class.
 */
public EffectorBody<Void> newStartEffectorTask() {
    // TODO included anonymous inner class for backwards compatibility with persisted state.
    new EffectorBody<Void>() {
        @Override
        public Void call(ConfigBag parameters) {
            Collection<? extends Location> locations  = null;

            Object locationsRaw = parameters.getStringKey(LOCATIONS.getName());
            locations = Locations.coerceToCollectionOfLocationsManaged(entity().getManagementContext(), locationsRaw);

            if (locations==null) {
                // null/empty will mean to inherit from parent
                locations = Collections.emptyList();
            }

            start(locations);
            return null;
        }
    };
    return new StartEffectorBody();
}
 
Example 3
Source File: BrooklynEntityDecorationResolver.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@Override
protected Iterable<Object> getDecorationAttributeJsonValue(ConfigBag attrs) {
    Object brooklynTags = attrs.getStringKey(BrooklynCampReservedKeys.BROOKLYN_TAGS);
    if (brooklynTags == null) {
        return null;
    } else if (!(brooklynTags instanceof List)) {
        throw new IllegalArgumentException(BrooklynCampReservedKeys.BROOKLYN_TAGS + " should be a List of String elements. You supplied " + brooklynTags);
    } else {
        checkArgument(Iterables.all((List<?>) brooklynTags, new Predicate<Object>() {
            @Override
            public boolean apply(Object input) {
                return !(input instanceof DeferredSupplier);
            }
        }), BrooklynCampReservedKeys.BROOKLYN_TAGS + " should not contain DeferredSupplier. A DeferredSupplier is made when using $brooklyn:attributeWhenReady. You supplied " + brooklynTags);
        @SuppressWarnings("unchecked")
        List<Object> result = (List<Object>)brooklynTags;
        return result;
    }
}
 
Example 4
Source File: CouchbaseNodeImpl.java    From brooklyn-library with Apache License 2.0 6 votes vote down vote up
/** exposed through {@link CouchbaseNode#ADD_REPLICATION_RULE} */
protected void addReplicationRule(ConfigBag ruleArgs) {
    Object toClusterO = Preconditions.checkNotNull(ruleArgs.getStringKey("toCluster"), "toCluster must not be null");
    if (toClusterO instanceof String) {
        toClusterO = getManagementContext().lookup((String)toClusterO);
    }
    Entity toCluster = Tasks.resolving(toClusterO, Entity.class).context(this).get();

    String fromBucket = Preconditions.checkNotNull( (String)ruleArgs.getStringKey("fromBucket"), "fromBucket must be specified" );

    String toBucket = (String)ruleArgs.getStringKey("toBucket");
    if (toBucket==null) toBucket = fromBucket;

    if (!ruleArgs.getUnusedConfig().isEmpty()) {
        throw new IllegalArgumentException("Unsupported replication rule data: "+ruleArgs.getUnusedConfig());
    }

    getDriver().addReplicationRule(toCluster, fromBucket, toBucket);
}
 
Example 5
Source File: EffectorTaskTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Override
public Void call(ConfigBag parameters) {
    AtomicBoolean lock = (AtomicBoolean)parameters.getStringKey("lock");
    synchronized(lock) {
        if (!lock.get()) {
            try {
                lock.wait();
            } catch (InterruptedException e) {
                Exceptions.propagate(e);
            }
        }
    }
    return null;
}
 
Example 6
Source File: EffectorTaskTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Override
public Integer call(ConfigBag parameters) {
    // do a sanity check
    Assert.assertNotNull(entity());
    
    // finally double the input
    return 2*(Integer)parameters.getStringKey("numberToDouble");
}
 
Example 7
Source File: InvokeEffectorOnCollectionSensorChangeRebindTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Override
public Void call(ConfigBag parameters) {
    synchronized (PublishingEffector.class) {
        Collection<Object> values = entity().sensors().get(REMOVED_EFFECTOR_VALUES);
        if (values == null) {
            values = Sets.newHashSet();
        }
        final Object v = parameters.getStringKey("value");
        values.add(v);
        entity().sensors().set(REMOVED_EFFECTOR_VALUES, values);
        return null;
    }
}
 
Example 8
Source File: SingleMachineLocationResolver.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Override
public LocationSpec<?> newLocationSpecFromString(String spec, Map<?, ?> locationFlags, LocationRegistry registry) {
    ConfigBag config = extractConfig(locationFlags, spec, registry);
    @SuppressWarnings("rawtypes")
    Map globalProperties = registry.getProperties();
    String namedLocation = (String) locationFlags.get(LocationInternal.NAMED_SPEC_NAME.getName());
    
    if (registry != null) {
        LocationPropertiesFromBrooklynProperties.setLocalTempDir(globalProperties, config);
    }

    if (config.getStringKey("target") == null) {
        throw new IllegalArgumentException("target must be specified in single-machine spec");
    }
    String target = config.getStringKey("target").toString();
    config.remove("target");
    Maybe<LocationSpec<?>> testResolve = managementContext.getLocationRegistry().getLocationSpec(target);
    if (!testResolve.isPresent()) {
        throw new IllegalArgumentException("Invalid target location '" + target + "' for location '"+SINGLE+"': "+
            Exceptions.collapseText( Maybe.getException(testResolve) ), Maybe.getException(testResolve));
    }
    
    return LocationSpec.create(SingleMachineProvisioningLocation.class)
            .configure("location", target)
            .configure("locationFlags", config.getAllConfig())
            .configure(LocationConfigUtils.finalAndOriginalSpecs(spec, locationFlags, globalProperties, namedLocation));
}
 
Example 9
Source File: JcloudsLocation.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
/**
 * Finds a node matching the properties given in config or throws an exception.
 * @param config
 * @return
 */
protected NodeMetadata findNodeOrThrow(ConfigBag config) {
    String user = checkNotNull(getUser(config), "user");
    String rawId = (String) config.getStringKey("id");
    String rawHostname = (String) config.getStringKey("hostname");
    Predicate<ComputeMetadata> predicate = getRebindToMachinePredicate(config);
    LOG.debug("Finding VM {} ({}@{}), in jclouds location for provider {} matching {}", new Object[]{
            rawId != null ? rawId : "<lookup>",
            user,
            rawHostname != null ? rawHostname : "<unspecified>",
            getProvider(),
            predicate
    });
    ComputeService computeService = getComputeService(config);
    Set<? extends NodeMetadata> candidateNodes = computeService.listNodesDetailsMatching(predicate);
    if (candidateNodes.isEmpty()) {
        throw new IllegalArgumentException("Jclouds node not found for rebind with predicate " + predicate);
    } else if (candidateNodes.size() > 1) {
        throw new IllegalArgumentException("Jclouds node for rebind matched multiple with " + predicate + ": " + candidateNodes);
    }
    NodeMetadata node = Iterables.getOnlyElement(candidateNodes);

    OsCredential osCredentials = LocationConfigUtils.getOsCredential(config).checkNoErrors().logAnyWarnings();
    String pkd = osCredentials.getPrivateKeyData();
    String password = osCredentials.getPassword();
    LoginCredentials expectedCredentials = node.getCredentials();
    if (Strings.isNonBlank(pkd)) {
        expectedCredentials = LoginCredentials.fromCredentials(new Credentials(user, pkd));
    } else if (Strings.isNonBlank(password)) {
        expectedCredentials = LoginCredentials.fromCredentials(new Credentials(user, password));
    } else if (expectedCredentials == null) {
        //need some kind of credential object, or will get NPE later
        expectedCredentials = LoginCredentials.fromCredentials(new Credentials(user, null));
    }
    node = NodeMetadataBuilder.fromNodeMetadata(node).credentials(expectedCredentials).build();

    return node;
}
 
Example 10
Source File: MachineLifecycleEffectorTasks.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Override
public Void call(ConfigBag parameters) {
    Collection<? extends Location> locations = null;

    Object locationsRaw = parameters.getStringKey(LOCATIONS.getName());
    locations = Locations.coerceToCollectionOfLocationsManaged(entity().getManagementContext(), locationsRaw);

    if (locations == null) {
        // null/empty will mean to inherit from parent
        locations = Collections.emptyList();
    }

    start(locations);
    return null;
}
 
Example 11
Source File: BrooklynNodeImpl.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
public static Map<String,Object> asMap(ConfigBag parameters, ConfigKey<?> key) {
    Object v = parameters.getStringKey(key.getName());
    if (v==null || (v instanceof String && Strings.isBlank((String)v)))
        return null;
    if (v instanceof Map) 
        return (Map<String, Object>) v;
    
    if (v instanceof String) {
        // TODO ideally, parse YAML 
        return new Gson().fromJson((String)v, Map.class);
    }
    throw new IllegalArgumentException("Invalid "+JavaClassNames.simpleClassName(v)+" value for "+key+": "+v);
}
 
Example 12
Source File: EffectorTaskTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Override
public Integer call(ConfigBag parameters) {
    int input = (Integer)parameters.getStringKey("numberToStartWith");
    // note the subtasks must be queued explicitly with a basic task
    // (but with the DynamicSequentialTask they can be resolved by the task itself; see above)
    Task<Integer> product = queue(times(input, 2));
    queue( addBasic(product, 1) );
    return last(Integer.class);
}
 
Example 13
Source File: EffectorTaskTest.java    From brooklyn-server with Apache License 2.0 4 votes vote down vote up
@Override
public Integer call(ConfigBag parameters) {
    int input = (Integer)parameters.getStringKey("numberToStartWith");
    queue( add(times(input, 2), 1) );
    return last(Integer.class);
}
 
Example 14
Source File: MaxConcurrencySensor.java    From brooklyn-server with Apache License 2.0 4 votes vote down vote up
public MaxConcurrencySensor(ConfigBag params) {
    this.sensorName = params.get(SENSOR_NAME);
    this.maxConcurrency = params.getStringKey(MAX_CONCURRENCY.getName());
}
 
Example 15
Source File: ByonLocationResolver.java    From brooklyn-server with Apache License 2.0 4 votes vote down vote up
@Override
protected ConfigBag extractConfig(Map<?,?> locationFlags, String spec, LocationRegistry registry) {
    ConfigBag config = super.extractConfig(locationFlags, spec, registry);

    Object hosts = config.getStringKey("hosts");
    config.remove("hosts");
    String user = (String) config.getStringKey("user");
    Integer port = TypeCoercions.coerce(config.getStringKey("port"), Integer.class);
    Class<? extends MachineLocation> locationClass = getLocationClass(config.get(OS_FAMILY));

    MutableMap<String, Object> defaultProps = MutableMap.of();
    defaultProps.addIfNotNull("user", user);
    defaultProps.addIfNotNull("port", port);

    List<?> hostAddresses;
    
    if (hosts instanceof String) {
        if (((String) hosts).isEmpty()) {
            hostAddresses = ImmutableList.of();
        } else {
            hostAddresses = WildcardGlobs.getGlobsAfterBraceExpansion("{"+hosts+"}",
                    true /* numeric */, /* no quote support though */ PhraseTreatment.NOT_A_SPECIAL_CHAR, PhraseTreatment.NOT_A_SPECIAL_CHAR);
        }
    } else if (hosts instanceof Iterable) {
        hostAddresses = ImmutableList.copyOf((Iterable<?>)hosts);
    } else {
        throw new IllegalArgumentException("Invalid location '"+spec+"'; at least one host must be defined");
    }
    if (hostAddresses.isEmpty()) {
        throw new IllegalArgumentException("Invalid location '"+spec+"'; at least one host must be defined");
    }
    
    List<LocationSpec<? extends MachineLocation>> machineSpecs = Lists.newArrayList();
    for (Object host : hostAddresses) {
        LocationSpec<? extends MachineLocation> machineSpec;
        if (host instanceof String) {
            machineSpec = parseMachine((String)host, locationClass, defaultProps, spec);
        } else if (host instanceof Map) {
            machineSpec = parseMachine((Map<String, ?>)host, locationClass, defaultProps, spec);
        } else {
            throw new IllegalArgumentException("Expected machine to be String or Map, but was "+host.getClass().getName()+" ("+host+")");
        }
        machineSpec.configureIfNotNull(LocalLocationManager.CREATE_UNMANAGED, config.get(LocalLocationManager.CREATE_UNMANAGED));
        machineSpecs.add(machineSpec);
    }
    
    config.put(FixedListMachineProvisioningLocation.MACHINE_SPECS, machineSpecs);

    return config;
}
 
Example 16
Source File: BrooklynEntityDecorationResolver.java    From brooklyn-server with Apache License 2.0 4 votes vote down vote up
@Override
protected Object getDecorationAttributeJsonValue(ConfigBag attrs) {
    return attrs.getStringKey(BrooklynCampReservedKeys.BROOKLYN_PARAMETERS);
}
 
Example 17
Source File: BrooklynEntityDecorationResolver.java    From brooklyn-server with Apache License 2.0 4 votes vote down vote up
@Override
protected Object getDecorationAttributeJsonValue(ConfigBag attrs) {
    return attrs.getStringKey(BrooklynCampReservedKeys.BROOKLYN_INITIALIZERS);
}
 
Example 18
Source File: BrooklynEntityDecorationResolver.java    From brooklyn-server with Apache License 2.0 4 votes vote down vote up
@Override
protected Object getDecorationAttributeJsonValue(ConfigBag attrs) {
    return attrs.getStringKey(BrooklynCampReservedKeys.BROOKLYN_ENRICHERS);
}
 
Example 19
Source File: BrooklynEntityDecorationResolver.java    From brooklyn-server with Apache License 2.0 4 votes vote down vote up
@Override
protected Object getDecorationAttributeJsonValue(ConfigBag attrs) {
    return attrs.getStringKey(BrooklynCampReservedKeys.BROOKLYN_POLICIES);
}
 
Example 20
Source File: RebindToMachinePredicate.java    From brooklyn-server with Apache License 2.0 4 votes vote down vote up
public RebindToMachinePredicate(ConfigBag config) {
    rawId = (String) config.getStringKey("id");
    rawHostname = (String) config.getStringKey("hostname");
    rawRegion = (String) config.getStringKey("region");
}