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

The following examples show how to use org.apache.brooklyn.util.collections.MutableList#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: Strings.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
/** Returns canonicalized string from the given object, made "unique" by:
 * <li> putting sets into the toString order
 * <li> appending a hash code if it's longer than the max (and the max is bigger than 0) */
public static String toUniqueString(Object x, int optionalMax) {
    if (x instanceof Iterable && !(x instanceof List)) {
        // unsorted collections should have a canonical order imposed
        MutableList<String> result = MutableList.of();
        for (Object xi: (Iterable<?>)x) {
            result.add(toUniqueString(xi, optionalMax));
        }
        Collections.sort(result);
        x = result.toString();
    }
    if (x==null) return "{null}";
    String xs = x.toString();
    if (xs.length()<=optionalMax || optionalMax<=0) return xs;
    return maxlenWithEllipsis(xs, optionalMax-8)+"/"+Integer.toHexString(xs.hashCode());
}
 
Example 2
Source File: KafkaClusterImpl.java    From brooklyn-library with Apache License 2.0 6 votes vote down vote up
@Override
public void start(Collection<? extends Location> locations) {
    if (isLegacyConstruction()) {
        // TODO should no longer be needed?
        init();
    }

    locations = MutableList.copyOf(Locations.getLocationsCheckingAncestors(locations, this));

    Iterables.getOnlyElement(locations); // Assert just one
    // set it; here we don't allow changing locations
    addLocations(locations);

    List<Entity> childrenToStart = MutableList.<Entity>of(getCluster());
    // Set the KafkaZookeeper entity as child of cluster, if it does not already have a parent
    if (getZooKeeper().getParent() == null) {
        addChild(getZooKeeper());
    } // And only start zookeeper if we are parent
    if (Objects.equal(this, getZooKeeper().getParent())) childrenToStart.add(getZooKeeper());
    Entities.invokeEffector(this, childrenToStart, Startable.START, ImmutableMap.of("locations", locations)).getUnchecked();
}
 
Example 3
Source File: TestFrameworkSuiteBuilder.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
private Collection<URL> getLocationResources(Collection<String> locations) {
    if (testFrameworkSuiteBuilder.locationsFolder != null) {
        MutableList<URL> resources = MutableList.of();
        for (String location : locations) {
            File locationBom = new File(testFrameworkSuiteBuilder.locationsFolder, location + ".bom");
            if (locationBom.exists()) {
                try {
                    resources.add(locationBom.toURI().toURL());
                } catch (MalformedURLException e) {
                    throw new IllegalStateException("Could not conert the path " + locationBom.getAbsolutePath() + " to URL", e);
                }
            } else {
                log.info("Locationn file {} not found in {}. Assuming it's a location provided by the environment.",
                        location, testFrameworkSuiteBuilder.locationsFolder);
            }
        }
        return resources.asImmutableCopy();
    } else {
        return ImmutableList.of();
    }
}
 
Example 4
Source File: StringEscapes.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
/** as {@link #unwrapJsonishListIfPossible(String)} but throwing errors 
 * if something which looks like a string or set of brackets is not well-formed
 * (this does the work for that method) 
 * @throws IllegalArgumentException if looks to have quoted list or surrounding brackets but they are not syntactically valid */
public static List<String> unwrapOptionallyQuotedJavaStringList(String input) {
    if (input==null) return null;
    MutableList<String> result = MutableList.of();
    String i1 = input.trim();
    
    boolean inBrackets = (i1.startsWith("[") && i1.endsWith("]"));
    if (inBrackets) i1 = i1.substring(1, i1.length()-1).trim();
        
    QuotedStringTokenizer qst = new QuotedStringTokenizer(i1, "\"", true, ",", false);
    while (qst.hasMoreTokens()) {
        String t = qst.nextToken().trim();
        if (isWrappedInDoubleQuotes(t))
            result.add(unwrapJavaString(t));
        else {
            if (inBrackets && (t.indexOf('[')>=0 || t.indexOf(']')>=0))
                throw new IllegalArgumentException("Literal square brackets must be quoted, in element '"+t+"'");
            result.add(t.trim());
        }
    }
    
    return result;
}
 
Example 5
Source File: AbstractMemento.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("deprecation")
public B from(Memento other) {
    brooklynVersion = other.getBrooklynVersion();
    id = other.getId();
    type = other.getType();
    typeClass = other.getTypeClass();
    displayName = other.getDisplayName();
    catalogItemId = other.getCatalogItemId();
    searchPath = isEmpty(other.getCatalogItemIdSearchPath()) ?
        MutableList.<String>of() : MutableList.copyOf(other.getCatalogItemIdSearchPath());
    customFields.putAll(other.getCustomFields());
    tags.addAll(other.getTags());
    relations.putAll(other.getRelations());
    uniqueTag = other.getUniqueTag();
    return self();
}
 
