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

The following examples show how to use org.apache.brooklyn.util.collections.MutableList#copyOf() . 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: BasicLocationRegistry.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
protected void findServices() {
    Iterable<LocationResolver> loader = FrameworkLookup.lookupAll(LocationResolver.class, mgmt.getCatalogClassLoader());
    MutableList<LocationResolver> loadedResolvers;
    try {
        loadedResolvers = MutableList.copyOf(loader);
    } catch (Throwable e) {
        log.warn("Error loading resolvers (rethrowing): "+e);
        throw Exceptions.propagate(e);
    }
    
    for (LocationResolver r: loadedResolvers) {
        registerResolver(r);
    }
    if (log.isDebugEnabled()) log.debug("Location resolvers are: "+resolvers);
    if (resolvers.isEmpty()) log.warn("No location resolvers detected: is src/main/resources correctly included?");
}
 
Example 2
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 3
Source File: MultiLocation.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@Override
public void init() {
    super.init();
    
    List<MachineProvisioningLocation<?>> subLocs = MutableList.copyOf(getConfig(SUB_LOCATIONS));
    
    List<LocationSpec<?>> subLocSpecs = getConfig(SUB_LOCATION_SPECS);
    if (subLocSpecs != null) {
        for (LocationSpec<?> spec : subLocSpecs) {
            if (spec.getParent() == null) {
                // use a copy with us set as parent
                spec = LocationSpec.create(spec).parent(this);
            }
            MachineProvisioningLocation<?> subLoc = (MachineProvisioningLocation<?>) getManagementContext().getLocationManager().createLocation(spec);
            subLocs.add(subLoc);
        }
    }
    checkState(subLocs.size() >= 1, "sub-locations must not be empty");
    config().set(SUB_LOCATIONS, subLocs);
    config().set(SUB_LOCATION_SPECS, (List<LocationSpec<?>>) null);

    AvailabilityZoneExtension azExtension = new AvailabilityZoneExtensionImpl(getManagementContext(), subLocs);
    addExtension(AvailabilityZoneExtension.class, azExtension);
}
 
Example 4
Source File: PlanInterpretationNode.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
protected void applyToIterable() {
    MutableList<Object> input = MutableList.copyOf((Iterable<?>)originalValue);
    MutableList<Object> result = new MutableList<Object>();
    newValue = result;

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

        for (Object entry: input) {
            // then recurse in to this node and do various in-the-node applications
            PlanInterpretationNode value = newPlanInterpretation(this, Role.LIST_ENTRY, entry);
            value.apply();

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

            if (getContext().getAllInterpreter().applyListEntry(this, input, result, value))
                result.add(value.getNewValue());
        }

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

    if (changed==null) changed = false;
}
 
Example 5
Source File: Histogram.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@Override
public String toString() {
    if (counts.isEmpty()) return "<empty>";
    
    StringBuilder result = new StringBuilder("{");
    List<Integer> sortedPows = MutableList.copyOf(counts.keySet());
    Collections.sort(sortedPows);
    int minPow = sortedPows.get(0);
    int maxPow = sortedPows.get(sortedPows.size()-1);
    for (int i = minPow; i <= maxPow; i++) {
        if (i != minPow) result.append(", ");
        long lower = i == 0 ? 0 : (long) Math.pow(2, i-1);
        long upper = (long) Math.pow(2, i);
        Integer count = counts.get(i);
        result.append(Time.makeTimeStringRounded(lower, TimeUnit.NANOSECONDS) 
                + "-" + Time.makeTimeStringRounded(upper, TimeUnit.NANOSECONDS) 
                + ": " + (count == null ? 0 : count));
    }
    result.append("}");
    return result.toString();
}
 
