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

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

Introduction

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

Prototype

public static <T> boolean removeIf(Iterable<T> removeFrom, Predicate<? super T> predicate) 

Source Link

Document

Removes, from an iterable, every element that satisfies the provided predicate.

Usage

From source file:org.jclouds.abiquo.domain.cloud.VirtualMachine.java

public VirtualMachineTask setNics(final Network<?> gatewayNetwork, final List<Ip<?, ?>> ips,
        final List<UnmanagedNetwork> unmanagedNetworks) {
    // Remove the gateway configuration and the current nics
    Iterables.removeIf(target.getLinks(),
            Predicates.or(LinkPredicates.isNic(), LinkPredicates.rel(ParentLinkName.NETWORK_GATEWAY)));

    // Add the given nics in the appropriate order
    int i = 0;/*  ww  w  . ja va 2s  . com*/
    if (ips != null) {
        for (i = 0; i < ips.size(); i++) {
            RESTLink source = LinkUtils.getSelfLink(ips.get(i).unwrap());
            RESTLink link = new RESTLink("nic" + i, source.getHref());
            link.setType(ips.get(i).unwrap().getBaseMediaType());
            target.addLink(link);
        }
    }

    // Add unmanaged network references, if given
    if (unmanagedNetworks != null) {
        for (UnmanagedNetwork unmanaged : unmanagedNetworks) {
            RESTLink source = checkNotNull(unmanaged.unwrap().searchLink("ips"),
                    ValidationErrors.MISSING_REQUIRED_LINK + "ips");

            RESTLink link = new RESTLink("nic" + i, source.getHref());
            link.setType(UnmanagedIpDto.BASE_MEDIA_TYPE);
            target.addLink(link);
            i++;
        }
    }

    VirtualMachineTask task = update(true);
    if (gatewayNetwork == null) {
        return task;
    }

    // If there is a gateway network, we have to wait until the network
    // configuration links are
    // available
    if (task != null) {
        VirtualMachineState originalState = target.getState();
        VirtualMachineMonitor monitor = context.utils().injector().getInstance(MonitoringService.class)
                .getVirtualMachineMonitor();
        monitor.awaitState(originalState, this);
    }

    // Set the new network configuration

    // Refresh virtual machine, to get the new configuration links
    refresh();

    VMNetworkConfigurationsDto configs = context.getApi().getCloudApi().listNetworkConfigurations(target);

    Iterables.removeIf(target.getLinks(), LinkPredicates.rel(ParentLinkName.NETWORK_GATEWAY));
    for (VMNetworkConfigurationDto config : configs.getCollection()) {
        if (config.getGateway().equalsIgnoreCase(gatewayNetwork.getGateway())) {
            target.addLink(new RESTLink(ParentLinkName.NETWORK_GATEWAY, config.getEditLink().getHref()));
            break;
        }
    }

    return update(true);
}

From source file:org.asoem.greyfish.core.space.WalledPointSpace.java

@Override
public boolean removeIf(final Predicate<O> predicate) {
    synchronized (this) {
        if (Iterables.removeIf(point2DMap.keySet(), predicate)) {
            tree.invalidate();/*w w w.  ja  v  a  2s  .c  o m*/
            return true;
        }
        return false;
    }
}

From source file:org.eclipse.rcptt.launching.ext.Q7ExternalLaunchDelegate.java

