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

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

Introduction

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

Prototype

public static boolean contains(Iterable<?> iterable, @Nullable Object element) 

Source Link

Document

Returns true if iterable contains any object for which equals(element) is true.

Usage

From source file:org.apache.brooklyn.core.mgmt.persist.BrooklynMementoPersisterTestFixture.java

@Test
public void testDeleteAndLoadMemento() throws Exception {
    Entities.destroy(entity);/*w ww .  java2  s.  c  om*/

    BrooklynMemento reloadedMemento = loadMemento();

    assertNotNull(reloadedMemento);
    assertFalse(Iterables.contains(reloadedMemento.getEntityIds(), entity.getId()));
    assertEquals(Iterables.getOnlyElement(reloadedMemento.getLocationIds()), location.getId());
}

From source file:com.android.tools.idea.structure.AndroidModuleStructureConfigurable.java

@Override
protected boolean canBeRemoved(Object[] editableObjects) {
    for (Object editableObject : editableObjects) {
        if (editableObject != null && editableObject instanceof String) {
            String moduleName = (String) editableObject;
            if (Iterables.contains(mySettingsFile.getModules(), moduleName)) {
                return true;
            }//from w  w  w .ja  va2 s.  com
        }
    }
    return false;
}

From source file:org.apache.brooklyn.core.mgmt.persist.BrooklynMementoPersisterTestFixture.java

@Test
public void testLoadAndCheckpointRawMemento() throws Exception {
    if (persister instanceof BrooklynMementoPersisterToObjectStore) {
        // Test loading
        BrooklynMementoRawData rawMemento = loadRawMemento((BrooklynMementoPersisterToObjectStore) persister);
        assertNotNull(rawMemento);//from  w ww.  j  a v a  2  s. c om
        assertTrue(Iterables.contains(rawMemento.getEntities().keySet(), entity.getId()));
        assertEquals(Iterables.getOnlyElement(rawMemento.getLocations().keySet()), location.getId());
        assertEquals(Iterables.getOnlyElement(rawMemento.getPolicies().keySet()), policy.getId());
        assertTrue(rawMemento.getEnrichers().keySet().contains(enricher.getId()));

        // And test persisting
        PersistenceExceptionHandler exceptionHandler = PersistenceExceptionHandlerImpl.builder().build();
        ((BrooklynMementoPersisterToObjectStore) persister).checkpoint(rawMemento, exceptionHandler);
    } else {
        throw new SkipException("Persister " + persister + " not a "
                + BrooklynMementoPersisterToObjectStore.class.getSimpleName());
    }
}

From source file:com.android.tools.idea.structure.AndroidModuleStructureConfigurable.java

@Override
protected boolean removeObject(Object editableObject) {
    if (editableObject != null && editableObject instanceof String) {
        final String moduleName = (String) editableObject;
        if (Iterables.contains(mySettingsFile.getModules(), moduleName)) {

            // TODO: This applies changes immediately. We need to save up changes and not apply them until the user confirms the dialog.
            // In the old dialog this is handled by the fact that we have a ModifiableRootModel that queues changes.

            // TODO: If removing a module, remove any dependencies on that module in other modules. Perhaps we should show this to the user
            // in the confirmation dialog, and ask if dependencies should be cleaned up?

            String question;// w  w w  .j a v  a 2 s  . c o m
            if (Iterables.size(mySettingsFile.getModules()) == 1) {
                question = ProjectBundle.message("module.remove.last.confirmation");
            } else {
                question = ProjectBundle.message("module.remove.confirmation", moduleName);
            }
            int result = Messages.showYesNoDialog(myProject, question,
                    ProjectBundle.message("module.remove.confirmation.title"), Messages.getQuestionIcon());
            if (result != 0) {
                return false;
            }
            ApplicationManager.getApplication().runWriteAction(new Runnable() {
                @Override
                public void run() {
                    mySettingsFile.removeModule(moduleName);
                }
            });
            return true;
        }
    }
    return false;
}

From source file:com.eucalyptus.reporting.ReportingDataVerifier.java

/**
 * Get the events neccessary to align the current view with the target view.
 *
 * @param target The desired "event" state
 * @param current The current state//  w  ww  . j av a2  s . c om
 * @return The bag describing the necessary events
 */
