Example usage for com.google.common.collect Iterables all

List of usage examples for com.google.common.collect Iterables all

Introduction

In this page you can find the example usage for com.google.common.collect Iterables all.

Prototype

public static <T> boolean all(Iterable<T> iterable, Predicate<? super T> predicate) 

Source Link

Document

Returns true if every element in iterable satisfies the predicate.

Usage

From source file:com.eucalyptus.stats.sensors.ComponentsSensor.java

/**
 * Returns metrics with names 'euca.components.<compname>.state
 *
 * @return//from   w ww  . j a va 2  s.c om
 * @throws Exception
 */
@Override
public List<SystemMetric> poll() throws Exception {
    List<SystemMetric> results = Lists.newArrayList();
    SystemMetric stateOutput;
    boolean result;
    String componentName;
    List<String> componentTags;
    for (Component comp : Components.listLocal()) {
        componentName = comp.getComponentId().getName();
        componentTags = new ArrayList<String>(tags.size() + 1);
        componentTags.addAll(tags);
        componentTags.add(comp.getLocalServiceConfiguration().getFullName().toString()); //Add the arn to the tags
        stateOutput = new SystemMetric(this.sensorName + "." + componentName + "." + STATE_NAME, componentTags,
                "Component " + componentName + " state and health checks", new HashMap<String, Object>(), ttl);

        //Check()
        try {
            LOG.trace("Running check() on component: " + componentName + " for monitoring results");
            result = Iterables.all(comp.getBootstrappers(), RUN_CHECK);
        } catch (Throwable e) {
            LOG.fatal("Component " + componentName
                    + " Check() call threw exception. Component may not be available for use", e);
            result = false;
        }
        stateOutput.getValues().put("Check",
                result ? StatsOutputValues.CHECK_OK : StatsOutputValues.CHECK_FAILED);

        //Internal state
        try {
            LOG.trace("Getting state for component: " + componentName + " for monitoring results");
            stateOutput.getValues().put("State", comp.getState().toString());
        } catch (Throwable e) {
            LOG.fatal("Component " + componentName
                    + " getState() call threw exception. Component may not be available for use", e);
        }
        results.add(stateOutput);
    }
    return results;
}

From source file:com.eviware.loadui.impl.addon.AddonRegistryImpl.java

/**
 * Called by Spring whenever a new Factory is registered as an OSGi service.
 * /*w w  w  .  ja  v  a 2  s.c  o m*/
 * @param factory
 * @param properties
 */
public synchronized void factoryAdded(final Addon.Factory<?> factory, Map<String, String> properties) {
    final String typeStr = factory.getType().getName();

    factories.put(typeStr, factory);
    for (Class<?> type : factory.getEagerTypes()) {
        eagerAddons.put(type, factory);
    }
    log.debug("Registered Addon.Factory for type: {}", typeStr);

    Iterable<AddonHolder> matchingHolders = Iterables.filter(registeredHolders, new Predicate<AddonHolder>() {
        @Override
        public boolean apply(final AddonHolder addonHolder) {
            return Iterables.all(factory.getEagerTypes(), new Predicate<Class<?>>() {
                @Override
                public boolean apply(Class<?> cls) {
                    return cls.isInstance(addonHolder);
                }
            });
        }
    });

    for (AddonHolder holder : matchingHolders) {
        loadAddon(holder, factory);
    }
}

From source file:com.google.devtools.build.lib.skyframe.ActionArtifactCycleReporter.java

@Override
protected boolean canReportCycle(SkyKey topLevelKey, CycleInfo cycleInfo) {
    return IS_ARTIFACT_OR_ACTION_SKY_KEY.apply(topLevelKey)
            && Iterables.all(cycleInfo.getCycle(), IS_ARTIFACT_OR_ACTION_SKY_KEY);
}

From source file:com.googlecode.blaisemath.app.MenuConfig.java

/**
 * Gets the menubar configuration from file.
 * @param cls class with associated resource
 * @param key key for menubar component in config file
 * @return menus to comprise menubar, where values are lists with either strings or nested menus
 * @throws IOException if there's an error reading from the config file
 *//*from   w  w  w.  j  av  a2  s. c  o  m*/
public static List<Map> readMenuBarConfig(Class cls, String key) throws IOException {
    Object res = readConfig(cls).get(key);
    checkState(res instanceof List, "Expected menubar to be a list of maps but was " + res);
    checkState(Iterables.all((List) res, Predicates.instanceOf(Map.class)),
            "Expected list elements of menubar to be maps");
    return (List<Map>) res;
}

