Java Code Examples for org.apache.brooklyn.util.collections.MutableMap#addIfNotNull()

The following examples show how to use org.apache.brooklyn.util.collections.MutableMap#addIfNotNull() . 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: BrooklynNodeImpl.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@Override
public Void call(ConfigBag parameters) {
    MutableMap<String, String> formParams = MutableMap.of();
    Lifecycle initialState = entity().getAttribute(Attributes.SERVICE_STATE_ACTUAL);
    ServiceStateLogic.setExpectedState(entity(), Lifecycle.STOPPING);
    for (ConfigKey<?> k: new ConfigKey<?>[] { STOP_APPS_FIRST, FORCE_SHUTDOWN_ON_ERROR, SHUTDOWN_TIMEOUT, REQUEST_TIMEOUT, DELAY_FOR_HTTP_RETURN })
        formParams.addIfNotNull(k.getName(), toNullableString(parameters.get(k)));
    try {
        log.debug("Shutting down "+entity()+" with "+formParams);
        HttpToolResponse resp = ((BrooklynNode)entity()).http()
            .post("/v1/server/shutdown",
                ImmutableMap.of("Brooklyn-Allow-Non-Master-Access", "true"),
                formParams);
        if (resp.getResponseCode() != HttpStatus.SC_NO_CONTENT) {
            throw new IllegalStateException("Response code "+resp.getResponseCode());
        }
    } catch (Exception e) {
        Exceptions.propagateIfFatal(e);
        throw new PropagatedRuntimeException("Error shutting down remote node "+entity()+" (in state "+initialState+"): "+Exceptions.collapseText(e), e);
    }
    ServiceNotUpLogic.updateNotUpIndicator(entity(), SHUTDOWN.getName(), "Shutdown of remote node has completed successfuly");
    return null;
}
 
Example 2
Source File: LogoutResource.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Override
public Response logout(String unauthorize, String requestedUser) {
    MultiSessionAttributeAdapter session = MultiSessionAttributeAdapter.of(req, false);
    WebEntitlementContext ctx = (WebEntitlementContext) Entitlements.getEntitlementContext();
    String currentUser = ctx==null ? null : ctx.user();
    log.debug("Logging out: {}, session id {} ({})"+", unauthorized={}", currentUser, (session!=null ? session.getId()+" " : ""), session, unauthorize);
    
    MutableMap<String,String> body = MutableMap.of();
    body.addIfNotNull("currentUser", currentUser);
    body.addIfNotNull("requestedUser", requestedUser);
    body.addIfNotNull("sessionId", session==null ? null : session.getId());
    body.addIfNotNull("requestedSessionId", req.getRequestedSessionId());
    
    if (requestedUser!=null && !requestedUser.equals(currentUser)) {
        return Response.status(Status.FORBIDDEN)
            .entity(body.add("message", "The user requested to be logged out is not the user currently logged in"))
            .build();
    }
    doLogout();

    if (unauthorize!=null) {
        // returning 401 UNAUTHORIZED has the nice property that it causes browser (mostly)
        // to re-prompt for cached credentials to set in the "Authorization: " header to re-login;
        // however it's not 100%; e.g. in Chrome if there is an active ajax/$http request that had prompted for
        // credentials it will keep the Authorization header and log you back in (eg /server/up/extended);
        // it is a known issue that we cannot absolutely clear creds in most browsers, but returning 401 helps
        return Response.status(Status.UNAUTHORIZED)
            .entity(body.add("message", unauthorize))
            .build();
    }
    
    return Response.status(Status.OK)
            .entity(body.add("message", "Logged out user "+currentUser))
            .build();
}
 
Example 3
Source File: BrooklynRestResourceUtils.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
protected Map<?, ?> getRenderingConfigurationFor(String catalogId) {
    MutableMap<Object, Object> result = MutableMap.of();
    RegisteredType item = mgmt.getTypeRegistry().get(catalogId);
    if (item==null) return result;
    
    result.addIfNotNull("iconUrl", item.getIconUrl());
    return result;
}
 
Example 4
Source File: BasicConfigKey.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Override
public Map<ConfigInheritanceContext,ConfigInheritance> getInheritanceByContext() {
    MutableMap<ConfigInheritanceContext, ConfigInheritance> result = MutableMap.of();
    for (InheritanceContext context: InheritanceContext.values()) {
        result.addIfNotNull(context, getInheritanceByContext(context));
    }
    return result;
}
 
Example 5
Source File: SshCommandEffector.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
public SshEffectorTaskFactory<String> makePartialTaskFactory(ConfigBag params, Entity entity) {
    String sshCommand = SshCommandSensor.makeCommandExecutingInDirectory(command, executionDir, entity);

    MutableMap<String, Object> env = MutableMap.of();

    // Set all declared parameters, including default values
    for (ParameterType<?> param : effector.getParameters()) {
        env.addIfNotNull(param.getName(), params.get(Effectors.asConfigKey(param)));
    }

    // Set things from the entity's defined shell environment, if applicable
    env.putAll(entity.config().get(BrooklynConfigKeys.SHELL_ENVIRONMENT));

    // Set the parameters we've been passed. This will repeat declared parameters but to no harm,
    // it may pick up additional values (could be a flag defining whether this is permitted or not.)
    // Make sure we do not include the shell.env here again, by filtering it out.
    env.putAll(Maps.filterKeys(params.getAllConfig(), Predicates.not(Predicates.equalTo(EFFECTOR_SHELL_ENVIRONMENT.getName()))));

    // Add the shell environment entries from the effector configuration
    if (shellEnv != null) env.putAll(shellEnv);

    // Add the shell environment entries from our invocation
    Map<String, Object> effectorEnv = params.get(EFFECTOR_SHELL_ENVIRONMENT);
    if (effectorEnv != null) env.putAll(effectorEnv);
    
    // Try to resolve the configuration in the env Map
    try {
        env = MutableMap.copyOf(resolveEnv(env));
    } catch (InterruptedException | ExecutionException e) {
        Exceptions.propagateIfFatal(e);
    }

    // Execute the effector with the serialized environment strings
    ShellEnvironmentSerializer serializer = new ShellEnvironmentSerializer(entity().getManagementContext());

    return SshEffectorTasks.ssh(sshCommand)
            .requiringZeroAndReturningStdout()
            .environmentVariables(serializer.serialize(env));
}
 
Example 6
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;
}