Example 6
Source File: BasicBrooklynCatalog.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
public PlanInterpreterGuessingType reconstruct() {
    if (catalogItemType==CatalogItemType.TEMPLATE) {
        // template *must* be explicitly defined, and if so, none of the other calls apply
        attemptType(null, CatalogItemType.TEMPLATE);
        
    } else {
        attemptType(null, CatalogItemType.ENTITY);
        
        List<Exception> oldEntityErrors = MutableList.copyOf(entityErrors);
        // try with services key
        attemptType("services", CatalogItemType.ENTITY);
        entityErrors.removeAll(oldEntityErrors);
        entityErrors.addAll(oldEntityErrors);
        // errors when wrapped in services block are better currently
        // as we parse using CAMP and need that
        // so prefer those for now (may change with YOML)
        
        attemptType(POLICIES_KEY, CatalogItemType.POLICY);
        attemptType(ENRICHERS_KEY, CatalogItemType.ENRICHER);
        attemptType(LOCATIONS_KEY, CatalogItemType.LOCATION);
    }
    
    if (!resolved && catalogItemType==CatalogItemType.TEMPLATE) {
        // anything goes, for an explicit template, because we can't easily recurse into the types
        planYaml = itemYaml;
        resolved = true;
    }
    
    return this;
}
 
Example 7
Source File: KubernetesLocation.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
protected Iterable<Integer> findInboundPorts(Entity entity, ConfigBag setup) {
    Iterable<String> inboundTcpPorts = entity.config().get(DockerContainer.INBOUND_TCP_PORTS);
    if(inboundTcpPorts == null)
        return setup.containsKey(INBOUND_PORTS) ? toIntPortList(setup.get(INBOUND_PORTS)) : ImmutableList.of(22);

    List<Integer> inboundPorts = Lists.newArrayList();
    List<String> portRanges = MutableList.copyOf(entity.config().get(DockerContainer.INBOUND_TCP_PORTS));
    for (String portRange : portRanges) {
        for (Integer port : PortRanges.fromString(portRange)) {
            inboundPorts.add(port);
        }
    }
    return inboundPorts;
}
 
Example 8
Source File: TestSshCommandImpl.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
private static String getLastPartOfPath(Iterable<String> path, String defaultName) {
    MutableList<String> parts = MutableList.copyOf(path);
    Collections.reverse(parts);
    Iterator<String> it = parts.iterator();
    String scriptName = null;

    // strip any trailing "/" parts of URL
    while (isBlank(scriptName) && it.hasNext()) {
        scriptName = it.next();
    }
    if (isBlank(scriptName)) {
        scriptName = defaultName;
    }
    return scriptName;
}
 
Example 9
Source File: DynamicFabricImpl.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
/**
 * If including initial children, first look at existing Startable children - start them with 
 * the locations passed in here (if they have no locations yet). This "consumes" a location
 * so we won't create an additional member in that location.
 * 
 * If not {@code includeInitialChildren}, then start those children in the first location but
 * don't "consume" a location - so we'll create additional members.
 * 
 * @param includeInitialChildren
 * @param allLocations
 * @param tasks side-effects this map, to add the tasks created for starting the child entities
 * 
 * @return unused locations
 */
protected List<Location> startChildren(boolean includeInitialChildren, Collection<? extends Location> allLocations, Map<Entity, Task<?>> tasks) {
    List<Location> locations = MutableList.copyOf(allLocations);
    int locIndex = 0;
    
    for (Entity child: getChildren()) {
        if (child instanceof Startable) {
            if (includeInitialChildren) {
                addMember(child);
            }
            
            Location it = null;
            if (child.getLocations().isEmpty()) {
                // give him any of these locations if he has none, allowing round robin here
                if (!locations.isEmpty()) {
                    if (includeInitialChildren) {
                        it = locations.get(locIndex++ % locations.size());
                    } else {
                        it = locations.get(0);
                    }
                    ((EntityInternal)child).addLocations(Arrays.asList(it));
                }
            }
            
            tasks.put(child, Entities.submit(this,
                Effectors.invocation(child, START, ImmutableMap.of("locations", 
                    it==null ? ImmutableList.of() : ImmutableList.of(it))).asTask()));
        }
    }
        
    // remove all the locations we applied to existing nodes
    while (locIndex-->0 && !locations.isEmpty()) {
        locations.remove(0);
    }
    
    return locations;
}
 