Example 6
Source File: EntityManagementUtils.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
/** adds entities from the given yaml, under the given parent; but does not start them */
public static List<Entity> addChildrenUnstarted(final Entity parent, String yaml) {
    log.debug("Creating child of "+parent+" from yaml:\n{}", yaml);

    ManagementContext mgmt = parent.getApplication().getManagementContext();

    EntitySpec<? extends Application> specA = createEntitySpecForApplication(mgmt, yaml);

    // see whether we can promote children
    List<EntitySpec<?>> specs = MutableList.of();
    if (!canUnwrapEntity(specA)) {
        // if not promoting, set a nice name if needed
        if (Strings.isEmpty(specA.getDisplayName())) {
            int size = specA.getChildren().size();
            String childrenCountString = size+" "+(size!=1 ? "children" : "child");
            specA.displayName("Dynamically added "+childrenCountString);
        }
    }
    
    specs.add(unwrapEntity(specA));

    final List<Entity> children = MutableList.of();
    for (EntitySpec<?> spec: specs) {
        Entity child = parent.addChild(spec);
        children.add(child);
    }

    return children;
}
 
Example 7
Source File: Strings.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
/** converts a list of any objects to a list of strings, using {@link Object#toString()},
 * with the second argument used where an entry is null */
public static List<String> toStringList(List<?> list, String valueIfNull) {
    if (list==null) return null;
    List<String> result = MutableList.of();
    for (Object v: list) result.add(toStringWithValueForNull(v, valueIfNull));
    return result;
}
 
Example 8
Source File: TestWinrmCommandImpl.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
private List<Map<String, Object>> exitCodeAssertions() {

        List<Map<String, Object>> assertStatus = getAssertions(this, ASSERT_STATUS);
        List<Map<String, Object>> assertOut = getAssertions(this, ASSERT_OUT);
        List<Map<String, Object>> assertErr = getAssertions(this, ASSERT_ERR);

        List<Map<String, Object>> result;
        if (assertStatus.isEmpty() && assertOut.isEmpty() && assertErr.isEmpty()) {
            Map<String, Object> shouldSucceed = DEFAULT_ASSERTION;
            result = MutableList.of(shouldSucceed);
        } else {
            result = assertStatus;
        }
        return result;
    }
 
Example 9
Source File: ApplicationMetadataGenerator.java    From SeaCloudsPlatform with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
private void initImports() {
    this.imports = (template.get(IMPORTS) != null)
            ? (List<String>) template.get(IMPORTS)
            : MutableList.<String>of();

    fixNormativeTypesVersion();
    imports.add(SEACLOUDS_NODE_TYPES + ":" + SEACLOUDS_NODE_TYPES_VERSION);
}
 
Example 10
Source File: Propagator.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
private List<Sensor<?>> resolveSensorCollection(Iterable<?> sensors) {
    if (sensors == null) {
        return MutableList.of();
    }
    List<Sensor<?>> result = MutableList.of();
    for (Object sensorO : sensors) {
        Sensor<?> sensor = Tasks.resolving(sensorO).as(Sensor.class).immediately(true).context(producer).get();
        result.add(sensor);
    }
    return result;
}
 
Example 11
Source File: ServiceStateLogic.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
protected Object computeServiceProblems() {
    Map<Entity, Lifecycle> values = getValues(SERVICE_STATE_ACTUAL);
    int numRunning=0;
    List<Entity> onesNotHealthy=MutableList.of();
    Set<Lifecycle> ignoreStates = getConfig(IGNORE_ENTITIES_WITH_THESE_SERVICE_STATES);
    for (Map.Entry<Entity,Lifecycle> state: values.entrySet()) {
        if (state.getValue()==Lifecycle.RUNNING) numRunning++;
        else if (!ignoreStates.contains(state.getValue()))
            onesNotHealthy.add(state.getKey());
    }

    QuorumCheck qc = getConfig(RUNNING_QUORUM_CHECK);
    if (qc!=null) {
        if (qc.isQuorate(numRunning, onesNotHealthy.size()+numRunning))
            // quorate
            return null;

        if (onesNotHealthy.isEmpty())
            return "Not enough entities running to be quorate";
    } else {
        if (onesNotHealthy.isEmpty())
            return null;
    }

    return "Required entit"+Strings.ies(onesNotHealthy.size())+" not healthy: "+
        (onesNotHealthy.size()>3 ? nameOfEntity(onesNotHealthy.get(0))+" and "+(onesNotHealthy.size()-1)+" others"
            : Strings.join(nameOfEntity(onesNotHealthy), ", "));
}
 
