List of usage examples for com.google.common.collect Iterables all
public static <T> boolean all(Iterable<T> iterable, Predicate<? super T> predicate)
From source file:org.opensaml.saml.common.profile.logic.EntityAttributesPredicate.java
/** {@inheritDoc} */ @Override/*from w ww .j a v a 2 s .c om*/ public boolean apply(@Nullable final EntityDescriptor input) { if (input == null) { return false; } Collection<Attribute> entityAttributes = null; // Check for a tag match in the EntityAttributes extension of the entity and its parent(s). Extensions exts = input.getExtensions(); if (exts != null) { final List<XMLObject> children = exts.getUnknownXMLObjects(EntityAttributes.DEFAULT_ELEMENT_NAME); if (!children.isEmpty() && children.get(0) instanceof EntityAttributes) { if (entityAttributes == null) { entityAttributes = new ArrayList<>(); } entityAttributes.addAll(((EntityAttributes) children.get(0)).getAttributes()); } } EntitiesDescriptor group = (EntitiesDescriptor) input.getParent(); while (group != null) { exts = group.getExtensions(); if (exts != null) { final List<XMLObject> children = exts.getUnknownXMLObjects(EntityAttributes.DEFAULT_ELEMENT_NAME); if (!children.isEmpty() && children.get(0) instanceof EntityAttributes) { if (entityAttributes == null) { entityAttributes = new ArrayList<>(); } entityAttributes.addAll(((EntityAttributes) children.get(0)).getAttributes()); } } group = (EntitiesDescriptor) group.getParent(); } if (entityAttributes == null || entityAttributes.isEmpty()) { log.debug("no EntityAttributes extension found for {}", input.getEntityID()); return false; } // If we find a matching tag, we win. Each tag is treated in OR fashion. final EntityAttributesMatcher matcher = new EntityAttributesMatcher(entityAttributes); if (matchAll) { return Iterables.all(candidateSet, matcher); } else { if (Iterables.tryFind(candidateSet, matcher).isPresent()) { return true; } } return false; }
From source file:org.eclipse.sirius.diagram.ui.tools.internal.actions.delete.DeleteFromDiagramAction.java
/** * Check if the action should be enabled for this edit parts : * <UL>//from w w w . j ava2 s. c o m * <LI>First check that all edit parts has his edit mode enabled</LI> * <LI>And then do some checks on target of edit parts.</LI> * </UL> * * @param selectedParts * the selected objects * @return true if the action should be enabled, false otherwise. */ public static boolean shouldBeEnabledForEditParts(Iterable<? extends IGraphicalEditPart> selectedParts) { Predicate<IGraphicalEditPart> isEditModeEnabledPredicate = new Predicate<IGraphicalEditPart>() { public boolean apply(IGraphicalEditPart input) { return input.isEditModeEnabled(); } }; if (Iterables.all(selectedParts, isEditModeEnabledPredicate) && !Iterables.all(selectedParts, Predicates.instanceOf(IDiagramNameEditPart.class))) { return shouldBeEnabled(getSelectedEObject(selectedParts)); } return false; }
From source file:com.datastax.driver.core.AbstractTableMetadata.java
protected StringBuilder appendOptions(StringBuilder sb, boolean formatted) { // Options/*ww w . jav a 2 s . c o m*/ sb.append(" WITH "); if (options.isCompactStorage()) and(sb.append("COMPACT STORAGE"), formatted); if (!Iterables.all(clusteringOrder, isAscending)) and(appendClusteringOrder(sb), formatted); sb.append("read_repair_chance = ").append(options.getReadRepairChance()); and(sb, formatted).append("dclocal_read_repair_chance = ").append(options.getLocalReadRepairChance()); if (cassandraVersion.getMajor() < 2 || (cassandraVersion.getMajor() == 2 && cassandraVersion.getMinor() == 0)) and(sb, formatted).append("replicate_on_write = ").append(options.getReplicateOnWrite()); and(sb, formatted).append("gc_grace_seconds = ").append(options.getGcGraceInSeconds()); and(sb, formatted).append("bloom_filter_fp_chance = ").append(options.getBloomFilterFalsePositiveChance()); if (cassandraVersion.getMajor() < 2 || cassandraVersion.getMajor() == 2 && cassandraVersion.getMinor() < 1) and(sb, formatted).append("caching = '").append(options.getCaching().get("keys")).append('\''); else and(sb, formatted).append("caching = ").append(formatOptionMap(options.getCaching())); if (options.getComment() != null) and(sb, formatted).append("comment = '").append(options.getComment().replace("'", "''")).append('\''); and(sb, formatted).append("compaction = ").append(formatOptionMap(options.getCompaction())); and(sb, formatted).append("compression = ").append(formatOptionMap(options.getCompression())); if (cassandraVersion.getMajor() >= 2) { and(sb, formatted).append("default_time_to_live = ").append(options.getDefaultTimeToLive()); and(sb, formatted).append("speculative_retry = '").append(options.getSpeculativeRetry()).append('\''); if (options.getIndexInterval() != null) and(sb, formatted).append("index_interval = ").append(options.getIndexInterval()); } if (cassandraVersion.getMajor() > 2 || (cassandraVersion.getMajor() == 2 && cassandraVersion.getMinor() >= 1)) { and(sb, formatted).append("min_index_interval = ").append(options.getMinIndexInterval()); and(sb, formatted).append("max_index_interval = ").append(options.getMaxIndexInterval()); } if (cassandraVersion.getMajor() > 2) { and(sb, formatted).append("crc_check_chance = ").append(options.getCrcCheckChance()); } sb.append(';'); return sb; }
From source file:de.cau.cs.kieler.klay.layered.p5edges.PolylineEdgeRouter.java
/** * {@inheritDoc}//from w w w.j av a2 s .co m */ public void process(final LGraph layeredGraph, final IKielerProgressMonitor monitor) { monitor.begin("Polyline edge routing", 1); float nodeSpacing = layeredGraph.getProperty(InternalProperties.SPACING); float edgeSpaceFac = layeredGraph.getProperty(Properties.EDGE_SPACING_FACTOR); double xpos = 0.0; double layerSpacing = 0.0; // Determine the spacing required for west-side in-layer edges of the first layer if (!layeredGraph.getLayers().isEmpty()) { double firstDiff = determineNextInLayerDiff(layeredGraph.getLayers().get(0)); xpos = LAYER_SPACE_FAC * edgeSpaceFac * firstDiff; } // Iterate over the layers ListIterator<Layer> layerIter = layeredGraph.getLayers().listIterator(); while (layerIter.hasNext()) { Layer layer = layerIter.next(); boolean externalLayer = Iterables.all(layer, PRED_EXTERNAL_WEST_OR_EAST_PORT); // The rightmost layer is not given any node spacing if (externalLayer && xpos > 0) { xpos -= nodeSpacing; } // Set horizontal coordinates for all nodes of the layer LGraphUtil.placeNodes(layer, xpos); double maxVertDiff = 0.0; // Iterate over the layer's nodes for (LNode node : layer) { // Calculate the maximal vertical span of output edges. In-layer edges are already // routed at this point by inserting bend points appropriately double maxOutputYDiff = 0.0; for (LEdge outgoingEdge : node.getOutgoingEdges()) { double sourcePos = outgoingEdge.getSource().getAbsoluteAnchor().y; double targetPos = outgoingEdge.getTarget().getAbsoluteAnchor().y; if (layer == outgoingEdge.getTarget().getNode().getLayer()) { // We have an in-layer edge -- route it! routeInLayerEdge(outgoingEdge, xpos, layer.getSize().x, LAYER_SPACE_FAC * edgeSpaceFac * Math.abs(sourcePos - targetPos)); if (outgoingEdge.getSource().getSide() == PortSide.WEST) { // West-side in-layer edges have been considered in the previous iteration sourcePos = 0; targetPos = 0; } } maxOutputYDiff = KielerMath.maxd(maxOutputYDiff, targetPos - sourcePos, sourcePos - targetPos); } // Different node types have to be handled differently NodeType nodeType = node.getNodeType(); // FIXME use switch-case here? if (nodeType == NodeType.NORMAL) { processNormalNode(node, xpos, layer.getSize().x); } else if (nodeType == NodeType.LONG_EDGE) { processLongEdgeDummyNode(node, nodeSpacing, edgeSpaceFac, xpos, maxOutputYDiff); } else if (nodeType == NodeType.LABEL) { processLabelDummyNode(node, xpos, layer.getSize().x); } maxVertDiff = Math.max(maxVertDiff, maxOutputYDiff); } // Consider west-side in-layer edges of the next layer if (layerIter.hasNext()) { double nextDiff = determineNextInLayerDiff(layerIter.next()); maxVertDiff = Math.max(maxVertDiff, nextDiff); layerIter.previous(); } // Determine placement of next layer based on the maximal vertical difference (as the // maximum vertical difference edges span grows, the layer grows wider to allow enough // space for such sloped edges to avoid too harsh angles) layerSpacing = LAYER_SPACE_FAC * edgeSpaceFac * maxVertDiff; if (!externalLayer && layerIter.hasNext()) { layerSpacing += nodeSpacing; } xpos += layer.getSize().x + layerSpacing; } // Set the graph's horizontal size layeredGraph.getSize().x = xpos; monitor.done(); }
From source file:org.geoserver.importer.ImportContext.java
/** * We are going to scan all the Import Context Tasks and return "true" if all of them do not have * a configured Layer on the Catalog.//from www .j ava 2s . com * * That means that the user has removed the Layers from the Catalog and therefore we are safe to * wipe out the uploaded data. * * @return boolean */ public boolean isEmpty() { boolean noLayersAvailable = Iterables.all(getTasks(), new Predicate<ImportTask>() { @Override public boolean apply(ImportTask input) { final StoreInfo store = input != null ? input.getStore() : null; final Catalog catalog = store != null ? store.getCatalog() : null; final LayerInfo layer = catalog != null ? catalog.getLayer(input.getLayer().getId()) : null; return (layer == null); } }); return noLayersAvailable; }
From source file:kr.debop4j.core.parallelism.AsyncTool.java
/** * {@link java.util.concurrent.Future}? {@link java.util.concurrent.Future#isDone()} * ? {@link java.util.concurrent.Future#isCancelled()} ? . * * @param futures futures/*from w ww.ja v a2 s . c o m*/ * @param <T> * @throws InterruptedException */ public static <T> void waitAll(final Iterable<? extends Future<T>> futures) throws InterruptedException { boolean allCompleted = false; while (!allCompleted) { allCompleted = Iterables.all(futures, new Predicate<Future<?>>() { @Override public boolean apply(Future<?> input) { assert input != null; return input.isDone() || input.isCancelled(); } }); if (!allCompleted) Thread.sleep(1); } }
From source file:org.apache.cassandra.db.lifecycle.Tracker.java
/** * removes all sstables that are not busy compacting. *///w ww . j a va 2 s .com public Throwable dropSSTables(final Predicate<SSTableReader> remove, OperationType operationType, Throwable accumulate) { Pair<View, View> result = apply(new Function<View, View>() { public View apply(View view) { Set<SSTableReader> toremove = copyOf(filter(view.sstables, and(remove, notIn(view.compacting)))); return updateLiveSet(toremove, emptySet()).apply(view); } }); Set<SSTableReader> removed = Sets.difference(result.left.sstables, result.right.sstables); assert Iterables.all(removed, remove); if (!removed.isEmpty()) { // notifySSTablesChanged -> LeveledManifest.promote doesn't like a no-op "promotion" accumulate = notifySSTablesChanged(removed, Collections.<SSTableReader>emptySet(), operationType, accumulate); accumulate = updateSizeTracking(removed, emptySet(), accumulate); accumulate = markObsolete(this, removed, accumulate); accumulate = release(selfRefs(removed), accumulate); } return accumulate; }
From source file:org.grouplens.lenskit.eval.script.ConfigMethodInvoker.java
/** * Find a method that should be invoked multiple times, if the argument is iterable. The * argument may be iterated multiple times. * * @param self The configurable object.//from ww w .j ava2 s . c om * @param name The method name. * @param args The arguments. * @return A thunk that will invoke the method. */ private Supplier<Object> findMultiMethod(final Object self, String name, final Object[] args) { if (args.length != 1) return null; // the argument is a list final Object arg = args[0]; if (!(arg instanceof Iterable)) { return null; } final Iterable<?> objects = (Iterable<?>) arg; Supplier<Object> result = null; for (final Method method : getOneArgMethods(self, name)) { Class ptype = method.getParameterTypes()[0]; boolean good = Iterables.all(objects, Predicates.or(Predicates.isNull(), Predicates.instanceOf(ptype))); if (good) { if (result != null) { throw new RuntimeException("multiple compatible methods named " + name); } else { result = new Supplier<Object>() { @Override public Object get() { for (Object obj : objects) { try { method.invoke(self, obj); } catch (IllegalAccessException e) { throw Throwables.propagate(e); } catch (InvocationTargetException e) { if (e.getCause() != null) { throw Throwables.propagate(e); } } } return null; } }; } } } return result; }
From source file:com.eucalyptus.blockstorage.async.VolumeDeleter.java
private static Function<String, VolumeInfo> invalidateAndDetachAll(final LogicalStorageManager blockManager) { final Predicate<VolumeToken> invalidateExports = new Predicate<VolumeToken>() { @Override//www. j a v a 2 s . com public boolean apply(VolumeToken volToken) { VolumeToken tokenEntity = Entities.merge(volToken); try { tokenEntity.invalidateAllExportsAndToken(); return true; } catch (Exception e) { LOG.error("Failed invalidating exports for token " + tokenEntity.getToken()); return false; } } }; // Could save cycles by statically setting all of these functions that don't require closures so they are not // constructed for each request. return new Function<String, VolumeInfo>() { @Override public VolumeInfo apply(String volumeId) { try { VolumeInfo volumeEntity = Entities.uniqueResult(new VolumeInfo(volumeId)); try { LOG.debug("Invalidating all tokens and all exports for " + volumeId); // Invalidate all tokens and exports and forcibly detach. if (!Iterables.all(volumeEntity.getAttachmentTokens(), invalidateExports)) { // At least one failed. LOG.error("Failed to invalidate all tokens and exports"); } } catch (Exception e) { LOG.error("Error invalidating tokens", e); } try { LOG.debug("Unexporting volume " + volumeId + " from all hosts"); blockManager.unexportVolumeFromAll(volumeId); } catch (EucalyptusCloudException ex) { LOG.error("Detaching volume " + volumeId + " from all hosts failed", ex); } } catch (NoSuchElementException e) { LOG.error("Cannot force detach of volume " + volumeId + " because it is not found in database"); return null; } catch (TransactionException e) { LOG.error("Failed to lookup volume " + volumeId); } return null; } }; }
From source file:com.google.devtools.build.lib.skyframe.PackageFunction.java
/** * Marks the given dependencies, and returns those already present. Ignores any exception thrown * while building the dependency, except for filesystem inconsistencies. * * <p>We need to mark dependencies implicitly used by the legacy package loading code, but we * don't care about any skyframe errors since the package knows whether it's in error or not. *///from w w w . ja v a 2s. co m private static Pair<? extends Map<PathFragment, PackageLookupValue>, Boolean> getPackageLookupDepsAndPropagateInconsistentFilesystemExceptions( PackageIdentifier packageIdentifier, Iterable<SkyKey> depKeys, Environment env, boolean packageWasInError) throws InternalInconsistentFilesystemException, InterruptedException { Preconditions.checkState(Iterables.all(depKeys, SkyFunctions.isSkyFunction(SkyFunctions.PACKAGE_LOOKUP)), depKeys); boolean packageShouldBeInError = packageWasInError; ImmutableMap.Builder<PathFragment, PackageLookupValue> builder = ImmutableMap.builder(); for (Map.Entry<SkyKey, ValueOrException3<BuildFileNotFoundException, InconsistentFilesystemException, FileSymlinkException>> entry : env .getValuesOrThrow(depKeys, BuildFileNotFoundException.class, InconsistentFilesystemException.class, FileSymlinkException.class) .entrySet()) { PathFragment pkgName = ((PackageIdentifier) entry.getKey().argument()).getPackageFragment(); try { PackageLookupValue value = (PackageLookupValue) entry.getValue().get(); if (value != null) { builder.put(pkgName, value); } } catch (BuildFileNotFoundException e) { maybeThrowFilesystemInconsistency(packageIdentifier, e, packageWasInError); } catch (InconsistentFilesystemException e) { throw new InternalInconsistentFilesystemException(packageIdentifier, e); } catch (FileSymlinkException e) { // Legacy doesn't detect symlink cycles. packageShouldBeInError = true; } } return Pair.of(builder.build(), packageShouldBeInError); }