Example 10
Source File: BasicExecutionManager.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
/** not on interface because potentially expensive */
public List<Task<?>> getAllTasks() {
    // not sure if synching makes any difference; have not observed CME's yet
    // (and so far this is only called when a CME was caught on a previous operation)
    synchronized (tasksById) {
        return MutableList.copyOf(tasksById.values());
    }
}
 
Example 11
Source File: ApplicationResource.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Override
public List<EntitySummary> details(String entityIds, boolean includeAllApps, String extraSensorsGlobsS, String extraConfigGlobsS, int depth) {
    List<String> extraSensorGlobs = JavaStringEscapes.unwrapOptionallyQuotedJavaStringList(extraSensorsGlobsS);
    List<String> extraConfigGlobs = JavaStringEscapes.unwrapOptionallyQuotedJavaStringList(extraConfigGlobsS);

    Map<String, EntitySummary> entitySummaries = MutableMap.of();

    if (includeAllApps) {
        for (Entity application : mgmt().getApplications()) {
            if (Entitlements.isEntitled(mgmt().getEntitlementManager(), Entitlements.SEE_ENTITY, application)) {
                entitySummaries.put(application.getId(), fromEntity(application, true, depth, extraSensorGlobs, extraConfigGlobs));
            }
        }
    }

    if (Strings.isNonBlank(entityIds)) {
        List<String> extraEntities = JavaStringEscapes.unwrapOptionallyQuotedJavaStringList(entityIds);
        for (String entityId: extraEntities) {
            Entity entity = mgmt().getEntityManager().getEntity(entityId.trim());
            while (entity != null && !entitySummaries.containsKey(entity.getId())) {
                if (Entitlements.isEntitled(mgmt().getEntitlementManager(), Entitlements.SEE_ENTITY, entity)) {
                    entitySummaries.put(entity.getId(), fromEntity(entity, true, depth, extraSensorGlobs, extraConfigGlobs));
                }
                entity = entity.getParent();
            }
        }
    }
    return MutableList.copyOf(entitySummaries.values());
}
 
Example 12
Source File: AbstractScheduledEffectorPolicy.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
protected void schedule(Duration wait) {
    List<Long> scheduled = MutableList.copyOf(config().get(SCHEDULED));
    scheduled.add(System.currentTimeMillis() + wait.toMilliseconds());
    config().set(SCHEDULED, scheduled);

    scheduleInExecutor(wait);
}
 
