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:org.eclipse.sirius.diagram.ui.tools.internal.actions.straighten.StraightenToAction.java

/**
 * Return only a list of selected AbstractDiagramEdgeEditPart that
 * understands the request. If there is at least one other kind of edit
 * part, an empty list is returned./*  w  ww.  j a va 2 s  .  co  m*/
 * 
 * @return A list of {@link AbstractDiagramEdgeEditPart} selected.
 */
@Override
protected List<?> createOperationSet() {
    List<?> selection = getSelectedObjects();
    if (!Iterables.all(selection, Predicates.instanceOf(AbstractDiagramEdgeEditPart.class))) {
        selection = Collections.EMPTY_LIST;
    }
    return selection;
}

From source file:org.immutables.sequence.Sequence.java

/**
 * Returns {@code true} if every element in this fluent iterable satisfies the predicate.
 * If this fluent iterable is empty, {@code true} is returned.
 * @param predicate the predicate//w w  w  . j ava2  s  .com
 * @return true, if successful
 */
public final boolean allMatch(Predicate<? super E> predicate) {
    return Iterables.all(iterable, predicate::test);
}

From source file:de.cosmocode.palava.salesforce.DefaultSalesforceService.java

private List<SaveResult> create(List<SObject> objects, int retries) {
    Preconditions.checkNotNull(objects, "Objects");
    if (objects.isEmpty())
        throw new IllegalArgumentException("Objects must not be empty");
    final List<SaveResult> results;

    try {// w ww . j av  a2 s  .  co  m
        results = get().create(objects);
    } catch (InvalidFieldFault e) {
        throw new SalesforceException(e);
    } catch (InvalidIdFault e) {
        throw new SalesforceException(e);
    } catch (InvalidSObjectFault e) {
        throw new SalesforceException(e);
    } catch (UnexpectedErrorFault e) {
        if (retries < maxRetries) {
            reconnect();
            return create(objects, retries + 1);
        } else {
            throw new SalesforceException(e);
        }
    }

    if (Iterables.all(results, Salesforce.SAVE_SUCCESS)) {
        final String name = objects.get(0).getClass().getSimpleName();
        LOG.info("Successfully created {} {}(s)", results.size(), name);
        return results;
    } else {
        final Iterable<SaveResult> failures = Iterables.filter(results, Salesforce.SAVE_FAILURE);
        final List<Error> errors = Lists.newArrayList();
        for (SaveResult failure : failures) {
            errors.addAll(failure.getErrors());
        }
        throw new SalesforceException(errors);
    }
}

From source file:edu.ucsb.eucalyptus.cloud.entities.VolumeToken.java

/**
 * Return true if and only if this token's only active export is for the given ip/iqn pair.
 * Does not restrict to a single export record, but if multiple exist for same ip/iqn it will
 * still return true /*from  ww  w.j  av  a 2  s  . co m*/
 * @param ip
 * @param iqn
 * @return
 * @throws EucalyptusCloudException
 */
public boolean hasOnlyExport(final String ip, final String iqn) throws EucalyptusCloudException {
    try {
        return Iterables.all(this.getExportRecords(), new Predicate<VolumeExportRecord>() {
            @Override
            public boolean apply(VolumeExportRecord rec) {
                if (rec.getIsActive()) {
                    return rec.getHostIp().equals(ip) && rec.getHostIqn().equals(iqn);
                } else {
                    //Return true if not an active export, since we don't care which host it is for.
                    return true;
                }
            }
        });
    } catch (Exception e) {
        LOG.error("Error checking for only export on " + ip + " : " + iqn + ". Error:" + e.getMessage());
        throw new EucalyptusCloudException(e);
    }
}

From source file:org.edna.datamodel.transformations.m2m.Dsl2UmlTransformation.java

/**
 * Types which only contain elements, whose type is a primitive type,
 * are considered as Datatype Wrapper. References to those types should
 * be just a Property without association in the target UML model.
 *//*from  w w  w.  j a  v  a  2s .c  o m*/
private boolean isDataTypeWrapper(ComplexType type) {
    return Iterables.all(type.getElements(), new Predicate<ElementDeclaration>() {
        public boolean apply(ElementDeclaration input) {
            return input.getRef() == null;
        }
    });
}

From source file:com.isotrol.impe3.pms.core.impl.PortalsServiceImpl.java