public static EventDescriptionBag getEventDifferences(final View target, final View current) {
    final EventDescriptionBag description = new EventDescriptionBag();

    final Set<Class<?>> types = Sets.newHashSet(Iterables
            .transform(Iterables.concat(target.typedResourceHolders, current.typedResourceHolders), type()));
    for (final Class<?> type : types) {
        final TypedResourceHolder targetHolder = target.getHolderOrNull(type);
        final TypedResourceHolder currentHolder = current.getHolderOrNull(type);

        if (targetHolder == null) {
            description.delete.add(currentHolder);
        } else if (currentHolder == null) {
            description.create.add(targetHolder);
        } else { // determine difference
            final TypedResourceHolder add = new TypedResourceHolder(type);
            final TypedResourceHolder del = new TypedResourceHolder(type);
            final TypedResourceHolder att = new TypedResourceHolder(type);
            final TypedResourceHolder det = new TypedResourceHolder(type);

            // create copies containing only items that differ
            List<ResourceWithRelation<?>> targetCopy = Lists.newArrayList(targetHolder.resources);
            List<ResourceWithRelation<?>> currentCopy = Lists.newArrayList(currentHolder.resources);
            targetCopy.removeAll(currentHolder.resources);
            currentCopy.removeAll(targetHolder.resources);

            final Set<ResourceKey> keys = Sets
                    .newHashSet(Iterables.transform(Iterables.concat(targetCopy, currentCopy), key()));
            for (final ResourceKey key : keys) {
                final List<ResourceWithRelation<?>> findIn;
                final TypedResourceHolder addTo;
                if (!Iterables.contains(Iterables.transform(targetCopy, key()), key)) {
                    findIn = currentCopy;
                    addTo = del;
                } else if (!Iterables.contains(Iterables.transform(currentCopy, key()), key)) {
                    findIn = targetCopy;
                    addTo = add;
                } else if (Iterables.find(targetCopy, withKeyMatching(key)).relationId == null) {
                    findIn = currentCopy;
                    addTo = det;
                } else {
                    findIn = targetCopy;
                    addTo = att;
                }
                addTo.resources.add(Iterables.find(findIn, withKeyMatching(key)));
            }

            if (!add.resources.isEmpty())
                description.create.add(add);
            if (!del.resources.isEmpty())
                description.delete.add(del);
            if (!att.resources.isEmpty())
                description.attach.add(att);
            if (!det.resources.isEmpty())
                description.detach.add(det);
        }
    }

    return description;
}

From source file:mesosphere.marathon.core.leadership.CandidateImpl.java

