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

The following examples show how to use org.apache.brooklyn.util.collections.MutableMap#of() . 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: InternalFactory.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
/**
 * Constructs an instance (e.g. of entity, location, enricher or policy.
 * Checks if special instructions on the spec, if supplied;
 * else if new-style class, calls no-arg constructor (ignoring spec); 
 * else if old-style, uses flags if avail as args or as spec and passes to constructor.
 */
protected <T> T construct(Class<? extends T> clazz, AbstractBrooklynObjectSpec<?,?> optionalSpec, Map<String,?> optionalOldStyleConstructorFlags) {
    try {
        if (optionalSpec!=null) {
            ConfigBag bag = ConfigBag.newInstance(optionalSpec.getConfig());
            Class<? extends SpecialBrooklynObjectConstructor> special = bag.get(SpecialBrooklynObjectConstructor.Config.SPECIAL_CONSTRUCTOR);
            if (special!=null) {
                // special construction requested; beta and very limited scope; see SpecialBrooklynObjectConstructor 
                return constructWithSpecial(special, clazz, optionalSpec);
            }
        }
        
        if (isNewStyle(clazz)) {
            return constructNewStyle(clazz);
        } else {
            MutableMap<String,Object> constructorFlags = MutableMap.of();
            if (optionalOldStyleConstructorFlags!=null) constructorFlags.add(optionalOldStyleConstructorFlags);
            else constructorFlags.add(optionalSpec.getFlags());
            
            return constructOldStyle(clazz, MutableMap.copyOf(constructorFlags));
        }
    } catch (Exception e) {
        throw Exceptions.propagate(e);
     }
 }
 
Example 2
Source File: FixedListMachineProvisioningLocationTest.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@Test
public void testCanAddMachineToPool() throws UnknownHostException, NoMachinesAvailableException {
    SshMachineLocation machine2 = new SshMachineLocation(
            MutableMap.of("address", Inet4Address.getByName("192.168.144.200")));
    provisioner2 = new FixedListMachineProvisioningLocation<SshMachineLocation>(
            MutableMap.of("machines", MutableList.of()));
    provisioner2.addMachine(machine2);
    
    assertEquals(ImmutableList.copyOf(provisioner2.getChildren()), ImmutableList.of(machine2));
    assertEquals(ImmutableSet.copyOf(provisioner2.getAvailable()), ImmutableSet.of(machine2));
    
    SshMachineLocation obtained = provisioner2.obtain();
    assertEquals(obtained, machine2);
    
    // Can only obtain the added machien once though (i.e. not added multiple times somehow)
    try {
        SshMachineLocation obtained2 = provisioner2.obtain();
        fail("obtained="+obtained2);
    } catch (NoMachinesAvailableException e) {
        // success
    }
}
 
Example 3
Source File: SimpleJcloudsLocationUserLoginAndConfigLiveTest.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("rawtypes")
@Test(groups="Live")
public void testJcloudsCreateBogStandardWithUserBrooklyn() throws Exception {
    log.info("TEST testJcloudsCreateBogStandardWithUserBrooklyn");
    JcloudsSshMachineLocation m1 = obtainMachine(MutableMap.of("user", "brooklyn"));

    Map details = MutableMap.of("id", m1.getJcloudsId(), "hostname", m1.getAddress().getHostAddress(), "user", m1.getUser());
    log.info("got machine "+m1+" at "+jcloudsLocation+": "+details+"; now trying to rebind");
    String result;
    // echo conflates spaces of arguments
    result = execWithOutput(m1, Arrays.asList("echo trying  m1", "hostname", "date"));
    Assert.assertTrue(result.contains("trying m1"));
    
    log.info("now trying rebind "+m1);
    JcloudsSshMachineLocation m2 = (JcloudsSshMachineLocation) jcloudsLocation.registerMachine(details);
    result = execWithOutput(m2, Arrays.asList("echo trying  m2", "hostname", "date"));
    Assert.assertTrue(result.contains("trying m2"));
    
    Assert.assertEquals(m2.getUser(), "brooklyn");
}
 
Example 4
Source File: SshMachineLocationPerformanceTest.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@Test(groups = {"Integration"})
public void testConsecutiveSmallCommandsWithDifferentProperties() throws Exception {
    final Map<String, ?> emptyProperties = Collections.emptyMap();
    final Map<String, ?> customProperties = MutableMap.of(
            "address", Networking.getReachableLocalHost(),
            SshTool.PROP_SESSION_TIMEOUT.getName(), 20000,
            SshTool.PROP_CONNECT_TIMEOUT.getName(), 50000,
            SshTool.PROP_SCRIPT_HEADER.getName(), "#!/bin/bash");

    Runnable task = new Runnable() {
        @Override public void run() {
            if (Math.random() < 0.5) {
                machine.execScript(emptyProperties, "test", ImmutableList.of("true"));
            } else {
                machine.execScript(customProperties, "test", ImmutableList.of("true"));
            }
        }};
    runMany(task, "small-cmd-custom-ssh-properties", 1, 10);
}
 
