Java Code Examples for org.apache.brooklyn.util.collections.MutableMap#Builder

The following examples show how to use org.apache.brooklyn.util.collections.MutableMap#Builder . 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: SensorTransformer.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
public static SensorSummary sensorSummary(Entity entity, Sensor<?> sensor, UriBuilder ub) {
    URI applicationUri = serviceUriBuilder(ub, ApplicationApi.class, "get").build(entity.getApplicationId());
    URI entityUri = serviceUriBuilder(ub, EntityApi.class, "get").build(entity.getApplicationId(), entity.getId());
    URI selfUri = serviceUriBuilder(ub, SensorApi.class, "get").build(entity.getApplicationId(), entity.getId(), sensor.getName());

    MutableMap.Builder<String, URI> lb = MutableMap.<String, URI>builder()
            .put("self", selfUri)
            .put("application", applicationUri)
            .put("entity", entityUri)
            .put("action:json", selfUri);

    if (sensor instanceof AttributeSensor) {
        Iterable<RendererHints.NamedAction> hints = Iterables.filter(RendererHints.getHintsFor((AttributeSensor<?>)sensor), RendererHints.NamedAction.class);
        for (RendererHints.NamedAction na : hints) addNamedAction(lb, na , entity, sensor);
    }

    return new SensorSummary(sensor.getName(), sensor.getTypeName(), sensor.getDescription(), lb.build());
}
 
Example 2
Source File: JavaSoftwareProcessSshDriver.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
/**
 * Return the configuration properties required to enable JMX for a Java application.
 *
 * These should be set as properties in the {@code JAVA_OPTS} environment variable when calling the
 * run script for the application.
 */
protected Map<String, ?> getJmxJavaSystemProperties() {
    MutableMap.Builder<String, Object> result = MutableMap.<String, Object> builder();

    if (isJmxEnabled()) {
        new JmxSupport(getEntity(), getRunDir()).applyJmxJavaSystemProperties(result);
    }

    return result.build();
}
 
Example 3
Source File: SensorTransformer.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
static <T> void addNamedAction(MutableMap.Builder<String, URI> lb, RendererHints.NamedAction na, T value, Object contextKeyOrSensor, BrooklynObject contextObject) {
    if (na instanceof RendererHints.NamedActionWithUrl) {
        try {
            String v = ((RendererHints.NamedActionWithUrl<T>) na).getUrlFromValue(value);
            if (Strings.isNonBlank(v)) {
                String action = na.getActionName().toLowerCase();
                lb.putIfAbsent("action:"+action, URI.create(v));
            }
        } catch (Exception e) {
            Exceptions.propagateIfFatal(e);
            log.warn("Unable to make action "+na+" from "+contextKeyOrSensor+" on "+contextObject+": "+e, e);
        }
    }
}
 
Example 4
Source File: LocationTransformer.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
private static Map<String, ?> copyConfig(Map<String,?> entries, LocationDetailLevel level) {
    MutableMap.Builder<String, Object> builder = MutableMap.builder();
    if (level!=LocationDetailLevel.NONE) {
        for (Map.Entry<String,?> entry : entries.entrySet()) {
            if (level==LocationDetailLevel.FULL_INCLUDING_SECRET || !Sanitizer.IS_SECRET_PREDICATE.apply(entry.getKey())) {
                builder.put(entry.getKey(), WebResourceUtils.getValueForDisplay(entry.getValue(), true, false));
            }
        }
    }
    return builder.build();
}
 
Example 5
Source File: ConfigTransformer.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
public ConfigSummary transform() {
    MutableMap.Builder<String, URI> lb = new MutableMap.Builder<String, URI>();
    
    if (ub!=null && entity!=null) {
        URI self;
        if (adjunct!=null) {
            self = serviceUriBuilder(ub, AdjunctApi.class, "getConfig").build(entity.getApplicationId(), entity.getId(), adjunct.getId(), key.getName());
        } else {
            self = serviceUriBuilder(ub, EntityConfigApi.class, "get").build(entity.getApplicationId(), entity.getId(), key.getName());
        }
        lb.put("self", self);
        
        if (includeContextLinks) {
            // TODO wasteful including these
            lb.put("application", EntityTransformer.applicationUri(entity.getApplication(), ub) );
            lb.put("entity", EntityTransformer.entityUri(entity, ub) );
            if (adjunct!=null) {
                lb.put("adjunct", AdjunctTransformer.adjunctUri(entity, adjunct, ub) );
            }
        }
        if (includeActionLinks) {
            // TODO is this json or a display value?
            lb.put("action:json", self);
            
            Iterable<RendererHints.NamedAction> hints = Iterables.filter(RendererHints.getHintsFor(key), RendererHints.NamedAction.class);
            BrooklynObject context = adjunct!=null ? adjunct : entity;
            for (RendererHints.NamedAction na : hints) {
                SensorTransformer.addNamedAction(lb, na, context.getConfig(key), key, context);
            }
        }
        
    }

    // TODO if ui metadata not set try to infer or get more info from caller ?
    
    return new ConfigSummary(key, label, priority, pinned, lb.build());
}
 
