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.eclipse.sirius.ui.tools.internal.views.common.navigator.SiriusCommonContentProvider.java

private Set<IProject> getProjectsToRefresh(Session session) {
    Set<IProject> projectsToRefresh = Sets.newHashSet();

    if (session != null) {
        Iterable<Resource> resources = Iterables.concat(session.getAllSessionResources(),
                session.getSemanticResources());
        if (session instanceof DAnalysisSessionEObject) {
            resources = Iterables.concat(resources,
                    ((DAnalysisSessionEObject) session).getControlledResources());
        }//from  www.j a v  a  2s  .  co  m
        // Can occurs during session close : the previous lists were already
        // emptied.
        if (!Iterables.contains(resources, session.getSessionResource())) {
            resources = Iterables.concat(resources, Collections.singletonList(session.getSessionResource()));
        }

        for (Resource res : resources) {
            try {
                if (res.getURI() != null && res.getURI().isPlatformResource()) {
                    IFile file = WorkspaceSynchronizer.getFile(res);
                    if (file != null && file.exists() && file.getProject() != null) {
                        projectsToRefresh.add(file.getProject());
                    }
                }
            } catch (IllegalStateException e) {
                // In case cdoView is closed
            }
        }
    }
    return projectsToRefresh;
}

From source file:eu.numberfour.n4js.validation.validators.N4JSMemberRedefinitionValidator.java

private void messageOverrideMemberTypeConflict(RedefinitionType redefinitionType, TMember overriding,
        TMember overridden, Result<Boolean> result, MemberMatrix mm) {

    String message;/*from w  w  w . j  a  v  a  2  s  . co m*/
    String code;
    String redefinitionTypeName = redefinitionType.name();
    if (redefinitionType == RedefinitionType.implemented && Iterables.contains(mm.implemented(), overriding)) {
        redefinitionTypeName = "consumed";
    }

    String overridingSource = "";
    if (redefinitionType == RedefinitionType.implemented && Iterables.contains(mm.inherited(), overriding)) {
        overridingSource = "inherited ";
    }

    String extraMessage = cfOtherImplementedMembers(mm, overriding, overridden);

    if (overriding.isField() && overridden.isField()) {
        code = CLF_REDEFINED_TYPE_NOT_SAME_TYPE;
        message = getMessageForCLF_REDEFINED_TYPE_NOT_SAME_TYPE(
                overridingSource + validatorMessageHelper.descriptionDifferentFrom(overriding, overridden),
                redefinitionTypeName, validatorMessageHelper.descriptionDifferentFrom(overridden, overriding),
                extraMessage);
    } else if (overriding.isMethod() && overridden.isMethod()) {
        code = CLF_REDEFINED_METHOD_TYPE_CONFLICT;

        message = getMessageForCLF_REDEFINED_METHOD_TYPE_CONFLICT(
                overridingSource + validatorMessageHelper.descriptionDifferentFrom(overriding, overridden),
                redefinitionTypeName, validatorMessageHelper.descriptionDifferentFrom(overridden, overriding),
                validatorMessageHelper.trimTypesystemMessage(result), extraMessage);
    } else {
        code = CLF_REDEFINED_MEMBER_TYPE_INVALID;
        message = getMessageForCLF_REDEFINED_MEMBER_TYPE_INVALID(
                overridingSource + validatorMessageHelper.descriptionDifferentFrom(overriding, overridden),
                validatorMessageHelper.descriptionDifferentFrom(overridden, overriding), redefinitionTypeName,
                validatorMessageHelper.trimTypesystemMessage(result), extraMessage);
    }

    addIssueToMemberOrInterfaceReference(redefinitionType, overriding, overridden, message, code);
}

From source file:com.eucalyptus.compute.vpc.VpcManager.java