Example 5
Source File: OsgiConfigLoader.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
private Map<String, String> dictToMap(Dictionary<String, Object> props) {
    Map<String, String> mapProps = MutableMap.of();
    Enumeration<String> keyEnum = props.keys();
    while (keyEnum.hasMoreElements()) {
        String key = keyEnum.nextElement();
        if (!EXCLUDED_KEYS.contains(key)) {
            mapProps.put(key, (String) props.get(key));
        }
    }
    return mapProps;
}
 
Example 6
Source File: SaltHighstate.java    From brooklyn-library with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
private static void addStateModuleValue(String id, Entity entity, Map<String, List<Object>> stateInfo,
    String stateModule) {

    if (isSaltInternal(stateModule)) {
        return;
    }
    try {
        final List<Object> stateEntries = stateInfo.get(stateModule);
        String stateFunction = "";
        Map<String, Object> moduleSettings = MutableMap.of();
        for (Object entry : stateEntries) {
            if (entry instanceof Map) {
                moduleSettings.putAll((Map<String, Object>)entry);
            } else {
                stateFunction = entry.toString();
            }
        }

        final String name = sensorName(id, stateModule, stateFunction);
        final AttributeSensor<Map<String, Object>> newSensor =
            Sensors.newSensor(STATE_FUNCTION_TYPE, HIGHSTATE_SENSOR_PREFIX + "." + name, name);
        entity.sensors().set(newSensor, moduleSettings);

        LOG.debug("Sensor set for: {}", moduleSettings);
    } catch (ClassCastException e) {
        LOG.info("Unexpected structure for state module {}, skipping ({})", id + "." + stateModule, e.getMessage());
    }
}
 
Example 7
Source File: PlanInterpretationNode.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
protected void applyToMap() {
    Map<Object, Object> input = MutableMap.<Object,Object>copyOf((Map<?,?>)originalValue);
    Map<Object, Object> result = MutableMap.<Object,Object>of();
    newValue = result;

    // first do a "whole-node" application
    if (getContext().getAllInterpreter().applyMapBefore(this, input)) {

        for (Map.Entry<Object,Object> entry: input.entrySet()) {
            // then recurse in to this node and do various in-the-node applications
            PlanInterpretationNode value = newPlanInterpretation(this, Role.MAP_VALUE, entry.getValue());
            value.apply();

            PlanInterpretationNode key = newPlanInterpretation(this, Role.MAP_KEY, entry.getKey());
            key.apply();

            if (key.isChanged() || value.isChanged()) 
                changed = true;

            if (getContext().getAllInterpreter().applyMapEntry(this, input, result, key, value))
                result.put(key.getNewValue(), value.getNewValue());
            else
                changed = true;
        }

        // finally try applying to this node again
        getContext().getAllInterpreter().applyMapAfter(this, input, result);
    }

    if (changed==null) changed = false;
}
 
Example 8
Source File: RebindLocationTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Test
public void testRestoresLocationIdAndDisplayName() throws Exception {
    MyLocation origLoc = new MyLocation(MutableMap.of("name", "mylocname"));
    origApp.start(ImmutableList.of(origLoc));
    
    newApp = rebind();
    MyLocation newLoc = (MyLocation) Iterables.get(newApp.getLocations(), 0);
    
    assertEquals(newLoc.getId(), origLoc.getId());
    assertEquals(newLoc.getDisplayName(), origLoc.getDisplayName());
}
 
Example 9
Source File: AbstractRelationModifier.java    From SeaCloudsPlatform with Apache License 2.0 5 votes vote down vote up
protected Map<String, Object> getRelationPropertiesValues(Map<String, Object> requirement) {
    Map<String, Object> properties = MutableMap.of();
    properties.put(PROP_COLLECTION, getPropCollection(requirement));
    properties.put(PROP_NAME, getPropName(requirement));
    properties.put(PROP_VALUE, getPropValue(requirement));
    return properties;
}
 