Example 12
Source File: Asserts.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
public static void assertStringContainsAtLeastOne(String input, String possiblePhrase1ToContain, String ...optionalOtherPossiblePhrasesToContain) {
    if (input==null) fail("Input is null.");
    List<String> missing = MutableList.of();
    if (possiblePhrase1ToContain!=null) {
        if (input.contains(possiblePhrase1ToContain)) return;
        missing.add(possiblePhrase1ToContain);
    }
    for (String otherPhrase: optionalOtherPossiblePhrasesToContain) {
        if (otherPhrase!=null) {
            if (input.contains(otherPhrase)) return;
            missing.add(otherPhrase);
        }
    }
    fail("Input did not contain any of the expected phrases "+missing+": "+input);
}
 
Example 13
Source File: ResourcesInstalledEverywhereTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
private static void assertAllClassesListedAtUrl(ResourceUtils loader, String url, Iterable<?> resourceClasses) {
    String text = loader.getResourceAsString(url);
    List<String> missingClasses = MutableList.of();
    for (Object c: resourceClasses) {
        if (c instanceof Class) c = ((Class<?>)c).getName();
        else c = c.getClass().getName();
        
        if (text.indexOf(c.toString())==-1) missingClasses.add(c.toString());
    }
    
    if (!missingClasses.isEmpty())
        Assert.fail("Missing entries at "+url+": "+missingClasses);
}
 
Example 14
Source File: BrooklynEntityDecorationResolver.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
protected List<? extends DT> buildListOfTheseDecorationsFromEntityAttributes(ConfigBag attrs) {
    Object value = getDecorationAttributeJsonValue(attrs); 
    if (value==null) { return MutableList.of(); }
    if (value instanceof Iterable) {
        return buildListOfTheseDecorationsFromIterable((Iterable<?>)value);
    } else {
        // in future may support types other than iterables here, 
        // e.g. a map short form where the key is the type
        throw new IllegalArgumentException(getDecorationKind()+" body should be iterable, not " + value.getClass());
    }
}
 
Example 15
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 16
Source File: ConstraintSerializationTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Test
public void testAnd() {
    Predicate<String> p = Predicates.<String>and(
            StringPredicates.matchesRegex("my.*first"), 
            StringPredicates.matchesRegex("my.*second"));
    List<?> json = MutableList.of(
            MutableMap.of("regex", "my.*first"), 
            MutableMap.of("regex", "my.*second"));
    
    assertPredJsonBidi(p, json);
}
 
Example 17
Source File: AbstractBrooklynObjectSpec.java    From brooklyn-server with Apache License 2.0 4 votes vote down vote up
protected Object readResolve() {
    if (catalogItemIdSearchPath == null) {
        catalogItemIdSearchPath = MutableList.of();
    }
    return this;
}
 
Example 18
Source File: AsyncApplicationImpl.java    From brooklyn-server with Apache License 2.0 4 votes vote down vote up
protected ValueAndReason<Lifecycle> computeServiceState(Lifecycle expectedState) {
    if (expectedState != null && (expectedState != Lifecycle.STARTING && expectedState != Lifecycle.RUNNING)) {
        return new ValueAndReason<>(expectedState, "expected state "+expectedState);
    }
    
    Set<Lifecycle> ignoredStates;
    if (expectedState == Lifecycle.STARTING) {
        ignoredStates = getConfig(ENTITY_IGNORED_STATES_ON_STARTING);
    } else {
        ignoredStates = getConfig(ENTITY_IGNORED_STATES_ON_OTHERS);
    }
    Set<Lifecycle> transitionStates;
    if (expectedState == Lifecycle.STARTING) {
        transitionStates = getConfig(ENTITY_TRANSITION_STATES_ON_STARTING);
    } else {
        transitionStates = ImmutableSet.of();
    }

    Map<Entity, Lifecycle> values = getValues(SERVICE_STATE_ACTUAL);
    List<Entity> violators = MutableList.of();
    int entries = 0;
    int numRunning = 0;
    int numTransitioning = 0;
    
    for (Map.Entry<Entity,Lifecycle> entry : values.entrySet()) {
        if (ignoredStates.contains(entry.getValue())) {
            continue;
        }
        entries++;
        
        if (entry.getValue() == Lifecycle.RUNNING) {
            numRunning++;
        } else if (transitionStates.contains(entry.getValue())) {
            numTransitioning++;
        } else {
            violators.add(entry.getKey());
        }
    }

    QuorumCheck qc = getConfig(RUNNING_QUORUM_CHECK);
    if (qc.isQuorate(numRunning, violators.size()+numRunning+numTransitioning)) {
        // quorate
        return new ValueAndReason<Lifecycle>(Lifecycle.RUNNING, "quorate");
    }
    boolean canEverBeQuorate = qc.isQuorate(numRunning+numTransitioning, violators.size()+numRunning+numTransitioning);
    if (expectedState == Lifecycle.STARTING && canEverBeQuorate) {
        // quorate
        return new ValueAndReason<Lifecycle>(Lifecycle.STARTING, "not yet quorate");
    }
    
    String reason;
    if (values.isEmpty()) {
        reason = "No entities present";
    } else if (entries == 0) {
        reason = "No entities in interesting states";
    } else if (violators.isEmpty()) {
        reason = "Not enough entities";
    } else if (violators.size() == 1) {
        reason = violators.get(0)+" is not healthy";
    } else if (violators.size() == entries) {
        reason = "None of the entities are healthy";
    } else {
        reason = violators.size()+" entities are not healthy, including "+violators.get(0);
    }            
    return new ValueAndReason<>(Lifecycle.ON_FIRE, reason);

}
 