From source file:com.salesforce.ide.core.services.ToolingDeployService.java

/**
 * <p>/*from w w  w .ja  va 2s  .c  om*/
 * Deploys the list of components through the Tooling API. It will attempt to compile and save. If there are
 * compilation errors, it will notify the user.
 * </p>
 * <p>
 * We create a fresh MetadataContainer each time (but with the same name). This is cleaner in case we wind up in
 * some weird state with partially created ContainerMember. This is different from the Dev Console, because we have
 * a local file system when we can store intermediate state. We don't need to exploit ContainerMembers to store
 * intermediate state.
 * </p>
 * 
 * @param list
 *            List of components that CAN be deployed using Tooling API.
 * @param monitor
 *            Monitor to provide feedback to the user.
 */
public void deploy(ForceProject project, ComponentList list, IProgressMonitor monitor) {
    //TODO: Optimize for the case of a single save, where we can just use the ContainerAsyncRequest without MetadataContainer
    try {
        clearSaveLocallyOnlyMarkers(list);

        ToolingStubExt stub = factoryLocator.getToolingFactory().getToolingStubExt(project);

        MetadataContainer container = new MetadataContainer();
        container.setName(constructProjectIdentifier(project));
        SaveResult[] containerResults = stub.create(new SObject[] { container });

        if (containerResults[0].isSuccess()) {
            String containerId = containerResults[0].getId();
            SObject[] classMembers = createContainerMembers(containerId, list);

            SaveResult[] classMemberResults = stub.create(classMembers);
            boolean allClassMembersCreatedSuccessfully = Iterables.all(Lists.newArrayList(classMemberResults),
                    new Predicate<SaveResult>() {

                        @Override
                        public boolean apply(SaveResult result) {
                            return result.isSuccess();
                        }
                    });

            if (allClassMembersCreatedSuccessfully) {
                ContainerAsyncRequest request = new ContainerAsyncRequest();
                request.setIsCheckOnly(false);
                request.setMetadataContainerId(containerId);
                SaveResult[] requestResults = stub.create(new SObject[] { request });

                if (requestResults[0].isSuccess()) {
                    ContainerAsyncRequest onGoingRequest = pollForStatus(stub, requestResults, monitor);
                    handleContainerAsyncMessages(list, onGoingRequest);
                } else {
                    handleContainerAsyncRequestCreationFailure(list, requestResults);
                }
            } else {
                handleClassMembersCreationFailure(list, classMemberResults);
            }

            // Clean up and delete the container member (this also deletes any ContainerMembers still referencing it)
            // If deletion fails, we will see a duplicate container error the next time we deploy and handle it there.
            stub.delete(new String[] { containerResults[0].getId() });

        } else {
            handleMetadataContainerCreationFailure(project, stub, list, containerResults);
        }

    } catch (ForceException e) {
        handleToolingDeployException(e);
    }

}

From source file:org.apache.tez.history.parser.datamodel.BaseParser.java

/**
 * Set reference time to all events/*from   w  w w.  j  ava 2s .co m*/
 *
 * @param eventList
 * @param referenceTime
 */
private void setReferenceTime(List<Event> eventList, final long referenceTime) {
    Iterables.all(eventList, new Predicate<Event>() {
        @Override
        public boolean apply(Event input) {
            input.setReferenceTime(referenceTime);
            return false;
        }
    });
}

From source file:org.eclipse.sirius.diagram.ui.tools.internal.layout.provider.PinnedElementsLayoutProvider.java

/**
 * {@inheritDoc}/*w ww . j a v  a  2  s . com*/
 */
@Override
public Command layoutEditParts(final List selectedObjects, final IAdaptable layoutHint) {
    final Map<IGraphicalEditPart, Rectangle> initialBounds = Maps
            .newHashMap(baseProvider.getExtender().getUpdatedBounds());

    // Finds if there are unpinned diagram elements to keep fixed stored in
    // the LayoutHint as a Collection
    ArrayList<IDiagramElementEditPart> elementsToKeepFixed = Lists.newArrayList();
    if (layoutHint.getAdapter(Collection.class) instanceof ArrayList<?>
            && Iterables.all((ArrayList<?>) layoutHint.getAdapter(Collection.class),
                    validateAllElementInArrayListAreIDiagramElementEditPart)) {
        elementsToKeepFixed = (ArrayList<IDiagramElementEditPart>) layoutHint.getAdapter(Collection.class);
    }

    if (ArrangeAllWithAutoSize.isEnabled()) {
        adjustAutoSizedContainers(initialBounds, elementsToKeepFixed);
    }
    final Collection<IGraphicalEditPart> editParts = Lists
            .newArrayList(Iterables.filter(selectedObjects, IGraphicalEditPart.class));
    // Removes the connectionEditPart
    editParts.removeAll(Lists.newArrayList(Iterables.filter(selectedObjects, ConnectionEditPart.class)));
    final CompoundCommand cc = new CompoundCommand();

    handlePinnedElements(editParts, initialBounds, cc, elementsToKeepFixed);
    return cc.unwrap();
}

