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<UpsertResult> upsert(List<SObject> objects, int retries) {
    Preconditions.checkNotNull(objects, "Objects");
    if (objects.isEmpty())
        throw new IllegalArgumentException("Objects must not be empty");
    final List<UpsertResult> results;

    try {//from ww  w .j  ava2 s  .  c o  m
        results = get().upsert(externalIdentifier, 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 upsert(objects, retries + 1);
        } else {
            throw new SalesforceException(e);
        }
    }

    if (Iterables.all(results, Salesforce.UPSERT_SUCCESS)) {
        final String name = objects.get(0).getClass().getSimpleName();
        final int created = Iterables.size(Iterables.filter(results, Salesforce.CREATED_VIA_UPSERT));
        LOG.info("Successfully updated {} and created {} {}(s)",
                new Object[] { results.size() - created, created, name });
        return results;
    } else {
        final Iterable<UpsertResult> failures = Iterables.filter(results, Salesforce.UPSERT_FAILURE);
        final List<Error> errors = Lists.newArrayList();
        for (UpsertResult failure : failures) {
            errors.addAll(failure.getErrors());
        }
        throw new SalesforceException(errors);
    }
}

From source file:io.selendroid.server.model.DeviceStore.java

private Predicate<AndroidDevice> deviceSatisfiesCapabilities(final SelendroidCapabilities capabilities) {
    return new Predicate<AndroidDevice>() {
        @Override//  w w  w .  j  a v a  2s  .c  om
        public boolean apply(AndroidDevice candidate) {
            ArrayList<Boolean> booleanExpressions = Lists.newArrayList(
                    candidate.screenSizeMatches(capabilities.getScreenSize()),
                    capabilities.getEmulator() == null ? true
                            : capabilities.getEmulator() ? candidate instanceof DefaultAndroidEmulator
                                    : candidate instanceof DefaultHardwareDevice,
                    StringUtils.isNotBlank(capabilities.getSerial())
                            ? capabilities.getSerial().equals(candidate.getSerial())
                            : true);

            return Iterables.all(booleanExpressions, Predicates.equalTo(true));
        }
    };
}

From source file:org.jboss.aerogear.controller.router.decorators.cors.Cors.java

/**
 * Checks that the preflight request headers ({@link RequestHeader#HEADERS}) are supported.
 * //from  w w  w . j  ava  2 s .  com
 * @param validHeaders a set of headers that are allowed.
 * @return {@code true} if the current request headers are supported.
 */
public boolean areRequestHeadersValid(final List<String> validHeaders) {
    final String requestHeaders = request.getHeader(RequestHeader.HEADERS.headerName);
    if (requestHeaders == null) {
        return true;
    }

    final Collection<String> lowerCaseValidHeaders = StringUtils.toLowerCase(validHeaders);
    final Iterable<String> headers = Splitter.on(',').trimResults().split(requestHeaders);
    boolean valid = Iterables.all(headers, new Predicate<String>() {
        @Override
        public boolean apply(final String header) {
            return lowerCaseValidHeaders.contains(header.toLowerCase());
        }
    });
    return valid;
}

From source file:org.eclipse.emf.compare.ide.ui.internal.structuremergeviewer.EMFCompareStructureMergeViewerContentProvider.java

/**
 * {@inheritDoc}/*  w  w w  .  ja  v  a  2 s.  c o m*/
 * 
 * @see org.eclipse.emf.edit.ui.provider.AdapterFactoryContentProvider#getChildren(java.lang.Object)
 */
@Override
public final Object[] getChildren(Object element) {
    Object[] children;
    if (element instanceof CompareInputAdapter) {
        children = getCompareInputAdapterChildren((CompareInputAdapter) element);
    } else if (element instanceof ICompareInput) {
        children = new Object[] {};
    } else {
        children = super.getChildren(element);
    }

    final Object[] compareInputChildren;
    // Avoid NPE.
    if (children == null) {
        children = new Object[] {};
    }
    // Do not adapt if it's a pending updater
    if (!Iterables.all(Arrays.asList(children), Predicates.instanceOf(PendingUpdateAdapter.class))) {
        Iterable<?> compareInputs = adapt(children, getAdapterFactory(), ICompareInput.class);
        compareInputChildren = toArray(compareInputs, Object.class);
    } else {
        compareInputChildren = children;
    }
    return compareInputChildren;
}

From source file:io.selendroid.standalone.server.model.DeviceStore.java

private Predicate<AndroidDevice> deviceSatisfiesCapabilities(final SelendroidCapabilities capabilities) {
    return new Predicate<AndroidDevice>() {
        @Override//from  www. j  a v a2  s .  c  o m
        public boolean apply(AndroidDevice candidate) {
            ArrayList<Boolean> booleanExpressions = Lists.newArrayList(
                    candidate.screenSizeMatches(capabilities.getScreenSize()),
                    capabilities.getEmulator() == null ? true
                            : capabilities.getEmulator() ? candidate instanceof DefaultAndroidEmulator
                                    : candidate instanceof DefaultHardwareDevice,
                    StringUtils.isNotBlank(capabilities.getSerial())
                            ? capabilities.getSerial().equals(candidate.getSerial())
                            : true,
                    StringUtils.isNotBlank(capabilities.getModel())
                            ? candidate.getModel().contains(capabilities.getModel())
                            : true,
                    StringUtils.isNotBlank(capabilities.getAPITargetType())
                            ? candidate.getAPITargetType() != null
                                    && candidate.getAPITargetType().contains(capabilities.getAPITargetType())
                            : true);

            return Iterables.all(booleanExpressions, Predicates.equalTo(true));
        }
    };
}