Example 10
Source File: ComputeNodeTemplate.java    From SeaCloudsPlatform with Apache License 2.0 5 votes vote down vote up
private Map<String, Object> createLocationConfigration() {
    Map<String, Object> locationProperties = MutableMap.of();
    Map<String, Object> properties = getProperties();
    String region = (String) properties.get(REGION);
    String hardwareId = (String) properties.get(HARDWARE_ID);

    locationProperties.put(REGION, region);
    locationProperties.put(HARDWARE_ID, hardwareId);
    locationProperties.put(ID_PROP_NAME, ID_PROP_DAFAULT_VALUE);
    locationProperties.put(CREDENTIAL_PROP_NAME, CREDENTIAL_PROP_DEFAULT_VALUE);
    return locationProperties;
}
 
Example 11
Source File: BasicLocationRegistry.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Override
public Map<String, LocationDefinition> getDefinedLocations(boolean includeThingsWeAreFacadeFor) {
    Map<String, LocationDefinition> result = MutableMap.of();
    synchronized (definedLocations) {
        result.putAll(definedLocations);
    }
    for (RegisteredType rt: mgmt.getTypeRegistry().getMatching(RegisteredTypePredicates.IS_LOCATION)) {
        result.put(rt.getId(), newDefinedLocation(rt));
    }
    return result;
}
 
Example 12
Source File: ApplicationResource.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
private EntitySummary addConfigByGlobs(EntitySummary result, Entity entity, List<String> extraConfigGlobs) {
    if (extraConfigGlobs!=null && !extraConfigGlobs.isEmpty()) {
        Object configO = result.getExtraFields().get("config");
        if (configO==null) {
            configO = MutableMap.of();
            result.setExtraField("config", configO);
        }
        if (!(configO instanceof Map)) {
            throw new IllegalStateException("config field in result for "+entity+" should be a Map; found: "+configO);
        }
        @SuppressWarnings("unchecked")
        Map<String,Object> configs = (Map<String, Object>) configO;
        
        List<Predicate<ConfigKey<?>>> extraConfigPreds = MutableList.of();
        extraConfigGlobs.stream().forEach(g -> { extraConfigPreds.add( ConfigPredicates.nameMatchesGlob(g) ); });
        entity.config().findKeysDeclared(Predicates.or(extraConfigPreds)).forEach(key -> {
            if (Entitlements.isEntitled(mgmt().getEntitlementManager(), Entitlements.SEE_CONFIG, new EntityAndItem<String>(entity, key.getName()))) {
                Maybe<Object> vRaw = ((EntityInternal)entity).config().getRaw(key);
                Object v = vRaw.isPresent() ? vRaw.get() : entity.config().get(key);
                if (v!=null) {
                    v = resolving(v, mgmt()).preferJson(true).asJerseyOutermostReturnValue(false).raw(true).context(entity).immediately(true).timeout(Duration.ZERO).resolve();
                    configs.put(key.getName(), v);
                }
            }
        });
    }
    return result;
}
 
Example 13
Source File: RebindIteration.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
/**
 * Constructs a new enricher, passing to its constructor the enricher id and all of memento.getConfig().
 */
protected Enricher newEnricher(EnricherMemento memento) {
    String id = memento.getId();
    LoadedClass<? extends Enricher> loaded = load(Enricher.class, memento);
    Class<? extends Enricher> enricherClazz = loaded.clazz;

    Enricher enricher;
    if (InternalFactory.isNewStyle(enricherClazz)) {
        InternalPolicyFactory policyFactory = managementContext.getPolicyFactory();
        enricher = policyFactory.constructEnricher(enricherClazz);
        FlagUtils.setFieldsFromFlags(ImmutableMap.of("id", id), enricher);
        ((AbstractEnricher)enricher).setManagementContext(managementContext);

    } else {
        LOG.warn("Deprecated rebind of enricher without no-arg constructor; " +
            "this may not be supported in future versions: id=" + id + "; type="+enricherClazz);

        // There are several possibilities for the constructor; find one that works.
        // Prefer passing in the flags because required for Application to set the management context
        // TODO Feels very hacky!
        Map<String, Object> flags = MutableMap.<String, Object>of(
            "id", id, 
            "deferConstructionChecks", true,
            "noConstructionInit", true);
        flags.putAll(memento.getConfig());

        enricher = invokeConstructor(reflections, enricherClazz, new Object[] {flags});
    }
    
    setCatalogItemIds(enricher, loaded.catalogItemId, loaded.searchPath);
    return enricher;
}
 