Example 13
Source File: DescendantsTest.java    From brooklyn-server with Apache License 2.0 4 votes vote down vote up
@Test
public void testDescendantsInSimpleDeployedApplication() throws InterruptedException, TimeoutException, IOException {
    Response response = clientDeploy(simpleSpec);
    assertTrue(response.getStatus()/100 == 2, "response is "+response);
    Application application = Iterables.getOnlyElement( getManagementContext().getApplications() );
    List<Entity> entities = MutableList.copyOf( application.getChildren() );
    log.debug("Created app "+application+" with children entities "+entities);
    assertEquals(entities.size(), 2);
    
    Set<EntitySummary> descs;
    descs = client().path("/applications/"+application.getApplicationId()+"/descendants")
        .get(new GenericType<Set<EntitySummary>>() {});
    // includes itself
    assertEquals(descs.size(), 3);
    
    descs = client().path("/applications/"+application.getApplicationId()+"/descendants")
        .query("typeRegex", ".*\\.RestMockSimpleEntity")
        .get(new GenericType<Set<EntitySummary>>() {});
    assertEquals(descs.size(), 2);
    
    descs = client().path("/applications/"+application.getApplicationId()+"/descendants")
        .query("typeRegex", ".*\\.BestBockSimpleEntity")
        .get(new GenericType<Set<EntitySummary>>() {});
    assertEquals(descs.size(), 0);

    descs = client().path("/applications/"+application.getApplicationId()
            + "/entities/"+entities.get(1).getId() + "/descendants")
        .query("typeRegex", ".*\\.RestMockSimpleEntity")
        .get(new GenericType<Set<EntitySummary>>() {});
    assertEquals(descs.size(), 1);
    
    Map<String,Object> sensors = client().path("/applications/"+application.getApplicationId()+"/descendants/sensor/foo")
        .query("typeRegex", ".*\\.RestMockSimpleEntity")
        .get(new GenericType<Map<String,Object>>() {});
    assertEquals(sensors.size(), 0);

    long v = 0;
    application.sensors().set(Sensors.newLongSensor("foo"), v);
    for (Entity e: entities)
        e.sensors().set(Sensors.newLongSensor("foo"), v+=123);
    
    sensors = client().path("/applications/"+application.getApplicationId()+"/descendants/sensor/foo")
        .get(new GenericType<Map<String,Object>>() {});
    assertEquals(sensors.size(), 3);
    assertEquals(sensors.get(entities.get(1).getId()), 246);
    
    sensors = client().path("/applications/"+application.getApplicationId()+"/descendants/sensor/foo")
        .query("typeRegex", ".*\\.RestMockSimpleEntity")
        .get(new GenericType<Map<String,Object>>() {});
    assertEquals(sensors.size(), 2);
    
    sensors = client().path("/applications/"+application.getApplicationId()+"/"
        + "entities/"+entities.get(1).getId()+"/"
        + "descendants/sensor/foo")
        .query("typeRegex", ".*\\.RestMockSimpleEntity")
        .get(new GenericType<Map<String,Object>>() {});
    assertEquals(sensors.size(), 1);

    sensors = client().path("/applications/"+application.getApplicationId()+"/"
        + "entities/"+entities.get(1).getId()+"/"
        + "descendants/sensor/foo")
        .query("typeRegex", ".*\\.FestPockSimpleEntity")
        .get(new GenericType<Map<String,Object>>() {});
    assertEquals(sensors.size(), 0);
}
 
Example 14
Source File: BasicExecutionManager.java    From brooklyn-server with Apache License 2.0 4 votes vote down vote up
@Override
public boolean cancel(TaskCancellationMode mode) {
    boolean result = false;
    if (log.isTraceEnabled()) {
        log.trace("CLFFT cancelling "+task+" mode "+mode);
    }
    if (!task.isCancelled()) result |= ((TaskInternal<T>)task).cancel(mode);
    result |= delegate().cancel(mode.isAllowedToInterruptTask());
    
    if (mode.isAllowedToInterruptDependentSubmittedTasks()) {
        int subtasksFound=0;
        int subtasksReallyCancelled=0;
        
        if (task instanceof HasTaskChildren) {
            // cancel tasks in reverse order --
            // it should be the case that if child1 is cancelled,
            // a parentTask should NOT call a subsequent child2,
            // but just in case, we cancel child2 first
            // NB: DST and others may apply their own recursive cancel behaviour
            MutableList<Task<?>> childrenReversed = MutableList.copyOf( ((HasTaskChildren)task).getChildren() );
            Collections.reverse(childrenReversed);
            
            for (Task<?> child: childrenReversed) {
                if (log.isTraceEnabled()) {
                    log.trace("Cancelling "+child+" on recursive cancellation of "+task);
                }
                subtasksFound++;
                if (((TaskInternal<?>)child).cancel(mode)) {
                    result = true;
                    subtasksReallyCancelled++;
                }
            }
        }
        for (Task<?> t: execMgmt.getAllTasks()) {
            if (task.equals(t.getSubmittedByTask())) {
                if (mode.isAllowedToInterruptAllSubmittedTasks() || BrooklynTaskTags.isTransient(t)) {
                    if (log.isTraceEnabled()) {
                        log.trace("Cancelling "+t+" on recursive cancellation of "+task);
                    }
                    subtasksFound++;
                    if (((TaskInternal<?>)t).cancel(mode)) {
                        result = true;
                        subtasksReallyCancelled++;
                    }
                }
            }
        }
        if (log.isTraceEnabled()) {
            log.trace("On cancel of "+task+", applicable subtask count "+subtasksFound+", of which "+subtasksReallyCancelled+" were actively cancelled");
        }
    }
  
    execMgmt.afterEndForCancelBeforeStart(null, task, true);
    return result;
}
 