public CreateNetworkInterfaceResponseType createNetworkInterface(final CreateNetworkInterfaceType request)
        throws EucalyptusCloudException {
    final CreateNetworkInterfaceResponseType reply = request.getReply();
    final Context ctx = Contexts.lookup();
    final AccountFullName accountFullName = ctx.getUserFullName().asAccountFullName();
    final String subnetId = Identifier.subnet.normalize(request.getSubnetId());
    final String privateIp = request.getPrivateIpAddress() != null ? request.getPrivateIpAddress()
            : request.getPrivateIpAddressesSet() != null
                    && !request.getPrivateIpAddressesSet().getItem().isEmpty()
                            ? request.getPrivateIpAddressesSet().getItem().get(0).getPrivateIpAddress()
                            : null;/*w  w w.  j  a  v a 2s.  c o m*/
    final Supplier<NetworkInterface> allocator = new Supplier<NetworkInterface>() {
        @Override
        public NetworkInterface get() {
            try {
                final Subnet subnet = subnets.lookupByName(accountFullName, subnetId,
                        Functions.<Subnet>identity());
                final Vpc vpc = subnet.getVpc();
                final Set<NetworkGroup> groups = request.getGroupSet() == null
                        || request.getGroupSet().groupIds().isEmpty()
                                ? Sets.newHashSet(securityGroups.lookupDefault(vpc.getDisplayName(),
                                        Functions.<NetworkGroup>identity()))
                                : Sets.newHashSet(Iterables.transform(request.getGroupSet().groupIds(),
                                        RestrictedTypes.resolver(NetworkGroup.class)));
                if (groups.size() > VpcConfiguration.getSecurityGroupsPerNetworkInterface()) {
                    throw new ClientComputeException("SecurityGroupsPerInterfaceLimitExceeded",
                            "Security group limit exceeded");
                }
                if (!Collections.singleton(vpc.getDisplayName())
                        .equals(Sets.newHashSet(Iterables.transform(groups, NetworkGroup.vpcId())))) {
                    throw Exceptions.toUndeclared(new ClientComputeException("InvalidParameterValue",
                            "Invalid security groups (inconsistent VPC)"));
                }
                final String identifier = Identifier.eni.generate();
                if (privateIp != null) {
                    final Cidr cidr = Cidr.parse(subnet.getCidr());
                    if (!cidr.contains(privateIp)) {
                        throw new ClientComputeException("InvalidParameterValue",
                                "Address does not fall within the subnet's address range");
                    } else if (!Iterables.contains(Iterables.skip(IPRange.fromCidr(cidr), 3),
                            PrivateAddresses.asInteger(privateIp))) {
                        throw new ClientComputeException("InvalidParameterValue",
                                "Address is in subnet's reserved address range");
                    }
                }
                final String mac = NetworkInterfaceHelper.mac(identifier);
                final String ip = NetworkInterfaceHelper.allocate(vpc.getDisplayName(), subnet.getDisplayName(),
                        identifier, mac, privateIp);
                return networkInterfaces.save(NetworkInterface.create(ctx.getUserFullName(), vpc, subnet,
                        groups, identifier, mac, ip,
                        vpc.getDnsHostnames() ? VmInstances.dnsName(ip, DomainNames.internalSubdomain()) : null,
                        firstNonNull(request.getDescription(), "")));
            } catch (VpcMetadataNotFoundException ex) {
                throw Exceptions.toUndeclared(new ClientComputeException("InvalidSubnetID.NotFound",
                        "Subnet not found '" + request.getSubnetId() + "'"));
            } catch (ResourceAllocationException ex) {
                throw Exceptions
                        .toUndeclared(new ClientComputeException("InvalidParameterValue", ex.getMessage()));
            } catch (Exception ex) {
                final NoSuchMetadataException e = Exceptions.findCause(ex, NoSuchMetadataException.class);
                if (e != null) {
                    throw Exceptions.toUndeclared(
                            new ClientComputeException("InvalidSecurityGroupID.NotFound", e.getMessage()));
                }
                throw new RuntimeException(ex);
            }
        }
    };
    reply.setNetworkInterface(allocate(allocator, NetworkInterface.class, NetworkInterfaceType.class));
    return reply;
}

From source file:com.google.security.zynamics.binnavi.disassembly.CommentManager.java

/**
 * Appends a new local comment to the list of local instruction comments associated with the given
 * instruction./*from  www .  j  a v  a  2 s  .co m*/
 *
 * @param instruction The instruction to which the appended comment will be associated.
 * @param commentText The comments text.
 * @return The list of local instruction comments associated to the {@link INaviInstruction
 *         instruction}.
 *
 * @throws CouldntSaveDataException if the information could not be saved to the database.
 * @throws CouldntLoadDataException if the comment information could not be loaded from the
 *         database.
 */