@Override
public Supplier<Boolean> offerLeadership(final Candidate.Leader leader)
        throws Group.JoinException, Group.WatchException, InterruptedException {

    // start a group watch, but only once in the life time of the the CandidateImpl.
    if (this.cancelWatch == null) {
        this.cancelWatch = this.group.watch(new Group.GroupChangeListener() {
            @Override/*w ww .ja va 2 s . c o  m*/
            public void onGroupChange(Iterable<String> memberIds) {
                Group.GroupChangeListener listener = groupChangeListener.get();
                if (listener != null) {
                    listener.onGroupChange(memberIds);
                }
            }
        });
    }

    // listen for group member changes
    final AtomicBoolean elected = new AtomicBoolean(false);
    final AtomicBoolean abdicated = new AtomicBoolean(false);
    final AtomicReference<Group.Membership> membershipRef = new AtomicReference<Group.Membership>(null);
    final AtomicReference<Iterable<String>> pendingChange = new AtomicReference<Iterable<String>>(null);
    this.groupChangeListener.set(new Group.GroupChangeListener() {
        @Override
        public void onGroupChange(Iterable<String> memberIds) {
            boolean noCandidates = Iterables.isEmpty(memberIds);
            Group.Membership membership;
            synchronized (CandidateImpl.this) {
                membership = membershipRef.get();
                if (membership == null) {
                    pendingChange.set(memberIds);
                    return;
                } else {
                    pendingChange.set(null);
                }
            }
            String memberId = membership.getMemberId();

            if (noCandidates) {
                LOG.warning("All candidates have temporarily left the group: " + group);
            } else if (!Iterables.contains(memberIds, memberId)) {
                LOG.severe(
                        String.format("Current member ID %s is not a candidate for leader, current voting: %s",
                                memberId, memberIds));
            } else {
                boolean electedLeader = memberId.equals(getLeader(memberIds));
                boolean previouslyElected = elected.getAndSet(electedLeader);

                if (!previouslyElected && electedLeader) {
                    LOG.info(String.format("Candidate %s is now leader of group: %s",
                            membership.getMemberPath(), memberIds));

                    leader.onElected(new ExceptionalCommand<Group.JoinException>() {
                        @Override
                        public void execute() throws Group.JoinException {
                            Group.Membership membership = membershipRef.get();
                            if (membership != null) {
                                membership.cancel();
                            }
                            abdicated.set(true);
                        }
                    });
                } else if (!electedLeader) {
                    if (previouslyElected) {
                        leader.onDefeated();
                    }
                    LOG.info(String.format(
                            "Candidate %s waiting for the next leader election, current voting: %s",
                            membership.getMemberPath(), memberIds));
                }
            }
        }
    });

    // join the group
    membershipRef.set(group.join(dataSupplier, new Command() {
        @Override
        public void execute() {
            membershipRef.set(null);
            leader.onDefeated();
        }
    }));

    // possibly the upper membershipRef.set is not finished yet when the groupChangeListener
    // fires above. Then one onGroupChange call is pending which is executed here:
    synchronized (this) {
        Iterable<String> memberIds = pendingChange.getAndSet(null);
        if (memberIds != null) {
            this.groupChangeListener.get().onGroupChange(memberIds);
        }
    }

    return new Supplier<Boolean>() {
        @Override
        public Boolean get() {
            return !abdicated.get() && elected.get();
        }
    };
}

From source file:io.brooklyn.ambari.AmbariClusterImpl.java

@Override
public void init() {
    super.init();

    isHostGroupsDeployment = Iterables.size(getHostGroups()) > 0;

    addChild(createServerSpec(getConfig(SECURITY_GROUP)));
    if (!getConfig(SERVER_COMPONENTS).isEmpty()) {
        for (AmbariServer ambariServer : getAmbariServers()) {
            ambariServer.config().set(SoftwareProcess.CHILDREN_STARTABLE_MODE,
                    SoftwareProcess.ChildStartableMode.BACKGROUND_LATE);
            EntitySpec<? extends AmbariAgent> agentSpec = AmbariAgentImpl.createAgentSpec(this, null);
            ambariServer.addChild(agentSpec);
        }//www.j  a v a 2  s .  com
    }

    services = MutableList.copyOf(getConfig(HADOOP_SERVICES));

    calculateTotalAgents();
    if (!isHostGroupsDeployment) {
        createClusterTopology();
        if (services.size() == 0) {
            services.addAll(DEFAULT_SERVICES);
        }
    }

    addEnricher(Enrichers.builder().propagating(Attributes.MAIN_URI).from(getMasterAmbariServer()).build());

    componentsByNode = new MutableMap<String, List<String>>();
    addDeprecatedExtraServiceToExtraServices();
    for (EntitySpec<? extends ExtraService> entitySpec : getConfig(EXTRA_HADOOP_SERVICES)) {
        LOG.warn(EXTRA_HADOOP_SERVICES.getName()
                + " configuration key is deprecated. Extra services should now be defined through as children by using 'brooklyn.children'");
        addChild(entitySpec);
    }

    final Iterable<String> ambariHostGroupNames = transform(getHostGroups(),
            new Function<AmbariHostGroup, String>() {
                @Nullable
                @Override
                public String apply(@Nullable AmbariHostGroup ambariHostGroup) {
                    return ambariHostGroup != null ? ambariHostGroup.getDisplayName() : null;
                }
            });

    for (ExtraService extraService : Entities.descendants(this, ExtraService.class)) {
        if (extraService.getConfig(ExtraService.SERVICE_NAME) == null
                && extraService.getConfig(ExtraService.COMPONENT_NAMES) == null) {
            continue;
        }

        if (isHostGroupsDeployment) {
            checkNotNull(extraService.getConfig(ExtraService.COMPONENT_NAMES),
                    "Entity \"%s\" must define a list of components names as this is a host groups based deployment. Please use the \"%s\" configuration key",
                    extraService.getEntityType().getName(), ExtraService.COMPONENT_NAMES.getName());

            for (ExtraService.ComponentMapping componentMapping : extraService.getComponentMappings()) {
                if (!componentMapping.getHost().equals(getConfig(SERVER_HOST_GROUP))
                        && !Iterables.contains(ambariHostGroupNames, componentMapping.getHost())) {
                    throw new IllegalStateException(String.format(
                            "Extra component \"%s\" of entity \"%s\" cannot be bound to \"%s\" host group because it does not exist. Please choose from %s or "
                                    + getConfig(SERVER_HOST_GROUP),
                            componentMapping.getComponent(), extraService.getEntityType().getName(),
                            componentMapping.getHost(), ambariHostGroupNames));
                }
                if (!componentsByNode.containsKey(componentMapping.getHost())) {
                    componentsByNode.put(componentMapping.getHost(), MutableList.<String>of());
                }
                componentsByNode.get(componentMapping.getHost()).add(componentMapping.getComponent());
            }
        } else {
            checkNotNull(extraService.getConfig(ExtraService.SERVICE_NAME),
                    "Entity \"%s\" must define a service name as this is a services based deployment. Please use the \"%s\" configuration key",
                    extraService.getEntityType().getName(), ExtraService.SERVICE_NAME.getName());

            if (StringUtils.isNotBlank(extraService.getConfig(ExtraService.SERVICE_NAME))) {
                services.add(extraService.getConfig(ExtraService.SERVICE_NAME));
            }
        }
    }

}