Example 6
Source File: DeserializingProvider.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Beta
public Map<String, String> loadDeserializingMapping() {
    synchronized (this) {
        if (cache == null) {
            MutableMap.Builder<String, String> builder = MutableMap.<String, String>builder();
            for (ConfigLoader loader : loaders) {
                builder.putAll(loader.load());
            }
            cache = builder.build();
            LOG.debug("Config cache loaded, size {}", cache.size());
        }
        return cache;
    }
}
 
Example 7
Source File: JcloudsLocation.java    From brooklyn-server with Apache License 2.0 4 votes vote down vote up
protected JcloudsSshMachineLocation createJcloudsSshMachineLocation(
        ComputeService computeService, NodeMetadata node, Optional<Template> template,
        LoginCredentials userCredentials, HostAndPort managementHostAndPort, ConfigBag setup) throws IOException {

    Collection<JcloudsLocationCustomizer> customizers = getCustomizers(setup);
    Collection<MachineLocationCustomizer> machineCustomizers = getMachineCustomizers(setup);
    Map<?,?> sshConfig = extractSshConfig(setup, node);
    String nodeAvailabilityZone = extractAvailabilityZone(setup, node);
    String nodeRegion = extractRegion(setup, node);
    if (nodeRegion == null) {
        // e.g. rackspace doesn't have "region", so rackspace-uk is best we can say (but zone="LON")
        nodeRegion = extractProvider(setup, node);
    }

    if (LOG.isDebugEnabled()) {
        LOG.debug("creating JcloudsSshMachineLocation representation for {}@{} ({}) for {}/{}",
                new Object[]{
                        getUser(setup),
                        managementHostAndPort,
                        Sanitizer.sanitize(sshConfig),
                        getCreationString(setup),
                        node
                });
    }

    String address = managementHostAndPort.getHostText();
    int port = managementHostAndPort.hasPort() ? managementHostAndPort.getPort() : node.getLoginPort();
    
    // The display name will be one of the IPs of the VM (preferring public if there are any).
    // If the managementHostAndPort matches any of the IP contenders, then prefer that.
    // (Don't just use the managementHostAndPort, because that could be using DNAT so could be
    // a shared IP address, for example).
    String displayName = getPublicHostnameGeneric(node, setup, Optional.of(address));
    
    final Object password = sshConfig.get(SshMachineLocation.PASSWORD.getName()) != null
            ? sshConfig.get(SshMachineLocation.PASSWORD.getName())
            : userCredentials.getOptionalPassword().orNull();
    final Object privateKeyData = sshConfig.get(SshMachineLocation.PRIVATE_KEY_DATA.getName()) != null
            ? sshConfig.get(SshMachineLocation.PRIVATE_KEY_DATA.getName())
            : userCredentials.getOptionalPrivateKey().orNull();
    if (isManaged()) {
        final LocationSpec<JcloudsSshMachineLocation> spec = LocationSpec.create(JcloudsSshMachineLocation.class)
                .configure(sshConfig)
                .configure("displayName", displayName)
                .configure("address", address)
                .configure(JcloudsSshMachineLocation.SSH_PORT, port)
                .configure("user", userCredentials.getUser())
                // The use of `getName` is intentional. See 11741d85b9f54 for details.
                .configure(SshMachineLocation.PASSWORD.getName(), password)
                .configure(SshMachineLocation.PRIVATE_KEY_DATA.getName(), privateKeyData)
                .configure("jcloudsParent", this)
                .configure("node", node)
                .configure("template", template.orNull())
                .configureIfNotNull(CLOUD_AVAILABILITY_ZONE_ID, nodeAvailabilityZone)
                .configureIfNotNull(CLOUD_REGION_ID, nodeRegion)
                .configure(CALLER_CONTEXT, setup.get(CALLER_CONTEXT))
                .configure(SshMachineLocation.DETECT_MACHINE_DETAILS, setup.get(SshMachineLocation.DETECT_MACHINE_DETAILS))
                .configureIfNotNull(SshMachineLocation.SCRIPT_DIR, setup.get(SshMachineLocation.SCRIPT_DIR))
                .configureIfNotNull(USE_PORT_FORWARDING, setup.get(USE_PORT_FORWARDING))
                .configureIfNotNull(PORT_FORWARDER, setup.get(PORT_FORWARDER))
                .configureIfNotNull(PORT_FORWARDING_MANAGER, setup.get(PORT_FORWARDING_MANAGER))
                .configureIfNotNull(SshMachineLocation.PRIVATE_ADDRESSES, node.getPrivateAddresses())
                .configureIfNotNull(JCLOUDS_LOCATION_CUSTOMIZERS, customizers.size() > 0 ? customizers : null)
                .configureIfNotNull(MACHINE_LOCATION_CUSTOMIZERS, machineCustomizers.size() > 0 ? machineCustomizers : null);
        return getManagementContext().getLocationManager().createLocation(spec);
    } else {
        LOG.warn("Using deprecated JcloudsSshMachineLocation constructor because " + this + " is not managed");
        final MutableMap.Builder<Object, Object> builder = MutableMap.builder()
            .putAll(sshConfig)
            .put("displayName", displayName)
            .put("address", address)
            .put("port", port)
            .put("user", userCredentials.getUser())
            // The use of `getName` is intentional. See 11741d85b9f54 for details.
            .putIfNotNull(SshMachineLocation.PASSWORD.getName(), password)
            .putIfNotNull(SshMachineLocation.PRIVATE_KEY_DATA.getName(), privateKeyData)
            .put("callerContext", setup.get(CALLER_CONTEXT))
            .putIfNotNull(CLOUD_AVAILABILITY_ZONE_ID.getName(), nodeAvailabilityZone)
            .putIfNotNull(CLOUD_REGION_ID.getName(), nodeRegion)
            .put(USE_PORT_FORWARDING, setup.get(USE_PORT_FORWARDING))
            .put(PORT_FORWARDER, setup.get(PORT_FORWARDER))
            .put(PORT_FORWARDING_MANAGER, setup.get(PORT_FORWARDING_MANAGER))
            .put(SshMachineLocation.PRIVATE_ADDRESSES, node.getPrivateAddresses());
        if (customizers.size() > 0) {
            builder.put(JCLOUDS_LOCATION_CUSTOMIZERS, customizers);
        }
        if (machineCustomizers.size() > 0) {
            builder.put(MACHINE_LOCATION_CUSTOMIZERS, machineCustomizers);
        }
        final MutableMap<Object, Object> properties = builder.build();
        return new JcloudsSshMachineLocation(properties, this, node);
    }
}
 