public synchronized List<IComment> appendLocalInstructionComment(final INaviInstruction instruction,
        final INaviCodeNode node, final String commentText)
        throws CouldntSaveDataException, CouldntLoadDataException {
    Preconditions.checkNotNull(instruction, "IE01246: Instruction argument can not be null");
    Preconditions.checkNotNull(node, "IE02560: node argument can not be null");
    Preconditions.checkArgument(Iterables.contains(node.getInstructions(), instruction),
            "Error: instruction does not belong to the specified node");
    return appendComment(new InstructionCommentingStrategy(instruction, node, CommentScope.LOCAL), commentText);
}

From source file:r.base.Types.java

@Primitive
public static boolean inherits(SEXP exp, StringVector what) {
    StringVector classes = getClass(exp);
    for (String whatClass : what) {
        if (Iterables.contains(classes, whatClass)) {
            return true;
        }/*from   www.  j a v  a 2s .c  o  m*/
    }
    return false;
}

From source file:r.base.Types.java

@Primitive
public static boolean inherits(SEXP exp, String what) {
    return Iterables.contains(getClass(exp), what);
}

From source file:org.killbill.billing.invoice.InvoiceDispatcher.java

private Iterable<DateTime> getNextScheduledInvoiceEffectiveDate(final Iterable<UUID> filteredSubscriptionIds,
        final InternalCallContext internalCallContext) {
    try {//from  w  ww  .j a  v  a2 s  .  c om
        final NotificationQueue notificationQueue = notificationQueueService.getNotificationQueue(
                DefaultInvoiceService.INVOICE_SERVICE_NAME,
                DefaultNextBillingDateNotifier.NEXT_BILLING_DATE_NOTIFIER_QUEUE);
        final Iterable<NotificationEventWithMetadata<NextBillingDateNotificationKey>> futureNotifications = notificationQueue
                .getFutureNotificationForSearchKeys(internalCallContext.getAccountRecordId(),
                        internalCallContext.getTenantRecordId());

        final Collection<DateTime> effectiveDates = new LinkedList<DateTime>();
        for (final NotificationEventWithMetadata<NextBillingDateNotificationKey> input : futureNotifications) {
            final boolean isEventForSubscription = !filteredSubscriptionIds.iterator().hasNext()
                    || Iterables.contains(filteredSubscriptionIds, input.getEvent().getUuidKey());

            final boolean isEventDryRunForNotifications = input.getEvent()
                    .isDryRunForInvoiceNotification() != null
                            ? input.getEvent().isDryRunForInvoiceNotification()
                            : false;
            if (isEventForSubscription && !isEventDryRunForNotifications) {
                effectiveDates.add(input.getEffectiveDate());
            }

        }

        return effectiveDates;
    } catch (final NoSuchNotificationQueue noSuchNotificationQueue) {
        throw new IllegalStateException(noSuchNotificationQueue);
    }
}

From source file:org.eclipse.qvtd.compiler.internal.scheduler.ScheduledRegion.java

/**
 * Create the Passed Binding edges and join nodes between all introducers and their corresponding consuming heads. 
 *//* ww  w.  j ava 2s.  com*/
