List of usage examples for com.google.common.collect Iterables any
public static <T> boolean any(Iterable<T> iterable, Predicate<? super T> predicate)
From source file:com.eucalyptus.ws.server.QueryPipeline.java
@Override public boolean checkAccepts(final HttpRequest message) { if (message instanceof MappingHttpRequest) { MappingHttpRequest httpRequest = (MappingHttpRequest) message; if (httpRequest.getMethod().equals(HttpMethod.POST)) { Map<String, String> parameters = new HashMap<String, String>(httpRequest.getParameters()); Set<String> nonQueryParameters = Sets.newHashSet(); ChannelBuffer buffer = httpRequest.getContent(); buffer.markReaderIndex();/*w w w . j a v a 2 s . c o m*/ byte[] read = new byte[buffer.readableBytes()]; buffer.readBytes(read); String query = new String(read); buffer.resetReaderIndex(); for (String p : query.split("&")) { String[] splitParam = p.split("="); String lhs = splitParam[0]; String rhs = splitParam.length == 2 ? splitParam[1] : null; try { if (lhs != null) lhs = new URLCodec().decode(lhs); } catch (DecoderException e) { } try { if (rhs != null) rhs = new URLCodec().decode(rhs); } catch (DecoderException e) { } parameters.put(lhs, rhs); nonQueryParameters.add(lhs); } for (RequiredQueryParams p : requiredQueryParams) { if (!parameters.containsKey(p.toString())) { return false; } } httpRequest.getParameters().putAll(parameters); httpRequest.addNonQueryParameterKeys(nonQueryParameters); } else { for (RequiredQueryParams p : requiredQueryParams) { if (!httpRequest.getParameters().containsKey(p.toString())) { return false; } } } final boolean usesServicePath = Iterables.any(servicePathPrefixes, Strings.isPrefixOf(message.getUri())); final boolean noPath = message.getUri().isEmpty() || message.getUri().equals("/") || message.getUri().startsWith("/?"); return usesServicePath || (noPath && resolvesByHost(message.getHeader(HttpHeaders.Names.HOST))); } return false; }
From source file:org.eclipse.viatra.query.patternlanguage.emf.internal.DuplicationChecker.java
private Set<IEObjectDescription> processDuplicateCandidates(Pattern pattern, boolean calculateVisibility, final Iterable<IEObjectDescription> shadowingPatternDescriptions) { Set<IEObjectDescription> duplicates = Sets.newHashSet(); for (IEObjectDescription shadowingPatternDescription : shadowingPatternDescriptions) { EObject shadowingPattern = shadowingPatternDescription.getEObjectOrProxy(); if (!Objects.equals(shadowingPattern, pattern)) { URI resourceUri = pattern.eResource().getURI(); // not using shadowingPattern because it might be proxy URI otherResourceUri = shadowingPatternDescription.getEObjectURI().trimFragment(); if (!Objects.equals(resourceUri, otherResourceUri) && projectHelper.isStandaloneFileURI(shadowingPattern, otherResourceUri)) { // If shadowing pattern is not in another source file in a source folder, it does not matter continue; }//from w ww . j a v a 2s . com if (calculateVisibility) { IResourceDescription resourceDescription = resourceDescriptions .getResourceDescription(resourceUri); IResourceDescription otherResourceDescription = resourceDescriptions .getResourceDescription(otherResourceUri); List<IContainer> visible = containerManager.getVisibleContainers(resourceDescription, resourceDescriptions); List<IContainer> visibleFromOther = containerManager .getVisibleContainers(otherResourceDescription, resourceDescriptions); if (Iterables.any(visible, contains(otherResourceDescription)) || Iterables.any(visibleFromOther, contains(resourceDescription))) { duplicates.add(shadowingPatternDescription); } } else { duplicates.add(shadowingPatternDescription); } } } return duplicates; }
From source file:com.google.devtools.kythe.platform.java.JavaCompilationDetails.java
public boolean hasCompileErrors() { return Iterables.any(diagnostics.getDiagnostics(), ERROR_DIAGNOSTIC); }
From source file:com.eucalyptus.blockstorage.async.VolumeDeleter.java
@Override public void run() { try {/*from w w w . jav a 2 s. c o m*/ // Look for volumes marked for deletion and delete them VolumeInfo searchVolume = new VolumeInfo(); searchVolume.setStatus(StorageProperties.Status.deleting.toString()); List<VolumeInfo> volumesToBeDeleted = null; try { volumesToBeDeleted = Transactions.findAll(searchVolume); } catch (Exception e) { LOG.error("Failed to lookup volumes marked for deletion", e); return; } if (volumesToBeDeleted != null && !volumesToBeDeleted.isEmpty()) { for (VolumeInfo vol : volumesToBeDeleted) { // Do separate transaction for each volume so we don't // keep the transaction open for a long time try (TransactionResource tran = Entities.transactionFor(VolumeInfo.class)) { vol = Entities.uniqueResult(vol); final String volumeId = vol.getVolumeId(); LOG.info("Volume: " + volumeId + " marked for deletion. Checking export status"); if (Iterables.any(vol.getAttachmentTokens(), new Predicate<VolumeToken>() { @Override public boolean apply(VolumeToken token) { // Return true if attachment is valid or export exists. try { return token.hasActiveExports(); } catch (EucalyptusCloudException e) { LOG.warn("Failure checking for active exports for volume " + volumeId); return false; } } })) { // Exports exists... try un exporting the volume before deleting. LOG.info("Volume: " + volumeId + " found to be exported. Detaching volume from all hosts"); try { Entities.asTransaction(VolumeInfo.class, invalidateAndDetachAll(blockManager)) .apply(volumeId); } catch (Exception e) { LOG.error("Failed to fully detach volume " + volumeId, e); } } LOG.info("Volume: " + volumeId + " was marked for deletion. Cleaning up..."); try { blockManager.deleteVolume(volumeId); } catch (EucalyptusCloudException e) { LOG.debug("Failed to delete " + volumeId, e); LOG.warn("Unable to delete " + volumeId + ". Will retry later"); continue; } vol.setStatus(StorageProperties.Status.deleted.toString()); vol.setDeletionTime(new Date()); EucaSemaphoreDirectory.removeSemaphore(volumeId); // who put it there ? tran.commit(); } catch (Exception e) { LOG.error("Error deleting volume " + vol.getVolumeId() + ": " + e.getMessage()); LOG.debug("Exception during deleting volume " + vol.getVolumeId() + ".", e); } } } else { LOG.trace("No volumes marked for deletion"); } } catch (Exception e) { // could catch InterruptedException LOG.warn("Unable to remove volumes marked for deletion", e); return; } }
From source file:com.eucalyptus.auth.euare.persist.DatabasePrincipalProvider.java
@Override public UserPrincipal lookupPrincipalByAccessKeyId(final String keyId, final String nonce) throws AuthException { try (final TransactionResource tx = Entities.readOnlyDistinctTransactionFor(AccessKeyEntity.class)) { final UserEntity user; try {/*from ww w .j av a 2 s .c o m*/ user = (UserEntity) Entities.createCriteria(UserEntity.class).createCriteria("keys") .add(Restrictions.eq("accessKey", keyId)).setFlushMode(FlushMode.MANUAL).setReadOnly(true) .uniqueResult(); } catch (Exception e) { throw new InvalidAccessKeyAuthException("Failed to find access key", e); } if (user == null) { throw new InvalidAccessKeyAuthException("Failed to find access key"); } final UserPrincipal principal = new UserPrincipalImpl(user); final Optional<AccessKey> accessKey = Iterables.tryFind(principal.getKeys(), CollectionUtils.propertyPredicate(keyId, AccessKeys.accessKeyIdentifier())); if (!Iterables.any(accessKey.asSet(), AccessKeys.isActive())) { throw new InvalidAccessKeyAuthException("Invalid access key or token"); } return decorateCredentials(principal, nonce, accessKey.get().getSecretKey()); } }
From source file:com.eucalyptus.cloudformation.resources.standard.TagHelper.java
public static void checkReservedCloudFormationResourceTemplateTags(List<CloudFormationResourceTag> tags) throws ValidationErrorException { if (tags == null) return;/*from w w w . ja va2 s. c om*/ List<String> tagNames = Lists.newArrayList(); for (CloudFormationResourceTag tag : tags) { if (Iterables.any(reservedPrefixes, Strings.isPrefixOf(tag.getKey()))) { throw new ValidationErrorException( "Tag " + tag.getKey() + " uses a reserved prefix " + reservedPrefixes); } } }
From source file:io.druid.query.groupby.strategy.GroupByStrategyV1.java
@Override public Sequence<Row> processSubqueryResult(GroupByQuery subquery, GroupByQuery query, Sequence<Row> subqueryResult) { final Set<AggregatorFactory> aggs = Sets.newHashSet(); // Nested group-bys work by first running the inner query and then materializing the results in an incremental // index which the outer query is then run against. To build the incremental index, we use the fieldNames from // the aggregators for the outer query to define the column names so that the index will match the query. If // there are multiple types of aggregators in the outer query referencing the same fieldName, we will try to build // multiple columns of the same name using different aggregator types and will fail. Here, we permit multiple // aggregators of the same type referencing the same fieldName (and skip creating identical columns for the // subsequent ones) and return an error if the aggregator types are different. for (AggregatorFactory aggregatorFactory : query.getAggregatorSpecs()) { for (final AggregatorFactory transferAgg : aggregatorFactory.getRequiredColumns()) { if (Iterables.any(aggs, new Predicate<AggregatorFactory>() { @Override/*www. j a v a2 s .com*/ public boolean apply(AggregatorFactory agg) { return agg.getName().equals(transferAgg.getName()) && !agg.equals(transferAgg); } })) { throw new IAE( "Inner aggregator can currently only be referenced by a single type of outer aggregator" + " for '%s'", transferAgg.getName()); } aggs.add(transferAgg); } } // We need the inner incremental index to have all the columns required by the outer query final GroupByQuery innerQuery = new GroupByQuery.Builder(subquery) .setAggregatorSpecs(Lists.newArrayList(aggs)).setInterval(subquery.getIntervals()) .setPostAggregatorSpecs(Lists.<PostAggregator>newArrayList()).build(); final GroupByQuery outerQuery = new GroupByQuery.Builder(query) .setLimitSpec(query.getLimitSpec().merge(subquery.getLimitSpec())).build(); final IncrementalIndex innerQueryResultIndex = makeIncrementalIndex( innerQuery.withOverriddenContext( ImmutableMap.<String, Object>of(GroupByQueryHelper.CTX_KEY_SORT_RESULTS, true)), subqueryResult); //Outer query might have multiple intervals, but they are expected to be non-overlapping and sorted which //is ensured by QuerySegmentSpec. //GroupByQueryEngine can only process one interval at a time, so we need to call it once per interval //and concatenate the results. final IncrementalIndex outerQueryResultIndex = makeIncrementalIndex(outerQuery, Sequences.concat( Sequences.map(Sequences.simple(outerQuery.getIntervals()), new Function<Interval, Sequence<Row>>() { @Override public Sequence<Row> apply(Interval interval) { return process( outerQuery.withQuerySegmentSpec( new MultipleIntervalSegmentSpec(ImmutableList.of(interval))), new IncrementalIndexStorageAdapter(innerQueryResultIndex)); } }))); innerQueryResultIndex.close(); return new ResourceClosingSequence<>( outerQuery.applyLimit(GroupByQueryHelper.postAggregate(query, outerQueryResultIndex)), outerQueryResultIndex); }
From source file:org.openhab.model.rule.scoping.RulesScopeProvider.java
private boolean containsItemTrigger(Rule rule) { return Iterables.any(rule.getEventtrigger(), Predicates.instanceOf(ItemEventTrigger.class)); }
From source file:org.sleuthkit.autopsy.imagegallery.datamodel.grouping.DrawableGroup.java
@Subscribe public synchronized void handleCatChange(CategoryManager.CategoryChangeEvent event) { if (Iterables.any(event.getFileIDs(), fileIDs::contains)) { uncatCount.set(-1);//from w w w.j a v a 2 s . co m } }
From source file:org.eclipse.xtext.ui.editor.outline.impl.OutlineRefreshJob.java
protected boolean containsUsingComparer(Iterable<IOutlineNode> list, final IOutlineNode node) { return Iterables.any(list, new Predicate<IOutlineNode>() { @Override/*from ww w. j a v a2 s. c om*/ public boolean apply(IOutlineNode nodeFromList) { return nodeComparer.equals(node, nodeFromList); } }); }