Example 15
Source File: BundleUpgradeParser.java    From brooklyn-server with Apache License 2.0 4 votes vote down vote up
@VisibleForTesting
static Multimap<VersionedName,VersionRangedName> parseVersionRangedNameEqualsVersionedNameList(String input, boolean singleVersionIsOsgiRange,
        List<String> wildcardNames, List<String> wildcardVersions,
        Function<VersionRangedName,VersionedName> defaultTargetFunction) {
    LinkedHashMultimap<VersionedName,VersionRangedName> result = LinkedHashMultimap.create();
    if (input == null) return result;
    
    List<String> vals = QuotedStringTokenizer.builder()
            .delimiterChars(",")
            .includeQuotes(false)
            .includeDelimiters(false)
            .buildList(input);
    
    for (String entry : vals) {
        entry = entry.trim();
        String key, val;
        String[] keVals = entry.split("=");
        if (keVals.length>2) {
            throw new IllegalArgumentException("Max one = permitted in entry (\""+entry+"\"). If defining a range on an entry you must quote the entry.");
        } else if (keVals.length==2) {
            key = keVals[0];
            val = keVals[1];
        } else {
            key = keVals[0];
            val = null;
        }
        
        List<String> sourceNames, sourceVersions;
        if (key.startsWith("*")) {
            if (wildcardNames==null) {
                throw new IllegalArgumentException("Wildcard cannot be inferred");
            }
            if  ("*".equals(key)) {
                if (wildcardVersions==null) {
                    throw new IllegalArgumentException("Version for wildcard cannot be inferred");
                }
                sourceVersions = wildcardVersions;
            } else if (key.startsWith("*:")) {
                sourceVersions = MutableList.of(key.substring(2));
            } else {
                throw new IllegalArgumentException("Wildcard entry key must be of the form \"*\" or \"*:range\"");
            }
            sourceNames = MutableList.copyOf(wildcardNames);
        } else {
            String[] parts = key.split(":");
            if (parts.length==1) {
                if (wildcardVersions==null) {
                    throw new IllegalArgumentException("Version for "+key+" cannot be inferred");
                }
                sourceNames = MutableList.of(key);
                sourceVersions = wildcardVersions;
            } else if (parts.length==2) {
                sourceNames = MutableList.of(parts[0]);
                sourceVersions = MutableList.of(parts[1]);
            } else {
                throw new IllegalArgumentException("Entry '"+entry+"' should be of form 'name[:versionRange][=name[:version]]'");
            }
        }
        for (String item: sourceNames) {
            for (String v: sourceVersions) {
                VersionRangedName source = parseVersionRangedName(item, v, false);
                VersionedName target;
                if (val!=null) {
                    target = VersionedName.fromString(val);
                } else if (defaultTargetFunction!=null) {
                    target = defaultTargetFunction.apply(source);
                } else {
                    throw new IllegalArgumentException("Wildcard entry key must be of the form \"*\" or \"*:range\"");
                }
                result.put(target, source);
            }
        }
    }
    return result;
}
 
Example 16
Source File: SelectMasterEffectorTest.java    From brooklyn-server with Apache License 2.0 4 votes vote down vote up
private List<Entity> makeTwoNodes() {
    List<Entity> nodes = MutableList.copyOf(cluster.resizeByDelta(2));
    setManagementState(nodes.get(0), ManagementNodeState.MASTER);
    setManagementState(nodes.get(1), ManagementNodeState.HOT_STANDBY);
    return nodes;
}
 