Example 19
Source File: HighAvailabilityManagerInMemoryTest.java    From brooklyn-server with Apache License 2.0 4 votes vote down vote up
private List<String> identities(Collection<?> objs) {
    List<String> result = MutableList.of();
    for (Object obj: objs)
        result.add(Integer.toHexString(System.identityHashCode(obj)));
    return result;
}
 
Example 20
Source File: CatalogUtils.java    From brooklyn-server with Apache License 2.0 4 votes vote down vote up
/** As {@link #installLibraries(ManagementContext, Collection)} but letting caller suppress the deferred start/install
 * (for use in tests where bundles' BOMs aren't resolvable). */
public static void installLibraries(ManagementContext managementContext, @Nullable Collection<CatalogBundle> libraries, boolean startBundlesAndInstallToBrooklyn) {
    if (libraries == null) return;

    ManagementContextInternal mgmt = (ManagementContextInternal) managementContext;
    if (!libraries.isEmpty()) {
        Maybe<OsgiManager> osgi = mgmt.getOsgiManager();
        if (osgi.isAbsent()) {
            throw new IllegalStateException("Unable to load bundles "+libraries+" because OSGi is not running.");
        }
        if (log.isDebugEnabled()) 
            logDebugOrTraceIfRebinding(log, 
                "Loading bundles in {}: {}", 
                new Object[] {managementContext, Joiner.on(", ").join(libraries)});
        Stopwatch timer = Stopwatch.createStarted();
        List<OsgiBundleInstallationResult> results = MutableList.of();
        for (CatalogBundle bundle : libraries) {
            OsgiBundleInstallationResult result = osgi.get().installDeferredStart(BasicManagedBundle.of(bundle), null, true).get();
            if (log.isDebugEnabled()) {
                logDebugOrTraceIfRebinding(log, "Installation of library "+bundle+": "+result);
            }
            results.add(result);
        }
        Map<String, Throwable> errors = MutableMap.of();
        if (startBundlesAndInstallToBrooklyn) {
            for (OsgiBundleInstallationResult r: results) {
                if (r.getDeferredStart()!=null) {
                    try {
                        r.getDeferredStart().run();
                    } catch (Throwable t) {
                        Exceptions.propagateIfFatal(t);
                        // above will done rollback for the failed item, but we need consistent behaviour for all libraries;
                        // for simplicity we simply have each bundle either fully installed or fully rolled back
                        // (alternative would be to roll back everything)
                        errors.put(r.getVersionedName().toString(), t);
                    }
                }
            }
        }
        if (!errors.isEmpty()) {
            logDebugOrTraceIfRebinding(log, "Tried registering {} libraries, {} succeeded, but failed {} (throwing)", 
                new Object[] { libraries.size(), libraries.size() - errors.size(), errors.keySet() });
            if (errors.size()==1) {
                throw Exceptions.propagateAnnotated("Error starting referenced library in Brooklyn bundle "+Iterables.getOnlyElement(errors.keySet()), 
                    Iterables.getOnlyElement(errors.values()));
            } else {
                throw Exceptions.create("Error starting referenced libraries in Brooklyn bundles "+errors.keySet(), errors.values());                    
            }
        }
        if (log.isDebugEnabled()) { 
            logDebugOrTraceIfRebinding(log, 
                "Registered {} bundle{} in {}",
                new Object[]{libraries.size(), Strings.s(libraries.size()), Time.makeTimeStringRounded(timer)});
        }
    }
}