Example 8
Source File: JmxSupport.java    From brooklyn-server with Apache License 2.0 4 votes vote down vote up
/** applies _some_ of the common settings needed to connect via JMX */
public void applyJmxJavaSystemProperties(MutableMap.Builder<String,Object> result) {
    if (!isJmx()) return ;

    Integer jmxPort = Preconditions.checkNotNull(entity.getAttribute(JMX_PORT), "jmx port must not be null for %s", entity);
    HostAndPort jmx = BrooklynAccessUtils.getBrooklynAccessibleAddress(entity, jmxPort);
    Integer jmxRemotePort = getEntity().getAttribute(JMX_PORT);
    String hostName = jmx.getHostText();

    result.put("com.sun.management.jmxremote", null);
    result.put("java.rmi.server.hostname", hostName);

    switch (getJmxAgentMode()) {
    case JMXMP_AND_RMI:
        Integer rmiRegistryPort = Preconditions.checkNotNull(entity.getAttribute(UsesJmx.RMI_REGISTRY_PORT), "registry port (config val %s)", entity.getConfig(UsesJmx.RMI_REGISTRY_PORT));
        result.put(JmxmpAgent.RMI_REGISTRY_PORT_PROPERTY, rmiRegistryPort);
    case JMXMP:
        if (jmxRemotePort==null || jmxRemotePort<=0)
            throw new IllegalStateException("Unsupported JMX port "+jmxRemotePort+" - when applying system properties ("+getJmxAgentMode()+" / "+getEntity()+")");
        result.put(JmxmpAgent.JMXMP_PORT_PROPERTY, jmxRemotePort);
        // with JMXMP don't try to tell it the hostname -- it isn't needed for JMXMP, and if specified
        // it will break if the hostname we see is not known at the server, e.g. a forwarding public IP
        result.remove("java.rmi.server.hostname");
        break;
    case JMX_RMI_CUSTOM_AGENT:
        if (jmxRemotePort==null || jmxRemotePort<=0)
            throw new IllegalStateException("Unsupported JMX port "+jmxRemotePort+" - when applying system properties ("+getJmxAgentMode()+" / "+getEntity()+")");
        result.put(JmxRmiAgent.RMI_REGISTRY_PORT_PROPERTY, Preconditions.checkNotNull(entity.getAttribute(UsesJmx.RMI_REGISTRY_PORT), "registry port"));
        result.put(JmxRmiAgent.JMX_SERVER_PORT_PROPERTY, jmxRemotePort);
        break;
    case NONE:
        jmxRemotePort = fixPortsForModeNone();
    case JMX_RMI:
        result.put("com.sun.management.jmxremote.port", jmxRemotePort);
        result.put("java.rmi.server.useLocalHostname", "true");
        break;
    default:
        throw new IllegalStateException("Unsupported JMX mode - when applying system properties ("+getJmxAgentMode()+" / "+getEntity()+")");
    }

    if (isSecure()) {
        // set values true, and apply keys pointing to keystore / truststore
        getJmxSslSupport().applyAgentJmxJavaSystemProperties(result);
    } else {
        result.
            put("com.sun.management.jmxremote.ssl", false).
            put("com.sun.management.jmxremote.authenticate", false);
    }
}
 
Example 9
Source File: SensorTransformer.java    From brooklyn-server with Apache License 2.0 4 votes vote down vote up
private static <T> void addNamedAction(MutableMap.Builder<String, URI> lb, RendererHints.NamedAction na , Entity entity, Sensor<T> sensor) {
    addNamedAction(lb, na, entity.getAttribute( ((AttributeSensor<T>) sensor) ), sensor, entity);
}