From source file:org.eclipse.sirius.diagram.ui.business.internal.query.RequestQuery.java

/**
 * Check if:/*from   w w w.j  av  a2s .  c  o m*/
 * <UL>
 * <LI>all mappings of the creation tool of this request correspond to
 * BorderNode mapping,</LI>
 * <LI>or if all edit parts of the drop request is BorderNode edit part.
 * Warning the result is only available in case of drag'n'drop from diagram,
 * not from other view because in this case, the edit part is not
 * "real edit part" but a @link
 * {@link org.eclipse.sirius.diagram.ui.tools.internal.dnd.DragAndDropWrapper}
 * . The only solution in this case to know if it is a drop a element that
 * became bordered nodes is to call
 * {@link org.eclipse.sirius.diagram.ui.graphical.edit.internal.policies.validators.DragAndDropValidator#isConcerningOnlyBorderNodeFromView()}
 * .</LI>
 * </UL>
 * 
 * @return true in case of request concerning bordered nodes, false
 *         otherwise.
 */
public boolean isDropOrCreationOfBorderNode() {
    boolean isConcerningBorderNode = false;
    if (request instanceof CreateRequest) {
        CreateRequest createRequest = (CreateRequest) request;
        if (createRequest.getNewObject() instanceof NodeCreationDescriptionImpl) {
            isConcerningBorderNode = true;
            NodeCreationDescriptionImpl nodeCreationDescriptionImpl = (NodeCreationDescriptionImpl) createRequest
                    .getNewObject();
            for (NodeMapping nodeMapping : nodeCreationDescriptionImpl.getNodeMappings()) {
                if (!DescriptionPackage.eINSTANCE.getAbstractNodeMapping_BorderedNodeMappings()
                        .equals(nodeMapping.eContainingFeature())) {
                    isConcerningBorderNode = false;
                }
            }
        }
    } else if (RequestConstants.REQ_DROP.equals(request.getType())) {
        isConcerningBorderNode = !getEditParts().isEmpty()
                && Iterables.all(getEditParts(), Predicates.instanceOf(IBorderItemEditPart.class));
    }
    return isConcerningBorderNode;
}

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

private List<DeleteResult> delete(String[] identifiers, int retries) {
    Preconditions.checkNotNull(identifiers, "Identifiers");
    Preconditions.checkArgument(identifiers.length > 0, "Identifiers must not be empty");

    final List<DeleteResult> results;

    try {//  w  w w.  j  a v a2  s . co m
        results = get().delete(Arrays.asList(identifiers));
    } catch (UnexpectedErrorFault e) {
        if (retries < maxRetries) {
            reconnect();
            return delete(identifiers, retries + 1);
        } else {
            throw new SalesforceException(e);
        }
    }

    if (Iterables.all(results, Salesforce.DELETE_SUCCESS)) {
        LOG.info("Successfully deleted {} objects", results.size());
        return results;
    } else {
        final Iterable<DeleteResult> failures = Iterables.filter(results, Salesforce.DELETE_FAILURE);
        final List<Error> errors = Lists.newArrayList();
        for (DeleteResult failure : failures) {
            errors.addAll(failure.getErrors());
        }
        throw new SalesforceException(errors);
    }
}

From source file:com.eucalyptus.images.ImageInfo.java

/**
 * Add launch permissions.// w  w  w.ja  v a 2  s  . c  o  m
 * 
 * @param accountIds
 */
public void addPermissions(final List<String> accountIds) {
    final EntityTransaction db = Entities.get(ImageInfo.class);
    try {
        final ImageInfo entity = Entities.merge(this);
        Iterables.all(accountIds, new Predicate<String>() {

            @Override
            public boolean apply(final String input) {
                try {
                    final Account account = Accounts.lookupAccountById(input);
                    ImageInfo.this.getPermissions().add(input);
                } catch (final Exception e) {
                    try {
                        final User user = Accounts.lookupUserById(input);
                        ImageInfo.this.getPermissions().add(user.getAccount().getAccountNumber());
                    } catch (AuthException ex) {
                        try {
                            final User user = Accounts.lookupUserByAccessKeyId(input);
                            ImageInfo.this.getPermissions().add(user.getAccount().getAccountNumber());
                        } catch (AuthException ex1) {
                            LOG.error(ex1, ex1);
                        }
                    }
                }
                return true;
            }
        });
        db.commit();
    } catch (final Exception ex) {
        Logs.exhaust().error(ex, ex);
        db.rollback();
    }
}

From source file:com.eucalyptus.cloudwatch.domain.alarms.AlarmManager.java

private static boolean modifySelectedAlarms(final String accountId, final Collection<String> alarmNames,
        final Predicate<CloudWatchMetadata.AlarmMetadata> filter, final Predicate<AlarmEntity> update) {
    final Map<String, Collection<String>> accountToNamesMap = buildAccountIdToAlarmNamesMap(accountId,
            alarmNames);//w  w w  .  j ava2  s.  co m
    final EntityTransaction db = Entities.get(AlarmEntity.class);
    try {
        final Criteria criteria = Entities.createCriteria(AlarmEntity.class);
        final Junction disjunction = Restrictions.disjunction();
        for (final Map.Entry<String, Collection<String>> entry : accountToNamesMap.entrySet()) {
            final Junction conjunction = Restrictions.conjunction();
            conjunction.add(Restrictions.eq("accountId", entry.getKey()));
            conjunction.add(Restrictions.in("alarmName", entry.getValue()));
            disjunction.add(conjunction);
        }
        criteria.add(disjunction);
        criteria.addOrder(Order.asc("creationTimestamp"));
        criteria.addOrder(Order.asc("naturalId"));
        final Collection<AlarmEntity> alarmEntities = (Collection<AlarmEntity>) criteria.list();
        if (!Iterables.all(alarmEntities, filter)) {
            return false;
        }
        CollectionUtils.each(alarmEntities, update);
        db.commit();
        return true;
    } catch (RuntimeException ex) {
        Logs.extreme().error(ex, ex);
        throw ex;
    } finally {
        if (db.isActive())
            db.rollback();
    }
}

From source file:com.datastax.driver.core.TableMetadata.java

private String asCQLQuery(boolean formatted) {
    StringBuilder sb = new StringBuilder();

    sb.append("CREATE TABLE ").append(Metadata.escapeId(keyspace.getName())).append('.')
            .append(Metadata.escapeId(name)).append(" (");
    newLine(sb, formatted);//from  w  ww .  ja va  2s  . c  o m
    for (ColumnMetadata cm : columns.values())
        newLine(sb.append(spaces(4, formatted)).append(cm).append(','), formatted);

    // PK
    sb.append(spaces(4, formatted)).append("PRIMARY KEY (");
    if (partitionKey.size() == 1) {
        sb.append(partitionKey.get(0).getName());
    } else {
        sb.append('(');
        boolean first = true;
        for (ColumnMetadata cm : partitionKey) {
            if (first)
                first = false;
            else
                sb.append(", ");
            sb.append(Metadata.escapeId(cm.getName()));
        }
        sb.append(')');
    }
    for (ColumnMetadata cm : clusteringColumns)
        sb.append(", ").append(Metadata.escapeId(cm.getName()));
    sb.append(')');
    newLine(sb, formatted);
    // end PK

    // Options
    sb.append(") WITH ");

    if (options.isCompactStorage)
        and(sb.append("COMPACT STORAGE"), formatted);
    if (!Iterables.all(clusteringOrder, Order.isAscending))
        and(appendClusteringOrder(sb), formatted);
    sb.append("read_repair_chance = ").append(options.readRepair);
    and(sb, formatted).append("dclocal_read_repair_chance = ").append(options.localReadRepair);
    if (cassandraVersion.getMajor() < 2
            || (cassandraVersion.getMajor() == 2 && cassandraVersion.getMinor() == 0))
        and(sb, formatted).append("replicate_on_write = ").append(options.replicateOnWrite);
    and(sb, formatted).append("gc_grace_seconds = ").append(options.gcGrace);
    and(sb, formatted).append("bloom_filter_fp_chance = ").append(options.bfFpChance);
    if (cassandraVersion.getMajor() < 2 || cassandraVersion.getMajor() == 2 && cassandraVersion.getMinor() < 1)
        and(sb, formatted).append("caching = '").append(options.caching.get("keys")).append('\'');
    else
        and(sb, formatted).append("caching = ").append(formatOptionMap(options.caching));
    if (options.comment != null)
        and(sb, formatted).append("comment = '").append(options.comment).append('\'');
    and(sb, formatted).append("compaction = ").append(formatOptionMap(options.compaction));
    and(sb, formatted).append("compression = ").append(formatOptionMap(options.compression));
    if (cassandraVersion.getMajor() >= 2) {
        and(sb, formatted).append("default_time_to_live = ").append(options.defaultTTL);
        and(sb, formatted).append("speculative_retry = '").append(options.speculativeRetry).append('\'');
        if (options.indexInterval != null)
            and(sb, formatted).append("index_interval = ").append(options.indexInterval);
    }
    if (cassandraVersion.getMajor() > 2
            || (cassandraVersion.getMajor() == 2 && cassandraVersion.getMinor() >= 1)) {
        and(sb, formatted).append("min_index_interval = ").append(options.minIndexInterval);
        and(sb, formatted).append("max_index_interval = ").append(options.maxIndexInterval);
    }
    sb.append(';');
    return sb.toString();
}