List of usage examples for com.google.common.collect Iterators emptyIterator
@Deprecated public static <T> UnmodifiableIterator<T> emptyIterator()
From source file:nars.concept.Concept.java
@NotNull default Iterator<Task> iterateTasks(boolean onbeliefs, boolean ongoals, boolean onquestions, boolean onquests) { TaskTable beliefs = onbeliefs ? beliefs() : null; TaskTable goals = ongoals ? goals() : null; TaskTable questions = onquestions ? questions() : null; TaskTable quests = onquests ? quests() : null; Iterator<Task> b1 = beliefs != null ? beliefs.iterator() : Iterators.emptyIterator(); Iterator<Task> b2 = goals != null ? goals.iterator() : Iterators.emptyIterator(); Iterator<Task> b3 = questions != null ? questions.iterator() : Iterators.emptyIterator(); Iterator<Task> b4 = quests != null ? quests.iterator() : Iterators.emptyIterator(); return Iterators.concat(b1, b2, b3, b4); }
From source file:org.eclipse.emf.compare.match.DefaultMatchEngine.java
/** * This will query the scope for the given {@link EObject}s' children, then delegate to an * {@link IEObjectMatcher} to compute the {@link Match}es. * <p>//from w w w.j a v a 2 s .c o m * We expect at least the <code>left</code> and <code>right</code> EObjects not to be <code>null</code>. * </p> * * @param left * The left {@link EObject}. * @param right * The right {@link EObject}. * @param origin * The common ancestor of <code>left</code> and <code>right</code>. */ protected void match(EObject left, EObject right, EObject origin) { if (left == null || right == null) { // FIXME IAE or NPE? throw new IllegalArgumentException(); } final Iterator<? extends EObject> leftEObjects = getScope().getChildren(left); final Iterator<? extends EObject> rightEObjects = getScope().getChildren(right); final Iterator<? extends EObject> originEObjects; if (origin != null) { originEObjects = getScope().getChildren(origin); } else { originEObjects = Iterators.emptyIterator(); } final IEObjectMatcher matcher = createEObjectMatcher(); final Iterable<Match> matches = matcher.createMatches(leftEObjects, rightEObjects, originEObjects); Iterables.addAll(getComparison().getMatches(), matches); }
From source file:org.apache.cassandra.db.filter.NamesQueryFilter.java
public Iterator<RangeTombstone> getRangeTombstoneIterator(final ColumnFamily source) { if (!source.deletionInfo().hasRanges()) return Iterators.emptyIterator(); return new AbstractIterator<RangeTombstone>() { private final Iterator<CellName> names = columns.iterator(); private RangeTombstone lastFindRange; protected RangeTombstone computeNext() { while (names.hasNext()) { CellName next = names.next(); if (lastFindRange != null && lastFindRange.includes(source.getComparator(), next)) return lastFindRange; // We keep the last range around as since names are in sort order, it's // possible it will match the next name too. lastFindRange = source.deletionInfo().rangeCovering(next); if (lastFindRange != null) return lastFindRange; }/*from w w w . ja v a2s. co m*/ return endOfData(); } }; }
From source file:org.bonitasoft.studio.businessobject.core.repository.BusinessObjectModelRepositoryStore.java
private <T> Iterable<T> asIterable(final T[] elements) { return new Iterable<T>() { @Override/*from w ww .j a v a2 s .c om*/ public Iterator<T> iterator() { if (elements == null) { return Iterators.emptyIterator(); } return forArray(elements); } }; }
From source file:org.gradle.api.internal.changedetection.state.OrderInsensitiveTaskFilePropertyCompareStrategy.java
private Iterator<TaskStateChange> iterateChangesForRelativePaths( final Map<String, NormalizedFileSnapshot> current, Map<String, NormalizedFileSnapshot> previous, final String fileType) { final ListMultimap<NormalizedFileSnapshot, IncrementalFileSnapshotWithAbsolutePath> unaccountedForPreviousSnapshots = MultimapBuilder .hashKeys().linkedListValues().build(); for (Entry<String, NormalizedFileSnapshot> entry : previous.entrySet()) { String absolutePath = entry.getKey(); NormalizedFileSnapshot previousSnapshot = entry.getValue(); unaccountedForPreviousSnapshots.put(previousSnapshot, new IncrementalFileSnapshotWithAbsolutePath(absolutePath, previousSnapshot.getSnapshot())); }/* w w w. java2 s .co m*/ final Iterator<Entry<String, NormalizedFileSnapshot>> currentEntries = current.entrySet().iterator(); return new AbstractIterator<TaskStateChange>() { private Iterator<Entry<NormalizedFileSnapshot, IncrementalFileSnapshotWithAbsolutePath>> unaccountedForPreviousSnapshotsIterator; private final ListMultimap<String, IncrementalFileSnapshotWithAbsolutePath> addedFiles = MultimapBuilder .hashKeys().linkedListValues().build(); private Iterator<IncrementalFileSnapshotWithAbsolutePath> addedFilesIterator; @Override protected TaskStateChange computeNext() { while (currentEntries.hasNext()) { Entry<String, NormalizedFileSnapshot> entry = currentEntries.next(); String currentAbsolutePath = entry.getKey(); NormalizedFileSnapshot currentNormalizedSnapshot = entry.getValue(); IncrementalFileSnapshot currentSnapshot = currentNormalizedSnapshot.getSnapshot(); List<IncrementalFileSnapshotWithAbsolutePath> previousSnapshotsForNormalizedPath = unaccountedForPreviousSnapshots .get(currentNormalizedSnapshot); if (previousSnapshotsForNormalizedPath.isEmpty()) { IncrementalFileSnapshotWithAbsolutePath currentSnapshotWithAbsolutePath = new IncrementalFileSnapshotWithAbsolutePath( currentAbsolutePath, currentSnapshot); addedFiles.put(currentNormalizedSnapshot.getNormalizedPath(), currentSnapshotWithAbsolutePath); } else { IncrementalFileSnapshotWithAbsolutePath previousSnapshotWithAbsolutePath = previousSnapshotsForNormalizedPath .remove(0); IncrementalFileSnapshot previousSnapshot = previousSnapshotWithAbsolutePath.getSnapshot(); if (!currentSnapshot.isContentUpToDate(previousSnapshot)) { return new FileChange(currentAbsolutePath, ChangeType.MODIFIED, fileType); } } } // Create a single iterator to use for all of the still unaccounted files if (unaccountedForPreviousSnapshotsIterator == null) { if (unaccountedForPreviousSnapshots.isEmpty()) { unaccountedForPreviousSnapshotsIterator = Iterators.emptyIterator(); } else { List<Entry<NormalizedFileSnapshot, IncrementalFileSnapshotWithAbsolutePath>> entries = Lists .newArrayList(unaccountedForPreviousSnapshots.entries()); Collections.sort(entries, ENTRY_COMPARATOR); unaccountedForPreviousSnapshotsIterator = entries.iterator(); } } if (unaccountedForPreviousSnapshotsIterator.hasNext()) { Entry<NormalizedFileSnapshot, IncrementalFileSnapshotWithAbsolutePath> unaccountedForPreviousSnapshotEntry = unaccountedForPreviousSnapshotsIterator .next(); String normalizedPath = unaccountedForPreviousSnapshotEntry.getKey().getNormalizedPath(); List<IncrementalFileSnapshotWithAbsolutePath> addedFilesForNormalizedPath = addedFiles .get(normalizedPath); if (!addedFilesForNormalizedPath.isEmpty()) { // There might be multiple files with the same normalized path, here we choose one of them IncrementalFileSnapshotWithAbsolutePath modifiedSnapshot = addedFilesForNormalizedPath .remove(0); return new FileChange(modifiedSnapshot.getAbsolutePath(), ChangeType.MODIFIED, fileType); } else { IncrementalFileSnapshotWithAbsolutePath removedSnapshot = unaccountedForPreviousSnapshotEntry .getValue(); return new FileChange(removedSnapshot.getAbsolutePath(), ChangeType.REMOVED, fileType); } } if (includeAdded) { // Create a single iterator to use for all of the added files if (addedFilesIterator == null) { addedFilesIterator = addedFiles.values().iterator(); } if (addedFilesIterator.hasNext()) { IncrementalFileSnapshotWithAbsolutePath addedFile = addedFilesIterator.next(); return new FileChange(addedFile.getAbsolutePath(), ChangeType.ADDED, fileType); } } return endOfData(); } }; }
From source file:eu.numberfour.n4js.internal.FileBasedWorkspace.java
@Override public Iterator<URI> getArchiveIterator(final URI archiveLocation, String archiveRelativeLocation) { File archiveFile = new File(java.net.URI.create(archiveLocation.toString())); ZipInputStream stream = null; try {/*from w w w .ja v a 2s .c om*/ stream = new ZipInputStream(new BufferedInputStream(new FileInputStream(archiveFile))); Iterator<ZipEntry> entries = getArchiveIterator(stream, archiveRelativeLocation); return toArchiveURIs(archiveLocation, entries); } catch (FileNotFoundException e) { return Iterators.emptyIterator(); } finally { if (stream != null) { try { stream.close(); } catch (IOException e) { // ignore } } } }
From source file:io.druid.firehose.rabbitmq.RabbitMQFirehoseFactory.java
@Override public Firehose connect(final InputRowParser<ByteBuffer> firehoseParser, File temporaryDirectory) throws IOException { ConnectionOptions lyraOptions = new ConnectionOptions(this.connectionFactory); Config lyraConfig = new Config().withRecoveryPolicy(new RetryPolicy().withMaxRetries(config.getMaxRetries()) .withRetryInterval(Duration.seconds(config.getRetryIntervalSeconds())) .withMaxDuration(Duration.seconds(config.getMaxDurationSeconds()))); String queue = config.getQueue(); String exchange = config.getExchange(); String routingKey = config.getRoutingKey(); boolean durable = config.isDurable(); boolean exclusive = config.isExclusive(); boolean autoDelete = config.isAutoDelete(); final Connection connection = Connections.create(lyraOptions, lyraConfig); connection.addShutdownListener(new ShutdownListener() { @Override/*from w w w. j av a 2 s. c om*/ public void shutdownCompleted(ShutdownSignalException cause) { log.warn(cause, "Connection closed!"); } }); final Channel channel = connection.createChannel(); channel.queueDeclare(queue, durable, exclusive, autoDelete, null); channel.queueBind(queue, exchange, routingKey); channel.addShutdownListener(new ShutdownListener() { @Override public void shutdownCompleted(ShutdownSignalException cause) { log.warn(cause, "Channel closed!"); } }); // We create a QueueingConsumer that will not auto-acknowledge messages since that // happens on commit(). final QueueingConsumer consumer = new QueueingConsumer(channel); channel.basicConsume(queue, false, consumer); return new Firehose() { /** * Storing the latest row as a member variable should be safe since this will only be run * by a single thread. */ private InputRow nextRow; /** * Store the latest delivery tag to be able to commit (acknowledge) the message delivery up to * and including this tag. See commit() for more detail. */ private long lastDeliveryTag; private Iterator<InputRow> nextIterator = Iterators.emptyIterator(); @Override public boolean hasMore() { nextRow = null; try { if (nextIterator.hasNext()) { nextRow = nextIterator.next(); return true; } // Wait for the next delivery. This will block until something is available. final Delivery delivery = consumer.nextDelivery(); if (delivery != null) { lastDeliveryTag = delivery.getEnvelope().getDeliveryTag(); nextIterator = firehoseParser.parseBatch(ByteBuffer.wrap(delivery.getBody())).iterator(); if (nextIterator.hasNext()) { nextRow = nextIterator.next(); // If delivery is non-null, we report that there is something more to process. return true; } } } catch (InterruptedException e) { // A little unclear on how we should handle this. // At any rate, we're in an unknown state now so let's log something and return false. log.wtf(e, "Got interrupted while waiting for next delivery. Doubt this should ever happen."); } // This means that delivery is null or we caught the exception above so we report that we have // nothing more to process. return false; } @Nullable @Override public InputRow nextRow() { if (nextRow == null) { //Just making sure. log.wtf("I have nothing in delivery. Method hasMore() should have returned false."); return null; } return nextRow; } @Override public Runnable commit() { // This method will be called from the same thread that calls the other methods of // this Firehose. However, the returned Runnable will be called by a different thread. // // It should be (thread) safe to copy the lastDeliveryTag like we do below and then // acknowledge values up to and including that value. return new Runnable() { // Store (copy) the last delivery tag to "become" thread safe. final long deliveryTag = lastDeliveryTag; @Override public void run() { try { log.info("Acknowledging delivery of messages up to tag: " + deliveryTag); // Acknowledge all messages up to and including the stored delivery tag. channel.basicAck(deliveryTag, true); } catch (IOException e) { log.error(e, "Unable to acknowledge message reception to message queue."); } } }; } @Override public void close() throws IOException { log.info("Closing connection to RabbitMQ"); channel.close(); connection.close(); } }; }
From source file:eu.numberfour.n4js.ui.internal.EclipseBasedN4JSWorkspace.java
@Override public UnmodifiableIterator<URI> getFolderIterator(URI folderLocation) { final IContainer container; if (DIRECT_RESOURCE_IN_PROJECT_SEGMENTCOUNT == folderLocation.segmentCount()) { container = workspace.getProject(folderLocation.lastSegment()); } else {//from w w w . j av a 2 s.co m container = workspace.getFolder(new Path(folderLocation.toPlatformString(true))); } if (container != null && container.exists()) { final List<URI> result = Lists.newLinkedList(); try { container.accept(new IResourceVisitor() { @Override public boolean visit(IResource resource) throws CoreException { if (resource.getType() == IResource.FILE) { result.add(URI.createPlatformResourceURI(resource.getFullPath().toString(), true)); } return true; } }); return Iterators.unmodifiableIterator(result.iterator()); } catch (CoreException e) { return Iterators.unmodifiableIterator(result.iterator()); } } return Iterators.emptyIterator(); }
From source file:eu.numberfour.n4js.internal.FileBasedWorkspace.java
@Override public Iterator<URI> getFolderIterator(URI folderLocation) { final File sourceContainerDirectory = new File(java.net.URI.create(folderLocation.toString())); if (sourceContainerDirectory.isDirectory()) { AbstractTreeIterator<File> treeIterator = new AbstractTreeIterator<File>(sourceContainerDirectory, false) {/*from ww w .java 2s . co m*/ @Override protected Iterator<? extends File> getChildren(Object root) { if (root instanceof File && ((File) root).isDirectory()) { return Arrays.asList(((File) root).listFiles()).iterator(); } return Iterators.emptyIterator(); } }; return Iterators .unmodifiableIterator(Iterators.transform(Iterators.filter(treeIterator, new Predicate<File>() { @Override public boolean apply(File input) { return !input.isDirectory(); } }), new Function<File, URI>() { @Override public URI apply(File input) { return URI.createURI(input.toURI().toString()); } })); } return Iterators.emptyIterator(); }
From source file:org.geoserver.data.versioning.decorator.VersionQuery.java
/** * @param id/* ww w . ja va 2 s.com*/ * @return an iterator for all the requested versions of a given feature, or * the empty iterator if no such feature is found. * @throws Exception */ public Iterator<Ref> get(final ResourceId id) throws Exception { final String featureId = id.getID(); final String featureVersion = id.getFeatureVersion(); final Version version = id.getVersion(); final boolean isDateRangeQuery = id.getStartTime() != null || id.getEndTime() != null; final boolean isVesionQuery = !version.isEmpty(); final Ref requestedVersionRef = extractRequestedVersion(ggit, featureId, featureVersion); { final boolean explicitVersionQuery = !isDateRangeQuery && !isVesionQuery; if (explicitVersionQuery) { if (requestedVersionRef == null) { return Iterators.emptyIterator(); } else { // easy, no extra constraints specified return Iterators.singletonIterator(requestedVersionRef); } } } // at this point is either a version query or a date range query... List<Ref> result = new ArrayList<Ref>(5); // filter commits that affect the requested feature final List<String> path = path(featureId); LogOp logOp = ggit.log().addPath(path); if (isDateRangeQuery) { // time range query, limit commits by time range, if speficied Date startTime = id.getStartTime() == null ? new Date(0L) : id.getStartTime(); Date endTime = id.getEndTime() == null ? new Date(Long.MAX_VALUE) : id.getEndTime(); boolean isMinIncluded = true; boolean isMaxIncluded = true; Range<Date> timeRange = new Range<Date>(Date.class, startTime, isMinIncluded, endTime, isMaxIncluded); logOp.setTimeRange(timeRange); } // all commits whose tree contains the requested feature Iterator<RevCommit> featureCommits = logOp.call(); if (isDateRangeQuery) { List<Ref> allInAscendingOrder = getAllInAscendingOrder(ggit, featureCommits, featureId); result.addAll(allInAscendingOrder); } else if (isVesionQuery) { if (version.isDateTime()) { final Date validAsOf = version.getDateTime(); RevCommit closest = findClosest(validAsOf, featureCommits); if (closest != null) { featureCommits = Iterators.singletonIterator(closest); result.addAll(getAllInAscendingOrder(ggit, featureCommits, featureId)); } } else if (version.isIndex()) { final int requestIndex = version.getIndex().intValue(); final int listIndex = requestIndex - 1;// version indexing // starts at 1 List<Ref> allVersions = getAllInAscendingOrder(ggit, featureCommits, featureId); if (allVersions.size() > 0) { if (allVersions.size() >= requestIndex) { result.add(allVersions.get(listIndex)); } else { result.add(allVersions.get(allVersions.size() - 1)); } } } else if (version.isVersionAction()) { final Action versionAction = version.getVersionAction(); List<Ref> allInAscendingOrder = getAllInAscendingOrder(ggit, featureCommits, featureId); switch (versionAction) { case ALL: result.addAll(allInAscendingOrder); break; case FIRST: if (allInAscendingOrder.size() > 0) { result.add(allInAscendingOrder.get(0)); } break; case LAST: if (allInAscendingOrder.size() > 0) { result.add(allInAscendingOrder.get(allInAscendingOrder.size() - 1)); } break; case NEXT: Ref next = next(requestedVersionRef, allInAscendingOrder); if (next != null) { result.add(next); } break; case PREVIOUS: Ref previous = previous(requestedVersionRef, allInAscendingOrder); if (previous != null) { result.add(previous); } break; default: break; } } } return result.iterator(); }