@Transactional(rollbackFor = Throwable.class)
@Authorized(global = GlobalAuthority.PORTAL_SET)
public String create(PortalNameDTO dto, String parentId) throws PMSException {
    checkNotNull(dto);/*from w  w  w. ja v  a 2s  .c  o  m*/
    checkNotNull(MoreLocales.VALID.apply(dto.getDefaultLocale()));
    checkArgument(dto.getLocales() == null || Iterables.all(dto.getLocales().keySet(), MoreLocales.VALID));
    checkNotNull(dto.getName());
    checkNotNull(dto.getName().getDisplayName());
    final ContextGlobal global = loadContextGlobal();
    final PortalObject parent;
    final PortalEntity parentEntity;
    if (parentId != null) {
        parent = global.getPortals().load(parentId);
        parentEntity = load(parent.getId());
    } else {
        parent = null;
        parentEntity = null;
    }
    final PortalEntity entity = new PortalEntity();
    final DeviceEntity device = getDao().getDeviceByName(DeviceManager.DEFAULT);
    entity.setDefaultDevice(device);
    final PortalDfn dfn = new PortalDfn();
    dfn.setRoutingDomain(findById(RoutingDomainEntity.class, global.getDomains().loadDefault().getId()));
    getEnvironment().touchPortalVersion(loadUser());
    dfn.setName(Mappers.DTO2NAME.apply(dto.getName()));
    dfn.setDescription(dto.getDescription());
    dfn.setDefaultLocale(dto.getDefaultLocale());
    dfn.getLocales().clear();
    if (dto.getLocales() != null) {
        dfn.getLocales().addAll(dto.getLocales().keySet());
    }
    dfn.getL7DNames().clear();
    if (dto.getLocales() != null) {
        dfn.getL7DNames().putAll(filterValues(dto.getLocales(), notNull()));
    }
    dfn.setParent(parentEntity);
    // Devices
    dfn.setInheritedDevices(parent != null);
    final UUID id = saveNewEntity(entity, dfn);
    return id.toString();
}

From source file:com.facebook.presto.sql.planner.EqualityInference.java

private static Predicate<Expression> symbolToExpressionPredicate(final Predicate<Symbol> symbolScope) {
    return expression -> Iterables.all(DependencyExtractor.extractUnique(expression), symbolScope);
}

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

private static boolean markFileDepsAndPropagateFilesystemExceptions(PackageIdentifier packageIdentifier,
        Iterable<SkyKey> depKeys, Environment env, boolean packageWasInError)
        throws InternalInconsistentFilesystemException, InterruptedException {
    Preconditions.checkState(Iterables.all(depKeys, SkyFunctions.isSkyFunction(SkyFunctions.FILE)), depKeys);
    boolean packageShouldBeInError = packageWasInError;
    for (Map.Entry<SkyKey, ValueOrException3<IOException, FileSymlinkException, InconsistentFilesystemException>> entry : env
            .getValuesOrThrow(depKeys, IOException.class, FileSymlinkException.class,
                    InconsistentFilesystemException.class)
            .entrySet()) {/*  ww  w  .j  a  va 2 s  . co m*/
        try {
            entry.getValue().get();
        } catch (IOException e) {
            maybeThrowFilesystemInconsistency(packageIdentifier, e, packageWasInError);
        } catch (FileSymlinkException e) {
            // Legacy doesn't detect symlink cycles.
            packageShouldBeInError = true;
        } catch (InconsistentFilesystemException e) {
            throw new InternalInconsistentFilesystemException(packageIdentifier, e);
        }
    }
    return packageShouldBeInError;
}

From source file:org.eclipse.sirius.diagram.ui.graphical.edit.policies.MoveEdgeGroupManager.java

/**
 * Determines if the given request is a valid request for this tool.<br/>
 * Each selected edge should respect the following rules:
 * <ul>//from  ww w. j a va 2 s  .c  o m
 * <li>a border node as source</li>
 * <li>a border node as target</li>
 * <li>source node has only one connection: the moved edge.</li>
 * <li>target node has only one connection: the moved edge.</li>
 * <li>Both border nodes are on the same axe (Horizontal or Vertical)</li>
 * </ul>
 * <br/>
 * Furthermore, every selected edge group should be in the same direction
 * and only edges should be selected.
 * 
 * @return true if the moved edges and border nodes can be activated,
 *         otherwise false.
 */
