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:de.cosmocode.palava.salesforce.DefaultSalesforceService.java

private List<SaveResult> update(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 {//from   ww w .  j a  v  a2s  .com
        results = get().update(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 update(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 updated {} {}(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:org.eclipse.sirius.diagram.ui.internal.refresh.listeners.EdgeLayoutUpdaterModelChangeTrigger.java

/**
 * Test whether the edge centering should be refreshed for this
 * notification./* w w w.j av a  2s  .com*/
 * 
 * @param notification
 *            The {@link Notification} to check.
 * @param notifications
 *            the whole notification list.
 * @return true if this notification concerns the edge ends centering, false
 *         otherwise.
 */
private boolean isRefreshEdgeLayoutNeededForNotification(final Notification notification,
        Collection<Notification> notifications) {
    if (REFRESH_FEATURES.contains(notification.getFeature())) {
        Option<Edge> optionalEdge = getCorrespondingEdge(notification);
        if (optionalEdge.some()) {
            final Edge referenceEdge = optionalEdge.get();
            // Analyze other notifications to detect if the source or the
            // target of the concerned edges has been moved. In this case we
            // consider that a "full" layout has been done and that it its
            // responsibility to correctly set the edge layout.
            return Iterables.all(notifications, new Predicate<Notification>() {
                @Override
                public boolean apply(Notification currentNotification) {
                    boolean apply = false;
                    if (currentNotification == notification) {
                        apply = true;
                    } else {
                        Option<? extends View> optionalView = getCorrespondingView(currentNotification);
                        if (optionalView.some() && optionalView.get() == referenceEdge.getSource()
                                || optionalView.get() == referenceEdge.getTarget()) {
                            // The notification concerns the source or the
                            // target of the edge, return true only if the
                            // notification does not concern a move or a
                            // resize feature
                            apply = !MOVE_OR_RESIZE_FEATURES.contains(currentNotification.getFeature());
                        } else {
                            apply = true;
                        }
                    }
                    return apply;
                }
            });
        }
    }
    return false;
}

From source file:com.google.enterprise.adaptor.secmgr.servlets.ResponseParser.java

private boolean areValidSubjectConfirmations(List<SubjectConfirmation> confirmations) {
    if (confirmations.isEmpty()) {
        // This violates the SAML spec, but the GSA has historically ignored this
        // information, so we must allow it.
        warn("SAML assertion received without subject confirmation");
        return true;
    }//from  w ww.  j a va  2 s . com
    Iterable<SubjectConfirmation> bearers = Iterables.filter(confirmations, bearerPredicate);
    return warnIfFalse(!Iterables.isEmpty(bearers), "SubjectConfirmations contains no bearers.")
            && warnIfFalse(Iterables.all(bearers, validBearerPredicate), "SubjectConfirmations were invalid.");
}

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

/**
 * These deps have already been marked (see {@link SkyframeHybridGlobber}) but we need to properly
 * handle some errors that legacy package loading can't handle gracefully.
 *//*from  w ww  .  j a va 2s.  c om*/
private static boolean handleGlobDepsAndPropagateFilesystemExceptions(PackageIdentifier packageIdentifier,
        Iterable<SkyKey> depKeys, Environment env, boolean packageWasInError)
        throws InternalInconsistentFilesystemException, InterruptedException {
    Preconditions.checkState(Iterables.all(depKeys, SkyFunctions.isSkyFunction(SkyFunctions.GLOB)), depKeys);
    boolean packageShouldBeInError = packageWasInError;
    for (Map.Entry<SkyKey, ValueOrException4<IOException, BuildFileNotFoundException, FileSymlinkException, InconsistentFilesystemException>> entry : env
            .getValuesOrThrow(depKeys, IOException.class, BuildFileNotFoundException.class,
                    FileSymlinkException.class, InconsistentFilesystemException.class)
            .entrySet()) {
        try {
            entry.getValue().get();
        } catch (IOException | BuildFileNotFoundException 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:com.isotrol.impe3.pms.core.impl.PortalsServiceImpl.java

/**
 * @see com.isotrol.impe3.pms.api.portal.PortalsService#setName(com.isotrol.impe3.pms.api.portal.PortalNameDTO)
 */// ww w  .  j  a  v a  2  s  .  c  om
@Transactional(rollbackFor = Throwable.class)
@Authorized(global = GlobalAuthority.PORTAL_SET, portal = PortalAuthority.SET)
public void setName(PortalNameDTO dto) throws PMSException {
    checkNotNull(dto);
    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 String id = dto.getId();
    final PortalEntity entity = load(id);
    final PortalDfn dfn = portalManager.touchOffline(entity);
    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()));
    }
}

From source file:google.registry.tools.CreateOrUpdateRegistrarCommand.java

@Override
protected final void init() throws Exception {
    initRegistrarCommand();/*from   ww w . jav  a 2 s .  co  m*/
    DateTime now = DateTime.now(UTC);
    for (String clientId : mainParameters) {
        Registrar oldRegistrar = getOldRegistrar(clientId);
        Registrar.Builder builder = (oldRegistrar == null) ? new Registrar.Builder().setClientId(clientId)
                : oldRegistrar.asBuilder();

        if (!isNullOrEmpty(password)) {
            builder.setPassword(password);
        }
        if (!isNullOrEmpty(registrarName)) {
            builder.setRegistrarName(registrarName);
        }
        if (email != null) {
            builder.setEmailAddress(email.orNull());
        }
        if (url != null) {
            builder.setUrl(url.orNull());
        }
        if (phone != null) {
            builder.setPhoneNumber(phone.orNull());
        }
        if (fax != null) {
            builder.setFaxNumber(fax.orNull());
        }
        if (registrarType != null) {
            builder.setType(registrarType);
        }
        if (registrarState != null) {
            builder.setState(registrarState);
        }
        if (driveFolderId != null) {
            builder.setDriveFolderId(driveFolderId.orNull());
        }
        if (!allowedTlds.isEmpty()) {
            checkArgument(addAllowedTlds.isEmpty(), "Can't specify both --allowedTlds and --addAllowedTlds");
            ImmutableSet.Builder<String> allowedTldsBuilder = new ImmutableSet.Builder<>();
            for (String allowedTld : allowedTlds) {
                allowedTldsBuilder.add(canonicalizeDomainName(allowedTld));
            }
            builder.setAllowedTlds(allowedTldsBuilder.build());
        }
        if (!addAllowedTlds.isEmpty()) {
            ImmutableSet.Builder<String> allowedTldsBuilder = new ImmutableSet.Builder<>();
            if (oldRegistrar != null) {
                allowedTldsBuilder.addAll(oldRegistrar.getAllowedTlds());
            }
            for (String allowedTld : addAllowedTlds) {
                allowedTldsBuilder.add(canonicalizeDomainName(allowedTld));
            }
            builder.setAllowedTlds(allowedTldsBuilder.build());
        }
        if (!ipWhitelist.isEmpty()) {
            ImmutableList.Builder<CidrAddressBlock> ipWhitelistBuilder = new ImmutableList.Builder<>();
            if (!(ipWhitelist.size() == 1 && ipWhitelist.get(0).contains("null"))) {
                for (String ipRange : ipWhitelist) {
                    ipWhitelistBuilder.add(CidrAddressBlock.create(ipRange));
                }
            }
            builder.setIpAddressWhitelist(ipWhitelistBuilder.build());
        }
        if (clientCertificateFilename != null) {
            String asciiCert = new String(Files.readAllBytes(clientCertificateFilename), US_ASCII);
            builder.setClientCertificate(asciiCert, now);
        }
        if (failoverClientCertificateFilename != null) {
            String asciiCert = new String(Files.readAllBytes(failoverClientCertificateFilename), US_ASCII);
            builder.setFailoverClientCertificate(asciiCert, now);
        }
        if (!isNullOrEmpty(clientCertificateHash)) {
            checkArgument(clientCertificateFilename == null, "Can't specify both --cert_hash and --cert_file");
            if ("null".equals(clientCertificateHash)) {
                clientCertificateHash = null;
            }
            builder.setClientCertificateHash(clientCertificateHash);
        }
        if (ianaId != null) {
            builder.setIanaIdentifier(ianaId.orNull());
        }
        if (billingId != null) {
            builder.setBillingIdentifier(billingId.orNull());
        }
        if (billingMethod != null) {
            if (oldRegistrar != null && !billingMethod.equals(oldRegistrar.getBillingMethod())) {
                Map<CurrencyUnit, Money> balances = RegistrarBillingUtils.loadBalance(oldRegistrar);
                for (Money balance : balances.values()) {
                    checkState(balance.isZero(),
                            "Refusing to change billing method on Registrar '%s' from %s to %s"
                                    + " because current balance is non-zero: %s",
                            clientId, oldRegistrar.getBillingMethod(), billingMethod, balances);
                }
            }
            builder.setBillingMethod(billingMethod);
        }
        List<Object> streetAddressFields = Arrays.asList(street, city, state, zip, countryCode);
        checkArgument(
                Iterables.any(streetAddressFields, isNull()) == Iterables.all(streetAddressFields, isNull()),
                "Must specify all fields of address");
        if (street != null) {
            // We always set the localized address for now. That should be safe to do since it supports
            // unrestricted UTF-8.
            builder.setLocalizedAddress(new RegistrarAddress.Builder().setStreet(ImmutableList.copyOf(street))
                    .setCity(city).setState("null".equals(state) ? null : state)
                    .setZip("null".equals(zip) ? null : zip).setCountryCode(countryCode).build());
        }
        if (blockPremiumNames != null) {
            builder.setBlockPremiumNames(blockPremiumNames);
        }
        if (contactsRequireSyncing != null) {
            builder.setContactsRequireSyncing(contactsRequireSyncing);
        }
        // When creating a new REAL registrar or changing the type to REAL, a passcode is required.
        // Leave existing REAL registrars alone.
        if (Registrar.Type.REAL.equals(registrarType)
                && (oldRegistrar == null || oldRegistrar.getPhonePasscode() == null)) {
            checkArgument(phonePasscode != null, "--passcode is required for REAL registrars.");
        }
        if (phonePasscode != null) {
            builder.setPhonePasscode(phonePasscode);
        }
        if (icannReferralEmail != null) {
            builder.setIcannReferralEmail(icannReferralEmail);
        }
        if (whoisServer != null) {
            builder.setWhoisServer(whoisServer);
        }

        // If the registrarName is being set, verify that it is either null or it normalizes uniquely.
        String oldRegistrarName = (oldRegistrar == null) ? null : oldRegistrar.getRegistrarName();
        if (registrarName != null && !registrarName.equals(oldRegistrarName)) {
            String normalizedName = normalizeRegistrarName(registrarName);
            for (Registrar registrar : Registrar.loadAll()) {
                if (registrar.getRegistrarName() != null) {
                    checkArgument(!normalizedName.equals(normalizeRegistrarName(registrar.getRegistrarName())),
                            "The registrar name %s normalizes identically to existing registrar name %s",
                            registrarName, registrar.getRegistrarName());
                }
            }
        }

        stageEntityChange(oldRegistrar, builder.build());
    }
}

From source file:com.palantir.atlasdb.keyvalue.cassandra.CQLKeyValueService.java

protected void performInitialSetup() {
    Metadata metadata = cluster.getMetadata();

    final CassandraKeyValueServiceConfig config = configManager.getConfig();
    String partitioner = metadata.getPartitioner();
    if (!config.safetyDisabled()) {
        Validate.isTrue(CassandraConstants.ALLOWED_PARTITIONERS.contains(partitioner),
                "partitioner is: " + partitioner);
    }/*from  w ww.ja v  a  2 s.  c  om*/

    Set<Peer> peers = CQLKeyValueServices.getPeers(session);

    boolean noDatacentersPresentInCluster = Iterables.all(peers, new Predicate<Peer>() {
        @Override
        public boolean apply(Peer peer) {
            return peer.data_center == null;
        }
    });

    boolean allNodesHaveSaneNumberOfVnodes = Iterables.all(peers, new Predicate<Peer>() {
        @Override
        public boolean apply(Peer peer) {
            return peer.tokens.size() > CassandraConstants.ABSOLUTE_MINIMUM_NUMBER_OF_TOKENS_PER_NODE;
        }
    });

    // node we're querying doesn't count itself as a peer
    if (peers.size() > 0 && !allNodesHaveSaneNumberOfVnodes) {
        throw new IllegalStateException(
                "All nodes in cluster must have sane number of vnodes (or cluster must consist of a single node).");
    }

    Set<String> dcsInCluster = Sets.newHashSet();
    if (!noDatacentersPresentInCluster) {
        for (Peer peer : peers) {
            dcsInCluster.add(peer.data_center);
            if (peer.data_center == null) {
                throw new IllegalStateException(
                        "Cluster should not mix datacenter-aware and non-datacenter-aware nodes.");
            }
        }
    }

    if (metadata.getKeyspace(config.keyspace()) == null) { // keyspace previously didn't exist; we need to set it up
        createKeyspace(config.keyspace(), dcsInCluster);
        return;
    }

    createTables(ImmutableMap.of(CassandraConstants.METADATA_TABLE, AtlasDbConstants.EMPTY_TABLE_METADATA));
}

From source file:com.qcadoo.mes.productionPerShift.util.ProgressPerShiftViewSaver.java

private Either<? extends List<Entity>, Void> validateDailyProgressesFor(final Entity progressForDay) {
    List<Entity> savedDailyProgresses = FluentIterable
            .from(progressForDay.getHasManyField(ProgressForDayFields.DAILY_PROGRESS))
            .transform(new Function<Entity, Entity>() {

                @Override// w  ww.j a  v  a2s  .c om
                public Entity apply(final Entity dailyProgress) {
                    return tryValidateDailyProgress(dailyProgress).fold(Functions.<Entity>identity(),
                            Functions.constant(dailyProgress));
                }
            }).toList();
    if (Iterables.all(savedDailyProgresses, IS_VALID)) {
        return Either.right(null);
    }
    return Either.left(savedDailyProgresses);
}

From source file:org.richfaces.ui.input.autocomplete.AbstractAutocomplete.java

/**
 * Returns 'table' if all children are columns and thus the component should be rendered as a table; it returns 'list'
 * otherwise/*  w w  w. ja  va2 s.c om*/
 */
@Attribute(generate = false, hidden = true, defaultValue = "Layout.list")
public String getLayout() {
    return (getChildCount() > 0 && Iterables.all(getChildren(), Predicates.instanceOf(UIColumn.class)))
            ? "table"
            : "list";
}

From source file:org.jclouds.gogrid.GoGridLiveTestDisabled.java

/**
 * Tests common server image operations.
 *///from  w w  w .  ja  v  a  2 s.co  m
@Test(enabled = true)
public void testImageLifecycle() {
    GetImageListOptions options = GetImageListOptions.Builder.publicDatabaseServers();
    Set<ServerImage> images = api.getImageServices().getImageList(options);

    Predicate<ServerImage> isDatabaseServer = new Predicate<ServerImage>() {
        @Override
        public boolean apply(@Nullable ServerImage serverImage) {
            return checkNotNull(serverImage).getType() == ServerImageType.DATABASE_SERVER;
        }
    };

    assert Iterables.all(images, isDatabaseServer) : "All of the images should've been of database type";

    ServerImage image = Iterables.getLast(images);
    ServerImage imageFromServer = Iterables
            .getOnlyElement(api.getImageServices().getImagesByName(image.getName()));
    assertEquals(image, imageFromServer);

    try {
        api.getImageServices().editImageDescription(image.getName(), "newDescription");
        throw new TestException(
                "An exception hasn't been thrown where expected; expected GoGridResponseException");
    } catch (GoGridResponseException e) {
        // expected situation - check and proceed
        assertTrue(e.getMessage().contains("GoGridIllegalArgumentException"));
    }

}