private void createBindings() {
    for (Region region : getCallableRegions()) {
        if (region instanceof RootRegion) {
            continue;
        }
        //
        //   Single-node head groups contribute a corresponding consumed class provided the
        //   class is part of the input model and is not an internal convenience.
        //
        for (List<Node> headNodes : region.getHeadNodeGroups()) {
            Node headNode;
            if (headNodes.size() == 1) {
                headNode = headNodes.get(0);
            } else {
                headNode = selectBestHeadNode(headNodes);
            }
            if (/*headNode.isLoaded() &&*/ !headNode.isInternal()) {
                createBinding(headNode);
            }
        }
        //
        //   Bind the non-navigable predicated nodes too
        //
        for (NavigationEdge predicatedEdge : region.getPredicatedNavigationEdges()) {
            Node predicatedNode = predicatedEdge.getTarget();
            if (predicatedEdge.isNavigation() && !predicatedEdge.isCast()) { // FIXME isCast does not need to be isNavigation now that it can be isNavigable
                PropertyDatum propertyDatum = getPropertyDatum(predicatedEdge);
                List<NavigationEdge> realizedEdges = producedPropertyDatum2realizedEdges.get(propertyDatum);
                if (realizedEdges != null) {
                    Property predicatedProperty = predicatedEdge.getProperty();
                    List<Node> realizingNodes = new ArrayList<Node>();
                    for (NavigationEdge realizedEdge : realizedEdges) {
                        Node realizedNode;
                        if (realizedEdge.getProperty() == predicatedProperty) {
                            realizedNode = realizedEdge.getTarget();
                        } else {
                            assert realizedEdge.getProperty() == predicatedProperty.getOpposite();
                            realizedNode = realizedEdge.getSource();
                        }
                        if (!realizingNodes.contains(realizedNode)) {
                            realizingNodes.add(realizedNode);
                        }
                    }
                    boolean isCast = false;
                    boolean isOther = false;
                    boolean isRecursion = false;
                    for (Edge outgoingEdge : predicatedNode.getOutgoingEdges()) {
                        if (outgoingEdge.isCast()) {
                            isCast = true;
                            Node castNode = outgoingEdge.getTarget();
                            assert !castNode.isConstant();
                            assert !castNode.isLoaded();
                            Connection predicatedConnection = getConnection(realizingNodes,
                                    castNode.getClassDatumAnalysis());
                            if (!Iterables.contains(predicatedConnection.getTargets(), castNode)) {
                                predicatedConnection.addUsedTargetNode(castNode, false);
                            }
                        } else if (outgoingEdge.isRecursion()) {
                            isRecursion = true;
                        } else {
                            isOther = true;
                        }
                    }
                    if (isOther || !(isCast || isRecursion)) {
                        //                  Iterable<Connection> passedConnections = predicatedNode.getIncomingPassedConnections();
                        //                  Connection usedConnection = predicatedNode.getIncomingUsedConnection();
                        //                  boolean isNew = (usedConnection == null) && Iterables.isEmpty(passedConnections);
                        //                  if (!isNew) {      // FIXME could be multiple
                        //                     isNew = (usedConnection == null) && Iterables.isEmpty(passedConnections);
                        //                  }      // FIXME could be multiple
                        Connection predicatedConnection = getConnection(realizingNodes,
                                predicatedNode.getClassDatumAnalysis());
                        if (!Iterables.contains(predicatedConnection.getTargets(), predicatedNode)) {
                            predicatedConnection.addUsedTargetNode(predicatedNode, false);
                        }
                    }
                }
            }
            //            if (!predicatedNode.isLoaded() && !predicatedNode.isConstant() && !isOnlyCastOrRecursed(predicatedNode)) {
            //            }
        }
    }
}

From source file:org.eclipse.qvtd.compiler.internal.scheduler.ScheduledRegion.java