@SuppressWarnings("unchecked")
private boolean accept() {
    if (request instanceof BendpointRequest) {
        ConnectionEditPart connectionEditPart = ((BendpointRequest) request).getSource();
        // The selected diagram element should only contain edges otherwise
        // the move is not valid
        final Set<Integer> edgeDirections = Sets.newLinkedHashSet();
        boolean result = Iterables.all(connectionEditPart.getViewer().getSelectedEditParts(), Predicates
                .and(Predicates.instanceOf(ConnectionEditPart.class), new Predicate<ConnectionEditPart>() {
                    /**
                     * Determines if the given edge respects the following rules:
                     * <ul>
                     * <li>a border node as source</li>
                     * <li>a border node as target</li>
                     * <li>source node has only one connection: the moved edge.</li>
                     * <li>target node has only one connection: the moved edge.</li>
                     * <li>Both border nodes are on the same axe (Horizontal or
                     * Vertical)</li>
                     * </ul>
                     */
                    @Override
                    public boolean apply(ConnectionEditPart input) {
                        EditPart sourceEditPart = input.getSource();
                        EditPart targetEditPart = input.getTarget();

                        if (sourceEditPart instanceof AbstractDiagramBorderNodeEditPart
                                && targetEditPart instanceof AbstractDiagramBorderNodeEditPart) {
                            if (getAllConnections((AbstractDiagramBorderNodeEditPart) sourceEditPart)
                                    .size() == 1
                                    && getAllConnections((AbstractDiagramBorderNodeEditPart) targetEditPart)
                                            .size() == 1) {
                                int sourceDirection = getBorderNodeDirection(
                                        (AbstractDiagramBorderNodeEditPart) sourceEditPart);
                                int targetDirection = getBorderNodeDirection(
                                        (AbstractDiagramBorderNodeEditPart) targetEditPart);
                                if (sourceDirection == targetDirection) {
                                    direction = sourceDirection;
                                    edgeDirections.add(sourceDirection);
                                    return true;
                                }
                            }
                        }
                        return false;
                    }
                }));
        // There should be only one kind of direction for every edges to
        // authorize the move
        return result && edgeDirections.size() == 1;
    }
    return false;
}

From source file:de.cau.cs.kieler.klay.layered.p5edges.OrthogonalEdgeRouter.java

/**
 * {@inheritDoc}/*from  w  ww. j a  v  a2  s  . c o  m*/
 */
public void process(final LGraph layeredGraph, final IKielerProgressMonitor monitor) {
    monitor.begin("Orthogonal edge routing", 1);

    // Retrieve some generic values
    double nodeSpacing = layeredGraph.getProperty(InternalProperties.SPACING).doubleValue();
    double edgeSpacing = nodeSpacing * layeredGraph.getProperty(Properties.EDGE_SPACING_FACTOR);
    boolean debug = layeredGraph.getProperty(LayoutOptions.DEBUG_MODE);

    // Prepare for iteration!
    OrthogonalRoutingGenerator routingGenerator = new OrthogonalRoutingGenerator(
            OrthogonalRoutingGenerator.RoutingDirection.WEST_TO_EAST, edgeSpacing, debug ? "phase5" : null);
    float xpos = 0.0f;
    ListIterator<Layer> layerIter = layeredGraph.getLayers().listIterator();
    Layer leftLayer = null;
    Layer rightLayer = null;
    List<LNode> leftLayerNodes = null;
    List<LNode> rightLayerNodes = null;
    int leftLayerIndex = -1;
    int rightLayerIndex = -1;

    // Iterate!
    do {
        int slotsCount;

        // Fetch the next layer, if any
        rightLayer = layerIter.hasNext() ? layerIter.next() : null;
        rightLayerNodes = rightLayer == null ? null : rightLayer.getNodes();
        rightLayerIndex = layerIter.previousIndex();

        // Place the left layer's nodes, if any
        if (leftLayer != null) {
            LGraphUtil.placeNodes(leftLayer, xpos);
            xpos += leftLayer.getSize().x;
        }

        // Route edges between the two layers
        slotsCount = routingGenerator.routeEdges(layeredGraph, leftLayerNodes, leftLayerIndex, rightLayerNodes,
                leftLayer == null ? xpos : xpos + edgeSpacing);

        boolean isLeftLayerExternal = leftLayer == null
                || Iterables.all(leftLayerNodes, PolylineEdgeRouter.PRED_EXTERNAL_WEST_OR_EAST_PORT);
        boolean isRightLayerExternal = rightLayer == null
                || Iterables.all(rightLayerNodes, PolylineEdgeRouter.PRED_EXTERNAL_WEST_OR_EAST_PORT);

        if (slotsCount > 0) {
            // The space between each pair of edge segments, and between nodes and edges
            double increment = slotsCount * edgeSpacing;
            if (rightLayer != null) {
                increment += edgeSpacing;
            }

            // If we are between two layers, make sure their minimal spacing is preserved
            if (increment < nodeSpacing && !isLeftLayerExternal && !isRightLayerExternal) {
                increment = nodeSpacing;
            }
            xpos += increment;
        } else if (!isLeftLayerExternal && !isRightLayerExternal) {
            // If all edges are straight, use the usual spacing 
            xpos += nodeSpacing;
        }

        leftLayer = rightLayer;
        leftLayerNodes = rightLayerNodes;
        leftLayerIndex = rightLayerIndex;
    } while (rightLayer != null);

    layeredGraph.getSize().x = xpos;

    monitor.done();
}