@Override
public String[] getVMArguments(ILaunchConfiguration config) throws CoreException {
    CachedInfo info = LaunchInfoCache.getInfo(config);
    if (info.vmArgs != null) {
        return info.vmArgs;
    }/*w ww  .  ja  v  a2 s.  co  m*/
    List<String> args = new ArrayList<String>(Arrays.asList(super.getVMArguments(config)));

    // Filter some PDE parameters
    Iterables.removeIf(args, new Predicate<String>() {
        public boolean apply(String input) {
            if (input.contains("-Declipse.pde.launch=true")) {
                return true;
            }
            return false;
        }
    });

    args.add("-Dq7id=" + launch.getAttribute(IQ7Launch.ATTR_AUT_ID));
    args.add("-Dq7EclPort=" + AutEventManager.INSTANCE.getPort());

    TargetPlatformHelper target = (TargetPlatformHelper) ((ITargetPlatformHelper) info.target);

    IPluginModelBase hook = target.getWeavingHook();
    if (hook == null) {
        throw new CoreException(Q7ExtLaunchingPlugin.status("No " + AJConstants.HOOK + " plugin"));
    }

    // Append all other properties from original config file
    OriginalOrderProperties properties = target.getConfigIniProperties();

    args = UpdateVMArgs.addHook(args, hook, properties.getProperty(OSGI_FRAMEWORK_EXTENSIONS));

    args.add("-Declipse.vmargs=" + Joiner.on("\n").join(args) + "\n");

    info.vmArgs = args.toArray(new String[args.size()]);
    Q7ExtLaunchingPlugin.getDefault().info(Q7_LAUNCHING_AUT + config.getName()
            + ": AUT JVM arguments is set to : " + Arrays.toString(info.vmArgs));
    return info.vmArgs;
}

From source file:org.apache.twill.yarn.YarnTwillRunnerService.java

private YarnTwillController listenController(final YarnTwillController controller) {
    controller.onTerminated(new Runnable() {
        @Override//from  www.j  av  a2s .  com
        public void run() {
            synchronized (YarnTwillRunnerService.this) {
                Iterables.removeIf(controllers.values(), new Predicate<YarnTwillController>() {
                    @Override
                    public boolean apply(YarnTwillController input) {
                        return input == controller;
                    }
                });
            }
        }
    }, Threads.SAME_THREAD_EXECUTOR);
    return controller;
}

From source file:org.syncany.cli.AbstractInitCommand.java

protected TransferPlugin askPlugin(final Class<? extends TransferPlugin> ignoreTransferPluginClass) {
    TransferPlugin plugin = null;//from ww  w . ja v a2s  .c o  m
    final List<TransferPlugin> plugins = Plugins.list(TransferPlugin.class);

    Iterables.removeIf(plugins, new Predicate<TransferPlugin>() {
        @Override
        public boolean apply(TransferPlugin transferPlugin) {
            return ignoreTransferPluginClass == transferPlugin.getClass();
        }
    });

    String pluginsList = StringUtil.join(plugins, ", ", new StringJoinListener<TransferPlugin>() {
        @Override
        public String getString(TransferPlugin plugin) {
            return plugin.getId();
        }
    });

    while (plugin == null) {
        out.println("Choose a storage plugin. Available plugins are: " + pluginsList);
        out.print("Plugin: ");
        String pluginStr = console.readLine();

        plugin = Plugins.get(pluginStr, TransferPlugin.class);

        if (plugin == null || ignoreTransferPluginClass == plugin.getClass()) {
            out.println("ERROR: Plugin does not exist or cannot be used.");
            out.println();

            plugin = null;
        }
    }

    return plugin;
}

From source file:ezbake.groups.graph.EzGroupsGraphImpl.java

/**
 * Gets all groups excluding any 'special' groups.
 *
 * @return all groups excluding any 'special' groups
 *//*from www .ja va  2s  .c om*/
@Override
public Set<Group> getGroups() {
    final FramedGraph<TitanGraph> framedGraph = getFramedGraph();

    final Iterable<Group> groups = framedGraph.frameVertices(
            framedGraph.query().has(BaseVertex.TYPE, BaseVertex.VertexType.GROUP.toString()).vertices(),
            Group.class);

    final Set<Group> retrievedGroups = Sets.newHashSet(groups);
    Iterables.removeIf(retrievedGroups, NON_USER_FACING_GROUP);

    return retrievedGroups;
}

From source file:org.apache.hadoop.hive.shims.Hadoop23Shims.java

/**
 * Removes basic permission acls (unamed acls) from the list of acl entries
 * @param entries acl entries to remove from.
 *//* ww w . j a  v a2  s .  c o  m*/
private void removeBaseAclEntries(List<AclEntry> entries) {
    Iterables.removeIf(entries, new Predicate<AclEntry>() {
        @Override
        public boolean apply(AclEntry input) {
            if (input.getName() == null) {
                return true;
            }
            return false;
        }
    });
}