Example 17
Source File: VanillaSoftwareProcessYamlTest.java    From brooklyn-server with Apache License 2.0 4 votes vote down vote up
private void assertIterablesEqual(Iterable<?> actual, Function<? super List<?>, List<?>> transformer, Iterable<?> expected) {
    List<?> actualList = (actual instanceof List) ? (List<?>) actual : MutableList.copyOf(actual);
    List<?> expectedList = (expected instanceof List) ? (List<?>) expected : MutableList.copyOf(expected);
    String errMsg = "actual="+actualList+"; expected="+expectedList;
    assertEquals(transformer.apply(actualList), expectedList, errMsg);
}
 
Example 18
Source File: ConstraintSerialization.java    From brooklyn-server with Apache License 2.0 4 votes vote down vote up
public List<Predicate<?>> toPredicateListFromJsonList(Collection<?> o) {
    Set<Predicate<?>> result = MutableSet.of();
    collectPredicateListFromJson(o, result);
    return MutableList.copyOf(result);
}
 
Example 19
Source File: ObjectsYamlTest.java    From brooklyn-server with Apache License 2.0 4 votes vote down vote up
public static List<String> getCalls() {
    synchronized (calls) {
        return MutableList.copyOf(calls);
    }
}
 
Example 20
Source File: DockerJcloudsLocation.java    From brooklyn-server with Apache License 2.0 4 votes vote down vote up
@Override
public Template buildTemplate(ComputeService computeService, ConfigBag config, Collection<JcloudsLocationCustomizer> customizers) {
    String loginUser = config.get(JcloudsLocation.LOGIN_USER);
    String loginPassword = config.get(JcloudsLocation.LOGIN_USER_PASSWORD);
    String loginKeyFile = config.get(JcloudsLocation.LOGIN_USER_PRIVATE_KEY_FILE);
    String loginKeyData = config.get(JcloudsLocation.LOGIN_USER_PRIVATE_KEY_DATA);

    Template template = super.buildTemplate(computeService, config, customizers);
    DockerTemplateOptions templateOptions = (DockerTemplateOptions) template.getOptions();
    Image image = template.getImage();
    List<String> env = MutableList.copyOf(templateOptions.getEnv());

    // Inject login credentials, if required
    Boolean injectLoginCredentials = config.get(INJECT_LOGIN_CREDENTIAL);
    if (injectLoginCredentials == null) {
        String imageDescription = image.getDescription();
        for (String regex : IMAGE_DESCRIPTION_REGEXES_REQUIRING_INJECTED_LOGIN_CREDS) {
            if (imageDescription != null && imageDescription.matches(regex)) {
                injectLoginCredentials = true;
                break;
            }
        }
    }
    if (Strings.isBlank(loginUser) && Strings.isBlank(loginPassword) && Strings.isBlank(loginKeyFile) && Strings.isBlank(loginKeyData)) {
        if (Boolean.TRUE.equals(injectLoginCredentials)) {
            loginUser = "root";
            loginPassword = Identifiers.makeRandomPassword(12);
            templateOptions.overrideLoginUser(loginUser);
            templateOptions.overrideLoginPassword(loginPassword);

            env.add("BROOKLYN_ROOT_PASSWORD=" + loginPassword);
        }
    }

    Entity context = validateCallerContext(config);
    Map<String, Object> containerEnv = MutableMap.copyOf(context.config().get(DockerContainer.CONTAINER_ENVIRONMENT));
    for (Map.Entry<String, String> entry : Maps.transformValues(containerEnv, Functions.toStringFunction()).entrySet()) {
        env.add(String.format("%s=%s", entry.getKey(), entry.getValue()));
    }
    templateOptions.env(env);

    return template;
}