From source file:io.sidecar.event.Event.java

private void checkAllTagsHaveNoWhitespace() {
    List<String> allTags = Lists.newArrayList((tags != null) ? tags : Collections.<String>emptyList());
    for (KeyTag keyTag : (keytags != null) ? keytags : Collections.<KeyTag>emptyList()) {
        allTags.addAll(keyTag.getTags());
    }// w w  w .  j a v a2 s.  c  om
    checkArgument(Iterables.all(allTags, new Predicate<String>() {
        @Override
        public boolean apply(String input) {
            return CharMatcher.WHITESPACE.matchesNoneOf(input);
        }
    }), "tags or keytags must contain no whitespace characters");
}

From source file:natlab.tame.tir.TIRCommaSeparatedList.java

/**
 * returns true if all the expressions in the list are just name expressions
 *///from  w w  w .j a  v a2  s. c  o  m
public boolean isAllNameExpressions() {
    return Iterables.all(this, Predicates.instanceOf(NameExpr.class));
}

From source file:org.apache.cassandra.db.compaction.CompactionController.java

/**
 * Finds expired sstables//from   w  w w.  ja  va2s. c om
 *
 * works something like this;
 * 1. find "global" minTimestamp of overlapping sstables, compacting sstables and memtables containing any non-expired data
 * 2. build a list of fully expired candidates
 * 3. check if the candidates to be dropped actually can be dropped (maxTimestamp < global minTimestamp)
 *    - if not droppable, remove from candidates
 * 4. return candidates.
 *
 * @param cfStore
 * @param compacting we take the drop-candidates from this set, it is usually the sstables included in the compaction
 * @param overlapping the sstables that overlap the ones in compacting.
 * @param gcBefore
 * @return
 */
public static Set<SSTableReader> getFullyExpiredSSTables(ColumnFamilyStore cfStore,
        Iterable<SSTableReader> compacting, Iterable<SSTableReader> overlapping, int gcBefore) {
    logger.trace("Checking droppable sstables in {}", cfStore);

    if (compacting == null || NEVER_PURGE_TOMBSTONES)
        return Collections.<SSTableReader>emptySet();

    if (cfStore.getCompactionStrategyManager().onlyPurgeRepairedTombstones()
            && !Iterables.all(compacting, SSTableReader::isRepaired))
        return Collections.emptySet();

    List<SSTableReader> candidates = new ArrayList<>();

    long minTimestamp = Long.MAX_VALUE;

    for (SSTableReader sstable : overlapping) {
        // Overlapping might include fully expired sstables. What we care about here is
        // the min timestamp of the overlapping sstables that actually contain live data.
        if (sstable.getSSTableMetadata().maxLocalDeletionTime >= gcBefore)
            minTimestamp = Math.min(minTimestamp, sstable.getMinTimestamp());
    }

    for (SSTableReader candidate : compacting) {
        if (candidate.getSSTableMetadata().maxLocalDeletionTime < gcBefore)
            candidates.add(candidate);
        else
            minTimestamp = Math.min(minTimestamp, candidate.getMinTimestamp());
    }

    for (Memtable memtable : cfStore.getTracker().getView().getAllMemtables())
        minTimestamp = Math.min(minTimestamp, memtable.getMinTimestamp());

    // At this point, minTimestamp denotes the lowest timestamp of any relevant
    // SSTable or Memtable that contains a constructive value. candidates contains all the
    // candidates with no constructive values. The ones out of these that have
    // (getMaxTimestamp() < minTimestamp) serve no purpose anymore.

    Iterator<SSTableReader> iterator = candidates.iterator();
    while (iterator.hasNext()) {
        SSTableReader candidate = iterator.next();
        if (candidate.getMaxTimestamp() >= minTimestamp) {
            iterator.remove();
        } else {
            logger.trace("Dropping expired SSTable {} (maxLocalDeletionTime={}, gcBefore={})", candidate,
                    candidate.getSSTableMetadata().maxLocalDeletionTime, gcBefore);
        }
    }
    return new HashSet<>(candidates);
}