From source file:com.eucalyptus.vm.VmInstances.java

private static void cleanUpAttachedVolumes(final VmInstance vm) {
    if (VmStateSet.DONE.apply(vm)) {
        final Collection<String> volumesToDelete = Sets.newTreeSet();
        try (final TransactionResource db = Entities.distinctTransactionFor(VmInstance.class)) {
            final VmInstance instance = Entities.merge(vm);

            // Clean up transient volumes
            if (instance.getTransientVolumeState() != null) {
                cleanUpAttachedVolumes(instance.getInstanceId(), "transient",
                        instance.getTransientVolumeState().getAttachments(), deleteOnTerminateFilter(false));
                addMatchingVolumeIds(volumesToDelete, instance.getTransientVolumeState().getAttachments(),
                        deleteOnTerminateFilter(true));
            }//from ww w .j  a v  a2s  . co m

            // Clean up persistent volumes that are not delete-on-terminate
            if (instance.getBootRecord() != null) {
                cleanUpAttachedVolumes(instance.getInstanceId(), "persistent",
                        instance.getBootRecord().getPersistentVolumes(), deleteOnTerminateFilter(false));
                addMatchingVolumeIds(volumesToDelete, instance.getBootRecord().getPersistentVolumes(),
                        deleteOnTerminateFilter(true));
            }

            db.commit();
        } catch (Exception ex) {
            LOG.error(vm.getInstanceId() + ": Failed to cleanup attached volumes", ex);
        }

        try {
            if (!volumesToDelete.isEmpty()) {
                LOG.debug(vm.getInstanceId() + ": Cleanup for delete on terminate volumes.");
                for (final String volumeId : volumesToDelete) {
                    try {
                        LOG.debug(vm.getInstanceId() + ": Firing delete request for " + volumeId);
                        AsyncRequests.newRequest(
                                new MessageCallback<DeleteStorageVolumeType, DeleteStorageVolumeResponseType>(
                                        new DeleteStorageVolumeType(volumeId)) {
                                    @Override
                                    public void initialize(final DeleteStorageVolumeType request) {
                                    }

                                    @Override
                                    public void fire(final DeleteStorageVolumeResponseType response) {
                                        Function<DeleteStorageVolumeResponseType, Void> deleteVolume = new Function<DeleteStorageVolumeResponseType, Void>() {
                                            @Nullable
                                            @Override
                                            public Void apply(
                                                    final DeleteStorageVolumeResponseType deleteStorageVolumeResponseType) {
                                                final Volume volume = Volumes.lookup(null, volumeId);
                                                if (null != response && response.get_return()) {
                                                    Volumes.annihilateStorageVolume(volume);
                                                } else {
                                                    LOG.error(vm.getInstanceId() + ": Failed to delete volume "
                                                            + volumeId);
                                                }
                                                VmInstance instance = Entities.merge(vm);
                                                if (instance.getTransientVolumeState() != null && instance
                                                        .getTransientVolumeState().getAttachments() != null) {
                                                    Iterables.removeIf(
                                                            instance.getTransientVolumeState().getAttachments(),
                                                            volumeIdFilter(volumeId));
                                                }
                                                if (instance.getBootRecord() != null && instance.getBootRecord()
                                                        .getPersistentVolumes() != null) {
                                                    Iterables.removeIf(
                                                            instance.getBootRecord().getPersistentVolumes(),
                                                            volumeIdFilter(volumeId));
                                                }
                                                return null;
                                            }
                                        };
                                        Entities.asTransaction(Volume.class, deleteVolume).apply(response);
                                    }

                                    @Override
                                    public void fireException(final Throwable throwable) {
                                        LOG.error(vm.getInstanceId() + ": Failed to delete volume " + volumeId,
                                                throwable);
                                    }
                                }).dispatch(Topology.lookup(Storage.class, vm.lookupPartition()));
                    } catch (NoSuchElementException e) {
                        LOG.debug(vm.getInstanceId() + ": Persistent volume not found for cleanup " + volumeId);
                    } catch (Exception ex) {
                        LOG.error(vm.getInstanceId() + ": Failed to cleanup persistent volume attachment for "
                                + volumeId, ex);
                    }
                }
            }
        } catch (Exception ex) {
            LOG.error(vm.getInstanceId() + ": Failed to cleanup attached volumes", ex);
        }
    }
}