private void createBinding(@NonNull Node headNode) {
    List<Node> sourceNodes = null;
    ClassDatumAnalysis classDatumAnalysis = headNode.getClassDatumAnalysis();
    ////from   w w  w .j av a2s . c o m
    //   Locate viable introducers
    //
    Iterable<Node> recursionSources = headNode.getRecursionSources();
    List<Node> introducingNodes = getIntroducingNodes(classDatumAnalysis);
    if (introducingNodes != null) {
        for (@SuppressWarnings("null")
        @NonNull
        Node introducingNode : introducingNodes) {
            if (isConflictFree(headNode, introducingNode, new HashMap<Node, Node>())
                    && !Iterables.contains(recursionSources, introducingNode)) {
                if (sourceNodes == null) {
                    sourceNodes = new ArrayList<Node>();
                }
                sourceNodes.add(introducingNode);
            }
        }
    }
    //
    //   Locate viable producers
    //
    List<Node> producingNodes = getProducingNodes(classDatumAnalysis);
    if (producingNodes != null) {
        for (@SuppressWarnings("null")
        @NonNull
        Node producingNode : producingNodes) {
            if (isConflictFree(headNode, producingNode, new HashMap<Node, Node>())) {
                if (sourceNodes == null) {
                    sourceNodes = new ArrayList<Node>();
                }
                sourceNodes.add(producingNode);
            }
        }
    }
    if (sourceNodes != null) {
        //
        //   Connection up the head
        //
        Connection headConnection = getConnection(sourceNodes, headNode.getClassDatumAnalysis());
        if (headNode.getNodeRole().isExtraGuardVariable()) {
            headConnection.addUsedTargetNode(headNode, false);
        } else {
            headConnection.addPassedTargetNode(headNode);
        }
        //
        //   Locate the corresponding sources for each guard in each calling region. 
        //
        HashMap<Node, List<Node>> predicated2availableSources = new HashMap<Node, List<Node>>();
        HashMap<Node, List<Region>> predicated2missingSources = new HashMap<Node, List<Region>>();
        for (Node sourceNode : sourceNodes) {
            Region headRegion = headNode.getRegion();
            if ((headRegion != sourceNode.getRegion()) && !(headRegion instanceof CompositionRegion)) {
                HashMap<Node, Node> predicated2source = new HashMap<Node, Node>();
                createUsedBindings(headNode, sourceNode, predicated2source);
                for (Map.Entry<Node, Node> entry : predicated2source.entrySet()) {
                    @SuppressWarnings("null")
                    @NonNull
                    Node calledNode = entry.getKey();
                    if (!calledNode.isHead()) {
                        Node callingNode = entry.getValue();
                        if (callingNode != null) {
                            List<Node> availableSources = predicated2availableSources.get(calledNode);
                            if (availableSources == null) {
                                availableSources = new ArrayList<Node>();
                                predicated2availableSources.put(calledNode, availableSources);
                            }
                            availableSources.add(callingNode);
                        } else {
                            List<Region> missingSources = predicated2missingSources.get(calledNode);
                            if (missingSources == null) {
                                missingSources = new ArrayList<Region>();
                                predicated2missingSources.put(calledNode, missingSources);
                            }
                            missingSources.add(sourceNode.getRegion());
                        }
                    }
                }
            }
        }
        //
        //   Connection the available calling sources to their called guards.
        //
        for (Map.Entry<Node, List<Node>> entry : predicated2availableSources.entrySet()) {
            @SuppressWarnings("null")
            @NonNull
            Node calledNode = entry.getKey();
            if (!calledNode.isLoaded() && !calledNode.isConstant()) {
                @SuppressWarnings("null")
                @NonNull
                List<Node> availableNodes = entry.getValue();
                Connection guardConnection = getConnection(availableNodes, calledNode.getClassDatumAnalysis());
                guardConnection.addUsedTargetNode(calledNode, false);
            }
        }
        for (Map.Entry<Node, List<Region>> entry : predicated2missingSources.entrySet()) {
            @SuppressWarnings("null")
            @NonNull
            Node calledNode = entry.getKey();
            //            @SuppressWarnings("null")@NonNull List<Region> missingRegions = entry.getValue();
            //            for (Region missingRegion : missingRegions) {
            ClassDatumAnalysis classDatumAnalysis2 = calledNode.getClassDatumAnalysis();
            List<Node> missingSourceNodes = new ArrayList<Node>();
            List<Node> introducedNodes = getIntroducingNodes(classDatumAnalysis2);
            if (introducedNodes != null) {
                missingSourceNodes.addAll(introducedNodes);
            }
            List<Node> producedNodes = getProducingNodes(classDatumAnalysis2);
            if (producedNodes != null) {
                missingSourceNodes.addAll(producedNodes);
            }
            for (int i = missingSourceNodes.size(); --i >= 0;) {
                Node missingSourceNode = missingSourceNodes.get(i);
                if (missingSourceNode.getRegion() == calledNode.getRegion()) {
                    missingSourceNodes.remove(i); // FIXME only if a Recursion Edge
                }
            }
            if ((missingSourceNodes.size() > 0) && !calledNode.isLoaded()) {
                Connection missingConnection = getConnection(missingSourceNodes,
                        calledNode.getClassDatumAnalysis());
                missingConnection.addUsedTargetNode(calledNode, false);
            }
            //            }
        }
        // FIXME guard2missingSources
    }
}

From source file:com.forerunnergames.tools.common.Arguments.java

private static boolean hasNullKeys(final Map<?, ?> map) {
    return map != null && Iterables.contains(map.keySet(), null);
}