Example 14
Source File: OsgiManager.java    From brooklyn-server with Apache License 2.0 4 votes vote down vote up
public <T> Maybe<Class<T>> tryResolveClass(String type, Iterable<? extends OsgiBundleWithUrl> osgiBundles) {
    Map<OsgiBundleWithUrl,Throwable> bundleProblems = MutableMap.of();
    Set<String> extraMessages = MutableSet.of();
    for (OsgiBundleWithUrl osgiBundle: osgiBundles) {
        try {
            Maybe<Bundle> bundle = findBundle(osgiBundle);
            if (bundle.isPresent()) {
                Bundle b = bundle.get();
                Optional<String> strippedType = osgiClassPrefixer.stripMatchingPrefix(b, type);
                String typeToLoad = strippedType.isPresent() ? strippedType.get() : type;
                if (osgiClassPrefixer.hasPrefix(typeToLoad)) {
                    bundleProblems.put(osgiBundle, new UserFacingException("Bundle does not match prefix in type name '"+typeToLoad+"'"));
                    continue;
                }
                //Extension bundles don't support loadClass.
                //Instead load from the app classpath.
                Class<T> clazz = SystemFrameworkLoader.get().loadClassFromBundle(typeToLoad, b);
                return Maybe.of(clazz);
            } else {
                bundleProblems.put(osgiBundle, Maybe.getException(bundle));
            }
            
        } catch (Exception e) {
            // should come from classloading now; name formatting or missing bundle errors will be caught above 
            Exceptions.propagateIfFatal(e);
            bundleProblems.put(osgiBundle, e);

            Throwable cause = e.getCause();
            if (cause != null && cause.getMessage().contains("Unresolved constraint in bundle")) {
                if (BrooklynVersion.INSTANCE.getVersionFromOsgiManifest()==null) {
                    extraMessages.add("No brooklyn-core OSGi manifest available. OSGi will not work.");
                }
                if (BrooklynVersion.isDevelopmentEnvironment()) {
                    extraMessages.add("Your development environment may not have created necessary files. Doing a maven build then retrying may fix the issue.");
                }
                if (!extraMessages.isEmpty()) log.warn(Strings.join(extraMessages, " "));
                log.warn("Unresolved constraint resolving OSGi bundle "+osgiBundle+" to load "+type+": "+cause.getMessage());
                if (log.isDebugEnabled()) log.debug("Trace for OSGi resolution failure", e);
            }
        }
    }
    if (bundleProblems.size()==1) {
        Throwable error = Iterables.getOnlyElement(bundleProblems.values());
        if (error instanceof ClassNotFoundException && error.getCause()!=null && error.getCause().getMessage()!=null) {
            error = Exceptions.collapseIncludingAllCausalMessages(error);
        }
        return Maybe.absent("Unable to resolve class "+type+" in "+Iterables.getOnlyElement(bundleProblems.keySet())
            + (extraMessages.isEmpty() ? "" : " ("+Strings.join(extraMessages, " ")+")"), error);
    } else {
        return Maybe.absent(Exceptions.create("Unable to resolve class "+type+": "+bundleProblems
            + (extraMessages.isEmpty() ? "" : " ("+Strings.join(extraMessages, " ")+")"), bundleProblems.values()));
    }
}
 
Example 15
Source File: CloudFoundryServiceImpl.java    From SeaCloudsPlatform with Apache License 2.0 4 votes vote down vote up
public CloudFoundryServiceImpl(Entity parent) {
    this(MutableMap.of(), parent);
}
 
Example 16
Source File: SshMachineLocation.java    From brooklyn-server with Apache License 2.0 4 votes vote down vote up
public SshMachineLocation() {
    this(MutableMap.of());
}
 
Example 17
Source File: KafkaBrokerSshDriver.java    From brooklyn-library with Apache License 2.0 4 votes vote down vote up
@Override
protected Map<String, Integer> getPortMap() {
    return MutableMap.of("kafkaPort", getKafkaPort());
}
 
Example 18
Source File: OpenShiftWebAppImpl.java    From SeaCloudsPlatform with Apache License 2.0 4 votes vote down vote up
public OpenShiftWebAppImpl(Entity parent) {
    this(MutableMap.of(), parent);
}
 
Example 19
Source File: CloudFoundryEntityImpl.java    From SeaCloudsPlatform with Apache License 2.0 4 votes vote down vote up
public CloudFoundryEntityImpl() {
    super(MutableMap.of(), null);
}
 
Example 20
Source File: SizeHistory.java    From brooklyn-server with Apache License 2.0 4 votes vote down vote up
public SizeHistory(long windowSize) {
    recentDesiredResizes = new TimeWindowedList<Number>(MutableMap.of("timePeriod", windowSize, "minExpiredVals", 1));
}