From source file:org.eclipse.sirius.diagram.sequence.ui.tool.internal.edit.operation.ShiftDescendantMessagesOperation.java

private void shiftAnchor(Edge edge) {
    boolean isOutgoing = Iterables.contains(Iterables.transform(movedElements, ISequenceElement.NOTATION_VIEW),
            edge.getSource());/*from  www  .jav a 2 s. c o  m*/

    if (isOutgoing) {
        IdentityAnchor sourceAnchor = (IdentityAnchor) edge.getSourceAnchor();
        int sourceAnchorLocation = SequenceGraphicalHelper.getAnchorAbsolutePosition(sourceAnchor,
                oldParentRange);
        PrecisionPoint position = BaseSlidableAnchor.parseTerminalString(sourceAnchor.getId());
        position.setPreciseY(newParentRange.getProportionalLocation(sourceAnchorLocation));
        String terminal = new SlidableAnchor(null, position).getTerminal();
        sourceAnchor.setId(terminal);
    } else {
        IdentityAnchor targetAnchor = (IdentityAnchor) edge.getTargetAnchor();
        int targetAnchorLocation = SequenceGraphicalHelper.getAnchorAbsolutePosition(targetAnchor,
                oldParentRange);
        PrecisionPoint position = BaseSlidableAnchor.parseTerminalString(targetAnchor.getId());
        position.setPreciseY(newParentRange.getProportionalLocation(targetAnchorLocation));
        String terminal = new SlidableAnchor(null, position).getTerminal();
        targetAnchor.setId(terminal);
    }
}

From source file:org.atlasapi.content.Described.java

public <T extends Described> boolean isEquivalentTo(T content) {
    return getEquivalentTo().contains(EquivalenceRef.valueOf(content)) || Iterables
            .contains(Iterables.transform(content.getEquivalentTo(), Identifiables.toId()), getId());
}

From source file:bear.plugins.misc.Releases.java

void delete(List<String> toDelete) {
    checkLoaded();/* ww  w  .j a va2 s.  co  m*/

    Preconditions.checkArgument(!Iterables.contains(toDelete, current), "won't delete current folder!");

    for (String s : toDelete) {
        removeItem(s);
    }

    //apps may be run under a root and create files with root's owner
    String[] paths = toDelete.toArray(new String[toDelete.size()]);

    $.sys.rm(paths).sudo().run();

    sort();
}