/** @since 12.0 */ @GwtIncompatible("NavigableSet") @Override public ImmutableSortedSet<E> subSet( E fromElement, boolean fromInclusive, E toElement, boolean toInclusive) { checkNotNull(fromElement); checkNotNull(toElement); checkArgument(comparator.compare(fromElement, toElement) <= 0); return subSetImpl(fromElement, fromInclusive, toElement, toInclusive); }
/** * Returns the elements of {@code unfiltered} that satisfy a predicate. The resulting iterable's * iterator does not support {@code remove()}. */ @CheckReturnValue public static <T> Iterable<T> filter( final Iterable<T> unfiltered, final Predicate<? super T> predicate) { checkNotNull(unfiltered); checkNotNull(predicate); return new FluentIterable<T>() { @Override public Iterator<T> iterator() { return Iterators.filter(unfiltered.iterator(), predicate); } }; }
/** * Returns all instances of class {@code type} in {@code unfiltered}. The returned iterable has * elements whose class is {@code type} or a subclass of {@code type}. The returned iterable's * iterator does not support {@code remove()}. * * @param unfiltered an iterable containing objects of any type * @param type the type of elements desired * @return an unmodifiable iterable containing all elements of the original iterable that were of * the requested type */ @GwtIncompatible("Class.isInstance") @CheckReturnValue public static <T> Iterable<T> filter(final Iterable<?> unfiltered, final Class<T> type) { checkNotNull(unfiltered); checkNotNull(type); return new FluentIterable<T>() { @Override public Iterator<T> iterator() { return Iterators.filter(unfiltered.iterator(), type); } }; }
/** * Returns an iterable that applies {@code function} to each element of {@code fromIterable}. * * <p>The returned iterable's iterator supports {@code remove()} if the provided iterator does. * After a successful {@code remove()} call, {@code fromIterable} no longer contains the * corresponding element. * * <p>If the input {@code Iterable} is known to be a {@code List} or other {@code Collection}, * consider {@link Lists#transform} and {@link Collections2#transform}. */ @CheckReturnValue public static <F, T> Iterable<T> transform( final Iterable<F> fromIterable, final Function<? super F, ? extends T> function) { checkNotNull(fromIterable); checkNotNull(function); return new FluentIterable<T>() { @Override public Iterator<T> iterator() { return Iterators.transform(fromIterable.iterator(), function); } }; }
void addListener(Listener listener, Executor executor) { checkNotNull(listener, "listener"); checkNotNull(executor, "executor"); monitor.enter(); try { // no point in adding a listener that will never be called if (!stoppedGuard.isSatisfied()) { listeners.add(new ListenerCallQueue<Listener>(listener, executor)); } } finally { monitor.leave(); } }
@Nullable static Type getComponentType(Type type) { checkNotNull(type); final AtomicReference<Type> result = new AtomicReference<Type>(); new TypeVisitor() { @Override void visitTypeVariable(TypeVariable<?> t) { result.set(subtypeOfComponentType(t.getBounds())); } @Override void visitWildcardType(WildcardType t) { result.set(subtypeOfComponentType(t.getUpperBounds())); } @Override void visitGenericArrayType(GenericArrayType t) { result.set(t.getGenericComponentType()); } @Override void visitClass(Class<?> t) { result.set(t.getComponentType()); } }.visit(type); return result.get(); }
/** * Returns an iterable over the merged contents of all given {@code iterables}. Equivalent entries * will not be de-duplicated. * * <p>Callers must ensure that the source {@code iterables} are in non-descending order as this * method does not sort its input. * * <p>For any equivalent elements across all {@code iterables}, it is undefined which element is * returned first. * * @since 11.0 */ @Beta public static <T> Iterable<T> mergeSorted( final Iterable<? extends Iterable<? extends T>> iterables, final Comparator<? super T> comparator) { checkNotNull(iterables, "iterables"); checkNotNull(comparator, "comparator"); Iterable<T> iterable = new FluentIterable<T>() { @Override public Iterator<T> iterator() { return Iterators.mergeSorted( Iterables.transform(iterables, Iterables.<T>toIterator()), comparator); } }; return new UnmodifiableIterable<T>(iterable); }
/** Returns an unmodifiable view of {@code iterable}. */ public static <T> Iterable<T> unmodifiableIterable(final Iterable<T> iterable) { checkNotNull(iterable); if (iterable instanceof UnmodifiableIterable || iterable instanceof ImmutableCollection) { return iterable; } return new UnmodifiableIterable<T>(iterable); }
/** * Returns a view of the supplied iterable that wraps each generated {@link Iterator} through * {@link Iterators#consumingIterator(Iterator)}. * * <p>Note: If {@code iterable} is a {@link Queue}, the returned iterable will get entries from * {@link Queue#remove()} since {@link Queue}'s iteration order is undefined. Calling {@link * Iterator#hasNext()} on a generated iterator from the returned iterable may cause an item to be * immediately dequeued for return on a subsequent call to {@link Iterator#next()}. * * @param iterable the iterable to wrap * @return a view of the supplied iterable that wraps each generated iterator through {@link * Iterators#consumingIterator(Iterator)}; for queues, an iterable that generates iterators * that return and consume the queue's elements in queue order * @see Iterators#consumingIterator(Iterator) * @since 2.0 */ public static <T> Iterable<T> consumingIterable(final Iterable<T> iterable) { if (iterable instanceof Queue) { return new FluentIterable<T>() { @Override public Iterator<T> iterator() { return new ConsumingQueueIterator<T>((Queue<T>) iterable); } @Override public String toString() { return "Iterables.consumingIterable(...)"; } }; } checkNotNull(iterable); return new FluentIterable<T>() { @Override public Iterator<T> iterator() { return Iterators.consumingIterator(iterable.iterator()); } @Override public String toString() { return "Iterables.consumingIterable(...)"; } }; }
ParameterizedTypeImpl(@Nullable Type ownerType, Class<?> rawType, Type[] typeArguments) { checkNotNull(rawType); checkArgument(typeArguments.length == rawType.getTypeParameters().length); disallowPrimitiveType(typeArguments, "type parameter"); this.ownerType = ownerType; this.rawType = rawType; this.argumentsList = JavaVersion.CURRENT.usedInGenericType(typeArguments); }
/** * Returns the start position of the first occurrence of the specified {@code target} within * {@code array}, or {@code -1} if there is no such occurrence. * * <p>More formally, returns the lowest index {@code i} such that {@code * java.util.Arrays.copyOfRange(array, i, i + target.length)} contains exactly the same elements * as {@code target}. * * @param array the array to search for the sequence {@code target} * @param target the array to search for as a sub-sequence of {@code array} */ public static int indexOf(short[] array, short[] target) { checkNotNull(array, "array"); checkNotNull(target, "target"); if (target.length == 0) { return 0; } outer: for (int i = 0; i < array.length - target.length + 1; i++) { for (int j = 0; j < target.length; j++) { if (array[i + j] != target[j]) { continue outer; } } return i; } return -1; }
/** * Combines multiple iterables into a single iterable. The returned iterable has an iterator that * traverses the elements of each iterable in {@code inputs}. The input iterators are not polled * until necessary. * * <p>The returned iterable's iterator supports {@code remove()} when the corresponding input * iterator supports it. The methods of the returned iterable may throw {@code * NullPointerException} if any of the input iterators is null. */ public static <T> Iterable<T> concat(final Iterable<? extends Iterable<? extends T>> inputs) { checkNotNull(inputs); return new FluentIterable<T>() { @Override public Iterator<T> iterator() { return Iterators.concat(iterators(inputs)); } }; }
/** * Returns a type where {@code rawType} is parameterized by {@code arguments} and is owned by * {@code ownerType}. */ static ParameterizedType newParameterizedTypeWithOwner( @Nullable Type ownerType, Class<?> rawType, Type... arguments) { if (ownerType == null) { return newParameterizedType(rawType, arguments); } // ParameterizedTypeImpl constructor already checks, but we want to throw NPE before IAE checkNotNull(arguments); checkArgument(rawType.getEnclosingClass() != null, "Owner type for unenclosed %s", rawType); return new ParameterizedTypeImpl(ownerType, rawType, arguments); }
/** * Divides an iterable into unmodifiable sublists of the given size, padding the final iterable * with null values if necessary. For example, partitioning an iterable containing {@code [a, b, * c, d, e]} with a partition size of 3 yields {@code [[a, b, c], [d, e, null]]} -- an outer * iterable containing two inner lists of three elements each, all in the original order. * * <p>Iterators returned by the returned iterable do not support the {@link Iterator#remove()} * method. * * @param iterable the iterable to return a partitioned view of * @param size the desired size of each partition * @return an iterable of unmodifiable lists containing the elements of {@code iterable} divided * into partitions (the final iterable may have trailing null elements) * @throws IllegalArgumentException if {@code size} is nonpositive */ public static <T> Iterable<List<T>> paddedPartition(final Iterable<T> iterable, final int size) { checkNotNull(iterable); checkArgument(size > 0); return new FluentIterable<List<T>>() { @Override public Iterator<List<T>> iterator() { return Iterators.paddedPartition(iterable.iterator(), size); } }; }
/** * Creates an iterable with the first {@code limitSize} elements of the given iterable. If the * original iterable does not contain that many elements, the returned iterable will have the same * behavior as the original iterable. The returned iterable's iterator supports {@code remove()} * if the original iterator does. * * @param iterable the iterable to limit * @param limitSize the maximum number of elements in the returned iterable * @throws IllegalArgumentException if {@code limitSize} is negative * @since 3.0 */ public static <T> Iterable<T> limit(final Iterable<T> iterable, final int limitSize) { checkNotNull(iterable); checkArgument(limitSize >= 0, "limit is negative"); return new FluentIterable<T>() { @Override public Iterator<T> iterator() { return Iterators.limit(iterable.iterator(), limitSize); } }; }
@Override Type usedInGenericType(Type type) { checkNotNull(type); if (type instanceof Class) { Class<?> cls = (Class<?>) type; if (cls.isArray()) { return new GenericArrayTypeImpl(cls.getComponentType()); } } return type; }
/** * Updates the state with the given service transition. * * <p>This method performs the main logic of ServiceManager in the following steps. * * <ol> * <li>Update the {@link #servicesByState()} * <li>Update the {@link #startupTimers} * <li>Based on the new state queue listeners to run * <li>Run the listeners (outside of the lock) * </ol> */ void transitionService(final Service service, State from, State to) { checkNotNull(service); checkArgument(from != to); monitor.enter(); try { transitioned = true; if (!ready) { return; } // Update state. checkState( servicesByState.remove(from, service), "Service %s not at the expected location in the state map %s", service, from); checkState( servicesByState.put(to, service), "Service %s in the state map unexpectedly at %s", service, to); // Update the timer Stopwatch stopwatch = startupTimers.get(service); if (stopwatch == null) { // This means the service was started by some means other than ServiceManager.startAsync stopwatch = Stopwatch.createStarted(); startupTimers.put(service, stopwatch); } if (to.compareTo(RUNNING) >= 0 && stopwatch.isRunning()) { // N.B. if we miss the STARTING event then we may never record a startup time. stopwatch.stop(); if (!(service instanceof NoOpService)) { logger.log(Level.FINE, "Started {0} in {1}.", new Object[] {service, stopwatch}); } } // Queue our listeners // Did a service fail? if (to == FAILED) { fireFailedListeners(service); } if (states.count(RUNNING) == numberOfServices) { // This means that the manager is currently healthy. N.B. If other threads call isHealthy // they are not guaranteed to get 'true', because any service could fail right now. fireHealthyListeners(); } else if (states.count(TERMINATED) + states.count(FAILED) == numberOfServices) { fireStoppedListeners(); } } finally { monitor.leave(); // Run our executors outside of the lock executeListeners(); } }
/** * Returns a view of {@code iterable} that skips its first {@code numberToSkip} elements. If * {@code iterable} contains fewer than {@code numberToSkip} elements, the returned iterable skips * all of its elements. * * <p>Modifications to the underlying {@link Iterable} before a call to {@code iterator()} are * reflected in the returned iterator. That is, the iterator skips the first {@code numberToSkip} * elements that exist when the {@code Iterator} is created, not when {@code skip()} is called. * * <p>The returned iterable's iterator supports {@code remove()} if the iterator of the underlying * iterable supports it. Note that it is <i>not</i> possible to delete the last skipped element by * immediately calling {@code remove()} on that iterator, as the {@code Iterator} contract states * that a call to {@code remove()} before a call to {@code next()} will throw an {@link * IllegalStateException}. * * @since 3.0 */ public static <T> Iterable<T> skip(final Iterable<T> iterable, final int numberToSkip) { checkNotNull(iterable); checkArgument(numberToSkip >= 0, "number to skip cannot be negative"); if (iterable instanceof List) { final List<T> list = (List<T>) iterable; return new FluentIterable<T>() { @Override public Iterator<T> iterator() { // TODO(kevinb): Support a concurrently modified collection? int toSkip = Math.min(list.size(), numberToSkip); return list.subList(toSkip, list.size()).iterator(); } }; } return new FluentIterable<T>() { @Override public Iterator<T> iterator() { final Iterator<T> iterator = iterable.iterator(); Iterators.advance(iterator, numberToSkip); /* * We can't just return the iterator because an immediate call to its * remove() method would remove one of the skipped elements instead of * throwing an IllegalStateException. */ return new Iterator<T>() { boolean atStart = true; @Override public boolean hasNext() { return iterator.hasNext(); } @Override public T next() { T result = iterator.next(); atStart = false; // not called if next() fails return result; } @Override public void remove() { checkRemove(!atStart); iterator.remove(); } }; } }; }
/** * Returns the element at the specified position in an iterable or a default value otherwise. * * @param position position of the element to return * @param defaultValue the default value to return if {@code position} is greater than or equal to * the size of the iterable * @return the element at the specified position in {@code iterable} or {@code defaultValue} if * {@code iterable} contains fewer than {@code position + 1} elements. * @throws IndexOutOfBoundsException if {@code position} is negative * @since 4.0 */ @Nullable public static <T> T get(Iterable<? extends T> iterable, int position, @Nullable T defaultValue) { checkNotNull(iterable); Iterators.checkNonnegative(position); if (iterable instanceof List) { List<? extends T> list = Lists.cast(iterable); return (position < list.size()) ? list.get(position) : defaultValue; } else { Iterator<? extends T> iterator = iterable.iterator(); Iterators.advance(iterator, position); return Iterators.getNext(iterator, defaultValue); } }
/** Removes and returns the first matching element, or returns {@code null} if there is none. */ @Nullable static <T> T removeFirstMatching(Iterable<T> removeFrom, Predicate<? super T> predicate) { checkNotNull(predicate); Iterator<T> iterator = removeFrom.iterator(); while (iterator.hasNext()) { T next = iterator.next(); if (predicate.apply(next)) { iterator.remove(); return next; } } return null; }
/** * Returns a string containing the supplied {@code short} values separated by {@code separator}. * For example, {@code join("-", (short) 1, (short) 2, (short) 3)} returns the string {@code * "1-2-3"}. * * @param separator the text that should appear between consecutive values in the resulting string * (but not at the start or end) * @param array an array of {@code short} values, possibly empty */ public static String join(String separator, short... array) { checkNotNull(separator); if (array.length == 0) { return ""; } // For pre-sizing a builder, just get the right order of magnitude StringBuilder builder = new StringBuilder(array.length * 6); builder.append(array[0]); for (int i = 1; i < array.length; i++) { builder.append(separator).append(array[i]); } return builder.toString(); }
/** * Returns an iterable whose iterators cycle indefinitely over the elements of {@code iterable}. * * <p>That iterator supports {@code remove()} if {@code iterable.iterator()} does. After {@code * remove()} is called, subsequent cycles omit the removed element, which is no longer in {@code * iterable}. The iterator's {@code hasNext()} method returns {@code true} until {@code iterable} * is empty. * * <p><b>Warning:</b> Typical uses of the resulting iterator may produce an infinite loop. You * should use an explicit {@code break} or be certain that you will eventually remove all the * elements. * * <p>To cycle over the iterable {@code n} times, use the following: {@code * Iterables.concat(Collections.nCopies(n, iterable))} */ public static <T> Iterable<T> cycle(final Iterable<T> iterable) { checkNotNull(iterable); return new FluentIterable<T>() { @Override public Iterator<T> iterator() { return Iterators.cycle(iterable); } @Override public String toString() { return iterable.toString() + " (cycled)"; } }; }
/** * Adds the given element to this queue. If this queue has a maximum size, after adding {@code * element} the queue will automatically evict its greatest element (according to its comparator), * which may be {@code element} itself. */ @CanIgnoreReturnValue @Override public boolean offer(E element) { checkNotNull(element); modCount++; int insertIndex = size++; growIfNeeded(); // Adds the element to the end of the heap and bubbles it up to the correct // position. heapForIndex(insertIndex).bubbleUp(insertIndex, element); return size <= maximumSize || pollLast() != element; }
/** * Returns an immutable sorted set containing the given elements sorted by the given {@code * Comparator}. When multiple elements are equivalent according to {@code compare()}, only the * first one specified is included. This method iterates over {@code elements} at most once. * * <p>Despite the method name, this method attempts to avoid actually copying the data when it is * safe to do so. The exact circumstances under which a copy will or will not be performed are * undocumented and subject to change. * * @throws NullPointerException if {@code comparator} or any of {@code elements} is null */ public static <E> ImmutableSortedSet<E> copyOf( Comparator<? super E> comparator, Iterable<? extends E> elements) { checkNotNull(comparator); boolean hasSameComparator = SortedIterables.hasSameComparator(comparator, elements); if (hasSameComparator && (elements instanceof ImmutableSortedSet)) { @SuppressWarnings("unchecked") ImmutableSortedSet<E> original = (ImmutableSortedSet<E>) elements; if (!original.isPartialView()) { return original; } } @SuppressWarnings("unchecked") // elements only contains E's; it's safe. E[] array = (E[]) Iterables.toArray(elements); return construct(comparator, array.length, array); }
/** * Resolves all type variables in {@code type} and all downstream types and returns a * corresponding type with type variables resolved. */ public Type resolveType(Type type) { checkNotNull(type); if (type instanceof TypeVariable) { return typeTable.resolve((TypeVariable<?>) type); } else if (type instanceof ParameterizedType) { return resolveParameterizedType((ParameterizedType) type); } else if (type instanceof GenericArrayType) { return resolveGenericArrayType((GenericArrayType) type); } else if (type instanceof WildcardType) { WildcardType wildcardType = (WildcardType) type; return new Types.WildcardTypeImpl( resolveTypes(wildcardType.getLowerBounds()), resolveTypes(wildcardType.getUpperBounds())); } else { // if Class<?>, no resolution needed, we are done. return type; } }
/** * An implementation of run() that does not block the site thread. The Site has responsibility for * transactions that occur between schedulings of this task. */ @Override public void runForRejoin(SiteProcedureConnection siteConnection, TaskLog m_taskLog) throws IOException { RestoreWork rejoinWork = m_rejoinSiteProcessor.poll(m_snapshotBufferAllocator); if (rejoinWork != null) { restoreBlock(rejoinWork, siteConnection); } if (m_rejoinSiteProcessor.isEOF() == false) { m_taskQueue.offer(this); } else { REJOINLOG.debug(m_whoami + "Rejoin snapshot transfer is finished"); m_rejoinSiteProcessor.close(); Preconditions.checkNotNull(m_streamSnapshotMb); VoltDB.instance().getHostMessenger().removeMailbox(m_streamSnapshotMb.getHSId()); doFinishingTask(siteConnection); } }
Type capture(Type type) { checkNotNull(type); if (type instanceof Class) { return type; } if (type instanceof TypeVariable) { return type; } if (type instanceof GenericArrayType) { GenericArrayType arrayType = (GenericArrayType) type; return Types.newArrayType(capture(arrayType.getGenericComponentType())); } if (type instanceof ParameterizedType) { ParameterizedType parameterizedType = (ParameterizedType) type; return Types.newParameterizedTypeWithOwner( captureNullable(parameterizedType.getOwnerType()), (Class<?>) parameterizedType.getRawType(), capture(parameterizedType.getActualTypeArguments())); } if (type instanceof WildcardType) { WildcardType wildcardType = (WildcardType) type; Type[] lowerBounds = wildcardType.getLowerBounds(); if (lowerBounds.length == 0) { // ? extends something changes to capture-of Type[] upperBounds = wildcardType.getUpperBounds(); String name = "capture#" + id.incrementAndGet() + "-of ? extends " + Joiner.on('&').join(upperBounds); return Types.newTypeVariable(WildcardCapturer.class, name, wildcardType.getUpperBounds()); } else { // TODO(benyu): handle ? super T somehow. return type; } } throw new AssertionError("must have been one of the known types"); }
/** Creates a new instance that will read lines from the given {@code Readable} object. */ public LineReader(Readable readable) { Preconditions.checkNotNull(readable); this.readable = readable; this.reader = (readable instanceof Reader) ? (Reader) readable : null; }
protected SimpleForwardingLoadingCache(LoadingCache<K, V> delegate) { this.delegate = Preconditions.checkNotNull(delegate); }
/** * Returns the element at the specified position in an iterable. * * @param position position of the element to return * @return the element at the specified position in {@code iterable} * @throws IndexOutOfBoundsException if {@code position} is negative or greater than or equal to * the size of {@code iterable} */ public static <T> T get(Iterable<T> iterable, int position) { checkNotNull(iterable); return (iterable instanceof List) ? ((List<T>) iterable).get(position) : Iterators.get(iterable.iterator(), position); }