From source file:com.cloudera.impala.planner.SingleNodePlanner.java

/**
 * Returns plan tree for an inline view ref:
 * - predicates from the enclosing scope that can be evaluated directly within
 *   the inline-view plan are pushed down
 * - predicates that cannot be evaluated directly within the inline-view plan
 *   but only apply to the inline view are evaluated in a SelectNode placed
 *   on top of the inline view plan/*from   www .  j  ava2s.  co  m*/
 * - all slots that are referenced by predicates from the enclosing scope that cannot
 *   be pushed down are marked as materialized (so that when computeMemLayout() is
 *   called on the base table descriptors materialized by the inline view it has a
 *   complete picture)
 */
private PlanNode createInlineViewPlan(Analyzer analyzer, InlineViewRef inlineViewRef) throws ImpalaException {
    // If possible, "push down" view predicates; this is needed in order to ensure
    // that predicates such as "x + y = 10" are evaluated in the view's plan tree
    // rather than a SelectNode grafted on top of that plan tree.
    // This doesn't prevent predicate propagation, because predicates like
    // "x = 10" that get pushed down are still connected to equivalent slots
    // via the equality predicates created for the view's select list.
    // Include outer join conjuncts here as well because predicates from the
    // On-clause of an outer join may be pushed into the inline view as well.
    //
    // Limitations on predicate propagation into inline views:
    // If the inline view computes analytic functions, we cannot push any
    // predicate into the inline view tree (see IMPALA-1243). The reason is that
    // analytic functions compute aggregates over their entire input, and applying
    // filters from the enclosing scope *before* the aggregate computation would
    // alter the results. This is unlike regular aggregate computation, which only
    // makes the *output* of the computation visible to the enclosing scope, so that
    // filters from the enclosing scope can be safely applied (to the grouping cols, say)
    List<Expr> unassigned = analyzer.getUnassignedConjuncts(inlineViewRef.getId().asList(), true);
    boolean migrateConjuncts = !inlineViewRef.getViewStmt().hasLimit()
            && !inlineViewRef.getViewStmt().hasOffset() && (!(inlineViewRef.getViewStmt() instanceof SelectStmt)
                    || !((SelectStmt) (inlineViewRef.getViewStmt())).hasAnalyticInfo());
    if (migrateConjuncts) {
        // check if we can evaluate them
        List<Expr> preds = Lists.newArrayList();
        for (Expr e : unassigned) {
            if (analyzer.canEvalPredicate(inlineViewRef.getId().asList(), e))
                preds.add(e);
        }
        unassigned.removeAll(preds);

        // Generate predicates to enforce equivalences among slots of the inline view
        // tuple. These predicates are also migrated into the inline view.
        analyzer.createEquivConjuncts(inlineViewRef.getId(), preds);

        // create new predicates against the inline view's unresolved result exprs, not
        // the resolved result exprs, in order to avoid skipping scopes (and ignoring
        // limit clauses on the way)
        List<Expr> viewPredicates = Expr.substituteList(preds, inlineViewRef.getSmap(), analyzer, false);

        // Remove unregistered predicates that reference the same slot on
        // both sides (e.g. a = a). Such predicates have been generated from slot
        // equivalences and may incorrectly reject rows with nulls (IMPALA-1412).
        Predicate<Expr> isIdentityPredicate = new Predicate<Expr>() {
            @Override
            public boolean apply(Expr expr) {
                if (!(expr instanceof BinaryPredicate)
                        || ((BinaryPredicate) expr).getOp() != BinaryPredicate.Operator.EQ) {
                    return false;
                }
                if (!expr.isRegisteredPredicate() && expr.getChild(0) instanceof SlotRef
                        && expr.getChild(1) instanceof SlotRef && (((SlotRef) expr.getChild(0))
                                .getSlotId() == ((SlotRef) expr.getChild(1)).getSlotId())) {
                    return true;
                }
                return false;
            }
        };
        Iterables.removeIf(viewPredicates, isIdentityPredicate);

        // "migrate" conjuncts_ by marking them as assigned and re-registering them with
        // new ids.
        // Mark pre-substitution conjuncts as assigned, since the ids of the new exprs may
        // have changed.
        analyzer.markConjunctsAssigned(preds);
        inlineViewRef.getAnalyzer().registerConjuncts(viewPredicates);
    }

    // mark (fully resolve) slots referenced by remaining unassigned conjuncts_ as
    // materialized
    List<Expr> substUnassigned = Expr.substituteList(unassigned, inlineViewRef.getBaseTblSmap(), analyzer,
            false);
    analyzer.materializeSlots(substUnassigned);

    // Turn a constant select into a UnionNode that materializes the exprs.
    // TODO: unify this with createConstantSelectPlan(), this is basically the
    // same thing
    QueryStmt viewStmt = inlineViewRef.getViewStmt();
    if (viewStmt instanceof SelectStmt) {
        SelectStmt selectStmt = (SelectStmt) viewStmt;
        if (selectStmt.getTableRefs().isEmpty()) {
            if (inlineViewRef.getAnalyzer().hasEmptyResultSet()) {
                return createEmptyNode(viewStmt, inlineViewRef.getAnalyzer());
            }
            // Analysis should have generated a tuple id_ into which to materialize the exprs.
            Preconditions.checkState(inlineViewRef.getMaterializedTupleIds().size() == 1);
            // we need to materialize all slots of our inline view tuple
            analyzer.getTupleDesc(inlineViewRef.getId()).materializeSlots();
            UnionNode unionNode = new UnionNode(ctx_.getNextNodeId(),
                    inlineViewRef.getMaterializedTupleIds().get(0));
            if (analyzer.hasEmptyResultSet())
                return unionNode;
            unionNode.setTblRefIds(Lists.newArrayList(inlineViewRef.getId()));
            unionNode.addConstExprList(selectStmt.getBaseTblResultExprs());
            unionNode.init(analyzer);
            return unionNode;
        }
    }

    PlanNode rootNode = createQueryPlan(inlineViewRef.getViewStmt(), inlineViewRef.getAnalyzer(), false);
    // TODO: we should compute the "physical layout" of the view's descriptor, so that
    // the avg row size is availble during optimization; however, that means we need to
    // select references to its resultExprs from the enclosing scope(s)
    rootNode.setTblRefIds(Lists.newArrayList(inlineViewRef.getId()));
    // Set smap *before* creating a SelectNode in order to allow proper resolution.
    // Analytics have an additional level of logical to physical slot remapping.
    // The composition creates a mapping from the logical output of the inline view
    // to the physical analytic output. In addition, it retains the logical to
    // physical analytic slot mappings which are needed to resolve exprs that already
    // reference the logical analytic tuple (and not the inline view tuple), e.g.,
    // the result exprs set in the coordinator fragment.
    rootNode.setOutputSmap(
            ExprSubstitutionMap.compose(inlineViewRef.getBaseTblSmap(), rootNode.getOutputSmap(), analyzer));
    // if the view has a limit we may have conjuncts_ from the enclosing scope left
    if (!migrateConjuncts) {
        rootNode = addUnassignedConjuncts(analyzer, inlineViewRef.getDesc().getId().asList(), rootNode);
    }
    return rootNode;
}

From source file:cz.cuni.mff.ms.brodecva.botnicek.ide.design.system.model.DefaultSystem.java

private void removeReferences(final Network removed) {
    final Collection<Entry<EnterNode, RecurentArc>> entries = this.references.entries();
    Iterables.removeIf(entries, new Predicate<Entry<EnterNode, RecurentArc>>() {

        @Override/*from w ww. ja  v a2  s . c o  m*/
        public boolean apply(final Entry<EnterNode, RecurentArc> input) {
            final RecurentArc referring = input.getValue();
            return referring.getNetwork().equals(removed);
        }

    });
}