code
stringlengths
1
2.01M
repo_name
stringlengths
3
62
path
stringlengths
1
267
language
stringclasses
231 values
license
stringclasses
13 values
size
int64
1
2.01M
/* * Copyright (C) 2012 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import com.google.common.annotations.GwtCompatible; import com.google.common.base.Predicate; import java.util.Map.Entry; import java.util.Set; /** * Implementation of {@link Multimaps#filterEntries(SetMultimap, Predicate)}. * * @author Louis Wasserman */ @GwtCompatible final class FilteredEntrySetMultimap<K, V> extends FilteredEntryMultimap<K, V> implements FilteredSetMultimap<K, V> { FilteredEntrySetMultimap(SetMultimap<K, V> unfiltered, Predicate<? super Entry<K, V>> predicate) { super(unfiltered, predicate); } @Override public SetMultimap<K, V> unfiltered() { return (SetMultimap<K, V>) unfiltered; } @Override public Set<V> get(K key) { return (Set<V>) super.get(key); } @Override public Set<V> removeAll(Object key) { return (Set<V>) super.removeAll(key); } @Override public Set<V> replaceValues(K key, Iterable<? extends V> values) { return (Set<V>) super.replaceValues(key, values); } @Override Set<Entry<K, V>> createEntries() { return Sets.filter(unfiltered().entries(), entryPredicate()); } @Override public Set<Entry<K, V>> entries() { return (Set<Entry<K, V>>) super.entries(); } }
zzhhhhh-aw4rwer
guava/src/com/google/common/collect/FilteredEntrySetMultimap.java
Java
asf20
1,828
/* * Copyright (C) 2008 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import static com.google.common.base.Preconditions.checkState; import com.google.common.annotations.GwtCompatible; /** * Precondition checks useful in collection implementations. */ @GwtCompatible final class CollectPreconditions { static void checkEntryNotNull(Object key, Object value) { if (key == null) { throw new NullPointerException("null key in entry: null=" + value); } else if (value == null) { throw new NullPointerException("null value in entry: " + key + "=null"); } } static int checkNonnegative(int value, String name) { if (value < 0) { throw new IllegalArgumentException(name + " cannot be negative but was: " + value); } return value; } /** * Precondition tester for {@code Iterator.remove()} that throws an exception with a consistent * error message. */ static void checkRemove(boolean canRemove) { checkState(canRemove, "no calls to next() since the last call to remove()"); } }
zzhhhhh-aw4rwer
guava/src/com/google/common/collect/CollectPreconditions.java
Java
asf20
1,614
/* * Copyright (C) 2008 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; import com.google.common.annotations.Beta; import com.google.common.annotations.GwtCompatible; import com.google.common.base.Function; import com.google.common.base.Supplier; import java.io.Serializable; import java.util.Comparator; import java.util.Iterator; import java.util.Map; import java.util.NoSuchElementException; import java.util.Set; import java.util.SortedMap; import java.util.SortedSet; import java.util.TreeMap; import javax.annotation.Nullable; /** * Implementation of {@code Table} whose row keys and column keys are ordered * by their natural ordering or by supplied comparators. When constructing a * {@code TreeBasedTable}, you may provide comparators for the row keys and * the column keys, or you may use natural ordering for both. * * <p>The {@link #rowKeySet} method returns a {@link SortedSet} and the {@link * #rowMap} method returns a {@link SortedMap}, instead of the {@link Set} and * {@link Map} specified by the {@link Table} interface. * * <p>The views returned by {@link #column}, {@link #columnKeySet()}, and {@link * #columnMap()} have iterators that don't support {@code remove()}. Otherwise, * all optional operations are supported. Null row keys, columns keys, and * values are not supported. * * <p>Lookups by row key are often faster than lookups by column key, because * the data is stored in a {@code Map<R, Map<C, V>>}. A method call like {@code * column(columnKey).get(rowKey)} still runs quickly, since the row key is * provided. However, {@code column(columnKey).size()} takes longer, since an * iteration across all row keys occurs. * * <p>Because a {@code TreeBasedTable} has unique sorted values for a given * row, both {@code row(rowKey)} and {@code rowMap().get(rowKey)} are {@link * SortedMap} instances, instead of the {@link Map} specified in the {@link * Table} interface. * * <p>Note that this implementation is not synchronized. If multiple threads * access this table concurrently and one of the threads modifies the table, it * must be synchronized externally. * * <p>See the Guava User Guide article on <a href= * "http://code.google.com/p/guava-libraries/wiki/NewCollectionTypesExplained#Table"> * {@code Table}</a>. * * @author Jared Levy * @author Louis Wasserman * @since 7.0 */ @GwtCompatible(serializable = true) @Beta public class TreeBasedTable<R, C, V> extends StandardRowSortedTable<R, C, V> { private final Comparator<? super C> columnComparator; private static class Factory<C, V> implements Supplier<TreeMap<C, V>>, Serializable { final Comparator<? super C> comparator; Factory(Comparator<? super C> comparator) { this.comparator = comparator; } @Override public TreeMap<C, V> get() { return new TreeMap<C, V>(comparator); } private static final long serialVersionUID = 0; } /** * Creates an empty {@code TreeBasedTable} that uses the natural orderings * of both row and column keys. * * <p>The method signature specifies {@code R extends Comparable} with a raw * {@link Comparable}, instead of {@code R extends Comparable<? super R>}, * and the same for {@code C}. That's necessary to support classes defined * without generics. */ public static <R extends Comparable, C extends Comparable, V> TreeBasedTable<R, C, V> create() { return new TreeBasedTable<R, C, V>(Ordering.natural(), Ordering.natural()); } /** * Creates an empty {@code TreeBasedTable} that is ordered by the specified * comparators. * * @param rowComparator the comparator that orders the row keys * @param columnComparator the comparator that orders the column keys */ public static <R, C, V> TreeBasedTable<R, C, V> create( Comparator<? super R> rowComparator, Comparator<? super C> columnComparator) { checkNotNull(rowComparator); checkNotNull(columnComparator); return new TreeBasedTable<R, C, V>(rowComparator, columnComparator); } /** * Creates a {@code TreeBasedTable} with the same mappings and sort order * as the specified {@code TreeBasedTable}. */ public static <R, C, V> TreeBasedTable<R, C, V> create( TreeBasedTable<R, C, ? extends V> table) { TreeBasedTable<R, C, V> result = new TreeBasedTable<R, C, V>( table.rowComparator(), table.columnComparator()); result.putAll(table); return result; } TreeBasedTable(Comparator<? super R> rowComparator, Comparator<? super C> columnComparator) { super(new TreeMap<R, Map<C, V>>(rowComparator), new Factory<C, V>(columnComparator)); this.columnComparator = columnComparator; } // TODO(jlevy): Move to StandardRowSortedTable? /** * Returns the comparator that orders the rows. With natural ordering, * {@link Ordering#natural()} is returned. */ public Comparator<? super R> rowComparator() { return rowKeySet().comparator(); } /** * Returns the comparator that orders the columns. With natural ordering, * {@link Ordering#natural()} is returned. */ public Comparator<? super C> columnComparator() { return columnComparator; } // TODO(user): make column return a SortedMap /** * {@inheritDoc} * * <p>Because a {@code TreeBasedTable} has unique sorted values for a given * row, this method returns a {@link SortedMap}, instead of the {@link Map} * specified in the {@link Table} interface. * @since 10.0 * (<a href="http://code.google.com/p/guava-libraries/wiki/Compatibility" * >mostly source-compatible</a> since 7.0) */ @Override public SortedMap<C, V> row(R rowKey) { return new TreeRow(rowKey); } private class TreeRow extends Row implements SortedMap<C, V> { @Nullable final C lowerBound; @Nullable final C upperBound; TreeRow(R rowKey) { this(rowKey, null, null); } TreeRow(R rowKey, @Nullable C lowerBound, @Nullable C upperBound) { super(rowKey); this.lowerBound = lowerBound; this.upperBound = upperBound; checkArgument(lowerBound == null || upperBound == null || compare(lowerBound, upperBound) <= 0); } @Override public SortedSet<C> keySet() { return new Maps.SortedKeySet<C, V>(this); } @Override public Comparator<? super C> comparator() { return columnComparator(); } int compare(Object a, Object b) { // pretend we can compare anything @SuppressWarnings({"rawtypes", "unchecked"}) Comparator<Object> cmp = (Comparator) comparator(); return cmp.compare(a, b); } boolean rangeContains(@Nullable Object o) { return o != null && (lowerBound == null || compare(lowerBound, o) <= 0) && (upperBound == null || compare(upperBound, o) > 0); } @Override public SortedMap<C, V> subMap(C fromKey, C toKey) { checkArgument(rangeContains(checkNotNull(fromKey)) && rangeContains(checkNotNull(toKey))); return new TreeRow(rowKey, fromKey, toKey); } @Override public SortedMap<C, V> headMap(C toKey) { checkArgument(rangeContains(checkNotNull(toKey))); return new TreeRow(rowKey, lowerBound, toKey); } @Override public SortedMap<C, V> tailMap(C fromKey) { checkArgument(rangeContains(checkNotNull(fromKey))); return new TreeRow(rowKey, fromKey, upperBound); } @Override public C firstKey() { SortedMap<C, V> backing = backingRowMap(); if (backing == null) { throw new NoSuchElementException(); } return backingRowMap().firstKey(); } @Override public C lastKey() { SortedMap<C, V> backing = backingRowMap(); if (backing == null) { throw new NoSuchElementException(); } return backingRowMap().lastKey(); } transient SortedMap<C, V> wholeRow; /* * If the row was previously empty, we check if there's a new row here every * time we're queried. */ SortedMap<C, V> wholeRow() { if (wholeRow == null || (wholeRow.isEmpty() && backingMap.containsKey(rowKey))) { wholeRow = (SortedMap<C, V>) backingMap.get(rowKey); } return wholeRow; } @Override SortedMap<C, V> backingRowMap() { return (SortedMap<C, V>) super.backingRowMap(); } @Override SortedMap<C, V> computeBackingRowMap() { SortedMap<C, V> map = wholeRow(); if (map != null) { if (lowerBound != null) { map = map.tailMap(lowerBound); } if (upperBound != null) { map = map.headMap(upperBound); } return map; } return null; } @Override void maintainEmptyInvariant() { if (wholeRow() != null && wholeRow.isEmpty()) { backingMap.remove(rowKey); wholeRow = null; backingRowMap = null; } } @Override public boolean containsKey(Object key) { return rangeContains(key) && super.containsKey(key); } @Override public V put(C key, V value) { checkArgument(rangeContains(checkNotNull(key))); return super.put(key, value); } } // rowKeySet() and rowMap() are defined here so they appear in the Javadoc. @Override public SortedSet<R> rowKeySet() { return super.rowKeySet(); } @Override public SortedMap<R, Map<C, V>> rowMap() { return super.rowMap(); } /** * Overridden column iterator to return columns values in globally sorted * order. */ @Override Iterator<C> createColumnKeyIterator() { final Comparator<? super C> comparator = columnComparator(); final Iterator<C> merged = Iterators.mergeSorted(Iterables.transform(backingMap.values(), new Function<Map<C, V>, Iterator<C>>() { @Override public Iterator<C> apply(Map<C, V> input) { return input.keySet().iterator(); } }), comparator); return new AbstractIterator<C>() { C lastValue; @Override protected C computeNext() { while (merged.hasNext()) { C next = merged.next(); boolean duplicate = lastValue != null && comparator.compare(next, lastValue) == 0; // Keep looping till we find a non-duplicate value. if (!duplicate) { lastValue = next; return lastValue; } } lastValue = null; // clear reference to unused data return endOfData(); } }; } private static final long serialVersionUID = 0; }
zzhhhhh-aw4rwer
guava/src/com/google/common/collect/TreeBasedTable.java
Java
asf20
11,299
/* * Copyright (C) 2011 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.common.collect; import com.google.common.annotations.Beta; import com.google.common.base.Preconditions; import java.util.ArrayDeque; import java.util.Collection; import java.util.Deque; import java.util.PriorityQueue; import java.util.Queue; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.BlockingQueue; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.LinkedBlockingDeque; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.PriorityBlockingQueue; import java.util.concurrent.SynchronousQueue; import java.util.concurrent.TimeUnit; /** * Static utility methods pertaining to {@link Queue} and {@link Deque} instances. * Also see this class's counterparts {@link Lists}, {@link Sets}, and {@link Maps}. * * @author Kurt Alfred Kluever * @since 11.0 */ public final class Queues { private Queues() {} // ArrayBlockingQueue /** * Creates an empty {@code ArrayBlockingQueue} with the given (fixed) capacity * and nonfair access policy. */ public static <E> ArrayBlockingQueue<E> newArrayBlockingQueue(int capacity) { return new ArrayBlockingQueue<E>(capacity); } // ArrayDeque /** * Creates an empty {@code ArrayDeque}. * * @since 12.0 */ public static <E> ArrayDeque<E> newArrayDeque() { return new ArrayDeque<E>(); } /** * Creates an {@code ArrayDeque} containing the elements of the specified iterable, * in the order they are returned by the iterable's iterator. * * @since 12.0 */ public static <E> ArrayDeque<E> newArrayDeque(Iterable<? extends E> elements) { if (elements instanceof Collection) { return new ArrayDeque<E>(Collections2.cast(elements)); } ArrayDeque<E> deque = new ArrayDeque<E>(); Iterables.addAll(deque, elements); return deque; } // ConcurrentLinkedQueue /** * Creates an empty {@code ConcurrentLinkedQueue}. */ public static <E> ConcurrentLinkedQueue<E> newConcurrentLinkedQueue() { return new ConcurrentLinkedQueue<E>(); } /** * Creates a {@code ConcurrentLinkedQueue} containing the elements of the specified iterable, * in the order they are returned by the iterable's iterator. */ public static <E> ConcurrentLinkedQueue<E> newConcurrentLinkedQueue( Iterable<? extends E> elements) { if (elements instanceof Collection) { return new ConcurrentLinkedQueue<E>(Collections2.cast(elements)); } ConcurrentLinkedQueue<E> queue = new ConcurrentLinkedQueue<E>(); Iterables.addAll(queue, elements); return queue; } // LinkedBlockingDeque /** * Creates an empty {@code LinkedBlockingDeque} with a capacity of {@link Integer#MAX_VALUE}. * * @since 12.0 */ public static <E> LinkedBlockingDeque<E> newLinkedBlockingDeque() { return new LinkedBlockingDeque<E>(); } /** * Creates an empty {@code LinkedBlockingDeque} with the given (fixed) capacity. * * @throws IllegalArgumentException if {@code capacity} is less than 1 * @since 12.0 */ public static <E> LinkedBlockingDeque<E> newLinkedBlockingDeque(int capacity) { return new LinkedBlockingDeque<E>(capacity); } /** * Creates a {@code LinkedBlockingDeque} with a capacity of {@link Integer#MAX_VALUE}, * containing the elements of the specified iterable, * in the order they are returned by the iterable's iterator. * * @since 12.0 */ public static <E> LinkedBlockingDeque<E> newLinkedBlockingDeque(Iterable<? extends E> elements) { if (elements instanceof Collection) { return new LinkedBlockingDeque<E>(Collections2.cast(elements)); } LinkedBlockingDeque<E> deque = new LinkedBlockingDeque<E>(); Iterables.addAll(deque, elements); return deque; } // LinkedBlockingQueue /** * Creates an empty {@code LinkedBlockingQueue} with a capacity of {@link Integer#MAX_VALUE}. */ public static <E> LinkedBlockingQueue<E> newLinkedBlockingQueue() { return new LinkedBlockingQueue<E>(); } /** * Creates an empty {@code LinkedBlockingQueue} with the given (fixed) capacity. * * @throws IllegalArgumentException if {@code capacity} is less than 1 */ public static <E> LinkedBlockingQueue<E> newLinkedBlockingQueue(int capacity) { return new LinkedBlockingQueue<E>(capacity); } /** * Creates a {@code LinkedBlockingQueue} with a capacity of {@link Integer#MAX_VALUE}, * containing the elements of the specified iterable, * in the order they are returned by the iterable's iterator. * * @param elements the elements that the queue should contain, in order * @return a new {@code LinkedBlockingQueue} containing those elements */ public static <E> LinkedBlockingQueue<E> newLinkedBlockingQueue(Iterable<? extends E> elements) { if (elements instanceof Collection) { return new LinkedBlockingQueue<E>(Collections2.cast(elements)); } LinkedBlockingQueue<E> queue = new LinkedBlockingQueue<E>(); Iterables.addAll(queue, elements); return queue; } // LinkedList: see {@link com.google.common.collect.Lists} // PriorityBlockingQueue /** * Creates an empty {@code PriorityBlockingQueue} with the ordering given by its * elements' natural ordering. * * @since 11.0 (requires that {@code E} be {@code Comparable} since 15.0). */ public static <E extends Comparable> PriorityBlockingQueue<E> newPriorityBlockingQueue() { return new PriorityBlockingQueue<E>(); } /** * Creates a {@code PriorityBlockingQueue} containing the given elements. * * <b>Note:</b> If the specified iterable is a {@code SortedSet} or a {@code PriorityQueue}, * this priority queue will be ordered according to the same ordering. * * @since 11.0 (requires that {@code E} be {@code Comparable} since 15.0). */ public static <E extends Comparable> PriorityBlockingQueue<E> newPriorityBlockingQueue( Iterable<? extends E> elements) { if (elements instanceof Collection) { return new PriorityBlockingQueue<E>(Collections2.cast(elements)); } PriorityBlockingQueue<E> queue = new PriorityBlockingQueue<E>(); Iterables.addAll(queue, elements); return queue; } // PriorityQueue /** * Creates an empty {@code PriorityQueue} with the ordering given by its * elements' natural ordering. * * @since 11.0 (requires that {@code E} be {@code Comparable} since 15.0). */ public static <E extends Comparable> PriorityQueue<E> newPriorityQueue() { return new PriorityQueue<E>(); } /** * Creates a {@code PriorityQueue} containing the given elements. * * <b>Note:</b> If the specified iterable is a {@code SortedSet} or a {@code PriorityQueue}, * this priority queue will be ordered according to the same ordering. * * @since 11.0 (requires that {@code E} be {@code Comparable} since 15.0). */ public static <E extends Comparable> PriorityQueue<E> newPriorityQueue( Iterable<? extends E> elements) { if (elements instanceof Collection) { return new PriorityQueue<E>(Collections2.cast(elements)); } PriorityQueue<E> queue = new PriorityQueue<E>(); Iterables.addAll(queue, elements); return queue; } // SynchronousQueue /** * Creates an empty {@code SynchronousQueue} with nonfair access policy. */ public static <E> SynchronousQueue<E> newSynchronousQueue() { return new SynchronousQueue<E>(); } /** * Drains the queue as {@link BlockingQueue#drainTo(Collection, int)}, but if the requested * {@code numElements} elements are not available, it will wait for them up to the specified * timeout. * * @param q the blocking queue to be drained * @param buffer where to add the transferred elements * @param numElements the number of elements to be waited for * @param timeout how long to wait before giving up, in units of {@code unit} * @param unit a {@code TimeUnit} determining how to interpret the timeout parameter * @return the number of elements transferred * @throws InterruptedException if interrupted while waiting */ @Beta public static <E> int drain(BlockingQueue<E> q, Collection<? super E> buffer, int numElements, long timeout, TimeUnit unit) throws InterruptedException { Preconditions.checkNotNull(buffer); /* * This code performs one System.nanoTime() more than necessary, and in return, the time to * execute Queue#drainTo is not added *on top* of waiting for the timeout (which could make * the timeout arbitrarily inaccurate, given a queue that is slow to drain). */ long deadline = System.nanoTime() + unit.toNanos(timeout); int added = 0; while (added < numElements) { // we could rely solely on #poll, but #drainTo might be more efficient when there are multiple // elements already available (e.g. LinkedBlockingQueue#drainTo locks only once) added += q.drainTo(buffer, numElements - added); if (added < numElements) { // not enough elements immediately available; will have to poll E e = q.poll(deadline - System.nanoTime(), TimeUnit.NANOSECONDS); if (e == null) { break; // we already waited enough, and there are no more elements in sight } buffer.add(e); added++; } } return added; } /** * Drains the queue as {@linkplain #drain(BlockingQueue, Collection, int, long, TimeUnit)}, * but with a different behavior in case it is interrupted while waiting. In that case, the * operation will continue as usual, and in the end the thread's interruption status will be set * (no {@code InterruptedException} is thrown). * * @param q the blocking queue to be drained * @param buffer where to add the transferred elements * @param numElements the number of elements to be waited for * @param timeout how long to wait before giving up, in units of {@code unit} * @param unit a {@code TimeUnit} determining how to interpret the timeout parameter * @return the number of elements transferred */ @Beta public static <E> int drainUninterruptibly(BlockingQueue<E> q, Collection<? super E> buffer, int numElements, long timeout, TimeUnit unit) { Preconditions.checkNotNull(buffer); long deadline = System.nanoTime() + unit.toNanos(timeout); int added = 0; boolean interrupted = false; try { while (added < numElements) { // we could rely solely on #poll, but #drainTo might be more efficient when there are // multiple elements already available (e.g. LinkedBlockingQueue#drainTo locks only once) added += q.drainTo(buffer, numElements - added); if (added < numElements) { // not enough elements immediately available; will have to poll E e; // written exactly once, by a successful (uninterrupted) invocation of #poll while (true) { try { e = q.poll(deadline - System.nanoTime(), TimeUnit.NANOSECONDS); break; } catch (InterruptedException ex) { interrupted = true; // note interruption and retry } } if (e == null) { break; // we already waited enough, and there are no more elements in sight } buffer.add(e); added++; } } } finally { if (interrupted) { Thread.currentThread().interrupt(); } } return added; } /** * Returns a synchronized (thread-safe) queue backed by the specified queue. In order to * guarantee serial access, it is critical that <b>all</b> access to the backing queue is * accomplished through the returned queue. * * <p>It is imperative that the user manually synchronize on the returned queue when accessing * the queue's iterator: <pre> {@code * * Queue<E> queue = Queues.synchronizedQueue(MinMaxPriorityQueue.<E>create()); * ... * queue.add(element); // Needn't be in synchronized block * ... * synchronized (queue) { // Must synchronize on queue! * Iterator<E> i = queue.iterator(); // Must be in synchronized block * while (i.hasNext()) { * foo(i.next()); * } * }}</pre> * * <p>Failure to follow this advice may result in non-deterministic behavior. * * <p>The returned queue will be serializable if the specified queue is serializable. * * @param queue the queue to be wrapped in a synchronized view * @return a synchronized view of the specified queue * @since 14.0 */ @Beta public static <E> Queue<E> synchronizedQueue(Queue<E> queue) { return Synchronized.queue(queue, null); } /** * Returns a synchronized (thread-safe) deque backed by the specified deque. In order to * guarantee serial access, it is critical that <b>all</b> access to the backing deque is * accomplished through the returned deque. * * <p>It is imperative that the user manually synchronize on the returned deque when accessing * any of the deque's iterators: <pre> {@code * * Deque<E> deque = Queues.synchronizedDeque(Queues.<E>newArrayDeque()); * ... * deque.add(element); // Needn't be in synchronized block * ... * synchronized (deque) { // Must synchronize on deque! * Iterator<E> i = deque.iterator(); // Must be in synchronized block * while (i.hasNext()) { * foo(i.next()); * } * }}</pre> * * <p>Failure to follow this advice may result in non-deterministic behavior. * * <p>The returned deque will be serializable if the specified deque is serializable. * * @param deque the deque to be wrapped in a synchronized view * @return a synchronized view of the specified deque * @since 15.0 */ @Beta public static <E> Deque<E> synchronizedDeque(Deque<E> deque) { return Synchronized.deque(deque, null); } }
zzhhhhh-aw4rwer
guava/src/com/google/common/collect/Queues.java
Java
asf20
14,546
/* * Copyright (C) 2007 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Preconditions.checkState; import static com.google.common.base.Predicates.equalTo; import static com.google.common.base.Predicates.in; import static com.google.common.base.Predicates.instanceOf; import static com.google.common.base.Predicates.not; import static com.google.common.collect.CollectPreconditions.checkRemove; import com.google.common.annotations.Beta; import com.google.common.annotations.GwtCompatible; import com.google.common.annotations.GwtIncompatible; import com.google.common.base.Function; import com.google.common.base.Objects; import com.google.common.base.Optional; import com.google.common.base.Preconditions; import com.google.common.base.Predicate; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.Enumeration; import java.util.Iterator; import java.util.List; import java.util.ListIterator; import java.util.NoSuchElementException; import java.util.PriorityQueue; import java.util.Queue; import javax.annotation.Nullable; /** * This class contains static utility methods that operate on or return objects * of type {@link Iterator}. Except as noted, each method has a corresponding * {@link Iterable}-based method in the {@link Iterables} class. * * <p><i>Performance notes:</i> Unless otherwise noted, all of the iterators * produced in this class are <i>lazy</i>, which means that they only advance * the backing iteration when absolutely necessary. * * <p>See the Guava User Guide section on <a href= * "http://code.google.com/p/guava-libraries/wiki/CollectionUtilitiesExplained#Iterables"> * {@code Iterators}</a>. * * @author Kevin Bourrillion * @author Jared Levy * @since 2.0 (imported from Google Collections Library) */ @GwtCompatible(emulated = true) public final class Iterators { private Iterators() {} static final UnmodifiableListIterator<Object> EMPTY_LIST_ITERATOR = new UnmodifiableListIterator<Object>() { @Override public boolean hasNext() { return false; } @Override public Object next() { throw new NoSuchElementException(); } @Override public boolean hasPrevious() { return false; } @Override public Object previous() { throw new NoSuchElementException(); } @Override public int nextIndex() { return 0; } @Override public int previousIndex() { return -1; } }; /** * Returns the empty iterator. * * <p>The {@link Iterable} equivalent of this method is {@link * ImmutableSet#of()}. */ public static <T> UnmodifiableIterator<T> emptyIterator() { return emptyListIterator(); } /** * Returns the empty iterator. * * <p>The {@link Iterable} equivalent of this method is {@link * ImmutableSet#of()}. */ // Casting to any type is safe since there are no actual elements. @SuppressWarnings("unchecked") static <T> UnmodifiableListIterator<T> emptyListIterator() { return (UnmodifiableListIterator<T>) EMPTY_LIST_ITERATOR; } private static final Iterator<Object> EMPTY_MODIFIABLE_ITERATOR = new Iterator<Object>() { @Override public boolean hasNext() { return false; } @Override public Object next() { throw new NoSuchElementException(); } @Override public void remove() { checkRemove(false); } }; /** * Returns the empty {@code Iterator} that throws * {@link IllegalStateException} instead of * {@link UnsupportedOperationException} on a call to * {@link Iterator#remove()}. */ // Casting to any type is safe since there are no actual elements. @SuppressWarnings("unchecked") static <T> Iterator<T> emptyModifiableIterator() { return (Iterator<T>) EMPTY_MODIFIABLE_ITERATOR; } /** Returns an unmodifiable view of {@code iterator}. */ public static <T> UnmodifiableIterator<T> unmodifiableIterator( final Iterator<T> iterator) { checkNotNull(iterator); if (iterator instanceof UnmodifiableIterator) { return (UnmodifiableIterator<T>) iterator; } return new UnmodifiableIterator<T>() { @Override public boolean hasNext() { return iterator.hasNext(); } @Override public T next() { return iterator.next(); } }; } /** * Simply returns its argument. * * @deprecated no need to use this * @since 10.0 */ @Deprecated public static <T> UnmodifiableIterator<T> unmodifiableIterator( UnmodifiableIterator<T> iterator) { return checkNotNull(iterator); } /** * Returns the number of elements remaining in {@code iterator}. The iterator * will be left exhausted: its {@code hasNext()} method will return * {@code false}. */ public static int size(Iterator<?> iterator) { int count = 0; while (iterator.hasNext()) { iterator.next(); count++; } return count; } /** * Returns {@code true} if {@code iterator} contains {@code element}. */ public static boolean contains(Iterator<?> iterator, @Nullable Object element) { return any(iterator, equalTo(element)); } /** * Traverses an iterator and removes every element that belongs to the * provided collection. The iterator will be left exhausted: its * {@code hasNext()} method will return {@code false}. * * @param removeFrom the iterator to (potentially) remove elements from * @param elementsToRemove the elements to remove * @return {@code true} if any element was removed from {@code iterator} */ public static boolean removeAll( Iterator<?> removeFrom, Collection<?> elementsToRemove) { return removeIf(removeFrom, in(elementsToRemove)); } /** * Removes every element that satisfies the provided predicate from the * iterator. The iterator will be left exhausted: its {@code hasNext()} * method will return {@code false}. * * @param removeFrom the iterator to (potentially) remove elements from * @param predicate a predicate that determines whether an element should * be removed * @return {@code true} if any elements were removed from the iterator * @since 2.0 */ public static <T> boolean removeIf( Iterator<T> removeFrom, Predicate<? super T> predicate) { checkNotNull(predicate); boolean modified = false; while (removeFrom.hasNext()) { if (predicate.apply(removeFrom.next())) { removeFrom.remove(); modified = true; } } return modified; } /** * Traverses an iterator and removes every element that does not belong to the * provided collection. The iterator will be left exhausted: its * {@code hasNext()} method will return {@code false}. * * @param removeFrom the iterator to (potentially) remove elements from * @param elementsToRetain the elements to retain * @return {@code true} if any element was removed from {@code iterator} */ public static boolean retainAll( Iterator<?> removeFrom, Collection<?> elementsToRetain) { return removeIf(removeFrom, not(in(elementsToRetain))); } /** * Determines whether two iterators contain equal elements in the same order. * More specifically, this method returns {@code true} if {@code iterator1} * and {@code iterator2} contain the same number of elements and every element * of {@code iterator1} is equal to the corresponding element of * {@code iterator2}. * * <p>Note that this will modify the supplied iterators, since they will have * been advanced some number of elements forward. */ public static boolean elementsEqual( Iterator<?> iterator1, Iterator<?> iterator2) { while (iterator1.hasNext()) { if (!iterator2.hasNext()) { return false; } Object o1 = iterator1.next(); Object o2 = iterator2.next(); if (!Objects.equal(o1, o2)) { return false; } } return !iterator2.hasNext(); } /** * Returns a string representation of {@code iterator}, with the format * {@code [e1, e2, ..., en]}. The iterator will be left exhausted: its * {@code hasNext()} method will return {@code false}. */ public static String toString(Iterator<?> iterator) { return Collections2.STANDARD_JOINER .appendTo(new StringBuilder().append('['), iterator) .append(']') .toString(); } /** * Returns the single element contained in {@code iterator}. * * @throws NoSuchElementException if the iterator is empty * @throws IllegalArgumentException if the iterator contains multiple * elements. The state of the iterator is unspecified. */ public static <T> T getOnlyElement(Iterator<T> iterator) { T first = iterator.next(); if (!iterator.hasNext()) { return first; } StringBuilder sb = new StringBuilder(); sb.append("expected one element but was: <" + first); for (int i = 0; i < 4 && iterator.hasNext(); i++) { sb.append(", " + iterator.next()); } if (iterator.hasNext()) { sb.append(", ..."); } sb.append('>'); throw new IllegalArgumentException(sb.toString()); } /** * Returns the single element contained in {@code iterator}, or {@code * defaultValue} if the iterator is empty. * * @throws IllegalArgumentException if the iterator contains multiple * elements. The state of the iterator is unspecified. */ @Nullable public static <T> T getOnlyElement(Iterator<? extends T> iterator, @Nullable T defaultValue) { return iterator.hasNext() ? getOnlyElement(iterator) : defaultValue; } /** * Copies an iterator's elements into an array. The iterator will be left * exhausted: its {@code hasNext()} method will return {@code false}. * * @param iterator the iterator to copy * @param type the type of the elements * @return a newly-allocated array into which all the elements of the iterator * have been copied */ @GwtIncompatible("Array.newInstance(Class, int)") public static <T> T[] toArray( Iterator<? extends T> iterator, Class<T> type) { List<T> list = Lists.newArrayList(iterator); return Iterables.toArray(list, type); } /** * Adds all elements in {@code iterator} to {@code collection}. The iterator * will be left exhausted: its {@code hasNext()} method will return * {@code false}. * * @return {@code true} if {@code collection} was modified as a result of this * operation */ public static <T> boolean addAll( Collection<T> addTo, Iterator<? extends T> iterator) { checkNotNull(addTo); checkNotNull(iterator); boolean wasModified = false; while (iterator.hasNext()) { wasModified |= addTo.add(iterator.next()); } return wasModified; } /** * Returns the number of elements in the specified iterator that equal the * specified object. The iterator will be left exhausted: its * {@code hasNext()} method will return {@code false}. * * @see Collections#frequency */ public static int frequency(Iterator<?> iterator, @Nullable Object element) { return size(filter(iterator, equalTo(element))); } /** * Returns an iterator that cycles indefinitely over the elements of {@code * iterable}. * * <p>The returned iterator supports {@code remove()} if the provided 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. */ public static <T> Iterator<T> cycle(final Iterable<T> iterable) { checkNotNull(iterable); return new Iterator<T>() { Iterator<T> iterator = emptyIterator(); Iterator<T> removeFrom; @Override public boolean hasNext() { if (!iterator.hasNext()) { iterator = iterable.iterator(); } return iterator.hasNext(); } @Override public T next() { if (!hasNext()) { throw new NoSuchElementException(); } removeFrom = iterator; return iterator.next(); } @Override public void remove() { checkRemove(removeFrom != null); removeFrom.remove(); removeFrom = null; } }; } /** * Returns an iterator that cycles indefinitely over the provided elements. * * <p>The returned iterator supports {@code remove()}. After {@code remove()} * is called, subsequent cycles omit the removed * element, but {@code elements} does not change. The iterator's * {@code hasNext()} method returns {@code true} until all of the original * elements have been removed. * * <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. */ public static <T> Iterator<T> cycle(T... elements) { return cycle(Lists.newArrayList(elements)); } /** * Combines two iterators into a single iterator. The returned iterator * iterates across the elements in {@code a}, followed by the elements in * {@code b}. The source iterators are not polled until necessary. * * <p>The returned iterator supports {@code remove()} when the corresponding * input iterator supports it. * * <p><b>Note:</b> the current implementation is not suitable for nested * concatenated iterators, i.e. the following should be avoided when in a loop: * {@code iterator = Iterators.concat(iterator, suffix);}, since iteration over the * resulting iterator has a cubic complexity to the depth of the nesting. */ public static <T> Iterator<T> concat(Iterator<? extends T> a, Iterator<? extends T> b) { return concat(ImmutableList.of(a, b).iterator()); } /** * Combines three iterators into a single iterator. The returned iterator * iterates across the elements in {@code a}, followed by the elements in * {@code b}, followed by the elements in {@code c}. The source iterators * are not polled until necessary. * * <p>The returned iterator supports {@code remove()} when the corresponding * input iterator supports it. * * <p><b>Note:</b> the current implementation is not suitable for nested * concatenated iterators, i.e. the following should be avoided when in a loop: * {@code iterator = Iterators.concat(iterator, suffix);}, since iteration over the * resulting iterator has a cubic complexity to the depth of the nesting. */ public static <T> Iterator<T> concat(Iterator<? extends T> a, Iterator<? extends T> b, Iterator<? extends T> c) { return concat(ImmutableList.of(a, b, c).iterator()); } /** * Combines four iterators into a single iterator. The returned iterator * iterates across the elements in {@code a}, followed by the elements in * {@code b}, followed by the elements in {@code c}, followed by the elements * in {@code d}. The source iterators are not polled until necessary. * * <p>The returned iterator supports {@code remove()} when the corresponding * input iterator supports it. * * <p><b>Note:</b> the current implementation is not suitable for nested * concatenated iterators, i.e. the following should be avoided when in a loop: * {@code iterator = Iterators.concat(iterator, suffix);}, since iteration over the * resulting iterator has a cubic complexity to the depth of the nesting. */ public static <T> Iterator<T> concat(Iterator<? extends T> a, Iterator<? extends T> b, Iterator<? extends T> c, Iterator<? extends T> d) { return concat(ImmutableList.of(a, b, c, d).iterator()); } /** * Combines multiple iterators into a single iterator. The returned iterator * iterates across the elements of each iterator in {@code inputs}. The input * iterators are not polled until necessary. * * <p>The returned iterator supports {@code remove()} when the corresponding * input iterator supports it. * * <p><b>Note:</b> the current implementation is not suitable for nested * concatenated iterators, i.e. the following should be avoided when in a loop: * {@code iterator = Iterators.concat(iterator, suffix);}, since iteration over the * resulting iterator has a cubic complexity to the depth of the nesting. * * @throws NullPointerException if any of the provided iterators is null */ public static <T> Iterator<T> concat(Iterator<? extends T>... inputs) { return concat(ImmutableList.copyOf(inputs).iterator()); } /** * Combines multiple iterators into a single iterator. The returned iterator * iterates across the elements of each iterator in {@code inputs}. The input * iterators are not polled until necessary. * * <p>The returned iterator supports {@code remove()} when the corresponding * input iterator supports it. The methods of the returned iterator may throw * {@code NullPointerException} if any of the input iterators is null. * * <p><b>Note:</b> the current implementation is not suitable for nested * concatenated iterators, i.e. the following should be avoided when in a loop: * {@code iterator = Iterators.concat(iterator, suffix);}, since iteration over the * resulting iterator has a cubic complexity to the depth of the nesting. */ public static <T> Iterator<T> concat( final Iterator<? extends Iterator<? extends T>> inputs) { checkNotNull(inputs); return new Iterator<T>() { Iterator<? extends T> current = emptyIterator(); Iterator<? extends T> removeFrom; @Override public boolean hasNext() { // http://code.google.com/p/google-collections/issues/detail?id=151 // current.hasNext() might be relatively expensive, worth minimizing. boolean currentHasNext; // checkNotNull eager for GWT // note: it must be here & not where 'current' is assigned, // because otherwise we'll have called inputs.next() before throwing // the first NPE, and the next time around we'll call inputs.next() // again, incorrectly moving beyond the error. while (!(currentHasNext = checkNotNull(current).hasNext()) && inputs.hasNext()) { current = inputs.next(); } return currentHasNext; } @Override public T next() { if (!hasNext()) { throw new NoSuchElementException(); } removeFrom = current; return current.next(); } @Override public void remove() { checkRemove(removeFrom != null); removeFrom.remove(); removeFrom = null; } }; } /** * Divides an iterator into unmodifiable sublists of the given size (the final * list may be smaller). For example, partitioning an iterator containing * {@code [a, b, c, d, e]} with a partition size of 3 yields {@code * [[a, b, c], [d, e]]} -- an outer iterator containing two inner lists of * three and two elements, all in the original order. * * <p>The returned lists implement {@link java.util.RandomAccess}. * * @param iterator the iterator to return a partitioned view of * @param size the desired size of each partition (the last may be smaller) * @return an iterator of immutable lists containing the elements of {@code * iterator} divided into partitions * @throws IllegalArgumentException if {@code size} is nonpositive */ public static <T> UnmodifiableIterator<List<T>> partition( Iterator<T> iterator, int size) { return partitionImpl(iterator, size, false); } /** * Divides an iterator into unmodifiable sublists of the given size, padding * the final iterator with null values if necessary. For example, partitioning * an iterator containing {@code [a, b, c, d, e]} with a partition size of 3 * yields {@code [[a, b, c], [d, e, null]]} -- an outer iterator containing * two inner lists of three elements each, all in the original order. * * <p>The returned lists implement {@link java.util.RandomAccess}. * * @param iterator the iterator to return a partitioned view of * @param size the desired size of each partition * @return an iterator of immutable lists containing the elements of {@code * iterator} divided into partitions (the final iterable may have * trailing null elements) * @throws IllegalArgumentException if {@code size} is nonpositive */ public static <T> UnmodifiableIterator<List<T>> paddedPartition( Iterator<T> iterator, int size) { return partitionImpl(iterator, size, true); } private static <T> UnmodifiableIterator<List<T>> partitionImpl( final Iterator<T> iterator, final int size, final boolean pad) { checkNotNull(iterator); checkArgument(size > 0); return new UnmodifiableIterator<List<T>>() { @Override public boolean hasNext() { return iterator.hasNext(); } @Override public List<T> next() { if (!hasNext()) { throw new NoSuchElementException(); } Object[] array = new Object[size]; int count = 0; for (; count < size && iterator.hasNext(); count++) { array[count] = iterator.next(); } for (int i = count; i < size; i++) { array[i] = null; // for GWT } @SuppressWarnings("unchecked") // we only put Ts in it List<T> list = Collections.unmodifiableList( (List<T>) Arrays.asList(array)); return (pad || count == size) ? list : list.subList(0, count); } }; } /** * Returns the elements of {@code unfiltered} that satisfy a predicate. */ public static <T> UnmodifiableIterator<T> filter( final Iterator<T> unfiltered, final Predicate<? super T> predicate) { checkNotNull(unfiltered); checkNotNull(predicate); return new AbstractIterator<T>() { @Override protected T computeNext() { while (unfiltered.hasNext()) { T element = unfiltered.next(); if (predicate.apply(element)) { return element; } } return endOfData(); } }; } /** * Returns all instances of class {@code type} in {@code unfiltered}. The * returned iterator has elements whose class is {@code type} or a subclass of * {@code type}. * * @param unfiltered an iterator containing objects of any type * @param type the type of elements desired * @return an unmodifiable iterator containing all elements of the original * iterator that were of the requested type */ @SuppressWarnings("unchecked") // can cast to <T> because non-Ts are removed @GwtIncompatible("Class.isInstance") public static <T> UnmodifiableIterator<T> filter( Iterator<?> unfiltered, Class<T> type) { return (UnmodifiableIterator<T>) filter(unfiltered, instanceOf(type)); } /** * Returns {@code true} if one or more elements returned by {@code iterator} * satisfy the given predicate. */ public static <T> boolean any( Iterator<T> iterator, Predicate<? super T> predicate) { return indexOf(iterator, predicate) != -1; } /** * Returns {@code true} if every element returned by {@code iterator} * satisfies the given predicate. If {@code iterator} is empty, {@code true} * is returned. */ public static <T> boolean all( Iterator<T> iterator, Predicate<? super T> predicate) { checkNotNull(predicate); while (iterator.hasNext()) { T element = iterator.next(); if (!predicate.apply(element)) { return false; } } return true; } /** * Returns the first element in {@code iterator} that satisfies the given * predicate; use this method only when such an element is known to exist. If * no such element is found, the iterator will be left exhausted: its {@code * hasNext()} method will return {@code false}. If it is possible that * <i>no</i> element will match, use {@link #tryFind} or {@link * #find(Iterator, Predicate, Object)} instead. * * @throws NoSuchElementException if no element in {@code iterator} matches * the given predicate */ public static <T> T find( Iterator<T> iterator, Predicate<? super T> predicate) { return filter(iterator, predicate).next(); } /** * Returns the first element in {@code iterator} that satisfies the given * predicate. If no such element is found, {@code defaultValue} will be * returned from this method and the iterator will be left exhausted: its * {@code hasNext()} method will return {@code false}. Note that this can * usually be handled more naturally using {@code * tryFind(iterator, predicate).or(defaultValue)}. * * @since 7.0 */ @Nullable public static <T> T find(Iterator<? extends T> iterator, Predicate<? super T> predicate, @Nullable T defaultValue) { return getNext(filter(iterator, predicate), defaultValue); } /** * Returns an {@link Optional} containing the first element in {@code * iterator} that satisfies the given predicate, if such an element exists. If * no such element is found, an empty {@link Optional} will be returned from * this method and the iterator will be left exhausted: its {@code * hasNext()} method will return {@code false}. * * <p><b>Warning:</b> avoid using a {@code predicate} that matches {@code * null}. If {@code null} is matched in {@code iterator}, a * NullPointerException will be thrown. * * @since 11.0 */ public static <T> Optional<T> tryFind( Iterator<T> iterator, Predicate<? super T> predicate) { UnmodifiableIterator<T> filteredIterator = filter(iterator, predicate); return filteredIterator.hasNext() ? Optional.of(filteredIterator.next()) : Optional.<T>absent(); } /** * Returns the index in {@code iterator} of the first element that satisfies * the provided {@code predicate}, or {@code -1} if the Iterator has no such * elements. * * <p>More formally, returns the lowest index {@code i} such that * {@code predicate.apply(Iterators.get(iterator, i))} returns {@code true}, * or {@code -1} if there is no such index. * * <p>If -1 is returned, the iterator will be left exhausted: its * {@code hasNext()} method will return {@code false}. Otherwise, * the iterator will be set to the element which satisfies the * {@code predicate}. * * @since 2.0 */ public static <T> int indexOf( Iterator<T> iterator, Predicate<? super T> predicate) { checkNotNull(predicate, "predicate"); for (int i = 0; iterator.hasNext(); i++) { T current = iterator.next(); if (predicate.apply(current)) { return i; } } return -1; } /** * Returns an iterator that applies {@code function} to each element of {@code * fromIterator}. * * <p>The returned iterator supports {@code remove()} if the provided iterator * does. After a successful {@code remove()} call, {@code fromIterator} no * longer contains the corresponding element. */ public static <F, T> Iterator<T> transform(final Iterator<F> fromIterator, final Function<? super F, ? extends T> function) { checkNotNull(function); return new TransformedIterator<F, T>(fromIterator) { @Override T transform(F from) { return function.apply(from); } }; } /** * Advances {@code iterator} {@code position + 1} times, returning the * element at the {@code position}th position. * * @param position position of the element to return * @return the element at the specified position in {@code iterator} * @throws IndexOutOfBoundsException if {@code position} is negative or * greater than or equal to the number of elements remaining in * {@code iterator} */ public static <T> T get(Iterator<T> iterator, int position) { checkNonnegative(position); int skipped = advance(iterator, position); if (!iterator.hasNext()) { throw new IndexOutOfBoundsException("position (" + position + ") must be less than the number of elements that remained (" + skipped + ")"); } return iterator.next(); } static void checkNonnegative(int position) { if (position < 0) { throw new IndexOutOfBoundsException("position (" + position + ") must not be negative"); } } /** * Advances {@code iterator} {@code position + 1} times, returning the * element at the {@code position}th position or {@code defaultValue} * otherwise. * * @param position position of the element to return * @param defaultValue the default value to return if the iterator is empty * or if {@code position} is greater than the number of elements * remaining in {@code iterator} * @return the element at the specified position in {@code iterator} or * {@code defaultValue} if {@code iterator} produces fewer than * {@code position + 1} elements. * @throws IndexOutOfBoundsException if {@code position} is negative * @since 4.0 */ @Nullable public static <T> T get(Iterator<? extends T> iterator, int position, @Nullable T defaultValue) { checkNonnegative(position); advance(iterator, position); return getNext(iterator, defaultValue); } /** * Returns the next element in {@code iterator} or {@code defaultValue} if * the iterator is empty. The {@link Iterables} analog to this method is * {@link Iterables#getFirst}. * * @param defaultValue the default value to return if the iterator is empty * @return the next element of {@code iterator} or the default value * @since 7.0 */ @Nullable public static <T> T getNext(Iterator<? extends T> iterator, @Nullable T defaultValue) { return iterator.hasNext() ? iterator.next() : defaultValue; } /** * Advances {@code iterator} to the end, returning the last element. * * @return the last element of {@code iterator} * @throws NoSuchElementException if the iterator is empty */ public static <T> T getLast(Iterator<T> iterator) { while (true) { T current = iterator.next(); if (!iterator.hasNext()) { return current; } } } /** * Advances {@code iterator} to the end, returning the last element or * {@code defaultValue} if the iterator is empty. * * @param defaultValue the default value to return if the iterator is empty * @return the last element of {@code iterator} * @since 3.0 */ @Nullable public static <T> T getLast(Iterator<? extends T> iterator, @Nullable T defaultValue) { return iterator.hasNext() ? getLast(iterator) : defaultValue; } /** * Calls {@code next()} on {@code iterator}, either {@code numberToAdvance} times * or until {@code hasNext()} returns {@code false}, whichever comes first. * * @return the number of elements the iterator was advanced * @since 13.0 (since 3.0 as {@code Iterators.skip}) */ public static int advance(Iterator<?> iterator, int numberToAdvance) { checkNotNull(iterator); checkArgument(numberToAdvance >= 0, "numberToAdvance must be nonnegative"); int i; for (i = 0; i < numberToAdvance && iterator.hasNext(); i++) { iterator.next(); } return i; } /** * Creates an iterator returning the first {@code limitSize} elements of the * given iterator. If the original iterator does not contain that many * elements, the returned iterator will have the same behavior as the original * iterator. The returned iterator supports {@code remove()} if the original * iterator does. * * @param iterator the iterator to limit * @param limitSize the maximum number of elements in the returned iterator * @throws IllegalArgumentException if {@code limitSize} is negative * @since 3.0 */ public static <T> Iterator<T> limit( final Iterator<T> iterator, final int limitSize) { checkNotNull(iterator); checkArgument(limitSize >= 0, "limit is negative"); return new Iterator<T>() { private int count; @Override public boolean hasNext() { return count < limitSize && iterator.hasNext(); } @Override public T next() { if (!hasNext()) { throw new NoSuchElementException(); } count++; return iterator.next(); } @Override public void remove() { iterator.remove(); } }; } /** * Returns a view of the supplied {@code iterator} that removes each element * from the supplied {@code iterator} as it is returned. * * <p>The provided iterator must support {@link Iterator#remove()} or * else the returned iterator will fail on the first call to {@code * next}. * * @param iterator the iterator to remove and return elements from * @return an iterator that removes and returns elements from the * supplied iterator * @since 2.0 */ public static <T> Iterator<T> consumingIterator(final Iterator<T> iterator) { checkNotNull(iterator); return new UnmodifiableIterator<T>() { @Override public boolean hasNext() { return iterator.hasNext(); } @Override public T next() { T next = iterator.next(); iterator.remove(); return next; } @Override public String toString() { return "Iterators.consumingIterator(...)"; } }; } /** * Deletes and returns the next value from the iterator, or returns * {@code null} if there is no such value. */ @Nullable static <T> T pollNext(Iterator<T> iterator) { if (iterator.hasNext()) { T result = iterator.next(); iterator.remove(); return result; } else { return null; } } // Methods only in Iterators, not in Iterables /** * Clears the iterator using its remove method. */ static void clear(Iterator<?> iterator) { checkNotNull(iterator); while (iterator.hasNext()) { iterator.next(); iterator.remove(); } } /** * Returns an iterator containing the elements of {@code array} in order. The * returned iterator is a view of the array; subsequent changes to the array * will be reflected in the iterator. * * <p><b>Note:</b> It is often preferable to represent your data using a * collection type, for example using {@link Arrays#asList(Object[])}, making * this method unnecessary. * * <p>The {@code Iterable} equivalent of this method is either {@link * Arrays#asList(Object[])}, {@link ImmutableList#copyOf(Object[])}}, * or {@link ImmutableList#of}. */ public static <T> UnmodifiableIterator<T> forArray(final T... array) { return forArray(array, 0, array.length, 0); } /** * Returns a list iterator containing the elements in the specified range of * {@code array} in order, starting at the specified index. * * <p>The {@code Iterable} equivalent of this method is {@code * Arrays.asList(array).subList(offset, offset + length).listIterator(index)}. */ static <T> UnmodifiableListIterator<T> forArray( final T[] array, final int offset, int length, int index) { checkArgument(length >= 0); int end = offset + length; // Technically we should give a slightly more descriptive error on overflow Preconditions.checkPositionIndexes(offset, end, array.length); Preconditions.checkPositionIndex(index, length); if (length == 0) { return emptyListIterator(); } /* * We can't use call the two-arg constructor with arguments (offset, end) * because the returned Iterator is a ListIterator that may be moved back * past the beginning of the iteration. */ return new AbstractIndexedListIterator<T>(length, index) { @Override protected T get(int index) { return array[offset + index]; } }; } /** * Returns an iterator containing only {@code value}. * * <p>The {@link Iterable} equivalent of this method is {@link * Collections#singleton}. */ public static <T> UnmodifiableIterator<T> singletonIterator( @Nullable final T value) { return new UnmodifiableIterator<T>() { boolean done; @Override public boolean hasNext() { return !done; } @Override public T next() { if (done) { throw new NoSuchElementException(); } done = true; return value; } }; } /** * Adapts an {@code Enumeration} to the {@code Iterator} interface. * * <p>This method has no equivalent in {@link Iterables} because viewing an * {@code Enumeration} as an {@code Iterable} is impossible. However, the * contents can be <i>copied</i> into a collection using {@link * Collections#list}. */ public static <T> UnmodifiableIterator<T> forEnumeration( final Enumeration<T> enumeration) { checkNotNull(enumeration); return new UnmodifiableIterator<T>() { @Override public boolean hasNext() { return enumeration.hasMoreElements(); } @Override public T next() { return enumeration.nextElement(); } }; } /** * Adapts an {@code Iterator} to the {@code Enumeration} interface. * * <p>The {@code Iterable} equivalent of this method is either {@link * Collections#enumeration} (if you have a {@link Collection}), or * {@code Iterators.asEnumeration(collection.iterator())}. */ public static <T> Enumeration<T> asEnumeration(final Iterator<T> iterator) { checkNotNull(iterator); return new Enumeration<T>() { @Override public boolean hasMoreElements() { return iterator.hasNext(); } @Override public T nextElement() { return iterator.next(); } }; } /** * Implementation of PeekingIterator that avoids peeking unless necessary. */ private static class PeekingImpl<E> implements PeekingIterator<E> { private final Iterator<? extends E> iterator; private boolean hasPeeked; private E peekedElement; public PeekingImpl(Iterator<? extends E> iterator) { this.iterator = checkNotNull(iterator); } @Override public boolean hasNext() { return hasPeeked || iterator.hasNext(); } @Override public E next() { if (!hasPeeked) { return iterator.next(); } E result = peekedElement; hasPeeked = false; peekedElement = null; return result; } @Override public void remove() { checkState(!hasPeeked, "Can't remove after you've peeked at next"); iterator.remove(); } @Override public E peek() { if (!hasPeeked) { peekedElement = iterator.next(); hasPeeked = true; } return peekedElement; } } /** * Returns a {@code PeekingIterator} backed by the given iterator. * * <p>Calls to the {@code peek} method with no intervening calls to {@code * next} do not affect the iteration, and hence return the same object each * time. A subsequent call to {@code next} is guaranteed to return the same * object again. For example: <pre> {@code * * PeekingIterator<String> peekingIterator = * Iterators.peekingIterator(Iterators.forArray("a", "b")); * String a1 = peekingIterator.peek(); // returns "a" * String a2 = peekingIterator.peek(); // also returns "a" * String a3 = peekingIterator.next(); // also returns "a"}</pre> * * <p>Any structural changes to the underlying iteration (aside from those * performed by the iterator's own {@link PeekingIterator#remove()} method) * will leave the iterator in an undefined state. * * <p>The returned iterator does not support removal after peeking, as * explained by {@link PeekingIterator#remove()}. * * <p>Note: If the given iterator is already a {@code PeekingIterator}, * it <i>might</i> be returned to the caller, although this is neither * guaranteed to occur nor required to be consistent. For example, this * method <i>might</i> choose to pass through recognized implementations of * {@code PeekingIterator} when the behavior of the implementation is * known to meet the contract guaranteed by this method. * * <p>There is no {@link Iterable} equivalent to this method, so use this * method to wrap each individual iterator as it is generated. * * @param iterator the backing iterator. The {@link PeekingIterator} assumes * ownership of this iterator, so users should cease making direct calls * to it after calling this method. * @return a peeking iterator backed by that iterator. Apart from the * additional {@link PeekingIterator#peek()} method, this iterator behaves * exactly the same as {@code iterator}. */ public static <T> PeekingIterator<T> peekingIterator( Iterator<? extends T> iterator) { if (iterator instanceof PeekingImpl) { // Safe to cast <? extends T> to <T> because PeekingImpl only uses T // covariantly (and cannot be subclassed to add non-covariant uses). @SuppressWarnings("unchecked") PeekingImpl<T> peeking = (PeekingImpl<T>) iterator; return peeking; } return new PeekingImpl<T>(iterator); } /** * Simply returns its argument. * * @deprecated no need to use this * @since 10.0 */ @Deprecated public static <T> PeekingIterator<T> peekingIterator( PeekingIterator<T> iterator) { return checkNotNull(iterator); } /** * Returns an iterator over the merged contents of all given * {@code iterators}, traversing every element of the input iterators. * Equivalent entries will not be de-duplicated. * * <p>Callers must ensure that the source {@code iterators} are in * non-descending order as this method does not sort its input. * * <p>For any equivalent elements across all {@code iterators}, it is * undefined which element is returned first. * * @since 11.0 */ @Beta public static <T> UnmodifiableIterator<T> mergeSorted( Iterable<? extends Iterator<? extends T>> iterators, Comparator<? super T> comparator) { checkNotNull(iterators, "iterators"); checkNotNull(comparator, "comparator"); return new MergingIterator<T>(iterators, comparator); } /** * An iterator that performs a lazy N-way merge, calculating the next value * each time the iterator is polled. This amortizes the sorting cost over the * iteration and requires less memory than sorting all elements at once. * * <p>Retrieving a single element takes approximately O(log(M)) time, where M * is the number of iterators. (Retrieving all elements takes approximately * O(N*log(M)) time, where N is the total number of elements.) */ private static class MergingIterator<T> extends UnmodifiableIterator<T> { final Queue<PeekingIterator<T>> queue; public MergingIterator(Iterable<? extends Iterator<? extends T>> iterators, final Comparator<? super T> itemComparator) { // A comparator that's used by the heap, allowing the heap // to be sorted based on the top of each iterator. Comparator<PeekingIterator<T>> heapComparator = new Comparator<PeekingIterator<T>>() { @Override public int compare(PeekingIterator<T> o1, PeekingIterator<T> o2) { return itemComparator.compare(o1.peek(), o2.peek()); } }; queue = new PriorityQueue<PeekingIterator<T>>(2, heapComparator); for (Iterator<? extends T> iterator : iterators) { if (iterator.hasNext()) { queue.add(Iterators.peekingIterator(iterator)); } } } @Override public boolean hasNext() { return !queue.isEmpty(); } @Override public T next() { PeekingIterator<T> nextIter = queue.remove(); T next = nextIter.next(); if (nextIter.hasNext()) { queue.add(nextIter); } return next; } } /** * Used to avoid http://bugs.sun.com/view_bug.do?bug_id=6558557 */ static <T> ListIterator<T> cast(Iterator<T> iterator) { return (ListIterator<T>) iterator; } }
zzhhhhh-aw4rwer
guava/src/com/google/common/collect/Iterators.java
Java
asf20
45,571
/* * Copyright (C) 2010 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import com.google.common.annotations.GwtCompatible; import java.util.List; import javax.annotation.Nullable; /** * A list multimap which forwards all its method calls to another list multimap. * Subclasses should override one or more methods to modify the behavior of * the backing multimap as desired per the <a * href="http://en.wikipedia.org/wiki/Decorator_pattern">decorator pattern</a>. * * @author Kurt Alfred Kluever * @since 3.0 */ @GwtCompatible public abstract class ForwardingListMultimap<K, V> extends ForwardingMultimap<K, V> implements ListMultimap<K, V> { /** Constructor for use by subclasses. */ protected ForwardingListMultimap() {} @Override protected abstract ListMultimap<K, V> delegate(); @Override public List<V> get(@Nullable K key) { return delegate().get(key); } @Override public List<V> removeAll(@Nullable Object key) { return delegate().removeAll(key); } @Override public List<V> replaceValues(K key, Iterable<? extends V> values) { return delegate().replaceValues(key, values); } }
zzhhhhh-aw4rwer
guava/src/com/google/common/collect/ForwardingListMultimap.java
Java
asf20
1,700
/* * Copyright (C) 2012 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import com.google.common.annotations.GwtCompatible; /** * Unused stub class, unreferenced under Java and manually emulated under GWT. * * @author Chris Povirk */ @GwtCompatible(emulated = true) abstract class ForwardingImmutableList<E> { private ForwardingImmutableList() {} }
zzhhhhh-aw4rwer
guava/src/com/google/common/collect/ForwardingImmutableList.java
Java
asf20
922
/* * Copyright (C) 2012 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import static com.google.common.base.Preconditions.checkNotNull; import com.google.common.annotations.Beta; import com.google.common.annotations.GwtCompatible; import java.util.ArrayDeque; import java.util.Deque; import java.util.Iterator; import java.util.Queue; /** * Views elements of a type {@code T} as nodes in a tree, and provides methods to traverse the trees * induced by this traverser. * * <p>For example, the tree * * <pre> {@code * h * / | \ * / e \ * d g * /|\ | * / | \ f * a b c }</pre> * * <p>can be iterated over in preorder (hdabcegf), postorder (abcdefgh), or breadth-first order * (hdegabcf). * * <p>Null nodes are strictly forbidden. * * @author Louis Wasserman * @since 15.0 */ @Beta @GwtCompatible(emulated = true) public abstract class TreeTraverser<T> { // TODO(user): make this GWT-compatible when we've checked in ArrayDeque emulation /** * Returns the children of the specified node. Must not contain null. */ public abstract Iterable<T> children(T root); /** * Returns an unmodifiable iterable over the nodes in a tree structure, using pre-order * traversal. That is, each node's subtrees are traversed after the node itself is returned. * * <p>No guarantees are made about the behavior of the traversal when nodes change while * iteration is in progress or when the iterators generated by {@link #children} are advanced. */ public final FluentIterable<T> preOrderTraversal(final T root) { checkNotNull(root); return new FluentIterable<T>() { @Override public UnmodifiableIterator<T> iterator() { return preOrderIterator(root); } }; } // overridden in BinaryTreeTraverser UnmodifiableIterator<T> preOrderIterator(T root) { return new PreOrderIterator(root); } private final class PreOrderIterator extends UnmodifiableIterator<T> { private final Deque<Iterator<T>> stack; PreOrderIterator(T root) { this.stack = new ArrayDeque<Iterator<T>>(); stack.addLast(Iterators.singletonIterator(checkNotNull(root))); } @Override public boolean hasNext() { return !stack.isEmpty(); } @Override public T next() { Iterator<T> itr = stack.getLast(); // throws NSEE if empty T result = checkNotNull(itr.next()); if (!itr.hasNext()) { stack.removeLast(); } Iterator<T> childItr = children(result).iterator(); if (childItr.hasNext()) { stack.addLast(childItr); } return result; } } /** * Returns an unmodifiable iterable over the nodes in a tree structure, using post-order * traversal. That is, each node's subtrees are traversed before the node itself is returned. * * <p>No guarantees are made about the behavior of the traversal when nodes change while * iteration is in progress or when the iterators generated by {@link #children} are advanced. */ public final FluentIterable<T> postOrderTraversal(final T root) { checkNotNull(root); return new FluentIterable<T>() { @Override public UnmodifiableIterator<T> iterator() { return postOrderIterator(root); } }; } // overridden in BinaryTreeTraverser UnmodifiableIterator<T> postOrderIterator(T root) { return new PostOrderIterator(root); } private static final class PostOrderNode<T> { final T root; final Iterator<T> childIterator; PostOrderNode(T root, Iterator<T> childIterator) { this.root = checkNotNull(root); this.childIterator = checkNotNull(childIterator); } } private final class PostOrderIterator extends AbstractIterator<T> { private final ArrayDeque<PostOrderNode<T>> stack; PostOrderIterator(T root) { this.stack = new ArrayDeque<PostOrderNode<T>>(); stack.addLast(expand(root)); } @Override protected T computeNext() { while (!stack.isEmpty()) { PostOrderNode<T> top = stack.getLast(); if (top.childIterator.hasNext()) { T child = top.childIterator.next(); stack.addLast(expand(child)); } else { stack.removeLast(); return top.root; } } return endOfData(); } private PostOrderNode<T> expand(T t) { return new PostOrderNode<T>(t, children(t).iterator()); } } /** * Returns an unmodifiable iterable over the nodes in a tree structure, using breadth-first * traversal. That is, all the nodes of depth 0 are returned, then depth 1, then 2, and so on. * * <p>No guarantees are made about the behavior of the traversal when nodes change while * iteration is in progress or when the iterators generated by {@link #children} are advanced. */ public final FluentIterable<T> breadthFirstTraversal(final T root) { checkNotNull(root); return new FluentIterable<T>() { @Override public UnmodifiableIterator<T> iterator() { return new BreadthFirstIterator(root); } }; } private final class BreadthFirstIterator extends UnmodifiableIterator<T> implements PeekingIterator<T> { private final Queue<T> queue; BreadthFirstIterator(T root) { this.queue = new ArrayDeque<T>(); queue.add(root); } @Override public boolean hasNext() { return !queue.isEmpty(); } @Override public T peek() { return queue.element(); } @Override public T next() { T result = queue.remove(); Iterables.addAll(queue, children(result)); return result; } } }
zzhhhhh-aw4rwer
guava/src/com/google/common/collect/TreeTraverser.java
Java
asf20
6,263
/* * Copyright (C) 2011 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.common.collect; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; import com.google.common.annotations.Beta; import com.google.common.annotations.GwtIncompatible; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Objects; import java.util.Collection; import java.util.Comparator; import java.util.Iterator; import java.util.Map.Entry; import java.util.NavigableMap; import java.util.NoSuchElementException; import java.util.Set; import java.util.TreeMap; import javax.annotation.Nullable; /** * An implementation of {@link RangeSet} backed by a {@link TreeMap}. * * @author Louis Wasserman * @since 14.0 */ @Beta @GwtIncompatible("uses NavigableMap") public class TreeRangeSet<C extends Comparable<?>> extends AbstractRangeSet<C> { @VisibleForTesting final NavigableMap<Cut<C>, Range<C>> rangesByLowerBound; /** * Creates an empty {@code TreeRangeSet} instance. */ public static <C extends Comparable<?>> TreeRangeSet<C> create() { return new TreeRangeSet<C>(new TreeMap<Cut<C>, Range<C>>()); } /** * Returns a {@code TreeRangeSet} initialized with the ranges in the specified range set. */ public static <C extends Comparable<?>> TreeRangeSet<C> create(RangeSet<C> rangeSet) { TreeRangeSet<C> result = create(); result.addAll(rangeSet); return result; } private TreeRangeSet(NavigableMap<Cut<C>, Range<C>> rangesByLowerCut) { this.rangesByLowerBound = rangesByLowerCut; } private transient Set<Range<C>> asRanges; @Override public Set<Range<C>> asRanges() { Set<Range<C>> result = asRanges; return (result == null) ? asRanges = new AsRanges() : result; } final class AsRanges extends ForwardingCollection<Range<C>> implements Set<Range<C>> { @Override protected Collection<Range<C>> delegate() { return rangesByLowerBound.values(); } @Override public int hashCode() { return Sets.hashCodeImpl(this); } @Override public boolean equals(@Nullable Object o) { return Sets.equalsImpl(this, o); } } @Override @Nullable public Range<C> rangeContaining(C value) { checkNotNull(value); Entry<Cut<C>, Range<C>> floorEntry = rangesByLowerBound.floorEntry(Cut.belowValue(value)); if (floorEntry != null && floorEntry.getValue().contains(value)) { return floorEntry.getValue(); } else { // TODO(kevinb): revisit this design choice return null; } } @Override public boolean encloses(Range<C> range) { checkNotNull(range); Entry<Cut<C>, Range<C>> floorEntry = rangesByLowerBound.floorEntry(range.lowerBound); return floorEntry != null && floorEntry.getValue().encloses(range); } @Nullable private Range<C> rangeEnclosing(Range<C> range) { checkNotNull(range); Entry<Cut<C>, Range<C>> floorEntry = rangesByLowerBound.floorEntry(range.lowerBound); return (floorEntry != null && floorEntry.getValue().encloses(range)) ? floorEntry.getValue() : null; } @Override public Range<C> span() { Entry<Cut<C>, Range<C>> firstEntry = rangesByLowerBound.firstEntry(); Entry<Cut<C>, Range<C>> lastEntry = rangesByLowerBound.lastEntry(); if (firstEntry == null) { throw new NoSuchElementException(); } return Range.create(firstEntry.getValue().lowerBound, lastEntry.getValue().upperBound); } @Override public void add(Range<C> rangeToAdd) { checkNotNull(rangeToAdd); if (rangeToAdd.isEmpty()) { return; } // We will use { } to illustrate ranges currently in the range set, and < > // to illustrate rangeToAdd. Cut<C> lbToAdd = rangeToAdd.lowerBound; Cut<C> ubToAdd = rangeToAdd.upperBound; Entry<Cut<C>, Range<C>> entryBelowLB = rangesByLowerBound.lowerEntry(lbToAdd); if (entryBelowLB != null) { // { < Range<C> rangeBelowLB = entryBelowLB.getValue(); if (rangeBelowLB.upperBound.compareTo(lbToAdd) >= 0) { // { < }, and we will need to coalesce if (rangeBelowLB.upperBound.compareTo(ubToAdd) >= 0) { // { < > } ubToAdd = rangeBelowLB.upperBound; /* * TODO(cpovirk): can we just "return;" here? Or, can we remove this if() entirely? If * not, add tests to demonstrate the problem with each approach */ } lbToAdd = rangeBelowLB.lowerBound; } } Entry<Cut<C>, Range<C>> entryBelowUB = rangesByLowerBound.floorEntry(ubToAdd); if (entryBelowUB != null) { // { > Range<C> rangeBelowUB = entryBelowUB.getValue(); if (rangeBelowUB.upperBound.compareTo(ubToAdd) >= 0) { // { > }, and we need to coalesce ubToAdd = rangeBelowUB.upperBound; } } // Remove ranges which are strictly enclosed. rangesByLowerBound.subMap(lbToAdd, ubToAdd).clear(); replaceRangeWithSameLowerBound(Range.create(lbToAdd, ubToAdd)); } @Override public void remove(Range<C> rangeToRemove) { checkNotNull(rangeToRemove); if (rangeToRemove.isEmpty()) { return; } // We will use { } to illustrate ranges currently in the range set, and < > // to illustrate rangeToRemove. Entry<Cut<C>, Range<C>> entryBelowLB = rangesByLowerBound.lowerEntry(rangeToRemove.lowerBound); if (entryBelowLB != null) { // { < Range<C> rangeBelowLB = entryBelowLB.getValue(); if (rangeBelowLB.upperBound.compareTo(rangeToRemove.lowerBound) >= 0) { // { < }, and we will need to subdivide if (rangeToRemove.hasUpperBound() && rangeBelowLB.upperBound.compareTo(rangeToRemove.upperBound) >= 0) { // { < > } replaceRangeWithSameLowerBound( Range.create(rangeToRemove.upperBound, rangeBelowLB.upperBound)); } replaceRangeWithSameLowerBound( Range.create(rangeBelowLB.lowerBound, rangeToRemove.lowerBound)); } } Entry<Cut<C>, Range<C>> entryBelowUB = rangesByLowerBound.floorEntry(rangeToRemove.upperBound); if (entryBelowUB != null) { // { > Range<C> rangeBelowUB = entryBelowUB.getValue(); if (rangeToRemove.hasUpperBound() && rangeBelowUB.upperBound.compareTo(rangeToRemove.upperBound) >= 0) { // { > } replaceRangeWithSameLowerBound( Range.create(rangeToRemove.upperBound, rangeBelowUB.upperBound)); } } rangesByLowerBound.subMap(rangeToRemove.lowerBound, rangeToRemove.upperBound).clear(); } private void replaceRangeWithSameLowerBound(Range<C> range) { if (range.isEmpty()) { rangesByLowerBound.remove(range.lowerBound); } else { rangesByLowerBound.put(range.lowerBound, range); } } private transient RangeSet<C> complement; @Override public RangeSet<C> complement() { RangeSet<C> result = complement; return (result == null) ? complement = new Complement() : result; } @VisibleForTesting static final class RangesByUpperBound<C extends Comparable<?>> extends AbstractNavigableMap<Cut<C>, Range<C>> { private final NavigableMap<Cut<C>, Range<C>> rangesByLowerBound; /** * upperBoundWindow represents the headMap/subMap/tailMap view of the entire "ranges by upper * bound" map; it's a constraint on the *keys*, and does not affect the values. */ private final Range<Cut<C>> upperBoundWindow; RangesByUpperBound(NavigableMap<Cut<C>, Range<C>> rangesByLowerBound) { this.rangesByLowerBound = rangesByLowerBound; this.upperBoundWindow = Range.all(); } private RangesByUpperBound( NavigableMap<Cut<C>, Range<C>> rangesByLowerBound, Range<Cut<C>> upperBoundWindow) { this.rangesByLowerBound = rangesByLowerBound; this.upperBoundWindow = upperBoundWindow; } private NavigableMap<Cut<C>, Range<C>> subMap(Range<Cut<C>> window) { if (window.isConnected(upperBoundWindow)) { return new RangesByUpperBound<C>(rangesByLowerBound, window.intersection(upperBoundWindow)); } else { return ImmutableSortedMap.of(); } } @Override public NavigableMap<Cut<C>, Range<C>> subMap( Cut<C> fromKey, boolean fromInclusive, Cut<C> toKey, boolean toInclusive) { return subMap(Range.range( fromKey, BoundType.forBoolean(fromInclusive), toKey, BoundType.forBoolean(toInclusive))); } @Override public NavigableMap<Cut<C>, Range<C>> headMap(Cut<C> toKey, boolean inclusive) { return subMap(Range.upTo(toKey, BoundType.forBoolean(inclusive))); } @Override public NavigableMap<Cut<C>, Range<C>> tailMap(Cut<C> fromKey, boolean inclusive) { return subMap(Range.downTo(fromKey, BoundType.forBoolean(inclusive))); } @Override public Comparator<? super Cut<C>> comparator() { return Ordering.<Cut<C>>natural(); } @Override public boolean containsKey(@Nullable Object key) { return get(key) != null; } @Override public Range<C> get(@Nullable Object key) { if (key instanceof Cut) { try { @SuppressWarnings("unchecked") // we catch CCEs Cut<C> cut = (Cut<C>) key; if (!upperBoundWindow.contains(cut)) { return null; } Entry<Cut<C>, Range<C>> candidate = rangesByLowerBound.lowerEntry(cut); if (candidate != null && candidate.getValue().upperBound.equals(cut)) { return candidate.getValue(); } } catch (ClassCastException e) { return null; } } return null; } @Override Iterator<Entry<Cut<C>, Range<C>>> entryIterator() { /* * We want to start the iteration at the first range where the upper bound is in * upperBoundWindow. */ final Iterator<Range<C>> backingItr; if (!upperBoundWindow.hasLowerBound()) { backingItr = rangesByLowerBound.values().iterator(); } else { Entry<Cut<C>, Range<C>> lowerEntry = rangesByLowerBound.lowerEntry(upperBoundWindow.lowerEndpoint()); if (lowerEntry == null) { backingItr = rangesByLowerBound.values().iterator(); } else if (upperBoundWindow.lowerBound.isLessThan(lowerEntry.getValue().upperBound)) { backingItr = rangesByLowerBound.tailMap(lowerEntry.getKey(), true).values().iterator(); } else { backingItr = rangesByLowerBound.tailMap(upperBoundWindow.lowerEndpoint(), true) .values().iterator(); } } return new AbstractIterator<Entry<Cut<C>, Range<C>>>() { @Override protected Entry<Cut<C>, Range<C>> computeNext() { if (!backingItr.hasNext()) { return endOfData(); } Range<C> range = backingItr.next(); if (upperBoundWindow.upperBound.isLessThan(range.upperBound)) { return endOfData(); } else { return Maps.immutableEntry(range.upperBound, range); } } }; } @Override Iterator<Entry<Cut<C>, Range<C>>> descendingEntryIterator() { Collection<Range<C>> candidates; if (upperBoundWindow.hasUpperBound()) { candidates = rangesByLowerBound.headMap(upperBoundWindow.upperEndpoint(), false) .descendingMap().values(); } else { candidates = rangesByLowerBound.descendingMap().values(); } final PeekingIterator<Range<C>> backingItr = Iterators.peekingIterator(candidates.iterator()); if (backingItr.hasNext() && upperBoundWindow.upperBound.isLessThan(backingItr.peek().upperBound)) { backingItr.next(); } return new AbstractIterator<Entry<Cut<C>, Range<C>>>() { @Override protected Entry<Cut<C>, Range<C>> computeNext() { if (!backingItr.hasNext()) { return endOfData(); } Range<C> range = backingItr.next(); return upperBoundWindow.lowerBound.isLessThan(range.upperBound) ? Maps.immutableEntry(range.upperBound, range) : endOfData(); } }; } @Override public int size() { if (upperBoundWindow.equals(Range.all())) { return rangesByLowerBound.size(); } return Iterators.size(entryIterator()); } @Override public boolean isEmpty() { return upperBoundWindow.equals(Range.all()) ? rangesByLowerBound.isEmpty() : !entryIterator().hasNext(); } } private static final class ComplementRangesByLowerBound<C extends Comparable<?>> extends AbstractNavigableMap<Cut<C>, Range<C>> { private final NavigableMap<Cut<C>, Range<C>> positiveRangesByLowerBound; private final NavigableMap<Cut<C>, Range<C>> positiveRangesByUpperBound; /** * complementLowerBoundWindow represents the headMap/subMap/tailMap view of the entire * "complement ranges by lower bound" map; it's a constraint on the *keys*, and does not affect * the values. */ private final Range<Cut<C>> complementLowerBoundWindow; ComplementRangesByLowerBound(NavigableMap<Cut<C>, Range<C>> positiveRangesByLowerBound) { this(positiveRangesByLowerBound, Range.<Cut<C>>all()); } private ComplementRangesByLowerBound(NavigableMap<Cut<C>, Range<C>> positiveRangesByLowerBound, Range<Cut<C>> window) { this.positiveRangesByLowerBound = positiveRangesByLowerBound; this.positiveRangesByUpperBound = new RangesByUpperBound<C>(positiveRangesByLowerBound); this.complementLowerBoundWindow = window; } private NavigableMap<Cut<C>, Range<C>> subMap(Range<Cut<C>> subWindow) { if (!complementLowerBoundWindow.isConnected(subWindow)) { return ImmutableSortedMap.of(); } else { subWindow = subWindow.intersection(complementLowerBoundWindow); return new ComplementRangesByLowerBound<C>(positiveRangesByLowerBound, subWindow); } } @Override public NavigableMap<Cut<C>, Range<C>> subMap( Cut<C> fromKey, boolean fromInclusive, Cut<C> toKey, boolean toInclusive) { return subMap(Range.range( fromKey, BoundType.forBoolean(fromInclusive), toKey, BoundType.forBoolean(toInclusive))); } @Override public NavigableMap<Cut<C>, Range<C>> headMap(Cut<C> toKey, boolean inclusive) { return subMap(Range.upTo(toKey, BoundType.forBoolean(inclusive))); } @Override public NavigableMap<Cut<C>, Range<C>> tailMap(Cut<C> fromKey, boolean inclusive) { return subMap(Range.downTo(fromKey, BoundType.forBoolean(inclusive))); } @Override public Comparator<? super Cut<C>> comparator() { return Ordering.<Cut<C>>natural(); } @Override Iterator<Entry<Cut<C>, Range<C>>> entryIterator() { /* * firstComplementRangeLowerBound is the first complement range lower bound inside * complementLowerBoundWindow. Complement range lower bounds are either positive range upper * bounds, or Cut.belowAll(). * * positiveItr starts at the first positive range with lower bound greater than * firstComplementRangeLowerBound. (Positive range lower bounds correspond to complement range * upper bounds.) */ Collection<Range<C>> positiveRanges; if (complementLowerBoundWindow.hasLowerBound()) { positiveRanges = positiveRangesByUpperBound.tailMap( complementLowerBoundWindow.lowerEndpoint(), complementLowerBoundWindow.lowerBoundType() == BoundType.CLOSED).values(); } else { positiveRanges = positiveRangesByUpperBound.values(); } final PeekingIterator<Range<C>> positiveItr = Iterators.peekingIterator( positiveRanges.iterator()); final Cut<C> firstComplementRangeLowerBound; if (complementLowerBoundWindow.contains(Cut.<C>belowAll()) && (!positiveItr.hasNext() || positiveItr.peek().lowerBound != Cut.<C>belowAll())) { firstComplementRangeLowerBound = Cut.belowAll(); } else if (positiveItr.hasNext()) { firstComplementRangeLowerBound = positiveItr.next().upperBound; } else { return Iterators.emptyIterator(); } return new AbstractIterator<Entry<Cut<C>, Range<C>>>() { Cut<C> nextComplementRangeLowerBound = firstComplementRangeLowerBound; @Override protected Entry<Cut<C>, Range<C>> computeNext() { if (complementLowerBoundWindow.upperBound.isLessThan(nextComplementRangeLowerBound) || nextComplementRangeLowerBound == Cut.<C>aboveAll()) { return endOfData(); } Range<C> negativeRange; if (positiveItr.hasNext()) { Range<C> positiveRange = positiveItr.next(); negativeRange = Range.create(nextComplementRangeLowerBound, positiveRange.lowerBound); nextComplementRangeLowerBound = positiveRange.upperBound; } else { negativeRange = Range.create(nextComplementRangeLowerBound, Cut.<C>aboveAll()); nextComplementRangeLowerBound = Cut.aboveAll(); } return Maps.immutableEntry(negativeRange.lowerBound, negativeRange); } }; } @Override Iterator<Entry<Cut<C>, Range<C>>> descendingEntryIterator() { Iterator<Range<C>> itr; /* * firstComplementRangeUpperBound is the upper bound of the last complement range with lower * bound inside complementLowerBoundWindow. * * positiveItr starts at the first positive range with upper bound less than * firstComplementRangeUpperBound. (Positive range upper bounds correspond to complement range * lower bounds.) */ Cut<C> startingPoint = complementLowerBoundWindow.hasUpperBound() ? complementLowerBoundWindow.upperEndpoint() : Cut.<C>aboveAll(); boolean inclusive = complementLowerBoundWindow.hasUpperBound() && complementLowerBoundWindow.upperBoundType() == BoundType.CLOSED; final PeekingIterator<Range<C>> positiveItr = Iterators.peekingIterator(positiveRangesByUpperBound.headMap(startingPoint, inclusive) .descendingMap().values().iterator()); Cut<C> cut; if (positiveItr.hasNext()) { cut = (positiveItr.peek().upperBound == Cut.<C>aboveAll()) ? positiveItr.next().lowerBound : positiveRangesByLowerBound.higherKey(positiveItr.peek().upperBound); } else if (!complementLowerBoundWindow.contains(Cut.<C>belowAll()) || positiveRangesByLowerBound.containsKey(Cut.belowAll())) { return Iterators.emptyIterator(); } else { cut = positiveRangesByLowerBound.higherKey(Cut.<C>belowAll()); } final Cut<C> firstComplementRangeUpperBound = Objects.firstNonNull(cut, Cut.<C>aboveAll()); return new AbstractIterator<Entry<Cut<C>, Range<C>>>() { Cut<C> nextComplementRangeUpperBound = firstComplementRangeUpperBound; @Override protected Entry<Cut<C>, Range<C>> computeNext() { if (nextComplementRangeUpperBound == Cut.<C>belowAll()) { return endOfData(); } else if (positiveItr.hasNext()) { Range<C> positiveRange = positiveItr.next(); Range<C> negativeRange = Range.create(positiveRange.upperBound, nextComplementRangeUpperBound); nextComplementRangeUpperBound = positiveRange.lowerBound; if (complementLowerBoundWindow.lowerBound.isLessThan(negativeRange.lowerBound)) { return Maps.immutableEntry(negativeRange.lowerBound, negativeRange); } } else if (complementLowerBoundWindow.lowerBound.isLessThan(Cut.<C>belowAll())) { Range<C> negativeRange = Range.create(Cut.<C>belowAll(), nextComplementRangeUpperBound); nextComplementRangeUpperBound = Cut.belowAll(); return Maps.immutableEntry(Cut.<C>belowAll(), negativeRange); } return endOfData(); } }; } @Override public int size() { return Iterators.size(entryIterator()); } @Override @Nullable public Range<C> get(Object key) { if (key instanceof Cut) { try { @SuppressWarnings("unchecked") Cut<C> cut = (Cut<C>) key; // tailMap respects the current window Entry<Cut<C>, Range<C>> firstEntry = tailMap(cut, true).firstEntry(); if (firstEntry != null && firstEntry.getKey().equals(cut)) { return firstEntry.getValue(); } } catch (ClassCastException e) { return null; } } return null; } @Override public boolean containsKey(Object key) { return get(key) != null; } } private final class Complement extends TreeRangeSet<C> { Complement() { super(new ComplementRangesByLowerBound<C>(TreeRangeSet.this.rangesByLowerBound)); } @Override public void add(Range<C> rangeToAdd) { TreeRangeSet.this.remove(rangeToAdd); } @Override public void remove(Range<C> rangeToRemove) { TreeRangeSet.this.add(rangeToRemove); } @Override public boolean contains(C value) { return !TreeRangeSet.this.contains(value); } @Override public RangeSet<C> complement() { return TreeRangeSet.this; } } private static final class SubRangeSetRangesByLowerBound<C extends Comparable<?>> extends AbstractNavigableMap<Cut<C>, Range<C>> { /** * lowerBoundWindow is the headMap/subMap/tailMap view; it only restricts the keys, and does not * affect the values. */ private final Range<Cut<C>> lowerBoundWindow; /** * restriction is the subRangeSet view; ranges are truncated to their intersection with * restriction. */ private final Range<C> restriction; private final NavigableMap<Cut<C>, Range<C>> rangesByLowerBound; private final NavigableMap<Cut<C>, Range<C>> rangesByUpperBound; private SubRangeSetRangesByLowerBound(Range<Cut<C>> lowerBoundWindow, Range<C> restriction, NavigableMap<Cut<C>, Range<C>> rangesByLowerBound) { this.lowerBoundWindow = checkNotNull(lowerBoundWindow); this.restriction = checkNotNull(restriction); this.rangesByLowerBound = checkNotNull(rangesByLowerBound); this.rangesByUpperBound = new RangesByUpperBound<C>(rangesByLowerBound); } private NavigableMap<Cut<C>, Range<C>> subMap(Range<Cut<C>> window) { if (!window.isConnected(lowerBoundWindow)) { return ImmutableSortedMap.of(); } else { return new SubRangeSetRangesByLowerBound<C>( lowerBoundWindow.intersection(window), restriction, rangesByLowerBound); } } @Override public NavigableMap<Cut<C>, Range<C>> subMap( Cut<C> fromKey, boolean fromInclusive, Cut<C> toKey, boolean toInclusive) { return subMap(Range.range( fromKey, BoundType.forBoolean(fromInclusive), toKey, BoundType.forBoolean(toInclusive))); } @Override public NavigableMap<Cut<C>, Range<C>> headMap(Cut<C> toKey, boolean inclusive) { return subMap(Range.upTo(toKey, BoundType.forBoolean(inclusive))); } @Override public NavigableMap<Cut<C>, Range<C>> tailMap(Cut<C> fromKey, boolean inclusive) { return subMap(Range.downTo(fromKey, BoundType.forBoolean(inclusive))); } @Override public Comparator<? super Cut<C>> comparator() { return Ordering.<Cut<C>>natural(); } @Override public boolean containsKey(@Nullable Object key) { return get(key) != null; } @Override @Nullable public Range<C> get(@Nullable Object key) { if (key instanceof Cut) { try { @SuppressWarnings("unchecked") // we catch CCE's Cut<C> cut = (Cut<C>) key; if (!lowerBoundWindow.contains(cut) || cut.compareTo(restriction.lowerBound) < 0 || cut.compareTo(restriction.upperBound) >= 0) { return null; } else if (cut.equals(restriction.lowerBound)) { // it might be present, truncated on the left Range<C> candidate = Maps.valueOrNull(rangesByLowerBound.floorEntry(cut)); if (candidate != null && candidate.upperBound.compareTo(restriction.lowerBound) > 0) { return candidate.intersection(restriction); } } else { Range<C> result = rangesByLowerBound.get(cut); if (result != null) { return result.intersection(restriction); } } } catch (ClassCastException e) { return null; } } return null; } @Override Iterator<Entry<Cut<C>, Range<C>>> entryIterator() { if (restriction.isEmpty()) { return Iterators.emptyIterator(); } final Iterator<Range<C>> completeRangeItr; if (lowerBoundWindow.upperBound.isLessThan(restriction.lowerBound)) { return Iterators.emptyIterator(); } else if (lowerBoundWindow.lowerBound.isLessThan(restriction.lowerBound)) { // starts at the first range with upper bound strictly greater than restriction.lowerBound completeRangeItr = rangesByUpperBound.tailMap(restriction.lowerBound, false).values().iterator(); } else { // starts at the first range with lower bound above lowerBoundWindow.lowerBound completeRangeItr = rangesByLowerBound.tailMap(lowerBoundWindow.lowerBound.endpoint(), lowerBoundWindow.lowerBoundType() == BoundType.CLOSED).values().iterator(); } final Cut<Cut<C>> upperBoundOnLowerBounds = Ordering.natural() .min(lowerBoundWindow.upperBound, Cut.belowValue(restriction.upperBound)); return new AbstractIterator<Entry<Cut<C>, Range<C>>>() { @Override protected Entry<Cut<C>, Range<C>> computeNext() { if (!completeRangeItr.hasNext()) { return endOfData(); } Range<C> nextRange = completeRangeItr.next(); if (upperBoundOnLowerBounds.isLessThan(nextRange.lowerBound)) { return endOfData(); } else { nextRange = nextRange.intersection(restriction); return Maps.immutableEntry(nextRange.lowerBound, nextRange); } } }; } @Override Iterator<Entry<Cut<C>, Range<C>>> descendingEntryIterator() { if (restriction.isEmpty()) { return Iterators.emptyIterator(); } Cut<Cut<C>> upperBoundOnLowerBounds = Ordering.natural() .min(lowerBoundWindow.upperBound, Cut.belowValue(restriction.upperBound)); final Iterator<Range<C>> completeRangeItr = rangesByLowerBound.headMap( upperBoundOnLowerBounds.endpoint(), upperBoundOnLowerBounds.typeAsUpperBound() == BoundType.CLOSED) .descendingMap().values().iterator(); return new AbstractIterator<Entry<Cut<C>, Range<C>>>() { @Override protected Entry<Cut<C>, Range<C>> computeNext() { if (!completeRangeItr.hasNext()) { return endOfData(); } Range<C> nextRange = completeRangeItr.next(); if (restriction.lowerBound.compareTo(nextRange.upperBound) >= 0) { return endOfData(); } nextRange = nextRange.intersection(restriction); if (lowerBoundWindow.contains(nextRange.lowerBound)) { return Maps.immutableEntry(nextRange.lowerBound, nextRange); } else { return endOfData(); } } }; } @Override public int size() { return Iterators.size(entryIterator()); } } @Override public RangeSet<C> subRangeSet(Range<C> view) { return view.equals(Range.<C>all()) ? this : new SubRangeSet(view); } private final class SubRangeSet extends TreeRangeSet<C> { private final Range<C> restriction; SubRangeSet(Range<C> restriction) { super(new SubRangeSetRangesByLowerBound<C>( Range.<Cut<C>>all(), restriction, TreeRangeSet.this.rangesByLowerBound)); this.restriction = restriction; } @Override public boolean encloses(Range<C> range) { if (!restriction.isEmpty() && restriction.encloses(range)) { Range<C> enclosing = TreeRangeSet.this.rangeEnclosing(range); return enclosing != null && !enclosing.intersection(restriction).isEmpty(); } return false; } @Override @Nullable public Range<C> rangeContaining(C value) { if (!restriction.contains(value)) { return null; } Range<C> result = TreeRangeSet.this.rangeContaining(value); return (result == null) ? null : result.intersection(restriction); } @Override public void add(Range<C> rangeToAdd) { checkArgument(restriction.encloses(rangeToAdd), "Cannot add range %s to subRangeSet(%s)", rangeToAdd, restriction); super.add(rangeToAdd); } @Override public void remove(Range<C> rangeToRemove) { if (rangeToRemove.isConnected(restriction)) { TreeRangeSet.this.remove(rangeToRemove.intersection(restriction)); } } @Override public boolean contains(C value) { return restriction.contains(value) && TreeRangeSet.this.contains(value); } @Override public void clear() { TreeRangeSet.this.remove(restriction); } @Override public RangeSet<C> subRangeSet(Range<C> view) { if (view.encloses(restriction)) { return this; } else if (view.isConnected(restriction)) { return new SubRangeSet(restriction.intersection(view)); } else { return ImmutableRangeSet.of(); } } } }
zzhhhhh-aw4rwer
guava/src/com/google/common/collect/TreeRangeSet.java
Java
asf20
30,548
/* * Copyright (C) 2007 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import static com.google.common.base.Preconditions.checkNotNull; import com.google.common.annotations.GwtCompatible; import java.io.Serializable; import java.util.Comparator; import javax.annotation.Nullable; /** An ordering for a pre-existing comparator. */ @GwtCompatible(serializable = true) final class ComparatorOrdering<T> extends Ordering<T> implements Serializable { final Comparator<T> comparator; ComparatorOrdering(Comparator<T> comparator) { this.comparator = checkNotNull(comparator); } @Override public int compare(T a, T b) { return comparator.compare(a, b); } @Override public boolean equals(@Nullable Object object) { if (object == this) { return true; } if (object instanceof ComparatorOrdering) { ComparatorOrdering<?> that = (ComparatorOrdering<?>) object; return this.comparator.equals(that.comparator); } return false; } @Override public int hashCode() { return comparator.hashCode(); } @Override public String toString() { return comparator.toString(); } private static final long serialVersionUID = 0; }
zzhhhhh-aw4rwer
guava/src/com/google/common/collect/ComparatorOrdering.java
Java
asf20
1,754
/* * Copyright (C) 2012 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import static com.google.common.base.Preconditions.checkNotNull; import com.google.common.annotations.GwtCompatible; import javax.annotation.Nullable; /** * An implementation of an immutable sorted map with one or more entries. * * @author Louis Wasserman */ @GwtCompatible(emulated = true) @SuppressWarnings("serial") // uses writeReplace, not default serialization final class RegularImmutableSortedMap<K, V> extends ImmutableSortedMap<K, V> { private final transient RegularImmutableSortedSet<K> keySet; private final transient ImmutableList<V> valueList; RegularImmutableSortedMap(RegularImmutableSortedSet<K> keySet, ImmutableList<V> valueList) { this.keySet = keySet; this.valueList = valueList; } RegularImmutableSortedMap( RegularImmutableSortedSet<K> keySet, ImmutableList<V> valueList, ImmutableSortedMap<K, V> descendingMap) { super(descendingMap); this.keySet = keySet; this.valueList = valueList; } @Override ImmutableSet<Entry<K, V>> createEntrySet() { return new EntrySet(); } private class EntrySet extends ImmutableMapEntrySet<K, V> { @Override public UnmodifiableIterator<Entry<K, V>> iterator() { return asList().iterator(); } @Override ImmutableList<Entry<K, V>> createAsList() { return new ImmutableAsList<Entry<K, V>>() { // avoid additional indirection private final ImmutableList<K> keyList = keySet().asList(); @Override public Entry<K, V> get(int index) { return Maps.immutableEntry(keyList.get(index), valueList.get(index)); } @Override ImmutableCollection<Entry<K, V>> delegateCollection() { return EntrySet.this; } }; } @Override ImmutableMap<K, V> map() { return RegularImmutableSortedMap.this; } } @Override public ImmutableSortedSet<K> keySet() { return keySet; } @Override public ImmutableCollection<V> values() { return valueList; } @Override public V get(@Nullable Object key) { int index = keySet.indexOf(key); return (index == -1) ? null : valueList.get(index); } private ImmutableSortedMap<K, V> getSubMap(int fromIndex, int toIndex) { if (fromIndex == 0 && toIndex == size()) { return this; } else if (fromIndex == toIndex) { return emptyMap(comparator()); } else { return from( keySet.getSubSet(fromIndex, toIndex), valueList.subList(fromIndex, toIndex)); } } @Override public ImmutableSortedMap<K, V> headMap(K toKey, boolean inclusive) { return getSubMap(0, keySet.headIndex(checkNotNull(toKey), inclusive)); } @Override public ImmutableSortedMap<K, V> tailMap(K fromKey, boolean inclusive) { return getSubMap(keySet.tailIndex(checkNotNull(fromKey), inclusive), size()); } @Override ImmutableSortedMap<K, V> createDescendingMap() { return new RegularImmutableSortedMap<K, V>( (RegularImmutableSortedSet<K>) keySet.descendingSet(), valueList.reverse(), this); } }
zzhhhhh-aw4rwer
guava/src/com/google/common/collect/RegularImmutableSortedMap.java
Java
asf20
3,719
/* * Copyright (C) 2007 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import com.google.common.annotations.GwtCompatible; import com.google.common.annotations.GwtIncompatible; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Preconditions; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.util.Collection; import java.util.HashMap; import java.util.Map; import java.util.Set; /** * Implementation of {@link Multimap} using hash tables. * * <p>The multimap does not store duplicate key-value pairs. Adding a new * key-value pair equal to an existing key-value pair has no effect. * * <p>Keys and values may be null. All optional multimap methods are supported, * and all returned views are modifiable. * * <p>This class is not threadsafe when any concurrent operations update the * multimap. Concurrent read operations will work correctly. To allow concurrent * update operations, wrap your multimap with a call to {@link * Multimaps#synchronizedSetMultimap}. * * @author Jared Levy * @since 2.0 (imported from Google Collections Library) */ @GwtCompatible(serializable = true, emulated = true) public final class HashMultimap<K, V> extends AbstractSetMultimap<K, V> { private static final int DEFAULT_VALUES_PER_KEY = 2; @VisibleForTesting transient int expectedValuesPerKey = DEFAULT_VALUES_PER_KEY; /** * Creates a new, empty {@code HashMultimap} with the default initial * capacities. */ public static <K, V> HashMultimap<K, V> create() { return new HashMultimap<K, V>(); } /** * Constructs an empty {@code HashMultimap} with enough capacity to hold the * specified numbers of keys and values without rehashing. * * @param expectedKeys the expected number of distinct keys * @param expectedValuesPerKey the expected average number of values per key * @throws IllegalArgumentException if {@code expectedKeys} or {@code * expectedValuesPerKey} is negative */ public static <K, V> HashMultimap<K, V> create( int expectedKeys, int expectedValuesPerKey) { return new HashMultimap<K, V>(expectedKeys, expectedValuesPerKey); } /** * Constructs a {@code HashMultimap} with the same mappings as the specified * multimap. If a key-value mapping appears multiple times in the input * multimap, it only appears once in the constructed multimap. * * @param multimap the multimap whose contents are copied to this multimap */ public static <K, V> HashMultimap<K, V> create( Multimap<? extends K, ? extends V> multimap) { return new HashMultimap<K, V>(multimap); } private HashMultimap() { super(new HashMap<K, Collection<V>>()); } private HashMultimap(int expectedKeys, int expectedValuesPerKey) { super(Maps.<K, Collection<V>>newHashMapWithExpectedSize(expectedKeys)); Preconditions.checkArgument(expectedValuesPerKey >= 0); this.expectedValuesPerKey = expectedValuesPerKey; } private HashMultimap(Multimap<? extends K, ? extends V> multimap) { super(Maps.<K, Collection<V>>newHashMapWithExpectedSize( multimap.keySet().size())); putAll(multimap); } /** * {@inheritDoc} * * <p>Creates an empty {@code HashSet} for a collection of values for one key. * * @return a new {@code HashSet} containing a collection of values for one key */ @Override Set<V> createCollection() { return Sets.<V>newHashSetWithExpectedSize(expectedValuesPerKey); } /** * @serialData expectedValuesPerKey, number of distinct keys, and then for * each distinct key: the key, number of values for that key, and the * key's values */ @GwtIncompatible("java.io.ObjectOutputStream") private void writeObject(ObjectOutputStream stream) throws IOException { stream.defaultWriteObject(); stream.writeInt(expectedValuesPerKey); Serialization.writeMultimap(this, stream); } @GwtIncompatible("java.io.ObjectInputStream") private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException { stream.defaultReadObject(); expectedValuesPerKey = stream.readInt(); int distinctKeys = Serialization.readCount(stream); Map<K, Collection<V>> map = Maps.newHashMapWithExpectedSize(distinctKeys); setMap(map); Serialization.populateMultimap(this, stream, distinctKeys); } @GwtIncompatible("Not needed in emulated source") private static final long serialVersionUID = 0; }
zzhhhhh-aw4rwer
guava/src/com/google/common/collect/HashMultimap.java
Java
asf20
5,088
/* * Copyright (C) 2009 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.common.collect; import static com.google.common.base.Objects.firstNonNull; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Preconditions.checkState; import static com.google.common.collect.MapMakerInternalMap.Strength.SOFT; import com.google.common.annotations.GwtCompatible; import com.google.common.annotations.GwtIncompatible; import com.google.common.base.Ascii; import com.google.common.base.Equivalence; import com.google.common.base.Function; import com.google.common.base.Objects; import com.google.common.base.Throwables; import com.google.common.base.Ticker; import com.google.common.collect.MapMakerInternalMap.Strength; import java.io.Serializable; import java.lang.ref.SoftReference; import java.lang.ref.WeakReference; import java.util.AbstractMap; import java.util.Collections; import java.util.ConcurrentModificationException; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeUnit; import javax.annotation.Nullable; /** * <p>A builder of {@link ConcurrentMap} instances having any combination of the following features: * * <ul> * <li>keys or values automatically wrapped in {@linkplain WeakReference weak} or {@linkplain * SoftReference soft} references * <li>notification of evicted (or otherwise removed) entries * <li>on-demand computation of values for keys not already present * </ul> * * <p>Usage example: <pre> {@code * * ConcurrentMap<Request, Stopwatch> timers = new MapMaker() * .concurrencyLevel(4) * .weakKeys() * .makeMap();}</pre> * * <p>These features are all optional; {@code new MapMaker().makeMap()} returns a valid concurrent * map that behaves similarly to a {@link ConcurrentHashMap}. * * <p>The returned map is implemented as a hash table with similar performance characteristics to * {@link ConcurrentHashMap}. It supports all optional operations of the {@code ConcurrentMap} * interface. It does not permit null keys or values. * * <p><b>Note:</b> by default, the returned map uses equality comparisons (the {@link Object#equals * equals} method) to determine equality for keys or values. However, if {@link #weakKeys} was * specified, the map uses identity ({@code ==}) comparisons instead for keys. Likewise, if {@link * #weakValues} or {@link #softValues} was specified, the map uses identity comparisons for values. * * <p>The view collections of the returned map have <i>weakly consistent iterators</i>. This means * that they are safe for concurrent use, but if other threads modify the map after the iterator is * created, it is undefined which of these changes, if any, are reflected in that iterator. These * iterators never throw {@link ConcurrentModificationException}. * * <p>If {@link #weakKeys}, {@link #weakValues}, or {@link #softValues} are requested, it is * possible for a key or value present in the map to be reclaimed by the garbage collector. Entries * with reclaimed keys or values may be removed from the map on each map modification or on * occasional map accesses; such entries may be counted by {@link Map#size}, but will never be * visible to read or write operations. A partially-reclaimed entry is never exposed to the user. * Any {@link java.util.Map.Entry} instance retrieved from the map's * {@linkplain Map#entrySet entry set} is a snapshot of that entry's state at the time of * retrieval; such entries do, however, support {@link java.util.Map.Entry#setValue}, which simply * calls {@link Map#put} on the entry's key. * * <p>The maps produced by {@code MapMaker} are serializable, and the deserialized maps retain all * the configuration properties of the original map. During deserialization, if the original map had * used soft or weak references, the entries are reconstructed as they were, but it's not unlikely * they'll be quickly garbage-collected before they are ever accessed. * * <p>{@code new MapMaker().weakKeys().makeMap()} is a recommended replacement for {@link * java.util.WeakHashMap}, but note that it compares keys using object identity whereas {@code * WeakHashMap} uses {@link Object#equals}. * * @author Bob Lee * @author Charles Fry * @author Kevin Bourrillion * @since 2.0 (imported from Google Collections Library) */ @GwtCompatible(emulated = true) public final class MapMaker extends GenericMapMaker<Object, Object> { private static final int DEFAULT_INITIAL_CAPACITY = 16; private static final int DEFAULT_CONCURRENCY_LEVEL = 4; private static final int DEFAULT_EXPIRATION_NANOS = 0; static final int UNSET_INT = -1; // TODO(kevinb): dispense with this after benchmarking boolean useCustomMap; int initialCapacity = UNSET_INT; int concurrencyLevel = UNSET_INT; int maximumSize = UNSET_INT; Strength keyStrength; Strength valueStrength; long expireAfterWriteNanos = UNSET_INT; long expireAfterAccessNanos = UNSET_INT; RemovalCause nullRemovalCause; Equivalence<Object> keyEquivalence; Ticker ticker; /** * Constructs a new {@code MapMaker} instance with default settings, including strong keys, strong * values, and no automatic eviction of any kind. */ public MapMaker() {} /** * Sets a custom {@code Equivalence} strategy for comparing keys. * * <p>By default, the map uses {@link Equivalence#identity} to determine key equality when {@link * #weakKeys} is specified, and {@link Equivalence#equals()} otherwise. The only place this is * used is in {@link Interners.WeakInterner}. */ @GwtIncompatible("To be supported") @Override MapMaker keyEquivalence(Equivalence<Object> equivalence) { checkState(keyEquivalence == null, "key equivalence was already set to %s", keyEquivalence); keyEquivalence = checkNotNull(equivalence); this.useCustomMap = true; return this; } Equivalence<Object> getKeyEquivalence() { return firstNonNull(keyEquivalence, getKeyStrength().defaultEquivalence()); } /** * Sets the minimum total size for the internal hash tables. For example, if the initial capacity * is {@code 60}, and the concurrency level is {@code 8}, then eight segments are created, each * having a hash table of size eight. Providing a large enough estimate at construction time * avoids the need for expensive resizing operations later, but setting this value unnecessarily * high wastes memory. * * @throws IllegalArgumentException if {@code initialCapacity} is negative * @throws IllegalStateException if an initial capacity was already set */ @Override public MapMaker initialCapacity(int initialCapacity) { checkState(this.initialCapacity == UNSET_INT, "initial capacity was already set to %s", this.initialCapacity); checkArgument(initialCapacity >= 0); this.initialCapacity = initialCapacity; return this; } int getInitialCapacity() { return (initialCapacity == UNSET_INT) ? DEFAULT_INITIAL_CAPACITY : initialCapacity; } /** * Specifies the maximum number of entries the map may contain. Note that the map <b>may evict an * entry before this limit is exceeded</b>. As the map size grows close to the maximum, the map * evicts entries that are less likely to be used again. For example, the map may evict an entry * because it hasn't been used recently or very often. * * <p>When {@code size} is zero, elements can be successfully added to the map, but are evicted * immediately. This has the same effect as invoking {@link #expireAfterWrite * expireAfterWrite}{@code (0, unit)} or {@link #expireAfterAccess expireAfterAccess}{@code (0, * unit)}. It can be useful in testing, or to disable caching temporarily without a code change. * * <p>Caching functionality in {@code MapMaker} has been moved to * {@link com.google.common.cache.CacheBuilder}. * * @param size the maximum size of the map * @throws IllegalArgumentException if {@code size} is negative * @throws IllegalStateException if a maximum size was already set * @deprecated Caching functionality in {@code MapMaker} has been moved to * {@link com.google.common.cache.CacheBuilder}, with {@link #maximumSize} being * replaced by {@link com.google.common.cache.CacheBuilder#maximumSize}. Note that {@code * CacheBuilder} is simply an enhanced API for an implementation which was branched from * {@code MapMaker}. */ @Deprecated @Override MapMaker maximumSize(int size) { checkState(this.maximumSize == UNSET_INT, "maximum size was already set to %s", this.maximumSize); checkArgument(size >= 0, "maximum size must not be negative"); this.maximumSize = size; this.useCustomMap = true; if (maximumSize == 0) { // SIZE trumps EXPIRED this.nullRemovalCause = RemovalCause.SIZE; } return this; } /** * Guides the allowed concurrency among update operations. Used as a hint for internal sizing. The * table is internally partitioned to try to permit the indicated number of concurrent updates * without contention. Because assignment of entries to these partitions is not necessarily * uniform, the actual concurrency observed may vary. Ideally, you should choose a value to * accommodate as many threads as will ever concurrently modify the table. Using a significantly * higher value than you need can waste space and time, and a significantly lower value can lead * to thread contention. But overestimates and underestimates within an order of magnitude do not * usually have much noticeable impact. A value of one permits only one thread to modify the map * at a time, but since read operations can proceed concurrently, this still yields higher * concurrency than full synchronization. Defaults to 4. * * <p><b>Note:</b> Prior to Guava release 9.0, the default was 16. It is possible the default will * change again in the future. If you care about this value, you should always choose it * explicitly. * * @throws IllegalArgumentException if {@code concurrencyLevel} is nonpositive * @throws IllegalStateException if a concurrency level was already set */ @Override public MapMaker concurrencyLevel(int concurrencyLevel) { checkState(this.concurrencyLevel == UNSET_INT, "concurrency level was already set to %s", this.concurrencyLevel); checkArgument(concurrencyLevel > 0); this.concurrencyLevel = concurrencyLevel; return this; } int getConcurrencyLevel() { return (concurrencyLevel == UNSET_INT) ? DEFAULT_CONCURRENCY_LEVEL : concurrencyLevel; } /** * Specifies that each key (not value) stored in the map should be wrapped in a {@link * WeakReference} (by default, strong references are used). * * <p><b>Warning:</b> when this method is used, the resulting map will use identity ({@code ==}) * comparison to determine equality of keys, which is a technical violation of the {@link Map} * specification, and may not be what you expect. * * @throws IllegalStateException if the key strength was already set * @see WeakReference */ @GwtIncompatible("java.lang.ref.WeakReference") @Override public MapMaker weakKeys() { return setKeyStrength(Strength.WEAK); } MapMaker setKeyStrength(Strength strength) { checkState(keyStrength == null, "Key strength was already set to %s", keyStrength); keyStrength = checkNotNull(strength); checkArgument(keyStrength != SOFT, "Soft keys are not supported"); if (strength != Strength.STRONG) { // STRONG could be used during deserialization. useCustomMap = true; } return this; } Strength getKeyStrength() { return firstNonNull(keyStrength, Strength.STRONG); } /** * Specifies that each value (not key) stored in the map should be wrapped in a * {@link WeakReference} (by default, strong references are used). * * <p>Weak values will be garbage collected once they are weakly reachable. This makes them a poor * candidate for caching; consider {@link #softValues} instead. * * <p><b>Warning:</b> when this method is used, the resulting map will use identity ({@code ==}) * comparison to determine equality of values. This technically violates the specifications of * the methods {@link Map#containsValue containsValue}, * {@link ConcurrentMap#remove(Object, Object) remove(Object, Object)} and * {@link ConcurrentMap#replace(Object, Object, Object) replace(K, V, V)}, and may not be what you * expect. * * @throws IllegalStateException if the value strength was already set * @see WeakReference */ @GwtIncompatible("java.lang.ref.WeakReference") @Override public MapMaker weakValues() { return setValueStrength(Strength.WEAK); } /** * Specifies that each value (not key) stored in the map should be wrapped in a * {@link SoftReference} (by default, strong references are used). Softly-referenced objects will * be garbage-collected in a <i>globally</i> least-recently-used manner, in response to memory * demand. * * <p><b>Warning:</b> in most circumstances it is better to set a per-cache {@linkplain * #maximumSize maximum size} instead of using soft references. You should only use this method if * you are well familiar with the practical consequences of soft references. * * <p><b>Warning:</b> when this method is used, the resulting map will use identity ({@code ==}) * comparison to determine equality of values. This technically violates the specifications of * the methods {@link Map#containsValue containsValue}, * {@link ConcurrentMap#remove(Object, Object) remove(Object, Object)} and * {@link ConcurrentMap#replace(Object, Object, Object) replace(K, V, V)}, and may not be what you * expect. * * @throws IllegalStateException if the value strength was already set * @see SoftReference * @deprecated Caching functionality in {@code MapMaker} has been moved to {@link * com.google.common.cache.CacheBuilder}, with {@link #softValues} being replaced by {@link * com.google.common.cache.CacheBuilder#softValues}. Note that {@code CacheBuilder} is simply * an enhanced API for an implementation which was branched from {@code MapMaker}. <b>This * method is scheduled for deletion in September 2014.</b> */ @Deprecated @GwtIncompatible("java.lang.ref.SoftReference") @Override public MapMaker softValues() { return setValueStrength(Strength.SOFT); } MapMaker setValueStrength(Strength strength) { checkState(valueStrength == null, "Value strength was already set to %s", valueStrength); valueStrength = checkNotNull(strength); if (strength != Strength.STRONG) { // STRONG could be used during deserialization. useCustomMap = true; } return this; } Strength getValueStrength() { return firstNonNull(valueStrength, Strength.STRONG); } /** * Specifies that each entry should be automatically removed from the map once a fixed duration * has elapsed after the entry's creation, or the most recent replacement of its value. * * <p>When {@code duration} is zero, elements can be successfully added to the map, but are * evicted immediately. This has a very similar effect to invoking {@link #maximumSize * maximumSize}{@code (0)}. It can be useful in testing, or to disable caching temporarily without * a code change. * * <p>Expired entries may be counted by {@link Map#size}, but will never be visible to read or * write operations. Expired entries are currently cleaned up during write operations, or during * occasional read operations in the absense of writes; though this behavior may change in the * future. * * @param duration the length of time after an entry is created that it should be automatically * removed * @param unit the unit that {@code duration} is expressed in * @throws IllegalArgumentException if {@code duration} is negative * @throws IllegalStateException if the time to live or time to idle was already set * @deprecated Caching functionality in {@code MapMaker} has been moved to * {@link com.google.common.cache.CacheBuilder}, with {@link #expireAfterWrite} being * replaced by {@link com.google.common.cache.CacheBuilder#expireAfterWrite}. Note that {@code * CacheBuilder} is simply an enhanced API for an implementation which was branched from * {@code MapMaker}. */ @Deprecated @Override MapMaker expireAfterWrite(long duration, TimeUnit unit) { checkExpiration(duration, unit); this.expireAfterWriteNanos = unit.toNanos(duration); if (duration == 0 && this.nullRemovalCause == null) { // SIZE trumps EXPIRED this.nullRemovalCause = RemovalCause.EXPIRED; } useCustomMap = true; return this; } private void checkExpiration(long duration, TimeUnit unit) { checkState(expireAfterWriteNanos == UNSET_INT, "expireAfterWrite was already set to %s ns", expireAfterWriteNanos); checkState(expireAfterAccessNanos == UNSET_INT, "expireAfterAccess was already set to %s ns", expireAfterAccessNanos); checkArgument(duration >= 0, "duration cannot be negative: %s %s", duration, unit); } long getExpireAfterWriteNanos() { return (expireAfterWriteNanos == UNSET_INT) ? DEFAULT_EXPIRATION_NANOS : expireAfterWriteNanos; } /** * Specifies that each entry should be automatically removed from the map once a fixed duration * has elapsed after the entry's last read or write access. * * <p>When {@code duration} is zero, elements can be successfully added to the map, but are * evicted immediately. This has a very similar effect to invoking {@link #maximumSize * maximumSize}{@code (0)}. It can be useful in testing, or to disable caching temporarily without * a code change. * * <p>Expired entries may be counted by {@link Map#size}, but will never be visible to read or * write operations. Expired entries are currently cleaned up during write operations, or during * occasional read operations in the absense of writes; though this behavior may change in the * future. * * @param duration the length of time after an entry is last accessed that it should be * automatically removed * @param unit the unit that {@code duration} is expressed in * @throws IllegalArgumentException if {@code duration} is negative * @throws IllegalStateException if the time to idle or time to live was already set * @deprecated Caching functionality in {@code MapMaker} has been moved to * {@link com.google.common.cache.CacheBuilder}, with {@link #expireAfterAccess} being * replaced by {@link com.google.common.cache.CacheBuilder#expireAfterAccess}. Note that * {@code CacheBuilder} is simply an enhanced API for an implementation which was branched * from {@code MapMaker}. */ @Deprecated @GwtIncompatible("To be supported") @Override MapMaker expireAfterAccess(long duration, TimeUnit unit) { checkExpiration(duration, unit); this.expireAfterAccessNanos = unit.toNanos(duration); if (duration == 0 && this.nullRemovalCause == null) { // SIZE trumps EXPIRED this.nullRemovalCause = RemovalCause.EXPIRED; } useCustomMap = true; return this; } long getExpireAfterAccessNanos() { return (expireAfterAccessNanos == UNSET_INT) ? DEFAULT_EXPIRATION_NANOS : expireAfterAccessNanos; } Ticker getTicker() { return firstNonNull(ticker, Ticker.systemTicker()); } /** * Specifies a listener instance, which all maps built using this {@code MapMaker} will notify * each time an entry is removed from the map by any means. * * <p>Each map built by this map maker after this method is called invokes the supplied listener * after removing an element for any reason (see removal causes in {@link RemovalCause}). It will * invoke the listener during invocations of any of that map's public methods (even read-only * methods). * * <p><b>Important note:</b> Instead of returning <i>this</i> as a {@code MapMaker} instance, * this method returns {@code GenericMapMaker<K, V>}. From this point on, either the original * reference or the returned reference may be used to complete configuration and build the map, * but only the "generic" one is type-safe. That is, it will properly prevent you from building * maps whose key or value types are incompatible with the types accepted by the listener already * provided; the {@code MapMaker} type cannot do this. For best results, simply use the standard * method-chaining idiom, as illustrated in the documentation at top, configuring a {@code * MapMaker} and building your {@link Map} all in a single statement. * * <p><b>Warning:</b> if you ignore the above advice, and use this {@code MapMaker} to build a map * or cache whose key or value type is incompatible with the listener, you will likely experience * a {@link ClassCastException} at some <i>undefined</i> point in the future. * * @throws IllegalStateException if a removal listener was already set * @deprecated Caching functionality in {@code MapMaker} has been moved to * {@link com.google.common.cache.CacheBuilder}, with {@link #removalListener} being * replaced by {@link com.google.common.cache.CacheBuilder#removalListener}. Note that {@code * CacheBuilder} is simply an enhanced API for an implementation which was branched from * {@code MapMaker}. */ @Deprecated @GwtIncompatible("To be supported") <K, V> GenericMapMaker<K, V> removalListener(RemovalListener<K, V> listener) { checkState(this.removalListener == null); // safely limiting the kinds of maps this can produce @SuppressWarnings("unchecked") GenericMapMaker<K, V> me = (GenericMapMaker<K, V>) this; me.removalListener = checkNotNull(listener); useCustomMap = true; return me; } /** * Builds a thread-safe map, without on-demand computation of values. This method does not alter * the state of this {@code MapMaker} instance, so it can be invoked again to create multiple * independent maps. * * <p>The bulk operations {@code putAll}, {@code equals}, and {@code clear} are not guaranteed to * be performed atomically on the returned map. Additionally, {@code size} and {@code * containsValue} are implemented as bulk read operations, and thus may fail to observe concurrent * writes. * * @return a serializable concurrent map having the requested features */ @Override public <K, V> ConcurrentMap<K, V> makeMap() { if (!useCustomMap) { return new ConcurrentHashMap<K, V>(getInitialCapacity(), 0.75f, getConcurrencyLevel()); } return (nullRemovalCause == null) ? new MapMakerInternalMap<K, V>(this) : new NullConcurrentMap<K, V>(this); } /** * Returns a MapMakerInternalMap for the benefit of internal callers that use features of * that class not exposed through ConcurrentMap. */ @Override @GwtIncompatible("MapMakerInternalMap") <K, V> MapMakerInternalMap<K, V> makeCustomMap() { return new MapMakerInternalMap<K, V>(this); } /** * Builds a map that supports atomic, on-demand computation of values. {@link Map#get} either * returns an already-computed value for the given key, atomically computes it using the supplied * function, or, if another thread is currently computing the value for this key, simply waits for * that thread to finish and returns its computed value. Note that the function may be executed * concurrently by multiple threads, but only for distinct keys. * * <p>New code should use {@link com.google.common.cache.CacheBuilder}, which supports * {@linkplain com.google.common.cache.CacheStats statistics} collection, introduces the * {@link com.google.common.cache.CacheLoader} interface for loading entries into the cache * (allowing checked exceptions to be thrown in the process), and more cleanly separates * computation from the cache's {@code Map} view. * * <p>If an entry's value has not finished computing yet, query methods besides {@code get} return * immediately as if an entry doesn't exist. In other words, an entry isn't externally visible * until the value's computation completes. * * <p>{@link Map#get} on the returned map will never return {@code null}. It may throw: * * <ul> * <li>{@link NullPointerException} if the key is null or the computing function returns a null * result * <li>{@link ComputationException} if an exception was thrown by the computing function. If that * exception is already of type {@link ComputationException} it is propagated directly; otherwise * it is wrapped. * </ul> * * <p><b>Note:</b> Callers of {@code get} <i>must</i> ensure that the key argument is of type * {@code K}. The {@code get} method accepts {@code Object}, so the key type is not checked at * compile time. Passing an object of a type other than {@code K} can result in that object being * unsafely passed to the computing function as type {@code K}, and unsafely stored in the map. * * <p>If {@link Map#put} is called before a computation completes, other threads waiting on the * computation will wake up and return the stored value. * * <p>This method does not alter the state of this {@code MapMaker} instance, so it can be invoked * again to create multiple independent maps. * * <p>Insertion, removal, update, and access operations on the returned map safely execute * concurrently by multiple threads. Iterators on the returned map are weakly consistent, * returning elements reflecting the state of the map at some point at or since the creation of * the iterator. They do not throw {@link ConcurrentModificationException}, and may proceed * concurrently with other operations. * * <p>The bulk operations {@code putAll}, {@code equals}, and {@code clear} are not guaranteed to * be performed atomically on the returned map. Additionally, {@code size} and {@code * containsValue} are implemented as bulk read operations, and thus may fail to observe concurrent * writes. * * @param computingFunction the function used to compute new values * @return a serializable concurrent map having the requested features * @deprecated Caching functionality in {@code MapMaker} has been moved to * {@link com.google.common.cache.CacheBuilder}, with {@link #makeComputingMap} being replaced * by {@link com.google.common.cache.CacheBuilder#build}. See the * <a href="http://code.google.com/p/guava-libraries/wiki/MapMakerMigration">MapMaker * Migration Guide</a> for more details. */ @Deprecated @Override <K, V> ConcurrentMap<K, V> makeComputingMap( Function<? super K, ? extends V> computingFunction) { return (nullRemovalCause == null) ? new MapMaker.ComputingMapAdapter<K, V>(this, computingFunction) : new NullComputingConcurrentMap<K, V>(this, computingFunction); } /** * Returns a string representation for this MapMaker instance. The exact form of the returned * string is not specificed. */ @Override public String toString() { Objects.ToStringHelper s = Objects.toStringHelper(this); if (initialCapacity != UNSET_INT) { s.add("initialCapacity", initialCapacity); } if (concurrencyLevel != UNSET_INT) { s.add("concurrencyLevel", concurrencyLevel); } if (maximumSize != UNSET_INT) { s.add("maximumSize", maximumSize); } if (expireAfterWriteNanos != UNSET_INT) { s.add("expireAfterWrite", expireAfterWriteNanos + "ns"); } if (expireAfterAccessNanos != UNSET_INT) { s.add("expireAfterAccess", expireAfterAccessNanos + "ns"); } if (keyStrength != null) { s.add("keyStrength", Ascii.toLowerCase(keyStrength.toString())); } if (valueStrength != null) { s.add("valueStrength", Ascii.toLowerCase(valueStrength.toString())); } if (keyEquivalence != null) { s.addValue("keyEquivalence"); } if (removalListener != null) { s.addValue("removalListener"); } return s.toString(); } /** * An object that can receive a notification when an entry is removed from a map. The removal * resulting in notification could have occured to an entry being manually removed or replaced, or * due to eviction resulting from timed expiration, exceeding a maximum size, or garbage * collection. * * <p>An instance may be called concurrently by multiple threads to process different entries. * Implementations of this interface should avoid performing blocking calls or synchronizing on * shared resources. * * @param <K> the most general type of keys this listener can listen for; for * example {@code Object} if any key is acceptable * @param <V> the most general type of values this listener can listen for; for * example {@code Object} if any key is acceptable */ interface RemovalListener<K, V> { /** * Notifies the listener that a removal occurred at some point in the past. */ void onRemoval(RemovalNotification<K, V> notification); } /** * A notification of the removal of a single entry. The key or value may be null if it was already * garbage collected. * * <p>Like other {@code Map.Entry} instances associated with MapMaker, this class holds strong * references to the key and value, regardless of the type of references the map may be using. */ static final class RemovalNotification<K, V> extends ImmutableEntry<K, V> { private static final long serialVersionUID = 0; private final RemovalCause cause; RemovalNotification(@Nullable K key, @Nullable V value, RemovalCause cause) { super(key, value); this.cause = cause; } /** * Returns the cause for which the entry was removed. */ public RemovalCause getCause() { return cause; } /** * Returns {@code true} if there was an automatic removal due to eviction (the cause is neither * {@link RemovalCause#EXPLICIT} nor {@link RemovalCause#REPLACED}). */ public boolean wasEvicted() { return cause.wasEvicted(); } } /** * The reason why an entry was removed. */ enum RemovalCause { /** * The entry was manually removed by the user. This can result from the user invoking * {@link Map#remove}, {@link ConcurrentMap#remove}, or {@link java.util.Iterator#remove}. */ EXPLICIT { @Override boolean wasEvicted() { return false; } }, /** * The entry itself was not actually removed, but its value was replaced by the user. This can * result from the user invoking {@link Map#put}, {@link Map#putAll}, * {@link ConcurrentMap#replace(Object, Object)}, or * {@link ConcurrentMap#replace(Object, Object, Object)}. */ REPLACED { @Override boolean wasEvicted() { return false; } }, /** * The entry was removed automatically because its key or value was garbage-collected. This can * occur when using {@link #softValues}, {@link #weakKeys}, or {@link #weakValues}. */ COLLECTED { @Override boolean wasEvicted() { return true; } }, /** * The entry's expiration timestamp has passed. This can occur when using {@link * #expireAfterWrite} or {@link #expireAfterAccess}. */ EXPIRED { @Override boolean wasEvicted() { return true; } }, /** * The entry was evicted due to size constraints. This can occur when using {@link * #maximumSize}. */ SIZE { @Override boolean wasEvicted() { return true; } }; /** * Returns {@code true} if there was an automatic removal due to eviction (the cause is neither * {@link #EXPLICIT} nor {@link #REPLACED}). */ abstract boolean wasEvicted(); } /** A map that is always empty and evicts on insertion. */ static class NullConcurrentMap<K, V> extends AbstractMap<K, V> implements ConcurrentMap<K, V>, Serializable { private static final long serialVersionUID = 0; private final RemovalListener<K, V> removalListener; private final RemovalCause removalCause; NullConcurrentMap(MapMaker mapMaker) { removalListener = mapMaker.getRemovalListener(); removalCause = mapMaker.nullRemovalCause; } // implements ConcurrentMap @Override public boolean containsKey(@Nullable Object key) { return false; } @Override public boolean containsValue(@Nullable Object value) { return false; } @Override public V get(@Nullable Object key) { return null; } void notifyRemoval(K key, V value) { RemovalNotification<K, V> notification = new RemovalNotification<K, V>(key, value, removalCause); removalListener.onRemoval(notification); } @Override public V put(K key, V value) { checkNotNull(key); checkNotNull(value); notifyRemoval(key, value); return null; } @Override public V putIfAbsent(K key, V value) { return put(key, value); } @Override public V remove(@Nullable Object key) { return null; } @Override public boolean remove(@Nullable Object key, @Nullable Object value) { return false; } @Override public V replace(K key, V value) { checkNotNull(key); checkNotNull(value); return null; } @Override public boolean replace(K key, @Nullable V oldValue, V newValue) { checkNotNull(key); checkNotNull(newValue); return false; } @Override public Set<Entry<K, V>> entrySet() { return Collections.emptySet(); } } /** Computes on retrieval and evicts the result. */ static final class NullComputingConcurrentMap<K, V> extends NullConcurrentMap<K, V> { private static final long serialVersionUID = 0; final Function<? super K, ? extends V> computingFunction; NullComputingConcurrentMap( MapMaker mapMaker, Function<? super K, ? extends V> computingFunction) { super(mapMaker); this.computingFunction = checkNotNull(computingFunction); } @SuppressWarnings("unchecked") // unsafe, which is why Cache is preferred @Override public V get(Object k) { K key = (K) k; V value = compute(key); checkNotNull(value, "%s returned null for key %s.", computingFunction, key); notifyRemoval(key, value); return value; } private V compute(K key) { checkNotNull(key); try { return computingFunction.apply(key); } catch (ComputationException e) { throw e; } catch (Throwable t) { throw new ComputationException(t); } } } /** * Overrides get() to compute on demand. Also throws an exception when {@code null} is returned * from a computation. */ /* * This might make more sense in ComputingConcurrentHashMap, but it causes a javac crash in some * cases there: http://code.google.com/p/guava-libraries/issues/detail?id=950 */ static final class ComputingMapAdapter<K, V> extends ComputingConcurrentHashMap<K, V> implements Serializable { private static final long serialVersionUID = 0; ComputingMapAdapter(MapMaker mapMaker, Function<? super K, ? extends V> computingFunction) { super(mapMaker, computingFunction); } @SuppressWarnings("unchecked") // unsafe, which is one advantage of Cache over Map @Override public V get(Object key) { V value; try { value = getOrCompute((K) key); } catch (ExecutionException e) { Throwable cause = e.getCause(); Throwables.propagateIfInstanceOf(cause, ComputationException.class); throw new ComputationException(cause); } if (value == null) { throw new NullPointerException(computingFunction + " returned null for key " + key + "."); } return value; } } }
zzhhhhh-aw4rwer
guava/src/com/google/common/collect/MapMaker.java
Java
asf20
37,107
/* * Copyright (C) 2007 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import com.google.common.annotations.Beta; import com.google.common.annotations.GwtCompatible; import com.google.common.base.Objects; import java.util.Map; import java.util.Map.Entry; import javax.annotation.Nullable; /** * A map entry which forwards all its method calls to another map entry. * Subclasses should override one or more methods to modify the behavior of the * backing map entry as desired per the <a * href="http://en.wikipedia.org/wiki/Decorator_pattern">decorator pattern</a>. * * <p><i>Warning:</i> The methods of {@code ForwardingMapEntry} forward * <i>indiscriminately</i> to the methods of the delegate. For example, * overriding {@link #getValue} alone <i>will not</i> change the behavior of * {@link #equals}, which can lead to unexpected behavior. In this case, you * should override {@code equals} as well, either providing your own * implementation, or delegating to the provided {@code standardEquals} method. * * <p>Each of the {@code standard} methods, where appropriate, use {@link * Objects#equal} to test equality for both keys and values. This may not be * the desired behavior for map implementations that use non-standard notions of * key equality, such as the entry of a {@code SortedMap} whose comparator is * not consistent with {@code equals}. * * <p>The {@code standard} methods are not guaranteed to be thread-safe, even * when all of the methods that they depend on are thread-safe. * * @author Mike Bostock * @author Louis Wasserman * @since 2.0 (imported from Google Collections Library) */ @GwtCompatible public abstract class ForwardingMapEntry<K, V> extends ForwardingObject implements Map.Entry<K, V> { // TODO(user): identify places where thread safety is actually lost /** Constructor for use by subclasses. */ protected ForwardingMapEntry() {} @Override protected abstract Map.Entry<K, V> delegate(); @Override public K getKey() { return delegate().getKey(); } @Override public V getValue() { return delegate().getValue(); } @Override public V setValue(V value) { return delegate().setValue(value); } @Override public boolean equals(@Nullable Object object) { return delegate().equals(object); } @Override public int hashCode() { return delegate().hashCode(); } /** * A sensible definition of {@link #equals(Object)} in terms of {@link * #getKey()} and {@link #getValue()}. If you override either of these * methods, you may wish to override {@link #equals(Object)} to forward to * this implementation. * * @since 7.0 */ protected boolean standardEquals(@Nullable Object object) { if (object instanceof Entry) { Entry<?, ?> that = (Entry<?, ?>) object; return Objects.equal(this.getKey(), that.getKey()) && Objects.equal(this.getValue(), that.getValue()); } return false; } /** * A sensible definition of {@link #hashCode()} in terms of {@link #getKey()} * and {@link #getValue()}. If you override either of these methods, you may * wish to override {@link #hashCode()} to forward to this implementation. * * @since 7.0 */ protected int standardHashCode() { K k = getKey(); V v = getValue(); return ((k == null) ? 0 : k.hashCode()) ^ ((v == null) ? 0 : v.hashCode()); } /** * A sensible definition of {@link #toString} in terms of {@link * #getKey} and {@link #getValue}. If you override either of these * methods, you may wish to override {@link #equals} to forward to this * implementation. * * @since 7.0 */ @Beta protected String standardToString() { return getKey() + "=" + getValue(); } }
zzhhhhh-aw4rwer
guava/src/com/google/common/collect/ForwardingMapEntry.java
Java
asf20
4,308
/* * Copyright (C) 2007 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import com.google.common.annotations.GwtCompatible; import java.util.ListIterator; /** * A list iterator which forwards all its method calls to another list * iterator. Subclasses should override one or more methods to modify the * behavior of the backing iterator as desired per the <a * href="http://en.wikipedia.org/wiki/Decorator_pattern">decorator pattern</a>. * * @author Mike Bostock * @since 2.0 (imported from Google Collections Library) */ @GwtCompatible public abstract class ForwardingListIterator<E> extends ForwardingIterator<E> implements ListIterator<E> { /** Constructor for use by subclasses. */ protected ForwardingListIterator() {} @Override protected abstract ListIterator<E> delegate(); @Override public void add(E element) { delegate().add(element); } @Override public boolean hasPrevious() { return delegate().hasPrevious(); } @Override public int nextIndex() { return delegate().nextIndex(); } @Override public E previous() { return delegate().previous(); } @Override public int previousIndex() { return delegate().previousIndex(); } @Override public void set(E element) { delegate().set(element); } }
zzhhhhh-aw4rwer
guava/src/com/google/common/collect/ForwardingListIterator.java
Java
asf20
1,853
/* * Copyright (C) 2007 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import com.google.common.annotations.GwtCompatible; import com.google.common.base.Objects; import java.util.Map.Entry; import javax.annotation.Nullable; /** * Implementation of the {@code equals}, {@code hashCode}, and {@code toString} * methods of {@code Entry}. * * @author Jared Levy */ @GwtCompatible abstract class AbstractMapEntry<K, V> implements Entry<K, V> { @Override public abstract K getKey(); @Override public abstract V getValue(); @Override public V setValue(V value) { throw new UnsupportedOperationException(); } @Override public boolean equals(@Nullable Object object) { if (object instanceof Entry) { Entry<?, ?> that = (Entry<?, ?>) object; return Objects.equal(this.getKey(), that.getKey()) && Objects.equal(this.getValue(), that.getValue()); } return false; } @Override public int hashCode() { K k = getKey(); V v = getValue(); return ((k == null) ? 0 : k.hashCode()) ^ ((v == null) ? 0 : v.hashCode()); } /** * Returns a string representation of the form {@code {key}={value}}. */ @Override public String toString() { return getKey() + "=" + getValue(); } }
zzhhhhh-aw4rwer
guava/src/com/google/common/collect/AbstractMapEntry.java
Java
asf20
1,821
/* * Copyright (C) 2008 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import static com.google.common.base.Preconditions.checkNotNull; import com.google.common.annotations.Beta; import com.google.common.annotations.GwtCompatible; import com.google.common.annotations.GwtIncompatible; import com.google.common.base.Function; import com.google.common.base.Optional; import com.google.common.base.Predicate; import java.util.Collection; import java.util.Comparator; import java.util.Iterator; import java.util.List; import java.util.SortedSet; import javax.annotation.CheckReturnValue; import javax.annotation.Nullable; /** * {@code FluentIterable} provides a rich interface for manipulating {@code Iterable} instances in a * chained fashion. A {@code FluentIterable} can be created from an {@code Iterable}, or from a set * of elements. The following types of methods are provided on {@code FluentIterable}: * <ul> * <li>chained methods which return a new {@code FluentIterable} based in some way on the contents * of the current one (for example {@link #transform}) * <li>conversion methods which copy the {@code FluentIterable}'s contents into a new collection or * array (for example {@link #toList}) * <li>element extraction methods which facilitate the retrieval of certain elements (for example * {@link #last}) * <li>query methods which answer questions about the {@code FluentIterable}'s contents (for example * {@link #anyMatch}) * </ul> * * <p>Here is an example that merges the lists returned by two separate database calls, transforms * it by invoking {@code toString()} on each element, and returns the first 10 elements as an * {@code ImmutableList}: <pre> {@code * * FluentIterable * .from(database.getClientList()) * .filter(activeInLastMonth()) * .transform(Functions.toStringFunction()) * .limit(10) * .toList();}</pre> * * <p>Anything which can be done using {@code FluentIterable} could be done in a different fashion * (often with {@link Iterables}), however the use of {@code FluentIterable} makes many sets of * operations significantly more concise. * * @author Marcin Mikosik * @since 12.0 */ @GwtCompatible(emulated = true) public abstract class FluentIterable<E> implements Iterable<E> { // We store 'iterable' and use it instead of 'this' to allow Iterables to perform instanceof // checks on the _original_ iterable when FluentIterable.from is used. private final Iterable<E> iterable; /** Constructor for use by subclasses. */ protected FluentIterable() { this.iterable = this; } FluentIterable(Iterable<E> iterable) { this.iterable = checkNotNull(iterable); } /** * Returns a fluent iterable that wraps {@code iterable}, or {@code iterable} itself if it * is already a {@code FluentIterable}. */ public static <E> FluentIterable<E> from(final Iterable<E> iterable) { return (iterable instanceof FluentIterable) ? (FluentIterable<E>) iterable : new FluentIterable<E>(iterable) { @Override public Iterator<E> iterator() { return iterable.iterator(); } }; } /** * Construct a fluent iterable from another fluent iterable. This is obviously never necessary, * but is intended to help call out cases where one migration from {@code Iterable} to * {@code FluentIterable} has obviated the need to explicitly convert to a {@code FluentIterable}. * * @deprecated instances of {@code FluentIterable} don't need to be converted to * {@code FluentIterable} */ @Deprecated public static <E> FluentIterable<E> from(FluentIterable<E> iterable) { return checkNotNull(iterable); } /** * Returns a string representation of this fluent iterable, with the format * {@code [e1, e2, ..., en]}. */ @Override public String toString() { return Iterables.toString(iterable); } /** * Returns the number of elements in this fluent iterable. */ public final int size() { return Iterables.size(iterable); } /** * Returns {@code true} if this fluent iterable contains any object for which * {@code equals(element)} is true. */ public final boolean contains(@Nullable Object element) { return Iterables.contains(iterable, element); } /** * Returns a fluent iterable whose {@code Iterator} cycles indefinitely over the elements of * this fluent 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 * this fluent iterable. The iterator's {@code hasNext()} method returns {@code true} until * this fluent 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. */ @CheckReturnValue public final FluentIterable<E> cycle() { return from(Iterables.cycle(iterable)); } /** * Returns the elements from this fluent iterable that satisfy a predicate. The * resulting fluent iterable's iterator does not support {@code remove()}. */ @CheckReturnValue public final FluentIterable<E> filter(Predicate<? super E> predicate) { return from(Iterables.filter(iterable, predicate)); } /** * Returns the elements from this fluent iterable that are instances of class {@code type}. * * @param type the type of elements desired */ @GwtIncompatible("Class.isInstance") @CheckReturnValue public final <T> FluentIterable<T> filter(Class<T> type) { return from(Iterables.filter(iterable, type)); } /** * Returns {@code true} if any element in this fluent iterable satisfies the predicate. */ public final boolean anyMatch(Predicate<? super E> predicate) { return Iterables.any(iterable, predicate); } /** * Returns {@code true} if every element in this fluent iterable satisfies the predicate. * If this fluent iterable is empty, {@code true} is returned. */ public final boolean allMatch(Predicate<? super E> predicate) { return Iterables.all(iterable, predicate); } /** * Returns an {@link Optional} containing the first element in this fluent iterable that * satisfies the given predicate, if such an element exists. * * <p><b>Warning:</b> avoid using a {@code predicate} that matches {@code null}. If {@code null} * is matched in this fluent iterable, a {@link NullPointerException} will be thrown. */ public final Optional<E> firstMatch(Predicate<? super E> predicate) { return Iterables.tryFind(iterable, predicate); } /** * Returns a fluent iterable that applies {@code function} to each element of this * fluent iterable. * * <p>The returned fluent iterable's iterator supports {@code remove()} if this iterable's * iterator does. After a successful {@code remove()} call, this fluent iterable no longer * contains the corresponding element. */ public final <T> FluentIterable<T> transform(Function<? super E, T> function) { return from(Iterables.transform(iterable, function)); } /** * Applies {@code function} to each element of this fluent iterable and returns * a fluent iterable with the concatenated combination of results. {@code function} * returns an Iterable of results. * * <p>The returned fluent iterable's iterator supports {@code remove()} if this * function-returned iterables' iterator does. After a successful {@code remove()} call, * the returned fluent iterable no longer contains the corresponding element. * * @since 13.0 (required {@code Function<E, Iterable<T>>} until 14.0) */ public <T> FluentIterable<T> transformAndConcat( Function<? super E, ? extends Iterable<? extends T>> function) { return from(Iterables.concat(transform(function))); } /** * Returns an {@link Optional} containing the first element in this fluent iterable. * If the iterable is empty, {@code Optional.absent()} is returned. * * @throws NullPointerException if the first element is null; if this is a possibility, use * {@code iterator().next()} or {@link Iterables#getFirst} instead. */ public final Optional<E> first() { Iterator<E> iterator = iterable.iterator(); return iterator.hasNext() ? Optional.of(iterator.next()) : Optional.<E>absent(); } /** * Returns an {@link Optional} containing the last element in this fluent iterable. * If the iterable is empty, {@code Optional.absent()} is returned. * * @throws NullPointerException if the last element is null; if this is a possibility, use * {@link Iterables#getLast} instead. */ public final Optional<E> last() { // Iterables#getLast was inlined here so we don't have to throw/catch a NSEE // TODO(kevinb): Support a concurrently modified collection? if (iterable instanceof List) { List<E> list = (List<E>) iterable; if (list.isEmpty()) { return Optional.absent(); } return Optional.of(list.get(list.size() - 1)); } Iterator<E> iterator = iterable.iterator(); if (!iterator.hasNext()) { return Optional.absent(); } /* * TODO(kevinb): consider whether this "optimization" is worthwhile. Users * with SortedSets tend to know they are SortedSets and probably would not * call this method. */ if (iterable instanceof SortedSet) { SortedSet<E> sortedSet = (SortedSet<E>) iterable; return Optional.of(sortedSet.last()); } while (true) { E current = iterator.next(); if (!iterator.hasNext()) { return Optional.of(current); } } } /** * Returns a view of this fluent iterable that skips its first {@code numberToSkip} * elements. If this fluent iterable contains fewer than {@code numberToSkip} elements, * the returned fluent iterable skips all of its elements. * * <p>Modifications to this fluent iterable before a call to {@code iterator()} are * reflected in the returned fluent iterable. That is, the its iterator skips the first * {@code numberToSkip} elements that exist when the iterator is created, not when {@code skip()} * is called. * * <p>The returned fluent iterable's iterator supports {@code remove()} if the * {@code Iterator} of this fluent iterable supports it. Note that it is <i>not</i> * possible to delete the last skipped element by immediately calling {@code remove()} on the * returned fluent iterable's iterator, as the {@code Iterator} contract states that a call * to {@code * remove()} before a call to {@code next()} will throw an * {@link IllegalStateException}. */ @CheckReturnValue public final FluentIterable<E> skip(int numberToSkip) { return from(Iterables.skip(iterable, numberToSkip)); } /** * Creates a fluent iterable with the first {@code size} elements of this * fluent iterable. If this fluent iterable does not contain that many elements, * the returned fluent iterable will have the same behavior as this fluent iterable. * The returned fluent iterable's iterator supports {@code remove()} if this * fluent iterable's iterator does. * * @param size the maximum number of elements in the returned fluent iterable * @throws IllegalArgumentException if {@code size} is negative */ @CheckReturnValue public final FluentIterable<E> limit(int size) { return from(Iterables.limit(iterable, size)); } /** * Determines whether this fluent iterable is empty. */ public final boolean isEmpty() { return !iterable.iterator().hasNext(); } /** * Returns an {@code ImmutableList} containing all of the elements from this fluent iterable in * proper sequence. * * @since 14.0 (since 12.0 as {@code toImmutableList()}). */ public final ImmutableList<E> toList() { return ImmutableList.copyOf(iterable); } /** * Returns an {@code ImmutableList} containing all of the elements from this {@code * FluentIterable} in the order specified by {@code comparator}. To produce an {@code * ImmutableList} sorted by its natural ordering, use {@code toSortedList(Ordering.natural())}. * * @param comparator the function by which to sort list elements * @throws NullPointerException if any element is null * @since 14.0 (since 13.0 as {@code toSortedImmutableList()}). */ @Beta public final ImmutableList<E> toSortedList(Comparator<? super E> comparator) { return Ordering.from(comparator).immutableSortedCopy(iterable); } /** * Returns an {@code ImmutableSet} containing all of the elements from this fluent iterable with * duplicates removed. * * @since 14.0 (since 12.0 as {@code toImmutableSet()}). */ public final ImmutableSet<E> toSet() { return ImmutableSet.copyOf(iterable); } /** * Returns an {@code ImmutableSortedSet} containing all of the elements from this {@code * FluentIterable} in the order specified by {@code comparator}, with duplicates (determined by * {@code comparator.compare(x, y) == 0}) removed. To produce an {@code ImmutableSortedSet} sorted * by its natural ordering, use {@code toSortedSet(Ordering.natural())}. * * @param comparator the function by which to sort set elements * @throws NullPointerException if any element is null * @since 14.0 (since 12.0 as {@code toImmutableSortedSet()}). */ public final ImmutableSortedSet<E> toSortedSet(Comparator<? super E> comparator) { return ImmutableSortedSet.copyOf(comparator, iterable); } /** * Returns an immutable map for which the elements of this {@code FluentIterable} are the keys in * the same order, mapped to values by the given function. If this iterable contains duplicate * elements, the returned map will contain each distinct element once in the order it first * appears. * * @throws NullPointerException if any element of this iterable is {@code null}, or if {@code * valueFunction} produces {@code null} for any key * @since 14.0 */ public final <V> ImmutableMap<E, V> toMap(Function<? super E, V> valueFunction) { return Maps.toMap(iterable, valueFunction); } /** * Creates an index {@code ImmutableListMultimap} that contains the results of applying a * specified function to each item in this {@code FluentIterable} of values. Each element of this * iterable will be stored as a value in the resulting multimap, yielding a multimap with the same * size as this iterable. The key used to store that value in the multimap will be the result of * calling the function on that value. The resulting multimap is created as an immutable snapshot. * In the returned multimap, keys appear in the order they are first encountered, and the values * corresponding to each key appear in the same order as they are encountered. * * @param keyFunction the function used to produce the key for each value * @throws NullPointerException if any of the following cases is true: * <ul> * <li>{@code keyFunction} is null * <li>An element in this fluent iterable is null * <li>{@code keyFunction} returns {@code null} for any element of this iterable * </ul> * @since 14.0 */ public final <K> ImmutableListMultimap<K, E> index(Function<? super E, K> keyFunction) { return Multimaps.index(iterable, keyFunction); } /** * Returns an immutable map for which the {@link java.util.Map#values} are the elements of this * {@code FluentIterable} in the given order, and each key is the product of invoking a supplied * function on its corresponding value. * * @param keyFunction the function used to produce the key for each value * @throws IllegalArgumentException if {@code keyFunction} produces the same key for more than one * value in this fluent iterable * @throws NullPointerException if any element of this fluent iterable is null, or if * {@code keyFunction} produces {@code null} for any value * @since 14.0 */ public final <K> ImmutableMap<K, E> uniqueIndex(Function<? super E, K> keyFunction) { return Maps.uniqueIndex(iterable, keyFunction); } /** * Returns an array containing all of the elements from this fluent iterable in iteration order. * * @param type the type of the elements * @return a newly-allocated array into which all the elements of this fluent iterable have * been copied */ @GwtIncompatible("Array.newArray(Class, int)") public final E[] toArray(Class<E> type) { return Iterables.toArray(iterable, type); } /** * Copies all the elements from this fluent iterable to {@code collection}. This is equivalent to * calling {@code Iterables.addAll(collection, this)}. * * @param collection the collection to copy elements to * @return {@code collection}, for convenience * @since 14.0 */ public final <C extends Collection<? super E>> C copyInto(C collection) { checkNotNull(collection); if (iterable instanceof Collection) { collection.addAll(Collections2.cast(iterable)); } else { for (E item : iterable) { collection.add(item); } } return collection; } /** * Returns the element at the specified position in this fluent iterable. * * @param position position of the element to return * @return the element at the specified position in this fluent iterable * @throws IndexOutOfBoundsException if {@code position} is negative or greater than or equal to * the size of this fluent iterable */ public final E get(int position) { return Iterables.get(iterable, position); } /** * Function that transforms {@code Iterable<E>} into a fluent iterable. */ private static class FromIterableFunction<E> implements Function<Iterable<E>, FluentIterable<E>> { @Override public FluentIterable<E> apply(Iterable<E> fromObject) { return FluentIterable.from(fromObject); } } }
zzhhhhh-aw4rwer
guava/src/com/google/common/collect/FluentIterable.java
Java
asf20
18,726
/* * Copyright (C) 2007 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import com.google.common.annotations.GwtCompatible; import com.google.common.annotations.GwtIncompatible; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.util.LinkedHashMap; /** * A {@code Multiset} implementation with predictable iteration order. Its * iterator orders elements according to when the first occurrence of the * element was added. When the multiset contains multiple instances of an * element, those instances are consecutive in the iteration order. If all * occurrences of an element are removed, after which that element is added to * the multiset, the element will appear at the end of the iteration. * * <p>See the Guava User Guide article on <a href= * "http://code.google.com/p/guava-libraries/wiki/NewCollectionTypesExplained#Multiset"> * {@code Multiset}</a>. * * @author Kevin Bourrillion * @author Jared Levy * @since 2.0 (imported from Google Collections Library) */ @GwtCompatible(serializable = true, emulated = true) @SuppressWarnings("serial") // we're overriding default serialization public final class LinkedHashMultiset<E> extends AbstractMapBasedMultiset<E> { /** * Creates a new, empty {@code LinkedHashMultiset} using the default initial * capacity. */ public static <E> LinkedHashMultiset<E> create() { return new LinkedHashMultiset<E>(); } /** * Creates a new, empty {@code LinkedHashMultiset} with the specified expected * number of distinct elements. * * @param distinctElements the expected number of distinct elements * @throws IllegalArgumentException if {@code distinctElements} is negative */ public static <E> LinkedHashMultiset<E> create(int distinctElements) { return new LinkedHashMultiset<E>(distinctElements); } /** * Creates a new {@code LinkedHashMultiset} containing the specified elements. * * <p>This implementation is highly efficient when {@code elements} is itself * a {@link Multiset}. * * @param elements the elements that the multiset should contain */ public static <E> LinkedHashMultiset<E> create( Iterable<? extends E> elements) { LinkedHashMultiset<E> multiset = create(Multisets.inferDistinctElements(elements)); Iterables.addAll(multiset, elements); return multiset; } private LinkedHashMultiset() { super(new LinkedHashMap<E, Count>()); } private LinkedHashMultiset(int distinctElements) { // Could use newLinkedHashMapWithExpectedSize() if it existed super(new LinkedHashMap<E, Count>(Maps.capacity(distinctElements))); } /** * @serialData the number of distinct elements, the first element, its count, * the second element, its count, and so on */ @GwtIncompatible("java.io.ObjectOutputStream") private void writeObject(ObjectOutputStream stream) throws IOException { stream.defaultWriteObject(); Serialization.writeMultiset(this, stream); } @GwtIncompatible("java.io.ObjectInputStream") private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException { stream.defaultReadObject(); int distinctElements = Serialization.readCount(stream); setBackingMap(new LinkedHashMap<E, Count>( Maps.capacity(distinctElements))); Serialization.populateMultiset(this, stream, distinctElements); } @GwtIncompatible("not needed in emulated source") private static final long serialVersionUID = 0; }
zzhhhhh-aw4rwer
guava/src/com/google/common/collect/LinkedHashMultiset.java
Java
asf20
4,098
/* * Copyright (C) 2007 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import com.google.common.annotations.GwtCompatible; import java.util.Collection; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import javax.annotation.Nullable; /** * A multimap which forwards all its method calls to another multimap. * Subclasses should override one or more methods to modify the behavior of * the backing multimap as desired per the <a * href="http://en.wikipedia.org/wiki/Decorator_pattern">decorator pattern</a>. * * @author Robert Konigsberg * @since 2.0 (imported from Google Collections Library) */ @GwtCompatible public abstract class ForwardingMultimap<K, V> extends ForwardingObject implements Multimap<K, V> { /** Constructor for use by subclasses. */ protected ForwardingMultimap() {} @Override protected abstract Multimap<K, V> delegate(); @Override public Map<K, Collection<V>> asMap() { return delegate().asMap(); } @Override public void clear() { delegate().clear(); } @Override public boolean containsEntry(@Nullable Object key, @Nullable Object value) { return delegate().containsEntry(key, value); } @Override public boolean containsKey(@Nullable Object key) { return delegate().containsKey(key); } @Override public boolean containsValue(@Nullable Object value) { return delegate().containsValue(value); } @Override public Collection<Entry<K, V>> entries() { return delegate().entries(); } @Override public Collection<V> get(@Nullable K key) { return delegate().get(key); } @Override public boolean isEmpty() { return delegate().isEmpty(); } @Override public Multiset<K> keys() { return delegate().keys(); } @Override public Set<K> keySet() { return delegate().keySet(); } @Override public boolean put(K key, V value) { return delegate().put(key, value); } @Override public boolean putAll(K key, Iterable<? extends V> values) { return delegate().putAll(key, values); } @Override public boolean putAll(Multimap<? extends K, ? extends V> multimap) { return delegate().putAll(multimap); } @Override public boolean remove(@Nullable Object key, @Nullable Object value) { return delegate().remove(key, value); } @Override public Collection<V> removeAll(@Nullable Object key) { return delegate().removeAll(key); } @Override public Collection<V> replaceValues(K key, Iterable<? extends V> values) { return delegate().replaceValues(key, values); } @Override public int size() { return delegate().size(); } @Override public Collection<V> values() { return delegate().values(); } @Override public boolean equals(@Nullable Object object) { return object == this || delegate().equals(object); } @Override public int hashCode() { return delegate().hashCode(); } }
zzhhhhh-aw4rwer
guava/src/com/google/common/collect/ForwardingMultimap.java
Java
asf20
3,489
/* * Copyright (C) 2009 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import com.google.common.annotations.GwtCompatible; /** * Implementation of {@link ImmutableListMultimap} with no entries. * * @author Mike Ward */ @GwtCompatible(serializable = true) class EmptyImmutableSetMultimap extends ImmutableSetMultimap<Object, Object> { static final EmptyImmutableSetMultimap INSTANCE = new EmptyImmutableSetMultimap(); private EmptyImmutableSetMultimap() { super(ImmutableMap.<Object, ImmutableSet<Object>>of(), 0, null); } private Object readResolve() { return INSTANCE; // preserve singleton property } private static final long serialVersionUID = 0; }
zzhhhhh-aw4rwer
guava/src/com/google/common/collect/EmptyImmutableSetMultimap.java
Java
asf20
1,254
/* * Copyright (C) 2007 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import static com.google.common.base.Preconditions.checkNotNull; import com.google.common.annotations.GwtCompatible; import com.google.common.base.Function; import com.google.common.base.Objects; import java.io.Serializable; import javax.annotation.Nullable; /** * An ordering that orders elements by applying an order to the result of a * function on those elements. */ @GwtCompatible(serializable = true) final class ByFunctionOrdering<F, T> extends Ordering<F> implements Serializable { final Function<F, ? extends T> function; final Ordering<T> ordering; ByFunctionOrdering( Function<F, ? extends T> function, Ordering<T> ordering) { this.function = checkNotNull(function); this.ordering = checkNotNull(ordering); } @Override public int compare(F left, F right) { return ordering.compare(function.apply(left), function.apply(right)); } @Override public boolean equals(@Nullable Object object) { if (object == this) { return true; } if (object instanceof ByFunctionOrdering) { ByFunctionOrdering<?, ?> that = (ByFunctionOrdering<?, ?>) object; return this.function.equals(that.function) && this.ordering.equals(that.ordering); } return false; } @Override public int hashCode() { return Objects.hashCode(function, ordering); } @Override public String toString() { return ordering + ".onResultOf(" + function + ")"; } private static final long serialVersionUID = 0; }
zzhhhhh-aw4rwer
guava/src/com/google/common/collect/ByFunctionOrdering.java
Java
asf20
2,124
/* * Copyright (C) 2013 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.reflect; import com.google.common.collect.Sets; import java.lang.reflect.GenericArrayType; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.lang.reflect.TypeVariable; import java.lang.reflect.WildcardType; import java.util.Set; import javax.annotation.concurrent.NotThreadSafe; /** * Based on what a {@link Type} is, dispatch it to the corresponding {@code visit*} method. By * default, no recursion is done for type arguments or type bounds. But subclasses can opt to do * recursion by calling {@link #visit} for any {@code Type} while visitation is in progress. For * example, this can be used to reject wildcards or type variables contained in a type as in: * * <pre> {@code * new TypeVisitor() { * protected void visitParameterizedType(ParameterizedType t) { * visit(t.getOwnerType()); * visit(t.getActualTypeArguments()); * } * protected void visitGenericArrayType(GenericArrayType t) { * visit(t.getGenericComponentType()); * } * protected void visitTypeVariable(TypeVariable<?> t) { * throw new IllegalArgumentException("Cannot contain type variable."); * } * protected void visitWildcardType(WildcardType t) { * throw new IllegalArgumentException("Cannot contain wildcard type."); * } * }.visit(type);}</pre> * * <p>One {@code Type} is visited at most once. The second time the same type is visited, it's * ignored by {@link #visit}. This avoids infinite recursion caused by recursive type bounds. * * <p>This class is <em>not</em> thread safe. * * @author Ben Yu */ @NotThreadSafe abstract class TypeVisitor { private final Set<Type> visited = Sets.newHashSet(); /** * Visits the given types. Null types are ignored. This allows subclasses to call * {@code visit(parameterizedType.getOwnerType())} safely without having to check nulls. */ public final void visit(Type... types) { for (Type type : types) { if (type == null || !visited.add(type)) { // null owner type, or already visited; continue; } boolean succeeded = false; try { if (type instanceof TypeVariable) { visitTypeVariable((TypeVariable<?>) type); } else if (type instanceof WildcardType) { visitWildcardType((WildcardType) type); } else if (type instanceof ParameterizedType) { visitParameterizedType((ParameterizedType) type); } else if (type instanceof Class) { visitClass((Class<?>) type); } else if (type instanceof GenericArrayType) { visitGenericArrayType((GenericArrayType) type); } else { throw new AssertionError("Unknown type: " + type); } succeeded = true; } finally { if (!succeeded) { // When the visitation failed, we don't want to ignore the second. visited.remove(type); } } } } void visitClass(Class<?> t) {} void visitGenericArrayType(GenericArrayType t) {} void visitParameterizedType(ParameterizedType t) {} void visitTypeVariable(TypeVariable<?> t) {} void visitWildcardType(WildcardType t) {} }
zzhhhhh-aw4rwer
guava/src/com/google/common/reflect/TypeVisitor.java
Java
asf20
3,799
/* * Copyright (C) 2011 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.reflect; import static com.google.common.base.Preconditions.checkArgument; import com.google.common.annotations.Beta; import java.lang.reflect.Type; import java.lang.reflect.TypeVariable; import javax.annotation.Nullable; /** * Captures a free type variable that can be used in {@link TypeToken#where}. * For example: * * <pre> {@code * static <T> TypeToken<List<T>> listOf(Class<T> elementType) { * return new TypeToken<List<T>>() {} * .where(new TypeParameter<T>() {}, elementType); * }}</pre> * * @author Ben Yu * @since 12.0 */ @Beta public abstract class TypeParameter<T> extends TypeCapture<T> { final TypeVariable<?> typeVariable; protected TypeParameter() { Type type = capture(); checkArgument(type instanceof TypeVariable, "%s should be a type variable.", type); this.typeVariable = (TypeVariable<?>) type; } @Override public final int hashCode() { return typeVariable.hashCode(); } @Override public final boolean equals(@Nullable Object o) { if (o instanceof TypeParameter) { TypeParameter<?> that = (TypeParameter<?>) o; return typeVariable.equals(that.typeVariable); } return false; } @Override public String toString() { return typeVariable.toString(); } }
zzhhhhh-aw4rwer
guava/src/com/google/common/reflect/TypeParameter.java
Java
asf20
1,901
/* * Copyright (C) 2012 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * This package contains utilities to work with Java reflection. * It is a part of the open-source * <a href="http://guava-libraries.googlecode.com">Guava libraries</a>. */ @javax.annotation.ParametersAreNonnullByDefault package com.google.common.reflect;
zzhhhhh-aw4rwer
guava/src/com/google/common/reflect/package-info.java
Java
asf20
865
/* * Copyright (C) 2006 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.reflect; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Preconditions.checkState; import com.google.common.annotations.Beta; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Joiner; import com.google.common.base.Predicate; import com.google.common.collect.FluentIterable; import com.google.common.collect.ForwardingSet; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Maps; import com.google.common.collect.Ordering; import com.google.common.primitives.Primitives; import java.io.Serializable; import java.lang.reflect.Constructor; import java.lang.reflect.GenericArrayType; import java.lang.reflect.Method; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.lang.reflect.TypeVariable; import java.lang.reflect.WildcardType; import java.util.Arrays; import java.util.Comparator; import java.util.Map; import java.util.Set; import javax.annotation.Nullable; /** * A {@link Type} with generics. * * <p>Operations that are otherwise only available in {@link Class} are implemented to support * {@code Type}, for example {@link #isAssignableFrom}, {@link #isArray} and {@link * #getComponentType}. It also provides additional utilities such as {@link #getTypes} and {@link * #resolveType} etc. * * <p>There are three ways to get a {@code TypeToken} instance: <ul> * <li>Wrap a {@code Type} obtained via reflection. For example: {@code * TypeToken.of(method.getGenericReturnType())}. * <li>Capture a generic type with a (usually anonymous) subclass. For example: <pre> {@code * new TypeToken<List<String>>() {}}</pre> * <p>Note that it's critical that the actual type argument is carried by a subclass. * The following code is wrong because it only captures the {@code <T>} type variable * of the {@code listType()} method signature; while {@code <String>} is lost in erasure: * <pre> {@code * class Util { * static <T> TypeToken<List<T>> listType() { * return new TypeToken<List<T>>() {}; * } * } * * TypeToken<List<String>> stringListType = Util.<String>listType();}</pre> * <li>Capture a generic type with a (usually anonymous) subclass and resolve it against * a context class that knows what the type parameters are. For example: <pre> {@code * abstract class IKnowMyType<T> { * TypeToken<T> type = new TypeToken<T>(getClass()) {}; * } * new IKnowMyType<String>() {}.type => String}</pre> * </ul> * * <p>{@code TypeToken} is serializable when no type variable is contained in the type. * * <p>Note to Guice users: {@code} TypeToken is similar to Guice's {@code TypeLiteral} class * except that it is serializable and offers numerous additional utility methods. * * @author Bob Lee * @author Sven Mawson * @author Ben Yu * @since 12.0 */ @Beta @SuppressWarnings("serial") // SimpleTypeToken is the serialized form. public abstract class TypeToken<T> extends TypeCapture<T> implements Serializable { private final Type runtimeType; /** Resolver for resolving types with {@link #runtimeType} as context. */ private transient TypeResolver typeResolver; /** * Constructs a new type token of {@code T}. * * <p>Clients create an empty anonymous subclass. Doing so embeds the type * parameter in the anonymous class's type hierarchy so we can reconstitute * it at runtime despite erasure. * * <p>For example: <pre> {@code * TypeToken<List<String>> t = new TypeToken<List<String>>() {};}</pre> */ protected TypeToken() { this.runtimeType = capture(); checkState(!(runtimeType instanceof TypeVariable), "Cannot construct a TypeToken for a type variable.\n" + "You probably meant to call new TypeToken<%s>(getClass()) " + "that can resolve the type variable for you.\n" + "If you do need to create a TypeToken of a type variable, " + "please use TypeToken.of() instead.", runtimeType); } /** * Constructs a new type token of {@code T} while resolving free type variables in the context of * {@code declaringClass}. * * <p>Clients create an empty anonymous subclass. Doing so embeds the type * parameter in the anonymous class's type hierarchy so we can reconstitute * it at runtime despite erasure. * * <p>For example: <pre> {@code * abstract class IKnowMyType<T> { * TypeToken<T> getMyType() { * return new TypeToken<T>(getClass()) {}; * } * } * * new IKnowMyType<String>() {}.getMyType() => String}</pre> */ protected TypeToken(Class<?> declaringClass) { Type captured = super.capture(); if (captured instanceof Class) { this.runtimeType = captured; } else { this.runtimeType = of(declaringClass).resolveType(captured).runtimeType; } } private TypeToken(Type type) { this.runtimeType = checkNotNull(type); } /** Returns an instance of type token that wraps {@code type}. */ public static <T> TypeToken<T> of(Class<T> type) { return new SimpleTypeToken<T>(type); } /** Returns an instance of type token that wraps {@code type}. */ public static TypeToken<?> of(Type type) { return new SimpleTypeToken<Object>(type); } /** * Returns the raw type of {@code T}. Formally speaking, if {@code T} is returned by * {@link java.lang.reflect.Method#getGenericReturnType}, the raw type is what's returned by * {@link java.lang.reflect.Method#getReturnType} of the same method object. Specifically: * <ul> * <li>If {@code T} is a {@code Class} itself, {@code T} itself is returned. * <li>If {@code T} is a {@link ParameterizedType}, the raw type of the parameterized type is * returned. * <li>If {@code T} is a {@link GenericArrayType}, the returned type is the corresponding array * class. For example: {@code List<Integer>[] => List[]}. * <li>If {@code T} is a type variable or a wildcard type, the raw type of the first upper bound * is returned. For example: {@code <X extends Foo> => Foo}. * </ul> */ public final Class<? super T> getRawType() { Class<?> rawType = getRawType(runtimeType); @SuppressWarnings("unchecked") // raw type is |T| Class<? super T> result = (Class<? super T>) rawType; return result; } /** * Returns the raw type of the class or parameterized type; if {@code T} is type variable or * wildcard type, the raw types of all its upper bounds are returned. */ private ImmutableSet<Class<? super T>> getImmediateRawTypes() { // Cast from ImmutableSet<Class<?>> to ImmutableSet<Class<? super T>> @SuppressWarnings({"unchecked", "rawtypes"}) ImmutableSet<Class<? super T>> result = (ImmutableSet) getRawTypes(runtimeType); return result; } /** Returns the represented type. */ public final Type getType() { return runtimeType; } /** * <p>Returns a new {@code TypeToken} where type variables represented by {@code typeParam} * are substituted by {@code typeArg}. For example, it can be used to construct * {@code Map<K, V>} for any {@code K} and {@code V} type: <pre> {@code * static <K, V> TypeToken<Map<K, V>> mapOf( * TypeToken<K> keyType, TypeToken<V> valueType) { * return new TypeToken<Map<K, V>>() {} * .where(new TypeParameter<K>() {}, keyType) * .where(new TypeParameter<V>() {}, valueType); * }}</pre> * * @param <X> The parameter type * @param typeParam the parameter type variable * @param typeArg the actual type to substitute */ public final <X> TypeToken<T> where(TypeParameter<X> typeParam, TypeToken<X> typeArg) { TypeResolver resolver = new TypeResolver() .where(ImmutableMap.of( new TypeResolver.TypeVariableKey(typeParam.typeVariable), typeArg.runtimeType)); // If there's any type error, we'd report now rather than later. return new SimpleTypeToken<T>(resolver.resolveType(runtimeType)); } /** * <p>Returns a new {@code TypeToken} where type variables represented by {@code typeParam} * are substituted by {@code typeArg}. For example, it can be used to construct * {@code Map<K, V>} for any {@code K} and {@code V} type: <pre> {@code * static <K, V> TypeToken<Map<K, V>> mapOf( * Class<K> keyType, Class<V> valueType) { * return new TypeToken<Map<K, V>>() {} * .where(new TypeParameter<K>() {}, keyType) * .where(new TypeParameter<V>() {}, valueType); * }}</pre> * * @param <X> The parameter type * @param typeParam the parameter type variable * @param typeArg the actual type to substitute */ public final <X> TypeToken<T> where(TypeParameter<X> typeParam, Class<X> typeArg) { return where(typeParam, of(typeArg)); } /** * <p>Resolves the given {@code type} against the type context represented by this type. * For example: <pre> {@code * new TypeToken<List<String>>() {}.resolveType( * List.class.getMethod("get", int.class).getGenericReturnType()) * => String.class}</pre> */ public final TypeToken<?> resolveType(Type type) { checkNotNull(type); TypeResolver resolver = typeResolver; if (resolver == null) { resolver = (typeResolver = TypeResolver.accordingTo(runtimeType)); } return of(resolver.resolveType(type)); } private Type[] resolveInPlace(Type[] types) { for (int i = 0; i < types.length; i++) { types[i] = resolveType(types[i]).getType(); } return types; } private TypeToken<?> resolveSupertype(Type type) { TypeToken<?> supertype = resolveType(type); // super types' type mapping is a subset of type mapping of this type. supertype.typeResolver = typeResolver; return supertype; } /** * Returns the generic superclass of this type or {@code null} if the type represents * {@link Object} or an interface. This method is similar but different from {@link * Class#getGenericSuperclass}. For example, {@code * new TypeToken<StringArrayList>() {}.getGenericSuperclass()} will return {@code * new TypeToken<ArrayList<String>>() {}}; while {@code * StringArrayList.class.getGenericSuperclass()} will return {@code ArrayList<E>}, where {@code E} * is the type variable declared by class {@code ArrayList}. * * <p>If this type is a type variable or wildcard, its first upper bound is examined and returned * if the bound is a class or extends from a class. This means that the returned type could be a * type variable too. */ @Nullable final TypeToken<? super T> getGenericSuperclass() { if (runtimeType instanceof TypeVariable) { // First bound is always the super class, if one exists. return boundAsSuperclass(((TypeVariable<?>) runtimeType).getBounds()[0]); } if (runtimeType instanceof WildcardType) { // wildcard has one and only one upper bound. return boundAsSuperclass(((WildcardType) runtimeType).getUpperBounds()[0]); } Type superclass = getRawType().getGenericSuperclass(); if (superclass == null) { return null; } @SuppressWarnings("unchecked") // super class of T TypeToken<? super T> superToken = (TypeToken<? super T>) resolveSupertype(superclass); return superToken; } @Nullable private TypeToken<? super T> boundAsSuperclass(Type bound) { TypeToken<?> token = of(bound); if (token.getRawType().isInterface()) { return null; } @SuppressWarnings("unchecked") // only upper bound of T is passed in. TypeToken<? super T> superclass = (TypeToken<? super T>) token; return superclass; } /** * Returns the generic interfaces that this type directly {@code implements}. This method is * similar but different from {@link Class#getGenericInterfaces()}. For example, {@code * new TypeToken<List<String>>() {}.getGenericInterfaces()} will return a list that contains * {@code new TypeToken<Iterable<String>>() {}}; while {@code List.class.getGenericInterfaces()} * will return an array that contains {@code Iterable<T>}, where the {@code T} is the type * variable declared by interface {@code Iterable}. * * <p>If this type is a type variable or wildcard, its upper bounds are examined and those that * are either an interface or upper-bounded only by interfaces are returned. This means that the * returned types could include type variables too. */ final ImmutableList<TypeToken<? super T>> getGenericInterfaces() { if (runtimeType instanceof TypeVariable) { return boundsAsInterfaces(((TypeVariable<?>) runtimeType).getBounds()); } if (runtimeType instanceof WildcardType) { return boundsAsInterfaces(((WildcardType) runtimeType).getUpperBounds()); } ImmutableList.Builder<TypeToken<? super T>> builder = ImmutableList.builder(); for (Type interfaceType : getRawType().getGenericInterfaces()) { @SuppressWarnings("unchecked") // interface of T TypeToken<? super T> resolvedInterface = (TypeToken<? super T>) resolveSupertype(interfaceType); builder.add(resolvedInterface); } return builder.build(); } private ImmutableList<TypeToken<? super T>> boundsAsInterfaces(Type[] bounds) { ImmutableList.Builder<TypeToken<? super T>> builder = ImmutableList.builder(); for (Type bound : bounds) { @SuppressWarnings("unchecked") // upper bound of T TypeToken<? super T> boundType = (TypeToken<? super T>) of(bound); if (boundType.getRawType().isInterface()) { builder.add(boundType); } } return builder.build(); } /** * Returns the set of interfaces and classes that this type is or is a subtype of. The returned * types are parameterized with proper type arguments. * * <p>Subtypes are always listed before supertypes. But the reverse is not true. A type isn't * necessarily a subtype of all the types following. Order between types without subtype * relationship is arbitrary and not guaranteed. * * <p>If this type is a type variable or wildcard, upper bounds that are themselves type variables * aren't included (their super interfaces and superclasses are). */ public final TypeSet getTypes() { return new TypeSet(); } /** * Returns the generic form of {@code superclass}. For example, if this is * {@code ArrayList<String>}, {@code Iterable<String>} is returned given the * input {@code Iterable.class}. */ public final TypeToken<? super T> getSupertype(Class<? super T> superclass) { checkArgument(superclass.isAssignableFrom(getRawType()), "%s is not a super class of %s", superclass, this); if (runtimeType instanceof TypeVariable) { return getSupertypeFromUpperBounds(superclass, ((TypeVariable<?>) runtimeType).getBounds()); } if (runtimeType instanceof WildcardType) { return getSupertypeFromUpperBounds(superclass, ((WildcardType) runtimeType).getUpperBounds()); } if (superclass.isArray()) { return getArraySupertype(superclass); } @SuppressWarnings("unchecked") // resolved supertype TypeToken<? super T> supertype = (TypeToken<? super T>) resolveSupertype(toGenericType(superclass).runtimeType); return supertype; } /** * Returns subtype of {@code this} with {@code subclass} as the raw class. * For example, if this is {@code Iterable<String>} and {@code subclass} is {@code List}, * {@code List<String>} is returned. */ public final TypeToken<? extends T> getSubtype(Class<?> subclass) { checkArgument(!(runtimeType instanceof TypeVariable), "Cannot get subtype of type variable <%s>", this); if (runtimeType instanceof WildcardType) { return getSubtypeFromLowerBounds(subclass, ((WildcardType) runtimeType).getLowerBounds()); } checkArgument(getRawType().isAssignableFrom(subclass), "%s isn't a subclass of %s", subclass, this); // unwrap array type if necessary if (isArray()) { return getArraySubtype(subclass); } @SuppressWarnings("unchecked") // guarded by the isAssignableFrom() statement above TypeToken<? extends T> subtype = (TypeToken<? extends T>) of(resolveTypeArgsForSubclass(subclass)); return subtype; } /** Returns true if this type is assignable from the given {@code type}. */ public final boolean isAssignableFrom(TypeToken<?> type) { return isAssignableFrom(type.runtimeType); } /** Check if this type is assignable from the given {@code type}. */ public final boolean isAssignableFrom(Type type) { return isAssignable(checkNotNull(type), runtimeType); } /** * Returns true if this type is known to be an array type, such as {@code int[]}, {@code T[]}, * {@code <? extends Map<String, Integer>[]>} etc. */ public final boolean isArray() { return getComponentType() != null; } /** * Returns true if this type is one of the nine primitive types (including {@code void}). * * @since 15.0 */ public final boolean isPrimitive() { return (runtimeType instanceof Class) && ((Class<?>) runtimeType).isPrimitive(); } /** * Returns the corresponding wrapper type if this is a primitive type; otherwise returns * {@code this} itself. Idempotent. * * @since 15.0 */ public final TypeToken<T> wrap() { if (isPrimitive()) { @SuppressWarnings("unchecked") // this is a primitive class Class<T> type = (Class<T>) runtimeType; return TypeToken.of(Primitives.wrap(type)); } return this; } private boolean isWrapper() { return Primitives.allWrapperTypes().contains(runtimeType); } /** * Returns the corresponding primitive type if this is a wrapper type; otherwise returns * {@code this} itself. Idempotent. * * @since 15.0 */ public final TypeToken<T> unwrap() { if (isWrapper()) { @SuppressWarnings("unchecked") // this is a wrapper class Class<T> type = (Class<T>) runtimeType; return TypeToken.of(Primitives.unwrap(type)); } return this; } /** * Returns the array component type if this type represents an array ({@code int[]}, {@code T[]}, * {@code <? extends Map<String, Integer>[]>} etc.), or else {@code null} is returned. */ @Nullable public final TypeToken<?> getComponentType() { Type componentType = Types.getComponentType(runtimeType); if (componentType == null) { return null; } return of(componentType); } /** * Returns the {@link Invokable} for {@code method}, which must be a member of {@code T}. * * @since 14.0 */ public final Invokable<T, Object> method(Method method) { checkArgument(of(method.getDeclaringClass()).isAssignableFrom(this), "%s not declared by %s", method, this); return new Invokable.MethodInvokable<T>(method) { @Override Type getGenericReturnType() { return resolveType(super.getGenericReturnType()).getType(); } @Override Type[] getGenericParameterTypes() { return resolveInPlace(super.getGenericParameterTypes()); } @Override Type[] getGenericExceptionTypes() { return resolveInPlace(super.getGenericExceptionTypes()); } @Override public TypeToken<T> getOwnerType() { return TypeToken.this; } @Override public String toString() { return getOwnerType() + "." + super.toString(); } }; } /** * Returns the {@link Invokable} for {@code constructor}, which must be a member of {@code T}. * * @since 14.0 */ public final Invokable<T, T> constructor(Constructor<?> constructor) { checkArgument(constructor.getDeclaringClass() == getRawType(), "%s not declared by %s", constructor, getRawType()); return new Invokable.ConstructorInvokable<T>(constructor) { @Override Type getGenericReturnType() { return resolveType(super.getGenericReturnType()).getType(); } @Override Type[] getGenericParameterTypes() { return resolveInPlace(super.getGenericParameterTypes()); } @Override Type[] getGenericExceptionTypes() { return resolveInPlace(super.getGenericExceptionTypes()); } @Override public TypeToken<T> getOwnerType() { return TypeToken.this; } @Override public String toString() { return getOwnerType() + "(" + Joiner.on(", ").join(getGenericParameterTypes()) + ")"; } }; } /** * The set of interfaces and classes that {@code T} is or is a subtype of. {@link Object} is not * included in the set if this type is an interface. */ public class TypeSet extends ForwardingSet<TypeToken<? super T>> implements Serializable { private transient ImmutableSet<TypeToken<? super T>> types; TypeSet() {} /** Returns the types that are interfaces implemented by this type. */ public TypeSet interfaces() { return new InterfaceSet(this); } /** Returns the types that are classes. */ public TypeSet classes() { return new ClassSet(); } @Override protected Set<TypeToken<? super T>> delegate() { ImmutableSet<TypeToken<? super T>> filteredTypes = types; if (filteredTypes == null) { // Java has no way to express ? super T when we parameterize TypeToken vs. Class. @SuppressWarnings({"unchecked", "rawtypes"}) ImmutableList<TypeToken<? super T>> collectedTypes = (ImmutableList) TypeCollector.FOR_GENERIC_TYPE.collectTypes(TypeToken.this); return (types = FluentIterable.from(collectedTypes) .filter(TypeFilter.IGNORE_TYPE_VARIABLE_OR_WILDCARD) .toSet()); } else { return filteredTypes; } } /** Returns the raw types of the types in this set, in the same order. */ public Set<Class<? super T>> rawTypes() { // Java has no way to express ? super T when we parameterize TypeToken vs. Class. @SuppressWarnings({"unchecked", "rawtypes"}) ImmutableList<Class<? super T>> collectedTypes = (ImmutableList) TypeCollector.FOR_RAW_TYPE.collectTypes(getImmediateRawTypes()); return ImmutableSet.copyOf(collectedTypes); } private static final long serialVersionUID = 0; } private final class InterfaceSet extends TypeSet { private transient final TypeSet allTypes; private transient ImmutableSet<TypeToken<? super T>> interfaces; InterfaceSet(TypeSet allTypes) { this.allTypes = allTypes; } @Override protected Set<TypeToken<? super T>> delegate() { ImmutableSet<TypeToken<? super T>> result = interfaces; if (result == null) { return (interfaces = FluentIterable.from(allTypes) .filter(TypeFilter.INTERFACE_ONLY) .toSet()); } else { return result; } } @Override public TypeSet interfaces() { return this; } @Override public Set<Class<? super T>> rawTypes() { // Java has no way to express ? super T when we parameterize TypeToken vs. Class. @SuppressWarnings({"unchecked", "rawtypes"}) ImmutableList<Class<? super T>> collectedTypes = (ImmutableList) TypeCollector.FOR_RAW_TYPE.collectTypes(getImmediateRawTypes()); return FluentIterable.from(collectedTypes) .filter(new Predicate<Class<?>>() { @Override public boolean apply(Class<?> type) { return type.isInterface(); } }) .toSet(); } @Override public TypeSet classes() { throw new UnsupportedOperationException("interfaces().classes() not supported."); } private Object readResolve() { return getTypes().interfaces(); } private static final long serialVersionUID = 0; } private final class ClassSet extends TypeSet { private transient ImmutableSet<TypeToken<? super T>> classes; @Override protected Set<TypeToken<? super T>> delegate() { ImmutableSet<TypeToken<? super T>> result = classes; if (result == null) { @SuppressWarnings({"unchecked", "rawtypes"}) ImmutableList<TypeToken<? super T>> collectedTypes = (ImmutableList) TypeCollector.FOR_GENERIC_TYPE.classesOnly().collectTypes(TypeToken.this); return (classes = FluentIterable.from(collectedTypes) .filter(TypeFilter.IGNORE_TYPE_VARIABLE_OR_WILDCARD) .toSet()); } else { return result; } } @Override public TypeSet classes() { return this; } @Override public Set<Class<? super T>> rawTypes() { // Java has no way to express ? super T when we parameterize TypeToken vs. Class. @SuppressWarnings({"unchecked", "rawtypes"}) ImmutableList<Class<? super T>> collectedTypes = (ImmutableList) TypeCollector.FOR_RAW_TYPE.classesOnly().collectTypes(getImmediateRawTypes()); return ImmutableSet.copyOf(collectedTypes); } @Override public TypeSet interfaces() { throw new UnsupportedOperationException("classes().interfaces() not supported."); } private Object readResolve() { return getTypes().classes(); } private static final long serialVersionUID = 0; } private enum TypeFilter implements Predicate<TypeToken<?>> { IGNORE_TYPE_VARIABLE_OR_WILDCARD { @Override public boolean apply(TypeToken<?> type) { return !(type.runtimeType instanceof TypeVariable || type.runtimeType instanceof WildcardType); } }, INTERFACE_ONLY { @Override public boolean apply(TypeToken<?> type) { return type.getRawType().isInterface(); } } } /** * Returns true if {@code o} is another {@code TypeToken} that represents the same {@link Type}. */ @Override public boolean equals(@Nullable Object o) { if (o instanceof TypeToken) { TypeToken<?> that = (TypeToken<?>) o; return runtimeType.equals(that.runtimeType); } return false; } @Override public int hashCode() { return runtimeType.hashCode(); } @Override public String toString() { return Types.toString(runtimeType); } /** Implemented to support serialization of subclasses. */ protected Object writeReplace() { // TypeResolver just transforms the type to our own impls that are Serializable // except TypeVariable. return of(new TypeResolver().resolveType(runtimeType)); } /** * Ensures that this type token doesn't contain type variables, which can cause unchecked type * errors for callers like {@link TypeToInstanceMap}. */ final TypeToken<T> rejectTypeVariables() { new TypeVisitor() { @Override void visitTypeVariable(TypeVariable<?> type) { throw new IllegalArgumentException( runtimeType + "contains a type variable and is not safe for the operation"); } @Override void visitWildcardType(WildcardType type) { visit(type.getLowerBounds()); visit(type.getUpperBounds()); } @Override void visitParameterizedType(ParameterizedType type) { visit(type.getActualTypeArguments()); visit(type.getOwnerType()); } @Override void visitGenericArrayType(GenericArrayType type) { visit(type.getGenericComponentType()); } }.visit(runtimeType); return this; } private static boolean isAssignable(Type from, Type to) { if (to.equals(from)) { return true; } if (to instanceof WildcardType) { return isAssignableToWildcardType(from, (WildcardType) to); } // if "from" is type variable, it's assignable if any of its "extends" // bounds is assignable to "to". if (from instanceof TypeVariable) { return isAssignableFromAny(((TypeVariable<?>) from).getBounds(), to); } // if "from" is wildcard, it'a assignable to "to" if any of its "extends" // bounds is assignable to "to". if (from instanceof WildcardType) { return isAssignableFromAny(((WildcardType) from).getUpperBounds(), to); } if (from instanceof GenericArrayType) { return isAssignableFromGenericArrayType((GenericArrayType) from, to); } // Proceed to regular Type assignability check if (to instanceof Class) { return isAssignableToClass(from, (Class<?>) to); } else if (to instanceof ParameterizedType) { return isAssignableToParameterizedType(from, (ParameterizedType) to); } else if (to instanceof GenericArrayType) { return isAssignableToGenericArrayType(from, (GenericArrayType) to); } else { // to instanceof TypeVariable return false; } } private static boolean isAssignableFromAny(Type[] fromTypes, Type to) { for (Type from : fromTypes) { if (isAssignable(from, to)) { return true; } } return false; } private static boolean isAssignableToClass(Type from, Class<?> to) { return to.isAssignableFrom(getRawType(from)); } private static boolean isAssignableToWildcardType( Type from, WildcardType to) { // if "to" is <? extends Foo>, "from" can be: // Foo, SubFoo, <? extends Foo>, <? extends SubFoo>, <T extends Foo> or // <T extends SubFoo>. // if "to" is <? super Foo>, "from" can be: // Foo, SuperFoo, <? super Foo> or <? super SuperFoo>. return isAssignable(from, supertypeBound(to)) && isAssignableBySubtypeBound(from, to); } private static boolean isAssignableBySubtypeBound(Type from, WildcardType to) { Type toSubtypeBound = subtypeBound(to); if (toSubtypeBound == null) { return true; } Type fromSubtypeBound = subtypeBound(from); if (fromSubtypeBound == null) { return false; } return isAssignable(toSubtypeBound, fromSubtypeBound); } private static boolean isAssignableToParameterizedType(Type from, ParameterizedType to) { Class<?> matchedClass = getRawType(to); if (!matchedClass.isAssignableFrom(getRawType(from))) { return false; } Type[] typeParams = matchedClass.getTypeParameters(); Type[] toTypeArgs = to.getActualTypeArguments(); TypeToken<?> fromTypeToken = of(from); for (int i = 0; i < typeParams.length; i++) { // If "to" is "List<? extends CharSequence>" // and "from" is StringArrayList, // First step is to figure out StringArrayList "is-a" List<E> and <E> is // String. // typeParams[0] is E and fromTypeToken.get(typeParams[0]) will resolve to // String. // String is then matched against <? extends CharSequence>. Type fromTypeArg = fromTypeToken.resolveType(typeParams[i]).runtimeType; if (!matchTypeArgument(fromTypeArg, toTypeArgs[i])) { return false; } } return true; } private static boolean isAssignableToGenericArrayType(Type from, GenericArrayType to) { if (from instanceof Class) { Class<?> fromClass = (Class<?>) from; if (!fromClass.isArray()) { return false; } return isAssignable(fromClass.getComponentType(), to.getGenericComponentType()); } else if (from instanceof GenericArrayType) { GenericArrayType fromArrayType = (GenericArrayType) from; return isAssignable(fromArrayType.getGenericComponentType(), to.getGenericComponentType()); } else { return false; } } private static boolean isAssignableFromGenericArrayType(GenericArrayType from, Type to) { if (to instanceof Class) { Class<?> toClass = (Class<?>) to; if (!toClass.isArray()) { return toClass == Object.class; // any T[] is assignable to Object } return isAssignable(from.getGenericComponentType(), toClass.getComponentType()); } else if (to instanceof GenericArrayType) { GenericArrayType toArrayType = (GenericArrayType) to; return isAssignable(from.getGenericComponentType(), toArrayType.getGenericComponentType()); } else { return false; } } private static boolean matchTypeArgument(Type from, Type to) { if (from.equals(to)) { return true; } if (to instanceof WildcardType) { return isAssignableToWildcardType(from, (WildcardType) to); } return false; } private static Type supertypeBound(Type type) { if (type instanceof WildcardType) { return supertypeBound((WildcardType) type); } return type; } private static Type supertypeBound(WildcardType type) { Type[] upperBounds = type.getUpperBounds(); if (upperBounds.length == 1) { return supertypeBound(upperBounds[0]); } else if (upperBounds.length == 0) { return Object.class; } else { throw new AssertionError( "There should be at most one upper bound for wildcard type: " + type); } } @Nullable private static Type subtypeBound(Type type) { if (type instanceof WildcardType) { return subtypeBound((WildcardType) type); } else { return type; } } @Nullable private static Type subtypeBound(WildcardType type) { Type[] lowerBounds = type.getLowerBounds(); if (lowerBounds.length == 1) { return subtypeBound(lowerBounds[0]); } else if (lowerBounds.length == 0) { return null; } else { throw new AssertionError( "Wildcard should have at most one lower bound: " + type); } } @VisibleForTesting static Class<?> getRawType(Type type) { // For wildcard or type variable, the first bound determines the runtime type. return getRawTypes(type).iterator().next(); } @VisibleForTesting static ImmutableSet<Class<?>> getRawTypes(Type type) { checkNotNull(type); final ImmutableSet.Builder<Class<?>> builder = ImmutableSet.builder(); new TypeVisitor() { @Override void visitTypeVariable(TypeVariable<?> t) { visit(t.getBounds()); } @Override void visitWildcardType(WildcardType t) { visit(t.getUpperBounds()); } @Override void visitParameterizedType(ParameterizedType t) { builder.add((Class<?>) t.getRawType()); } @Override void visitClass(Class<?> t) { builder.add(t); } @Override void visitGenericArrayType(GenericArrayType t) { builder.add(Types.getArrayClass(getRawType(t.getGenericComponentType()))); } }.visit(type); return builder.build(); } /** * Returns the type token representing the generic type declaration of {@code cls}. For example: * {@code TypeToken.getGenericType(Iterable.class)} returns {@code Iterable<T>}. * * <p>If {@code cls} isn't parameterized and isn't a generic array, the type token of the class is * returned. */ @VisibleForTesting static <T> TypeToken<? extends T> toGenericType(Class<T> cls) { if (cls.isArray()) { Type arrayOfGenericType = Types.newArrayType( // If we are passed with int[].class, don't turn it to GenericArrayType toGenericType(cls.getComponentType()).runtimeType); @SuppressWarnings("unchecked") // array is covariant TypeToken<? extends T> result = (TypeToken<? extends T>) of(arrayOfGenericType); return result; } TypeVariable<Class<T>>[] typeParams = cls.getTypeParameters(); if (typeParams.length > 0) { @SuppressWarnings("unchecked") // Like, it's Iterable<T> for Iterable.class TypeToken<? extends T> type = (TypeToken<? extends T>) of(Types.newParameterizedType(cls, typeParams)); return type; } else { return of(cls); } } private TypeToken<? super T> getSupertypeFromUpperBounds( Class<? super T> supertype, Type[] upperBounds) { for (Type upperBound : upperBounds) { @SuppressWarnings("unchecked") // T's upperbound is <? super T>. TypeToken<? super T> bound = (TypeToken<? super T>) of(upperBound); if (of(supertype).isAssignableFrom(bound)) { @SuppressWarnings({"rawtypes", "unchecked"}) // guarded by the isAssignableFrom check. TypeToken<? super T> result = bound.getSupertype((Class) supertype); return result; } } throw new IllegalArgumentException(supertype + " isn't a super type of " + this); } private TypeToken<? extends T> getSubtypeFromLowerBounds(Class<?> subclass, Type[] lowerBounds) { for (Type lowerBound : lowerBounds) { @SuppressWarnings("unchecked") // T's lower bound is <? extends T> TypeToken<? extends T> bound = (TypeToken<? extends T>) of(lowerBound); // Java supports only one lowerbound anyway. return bound.getSubtype(subclass); } throw new IllegalArgumentException(subclass + " isn't a subclass of " + this); } private TypeToken<? super T> getArraySupertype(Class<? super T> supertype) { // with component type, we have lost generic type information // Use raw type so that compiler allows us to call getSupertype() @SuppressWarnings("rawtypes") TypeToken componentType = checkNotNull(getComponentType(), "%s isn't a super type of %s", supertype, this); // array is covariant. component type is super type, so is the array type. @SuppressWarnings("unchecked") // going from raw type back to generics TypeToken<?> componentSupertype = componentType.getSupertype(supertype.getComponentType()); @SuppressWarnings("unchecked") // component type is super type, so is array type. TypeToken<? super T> result = (TypeToken<? super T>) // If we are passed with int[].class, don't turn it to GenericArrayType of(newArrayClassOrGenericArrayType(componentSupertype.runtimeType)); return result; } private TypeToken<? extends T> getArraySubtype(Class<?> subclass) { // array is covariant. component type is subtype, so is the array type. TypeToken<?> componentSubtype = getComponentType() .getSubtype(subclass.getComponentType()); @SuppressWarnings("unchecked") // component type is subtype, so is array type. TypeToken<? extends T> result = (TypeToken<? extends T>) // If we are passed with int[].class, don't turn it to GenericArrayType of(newArrayClassOrGenericArrayType(componentSubtype.runtimeType)); return result; } private Type resolveTypeArgsForSubclass(Class<?> subclass) { if (runtimeType instanceof Class) { // no resolution needed return subclass; } // class Base<A, B> {} // class Sub<X, Y> extends Base<X, Y> {} // Base<String, Integer>.subtype(Sub.class): // Sub<X, Y>.getSupertype(Base.class) => Base<X, Y> // => X=String, Y=Integer // => Sub<X, Y>=Sub<String, Integer> TypeToken<?> genericSubtype = toGenericType(subclass); @SuppressWarnings({"rawtypes", "unchecked"}) // subclass isn't <? extends T> Type supertypeWithArgsFromSubtype = genericSubtype .getSupertype((Class) getRawType()) .runtimeType; return new TypeResolver().where(supertypeWithArgsFromSubtype, runtimeType) .resolveType(genericSubtype.runtimeType); } /** * Creates an array class if {@code componentType} is a class, or else, a * {@link GenericArrayType}. This is what Java7 does for generic array type * parameters. */ private static Type newArrayClassOrGenericArrayType(Type componentType) { return Types.JavaVersion.JAVA7.newArrayType(componentType); } private static final class SimpleTypeToken<T> extends TypeToken<T> { SimpleTypeToken(Type type) { super(type); } private static final long serialVersionUID = 0; } /** * Collects parent types from a sub type. * * @param <K> The type "kind". Either a TypeToken, or Class. */ private abstract static class TypeCollector<K> { static final TypeCollector<TypeToken<?>> FOR_GENERIC_TYPE = new TypeCollector<TypeToken<?>>() { @Override Class<?> getRawType(TypeToken<?> type) { return type.getRawType(); } @Override Iterable<? extends TypeToken<?>> getInterfaces(TypeToken<?> type) { return type.getGenericInterfaces(); } @Nullable @Override TypeToken<?> getSuperclass(TypeToken<?> type) { return type.getGenericSuperclass(); } }; static final TypeCollector<Class<?>> FOR_RAW_TYPE = new TypeCollector<Class<?>>() { @Override Class<?> getRawType(Class<?> type) { return type; } @Override Iterable<? extends Class<?>> getInterfaces(Class<?> type) { return Arrays.asList(type.getInterfaces()); } @Nullable @Override Class<?> getSuperclass(Class<?> type) { return type.getSuperclass(); } }; /** For just classes, we don't have to traverse interfaces. */ final TypeCollector<K> classesOnly() { return new ForwardingTypeCollector<K>(this) { @Override Iterable<? extends K> getInterfaces(K type) { return ImmutableSet.of(); } @Override ImmutableList<K> collectTypes(Iterable<? extends K> types) { ImmutableList.Builder<K> builder = ImmutableList.builder(); for (K type : types) { if (!getRawType(type).isInterface()) { builder.add(type); } } return super.collectTypes(builder.build()); } }; } final ImmutableList<K> collectTypes(K type) { return collectTypes(ImmutableList.of(type)); } ImmutableList<K> collectTypes(Iterable<? extends K> types) { // type -> order number. 1 for Object, 2 for anything directly below, so on so forth. Map<K, Integer> map = Maps.newHashMap(); for (K type : types) { collectTypes(type, map); } return sortKeysByValue(map, Ordering.natural().reverse()); } /** Collects all types to map, and returns the total depth from T up to Object. */ private int collectTypes(K type, Map<? super K, Integer> map) { Integer existing = map.get(this); if (existing != null) { // short circuit: if set contains type it already contains its supertypes return existing; } int aboveMe = getRawType(type).isInterface() ? 1 // interfaces should be listed before Object : 0; for (K interfaceType : getInterfaces(type)) { aboveMe = Math.max(aboveMe, collectTypes(interfaceType, map)); } K superclass = getSuperclass(type); if (superclass != null) { aboveMe = Math.max(aboveMe, collectTypes(superclass, map)); } /* * TODO(benyu): should we include Object for interface? * Also, CharSequence[] and Object[] for String[]? * */ map.put(type, aboveMe + 1); return aboveMe + 1; } private static <K, V> ImmutableList<K> sortKeysByValue( final Map<K, V> map, final Comparator<? super V> valueComparator) { Ordering<K> keyOrdering = new Ordering<K>() { @Override public int compare(K left, K right) { return valueComparator.compare(map.get(left), map.get(right)); } }; return keyOrdering.immutableSortedCopy(map.keySet()); } abstract Class<?> getRawType(K type); abstract Iterable<? extends K> getInterfaces(K type); @Nullable abstract K getSuperclass(K type); private static class ForwardingTypeCollector<K> extends TypeCollector<K> { private final TypeCollector<K> delegate; ForwardingTypeCollector(TypeCollector<K> delegate) { this.delegate = delegate; } @Override Class<?> getRawType(K type) { return delegate.getRawType(type); } @Override Iterable<? extends K> getInterfaces(K type) { return delegate.getInterfaces(type); } @Override K getSuperclass(K type) { return delegate.getSuperclass(type); } } } }
zzhhhhh-aw4rwer
guava/src/com/google/common/reflect/TypeToken.java
Java
asf20
44,596
/* * Copyright (C) 2005 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.reflect; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; import com.google.common.annotations.Beta; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Proxy; /** * Static utilities relating to Java reflection. * * @since 12.0 */ @Beta public final class Reflection { /** * Returns the package name of {@code clazz} according to the Java Language Specification (section * 6.7). Unlike {@link Class#getPackage}, this method only parses the class name, without * attempting to define the {@link Package} and hence load files. */ public static String getPackageName(Class<?> clazz) { return getPackageName(clazz.getName()); } /** * Returns the package name of {@code classFullName} according to the Java Language Specification * (section 6.7). Unlike {@link Class#getPackage}, this method only parses the class name, without * attempting to define the {@link Package} and hence load files. */ public static String getPackageName(String classFullName) { int lastDot = classFullName.lastIndexOf('.'); return (lastDot < 0) ? "" : classFullName.substring(0, lastDot); } /** * Ensures that the given classes are initialized, as described in * <a href="http://java.sun.com/docs/books/jls/third_edition/html/execution.html#12.4.2"> * JLS Section 12.4.2</a>. * * <p>WARNING: Normally it's a smell if a class needs to be explicitly initialized, because static * state hurts system maintainability and testability. In cases when you have no choice while * inter-operating with a legacy framework, this method helps to keep the code less ugly. * * @throws ExceptionInInitializerError if an exception is thrown during * initialization of a class */ public static void initialize(Class<?>... classes) { for (Class<?> clazz : classes) { try { Class.forName(clazz.getName(), true, clazz.getClassLoader()); } catch (ClassNotFoundException e) { throw new AssertionError(e); } } } /** * Returns a proxy instance that implements {@code interfaceType} by * dispatching method invocations to {@code handler}. The class loader of * {@code interfaceType} will be used to define the proxy class. To implement * multiple interfaces or specify a class loader, use * {@link Proxy#newProxyInstance}. * * @throws IllegalArgumentException if {@code interfaceType} does not specify * the type of a Java interface */ public static <T> T newProxy( Class<T> interfaceType, InvocationHandler handler) { checkNotNull(handler); checkArgument(interfaceType.isInterface(), "%s is not an interface", interfaceType); Object object = Proxy.newProxyInstance( interfaceType.getClassLoader(), new Class<?>[] { interfaceType }, handler); return interfaceType.cast(object); } private Reflection() {} }
zzhhhhh-aw4rwer
guava/src/com/google/common/reflect/Reflection.java
Java
asf20
3,609
/* * Copyright (C) 2012 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.reflect; import static com.google.common.base.Preconditions.checkNotNull; import com.google.common.annotations.Beta; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.CharMatcher; import com.google.common.base.Predicate; import com.google.common.base.Splitter; import com.google.common.collect.FluentIterable; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; import com.google.common.collect.ImmutableSortedSet; import com.google.common.collect.Maps; import com.google.common.collect.Ordering; import com.google.common.collect.Sets; import java.io.File; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; import java.net.URLClassLoader; import java.util.Enumeration; import java.util.LinkedHashMap; import java.util.Map; import java.util.Set; import java.util.jar.Attributes; import java.util.jar.JarEntry; import java.util.jar.JarFile; import java.util.jar.Manifest; import java.util.logging.Logger; import javax.annotation.Nullable; /** * Scans the source of a {@link ClassLoader} and finds all loadable classes and resources. * * @author Ben Yu * @since 14.0 */ @Beta public final class ClassPath { private static final Logger logger = Logger.getLogger(ClassPath.class.getName()); private static final Predicate<ClassInfo> IS_TOP_LEVEL = new Predicate<ClassInfo>() { @Override public boolean apply(ClassInfo info) { return info.className.indexOf('$') == -1; } }; /** Separator for the Class-Path manifest attribute value in jar files. */ private static final Splitter CLASS_PATH_ATTRIBUTE_SEPARATOR = Splitter.on(" ").omitEmptyStrings(); private static final String CLASS_FILE_NAME_EXTENSION = ".class"; private final ImmutableSet<ResourceInfo> resources; private ClassPath(ImmutableSet<ResourceInfo> resources) { this.resources = resources; } /** * Returns a {@code ClassPath} representing all classes and resources loadable from {@code * classloader} and its parent class loaders. * * <p>Currently only {@link URLClassLoader} and only {@code file://} urls are supported. * * @throws IOException if the attempt to read class path resources (jar files or directories) * failed. */ public static ClassPath from(ClassLoader classloader) throws IOException { Scanner scanner = new Scanner(); for (Map.Entry<URI, ClassLoader> entry : getClassPathEntries(classloader).entrySet()) { scanner.scan(entry.getKey(), entry.getValue()); } return new ClassPath(scanner.getResources()); } /** * Returns all resources loadable from the current class path, including the class files of all * loadable classes but excluding the "META-INF/MANIFEST.MF" file. */ public ImmutableSet<ResourceInfo> getResources() { return resources; } /** * Returns all classes loadable from the current class path. * * @since 16.0 */ public ImmutableSet<ClassInfo> getAllClasses() { return FluentIterable.from(resources).filter(ClassInfo.class).toSet(); } /** Returns all top level classes loadable from the current class path. */ public ImmutableSet<ClassInfo> getTopLevelClasses() { return FluentIterable.from(resources).filter(ClassInfo.class).filter(IS_TOP_LEVEL).toSet(); } /** Returns all top level classes whose package name is {@code packageName}. */ public ImmutableSet<ClassInfo> getTopLevelClasses(String packageName) { checkNotNull(packageName); ImmutableSet.Builder<ClassInfo> builder = ImmutableSet.builder(); for (ClassInfo classInfo : getTopLevelClasses()) { if (classInfo.getPackageName().equals(packageName)) { builder.add(classInfo); } } return builder.build(); } /** * Returns all top level classes whose package name is {@code packageName} or starts with * {@code packageName} followed by a '.'. */ public ImmutableSet<ClassInfo> getTopLevelClassesRecursive(String packageName) { checkNotNull(packageName); String packagePrefix = packageName + '.'; ImmutableSet.Builder<ClassInfo> builder = ImmutableSet.builder(); for (ClassInfo classInfo : getTopLevelClasses()) { if (classInfo.getName().startsWith(packagePrefix)) { builder.add(classInfo); } } return builder.build(); } /** * Represents a class path resource that can be either a class file or any other resource file * loadable from the class path. * * @since 14.0 */ @Beta public static class ResourceInfo { private final String resourceName; final ClassLoader loader; static ResourceInfo of(String resourceName, ClassLoader loader) { if (resourceName.endsWith(CLASS_FILE_NAME_EXTENSION)) { return new ClassInfo(resourceName, loader); } else { return new ResourceInfo(resourceName, loader); } } ResourceInfo(String resourceName, ClassLoader loader) { this.resourceName = checkNotNull(resourceName); this.loader = checkNotNull(loader); } /** Returns the url identifying the resource. */ public final URL url() { return checkNotNull(loader.getResource(resourceName), "Failed to load resource: %s", resourceName); } /** Returns the fully qualified name of the resource. Such as "com/mycomp/foo/bar.txt". */ public final String getResourceName() { return resourceName; } @Override public int hashCode() { return resourceName.hashCode(); } @Override public boolean equals(Object obj) { if (obj instanceof ResourceInfo) { ResourceInfo that = (ResourceInfo) obj; return resourceName.equals(that.resourceName) && loader == that.loader; } return false; } // Do not change this arbitrarily. We rely on it for sorting ResourceInfo. @Override public String toString() { return resourceName; } } /** * Represents a class that can be loaded through {@link #load}. * * @since 14.0 */ @Beta public static final class ClassInfo extends ResourceInfo { private final String className; ClassInfo(String resourceName, ClassLoader loader) { super(resourceName, loader); this.className = getClassName(resourceName); } /** * Returns the package name of the class, without attempting to load the class. * * <p>Behaves identically to {@link Package#getName()} but does not require the class (or * package) to be loaded. */ public String getPackageName() { return Reflection.getPackageName(className); } /** * Returns the simple name of the underlying class as given in the source code. * * <p>Behaves identically to {@link Class#getSimpleName()} but does not require the class to be * loaded. */ public String getSimpleName() { int lastDollarSign = className.lastIndexOf('$'); if (lastDollarSign != -1) { String innerClassName = className.substring(lastDollarSign + 1); // local and anonymous classes are prefixed with number (1,2,3...), anonymous classes are // entirely numeric whereas local classes have the user supplied name as a suffix return CharMatcher.DIGIT.trimLeadingFrom(innerClassName); } String packageName = getPackageName(); if (packageName.isEmpty()) { return className; } // Since this is a top level class, its simple name is always the part after package name. return className.substring(packageName.length() + 1); } /** * Returns the fully qualified name of the class. * * <p>Behaves identically to {@link Class#getName()} but does not require the class to be * loaded. */ public String getName() { return className; } /** * Loads (but doesn't link or initialize) the class. * * @throws LinkageError when there were errors in loading classes that this class depends on. * For example, {@link NoClassDefFoundError}. */ public Class<?> load() { try { return loader.loadClass(className); } catch (ClassNotFoundException e) { // Shouldn't happen, since the class name is read from the class path. throw new IllegalStateException(e); } } @Override public String toString() { return className; } } @VisibleForTesting static ImmutableMap<URI, ClassLoader> getClassPathEntries( ClassLoader classloader) { LinkedHashMap<URI, ClassLoader> entries = Maps.newLinkedHashMap(); // Search parent first, since it's the order ClassLoader#loadClass() uses. ClassLoader parent = classloader.getParent(); if (parent != null) { entries.putAll(getClassPathEntries(parent)); } if (classloader instanceof URLClassLoader) { URLClassLoader urlClassLoader = (URLClassLoader) classloader; for (URL entry : urlClassLoader.getURLs()) { URI uri; try { uri = entry.toURI(); } catch (URISyntaxException e) { throw new IllegalArgumentException(e); } if (!entries.containsKey(uri)) { entries.put(uri, classloader); } } } return ImmutableMap.copyOf(entries); } @VisibleForTesting static final class Scanner { private final ImmutableSortedSet.Builder<ResourceInfo> resources = new ImmutableSortedSet.Builder<ResourceInfo>(Ordering.usingToString()); private final Set<URI> scannedUris = Sets.newHashSet(); ImmutableSortedSet<ResourceInfo> getResources() { return resources.build(); } void scan(URI uri, ClassLoader classloader) throws IOException { if (uri.getScheme().equals("file") && scannedUris.add(uri)) { scanFrom(new File(uri), classloader); } } @VisibleForTesting void scanFrom(File file, ClassLoader classloader) throws IOException { if (!file.exists()) { return; } if (file.isDirectory()) { scanDirectory(file, classloader); } else { scanJar(file, classloader); } } private void scanDirectory(File directory, ClassLoader classloader) throws IOException { scanDirectory(directory, classloader, "", ImmutableSet.<File>of()); } private void scanDirectory( File directory, ClassLoader classloader, String packagePrefix, ImmutableSet<File> ancestors) throws IOException { File canonical = directory.getCanonicalFile(); if (ancestors.contains(canonical)) { // A cycle in the filesystem, for example due to a symbolic link. return; } File[] files = directory.listFiles(); if (files == null) { logger.warning("Cannot read directory " + directory); // IO error, just skip the directory return; } ImmutableSet<File> newAncestors = ImmutableSet.<File>builder() .addAll(ancestors) .add(canonical) .build(); for (File f : files) { String name = f.getName(); if (f.isDirectory()) { scanDirectory(f, classloader, packagePrefix + name + "/", newAncestors); } else { String resourceName = packagePrefix + name; if (!resourceName.equals(JarFile.MANIFEST_NAME)) { resources.add(ResourceInfo.of(resourceName, classloader)); } } } } private void scanJar(File file, ClassLoader classloader) throws IOException { JarFile jarFile; try { jarFile = new JarFile(file); } catch (IOException e) { // Not a jar file return; } try { for (URI uri : getClassPathFromManifest(file, jarFile.getManifest())) { scan(uri, classloader); } Enumeration<JarEntry> entries = jarFile.entries(); while (entries.hasMoreElements()) { JarEntry entry = entries.nextElement(); if (entry.isDirectory() || entry.getName().equals(JarFile.MANIFEST_NAME)) { continue; } resources.add(ResourceInfo.of(entry.getName(), classloader)); } } finally { try { jarFile.close(); } catch (IOException ignored) {} } } /** * Returns the class path URIs specified by the {@code Class-Path} manifest attribute, according * to <a href="http://docs.oracle.com/javase/6/docs/technotes/guides/jar/jar.html#Main%20Attributes"> * JAR File Specification</a>. If {@code manifest} is null, it means the jar file has no * manifest, and an empty set will be returned. */ @VisibleForTesting static ImmutableSet<URI> getClassPathFromManifest( File jarFile, @Nullable Manifest manifest) { if (manifest == null) { return ImmutableSet.of(); } ImmutableSet.Builder<URI> builder = ImmutableSet.builder(); String classpathAttribute = manifest.getMainAttributes() .getValue(Attributes.Name.CLASS_PATH.toString()); if (classpathAttribute != null) { for (String path : CLASS_PATH_ATTRIBUTE_SEPARATOR.split(classpathAttribute)) { URI uri; try { uri = getClassPathEntry(jarFile, path); } catch (URISyntaxException e) { // Ignore bad entry logger.warning("Invalid Class-Path entry: " + path); continue; } builder.add(uri); } } return builder.build(); } /** * Returns the absolute uri of the Class-Path entry value as specified in * <a href="http://docs.oracle.com/javase/6/docs/technotes/guides/jar/jar.html#Main%20Attributes"> * JAR File Specification</a>. Even though the specification only talks about relative urls, * absolute urls are actually supported too (for example, in Maven surefire plugin). */ @VisibleForTesting static URI getClassPathEntry(File jarFile, String path) throws URISyntaxException { URI uri = new URI(path); if (uri.isAbsolute()) { return uri; } else { return new File(jarFile.getParentFile(), path.replace('/', File.separatorChar)).toURI(); } } } @VisibleForTesting static String getClassName(String filename) { int classNameEnd = filename.length() - CLASS_FILE_NAME_EXTENSION.length(); return filename.substring(0, classNameEnd).replace('/', '.'); } }
zzhhhhh-aw4rwer
guava/src/com/google/common/reflect/ClassPath.java
Java
asf20
15,110
/* * Copyright (C) 2011 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.reflect; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.collect.Iterables.transform; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Function; import com.google.common.base.Joiner; import com.google.common.base.Objects; import com.google.common.base.Predicates; import com.google.common.collect.ImmutableList; import com.google.common.collect.Iterables; import java.io.Serializable; import java.lang.reflect.Array; import java.lang.reflect.GenericArrayType; import java.lang.reflect.GenericDeclaration; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.lang.reflect.TypeVariable; import java.lang.reflect.WildcardType; import java.util.Arrays; import java.util.Collection; import java.util.concurrent.atomic.AtomicReference; import javax.annotation.Nullable; /** * Utilities for working with {@link Type}. * * @author Ben Yu */ final class Types { /** Class#toString without the "class " and "interface " prefixes */ private static final Function<Type, String> TYPE_TO_STRING = new Function<Type, String>() { @Override public String apply(Type from) { return Types.toString(from); } }; private static final Joiner COMMA_JOINER = Joiner.on(", ").useForNull("null"); /** Returns the array type of {@code componentType}. */ static Type newArrayType(Type componentType) { if (componentType instanceof WildcardType) { WildcardType wildcard = (WildcardType) componentType; Type[] lowerBounds = wildcard.getLowerBounds(); checkArgument(lowerBounds.length <= 1, "Wildcard cannot have more than one lower bounds."); if (lowerBounds.length == 1) { return supertypeOf(newArrayType(lowerBounds[0])); } else { Type[] upperBounds = wildcard.getUpperBounds(); checkArgument(upperBounds.length == 1, "Wildcard should have only one upper bound."); return subtypeOf(newArrayType(upperBounds[0])); } } return JavaVersion.CURRENT.newArrayType(componentType); } /** * 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); } /** * Returns a type where {@code rawType} is parameterized by * {@code arguments}. */ static ParameterizedType newParameterizedType(Class<?> rawType, Type... arguments) { return new ParameterizedTypeImpl( ClassOwnership.JVM_BEHAVIOR.getOwnerType(rawType), rawType, arguments); } /** Decides what owner type to use for constructing {@link ParameterizedType} from a raw class. */ private enum ClassOwnership { OWNED_BY_ENCLOSING_CLASS { @Nullable @Override Class<?> getOwnerType(Class<?> rawType) { return rawType.getEnclosingClass(); } }, LOCAL_CLASS_HAS_NO_OWNER { @Nullable @Override Class<?> getOwnerType(Class<?> rawType) { if (rawType.isLocalClass()) { return null; } else { return rawType.getEnclosingClass(); } } }; @Nullable abstract Class<?> getOwnerType(Class<?> rawType); static final ClassOwnership JVM_BEHAVIOR = detectJvmBehavior(); private static ClassOwnership detectJvmBehavior() { class LocalClass<T> {} Class<?> subclass = new LocalClass<String>() {}.getClass(); ParameterizedType parameterizedType = (ParameterizedType) subclass.getGenericSuperclass(); for (ClassOwnership behavior : ClassOwnership.values()) { if (behavior.getOwnerType(LocalClass.class) == parameterizedType.getOwnerType()) { return behavior; } } throw new AssertionError(); } } /** * Returns a new {@link TypeVariable} that belongs to {@code declaration} with * {@code name} and {@code bounds}. */ static <D extends GenericDeclaration> TypeVariable<D> newArtificialTypeVariable( D declaration, String name, Type... bounds) { return new TypeVariableImpl<D>( declaration, name, (bounds.length == 0) ? new Type[] { Object.class } : bounds); } /** Returns a new {@link WildcardType} with {@code upperBound}. */ @VisibleForTesting static WildcardType subtypeOf(Type upperBound) { return new WildcardTypeImpl(new Type[0], new Type[] { upperBound }); } /** Returns a new {@link WildcardType} with {@code lowerBound}. */ @VisibleForTesting static WildcardType supertypeOf(Type lowerBound) { return new WildcardTypeImpl(new Type[] { lowerBound }, new Type[] { Object.class }); } /** * Returns human readable string representation of {@code type}. * <ul> * <li> For array type {@code Foo[]}, {@code "com.mypackage.Foo[]"} are * returned. * <li> For any class, {@code theClass.getName()} are returned. * <li> For all other types, {@code type.toString()} are returned. * </ul> */ static String toString(Type type) { return (type instanceof Class) ? ((Class<?>) type).getName() : type.toString(); } @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 {@code ? extends X} if any of {@code bounds} is a subtype of {@code X[]}; or null * otherwise. */ @Nullable private static Type subtypeOfComponentType(Type[] bounds) { for (Type bound : bounds) { Type componentType = getComponentType(bound); if (componentType != null) { // Only the first bound can be a class or array. // Bounds after the first can only be interfaces. if (componentType instanceof Class) { Class<?> componentClass = (Class<?>) componentType; if (componentClass.isPrimitive()) { return componentClass; } } return subtypeOf(componentType); } } return null; } private static final class GenericArrayTypeImpl implements GenericArrayType, Serializable { private final Type componentType; GenericArrayTypeImpl(Type componentType) { this.componentType = JavaVersion.CURRENT.usedInGenericType(componentType); } @Override public Type getGenericComponentType() { return componentType; } @Override public String toString() { return Types.toString(componentType) + "[]"; } @Override public int hashCode() { return componentType.hashCode(); } @Override public boolean equals(Object obj) { if (obj instanceof GenericArrayType) { GenericArrayType that = (GenericArrayType) obj; return Objects.equal( getGenericComponentType(), that.getGenericComponentType()); } return false; } private static final long serialVersionUID = 0; } private static final class ParameterizedTypeImpl implements ParameterizedType, Serializable { private final Type ownerType; private final ImmutableList<Type> argumentsList; private final Class<?> rawType; 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); } @Override public Type[] getActualTypeArguments() { return toArray(argumentsList); } @Override public Type getRawType() { return rawType; } @Override public Type getOwnerType() { return ownerType; } @Override public String toString() { StringBuilder builder = new StringBuilder(); if (ownerType != null) { builder.append(Types.toString(ownerType)).append('.'); } builder.append(rawType.getName()) .append('<') .append(COMMA_JOINER.join(transform(argumentsList, TYPE_TO_STRING))) .append('>'); return builder.toString(); } @Override public int hashCode() { return (ownerType == null ? 0 : ownerType.hashCode()) ^ argumentsList.hashCode() ^ rawType.hashCode(); } @Override public boolean equals(Object other) { if (!(other instanceof ParameterizedType)) { return false; } ParameterizedType that = (ParameterizedType) other; return getRawType().equals(that.getRawType()) && Objects.equal(getOwnerType(), that.getOwnerType()) && Arrays.equals( getActualTypeArguments(), that.getActualTypeArguments()); } private static final long serialVersionUID = 0; } private static final class TypeVariableImpl<D extends GenericDeclaration> implements TypeVariable<D> { private final D genericDeclaration; private final String name; private final ImmutableList<Type> bounds; TypeVariableImpl(D genericDeclaration, String name, Type[] bounds) { disallowPrimitiveType(bounds, "bound for type variable"); this.genericDeclaration = checkNotNull(genericDeclaration); this.name = checkNotNull(name); this.bounds = ImmutableList.copyOf(bounds); } @Override public Type[] getBounds() { return toArray(bounds); } @Override public D getGenericDeclaration() { return genericDeclaration; } @Override public String getName() { return name; } @Override public String toString() { return name; } @Override public int hashCode() { return genericDeclaration.hashCode() ^ name.hashCode(); } @Override public boolean equals(Object obj) { if (NativeTypeVariableEquals.NATIVE_TYPE_VARIABLE_ONLY) { // equal only to our TypeVariable implementation with identical bounds if (obj instanceof TypeVariableImpl) { TypeVariableImpl<?> that = (TypeVariableImpl<?>) obj; return name.equals(that.getName()) && genericDeclaration.equals(that.getGenericDeclaration()) && bounds.equals(that.bounds); } return false; } else { // equal to any TypeVariable implementation regardless of bounds if (obj instanceof TypeVariable) { TypeVariable<?> that = (TypeVariable<?>) obj; return name.equals(that.getName()) && genericDeclaration.equals(that.getGenericDeclaration()); } return false; } } } static final class WildcardTypeImpl implements WildcardType, Serializable { private final ImmutableList<Type> lowerBounds; private final ImmutableList<Type> upperBounds; WildcardTypeImpl(Type[] lowerBounds, Type[] upperBounds) { disallowPrimitiveType(lowerBounds, "lower bound for wildcard"); disallowPrimitiveType(upperBounds, "upper bound for wildcard"); this.lowerBounds = JavaVersion.CURRENT.usedInGenericType(lowerBounds); this.upperBounds = JavaVersion.CURRENT.usedInGenericType(upperBounds); } @Override public Type[] getLowerBounds() { return toArray(lowerBounds); } @Override public Type[] getUpperBounds() { return toArray(upperBounds); } @Override public boolean equals(Object obj) { if (obj instanceof WildcardType) { WildcardType that = (WildcardType) obj; return lowerBounds.equals(Arrays.asList(that.getLowerBounds())) && upperBounds.equals(Arrays.asList(that.getUpperBounds())); } return false; } @Override public int hashCode() { return lowerBounds.hashCode() ^ upperBounds.hashCode(); } @Override public String toString() { StringBuilder builder = new StringBuilder("?"); for (Type lowerBound : lowerBounds) { builder.append(" super ").append(Types.toString(lowerBound)); } for (Type upperBound : filterUpperBounds(upperBounds)) { builder.append(" extends ").append(Types.toString(upperBound)); } return builder.toString(); } private static final long serialVersionUID = 0; } private static Type[] toArray(Collection<Type> types) { return types.toArray(new Type[types.size()]); } private static Iterable<Type> filterUpperBounds(Iterable<Type> bounds) { return Iterables.filter( bounds, Predicates.not(Predicates.<Type>equalTo(Object.class))); } private static void disallowPrimitiveType(Type[] types, String usedAs) { for (Type type : types) { if (type instanceof Class) { Class<?> cls = (Class<?>) type; checkArgument(!cls.isPrimitive(), "Primitive type '%s' used as %s", cls, usedAs); } } } /** Returns the {@code Class} object of arrays with {@code componentType}. */ static Class<?> getArrayClass(Class<?> componentType) { // TODO(user): This is not the most efficient way to handle generic // arrays, but is there another way to extract the array class in a // non-hacky way (i.e. using String value class names- "[L...")? return Array.newInstance(componentType, 0).getClass(); } // TODO(benyu): Once we are on Java 7, delete this abstraction enum JavaVersion { JAVA6 { @Override GenericArrayType newArrayType(Type componentType) { return new GenericArrayTypeImpl(componentType); } @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; } }, JAVA7 { @Override Type newArrayType(Type componentType) { if (componentType instanceof Class) { return getArrayClass((Class<?>) componentType); } else { return new GenericArrayTypeImpl(componentType); } } @Override Type usedInGenericType(Type type) { return checkNotNull(type); } } ; static final JavaVersion CURRENT = (new TypeCapture<int[]>() {}.capture() instanceof Class) ? JAVA7 : JAVA6; abstract Type newArrayType(Type componentType); abstract Type usedInGenericType(Type type); final ImmutableList<Type> usedInGenericType(Type[] types) { ImmutableList.Builder<Type> builder = ImmutableList.builder(); for (Type type : types) { builder.add(usedInGenericType(type)); } return builder.build(); } } /** * Per https://code.google.com/p/guava-libraries/issues/detail?id=1635, * In JDK 1.7.0_51-b13, TypeVariableImpl.equals() is changed to no longer be equal to custom * TypeVariable implementations. As a result, we need to make sure our TypeVariable implementation * respects symmetry. * Moreover, we don't want to reconstruct a native type variable <A> using our implementation * unless some of its bounds have changed in resolution. This avoids creating unequal TypeVariable * implementation unnecessarily. When the bounds do change, however, it's fine for the synthetic * TypeVariable to be unequal to any native TypeVariable anyway. */ static final class NativeTypeVariableEquals<X> { static final boolean NATIVE_TYPE_VARIABLE_ONLY = !NativeTypeVariableEquals.class.getTypeParameters()[0].equals( newArtificialTypeVariable(NativeTypeVariableEquals.class, "X")); } private Types() {} }
zzhhhhh-aw4rwer
guava/src/com/google/common/reflect/Types.java
Java
asf20
17,322
/* * Copyright (C) 2012 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.reflect; import static com.google.common.base.Preconditions.checkNotNull; import com.google.common.annotations.Beta; import com.google.common.collect.ImmutableList; import java.lang.annotation.Annotation; import java.lang.reflect.AnnotatedElement; import javax.annotation.Nullable; /** * Represents a method or constructor parameter. * * @author Ben Yu * @since 14.0 */ @Beta public final class Parameter implements AnnotatedElement { private final Invokable<?, ?> declaration; private final int position; private final TypeToken<?> type; private final ImmutableList<Annotation> annotations; Parameter( Invokable<?, ?> declaration, int position, TypeToken<?> type, Annotation[] annotations) { this.declaration = declaration; this.position = position; this.type = type; this.annotations = ImmutableList.copyOf(annotations); } /** Returns the type of the parameter. */ public TypeToken<?> getType() { return type; } /** Returns the {@link Invokable} that declares this parameter. */ public Invokable<?, ?> getDeclaringInvokable() { return declaration; } @Override public boolean isAnnotationPresent(Class<? extends Annotation> annotationType) { return getAnnotation(annotationType) != null; } @Override @Nullable public <A extends Annotation> A getAnnotation(Class<A> annotationType) { checkNotNull(annotationType); for (Annotation annotation : annotations) { if (annotationType.isInstance(annotation)) { return annotationType.cast(annotation); } } return null; } @Override public Annotation[] getAnnotations() { return getDeclaredAnnotations(); } @Override public Annotation[] getDeclaredAnnotations() { return annotations.toArray(new Annotation[annotations.size()]); } @Override public boolean equals(@Nullable Object obj) { if (obj instanceof Parameter) { Parameter that = (Parameter) obj; return position == that.position && declaration.equals(that.declaration); } return false; } @Override public int hashCode() { return position; } @Override public String toString() { return type + " arg" + position; } }
zzhhhhh-aw4rwer
guava/src/com/google/common/reflect/Parameter.java
Java
asf20
2,843
/* * Copyright (C) 2012 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.reflect; import com.google.common.annotations.Beta; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; import java.util.Arrays; import javax.annotation.Nullable; /** * Abstract implementation of {@link InvocationHandler} that handles {@link Object#equals}, * {@link Object#hashCode} and {@link Object#toString}. For example: <pre> * class Unsupported extends AbstractInvocationHandler { * protected Object handleInvocation( * Object proxy, Method method, Object[] args) { * throw new UnsupportedOperationException(); * } * } * * CharSequence unsupported = Reflection.newProxy(CharSequence.class, new Unsupported()); * </pre> * * @author Ben Yu * @since 12.0 */ @Beta public abstract class AbstractInvocationHandler implements InvocationHandler { private static final Object[] NO_ARGS = {}; /** * {@inheritDoc} * * <p><ul> * <li>{@code proxy.hashCode()} delegates to {@link AbstractInvocationHandler#hashCode} * <li>{@code proxy.toString()} delegates to {@link AbstractInvocationHandler#toString} * <li>{@code proxy.equals(argument)} returns true if: <ul> * <li>{@code proxy} and {@code argument} are of the same type * <li>and {@link AbstractInvocationHandler#equals} returns true for the {@link * InvocationHandler} of {@code argument} * </ul> * <li>other method calls are dispatched to {@link #handleInvocation}. * </ul> */ @Override public final Object invoke(Object proxy, Method method, @Nullable Object[] args) throws Throwable { if (args == null) { args = NO_ARGS; } if (args.length == 0 && method.getName().equals("hashCode")) { return hashCode(); } if (args.length == 1 && method.getName().equals("equals") && method.getParameterTypes()[0] == Object.class) { Object arg = args[0]; if (arg == null) { return false; } if (proxy == arg) { return true; } return isProxyOfSameInterfaces(arg, proxy.getClass()) && equals(Proxy.getInvocationHandler(arg)); } if (args.length == 0 && method.getName().equals("toString")) { return toString(); } return handleInvocation(proxy, method, args); } /** * {@link #invoke} delegates to this method upon any method invocation on the proxy instance, * except {@link Object#equals}, {@link Object#hashCode} and {@link Object#toString}. The result * will be returned as the proxied method's return value. * * <p>Unlike {@link #invoke}, {@code args} will never be null. When the method has no parameter, * an empty array is passed in. */ protected abstract Object handleInvocation(Object proxy, Method method, Object[] args) throws Throwable; /** * By default delegates to {@link Object#equals} so instances are only equal if they are * identical. {@code proxy.equals(argument)} returns true if: <ul> * <li>{@code proxy} and {@code argument} are of the same type * <li>and this method returns true for the {@link InvocationHandler} of {@code argument} * </ul> * <p>Subclasses can override this method to provide custom equality. */ @Override public boolean equals(Object obj) { return super.equals(obj); } /** * By default delegates to {@link Object#hashCode}. The dynamic proxies' {@code hashCode()} will * delegate to this method. Subclasses can override this method to provide custom equality. */ @Override public int hashCode() { return super.hashCode(); } /** * By default delegates to {@link Object#toString}. The dynamic proxies' {@code toString()} will * delegate to this method. Subclasses can override this method to provide custom string * representation for the proxies. */ @Override public String toString() { return super.toString(); } private static boolean isProxyOfSameInterfaces(Object arg, Class<?> proxyClass) { return proxyClass.isInstance(arg) // Equal proxy instances should mostly be instance of proxyClass // Under some edge cases (such as the proxy of JDK types serialized and then deserialized) // the proxy type may not be the same. // We first check isProxyClass() so that the common case of comparing with non-proxy objects // is efficient. || (Proxy.isProxyClass(arg.getClass()) && Arrays.equals(arg.getClass().getInterfaces(), proxyClass.getInterfaces())); } }
zzhhhhh-aw4rwer
guava/src/com/google/common/reflect/AbstractInvocationHandler.java
Java
asf20
5,124
/* * Copyright (C) 2012 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.reflect; import static com.google.common.base.Preconditions.checkNotNull; import com.google.common.annotations.Beta; import com.google.common.collect.ImmutableList; import java.lang.annotation.Annotation; import java.lang.reflect.AccessibleObject; import java.lang.reflect.Constructor; import java.lang.reflect.GenericDeclaration; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Member; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.lang.reflect.Type; import java.lang.reflect.TypeVariable; import java.util.Arrays; import javax.annotation.Nullable; /** * Wrapper around either a {@link Method} or a {@link Constructor}. * Convenience API is provided to make common reflective operation easier to deal with, * such as {@link #isPublic}, {@link #getParameters} etc. * * <p>In addition to convenience methods, {@link TypeToken#method} and {@link * TypeToken#constructor} will resolve the type parameters of the method or constructor in the * context of the owner type, which may be a subtype of the declaring class. For example: * * <pre> {@code * Method getMethod = List.class.getMethod("get", int.class); * Invokable<List<String>, ?> invokable = new TypeToken<List<String>>() {}.method(getMethod); * assertEquals(TypeToken.of(String.class), invokable.getReturnType()); // Not Object.class! * assertEquals(new TypeToken<List<String>>() {}, invokable.getOwnerType());}</pre> * * @param <T> the type that owns this method or constructor. * @param <R> the return type of (or supertype thereof) the method or the declaring type of the * constructor. * @author Ben Yu * @since 14.0 */ @Beta public abstract class Invokable<T, R> extends Element implements GenericDeclaration { <M extends AccessibleObject & Member> Invokable(M member) { super(member); } /** Returns {@link Invokable} of {@code method}. */ public static Invokable<?, Object> from(Method method) { return new MethodInvokable<Object>(method); } /** Returns {@link Invokable} of {@code constructor}. */ public static <T> Invokable<T, T> from(Constructor<T> constructor) { return new ConstructorInvokable<T>(constructor); } /** * Returns {@code true} if this is an overridable method. Constructors, private, static or final * methods, or methods declared by final classes are not overridable. */ public abstract boolean isOverridable(); /** Returns {@code true} if this was declared to take a variable number of arguments. */ public abstract boolean isVarArgs(); /** * Invokes with {@code receiver} as 'this' and {@code args} passed to the underlying method * and returns the return value; or calls the underlying constructor with {@code args} and returns * the constructed instance. * * @throws IllegalAccessException if this {@code Constructor} object enforces Java language * access control and the underlying method or constructor is inaccessible. * @throws IllegalArgumentException if the number of actual and formal parameters differ; * if an unwrapping conversion for primitive arguments fails; or if, after possible * unwrapping, a parameter value cannot be converted to the corresponding formal * parameter type by a method invocation conversion. * @throws InvocationTargetException if the underlying method or constructor throws an exception. */ // All subclasses are owned by us and we'll make sure to get the R type right. @SuppressWarnings("unchecked") public final R invoke(@Nullable T receiver, Object... args) throws InvocationTargetException, IllegalAccessException { return (R) invokeInternal(receiver, checkNotNull(args)); } /** Returns the return type of this {@code Invokable}. */ // All subclasses are owned by us and we'll make sure to get the R type right. @SuppressWarnings("unchecked") public final TypeToken<? extends R> getReturnType() { return (TypeToken<? extends R>) TypeToken.of(getGenericReturnType()); } /** * Returns all declared parameters of this {@code Invokable}. Note that if this is a constructor * of a non-static inner class, unlike {@link Constructor#getParameterTypes}, the hidden * {@code this} parameter of the enclosing class is excluded from the returned parameters. */ public final ImmutableList<Parameter> getParameters() { Type[] parameterTypes = getGenericParameterTypes(); Annotation[][] annotations = getParameterAnnotations(); ImmutableList.Builder<Parameter> builder = ImmutableList.builder(); for (int i = 0; i < parameterTypes.length; i++) { builder.add(new Parameter( this, i, TypeToken.of(parameterTypes[i]), annotations[i])); } return builder.build(); } /** Returns all declared exception types of this {@code Invokable}. */ public final ImmutableList<TypeToken<? extends Throwable>> getExceptionTypes() { ImmutableList.Builder<TypeToken<? extends Throwable>> builder = ImmutableList.builder(); for (Type type : getGenericExceptionTypes()) { // getGenericExceptionTypes() will never return a type that's not exception @SuppressWarnings("unchecked") TypeToken<? extends Throwable> exceptionType = (TypeToken<? extends Throwable>) TypeToken.of(type); builder.add(exceptionType); } return builder.build(); } /** * Explicitly specifies the return type of this {@code Invokable}. For example: * <pre> {@code * Method factoryMethod = Person.class.getMethod("create"); * Invokable<?, Person> factory = Invokable.of(getNameMethod).returning(Person.class);}</pre> */ public final <R1 extends R> Invokable<T, R1> returning(Class<R1> returnType) { return returning(TypeToken.of(returnType)); } /** Explicitly specifies the return type of this {@code Invokable}. */ public final <R1 extends R> Invokable<T, R1> returning(TypeToken<R1> returnType) { if (!returnType.isAssignableFrom(getReturnType())) { throw new IllegalArgumentException( "Invokable is known to return " + getReturnType() + ", not " + returnType); } @SuppressWarnings("unchecked") // guarded by previous check Invokable<T, R1> specialized = (Invokable<T, R1>) this; return specialized; } @SuppressWarnings("unchecked") // The declaring class is T's raw class, or one of its supertypes. @Override public final Class<? super T> getDeclaringClass() { return (Class<? super T>) super.getDeclaringClass(); } /** Returns the type of {@code T}. */ // Overridden in TypeToken#method() and TypeToken#constructor() @SuppressWarnings("unchecked") // The declaring class is T. @Override public TypeToken<T> getOwnerType() { return (TypeToken<T>) TypeToken.of(getDeclaringClass()); } abstract Object invokeInternal(@Nullable Object receiver, Object[] args) throws InvocationTargetException, IllegalAccessException; abstract Type[] getGenericParameterTypes(); /** This should never return a type that's not a subtype of Throwable. */ abstract Type[] getGenericExceptionTypes(); abstract Annotation[][] getParameterAnnotations(); abstract Type getGenericReturnType(); static class MethodInvokable<T> extends Invokable<T, Object> { final Method method; MethodInvokable(Method method) { super(method); this.method = method; } @Override final Object invokeInternal(@Nullable Object receiver, Object[] args) throws InvocationTargetException, IllegalAccessException { return method.invoke(receiver, args); } @Override Type getGenericReturnType() { return method.getGenericReturnType(); } @Override Type[] getGenericParameterTypes() { return method.getGenericParameterTypes(); } @Override Type[] getGenericExceptionTypes() { return method.getGenericExceptionTypes(); } @Override final Annotation[][] getParameterAnnotations() { return method.getParameterAnnotations(); } @Override public final TypeVariable<?>[] getTypeParameters() { return method.getTypeParameters(); } @Override public final boolean isOverridable() { return !(isFinal() || isPrivate() || isStatic() || Modifier.isFinal(getDeclaringClass().getModifiers())); } @Override public final boolean isVarArgs() { return method.isVarArgs(); } } static class ConstructorInvokable<T> extends Invokable<T, T> { final Constructor<?> constructor; ConstructorInvokable(Constructor<?> constructor) { super(constructor); this.constructor = constructor; } @Override final Object invokeInternal(@Nullable Object receiver, Object[] args) throws InvocationTargetException, IllegalAccessException { try { return constructor.newInstance(args); } catch (InstantiationException e) { throw new RuntimeException(constructor + " failed.", e); } } /** If the class is parameterized, such as ArrayList, this returns ArrayList<E>. */ @Override Type getGenericReturnType() { Class<?> declaringClass = getDeclaringClass(); TypeVariable<?>[] typeParams = declaringClass.getTypeParameters(); if (typeParams.length > 0) { return Types.newParameterizedType(declaringClass, typeParams); } else { return declaringClass; } } @Override Type[] getGenericParameterTypes() { Type[] types = constructor.getGenericParameterTypes(); if (types.length > 0 && mayNeedHiddenThis()) { Class<?>[] rawParamTypes = constructor.getParameterTypes(); if (types.length == rawParamTypes.length && rawParamTypes[0] == getDeclaringClass().getEnclosingClass()) { // first parameter is the hidden 'this' return Arrays.copyOfRange(types, 1, types.length); } } return types; } @Override Type[] getGenericExceptionTypes() { return constructor.getGenericExceptionTypes(); } @Override final Annotation[][] getParameterAnnotations() { return constructor.getParameterAnnotations(); } /** * {@inheritDoc} * * {@code [<E>]} will be returned for ArrayList's constructor. When both the class and the * constructor have type parameters, the class parameters are prepended before those of the * constructor's. This is an arbitrary rule since no existing language spec mandates one way or * the other. From the declaration syntax, the class type parameter appears first, but the * call syntax may show up in opposite order such as {@code new <A>Foo<B>()}. */ @Override public final TypeVariable<?>[] getTypeParameters() { TypeVariable<?>[] declaredByClass = getDeclaringClass().getTypeParameters(); TypeVariable<?>[] declaredByConstructor = constructor.getTypeParameters(); TypeVariable<?>[] result = new TypeVariable<?>[declaredByClass.length + declaredByConstructor.length]; System.arraycopy(declaredByClass, 0, result, 0, declaredByClass.length); System.arraycopy( declaredByConstructor, 0, result, declaredByClass.length, declaredByConstructor.length); return result; } @Override public final boolean isOverridable() { return false; } @Override public final boolean isVarArgs() { return constructor.isVarArgs(); } private boolean mayNeedHiddenThis() { Class<?> declaringClass = constructor.getDeclaringClass(); if (declaringClass.getEnclosingConstructor() != null) { // Enclosed in a constructor, needs hidden this return true; } Method enclosingMethod = declaringClass.getEnclosingMethod(); if (enclosingMethod != null) { // Enclosed in a method, if it's not static, must need hidden this. return !Modifier.isStatic(enclosingMethod.getModifiers()); } else { // Strictly, this doesn't necessarily indicate a hidden 'this' in the case of // static initializer. But there seems no way to tell in that case. :( // This may cause issues when an anonymous class is created inside a static initializer, // and the class's constructor's first parameter happens to be the enclosing class. // In such case, we may mistakenly think that the class is within a non-static context // and the first parameter is the hidden 'this'. return declaringClass.getEnclosingClass() != null && !Modifier.isStatic(declaringClass.getModifiers()); } } } }
zzhhhhh-aw4rwer
guava/src/com/google/common/reflect/Invokable.java
Java
asf20
13,249
/* * Copyright (C) 2012 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.reflect; import static com.google.common.base.Preconditions.checkArgument; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; /** * Captures the actual type of {@code T}. * * @author Ben Yu */ abstract class TypeCapture<T> { /** Returns the captured type. */ final Type capture() { Type superclass = getClass().getGenericSuperclass(); checkArgument(superclass instanceof ParameterizedType, "%s isn't parameterized", superclass); return ((ParameterizedType) superclass).getActualTypeArguments()[0]; } }
zzhhhhh-aw4rwer
guava/src/com/google/common/reflect/TypeCapture.java
Java
asf20
1,188
/* * Copyright (C) 2012 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.reflect; import com.google.common.annotations.Beta; import java.util.Map; import javax.annotation.Nullable; /** * A map, each entry of which maps a {@link TypeToken} to an instance of that type. * In addition to implementing {@code Map}, the additional type-safe operations * {@link #putInstance} and {@link #getInstance} are available. * * <p>Generally, implementations don't support {@link #put} and {@link #putAll} * because there is no way to check an object at runtime to be an instance of a * {@link TypeToken}. Instead, caller should use the type safe {@link #putInstance}. * * <p>Also, if caller suppresses unchecked warnings and passes in an {@code Iterable<String>} * for type {@code Iterable<Integer>}, the map won't be able to detect and throw type error. * * <p>Like any other {@code Map<Class, Object>}, this map may contain entries * for primitive types, and a primitive type and its corresponding wrapper type * may map to different values. * * @param <B> the common supertype that all entries must share; often this is * simply {@link Object} * * @author Ben Yu * @since 13.0 */ @Beta public interface TypeToInstanceMap<B> extends Map<TypeToken<? extends B>, B> { /** * Returns the value the specified class is mapped to, or {@code null} if no * entry for this class is present. This will only return a value that was * bound to this specific class, not a value that may have been bound to a * subtype. * * <p>{@code getInstance(Foo.class)} is equivalent to * {@code getInstance(TypeToken.of(Foo.class))}. */ @Nullable <T extends B> T getInstance(Class<T> type); /** * Maps the specified class to the specified value. Does <i>not</i> associate * this value with any of the class's supertypes. * * <p>{@code putInstance(Foo.class, foo)} is equivalent to * {@code putInstance(TypeToken.of(Foo.class), foo)}. * * @return the value previously associated with this class (possibly {@code null}), * or {@code null} if there was no previous entry. */ @Nullable <T extends B> T putInstance(Class<T> type, @Nullable T value); /** * Returns the value the specified type is mapped to, or {@code null} if no * entry for this type is present. This will only return a value that was * bound to this specific type, not a value that may have been bound to a subtype. */ @Nullable <T extends B> T getInstance(TypeToken<T> type); /** * Maps the specified type to the specified value. Does <i>not</i> associate * this value with any of the type's supertypes. * * @return the value previously associated with this type (possibly {@code null}), * or {@code null} if there was no previous entry. */ @Nullable <T extends B> T putInstance(TypeToken<T> type, @Nullable T value); }
zzhhhhh-aw4rwer
guava/src/com/google/common/reflect/TypeToInstanceMap.java
Java
asf20
3,459
/* * Copyright (C) 2012 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.reflect; import static com.google.common.base.Preconditions.checkNotNull; import java.lang.annotation.Annotation; import java.lang.reflect.AccessibleObject; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.Member; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import javax.annotation.Nullable; /** * Represents either a {@link Field}, a {@link Method} or a {@link Constructor}. * Provides convenience methods such as {@link #isPublic} and {@link #isPackagePrivate}. * * @author Ben Yu */ class Element extends AccessibleObject implements Member { private final AccessibleObject accessibleObject; private final Member member; <M extends AccessibleObject & Member> Element(M member) { checkNotNull(member); this.accessibleObject = member; this.member = member; } public TypeToken<?> getOwnerType() { return TypeToken.of(getDeclaringClass()); } @Override public final boolean isAnnotationPresent(Class<? extends Annotation> annotationClass) { return accessibleObject.isAnnotationPresent(annotationClass); } @Override public final <A extends Annotation> A getAnnotation(Class<A> annotationClass) { return accessibleObject.getAnnotation(annotationClass); } @Override public final Annotation[] getAnnotations() { return accessibleObject.getAnnotations(); } @Override public final Annotation[] getDeclaredAnnotations() { return accessibleObject.getDeclaredAnnotations(); } @Override public final void setAccessible(boolean flag) throws SecurityException { accessibleObject.setAccessible(flag); } @Override public final boolean isAccessible() { return accessibleObject.isAccessible(); } @Override public Class<?> getDeclaringClass() { return member.getDeclaringClass(); } @Override public final String getName() { return member.getName(); } @Override public final int getModifiers() { return member.getModifiers(); } @Override public final boolean isSynthetic() { return member.isSynthetic(); } /** Returns true if the element is public. */ public final boolean isPublic() { return Modifier.isPublic(getModifiers()); } /** Returns true if the element is protected. */ public final boolean isProtected() { return Modifier.isProtected(getModifiers()); } /** Returns true if the element is package-private. */ public final boolean isPackagePrivate() { return !isPrivate() && !isPublic() && !isProtected(); } /** Returns true if the element is private. */ public final boolean isPrivate() { return Modifier.isPrivate(getModifiers()); } /** Returns true if the element is static. */ public final boolean isStatic() { return Modifier.isStatic(getModifiers()); } /** * Returns {@code true} if this method is final, per {@code Modifier.isFinal(getModifiers())}. * * <p>Note that a method may still be effectively "final", or non-overridable when it has no * {@code final} keyword. For example, it could be private, or it could be declared by a final * class. To tell whether a method is overridable, use {@link Invokable#isOverridable}. */ public final boolean isFinal() { return Modifier.isFinal(getModifiers()); } /** Returns true if the method is abstract. */ public final boolean isAbstract() { return Modifier.isAbstract(getModifiers()); } /** Returns true if the element is native. */ public final boolean isNative() { return Modifier.isNative(getModifiers()); } /** Returns true if the method is synchronized. */ public final boolean isSynchronized() { return Modifier.isSynchronized(getModifiers()); } /** Returns true if the field is volatile. */ final boolean isVolatile() { return Modifier.isVolatile(getModifiers()); } /** Returns true if the field is transient. */ final boolean isTransient() { return Modifier.isTransient(getModifiers()); } @Override public boolean equals(@Nullable Object obj) { if (obj instanceof Element) { Element that = (Element) obj; return getOwnerType().equals(that.getOwnerType()) && member.equals(that.member); } return false; } @Override public int hashCode() { return member.hashCode(); } @Override public String toString() { return member.toString(); } }
zzhhhhh-aw4rwer
guava/src/com/google/common/reflect/Element.java
Java
asf20
4,997
/* * Copyright (C) 2012 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.reflect; import static com.google.common.base.Preconditions.checkNotNull; import com.google.common.annotations.Beta; import com.google.common.base.Function; import com.google.common.collect.ForwardingMap; import com.google.common.collect.ForwardingMapEntry; import com.google.common.collect.ForwardingSet; import com.google.common.collect.Iterators; import com.google.common.collect.Maps; import java.util.Iterator; import java.util.Map; import java.util.Set; import javax.annotation.Nullable; /** * A mutable type-to-instance map. * See also {@link ImmutableTypeToInstanceMap}. * * @author Ben Yu * @since 13.0 */ @Beta public final class MutableTypeToInstanceMap<B> extends ForwardingMap<TypeToken<? extends B>, B> implements TypeToInstanceMap<B> { private final Map<TypeToken<? extends B>, B> backingMap = Maps.newHashMap(); @Nullable @Override public <T extends B> T getInstance(Class<T> type) { return trustedGet(TypeToken.of(type)); } @Nullable @Override public <T extends B> T putInstance(Class<T> type, @Nullable T value) { return trustedPut(TypeToken.of(type), value); } @Nullable @Override public <T extends B> T getInstance(TypeToken<T> type) { return trustedGet(type.rejectTypeVariables()); } @Nullable @Override public <T extends B> T putInstance(TypeToken<T> type, @Nullable T value) { return trustedPut(type.rejectTypeVariables(), value); } /** Not supported. Use {@link #putInstance} instead. */ @Override public B put(TypeToken<? extends B> key, B value) { throw new UnsupportedOperationException("Please use putInstance() instead."); } /** Not supported. Use {@link #putInstance} instead. */ @Override public void putAll(Map<? extends TypeToken<? extends B>, ? extends B> map) { throw new UnsupportedOperationException("Please use putInstance() instead."); } @Override public Set<Entry<TypeToken<? extends B>, B>> entrySet() { return UnmodifiableEntry.transformEntries(super.entrySet()); } @Override protected Map<TypeToken<? extends B>, B> delegate() { return backingMap; } @SuppressWarnings("unchecked") // value could not get in if not a T @Nullable private <T extends B> T trustedPut(TypeToken<T> type, @Nullable T value) { return (T) backingMap.put(type, value); } @SuppressWarnings("unchecked") // value could not get in if not a T @Nullable private <T extends B> T trustedGet(TypeToken<T> type) { return (T) backingMap.get(type); } private static final class UnmodifiableEntry<K, V> extends ForwardingMapEntry<K, V> { private final Entry<K, V> delegate; static <K, V> Set<Entry<K, V>> transformEntries(final Set<Entry<K, V>> entries) { return new ForwardingSet<Map.Entry<K, V>>() { @Override protected Set<Entry<K, V>> delegate() { return entries; } @Override public Iterator<Entry<K, V>> iterator() { return UnmodifiableEntry.transformEntries(super.iterator()); } @Override public Object[] toArray() { return standardToArray(); } @Override public <T> T[] toArray(T[] array) { return standardToArray(array); } }; } private static <K, V> Iterator<Entry<K, V>> transformEntries(Iterator<Entry<K, V>> entries) { return Iterators.transform(entries, new Function<Entry<K, V>, Entry<K, V>>() { @Override public Entry<K, V> apply(Entry<K, V> entry) { return new UnmodifiableEntry<K, V>(entry); } }); } private UnmodifiableEntry(java.util.Map.Entry<K, V> delegate) { this.delegate = checkNotNull(delegate); } @Override protected Entry<K, V> delegate() { return delegate; } @Override public V setValue(V value) { throw new UnsupportedOperationException(); } } }
zzhhhhh-aw4rwer
guava/src/com/google/common/reflect/MutableTypeToInstanceMap.java
Java
asf20
4,471
/* * Copyright (C) 2009 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.reflect; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Preconditions.checkState; import com.google.common.annotations.Beta; import com.google.common.base.Joiner; import com.google.common.base.Objects; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Maps; import java.lang.reflect.GenericArrayType; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.lang.reflect.TypeVariable; import java.lang.reflect.WildcardType; import java.util.Arrays; import java.util.Map; import java.util.concurrent.atomic.AtomicInteger; import javax.annotation.Nullable; /** * An object of this class encapsulates type mappings from type variables. Mappings are established * with {@link #where} and types are resolved using {@link #resolveType}. * * <p>Note that usually type mappings are already implied by the static type hierarchy (for example, * the {@code E} type variable declared by class {@code List} naturally maps to {@code String} in * the context of {@code class MyStringList implements List<String>}. In such case, prefer to use * {@link TypeToken#resolveType} since it's simpler and more type safe. This class should only be * used when the type mapping isn't implied by the static type hierarchy, but provided through other * means such as an annotation or external configuration file. * * @author Ben Yu * @since 15.0 */ @Beta public final class TypeResolver { private final TypeTable typeTable; public TypeResolver() { this.typeTable = new TypeTable(); } private TypeResolver(TypeTable typeTable) { this.typeTable = typeTable; } static TypeResolver accordingTo(Type type) { return new TypeResolver().where(TypeMappingIntrospector.getTypeMappings(type)); } /** * Returns a new {@code TypeResolver} with type variables in {@code formal} mapping to types in * {@code actual}. * * <p>For example, if {@code formal} is a {@code TypeVariable T}, and {@code actual} is {@code * String.class}, then {@code new TypeResolver().where(formal, actual)} will {@linkplain * #resolveType resolve} {@code ParameterizedType List<T>} to {@code List<String>}, and resolve * {@code Map<T, Something>} to {@code Map<String, Something>} etc. Similarly, {@code formal} and * {@code actual} can be {@code Map<K, V>} and {@code Map<String, Integer>} respectively, or they * can be {@code E[]} and {@code String[]} respectively, or even any arbitrary combination * thereof. * * @param formal The type whose type variables or itself is mapped to other type(s). It's almost * always a bug if {@code formal} isn't a type variable and contains no type variable. Make * sure you are passing the two parameters in the right order. * @param actual The type that the formal type variable(s) are mapped to. It can be or contain yet * other type variables, in which case these type variables will be further resolved if * corresponding mappings exist in the current {@code TypeResolver} instance. */ public TypeResolver where(Type formal, Type actual) { Map<TypeVariableKey, Type> mappings = Maps.newHashMap(); populateTypeMappings(mappings, checkNotNull(formal), checkNotNull(actual)); return where(mappings); } /** Returns a new {@code TypeResolver} with {@code variable} mapping to {@code type}. */ TypeResolver where(Map<TypeVariableKey, ? extends Type> mappings) { return new TypeResolver(typeTable.where(mappings)); } private static void populateTypeMappings( final Map<TypeVariableKey, Type> mappings, Type from, final Type to) { if (from.equals(to)) { return; } new TypeVisitor() { @Override void visitTypeVariable(TypeVariable<?> typeVariable) { mappings.put(new TypeVariableKey(typeVariable), to); } @Override void visitWildcardType(WildcardType fromWildcardType) { WildcardType toWildcardType = expectArgument(WildcardType.class, to); Type[] fromUpperBounds = fromWildcardType.getUpperBounds(); Type[] toUpperBounds = toWildcardType.getUpperBounds(); Type[] fromLowerBounds = fromWildcardType.getLowerBounds(); Type[] toLowerBounds = toWildcardType.getLowerBounds(); checkArgument( fromUpperBounds.length == toUpperBounds.length && fromLowerBounds.length == toLowerBounds.length, "Incompatible type: %s vs. %s", fromWildcardType, to); for (int i = 0; i < fromUpperBounds.length; i++) { populateTypeMappings(mappings, fromUpperBounds[i], toUpperBounds[i]); } for (int i = 0; i < fromLowerBounds.length; i++) { populateTypeMappings(mappings, fromLowerBounds[i], toLowerBounds[i]); } } @Override void visitParameterizedType(ParameterizedType fromParameterizedType) { ParameterizedType toParameterizedType = expectArgument(ParameterizedType.class, to); checkArgument(fromParameterizedType.getRawType().equals(toParameterizedType.getRawType()), "Inconsistent raw type: %s vs. %s", fromParameterizedType, to); Type[] fromArgs = fromParameterizedType.getActualTypeArguments(); Type[] toArgs = toParameterizedType.getActualTypeArguments(); checkArgument(fromArgs.length == toArgs.length, "%s not compatible with %s", fromParameterizedType, toParameterizedType); for (int i = 0; i < fromArgs.length; i++) { populateTypeMappings(mappings, fromArgs[i], toArgs[i]); } } @Override void visitGenericArrayType(GenericArrayType fromArrayType) { Type componentType = Types.getComponentType(to); checkArgument(componentType != null, "%s is not an array type.", to); populateTypeMappings(mappings, fromArrayType.getGenericComponentType(), componentType); } @Override void visitClass(Class<?> fromClass) { // Can't map from a raw class to anything other than itself. // You can't say "assuming String is Integer". // And we don't support "assuming String is T"; user has to say "assuming T is String". throw new IllegalArgumentException("No type mapping from " + fromClass); } }.visit(from); } /** * 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) { return resolveWildcardType((WildcardType) type); } else { // if Class<?>, no resolution needed, we are done. return type; } } private Type[] resolveTypes(Type[] types) { Type[] result = new Type[types.length]; for (int i = 0; i < types.length; i++) { result[i] = resolveType(types[i]); } return result; } private WildcardType resolveWildcardType(WildcardType type) { Type[] lowerBounds = type.getLowerBounds(); Type[] upperBounds = type.getUpperBounds(); return new Types.WildcardTypeImpl( resolveTypes(lowerBounds), resolveTypes(upperBounds)); } private Type resolveGenericArrayType(GenericArrayType type) { Type componentType = type.getGenericComponentType(); Type resolvedComponentType = resolveType(componentType); return Types.newArrayType(resolvedComponentType); } private ParameterizedType resolveParameterizedType(ParameterizedType type) { Type owner = type.getOwnerType(); Type resolvedOwner = (owner == null) ? null : resolveType(owner); Type resolvedRawType = resolveType(type.getRawType()); Type[] args = type.getActualTypeArguments(); Type[] resolvedArgs = resolveTypes(args); return Types.newParameterizedTypeWithOwner( resolvedOwner, (Class<?>) resolvedRawType, resolvedArgs); } private static <T> T expectArgument(Class<T> type, Object arg) { try { return type.cast(arg); } catch (ClassCastException e) { throw new IllegalArgumentException(arg + " is not a " + type.getSimpleName()); } } /** A TypeTable maintains mapping from {@link TypeVariable} to types. */ private static class TypeTable { private final ImmutableMap<TypeVariableKey, Type> map; TypeTable() { this.map = ImmutableMap.of(); } private TypeTable(ImmutableMap<TypeVariableKey, Type> map) { this.map = map; } /** Returns a new {@code TypeResolver} with {@code variable} mapping to {@code type}. */ final TypeTable where(Map<TypeVariableKey, ? extends Type> mappings) { ImmutableMap.Builder<TypeVariableKey, Type> builder = ImmutableMap.builder(); builder.putAll(map); for (Map.Entry<TypeVariableKey, ? extends Type> mapping : mappings.entrySet()) { TypeVariableKey variable = mapping.getKey(); Type type = mapping.getValue(); checkArgument(!variable.equalsType(type), "Type variable %s bound to itself", variable); builder.put(variable, type); } return new TypeTable(builder.build()); } final Type resolve(final TypeVariable<?> var) { final TypeTable unguarded = this; TypeTable guarded = new TypeTable() { @Override public Type resolveInternal( TypeVariable<?> intermediateVar, TypeTable forDependent) { if (intermediateVar.getGenericDeclaration().equals(var.getGenericDeclaration())) { return intermediateVar; } return unguarded.resolveInternal(intermediateVar, forDependent); } }; return resolveInternal(var, guarded); } /** * Resolves {@code var} using the encapsulated type mapping. If it maps to yet another * non-reified type or has bounds, {@code forDependants} is used to do further resolution, which * doesn't try to resolve any type variable on generic declarations that are already being * resolved. * * <p>Should only be called and overridden by {@link #resolve(TypeVariable)}. */ Type resolveInternal(TypeVariable<?> var, TypeTable forDependants) { Type type = map.get(new TypeVariableKey(var)); if (type == null) { Type[] bounds = var.getBounds(); if (bounds.length == 0) { return var; } Type[] resolvedBounds = new TypeResolver(forDependants).resolveTypes(bounds); /* * We'd like to simply create our own TypeVariable with the newly resolved bounds. There's * just one problem: Starting with JDK 7u51, the JDK TypeVariable's equals() method doesn't * recognize instances of our TypeVariable implementation. This is a problem because users * compare TypeVariables from the JDK against TypeVariables returned by TypeResolver. To * work with all JDK versions, TypeResolver must return the appropriate TypeVariable * implementation in each of the three possible cases: * * 1. Prior to JDK 7u51, the JDK TypeVariable implementation interoperates with ours. * Therefore, we can always create our own TypeVariable. * * 2. Starting with JDK 7u51, the JDK TypeVariable implementations does not interoperate * with ours. Therefore, we have to be careful about whether we create our own TypeVariable: * * 2a. If the resolved types are identical to the original types, then we can return the * original, identical JDK TypeVariable. By doing so, we sidestep the problem entirely. * * 2b. If the resolved types are different from the original types, things are trickier. The * only way to get a TypeVariable instance for the resolved types is to create our own. The * created TypeVariable will not interoperate with any JDK TypeVariable. But this is OK: We * don't _want_ our new TypeVariable to be equal to the JDK TypeVariable because it has * _different bounds_ than the JDK TypeVariable. And it wouldn't make sense for our new * TypeVariable to be equal to any _other_ JDK TypeVariable, either, because any other JDK * TypeVariable must have a different declaration or name. The only TypeVariable that our * new TypeVariable _will_ be equal to is an equivalent TypeVariable that was also created * by us. And that equality is guaranteed to hold because it doesn't involve the JDK * TypeVariable implementation at all. */ if (Types.NativeTypeVariableEquals.NATIVE_TYPE_VARIABLE_ONLY && Arrays.equals(bounds, resolvedBounds)) { return var; } return Types.newArtificialTypeVariable( var.getGenericDeclaration(), var.getName(), resolvedBounds); } // in case the type is yet another type variable. return new TypeResolver(forDependants).resolveType(type); } } private static final class TypeMappingIntrospector extends TypeVisitor { private static final WildcardCapturer wildcardCapturer = new WildcardCapturer(); private final Map<TypeVariableKey, Type> mappings = Maps.newHashMap(); /** * Returns type mappings using type parameters and type arguments found in * the generic superclass and the super interfaces of {@code contextClass}. */ static ImmutableMap<TypeVariableKey, Type> getTypeMappings( Type contextType) { TypeMappingIntrospector introspector = new TypeMappingIntrospector(); introspector.visit(wildcardCapturer.capture(contextType)); return ImmutableMap.copyOf(introspector.mappings); } @Override void visitClass(Class<?> clazz) { visit(clazz.getGenericSuperclass()); visit(clazz.getGenericInterfaces()); } @Override void visitParameterizedType(ParameterizedType parameterizedType) { Class<?> rawClass = (Class<?>) parameterizedType.getRawType(); TypeVariable<?>[] vars = rawClass.getTypeParameters(); Type[] typeArgs = parameterizedType.getActualTypeArguments(); checkState(vars.length == typeArgs.length); for (int i = 0; i < vars.length; i++) { map(new TypeVariableKey(vars[i]), typeArgs[i]); } visit(rawClass); visit(parameterizedType.getOwnerType()); } @Override void visitTypeVariable(TypeVariable<?> t) { visit(t.getBounds()); } @Override void visitWildcardType(WildcardType t) { visit(t.getUpperBounds()); } private void map(final TypeVariableKey var, final Type arg) { if (mappings.containsKey(var)) { // Mapping already established // This is possible when following both superClass -> enclosingClass // and enclosingclass -> superClass paths. // Since we follow the path of superclass first, enclosing second, // superclass mapping should take precedence. return; } // First, check whether var -> arg forms a cycle for (Type t = arg; t != null; t = mappings.get(TypeVariableKey.forLookup(t))) { if (var.equalsType(t)) { // cycle detected, remove the entire cycle from the mapping so that // each type variable resolves deterministically to itself. // Otherwise, a F -> T cycle will end up resolving both F and T // nondeterministically to either F or T. for (Type x = arg; x != null; x = mappings.remove(TypeVariableKey.forLookup(x))) {} return; } } mappings.put(var, arg); } } // This is needed when resolving types against a context with wildcards // For example: // class Holder<T> { // void set(T data) {...} // } // Holder<List<?>> should *not* resolve the set() method to set(List<?> data). // Instead, it should create a capture of the wildcard so that set() rejects any List<T>. private static final class WildcardCapturer { private final AtomicInteger id = new AtomicInteger(); 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.newArtificialTypeVariable( 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"); } private Type captureNullable(@Nullable Type type) { if (type == null) { return null; } return capture(type); } private Type[] capture(Type[] types) { Type[] result = new Type[types.length]; for (int i = 0; i < types.length; i++) { result[i] = capture(types[i]); } return result; } } /** * Wraps around {@code TypeVariable<?>} to ensure that any two type variables are equal as long as * they are declared by the same {@link java.lang.reflect.GenericDeclaration} and have the same * name, even if their bounds differ. * * <p>While resolving a type variable from a {var -> type} map, we don't care whether the * type variable's bound has been partially resolved. As long as the type variable "identity" * matches. * * <p>On the other hand, if for example we are resolving List<A extends B> to * List<A extends String>, we need to compare that <A extends B> is unequal to * <A extends String> in order to decide to use the transformed type instead of the original * type. */ static final class TypeVariableKey { private final TypeVariable<?> var; TypeVariableKey(TypeVariable<?> var) { this.var = checkNotNull(var); } @Override public int hashCode() { return Objects.hashCode(var.getGenericDeclaration(), var.getName()); } @Override public boolean equals(Object obj) { if (obj instanceof TypeVariableKey) { TypeVariableKey that = (TypeVariableKey) obj; return equalsTypeVariable(that.var); } else { return false; } } @Override public String toString() { return var.toString(); } /** Wraps {@code t} in a {@code TypeVariableKey} if it's a type variable. */ static Object forLookup(Type t) { if (t instanceof TypeVariable) { return new TypeVariableKey((TypeVariable<?>) t); } else { return null; } } /** * Returns true if {@code type} is a {@code TypeVariable} with the same name and declared by * the same {@code GenericDeclaration}. */ boolean equalsType(Type type) { if (type instanceof TypeVariable) { return equalsTypeVariable((TypeVariable<?>) type); } else { return false; } } private boolean equalsTypeVariable(TypeVariable<?> that) { return var.getGenericDeclaration().equals(that.getGenericDeclaration()) && var.getName().equals(that.getName()); } } }
zzhhhhh-aw4rwer
guava/src/com/google/common/reflect/TypeResolver.java
Java
asf20
21,005
/* * Copyright (C) 2012 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.reflect; import com.google.common.annotations.Beta; import com.google.common.collect.ForwardingMap; import com.google.common.collect.ImmutableMap; import java.util.Map; /** * A type-to-instance map backed by an {@link ImmutableMap}. See also {@link * MutableTypeToInstanceMap}. * * @author Ben Yu * @since 13.0 */ @Beta public final class ImmutableTypeToInstanceMap<B> extends ForwardingMap<TypeToken<? extends B>, B> implements TypeToInstanceMap<B> { /** Returns an empty type to instance map. */ public static <B> ImmutableTypeToInstanceMap<B> of() { return new ImmutableTypeToInstanceMap<B>(ImmutableMap.<TypeToken<? extends B>, B>of()); } /** Returns a new builder. */ public static <B> Builder<B> builder() { return new Builder<B>(); } /** * A builder for creating immutable type-to-instance maps. Example: * <pre> {@code * * static final ImmutableTypeToInstanceMap<Handler<?>> HANDLERS = * ImmutableTypeToInstanceMap.<Handler<?>>builder() * .put(new TypeToken<Handler<Foo>>() {}, new FooHandler()) * .put(new TypeToken<Handler<Bar>>() {}, new SubBarHandler()) * .build();}</pre> * * <p>After invoking {@link #build()} it is still possible to add more entries * and build again. Thus each map generated by this builder will be a superset * of any map generated before it. * * @since 13.0 */ @Beta public static final class Builder<B> { private final ImmutableMap.Builder<TypeToken<? extends B>, B> mapBuilder = ImmutableMap.builder(); private Builder() {} /** * Associates {@code key} with {@code value} in the built map. Duplicate * keys are not allowed, and will cause {@link #build} to fail. */ public <T extends B> Builder<B> put(Class<T> key, T value) { mapBuilder.put(TypeToken.of(key), value); return this; } /** * Associates {@code key} with {@code value} in the built map. Duplicate * keys are not allowed, and will cause {@link #build} to fail. */ public <T extends B> Builder<B> put(TypeToken<T> key, T value) { mapBuilder.put(key.rejectTypeVariables(), value); return this; } /** * Returns a new immutable type-to-instance map containing the entries * provided to this builder. * * @throws IllegalArgumentException if duplicate keys were added */ public ImmutableTypeToInstanceMap<B> build() { return new ImmutableTypeToInstanceMap<B>(mapBuilder.build()); } } private final ImmutableMap<TypeToken<? extends B>, B> delegate; private ImmutableTypeToInstanceMap(ImmutableMap<TypeToken<? extends B>, B> delegate) { this.delegate = delegate; } @Override public <T extends B> T getInstance(TypeToken<T> type) { return trustedGet(type.rejectTypeVariables()); } /** * Guaranteed to throw an exception and leave the map unmodified. * * @throws UnsupportedOperationException always */ @Override public <T extends B> T putInstance(TypeToken<T> type, T value) { throw new UnsupportedOperationException(); } @Override public <T extends B> T getInstance(Class<T> type) { return trustedGet(TypeToken.of(type)); } /** * Guaranteed to throw an exception and leave the map unmodified. * * @throws UnsupportedOperationException always */ @Override public <T extends B> T putInstance(Class<T> type, T value) { throw new UnsupportedOperationException(); } @Override protected Map<TypeToken<? extends B>, B> delegate() { return delegate; } @SuppressWarnings("unchecked") // value could not get in if not a T private <T extends B> T trustedGet(TypeToken<T> type) { return (T) delegate.get(type); } }
zzhhhhh-aw4rwer
guava/src/com/google/common/reflect/ImmutableTypeToInstanceMap.java
Java
asf20
4,388
/* * Copyright (C) 2009 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.net; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Preconditions.checkState; import com.google.common.annotations.Beta; import com.google.common.annotations.GwtCompatible; import com.google.common.base.Ascii; import com.google.common.base.CharMatcher; import com.google.common.base.Joiner; import com.google.common.base.Splitter; import com.google.common.collect.ImmutableList; import com.google.thirdparty.publicsuffix.PublicSuffixPatterns; import java.util.List; import javax.annotation.Nullable; /** * An immutable well-formed internet domain name, such as {@code com} or {@code * foo.co.uk}. Only syntactic analysis is performed; no DNS lookups or other * network interactions take place. Thus there is no guarantee that the domain * actually exists on the internet. * * <p>One common use of this class is to determine whether a given string is * likely to represent an addressable domain on the web -- that is, for a * candidate string {@code "xxx"}, might browsing to {@code "http://xxx/"} * result in a webpage being displayed? In the past, this test was frequently * done by determining whether the domain ended with a {@linkplain * #isPublicSuffix() public suffix} but was not itself a public suffix. However, * this test is no longer accurate. There are many domains which are both public * suffixes and addressable as hosts; {@code "uk.com"} is one example. As a * result, the only useful test to determine if a domain is a plausible web host * is {@link #hasPublicSuffix()}. This will return {@code true} for many domains * which (currently) are not hosts, such as {@code "com"}, but given that any * public suffix may become a host without warning, it is better to err on the * side of permissiveness and thus avoid spurious rejection of valid sites. * * <p>During construction, names are normalized in two ways: * <ol> * <li>ASCII uppercase characters are converted to lowercase. * <li>Unicode dot separators other than the ASCII period ({@code '.'}) are * converted to the ASCII period. * </ol> * <p>The normalized values will be returned from {@link #toString()} and * {@link #parts()}, and will be reflected in the result of * {@link #equals(Object)}. * * <p><a href="http://en.wikipedia.org/wiki/Internationalized_domain_name"> * Internationalized domain names</a> such as {@code 网络.cn} are supported, as * are the equivalent <a * href="http://en.wikipedia.org/wiki/Internationalized_domain_name">IDNA * Punycode-encoded</a> versions. * * @author Craig Berry * @since 5.0 */ @Beta @GwtCompatible public final class InternetDomainName { private static final CharMatcher DOTS_MATCHER = CharMatcher.anyOf(".\u3002\uFF0E\uFF61"); private static final Splitter DOT_SPLITTER = Splitter.on('.'); private static final Joiner DOT_JOINER = Joiner.on('.'); /** * Value of {@link #publicSuffixIndex} which indicates that no public suffix * was found. */ private static final int NO_PUBLIC_SUFFIX_FOUND = -1; private static final String DOT_REGEX = "\\."; /** * Maximum parts (labels) in a domain name. This value arises from * the 255-octet limit described in * <a href="http://www.ietf.org/rfc/rfc2181.txt">RFC 2181</a> part 11 with * the fact that the encoding of each part occupies at least two bytes * (dot plus label externally, length byte plus label internally). Thus, if * all labels have the minimum size of one byte, 127 of them will fit. */ private static final int MAX_PARTS = 127; /** * Maximum length of a full domain name, including separators, and * leaving room for the root label. See * <a href="http://www.ietf.org/rfc/rfc2181.txt">RFC 2181</a> part 11. */ private static final int MAX_LENGTH = 253; /** * Maximum size of a single part of a domain name. See * <a href="http://www.ietf.org/rfc/rfc2181.txt">RFC 2181</a> part 11. */ private static final int MAX_DOMAIN_PART_LENGTH = 63; /** * The full domain name, converted to lower case. */ private final String name; /** * The parts of the domain name, converted to lower case. */ private final ImmutableList<String> parts; /** * The index in the {@link #parts()} list at which the public suffix begins. * For example, for the domain name {@code www.google.co.uk}, the value would * be 2 (the index of the {@code co} part). The value is negative * (specifically, {@link #NO_PUBLIC_SUFFIX_FOUND}) if no public suffix was * found. */ private final int publicSuffixIndex; /** * Constructor used to implement {@link #from(String)}, and from subclasses. */ InternetDomainName(String name) { // Normalize: // * ASCII characters to lowercase // * All dot-like characters to '.' // * Strip trailing '.' name = Ascii.toLowerCase(DOTS_MATCHER.replaceFrom(name, '.')); if (name.endsWith(".")) { name = name.substring(0, name.length() - 1); } checkArgument(name.length() <= MAX_LENGTH, "Domain name too long: '%s':", name); this.name = name; this.parts = ImmutableList.copyOf(DOT_SPLITTER.split(name)); checkArgument(parts.size() <= MAX_PARTS, "Domain has too many parts: '%s'", name); checkArgument(validateSyntax(parts), "Not a valid domain name: '%s'", name); this.publicSuffixIndex = findPublicSuffix(); } /** * Returns the index of the leftmost part of the public suffix, or -1 if not * found. Note that the value defined as the "public suffix" may not be a * public suffix according to {@link #isPublicSuffix()} if the domain ends * with an excluded domain pattern such as {@code "nhs.uk"}. */ private int findPublicSuffix() { final int partsSize = parts.size(); for (int i = 0; i < partsSize; i++) { String ancestorName = DOT_JOINER.join(parts.subList(i, partsSize)); if (PublicSuffixPatterns.EXACT.containsKey(ancestorName)) { return i; } // Excluded domains (e.g. !nhs.uk) use the next highest // domain as the effective public suffix (e.g. uk). if (PublicSuffixPatterns.EXCLUDED.containsKey(ancestorName)) { return i + 1; } if (matchesWildcardPublicSuffix(ancestorName)) { return i; } } return NO_PUBLIC_SUFFIX_FOUND; } /** * Returns an instance of {@link InternetDomainName} after lenient * validation. Specifically, validation against <a * href="http://www.ietf.org/rfc/rfc3490.txt">RFC 3490</a> * ("Internationalizing Domain Names in Applications") is skipped, while * validation against <a * href="http://www.ietf.org/rfc/rfc1035.txt">RFC 1035</a> is relaxed in * the following ways: * <ul> * <li>Any part containing non-ASCII characters is considered valid. * <li>Underscores ('_') are permitted wherever dashes ('-') are permitted. * <li>Parts other than the final part may start with a digit. * </ul> * * * @param domain A domain name (not IP address) * @throws IllegalArgumentException if {@code name} is not syntactically valid * according to {@link #isValid} * @since 10.0 (previously named {@code fromLenient}) */ public static InternetDomainName from(String domain) { return new InternetDomainName(checkNotNull(domain)); } /** * Validation method used by {@from} to ensure that the domain name is * syntactically valid according to RFC 1035. * * @return Is the domain name syntactically valid? */ private static boolean validateSyntax(List<String> parts) { final int lastIndex = parts.size() - 1; // Validate the last part specially, as it has different syntax rules. if (!validatePart(parts.get(lastIndex), true)) { return false; } for (int i = 0; i < lastIndex; i++) { String part = parts.get(i); if (!validatePart(part, false)) { return false; } } return true; } private static final CharMatcher DASH_MATCHER = CharMatcher.anyOf("-_"); private static final CharMatcher PART_CHAR_MATCHER = CharMatcher.JAVA_LETTER_OR_DIGIT.or(DASH_MATCHER); /** * Helper method for {@link #validateSyntax(List)}. Validates that one part of * a domain name is valid. * * @param part The domain name part to be validated * @param isFinalPart Is this the final (rightmost) domain part? * @return Whether the part is valid */ private static boolean validatePart(String part, boolean isFinalPart) { // These tests could be collapsed into one big boolean expression, but // they have been left as independent tests for clarity. if (part.length() < 1 || part.length() > MAX_DOMAIN_PART_LENGTH) { return false; } /* * GWT claims to support java.lang.Character's char-classification methods, * but it actually only works for ASCII. So for now, assume any non-ASCII * characters are valid. The only place this seems to be documented is here: * http://osdir.com/ml/GoogleWebToolkitContributors/2010-03/msg00178.html * * <p>ASCII characters in the part are expected to be valid per RFC 1035, * with underscore also being allowed due to widespread practice. */ String asciiChars = CharMatcher.ASCII.retainFrom(part); if (!PART_CHAR_MATCHER.matchesAllOf(asciiChars)) { return false; } // No initial or final dashes or underscores. if (DASH_MATCHER.matches(part.charAt(0)) || DASH_MATCHER.matches(part.charAt(part.length() - 1))) { return false; } /* * Note that we allow (in contravention of a strict interpretation of the * relevant RFCs) domain parts other than the last may begin with a digit * (for example, "3com.com"). It's important to disallow an initial digit in * the last part; it's the only thing that stops an IPv4 numeric address * like 127.0.0.1 from looking like a valid domain name. */ if (isFinalPart && CharMatcher.DIGIT.matches(part.charAt(0))) { return false; } return true; } /** * Returns the individual components of this domain name, normalized to all * lower case. For example, for the domain name {@code mail.google.com}, this * method returns the list {@code ["mail", "google", "com"]}. */ public ImmutableList<String> parts() { return parts; } /** * Indicates whether this domain name represents a <i>public suffix</i>, as * defined by the Mozilla Foundation's * <a href="http://publicsuffix.org/">Public Suffix List</a> (PSL). A public * suffix is one under which Internet users can directly register names, such * as {@code com}, {@code co.uk} or {@code pvt.k12.wy.us}. Examples of domain * names that are <i>not</i> public suffixes include {@code google}, {@code * google.com} and {@code foo.co.uk}. * * @return {@code true} if this domain name appears exactly on the public * suffix list * @since 6.0 */ public boolean isPublicSuffix() { return publicSuffixIndex == 0; } /** * Indicates whether this domain name ends in a {@linkplain #isPublicSuffix() * public suffix}, including if it is a public suffix itself. For example, * returns {@code true} for {@code www.google.com}, {@code foo.co.uk} and * {@code com}, but not for {@code google} or {@code google.foo}. This is * the recommended method for determining whether a domain is potentially an * addressable host. * * @since 6.0 */ public boolean hasPublicSuffix() { return publicSuffixIndex != NO_PUBLIC_SUFFIX_FOUND; } /** * Returns the {@linkplain #isPublicSuffix() public suffix} portion of the * domain name, or {@code null} if no public suffix is present. * * @since 6.0 */ public InternetDomainName publicSuffix() { return hasPublicSuffix() ? ancestor(publicSuffixIndex) : null; } /** * Indicates whether this domain name ends in a {@linkplain #isPublicSuffix() * public suffix}, while not being a public suffix itself. For example, * returns {@code true} for {@code www.google.com}, {@code foo.co.uk} and * {@code bar.ca.us}, but not for {@code google}, {@code com}, or {@code * google.foo}. * * <p><b>Warning:</b> a {@code false} result from this method does not imply * that the domain does not represent an addressable host, as many public * suffixes are also addressable hosts. Use {@link #hasPublicSuffix()} for * that test. * * <p>This method can be used to determine whether it will probably be * possible to set cookies on the domain, though even that depends on * individual browsers' implementations of cookie controls. See * <a href="http://www.ietf.org/rfc/rfc2109.txt">RFC 2109</a> for details. * * @since 6.0 */ public boolean isUnderPublicSuffix() { return publicSuffixIndex > 0; } /** * Indicates whether this domain name is composed of exactly one subdomain * component followed by a {@linkplain #isPublicSuffix() public suffix}. For * example, returns {@code true} for {@code google.com} and {@code foo.co.uk}, * but not for {@code www.google.com} or {@code co.uk}. * * <p><b>Warning:</b> A {@code true} result from this method does not imply * that the domain is at the highest level which is addressable as a host, as * many public suffixes are also addressable hosts. For example, the domain * {@code bar.uk.com} has a public suffix of {@code uk.com}, so it would * return {@code true} from this method. But {@code uk.com} is itself an * addressable host. * * <p>This method can be used to determine whether a domain is probably the * highest level for which cookies may be set, though even that depends on * individual browsers' implementations of cookie controls. See * <a href="http://www.ietf.org/rfc/rfc2109.txt">RFC 2109</a> for details. * * @since 6.0 */ public boolean isTopPrivateDomain() { return publicSuffixIndex == 1; } /** * Returns the portion of this domain name that is one level beneath the * public suffix. For example, for {@code x.adwords.google.co.uk} it returns * {@code google.co.uk}, since {@code co.uk} is a public suffix. * * <p>If {@link #isTopPrivateDomain()} is true, the current domain name * instance is returned. * * <p>This method should not be used to determine the topmost parent domain * which is addressable as a host, as many public suffixes are also * addressable hosts. For example, the domain {@code foo.bar.uk.com} has * a public suffix of {@code uk.com}, so it would return {@code bar.uk.com} * from this method. But {@code uk.com} is itself an addressable host. * * <p>This method can be used to determine the probable highest level parent * domain for which cookies may be set, though even that depends on individual * browsers' implementations of cookie controls. * * @throws IllegalStateException if this domain does not end with a * public suffix * @since 6.0 */ public InternetDomainName topPrivateDomain() { if (isTopPrivateDomain()) { return this; } checkState(isUnderPublicSuffix(), "Not under a public suffix: %s", name); return ancestor(publicSuffixIndex - 1); } /** * Indicates whether this domain is composed of two or more parts. */ public boolean hasParent() { return parts.size() > 1; } /** * Returns an {@code InternetDomainName} that is the immediate ancestor of * this one; that is, the current domain with the leftmost part removed. For * example, the parent of {@code www.google.com} is {@code google.com}. * * @throws IllegalStateException if the domain has no parent, as determined * by {@link #hasParent} */ public InternetDomainName parent() { checkState(hasParent(), "Domain '%s' has no parent", name); return ancestor(1); } /** * Returns the ancestor of the current domain at the given number of levels * "higher" (rightward) in the subdomain list. The number of levels must be * non-negative, and less than {@code N-1}, where {@code N} is the number of * parts in the domain. * * <p>TODO: Reasonable candidate for addition to public API. */ private InternetDomainName ancestor(int levels) { return from(DOT_JOINER.join(parts.subList(levels, parts.size()))); } /** * Creates and returns a new {@code InternetDomainName} by prepending the * argument and a dot to the current name. For example, {@code * InternetDomainName.from("foo.com").child("www.bar")} returns a new * {@code InternetDomainName} with the value {@code www.bar.foo.com}. Only * lenient validation is performed, as described {@link #from(String) here}. * * @throws NullPointerException if leftParts is null * @throws IllegalArgumentException if the resulting name is not valid */ public InternetDomainName child(String leftParts) { return from(checkNotNull(leftParts) + "." + name); } /** * Indicates whether the argument is a syntactically valid domain name using * lenient validation. Specifically, validation against <a * href="http://www.ietf.org/rfc/rfc3490.txt">RFC 3490</a> * ("Internationalizing Domain Names in Applications") is skipped. * * <p>The following two code snippets are equivalent: * * <pre> {@code * domainName = InternetDomainName.isValid(name) * ? InternetDomainName.from(name) * : DEFAULT_DOMAIN;}</pre> * * <pre> {@code * try { * domainName = InternetDomainName.from(name); * } catch (IllegalArgumentException e) { * domainName = DEFAULT_DOMAIN; * }}</pre> * * @since 8.0 (previously named {@code isValidLenient}) */ public static boolean isValid(String name) { try { from(name); return true; } catch (IllegalArgumentException e) { return false; } } /** * Does the domain name match one of the "wildcard" patterns (e.g. * {@code "*.ar"})? */ private static boolean matchesWildcardPublicSuffix(String domain) { final String[] pieces = domain.split(DOT_REGEX, 2); return pieces.length == 2 && PublicSuffixPatterns.UNDER.containsKey(pieces[1]); } /** * Returns the domain name, normalized to all lower case. */ @Override public String toString() { return name; } /** * Equality testing is based on the text supplied by the caller, * after normalization as described in the class documentation. For * example, a non-ASCII Unicode domain name and the Punycode version * of the same domain name would not be considered equal. * */ @Override public boolean equals(@Nullable Object object) { if (object == this) { return true; } if (object instanceof InternetDomainName) { InternetDomainName that = (InternetDomainName) object; return this.name.equals(that.name); } return false; } @Override public int hashCode() { return name.hashCode(); } }
zzhhhhh-aw4rwer
guava/src/com/google/common/net/InternetDomainName.java
Java
asf20
19,732
/* * Copyright (C) 2009 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.net; import com.google.common.annotations.Beta; import com.google.common.annotations.GwtCompatible; import com.google.common.escape.Escaper; /** * {@code Escaper} instances suitable for strings to be included in particular * sections of URLs. * * <p>If the resulting URLs are inserted into an HTML or XML document, they will * require additional escaping with {@link com.google.common.html.HtmlEscapers} * or {@link com.google.common.xml.XmlEscapers}. * * * @author David Beaumont * @author Chris Povirk * @since 15.0 */ @Beta @GwtCompatible public final class UrlEscapers { private UrlEscapers() {} // For each xxxEscaper() method, please add links to external reference pages // that are considered authoritative for the behavior of that escaper. static final String URL_FORM_PARAMETER_OTHER_SAFE_CHARS = "-_.*"; static final String URL_PATH_OTHER_SAFE_CHARS_LACKING_PLUS = "-._~" + // Unreserved characters. "!$'()*,;&=" + // The subdelim characters (excluding '+'). "@:"; // The gendelim characters permitted in paths. /** * Returns an {@link Escaper} instance that escapes strings so they can be * safely included in <a href="http://goo.gl/OQEc8">URL form parameter names * and values</a>. Escaping is performed with the UTF-8 character encoding. * The caller is responsible for <a href="http://goo.gl/i20ms">replacing any * unpaired carriage return or line feed characters with a CR+LF pair</a> on * any non-file inputs before escaping them with this escaper. * * <p>When escaping a String, the following rules apply: * <ul> * <li>The alphanumeric characters "a" through "z", "A" through "Z" and "0" * through "9" remain the same. * <li>The special characters ".", "-", "*", and "_" remain the same. * <li>The space character " " is converted into a plus sign "+". * <li>All other characters are converted into one or more bytes using UTF-8 * encoding and each byte is then represented by the 3-character string * "%XY", where "XY" is the two-digit, uppercase, hexadecimal * representation of the byte value. * </ul> * * <p>This escaper is suitable for escaping parameter names and values even * when <a href="http://goo.gl/utn6M">using the non-standard semicolon</a>, * rather than the ampersand, as a parameter delimiter. Nevertheless, we * recommend using the ampersand unless you must interoperate with systems * that require semicolons. * * <p><b>Note</b>: Unlike other escapers, URL escapers produce uppercase * hexadecimal sequences. From <a href="http://www.ietf.org/rfc/rfc3986.txt"> * RFC 3986</a>:<br> * <i>"URI producers and normalizers should use uppercase hexadecimal digits * for all percent-encodings."</i> * */ public static Escaper urlFormParameterEscaper() { return URL_FORM_PARAMETER_ESCAPER; } private static final Escaper URL_FORM_PARAMETER_ESCAPER = new PercentEscaper(URL_FORM_PARAMETER_OTHER_SAFE_CHARS, true); /** * Returns an {@link Escaper} instance that escapes strings so they can be * safely included in <a href="http://goo.gl/swjbR">URL path segments</a>. The * returned escaper escapes all non-ASCII characters, even though <a * href="http://goo.gl/xIJWe">many of these are accepted in modern URLs</a>. * (<a href="http://goo.gl/WMGvZ">If the escaper were to leave these * characters unescaped, they would be escaped by the consumer at parse time, * anyway.</a>) Additionally, the escaper escapes the slash character ("/"). * While slashes are acceptable in URL paths, they are considered by the * specification to be separators between "path segments." This implies that, * if you wish for your path to contain slashes, you must escape each segment * separately and then join them. * * <p>When escaping a String, the following rules apply: * <ul> * <li>The alphanumeric characters "a" through "z", "A" through "Z" and "0" * through "9" remain the same. * <li>The unreserved characters ".", "-", "~", and "_" remain the same. * <li>The general delimiters "@" and ":" remain the same. * <li>The subdelimiters "!", "$", "&amp;", "'", "(", ")", "*", "+", ",", ";", * and "=" remain the same. * <li>The space character " " is converted into %20. * <li>All other characters are converted into one or more bytes using UTF-8 * encoding and each byte is then represented by the 3-character string * "%XY", where "XY" is the two-digit, uppercase, hexadecimal * representation of the byte value. * </ul> * * <p><b>Note</b>: Unlike other escapers, URL escapers produce uppercase * hexadecimal sequences. From <a href="http://www.ietf.org/rfc/rfc3986.txt"> * RFC 3986</a>:<br> * <i>"URI producers and normalizers should use uppercase hexadecimal digits * for all percent-encodings."</i> */ public static Escaper urlPathSegmentEscaper() { return URL_PATH_SEGMENT_ESCAPER; } private static final Escaper URL_PATH_SEGMENT_ESCAPER = new PercentEscaper(URL_PATH_OTHER_SAFE_CHARS_LACKING_PLUS + "+", false); /** * Returns an {@link Escaper} instance that escapes strings so they can be * safely included in a <a href="http://goo.gl/xXEq4p">URL fragment</a>. The * returned escaper escapes all non-ASCII characters, even though <a * href="http://goo.gl/xIJWe">many of these are accepted in modern URLs</a>. * (<a href="http://goo.gl/WMGvZ">If the escaper were to leave these * characters unescaped, they would be escaped by the consumer at parse time, * anyway.</a>) * * <p>When escaping a String, the following rules apply: * <ul> * <li>The alphanumeric characters "a" through "z", "A" through "Z" and "0" * through "9" remain the same. * <li>The unreserved characters ".", "-", "~", and "_" remain the same. * <li>The general delimiters "@" and ":" remain the same. * <li>The subdelimiters "!", "$", "&amp;", "'", "(", ")", "*", "+", ",", ";", * and "=" remain the same. * <li>The space character " " is converted into %20. * <li>Fragments allow unescaped "/" and "?", so they remain the same. * <li>All other characters are converted into one or more bytes using UTF-8 * encoding and each byte is then represented by the 3-character string * "%XY", where "XY" is the two-digit, uppercase, hexadecimal * representation of the byte value. * </ul> * * <p><b>Note</b>: Unlike other escapers, URL escapers produce uppercase * hexadecimal sequences. From <a href="http://www.ietf.org/rfc/rfc3986.txt"> * RFC 3986</a>:<br> * <i>"URI producers and normalizers should use uppercase hexadecimal digits * for all percent-encodings."</i> */ public static Escaper urlFragmentEscaper() { return URL_FRAGMENT_ESCAPER; } private static final Escaper URL_FRAGMENT_ESCAPER = new PercentEscaper(URL_PATH_OTHER_SAFE_CHARS_LACKING_PLUS + "+/?", false); }
zzhhhhh-aw4rwer
guava/src/com/google/common/net/UrlEscapers.java
Java
asf20
7,649
/* * Copyright (C) 2011 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.net; import static com.google.common.base.CharMatcher.ASCII; import static com.google.common.base.CharMatcher.JAVA_ISO_CONTROL; import static com.google.common.base.Charsets.UTF_8; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Preconditions.checkState; import com.google.common.annotations.Beta; import com.google.common.annotations.GwtCompatible; import com.google.common.base.Ascii; import com.google.common.base.CharMatcher; import com.google.common.base.Function; import com.google.common.base.Joiner; import com.google.common.base.Joiner.MapJoiner; import com.google.common.base.Objects; import com.google.common.base.Optional; import com.google.common.collect.ImmutableListMultimap; import com.google.common.collect.ImmutableMultiset; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Iterables; import com.google.common.collect.Maps; import com.google.common.collect.Multimap; import com.google.common.collect.Multimaps; import java.nio.charset.Charset; import java.nio.charset.IllegalCharsetNameException; import java.nio.charset.UnsupportedCharsetException; import java.util.Collection; import java.util.Map; import java.util.Map.Entry; import javax.annotation.Nullable; import javax.annotation.concurrent.Immutable; /** * Represents an <a href="http://en.wikipedia.org/wiki/Internet_media_type">Internet Media Type</a> * (also known as a MIME Type or Content Type). This class also supports the concept of media ranges * <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.1">defined by HTTP/1.1</a>. * As such, the {@code *} character is treated as a wildcard and is used to represent any acceptable * type or subtype value. A media type may not have wildcard type with a declared subtype. The * {@code *} character has no special meaning as part of a parameter. All values for type, subtype, * parameter attributes or parameter values must be valid according to RFCs * <a href="http://www.ietf.org/rfc/rfc2045.txt">2045</a> and * <a href="http://www.ietf.org/rfc/rfc2046.txt">2046</a>. * * <p>All portions of the media type that are case-insensitive (type, subtype, parameter attributes) * are normalized to lowercase. The value of the {@code charset} parameter is normalized to * lowercase, but all others are left as-is. * * <p>Note that this specifically does <strong>not</strong> represent the value of the MIME * {@code Content-Type} header and as such has no support for header-specific considerations such as * line folding and comments. * * <p>For media types that take a charset the predefined constants default to UTF-8 and have a * "_UTF_8" suffix. To get a version without a character set, use {@link #withoutParameters}. * * @since 12.0 * * @author Gregory Kick */ @Beta @GwtCompatible @Immutable public final class MediaType { private static final String CHARSET_ATTRIBUTE = "charset"; private static final ImmutableListMultimap<String, String> UTF_8_CONSTANT_PARAMETERS = ImmutableListMultimap.of(CHARSET_ATTRIBUTE, Ascii.toLowerCase(UTF_8.name())); /** Matcher for type, subtype and attributes. */ private static final CharMatcher TOKEN_MATCHER = ASCII.and(JAVA_ISO_CONTROL.negate()) .and(CharMatcher.isNot(' ')) .and(CharMatcher.noneOf("()<>@,;:\\\"/[]?=")); private static final CharMatcher QUOTED_TEXT_MATCHER = ASCII .and(CharMatcher.noneOf("\"\\\r")); /* * This matches the same characters as linear-white-space from RFC 822, but we make no effort to * enforce any particular rules with regards to line folding as stated in the class docs. */ private static final CharMatcher LINEAR_WHITE_SPACE = CharMatcher.anyOf(" \t\r\n"); // TODO(gak): make these public? private static final String APPLICATION_TYPE = "application"; private static final String AUDIO_TYPE = "audio"; private static final String IMAGE_TYPE = "image"; private static final String TEXT_TYPE = "text"; private static final String VIDEO_TYPE = "video"; private static final String WILDCARD = "*"; private static final Map<MediaType, MediaType> KNOWN_TYPES = Maps.newHashMap(); private static MediaType createConstant(String type, String subtype) { return addKnownType(new MediaType(type, subtype, ImmutableListMultimap.<String, String>of())); } private static MediaType createConstantUtf8(String type, String subtype) { return addKnownType(new MediaType(type, subtype, UTF_8_CONSTANT_PARAMETERS)); } private static MediaType addKnownType(MediaType mediaType) { KNOWN_TYPES.put(mediaType, mediaType); return mediaType; } /* * The following constants are grouped by their type and ordered alphabetically by the constant * name within that type. The constant name should be a sensible identifier that is closest to the * "common name" of the media. This is often, but not necessarily the same as the subtype. * * Be sure to declare all constants with the type and subtype in all lowercase. For types that * take a charset (e.g. all text/* types), default to UTF-8 and suffix the constant name with * "_UTF_8". */ public static final MediaType ANY_TYPE = createConstant(WILDCARD, WILDCARD); public static final MediaType ANY_TEXT_TYPE = createConstant(TEXT_TYPE, WILDCARD); public static final MediaType ANY_IMAGE_TYPE = createConstant(IMAGE_TYPE, WILDCARD); public static final MediaType ANY_AUDIO_TYPE = createConstant(AUDIO_TYPE, WILDCARD); public static final MediaType ANY_VIDEO_TYPE = createConstant(VIDEO_TYPE, WILDCARD); public static final MediaType ANY_APPLICATION_TYPE = createConstant(APPLICATION_TYPE, WILDCARD); /* text types */ public static final MediaType CACHE_MANIFEST_UTF_8 = createConstantUtf8(TEXT_TYPE, "cache-manifest"); public static final MediaType CSS_UTF_8 = createConstantUtf8(TEXT_TYPE, "css"); public static final MediaType CSV_UTF_8 = createConstantUtf8(TEXT_TYPE, "csv"); public static final MediaType HTML_UTF_8 = createConstantUtf8(TEXT_TYPE, "html"); public static final MediaType I_CALENDAR_UTF_8 = createConstantUtf8(TEXT_TYPE, "calendar"); public static final MediaType PLAIN_TEXT_UTF_8 = createConstantUtf8(TEXT_TYPE, "plain"); /** * <a href="http://www.rfc-editor.org/rfc/rfc4329.txt">RFC 4329</a> declares * {@link #JAVASCRIPT_UTF_8 application/javascript} to be the correct media type for JavaScript, * but this may be necessary in certain situations for compatibility. */ public static final MediaType TEXT_JAVASCRIPT_UTF_8 = createConstantUtf8(TEXT_TYPE, "javascript"); /** * <a href="http://www.iana.org/assignments/media-types/text/tab-separated-values"> * Tab separated values</a>. * * @since 15.0 */ public static final MediaType TSV_UTF_8 = createConstantUtf8(TEXT_TYPE, "tab-separated-values"); public static final MediaType VCARD_UTF_8 = createConstantUtf8(TEXT_TYPE, "vcard"); public static final MediaType WML_UTF_8 = createConstantUtf8(TEXT_TYPE, "vnd.wap.wml"); /** * As described in <a href="http://www.ietf.org/rfc/rfc3023.txt">RFC 3023</a>, this constant * ({@code text/xml}) is used for XML documents that are "readable by casual users." * {@link #APPLICATION_XML_UTF_8} is provided for documents that are intended for applications. */ public static final MediaType XML_UTF_8 = createConstantUtf8(TEXT_TYPE, "xml"); /* image types */ public static final MediaType BMP = createConstant(IMAGE_TYPE, "bmp"); /** * The media type for the <a href="http://en.wikipedia.org/wiki/Camera_Image_File_Format">Canon * Image File Format</a> ({@code crw} files), a widely-used "raw image" format for cameras. It is * found in {@code /etc/mime.types}, e.g. in <href= * "http://anonscm.debian.org/gitweb/?p=collab-maint/mime-support.git;a=blob;f=mime.types;hb=HEAD" * >Debian 3.48-1</a>. * * @since 15.0 */ public static final MediaType CRW = createConstant(IMAGE_TYPE, "x-canon-crw"); public static final MediaType GIF = createConstant(IMAGE_TYPE, "gif"); public static final MediaType ICO = createConstant(IMAGE_TYPE, "vnd.microsoft.icon"); public static final MediaType JPEG = createConstant(IMAGE_TYPE, "jpeg"); public static final MediaType PNG = createConstant(IMAGE_TYPE, "png"); /** * The media type for the Photoshop File Format ({@code psd} files) as defined by <a href= * "http://www.iana.org/assignments/media-types/image/vnd.adobe.photoshop">IANA</a>, and found in * {@code /etc/mime.types}, e.g. <a href= * "http://svn.apache.org/repos/asf/httpd/httpd/branches/1.3.x/conf/mime.types"></a> of the Apache * <a href="http://httpd.apache.org/">HTTPD project</a>; for the specification, see * <href="http://www.adobe.com/devnet-apps/photoshop/fileformatashtml/PhotoshopFileFormats.htm"> * Adobe Photoshop Document Format</a> and <a href= * "http://en.wikipedia.org/wiki/Adobe_Photoshop#File_format">Wikipedia</a>; this is the regular * output/input of Photoshop (which can also export to various image formats; note that files with * extension "PSB" are in a distinct but related format). * <p>This is a more recent replacement for the older, experimental type * {@code x-photoshop}: <a href="http://tools.ietf.org/html/rfc2046#section-6">RFC-2046.6</a>. * * @since 15.0 */ public static final MediaType PSD = createConstant(IMAGE_TYPE, "vnd.adobe.photoshop"); public static final MediaType SVG_UTF_8 = createConstantUtf8(IMAGE_TYPE, "svg+xml"); public static final MediaType TIFF = createConstant(IMAGE_TYPE, "tiff"); public static final MediaType WEBP = createConstant(IMAGE_TYPE, "webp"); /* audio types */ public static final MediaType MP4_AUDIO = createConstant(AUDIO_TYPE, "mp4"); public static final MediaType MPEG_AUDIO = createConstant(AUDIO_TYPE, "mpeg"); public static final MediaType OGG_AUDIO = createConstant(AUDIO_TYPE, "ogg"); public static final MediaType WEBM_AUDIO = createConstant(AUDIO_TYPE, "webm"); /* video types */ public static final MediaType MP4_VIDEO = createConstant(VIDEO_TYPE, "mp4"); public static final MediaType MPEG_VIDEO = createConstant(VIDEO_TYPE, "mpeg"); public static final MediaType OGG_VIDEO = createConstant(VIDEO_TYPE, "ogg"); public static final MediaType QUICKTIME = createConstant(VIDEO_TYPE, "quicktime"); public static final MediaType WEBM_VIDEO = createConstant(VIDEO_TYPE, "webm"); public static final MediaType WMV = createConstant(VIDEO_TYPE, "x-ms-wmv"); /* application types */ /** * As described in <a href="http://www.ietf.org/rfc/rfc3023.txt">RFC 3023</a>, this constant * ({@code application/xml}) is used for XML documents that are "unreadable by casual users." * {@link #XML_UTF_8} is provided for documents that may be read by users. */ public static final MediaType APPLICATION_XML_UTF_8 = createConstantUtf8(APPLICATION_TYPE, "xml"); public static final MediaType ATOM_UTF_8 = createConstantUtf8(APPLICATION_TYPE, "atom+xml"); public static final MediaType BZIP2 = createConstant(APPLICATION_TYPE, "x-bzip2"); /** * Media type for <a href="http://en.wikipedia.org/wiki/Embedded_OpenType">Embedded OpenType</a> * fonts. This is * <a href="http://www.iana.org/assignments/media-types/application/vnd.ms-fontobject">registered * </a> with the IANA. * * @since 17.0 */ public static final MediaType EOT = createConstant(APPLICATION_TYPE, "vnd.ms-fontobject"); /** * As described in the <a href="http://idpf.org/epub">International Digital Publishing Forum</a> * EPUB is the distribution and interchange format standard for digital publications and * documents. This media type is defined in the * <a href="http://www.idpf.org/epub/30/spec/epub30-ocf.html">EPUB Open Container Format</a> * specification. * * @since 15.0 */ public static final MediaType EPUB = createConstant(APPLICATION_TYPE, "epub+zip"); public static final MediaType FORM_DATA = createConstant(APPLICATION_TYPE, "x-www-form-urlencoded"); /** * As described in <a href="https://www.rsa.com/rsalabs/node.asp?id=2138">PKCS #12: Personal * Information Exchange Syntax Standard</a>, PKCS #12 defines an archive file format for storing * many cryptography objects as a single file. * * @since 15.0 */ public static final MediaType KEY_ARCHIVE = createConstant(APPLICATION_TYPE, "pkcs12"); /** * This is a non-standard media type, but is commonly used in serving hosted binary files as it is * <a href="http://code.google.com/p/browsersec/wiki/Part2#Survey_of_content_sniffing_behaviors"> * known not to trigger content sniffing in current browsers</a>. It <i>should not</i> be used in * other situations as it is not specified by any RFC and does not appear in the <a href= * "http://www.iana.org/assignments/media-types">/IANA MIME Media Types</a> list. Consider * {@link #OCTET_STREAM} for binary data that is not being served to a browser. * * * @since 14.0 */ public static final MediaType APPLICATION_BINARY = createConstant(APPLICATION_TYPE, "binary"); public static final MediaType GZIP = createConstant(APPLICATION_TYPE, "x-gzip"); /** * <a href="http://www.rfc-editor.org/rfc/rfc4329.txt">RFC 4329</a> declares this to be the * correct media type for JavaScript, but {@link #TEXT_JAVASCRIPT_UTF_8 text/javascript} may be * necessary in certain situations for compatibility. */ public static final MediaType JAVASCRIPT_UTF_8 = createConstantUtf8(APPLICATION_TYPE, "javascript"); public static final MediaType JSON_UTF_8 = createConstantUtf8(APPLICATION_TYPE, "json"); public static final MediaType KML = createConstant(APPLICATION_TYPE, "vnd.google-earth.kml+xml"); public static final MediaType KMZ = createConstant(APPLICATION_TYPE, "vnd.google-earth.kmz"); public static final MediaType MBOX = createConstant(APPLICATION_TYPE, "mbox"); public static final MediaType MICROSOFT_EXCEL = createConstant(APPLICATION_TYPE, "vnd.ms-excel"); public static final MediaType MICROSOFT_POWERPOINT = createConstant(APPLICATION_TYPE, "vnd.ms-powerpoint"); public static final MediaType MICROSOFT_WORD = createConstant(APPLICATION_TYPE, "msword"); public static final MediaType OCTET_STREAM = createConstant(APPLICATION_TYPE, "octet-stream"); public static final MediaType OGG_CONTAINER = createConstant(APPLICATION_TYPE, "ogg"); public static final MediaType OOXML_DOCUMENT = createConstant(APPLICATION_TYPE, "vnd.openxmlformats-officedocument.wordprocessingml.document"); public static final MediaType OOXML_PRESENTATION = createConstant(APPLICATION_TYPE, "vnd.openxmlformats-officedocument.presentationml.presentation"); public static final MediaType OOXML_SHEET = createConstant(APPLICATION_TYPE, "vnd.openxmlformats-officedocument.spreadsheetml.sheet"); public static final MediaType OPENDOCUMENT_GRAPHICS = createConstant(APPLICATION_TYPE, "vnd.oasis.opendocument.graphics"); public static final MediaType OPENDOCUMENT_PRESENTATION = createConstant(APPLICATION_TYPE, "vnd.oasis.opendocument.presentation"); public static final MediaType OPENDOCUMENT_SPREADSHEET = createConstant(APPLICATION_TYPE, "vnd.oasis.opendocument.spreadsheet"); public static final MediaType OPENDOCUMENT_TEXT = createConstant(APPLICATION_TYPE, "vnd.oasis.opendocument.text"); public static final MediaType PDF = createConstant(APPLICATION_TYPE, "pdf"); public static final MediaType POSTSCRIPT = createConstant(APPLICATION_TYPE, "postscript"); /** * <a href="http://tools.ietf.org/html/draft-rfernando-protocol-buffers-00">Protocol buffers</a> * * @since 15.0 */ public static final MediaType PROTOBUF = createConstant(APPLICATION_TYPE, "protobuf"); public static final MediaType RDF_XML_UTF_8 = createConstantUtf8(APPLICATION_TYPE, "rdf+xml"); public static final MediaType RTF_UTF_8 = createConstantUtf8(APPLICATION_TYPE, "rtf"); /** * Media type for SFNT fonts (which includes * <a href="http://en.wikipedia.org/wiki/TrueType/">TrueType</a> and * <a href="http://en.wikipedia.org/wiki/OpenType/">OpenType</a> fonts). This is * <a href="http://www.iana.org/assignments/media-types/application/font-sfnt">registered</a> * with the IANA. * * @since 17.0 */ public static final MediaType SFNT = createConstant(APPLICATION_TYPE, "font-sfnt"); public static final MediaType SHOCKWAVE_FLASH = createConstant(APPLICATION_TYPE, "x-shockwave-flash"); public static final MediaType SKETCHUP = createConstant(APPLICATION_TYPE, "vnd.sketchup.skp"); public static final MediaType TAR = createConstant(APPLICATION_TYPE, "x-tar"); /** * Media type for the * <a href="http://en.wikipedia.org/wiki/Web_Open_Font_Format">Web Open Font Format</a> (WOFF) * <a href="http://www.w3.org/TR/WOFF/">defined</a> by the W3C. This is * <a href="http://www.iana.org/assignments/media-types/application/font-woff">registered</a> * with the IANA. * * @since 17.0 */ public static final MediaType WOFF = createConstant(APPLICATION_TYPE, "font-woff"); public static final MediaType XHTML_UTF_8 = createConstantUtf8(APPLICATION_TYPE, "xhtml+xml"); /** * Media type for Extensible Resource Descriptors. This is not yet registered with the IANA, but * it is specified by OASIS in the * <a href="http://docs.oasis-open.org/xri/xrd/v1.0/cd02/xrd-1.0-cd02.html"> XRD definition</a> * and implemented in projects such as * <a href="http://code.google.com/p/webfinger/">WebFinger</a>. */ public static final MediaType XRD_UTF_8 = createConstantUtf8(APPLICATION_TYPE, "xrd+xml"); public static final MediaType ZIP = createConstant(APPLICATION_TYPE, "zip"); private final String type; private final String subtype; private final ImmutableListMultimap<String, String> parameters; private MediaType(String type, String subtype, ImmutableListMultimap<String, String> parameters) { this.type = type; this.subtype = subtype; this.parameters = parameters; } /** Returns the top-level media type. For example, {@code "text"} in {@code "text/plain"}. */ public String type() { return type; } /** Returns the media subtype. For example, {@code "plain"} in {@code "text/plain"}. */ public String subtype() { return subtype; } /** Returns a multimap containing the parameters of this media type. */ public ImmutableListMultimap<String, String> parameters() { return parameters; } private Map<String, ImmutableMultiset<String>> parametersAsMap() { return Maps.transformValues(parameters.asMap(), new Function<Collection<String>, ImmutableMultiset<String>>() { @Override public ImmutableMultiset<String> apply(Collection<String> input) { return ImmutableMultiset.copyOf(input); } }); } /** * Returns an optional charset for the value of the charset parameter if it is specified. * * @throws IllegalStateException if multiple charset values have been set for this media type * @throws IllegalCharsetNameException if a charset value is present, but illegal * @throws UnsupportedCharsetException if a charset value is present, but no support is available * in this instance of the Java virtual machine */ public Optional<Charset> charset() { ImmutableSet<String> charsetValues = ImmutableSet.copyOf(parameters.get(CHARSET_ATTRIBUTE)); switch (charsetValues.size()) { case 0: return Optional.absent(); case 1: return Optional.of(Charset.forName(Iterables.getOnlyElement(charsetValues))); default: throw new IllegalStateException("Multiple charset values defined: " + charsetValues); } } /** * Returns a new instance with the same type and subtype as this instance, but without any * parameters. */ public MediaType withoutParameters() { return parameters.isEmpty() ? this : create(type, subtype); } /** * <em>Replaces</em> all parameters with the given parameters. * * @throws IllegalArgumentException if any parameter or value is invalid */ public MediaType withParameters(Multimap<String, String> parameters) { return create(type, subtype, parameters); } /** * <em>Replaces</em> all parameters with the given attribute with a single parameter with the * given value. If multiple parameters with the same attributes are necessary use * {@link #withParameters}. Prefer {@link #withCharset} for setting the {@code charset} parameter * when using a {@link Charset} object. * * @throws IllegalArgumentException if either {@code attribute} or {@code value} is invalid */ public MediaType withParameter(String attribute, String value) { checkNotNull(attribute); checkNotNull(value); String normalizedAttribute = normalizeToken(attribute); ImmutableListMultimap.Builder<String, String> builder = ImmutableListMultimap.builder(); for (Entry<String, String> entry : parameters.entries()) { String key = entry.getKey(); if (!normalizedAttribute.equals(key)) { builder.put(key, entry.getValue()); } } builder.put(normalizedAttribute, normalizeParameterValue(normalizedAttribute, value)); MediaType mediaType = new MediaType(type, subtype, builder.build()); // Return one of the constants if the media type is a known type. return Objects.firstNonNull(KNOWN_TYPES.get(mediaType), mediaType); } /** * Returns a new instance with the same type and subtype as this instance, with the * {@code charset} parameter set to the {@link Charset#name name} of the given charset. Only one * {@code charset} parameter will be present on the new instance regardless of the number set on * this one. * * <p>If a charset must be specified that is not supported on this JVM (and thus is not * representable as a {@link Charset} instance, use {@link #withParameter}. */ public MediaType withCharset(Charset charset) { checkNotNull(charset); return withParameter(CHARSET_ATTRIBUTE, charset.name()); } /** Returns true if either the type or subtype is the wildcard. */ public boolean hasWildcard() { return WILDCARD.equals(type) || WILDCARD.equals(subtype); } /** * Returns {@code true} if this instance falls within the range (as defined by * <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html">the HTTP Accept header</a>) * given by the argument according to three criteria: * * <ol> * <li>The type of the argument is the wildcard or equal to the type of this instance. * <li>The subtype of the argument is the wildcard or equal to the subtype of this instance. * <li>All of the parameters present in the argument are present in this instance. * </ol> * * <p>For example: <pre> {@code * PLAIN_TEXT_UTF_8.is(PLAIN_TEXT_UTF_8) // true * PLAIN_TEXT_UTF_8.is(HTML_UTF_8) // false * PLAIN_TEXT_UTF_8.is(ANY_TYPE) // true * PLAIN_TEXT_UTF_8.is(ANY_TEXT_TYPE) // true * PLAIN_TEXT_UTF_8.is(ANY_IMAGE_TYPE) // false * PLAIN_TEXT_UTF_8.is(ANY_TEXT_TYPE.withCharset(UTF_8)) // true * PLAIN_TEXT_UTF_8.withoutParameters().is(ANY_TEXT_TYPE.withCharset(UTF_8)) // false * PLAIN_TEXT_UTF_8.is(ANY_TEXT_TYPE.withCharset(UTF_16)) // false}</pre> * * <p>Note that while it is possible to have the same parameter declared multiple times within a * media type this method does not consider the number of occurrences of a parameter. For * example, {@code "text/plain; charset=UTF-8"} satisfies * {@code "text/plain; charset=UTF-8; charset=UTF-8"}. */ public boolean is(MediaType mediaTypeRange) { return (mediaTypeRange.type.equals(WILDCARD) || mediaTypeRange.type.equals(this.type)) && (mediaTypeRange.subtype.equals(WILDCARD) || mediaTypeRange.subtype.equals(this.subtype)) && this.parameters.entries().containsAll(mediaTypeRange.parameters.entries()); } /** * Creates a new media type with the given type and subtype. * * @throws IllegalArgumentException if type or subtype is invalid or if a wildcard is used for the * type, but not the subtype. */ public static MediaType create(String type, String subtype) { return create(type, subtype, ImmutableListMultimap.<String, String>of()); } /** * Creates a media type with the "application" type and the given subtype. * * @throws IllegalArgumentException if subtype is invalid */ static MediaType createApplicationType(String subtype) { return create(APPLICATION_TYPE, subtype); } /** * Creates a media type with the "audio" type and the given subtype. * * @throws IllegalArgumentException if subtype is invalid */ static MediaType createAudioType(String subtype) { return create(AUDIO_TYPE, subtype); } /** * Creates a media type with the "image" type and the given subtype. * * @throws IllegalArgumentException if subtype is invalid */ static MediaType createImageType(String subtype) { return create(IMAGE_TYPE, subtype); } /** * Creates a media type with the "text" type and the given subtype. * * @throws IllegalArgumentException if subtype is invalid */ static MediaType createTextType(String subtype) { return create(TEXT_TYPE, subtype); } /** * Creates a media type with the "video" type and the given subtype. * * @throws IllegalArgumentException if subtype is invalid */ static MediaType createVideoType(String subtype) { return create(VIDEO_TYPE, subtype); } private static MediaType create(String type, String subtype, Multimap<String, String> parameters) { checkNotNull(type); checkNotNull(subtype); checkNotNull(parameters); String normalizedType = normalizeToken(type); String normalizedSubtype = normalizeToken(subtype); checkArgument(!WILDCARD.equals(normalizedType) || WILDCARD.equals(normalizedSubtype), "A wildcard type cannot be used with a non-wildcard subtype"); ImmutableListMultimap.Builder<String, String> builder = ImmutableListMultimap.builder(); for (Entry<String, String> entry : parameters.entries()) { String attribute = normalizeToken(entry.getKey()); builder.put(attribute, normalizeParameterValue(attribute, entry.getValue())); } MediaType mediaType = new MediaType(normalizedType, normalizedSubtype, builder.build()); // Return one of the constants if the media type is a known type. return Objects.firstNonNull(KNOWN_TYPES.get(mediaType), mediaType); } private static String normalizeToken(String token) { checkArgument(TOKEN_MATCHER.matchesAllOf(token)); return Ascii.toLowerCase(token); } private static String normalizeParameterValue(String attribute, String value) { return CHARSET_ATTRIBUTE.equals(attribute) ? Ascii.toLowerCase(value) : value; } /** * Parses a media type from its string representation. * * @throws IllegalArgumentException if the input is not parsable */ public static MediaType parse(String input) { checkNotNull(input); Tokenizer tokenizer = new Tokenizer(input); try { String type = tokenizer.consumeToken(TOKEN_MATCHER); tokenizer.consumeCharacter('/'); String subtype = tokenizer.consumeToken(TOKEN_MATCHER); ImmutableListMultimap.Builder<String, String> parameters = ImmutableListMultimap.builder(); while (tokenizer.hasMore()) { tokenizer.consumeCharacter(';'); tokenizer.consumeTokenIfPresent(LINEAR_WHITE_SPACE); String attribute = tokenizer.consumeToken(TOKEN_MATCHER); tokenizer.consumeCharacter('='); final String value; if ('"' == tokenizer.previewChar()) { tokenizer.consumeCharacter('"'); StringBuilder valueBuilder = new StringBuilder(); while ('"' != tokenizer.previewChar()) { if ('\\' == tokenizer.previewChar()) { tokenizer.consumeCharacter('\\'); valueBuilder.append(tokenizer.consumeCharacter(ASCII)); } else { valueBuilder.append(tokenizer.consumeToken(QUOTED_TEXT_MATCHER)); } } value = valueBuilder.toString(); tokenizer.consumeCharacter('"'); } else { value = tokenizer.consumeToken(TOKEN_MATCHER); } parameters.put(attribute, value); } return create(type, subtype, parameters.build()); } catch (IllegalStateException e) { throw new IllegalArgumentException("Could not parse '" + input + "'", e); } } private static final class Tokenizer { final String input; int position = 0; Tokenizer(String input) { this.input = input; } String consumeTokenIfPresent(CharMatcher matcher) { checkState(hasMore()); int startPosition = position; position = matcher.negate().indexIn(input, startPosition); return hasMore() ? input.substring(startPosition, position) : input.substring(startPosition); } String consumeToken(CharMatcher matcher) { int startPosition = position; String token = consumeTokenIfPresent(matcher); checkState(position != startPosition); return token; } char consumeCharacter(CharMatcher matcher) { checkState(hasMore()); char c = previewChar(); checkState(matcher.matches(c)); position++; return c; } char consumeCharacter(char c) { checkState(hasMore()); checkState(previewChar() == c); position++; return c; } char previewChar() { checkState(hasMore()); return input.charAt(position); } boolean hasMore() { return (position >= 0) && (position < input.length()); } } @Override public boolean equals(@Nullable Object obj) { if (obj == this) { return true; } else if (obj instanceof MediaType) { MediaType that = (MediaType) obj; return this.type.equals(that.type) && this.subtype.equals(that.subtype) // compare parameters regardless of order && this.parametersAsMap().equals(that.parametersAsMap()); } else { return false; } } @Override public int hashCode() { return Objects.hashCode(type, subtype, parametersAsMap()); } private static final MapJoiner PARAMETER_JOINER = Joiner.on("; ").withKeyValueSeparator("="); /** * Returns the string representation of this media type in the format described in <a * href="http://www.ietf.org/rfc/rfc2045.txt">RFC 2045</a>. */ @Override public String toString() { StringBuilder builder = new StringBuilder().append(type).append('/').append(subtype); if (!parameters.isEmpty()) { builder.append("; "); Multimap<String, String> quotedParameters = Multimaps.transformValues(parameters, new Function<String, String>() { @Override public String apply(String value) { return TOKEN_MATCHER.matchesAllOf(value) ? value : escapeAndQuote(value); } }); PARAMETER_JOINER.appendTo(builder, quotedParameters.entries()); } return builder.toString(); } private static String escapeAndQuote(String value) { StringBuilder escaped = new StringBuilder(value.length() + 16).append('"'); for (char ch : value.toCharArray()) { if (ch == '\r' || ch == '\\' || ch == '"') { escaped.append('\\'); } escaped.append(ch); } return escaped.append('"').toString(); } }
zzhhhhh-aw4rwer
guava/src/com/google/common/net/MediaType.java
Java
asf20
32,324
/* * Copyright (C) 2010 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * This package contains utility methods and classes for working with net * addresses (numeric IP and domain names). * * <p>This package is a part of the open-source * <a href="http://guava-libraries.googlecode.com">Guava libraries</a>. * * @author Craig Berry */ @ParametersAreNonnullByDefault package com.google.common.net; import javax.annotation.ParametersAreNonnullByDefault;
zzhhhhh-aw4rwer
guava/src/com/google/common/net/package-info.java
Java
asf20
996
/* * Copyright (C) 2011 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.net; import com.google.common.annotations.Beta; import com.google.common.annotations.GwtCompatible; /** * Contains constant definitions for the HTTP header field names. See: * <ul> * <li><a href="http://www.ietf.org/rfc/rfc2109.txt">RFC 2109</a> * <li><a href="http://www.ietf.org/rfc/rfc2183.txt">RFC 2183</a> * <li><a href="http://www.ietf.org/rfc/rfc2616.txt">RFC 2616</a> * <li><a href="http://www.ietf.org/rfc/rfc2965.txt">RFC 2965</a> * <li><a href="http://www.ietf.org/rfc/rfc5988.txt">RFC 5988</a> * </ul> * * * @author Kurt Alfred Kluever * @since 11.0 */ @GwtCompatible public final class HttpHeaders { private HttpHeaders() {} // HTTP Request and Response header fields /** The HTTP {@code Cache-Control} header field name. */ public static final String CACHE_CONTROL = "Cache-Control"; /** The HTTP {@code Content-Length} header field name. */ public static final String CONTENT_LENGTH = "Content-Length"; /** The HTTP {@code Content-Type} header field name. */ public static final String CONTENT_TYPE = "Content-Type"; /** The HTTP {@code Date} header field name. */ public static final String DATE = "Date"; /** The HTTP {@code Pragma} header field name. */ public static final String PRAGMA = "Pragma"; /** The HTTP {@code Via} header field name. */ public static final String VIA = "Via"; /** The HTTP {@code Warning} header field name. */ public static final String WARNING = "Warning"; // HTTP Request header fields /** The HTTP {@code Accept} header field name. */ public static final String ACCEPT = "Accept"; /** The HTTP {@code Accept-Charset} header field name. */ public static final String ACCEPT_CHARSET = "Accept-Charset"; /** The HTTP {@code Accept-Encoding} header field name. */ public static final String ACCEPT_ENCODING = "Accept-Encoding"; /** The HTTP {@code Accept-Language} header field name. */ public static final String ACCEPT_LANGUAGE = "Accept-Language"; /** The HTTP {@code Access-Control-Request-Headers} header field name. */ public static final String ACCESS_CONTROL_REQUEST_HEADERS = "Access-Control-Request-Headers"; /** The HTTP {@code Access-Control-Request-Method} header field name. */ public static final String ACCESS_CONTROL_REQUEST_METHOD = "Access-Control-Request-Method"; /** The HTTP {@code Authorization} header field name. */ public static final String AUTHORIZATION = "Authorization"; /** The HTTP {@code Connection} header field name. */ public static final String CONNECTION = "Connection"; /** The HTTP {@code Cookie} header field name. */ public static final String COOKIE = "Cookie"; /** The HTTP {@code Expect} header field name. */ public static final String EXPECT = "Expect"; /** The HTTP {@code From} header field name. */ public static final String FROM = "From"; /** * The HTTP {@code Follow-Only-When-Prerender-Shown}</a> header field name. * * @since 17.0 */ @Beta public static final String FOLLOW_ONLY_WHEN_PRERENDER_SHOWN = "Follow-Only-When-Prerender-Shown"; /** The HTTP {@code Host} header field name. */ public static final String HOST = "Host"; /** The HTTP {@code If-Match} header field name. */ public static final String IF_MATCH = "If-Match"; /** The HTTP {@code If-Modified-Since} header field name. */ public static final String IF_MODIFIED_SINCE = "If-Modified-Since"; /** The HTTP {@code If-None-Match} header field name. */ public static final String IF_NONE_MATCH = "If-None-Match"; /** The HTTP {@code If-Range} header field name. */ public static final String IF_RANGE = "If-Range"; /** The HTTP {@code If-Unmodified-Since} header field name. */ public static final String IF_UNMODIFIED_SINCE = "If-Unmodified-Since"; /** The HTTP {@code Last-Event-ID} header field name. */ public static final String LAST_EVENT_ID = "Last-Event-ID"; /** The HTTP {@code Max-Forwards} header field name. */ public static final String MAX_FORWARDS = "Max-Forwards"; /** The HTTP {@code Origin} header field name. */ public static final String ORIGIN = "Origin"; /** The HTTP {@code Proxy-Authorization} header field name. */ public static final String PROXY_AUTHORIZATION = "Proxy-Authorization"; /** The HTTP {@code Range} header field name. */ public static final String RANGE = "Range"; /** The HTTP {@code Referer} header field name. */ public static final String REFERER = "Referer"; /** The HTTP {@code TE} header field name. */ public static final String TE = "TE"; /** The HTTP {@code Upgrade} header field name. */ public static final String UPGRADE = "Upgrade"; /** The HTTP {@code User-Agent} header field name. */ public static final String USER_AGENT = "User-Agent"; // HTTP Response header fields /** The HTTP {@code Accept-Ranges} header field name. */ public static final String ACCEPT_RANGES = "Accept-Ranges"; /** The HTTP {@code Access-Control-Allow-Headers} header field name. */ public static final String ACCESS_CONTROL_ALLOW_HEADERS = "Access-Control-Allow-Headers"; /** The HTTP {@code Access-Control-Allow-Methods} header field name. */ public static final String ACCESS_CONTROL_ALLOW_METHODS = "Access-Control-Allow-Methods"; /** The HTTP {@code Access-Control-Allow-Origin} header field name. */ public static final String ACCESS_CONTROL_ALLOW_ORIGIN = "Access-Control-Allow-Origin"; /** The HTTP {@code Access-Control-Allow-Credentials} header field name. */ public static final String ACCESS_CONTROL_ALLOW_CREDENTIALS = "Access-Control-Allow-Credentials"; /** The HTTP {@code Access-Control-Expose-Headers} header field name. */ public static final String ACCESS_CONTROL_EXPOSE_HEADERS = "Access-Control-Expose-Headers"; /** The HTTP {@code Access-Control-Max-Age} header field name. */ public static final String ACCESS_CONTROL_MAX_AGE = "Access-Control-Max-Age"; /** The HTTP {@code Age} header field name. */ public static final String AGE = "Age"; /** The HTTP {@code Allow} header field name. */ public static final String ALLOW = "Allow"; /** The HTTP {@code Content-Disposition} header field name. */ public static final String CONTENT_DISPOSITION = "Content-Disposition"; /** The HTTP {@code Content-Encoding} header field name. */ public static final String CONTENT_ENCODING = "Content-Encoding"; /** The HTTP {@code Content-Language} header field name. */ public static final String CONTENT_LANGUAGE = "Content-Language"; /** The HTTP {@code Content-Location} header field name. */ public static final String CONTENT_LOCATION = "Content-Location"; /** The HTTP {@code Content-MD5} header field name. */ public static final String CONTENT_MD5 = "Content-MD5"; /** The HTTP {@code Content-Range} header field name. */ public static final String CONTENT_RANGE = "Content-Range"; /** * The HTTP <a href="http://w3.org/TR/CSP/#content-security-policy-header-field"> * {@code Content-Security-Policy}</a> header field name. * * @since 15.0 */ public static final String CONTENT_SECURITY_POLICY = "Content-Security-Policy"; /** * The HTTP <a href="http://w3.org/TR/CSP/#content-security-policy-report-only-header-field"> * {@code Content-Security-Policy-Report-Only}</a> header field name. * * @since 15.0 */ public static final String CONTENT_SECURITY_POLICY_REPORT_ONLY = "Content-Security-Policy-Report-Only"; /** The HTTP {@code ETag} header field name. */ public static final String ETAG = "ETag"; /** The HTTP {@code Expires} header field name. */ public static final String EXPIRES = "Expires"; /** The HTTP {@code Last-Modified} header field name. */ public static final String LAST_MODIFIED = "Last-Modified"; /** The HTTP {@code Link} header field name. */ public static final String LINK = "Link"; /** The HTTP {@code Location} header field name. */ public static final String LOCATION = "Location"; /** The HTTP {@code P3P} header field name. Limited browser support. */ public static final String P3P = "P3P"; /** The HTTP {@code Proxy-Authenticate} header field name. */ public static final String PROXY_AUTHENTICATE = "Proxy-Authenticate"; /** The HTTP {@code Refresh} header field name. Non-standard header supported by most browsers. */ public static final String REFRESH = "Refresh"; /** The HTTP {@code Retry-After} header field name. */ public static final String RETRY_AFTER = "Retry-After"; /** The HTTP {@code Server} header field name. */ public static final String SERVER = "Server"; /** The HTTP {@code Set-Cookie} header field name. */ public static final String SET_COOKIE = "Set-Cookie"; /** The HTTP {@code Set-Cookie2} header field name. */ public static final String SET_COOKIE2 = "Set-Cookie2"; /** * The HTTP <a href="http://tools.ietf.org/html/rfc6797#section-6.1"> * {@code Strict-Transport-Security}</a> header field name. * * @since 15.0 */ public static final String STRICT_TRANSPORT_SECURITY = "Strict-Transport-Security"; /** * The HTTP <a href="http://www.w3.org/TR/resource-timing/#cross-origin-resources"> * {@code Timing-Allow-Origin}</a> header field name. * * @since 15.0 */ public static final String TIMING_ALLOW_ORIGIN = "Timing-Allow-Origin"; /** The HTTP {@code Trailer} header field name. */ public static final String TRAILER = "Trailer"; /** The HTTP {@code Transfer-Encoding} header field name. */ public static final String TRANSFER_ENCODING = "Transfer-Encoding"; /** The HTTP {@code Vary} header field name. */ public static final String VARY = "Vary"; /** The HTTP {@code WWW-Authenticate} header field name. */ public static final String WWW_AUTHENTICATE = "WWW-Authenticate"; // Common, non-standard HTTP header fields /** The HTTP {@code DNT} header field name. */ public static final String DNT = "DNT"; /** The HTTP {@code X-Content-Type-Options} header field name. */ public static final String X_CONTENT_TYPE_OPTIONS = "X-Content-Type-Options"; /** The HTTP {@code X-Do-Not-Track} header field name. */ public static final String X_DO_NOT_TRACK = "X-Do-Not-Track"; /** The HTTP {@code X-Forwarded-For} header field name. */ public static final String X_FORWARDED_FOR = "X-Forwarded-For"; /** The HTTP {@code X-Forwarded-Proto} header field name. */ public static final String X_FORWARDED_PROTO = "X-Forwarded-Proto"; /** The HTTP {@code X-Frame-Options} header field name. */ public static final String X_FRAME_OPTIONS = "X-Frame-Options"; /** The HTTP {@code X-Powered-By} header field name. */ public static final String X_POWERED_BY = "X-Powered-By"; /** * The HTTP <a href="http://tools.ietf.org/html/draft-evans-palmer-key-pinning"> * {@code Public-Key-Pins}</a> header field name. * * @since 15.0 */ @Beta public static final String PUBLIC_KEY_PINS = "Public-Key-Pins"; /** * The HTTP <a href="http://tools.ietf.org/html/draft-evans-palmer-key-pinning"> * {@code Public-Key-Pins-Report-Only}</a> header field name. * * @since 15.0 */ @Beta public static final String PUBLIC_KEY_PINS_REPORT_ONLY = "Public-Key-Pins-Report-Only"; /** The HTTP {@code X-Requested-With} header field name. */ public static final String X_REQUESTED_WITH = "X-Requested-With"; /** The HTTP {@code X-User-IP} header field name. */ public static final String X_USER_IP = "X-User-IP"; /** The HTTP {@code X-XSS-Protection} header field name. */ public static final String X_XSS_PROTECTION = "X-XSS-Protection"; }
zzhhhhh-aw4rwer
guava/src/com/google/common/net/HttpHeaders.java
Java
asf20
12,169
/* * Copyright (C) 2009 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.net; import com.google.common.annotations.Beta; import com.google.common.base.Preconditions; import java.net.InetAddress; import java.text.ParseException; import javax.annotation.Nullable; /** * A syntactically valid host specifier, suitable for use in a URI. * This may be either a numeric IP address in IPv4 or IPv6 notation, or a * domain name. * * <p>Because this class is intended to represent host specifiers which can * reasonably be used in a URI, the domain name case is further restricted to * include only those domain names which end in a recognized public suffix; see * {@link InternetDomainName#isPublicSuffix()} for details. * * <p>Note that no network lookups are performed by any {@code HostSpecifier} * methods. No attempt is made to verify that a provided specifier corresponds * to a real or accessible host. Only syntactic and pattern-based checks are * performed. * * <p>If you know that a given string represents a numeric IP address, use * {@link InetAddresses} to obtain and manipulate a * {@link java.net.InetAddress} instance from it rather than using this class. * Similarly, if you know that a given string represents a domain name, use * {@link InternetDomainName} rather than this class. * * @author Craig Berry * @since 5.0 */ @Beta public final class HostSpecifier { private final String canonicalForm; private HostSpecifier(String canonicalForm) { this.canonicalForm = canonicalForm; } /** * Returns a {@code HostSpecifier} built from the provided {@code specifier}, * which is already known to be valid. If the {@code specifier} might be * invalid, use {@link #from(String)} instead. * * <p>The specifier must be in one of these formats: * <ul> * <li>A domain name, like {@code google.com} * <li>A IPv4 address string, like {@code 127.0.0.1} * <li>An IPv6 address string with or without brackets, like * {@code [2001:db8::1]} or {@code 2001:db8::1} * </ul> * * @throws IllegalArgumentException if the specifier is not valid. */ public static HostSpecifier fromValid(String specifier) { // Verify that no port was specified, and strip optional brackets from // IPv6 literals. final HostAndPort parsedHost = HostAndPort.fromString(specifier); Preconditions.checkArgument(!parsedHost.hasPort()); final String host = parsedHost.getHostText(); // Try to interpret the specifier as an IP address. Note we build // the address rather than using the .is* methods because we want to // use InetAddresses.toUriString to convert the result to a string in // canonical form. InetAddress addr = null; try { addr = InetAddresses.forString(host); } catch (IllegalArgumentException e) { // It is not an IPv4 or IPv6 literal } if (addr != null) { return new HostSpecifier(InetAddresses.toUriString(addr)); } // It is not any kind of IP address; must be a domain name or invalid. // TODO(user): different versions of this for different factories? final InternetDomainName domain = InternetDomainName.from(host); if (domain.hasPublicSuffix()) { return new HostSpecifier(domain.toString()); } throw new IllegalArgumentException( "Domain name does not have a recognized public suffix: " + host); } /** * Attempts to return a {@code HostSpecifier} for the given string, throwing * an exception if parsing fails. Always use this method in preference to * {@link #fromValid(String)} for a specifier that is not already known to be * valid. * * @throws ParseException if the specifier is not valid. */ public static HostSpecifier from(String specifier) throws ParseException { try { return fromValid(specifier); } catch (IllegalArgumentException e) { // Since the IAE can originate at several different points inside // fromValid(), we implement this method in terms of that one rather // than the reverse. ParseException parseException = new ParseException("Invalid host specifier: " + specifier, 0); parseException.initCause(e); throw parseException; } } /** * Determines whether {@code specifier} represents a valid * {@link HostSpecifier} as described in the documentation for * {@link #fromValid(String)}. */ public static boolean isValid(String specifier) { try { fromValid(specifier); return true; } catch (IllegalArgumentException e) { return false; } } @Override public boolean equals(@Nullable Object other) { if (this == other) { return true; } if (other instanceof HostSpecifier) { final HostSpecifier that = (HostSpecifier) other; return this.canonicalForm.equals(that.canonicalForm); } return false; } @Override public int hashCode() { return canonicalForm.hashCode(); } /** * Returns a string representation of the host specifier suitable for * inclusion in a URI. If the host specifier is a domain name, the * string will be normalized to all lower case. If the specifier was * an IPv6 address without brackets, brackets are added so that the * result will be usable in the host part of a URI. */ @Override public String toString() { return canonicalForm; } }
zzhhhhh-aw4rwer
guava/src/com/google/common/net/HostSpecifier.java
Java
asf20
5,971
/* * Copyright (C) 2008 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.net; import static com.google.common.base.Preconditions.checkNotNull; import com.google.common.annotations.Beta; import com.google.common.annotations.GwtCompatible; import com.google.common.escape.UnicodeEscaper; /** * A {@code UnicodeEscaper} that escapes some set of Java characters using a * UTF-8 based percent encoding scheme. The set of safe characters (those which * remain unescaped) can be specified on construction. * * <p>This class is primarily used for creating URI escapers in {@link * UrlEscapers} but can be used directly if required. While URI escapers impose * specific semantics on which characters are considered 'safe', this class has * a minimal set of restrictions. * * <p>When escaping a String, the following rules apply: * <ul> * <li>All specified safe characters remain unchanged. * <li>If {@code plusForSpace} was specified, the space character " " is * converted into a plus sign {@code "+"}. * <li>All other characters are converted into one or more bytes using UTF-8 * encoding and each byte is then represented by the 3-character string * "%XX", where "XX" is the two-digit, uppercase, hexadecimal representation * of the byte value. * </ul> * * <p>For performance reasons the only currently supported character encoding of * this class is UTF-8. * * <p><b>Note</b>: This escaper produces uppercase hexadecimal sequences. From * <a href="http://www.ietf.org/rfc/rfc3986.txt">RFC 3986</a>:<br> * <i>"URI producers and normalizers should use uppercase hexadecimal digits * for all percent-encodings."</i> * * @author David Beaumont * @since 15.0 */ @Beta @GwtCompatible public final class PercentEscaper extends UnicodeEscaper { // In some escapers spaces are escaped to '+' private static final char[] PLUS_SIGN = { '+' }; // Percent escapers output upper case hex digits (uri escapers require this). private static final char[] UPPER_HEX_DIGITS = "0123456789ABCDEF".toCharArray(); /** * If true we should convert space to the {@code +} character. */ private final boolean plusForSpace; /** * An array of flags where for any {@code char c} if {@code safeOctets[c]} is * true then {@code c} should remain unmodified in the output. If * {@code c > safeOctets.length} then it should be escaped. */ private final boolean[] safeOctets; /** * Constructs a percent escaper with the specified safe characters and * optional handling of the space character. * * <p>Not that it is allowed, but not necessarily desirable to specify {@code %} * as a safe character. This has the effect of creating an escaper which has no * well defined inverse but it can be useful when escaping additional characters. * * @param safeChars a non null string specifying additional safe characters * for this escaper (the ranges 0..9, a..z and A..Z are always safe and * should not be specified here) * @param plusForSpace true if ASCII space should be escaped to {@code +} * rather than {@code %20} * @throws IllegalArgumentException if any of the parameters were invalid */ public PercentEscaper(String safeChars, boolean plusForSpace) { // TODO(user): Switch to static factory methods for creation now that class is final. // TODO(user): Support escapers where alphanumeric chars are not safe. checkNotNull(safeChars); // eager for GWT. // Avoid any misunderstandings about the behavior of this escaper if (safeChars.matches(".*[0-9A-Za-z].*")) { throw new IllegalArgumentException( "Alphanumeric characters are always 'safe' and should not be " + "explicitly specified"); } safeChars += "abcdefghijklmnopqrstuvwxyz" + "ABCDEFGHIJKLMNOPQRSTUVWXYZ" + "0123456789"; // Avoid ambiguous parameters. Safe characters are never modified so if // space is a safe character then setting plusForSpace is meaningless. if (plusForSpace && safeChars.contains(" ")) { throw new IllegalArgumentException( "plusForSpace cannot be specified when space is a 'safe' character"); } this.plusForSpace = plusForSpace; this.safeOctets = createSafeOctets(safeChars); } /** * Creates a boolean array with entries corresponding to the character values * specified in safeChars set to true. The array is as small as is required to * hold the given character information. */ private static boolean[] createSafeOctets(String safeChars) { int maxChar = -1; char[] safeCharArray = safeChars.toCharArray(); for (char c : safeCharArray) { maxChar = Math.max(c, maxChar); } boolean[] octets = new boolean[maxChar + 1]; for (char c : safeCharArray) { octets[c] = true; } return octets; } /* * Overridden for performance. For unescaped strings this improved the * performance of the uri escaper from ~760ns to ~400ns as measured by * {@link CharEscapersBenchmark}. */ @Override protected int nextEscapeIndex(CharSequence csq, int index, int end) { checkNotNull(csq); for (; index < end; index++) { char c = csq.charAt(index); if (c >= safeOctets.length || !safeOctets[c]) { break; } } return index; } /* * Overridden for performance. For unescaped strings this improved the * performance of the uri escaper from ~400ns to ~170ns as measured by * {@link CharEscapersBenchmark}. */ @Override public String escape(String s) { checkNotNull(s); int slen = s.length(); for (int index = 0; index < slen; index++) { char c = s.charAt(index); if (c >= safeOctets.length || !safeOctets[c]) { return escapeSlow(s, index); } } return s; } /** * Escapes the given Unicode code point in UTF-8. */ @Override protected char[] escape(int cp) { // We should never get negative values here but if we do it will throw an // IndexOutOfBoundsException, so at least it will get spotted. if (cp < safeOctets.length && safeOctets[cp]) { return null; } else if (cp == ' ' && plusForSpace) { return PLUS_SIGN; } else if (cp <= 0x7F) { // Single byte UTF-8 characters // Start with "%--" and fill in the blanks char[] dest = new char[3]; dest[0] = '%'; dest[2] = UPPER_HEX_DIGITS[cp & 0xF]; dest[1] = UPPER_HEX_DIGITS[cp >>> 4]; return dest; } else if (cp <= 0x7ff) { // Two byte UTF-8 characters [cp >= 0x80 && cp <= 0x7ff] // Start with "%--%--" and fill in the blanks char[] dest = new char[6]; dest[0] = '%'; dest[3] = '%'; dest[5] = UPPER_HEX_DIGITS[cp & 0xF]; cp >>>= 4; dest[4] = UPPER_HEX_DIGITS[0x8 | (cp & 0x3)]; cp >>>= 2; dest[2] = UPPER_HEX_DIGITS[cp & 0xF]; cp >>>= 4; dest[1] = UPPER_HEX_DIGITS[0xC | cp]; return dest; } else if (cp <= 0xffff) { // Three byte UTF-8 characters [cp >= 0x800 && cp <= 0xffff] // Start with "%E-%--%--" and fill in the blanks char[] dest = new char[9]; dest[0] = '%'; dest[1] = 'E'; dest[3] = '%'; dest[6] = '%'; dest[8] = UPPER_HEX_DIGITS[cp & 0xF]; cp >>>= 4; dest[7] = UPPER_HEX_DIGITS[0x8 | (cp & 0x3)]; cp >>>= 2; dest[5] = UPPER_HEX_DIGITS[cp & 0xF]; cp >>>= 4; dest[4] = UPPER_HEX_DIGITS[0x8 | (cp & 0x3)]; cp >>>= 2; dest[2] = UPPER_HEX_DIGITS[cp]; return dest; } else if (cp <= 0x10ffff) { char[] dest = new char[12]; // Four byte UTF-8 characters [cp >= 0xffff && cp <= 0x10ffff] // Start with "%F-%--%--%--" and fill in the blanks dest[0] = '%'; dest[1] = 'F'; dest[3] = '%'; dest[6] = '%'; dest[9] = '%'; dest[11] = UPPER_HEX_DIGITS[cp & 0xF]; cp >>>= 4; dest[10] = UPPER_HEX_DIGITS[0x8 | (cp & 0x3)]; cp >>>= 2; dest[8] = UPPER_HEX_DIGITS[cp & 0xF]; cp >>>= 4; dest[7] = UPPER_HEX_DIGITS[0x8 | (cp & 0x3)]; cp >>>= 2; dest[5] = UPPER_HEX_DIGITS[cp & 0xF]; cp >>>= 4; dest[4] = UPPER_HEX_DIGITS[0x8 | (cp & 0x3)]; cp >>>= 2; dest[2] = UPPER_HEX_DIGITS[cp & 0x7]; return dest; } else { // If this ever happens it is due to bug in UnicodeEscaper, not bad input. throw new IllegalArgumentException( "Invalid unicode character value " + cp); } } }
zzhhhhh-aw4rwer
guava/src/com/google/common/net/PercentEscaper.java
Java
asf20
9,098
/* * Copyright (C) 2008 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.net; import com.google.common.annotations.Beta; import com.google.common.base.Objects; import com.google.common.base.Preconditions; import com.google.common.hash.Hashing; import com.google.common.io.ByteStreams; import com.google.common.primitives.Ints; import java.net.Inet4Address; import java.net.Inet6Address; import java.net.InetAddress; import java.net.UnknownHostException; import java.nio.ByteBuffer; import java.util.Arrays; import javax.annotation.Nullable; /** * Static utility methods pertaining to {@link InetAddress} instances. * * <p><b>Important note:</b> Unlike {@code InetAddress.getByName()}, the * methods of this class never cause DNS services to be accessed. For * this reason, you should prefer these methods as much as possible over * their JDK equivalents whenever you are expecting to handle only * IP address string literals -- there is no blocking DNS penalty for a * malformed string. * * <p>When dealing with {@link Inet4Address} and {@link Inet6Address} * objects as byte arrays (vis. {@code InetAddress.getAddress()}) they * are 4 and 16 bytes in length, respectively, and represent the address * in network byte order. * * <p>Examples of IP addresses and their byte representations: * <ul> * <li>The IPv4 loopback address, {@code "127.0.0.1"}.<br/> * {@code 7f 00 00 01} * * <li>The IPv6 loopback address, {@code "::1"}.<br/> * {@code 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 01} * * <li>From the IPv6 reserved documentation prefix ({@code 2001:db8::/32}), * {@code "2001:db8::1"}.<br/> * {@code 20 01 0d b8 00 00 00 00 00 00 00 00 00 00 00 01} * * <li>An IPv6 "IPv4 compatible" (or "compat") address, * {@code "::192.168.0.1"}.<br/> * {@code 00 00 00 00 00 00 00 00 00 00 00 00 c0 a8 00 01} * * <li>An IPv6 "IPv4 mapped" address, {@code "::ffff:192.168.0.1"}.<br/> * {@code 00 00 00 00 00 00 00 00 00 00 ff ff c0 a8 00 01} * </ul> * * <p>A few notes about IPv6 "IPv4 mapped" addresses and their observed * use in Java. * <br><br> * "IPv4 mapped" addresses were originally a representation of IPv4 * addresses for use on an IPv6 socket that could receive both IPv4 * and IPv6 connections (by disabling the {@code IPV6_V6ONLY} socket * option on an IPv6 socket). Yes, it's confusing. Nevertheless, * these "mapped" addresses were never supposed to be seen on the * wire. That assumption was dropped, some say mistakenly, in later * RFCs with the apparent aim of making IPv4-to-IPv6 transition simpler. * * <p>Technically one <i>can</i> create a 128bit IPv6 address with the wire * format of a "mapped" address, as shown above, and transmit it in an * IPv6 packet header. However, Java's InetAddress creation methods * appear to adhere doggedly to the original intent of the "mapped" * address: all "mapped" addresses return {@link Inet4Address} objects. * * <p>For added safety, it is common for IPv6 network operators to filter * all packets where either the source or destination address appears to * be a "compat" or "mapped" address. Filtering suggestions usually * recommend discarding any packets with source or destination addresses * in the invalid range {@code ::/3}, which includes both of these bizarre * address formats. For more information on "bogons", including lists * of IPv6 bogon space, see: * * <ul> * <li><a target="_parent" * href="http://en.wikipedia.org/wiki/Bogon_filtering" * >http://en.wikipedia.org/wiki/Bogon_filtering</a> * <li><a target="_parent" * href="http://www.cymru.com/Bogons/ipv6.txt" * >http://www.cymru.com/Bogons/ipv6.txt</a> * <li><a target="_parent" * href="http://www.cymru.com/Bogons/v6bogon.html" * >http://www.cymru.com/Bogons/v6bogon.html</a> * <li><a target="_parent" * href="http://www.space.net/~gert/RIPE/ipv6-filters.html" * >http://www.space.net/~gert/RIPE/ipv6-filters.html</a> * </ul> * * @author Erik Kline * @since 5.0 */ @Beta public final class InetAddresses { private static final int IPV4_PART_COUNT = 4; private static final int IPV6_PART_COUNT = 8; private static final Inet4Address LOOPBACK4 = (Inet4Address) forString("127.0.0.1"); private static final Inet4Address ANY4 = (Inet4Address) forString("0.0.0.0"); private InetAddresses() {} /** * Returns an {@link Inet4Address}, given a byte array representation of the IPv4 address. * * @param bytes byte array representing an IPv4 address (should be of length 4) * @return {@link Inet4Address} corresponding to the supplied byte array * @throws IllegalArgumentException if a valid {@link Inet4Address} can not be created */ private static Inet4Address getInet4Address(byte[] bytes) { Preconditions.checkArgument(bytes.length == 4, "Byte array has invalid length for an IPv4 address: %s != 4.", bytes.length); // Given a 4-byte array, this cast should always succeed. return (Inet4Address) bytesToInetAddress(bytes); } /** * Returns the {@link InetAddress} having the given string representation. * * <p>This deliberately avoids all nameservice lookups (e.g. no DNS). * * @param ipString {@code String} containing an IPv4 or IPv6 string literal, e.g. * {@code "192.168.0.1"} or {@code "2001:db8::1"} * @return {@link InetAddress} representing the argument * @throws IllegalArgumentException if the argument is not a valid IP string literal */ public static InetAddress forString(String ipString) { byte[] addr = ipStringToBytes(ipString); // The argument was malformed, i.e. not an IP string literal. if (addr == null) { throw new IllegalArgumentException( String.format("'%s' is not an IP string literal.", ipString)); } return bytesToInetAddress(addr); } /** * Returns {@code true} if the supplied string is a valid IP string * literal, {@code false} otherwise. * * @param ipString {@code String} to evaluated as an IP string literal * @return {@code true} if the argument is a valid IP string literal */ public static boolean isInetAddress(String ipString) { return ipStringToBytes(ipString) != null; } private static byte[] ipStringToBytes(String ipString) { // Make a first pass to categorize the characters in this string. boolean hasColon = false; boolean hasDot = false; for (int i = 0; i < ipString.length(); i++) { char c = ipString.charAt(i); if (c == '.') { hasDot = true; } else if (c == ':') { if (hasDot) { return null; // Colons must not appear after dots. } hasColon = true; } else if (Character.digit(c, 16) == -1) { return null; // Everything else must be a decimal or hex digit. } } // Now decide which address family to parse. if (hasColon) { if (hasDot) { ipString = convertDottedQuadToHex(ipString); if (ipString == null) { return null; } } return textToNumericFormatV6(ipString); } else if (hasDot) { return textToNumericFormatV4(ipString); } return null; } private static byte[] textToNumericFormatV4(String ipString) { String[] address = ipString.split("\\.", IPV4_PART_COUNT + 1); if (address.length != IPV4_PART_COUNT) { return null; } byte[] bytes = new byte[IPV4_PART_COUNT]; try { for (int i = 0; i < bytes.length; i++) { bytes[i] = parseOctet(address[i]); } } catch (NumberFormatException ex) { return null; } return bytes; } private static byte[] textToNumericFormatV6(String ipString) { // An address can have [2..8] colons, and N colons make N+1 parts. String[] parts = ipString.split(":", IPV6_PART_COUNT + 2); if (parts.length < 3 || parts.length > IPV6_PART_COUNT + 1) { return null; } // Disregarding the endpoints, find "::" with nothing in between. // This indicates that a run of zeroes has been skipped. int skipIndex = -1; for (int i = 1; i < parts.length - 1; i++) { if (parts[i].length() == 0) { if (skipIndex >= 0) { return null; // Can't have more than one :: } skipIndex = i; } } int partsHi; // Number of parts to copy from above/before the "::" int partsLo; // Number of parts to copy from below/after the "::" if (skipIndex >= 0) { // If we found a "::", then check if it also covers the endpoints. partsHi = skipIndex; partsLo = parts.length - skipIndex - 1; if (parts[0].length() == 0 && --partsHi != 0) { return null; // ^: requires ^:: } if (parts[parts.length - 1].length() == 0 && --partsLo != 0) { return null; // :$ requires ::$ } } else { // Otherwise, allocate the entire address to partsHi. The endpoints // could still be empty, but parseHextet() will check for that. partsHi = parts.length; partsLo = 0; } // If we found a ::, then we must have skipped at least one part. // Otherwise, we must have exactly the right number of parts. int partsSkipped = IPV6_PART_COUNT - (partsHi + partsLo); if (!(skipIndex >= 0 ? partsSkipped >= 1 : partsSkipped == 0)) { return null; } // Now parse the hextets into a byte array. ByteBuffer rawBytes = ByteBuffer.allocate(2 * IPV6_PART_COUNT); try { for (int i = 0; i < partsHi; i++) { rawBytes.putShort(parseHextet(parts[i])); } for (int i = 0; i < partsSkipped; i++) { rawBytes.putShort((short) 0); } for (int i = partsLo; i > 0; i--) { rawBytes.putShort(parseHextet(parts[parts.length - i])); } } catch (NumberFormatException ex) { return null; } return rawBytes.array(); } private static String convertDottedQuadToHex(String ipString) { int lastColon = ipString.lastIndexOf(':'); String initialPart = ipString.substring(0, lastColon + 1); String dottedQuad = ipString.substring(lastColon + 1); byte[] quad = textToNumericFormatV4(dottedQuad); if (quad == null) { return null; } String penultimate = Integer.toHexString(((quad[0] & 0xff) << 8) | (quad[1] & 0xff)); String ultimate = Integer.toHexString(((quad[2] & 0xff) << 8) | (quad[3] & 0xff)); return initialPart + penultimate + ":" + ultimate; } private static byte parseOctet(String ipPart) { // Note: we already verified that this string contains only hex digits. int octet = Integer.parseInt(ipPart); // Disallow leading zeroes, because no clear standard exists on // whether these should be interpreted as decimal or octal. if (octet > 255 || (ipPart.startsWith("0") && ipPart.length() > 1)) { throw new NumberFormatException(); } return (byte) octet; } private static short parseHextet(String ipPart) { // Note: we already verified that this string contains only hex digits. int hextet = Integer.parseInt(ipPart, 16); if (hextet > 0xffff) { throw new NumberFormatException(); } return (short) hextet; } /** * Convert a byte array into an InetAddress. * * {@link InetAddress#getByAddress} is documented as throwing a checked * exception "if IP address if of illegal length." We replace it with * an unchecked exception, for use by callers who already know that addr * is an array of length 4 or 16. * * @param addr the raw 4-byte or 16-byte IP address in big-endian order * @return an InetAddress object created from the raw IP address */ private static InetAddress bytesToInetAddress(byte[] addr) { try { return InetAddress.getByAddress(addr); } catch (UnknownHostException e) { throw new AssertionError(e); } } /** * Returns the string representation of an {@link InetAddress}. * * <p>For IPv4 addresses, this is identical to * {@link InetAddress#getHostAddress()}, but for IPv6 addresses, the output * follows <a href="http://tools.ietf.org/html/rfc5952">RFC 5952</a> * section 4. The main difference is that this method uses "::" for zero * compression, while Java's version uses the uncompressed form. * * <p>This method uses hexadecimal for all IPv6 addresses, including * IPv4-mapped IPv6 addresses such as "::c000:201". The output does not * include a Scope ID. * * @param ip {@link InetAddress} to be converted to an address string * @return {@code String} containing the text-formatted IP address * @since 10.0 */ public static String toAddrString(InetAddress ip) { Preconditions.checkNotNull(ip); if (ip instanceof Inet4Address) { // For IPv4, Java's formatting is good enough. return ip.getHostAddress(); } Preconditions.checkArgument(ip instanceof Inet6Address); byte[] bytes = ip.getAddress(); int[] hextets = new int[IPV6_PART_COUNT]; for (int i = 0; i < hextets.length; i++) { hextets[i] = Ints.fromBytes( (byte) 0, (byte) 0, bytes[2 * i], bytes[2 * i + 1]); } compressLongestRunOfZeroes(hextets); return hextetsToIPv6String(hextets); } /** * Identify and mark the longest run of zeroes in an IPv6 address. * * <p>Only runs of two or more hextets are considered. In case of a tie, the * leftmost run wins. If a qualifying run is found, its hextets are replaced * by the sentinel value -1. * * @param hextets {@code int[]} mutable array of eight 16-bit hextets */ private static void compressLongestRunOfZeroes(int[] hextets) { int bestRunStart = -1; int bestRunLength = -1; int runStart = -1; for (int i = 0; i < hextets.length + 1; i++) { if (i < hextets.length && hextets[i] == 0) { if (runStart < 0) { runStart = i; } } else if (runStart >= 0) { int runLength = i - runStart; if (runLength > bestRunLength) { bestRunStart = runStart; bestRunLength = runLength; } runStart = -1; } } if (bestRunLength >= 2) { Arrays.fill(hextets, bestRunStart, bestRunStart + bestRunLength, -1); } } /** * Convert a list of hextets into a human-readable IPv6 address. * * <p>In order for "::" compression to work, the input should contain negative * sentinel values in place of the elided zeroes. * * @param hextets {@code int[]} array of eight 16-bit hextets, or -1s */ private static String hextetsToIPv6String(int[] hextets) { /* * While scanning the array, handle these state transitions: * start->num => "num" start->gap => "::" * num->num => ":num" num->gap => "::" * gap->num => "num" gap->gap => "" */ StringBuilder buf = new StringBuilder(39); boolean lastWasNumber = false; for (int i = 0; i < hextets.length; i++) { boolean thisIsNumber = hextets[i] >= 0; if (thisIsNumber) { if (lastWasNumber) { buf.append(':'); } buf.append(Integer.toHexString(hextets[i])); } else { if (i == 0 || lastWasNumber) { buf.append("::"); } } lastWasNumber = thisIsNumber; } return buf.toString(); } /** * Returns the string representation of an {@link InetAddress} suitable * for inclusion in a URI. * * <p>For IPv4 addresses, this is identical to * {@link InetAddress#getHostAddress()}, but for IPv6 addresses it * compresses zeroes and surrounds the text with square brackets; for example * {@code "[2001:db8::1]"}. * * <p>Per section 3.2.2 of * <a target="_parent" * href="http://tools.ietf.org/html/rfc3986#section-3.2.2" * >http://tools.ietf.org/html/rfc3986</a>, * a URI containing an IPv6 string literal is of the form * {@code "http://[2001:db8::1]:8888/index.html"}. * * <p>Use of either {@link InetAddresses#toAddrString}, * {@link InetAddress#getHostAddress()}, or this method is recommended over * {@link InetAddress#toString()} when an IP address string literal is * desired. This is because {@link InetAddress#toString()} prints the * hostname and the IP address string joined by a "/". * * @param ip {@link InetAddress} to be converted to URI string literal * @return {@code String} containing URI-safe string literal */ public static String toUriString(InetAddress ip) { if (ip instanceof Inet6Address) { return "[" + toAddrString(ip) + "]"; } return toAddrString(ip); } /** * Returns an InetAddress representing the literal IPv4 or IPv6 host * portion of a URL, encoded in the format specified by RFC 3986 section 3.2.2. * * <p>This function is similar to {@link InetAddresses#forString(String)}, * however, it requires that IPv6 addresses are surrounded by square brackets. * * <p>This function is the inverse of * {@link InetAddresses#toUriString(java.net.InetAddress)}. * * @param hostAddr A RFC 3986 section 3.2.2 encoded IPv4 or IPv6 address * @return an InetAddress representing the address in {@code hostAddr} * @throws IllegalArgumentException if {@code hostAddr} is not a valid * IPv4 address, or IPv6 address surrounded by square brackets */ public static InetAddress forUriString(String hostAddr) { Preconditions.checkNotNull(hostAddr); // Decide if this should be an IPv6 or IPv4 address. String ipString; int expectBytes; if (hostAddr.startsWith("[") && hostAddr.endsWith("]")) { ipString = hostAddr.substring(1, hostAddr.length() - 1); expectBytes = 16; } else { ipString = hostAddr; expectBytes = 4; } // Parse the address, and make sure the length/version is correct. byte[] addr = ipStringToBytes(ipString); if (addr == null || addr.length != expectBytes) { throw new IllegalArgumentException( String.format("Not a valid URI IP literal: '%s'", hostAddr)); } return bytesToInetAddress(addr); } /** * Returns {@code true} if the supplied string is a valid URI IP string * literal, {@code false} otherwise. * * @param ipString {@code String} to evaluated as an IP URI host string literal * @return {@code true} if the argument is a valid IP URI host */ public static boolean isUriInetAddress(String ipString) { try { forUriString(ipString); return true; } catch (IllegalArgumentException e) { return false; } } /** * Evaluates whether the argument is an IPv6 "compat" address. * * <p>An "IPv4 compatible", or "compat", address is one with 96 leading * bits of zero, with the remaining 32 bits interpreted as an * IPv4 address. These are conventionally represented in string * literals as {@code "::192.168.0.1"}, though {@code "::c0a8:1"} is * also considered an IPv4 compatible address (and equivalent to * {@code "::192.168.0.1"}). * * <p>For more on IPv4 compatible addresses see section 2.5.5.1 of * <a target="_parent" * href="http://tools.ietf.org/html/rfc4291#section-2.5.5.1" * >http://tools.ietf.org/html/rfc4291</a> * * <p>NOTE: This method is different from * {@link Inet6Address#isIPv4CompatibleAddress} in that it more * correctly classifies {@code "::"} and {@code "::1"} as * proper IPv6 addresses (which they are), NOT IPv4 compatible * addresses (which they are generally NOT considered to be). * * @param ip {@link Inet6Address} to be examined for embedded IPv4 compatible address format * @return {@code true} if the argument is a valid "compat" address */ public static boolean isCompatIPv4Address(Inet6Address ip) { if (!ip.isIPv4CompatibleAddress()) { return false; } byte[] bytes = ip.getAddress(); if ((bytes[12] == 0) && (bytes[13] == 0) && (bytes[14] == 0) && ((bytes[15] == 0) || (bytes[15] == 1))) { return false; } return true; } /** * Returns the IPv4 address embedded in an IPv4 compatible address. * * @param ip {@link Inet6Address} to be examined for an embedded IPv4 address * @return {@link Inet4Address} of the embedded IPv4 address * @throws IllegalArgumentException if the argument is not a valid IPv4 compatible address */ public static Inet4Address getCompatIPv4Address(Inet6Address ip) { Preconditions.checkArgument(isCompatIPv4Address(ip), "Address '%s' is not IPv4-compatible.", toAddrString(ip)); return getInet4Address(Arrays.copyOfRange(ip.getAddress(), 12, 16)); } /** * Evaluates whether the argument is a 6to4 address. * * <p>6to4 addresses begin with the {@code "2002::/16"} prefix. * The next 32 bits are the IPv4 address of the host to which * IPv6-in-IPv4 tunneled packets should be routed. * * <p>For more on 6to4 addresses see section 2 of * <a target="_parent" href="http://tools.ietf.org/html/rfc3056#section-2" * >http://tools.ietf.org/html/rfc3056</a> * * @param ip {@link Inet6Address} to be examined for 6to4 address format * @return {@code true} if the argument is a 6to4 address */ public static boolean is6to4Address(Inet6Address ip) { byte[] bytes = ip.getAddress(); return (bytes[0] == (byte) 0x20) && (bytes[1] == (byte) 0x02); } /** * Returns the IPv4 address embedded in a 6to4 address. * * @param ip {@link Inet6Address} to be examined for embedded IPv4 in 6to4 address * @return {@link Inet4Address} of embedded IPv4 in 6to4 address * @throws IllegalArgumentException if the argument is not a valid IPv6 6to4 address */ public static Inet4Address get6to4IPv4Address(Inet6Address ip) { Preconditions.checkArgument(is6to4Address(ip), "Address '%s' is not a 6to4 address.", toAddrString(ip)); return getInet4Address(Arrays.copyOfRange(ip.getAddress(), 2, 6)); } /** * A simple immutable data class to encapsulate the information to be found in a * Teredo address. * * <p>All of the fields in this class are encoded in various portions * of the IPv6 address as part of the protocol. More protocols details * can be found at: * <a target="_parent" href="http://en.wikipedia.org/wiki/Teredo_tunneling" * >http://en.wikipedia.org/wiki/Teredo_tunneling</a>. * * <p>The RFC can be found here: * <a target="_parent" href="http://tools.ietf.org/html/rfc4380" * >http://tools.ietf.org/html/rfc4380</a>. * * @since 5.0 */ @Beta public static final class TeredoInfo { private final Inet4Address server; private final Inet4Address client; private final int port; private final int flags; /** * Constructs a TeredoInfo instance. * * <p>Both server and client can be {@code null}, in which case the * value {@code "0.0.0.0"} will be assumed. * * @throws IllegalArgumentException if either of the {@code port} or the {@code flags} * arguments are out of range of an unsigned short */ // TODO: why is this public? public TeredoInfo( @Nullable Inet4Address server, @Nullable Inet4Address client, int port, int flags) { Preconditions.checkArgument((port >= 0) && (port <= 0xffff), "port '%s' is out of range (0 <= port <= 0xffff)", port); Preconditions.checkArgument((flags >= 0) && (flags <= 0xffff), "flags '%s' is out of range (0 <= flags <= 0xffff)", flags); this.server = Objects.firstNonNull(server, ANY4); this.client = Objects.firstNonNull(client, ANY4); this.port = port; this.flags = flags; } public Inet4Address getServer() { return server; } public Inet4Address getClient() { return client; } public int getPort() { return port; } public int getFlags() { return flags; } } /** * Evaluates whether the argument is a Teredo address. * * <p>Teredo addresses begin with the {@code "2001::/32"} prefix. * * @param ip {@link Inet6Address} to be examined for Teredo address format * @return {@code true} if the argument is a Teredo address */ public static boolean isTeredoAddress(Inet6Address ip) { byte[] bytes = ip.getAddress(); return (bytes[0] == (byte) 0x20) && (bytes[1] == (byte) 0x01) && (bytes[2] == 0) && (bytes[3] == 0); } /** * Returns the Teredo information embedded in a Teredo address. * * @param ip {@link Inet6Address} to be examined for embedded Teredo information * @return extracted {@code TeredoInfo} * @throws IllegalArgumentException if the argument is not a valid IPv6 Teredo address */ public static TeredoInfo getTeredoInfo(Inet6Address ip) { Preconditions.checkArgument(isTeredoAddress(ip), "Address '%s' is not a Teredo address.", toAddrString(ip)); byte[] bytes = ip.getAddress(); Inet4Address server = getInet4Address(Arrays.copyOfRange(bytes, 4, 8)); int flags = ByteStreams.newDataInput(bytes, 8).readShort() & 0xffff; // Teredo obfuscates the mapped client port, per section 4 of the RFC. int port = ~ByteStreams.newDataInput(bytes, 10).readShort() & 0xffff; byte[] clientBytes = Arrays.copyOfRange(bytes, 12, 16); for (int i = 0; i < clientBytes.length; i++) { // Teredo obfuscates the mapped client IP, per section 4 of the RFC. clientBytes[i] = (byte) ~clientBytes[i]; } Inet4Address client = getInet4Address(clientBytes); return new TeredoInfo(server, client, port, flags); } /** * Evaluates whether the argument is an ISATAP address. * * <p>From RFC 5214: "ISATAP interface identifiers are constructed in * Modified EUI-64 format [...] by concatenating the 24-bit IANA OUI * (00-00-5E), the 8-bit hexadecimal value 0xFE, and a 32-bit IPv4 * address in network byte order [...]" * * <p>For more on ISATAP addresses see section 6.1 of * <a target="_parent" href="http://tools.ietf.org/html/rfc5214#section-6.1" * >http://tools.ietf.org/html/rfc5214</a> * * @param ip {@link Inet6Address} to be examined for ISATAP address format * @return {@code true} if the argument is an ISATAP address */ public static boolean isIsatapAddress(Inet6Address ip) { // If it's a Teredo address with the right port (41217, or 0xa101) // which would be encoded as 0x5efe then it can't be an ISATAP address. if (isTeredoAddress(ip)) { return false; } byte[] bytes = ip.getAddress(); if ((bytes[8] | (byte) 0x03) != (byte) 0x03) { // Verify that high byte of the 64 bit identifier is zero, modulo // the U/L and G bits, with which we are not concerned. return false; } return (bytes[9] == (byte) 0x00) && (bytes[10] == (byte) 0x5e) && (bytes[11] == (byte) 0xfe); } /** * Returns the IPv4 address embedded in an ISATAP address. * * @param ip {@link Inet6Address} to be examined for embedded IPv4 in ISATAP address * @return {@link Inet4Address} of embedded IPv4 in an ISATAP address * @throws IllegalArgumentException if the argument is not a valid IPv6 ISATAP address */ public static Inet4Address getIsatapIPv4Address(Inet6Address ip) { Preconditions.checkArgument(isIsatapAddress(ip), "Address '%s' is not an ISATAP address.", toAddrString(ip)); return getInet4Address(Arrays.copyOfRange(ip.getAddress(), 12, 16)); } /** * Examines the Inet6Address to determine if it is an IPv6 address of one * of the specified address types that contain an embedded IPv4 address. * * <p>NOTE: ISATAP addresses are explicitly excluded from this method * due to their trivial spoofability. With other transition addresses * spoofing involves (at least) infection of one's BGP routing table. * * @param ip {@link Inet6Address} to be examined for embedded IPv4 client address * @return {@code true} if there is an embedded IPv4 client address * @since 7.0 */ public static boolean hasEmbeddedIPv4ClientAddress(Inet6Address ip) { return isCompatIPv4Address(ip) || is6to4Address(ip) || isTeredoAddress(ip); } /** * Examines the Inet6Address to extract the embedded IPv4 client address * if the InetAddress is an IPv6 address of one of the specified address * types that contain an embedded IPv4 address. * * <p>NOTE: ISATAP addresses are explicitly excluded from this method * due to their trivial spoofability. With other transition addresses * spoofing involves (at least) infection of one's BGP routing table. * * @param ip {@link Inet6Address} to be examined for embedded IPv4 client address * @return {@link Inet4Address} of embedded IPv4 client address * @throws IllegalArgumentException if the argument does not have a valid embedded IPv4 address */ public static Inet4Address getEmbeddedIPv4ClientAddress(Inet6Address ip) { if (isCompatIPv4Address(ip)) { return getCompatIPv4Address(ip); } if (is6to4Address(ip)) { return get6to4IPv4Address(ip); } if (isTeredoAddress(ip)) { return getTeredoInfo(ip).getClient(); } throw new IllegalArgumentException( String.format("'%s' has no embedded IPv4 address.", toAddrString(ip))); } /** * Evaluates whether the argument is an "IPv4 mapped" IPv6 address. * * <p>An "IPv4 mapped" address is anything in the range ::ffff:0:0/96 * (sometimes written as ::ffff:0.0.0.0/96), with the last 32 bits * interpreted as an IPv4 address. * * <p>For more on IPv4 mapped addresses see section 2.5.5.2 of * <a target="_parent" * href="http://tools.ietf.org/html/rfc4291#section-2.5.5.2" * >http://tools.ietf.org/html/rfc4291</a> * * <p>Note: This method takes a {@code String} argument because * {@link InetAddress} automatically collapses mapped addresses to IPv4. * (It is actually possible to avoid this using one of the obscure * {@link Inet6Address} methods, but it would be unwise to depend on such * a poorly-documented feature.) * * @param ipString {@code String} to be examined for embedded IPv4-mapped IPv6 address format * @return {@code true} if the argument is a valid "mapped" address * @since 10.0 */ public static boolean isMappedIPv4Address(String ipString) { byte[] bytes = ipStringToBytes(ipString); if (bytes != null && bytes.length == 16) { for (int i = 0; i < 10; i++) { if (bytes[i] != 0) { return false; } } for (int i = 10; i < 12; i++) { if (bytes[i] != (byte) 0xff) { return false; } } return true; } return false; } /** * Coerces an IPv6 address into an IPv4 address. * * <p>HACK: As long as applications continue to use IPv4 addresses for * indexing into tables, accounting, et cetera, it may be necessary to * <b>coerce</b> IPv6 addresses into IPv4 addresses. This function does * so by hashing the upper 64 bits into {@code 224.0.0.0/3} * (64 bits into 29 bits). * * <p>A "coerced" IPv4 address is equivalent to itself. * * <p>NOTE: This function is failsafe for security purposes: ALL IPv6 * addresses (except localhost (::1)) are hashed to avoid the security * risk associated with extracting an embedded IPv4 address that might * permit elevated privileges. * * @param ip {@link InetAddress} to "coerce" * @return {@link Inet4Address} represented "coerced" address * @since 7.0 */ public static Inet4Address getCoercedIPv4Address(InetAddress ip) { if (ip instanceof Inet4Address) { return (Inet4Address) ip; } // Special cases: byte[] bytes = ip.getAddress(); boolean leadingBytesOfZero = true; for (int i = 0; i < 15; ++i) { if (bytes[i] != 0) { leadingBytesOfZero = false; break; } } if (leadingBytesOfZero && (bytes[15] == 1)) { return LOOPBACK4; // ::1 } else if (leadingBytesOfZero && (bytes[15] == 0)) { return ANY4; // ::0 } Inet6Address ip6 = (Inet6Address) ip; long addressAsLong = 0; if (hasEmbeddedIPv4ClientAddress(ip6)) { addressAsLong = getEmbeddedIPv4ClientAddress(ip6).hashCode(); } else { // Just extract the high 64 bits (assuming the rest is user-modifiable). addressAsLong = ByteBuffer.wrap(ip6.getAddress(), 0, 8).getLong(); } // Many strategies for hashing are possible. This might suffice for now. int coercedHash = Hashing.murmur3_32().hashLong(addressAsLong).asInt(); // Squash into 224/4 Multicast and 240/4 Reserved space (i.e. 224/3). coercedHash |= 0xe0000000; // Fixup to avoid some "illegal" values. Currently the only potential // illegal value is 255.255.255.255. if (coercedHash == 0xffffffff) { coercedHash = 0xfffffffe; } return getInet4Address(Ints.toByteArray(coercedHash)); } /** * Returns an integer representing an IPv4 address regardless of * whether the supplied argument is an IPv4 address or not. * * <p>IPv6 addresses are <b>coerced</b> to IPv4 addresses before being * converted to integers. * * <p>As long as there are applications that assume that all IP addresses * are IPv4 addresses and can therefore be converted safely to integers * (for whatever purpose) this function can be used to handle IPv6 * addresses as well until the application is suitably fixed. * * <p>NOTE: an IPv6 address coerced to an IPv4 address can only be used * for such purposes as rudimentary identification or indexing into a * collection of real {@link InetAddress}es. They cannot be used as * real addresses for the purposes of network communication. * * @param ip {@link InetAddress} to convert * @return {@code int}, "coerced" if ip is not an IPv4 address * @since 7.0 */ public static int coerceToInteger(InetAddress ip) { return ByteStreams.newDataInput(getCoercedIPv4Address(ip).getAddress()).readInt(); } /** * Returns an Inet4Address having the integer value specified by * the argument. * * @param address {@code int}, the 32bit integer address to be converted * @return {@link Inet4Address} equivalent of the argument */ public static Inet4Address fromInteger(int address) { return getInet4Address(Ints.toByteArray(address)); } /** * Returns an address from a <b>little-endian ordered</b> byte array * (the opposite of what {@link InetAddress#getByAddress} expects). * * <p>IPv4 address byte array must be 4 bytes long and IPv6 byte array * must be 16 bytes long. * * @param addr the raw IP address in little-endian byte order * @return an InetAddress object created from the raw IP address * @throws UnknownHostException if IP address is of illegal length */ public static InetAddress fromLittleEndianByteArray(byte[] addr) throws UnknownHostException { byte[] reversed = new byte[addr.length]; for (int i = 0; i < addr.length; i++) { reversed[i] = addr[addr.length - i - 1]; } return InetAddress.getByAddress(reversed); } /** * Returns a new InetAddress that is one more than the passed in address. * This method works for both IPv4 and IPv6 addresses. * * @param address the InetAddress to increment * @return a new InetAddress that is one more than the passed in address * @throws IllegalArgumentException if InetAddress is at the end of its range * @since 10.0 */ public static InetAddress increment(InetAddress address) { byte[] addr = address.getAddress(); int i = addr.length - 1; while (i >= 0 && addr[i] == (byte) 0xff) { addr[i] = 0; i--; } Preconditions.checkArgument(i >= 0, "Incrementing %s would wrap.", address); addr[i]++; return bytesToInetAddress(addr); } /** * Returns true if the InetAddress is either 255.255.255.255 for IPv4 or * ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff for IPv6. * * @return true if the InetAddress is either 255.255.255.255 for IPv4 or * ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff for IPv6 * @since 10.0 */ public static boolean isMaximum(InetAddress address) { byte[] addr = address.getAddress(); for (int i = 0; i < addr.length; i++) { if (addr[i] != (byte) 0xff) { return false; } } return true; } }
zzhhhhh-aw4rwer
guava/src/com/google/common/net/InetAddresses.java
Java
asf20
37,050
/* * Copyright (C) 2011 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.net; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Preconditions.checkState; import com.google.common.annotations.Beta; import com.google.common.annotations.GwtCompatible; import com.google.common.base.Objects; import com.google.common.base.Strings; import java.io.Serializable; import javax.annotation.Nullable; import javax.annotation.concurrent.Immutable; /** * An immutable representation of a host and port. * * <p>Example usage: * <pre> * HostAndPort hp = HostAndPort.fromString("[2001:db8::1]") * .withDefaultPort(80) * .requireBracketsForIPv6(); * hp.getHostText(); // returns "2001:db8::1" * hp.getPort(); // returns 80 * hp.toString(); // returns "[2001:db8::1]:80" * </pre> * * <p>Here are some examples of recognized formats: * <ul> * <li>example.com * <li>example.com:80 * <li>192.0.2.1 * <li>192.0.2.1:80 * <li>[2001:db8::1] - {@link #getHostText()} omits brackets * <li>[2001:db8::1]:80 - {@link #getHostText()} omits brackets * <li>2001:db8::1 - Use {@link #requireBracketsForIPv6()} to prohibit this * </ul> * * <p>Note that this is not an exhaustive list, because these methods are only * concerned with brackets, colons, and port numbers. Full validation of the * host field (if desired) is the caller's responsibility. * * @author Paul Marks * @since 10.0 */ @Beta @Immutable @GwtCompatible public final class HostAndPort implements Serializable { /** Magic value indicating the absence of a port number. */ private static final int NO_PORT = -1; /** Hostname, IPv4/IPv6 literal, or unvalidated nonsense. */ private final String host; /** Validated port number in the range [0..65535], or NO_PORT */ private final int port; /** True if the parsed host has colons, but no surrounding brackets. */ private final boolean hasBracketlessColons; private HostAndPort(String host, int port, boolean hasBracketlessColons) { this.host = host; this.port = port; this.hasBracketlessColons = hasBracketlessColons; } /** * Returns the portion of this {@code HostAndPort} instance that should * represent the hostname or IPv4/IPv6 literal. * * <p>A successful parse does not imply any degree of sanity in this field. * For additional validation, see the {@link HostSpecifier} class. */ public String getHostText() { return host; } /** Return true if this instance has a defined port. */ public boolean hasPort() { return port >= 0; } /** * Get the current port number, failing if no port is defined. * * @return a validated port number, in the range [0..65535] * @throws IllegalStateException if no port is defined. You can use * {@link #withDefaultPort(int)} to prevent this from occurring. */ public int getPort() { checkState(hasPort()); return port; } /** * Returns the current port number, with a default if no port is defined. */ public int getPortOrDefault(int defaultPort) { return hasPort() ? port : defaultPort; } /** * Build a HostAndPort instance from separate host and port values. * * <p>Note: Non-bracketed IPv6 literals are allowed. * Use {@link #requireBracketsForIPv6()} to prohibit these. * * @param host the host string to parse. Must not contain a port number. * @param port a port number from [0..65535] * @return if parsing was successful, a populated HostAndPort object. * @throws IllegalArgumentException if {@code host} contains a port number, * or {@code port} is out of range. */ public static HostAndPort fromParts(String host, int port) { checkArgument(isValidPort(port), "Port out of range: %s", port); HostAndPort parsedHost = fromString(host); checkArgument(!parsedHost.hasPort(), "Host has a port: %s", host); return new HostAndPort(parsedHost.host, port, parsedHost.hasBracketlessColons); } /** * Build a HostAndPort instance from a host only. * * <p>Note: Non-bracketed IPv6 literals are allowed. * Use {@link #requireBracketsForIPv6()} to prohibit these. * * @param host the host-only string to parse. Must not contain a port number. * @return if parsing was successful, a populated HostAndPort object. * @throws IllegalArgumentException if {@code host} contains a port number. * @since 17.0 */ public static HostAndPort fromHost(String host) { HostAndPort parsedHost = fromString(host); checkArgument(!parsedHost.hasPort(), "Host has a port: %s", host); return parsedHost; } /** * Split a freeform string into a host and port, without strict validation. * * Note that the host-only formats will leave the port field undefined. You * can use {@link #withDefaultPort(int)} to patch in a default value. * * @param hostPortString the input string to parse. * @return if parsing was successful, a populated HostAndPort object. * @throws IllegalArgumentException if nothing meaningful could be parsed. */ public static HostAndPort fromString(String hostPortString) { checkNotNull(hostPortString); String host; String portString = null; boolean hasBracketlessColons = false; if (hostPortString.startsWith("[")) { String[] hostAndPort = getHostAndPortFromBracketedHost(hostPortString); host = hostAndPort[0]; portString = hostAndPort[1]; } else { int colonPos = hostPortString.indexOf(':'); if (colonPos >= 0 && hostPortString.indexOf(':', colonPos + 1) == -1) { // Exactly 1 colon. Split into host:port. host = hostPortString.substring(0, colonPos); portString = hostPortString.substring(colonPos + 1); } else { // 0 or 2+ colons. Bare hostname or IPv6 literal. host = hostPortString; hasBracketlessColons = (colonPos >= 0); } } int port = NO_PORT; if (!Strings.isNullOrEmpty(portString)) { // Try to parse the whole port string as a number. // JDK7 accepts leading plus signs. We don't want to. checkArgument(!portString.startsWith("+"), "Unparseable port number: %s", hostPortString); try { port = Integer.parseInt(portString); } catch (NumberFormatException e) { throw new IllegalArgumentException("Unparseable port number: " + hostPortString); } checkArgument(isValidPort(port), "Port number out of range: %s", hostPortString); } return new HostAndPort(host, port, hasBracketlessColons); } /** * Parses a bracketed host-port string, throwing IllegalArgumentException if parsing fails. * * @param hostPortString the full bracketed host-port specification. Post might not be specified. * @return an array with 2 strings: host and port, in that order. * @throws IllegalArgumentException if parsing the bracketed host-port string fails. */ private static String[] getHostAndPortFromBracketedHost(String hostPortString) { int colonIndex = 0; int closeBracketIndex = 0; boolean hasPort = false; checkArgument(hostPortString.charAt(0) == '[', "Bracketed host-port string must start with a bracket: %s", hostPortString); colonIndex = hostPortString.indexOf(':'); closeBracketIndex = hostPortString.lastIndexOf(']'); checkArgument(colonIndex > -1 && closeBracketIndex > colonIndex, "Invalid bracketed host/port: %s", hostPortString); String host = hostPortString.substring(1, closeBracketIndex); if (closeBracketIndex + 1 == hostPortString.length()) { return new String[] { host, "" }; } else { checkArgument(hostPortString.charAt(closeBracketIndex + 1) == ':', "Only a colon may follow a close bracket: %s", hostPortString); for (int i = closeBracketIndex + 2; i < hostPortString.length(); ++i) { checkArgument(Character.isDigit(hostPortString.charAt(i)), "Port must be numeric: %s", hostPortString); } return new String[] { host, hostPortString.substring(closeBracketIndex + 2) }; } } /** * Provide a default port if the parsed string contained only a host. * * You can chain this after {@link #fromString(String)} to include a port in * case the port was omitted from the input string. If a port was already * provided, then this method is a no-op. * * @param defaultPort a port number, from [0..65535] * @return a HostAndPort instance, guaranteed to have a defined port. */ public HostAndPort withDefaultPort(int defaultPort) { checkArgument(isValidPort(defaultPort)); if (hasPort() || port == defaultPort) { return this; } return new HostAndPort(host, defaultPort, hasBracketlessColons); } /** * Generate an error if the host might be a non-bracketed IPv6 literal. * * <p>URI formatting requires that IPv6 literals be surrounded by brackets, * like "[2001:db8::1]". Chain this call after {@link #fromString(String)} * to increase the strictness of the parser, and disallow IPv6 literals * that don't contain these brackets. * * <p>Note that this parser identifies IPv6 literals solely based on the * presence of a colon. To perform actual validation of IP addresses, see * the {@link InetAddresses#forString(String)} method. * * @return {@code this}, to enable chaining of calls. * @throws IllegalArgumentException if bracketless IPv6 is detected. */ public HostAndPort requireBracketsForIPv6() { checkArgument(!hasBracketlessColons, "Possible bracketless IPv6 literal: %s", host); return this; } @Override public boolean equals(@Nullable Object other) { if (this == other) { return true; } if (other instanceof HostAndPort) { HostAndPort that = (HostAndPort) other; return Objects.equal(this.host, that.host) && this.port == that.port && this.hasBracketlessColons == that.hasBracketlessColons; } return false; } @Override public int hashCode() { return Objects.hashCode(host, port, hasBracketlessColons); } /** Rebuild the host:port string, including brackets if necessary. */ @Override public String toString() { // "[]:12345" requires 8 extra bytes. StringBuilder builder = new StringBuilder(host.length() + 8); if (host.indexOf(':') >= 0) { builder.append('[').append(host).append(']'); } else { builder.append(host); } if (hasPort()) { builder.append(':').append(port); } return builder.toString(); } /** Return true for valid port numbers. */ private static boolean isValidPort(int port) { return port >= 0 && port <= 65535; } private static final long serialVersionUID = 0; }
zzhhhhh-aw4rwer
guava/src/com/google/common/net/HostAndPort.java
Java
asf20
11,437
/* * Copyright (C) 2012 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * Escapers * for * HTML. * * <p>This package is a part of the open-source * <a href="http://guava-libraries.googlecode.com">Guava libraries</a>. */ @ParametersAreNonnullByDefault package com.google.common.html; import javax.annotation.ParametersAreNonnullByDefault;
zzhhhhh-aw4rwer
guava/src/com/google/common/html/package-info.java
Java
asf20
880
/* * Copyright (C) 2009 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.html; import com.google.common.annotations.Beta; import com.google.common.annotations.GwtCompatible; import com.google.common.escape.Escaper; import com.google.common.escape.Escapers; /** * {@code Escaper} instances suitable for strings to be included in HTML * attribute values and <em>most</em> elements' text contents. When possible, * avoid manual escaping by using templating systems and high-level APIs that * provide autoescaping. * * <p>HTML escaping is particularly tricky: For example, <a * href="http://goo.gl/5TgZb">some elements' text contents must not be HTML * escaped</a>. As a result, it is impossible to escape an HTML document * correctly without domain-specific knowledge beyond what {@code HtmlEscapers} * provides. We strongly encourage the use of HTML templating systems. * * @author Sven Mawson * @author David Beaumont * @since 15.0 */ @Beta @GwtCompatible public final class HtmlEscapers { /** * Returns an {@link Escaper} instance that escapes HTML metacharacters as * specified by <a href="http://www.w3.org/TR/html4/">HTML 4.01</a>. The * resulting strings can be used both in attribute values and in <em>most</em> * elements' text contents, provided that the HTML document's character * encoding can encode any non-ASCII code points in the input (as UTF-8 and * other Unicode encodings can). * * * <p><b>Note</b>: This escaper only performs minimal escaping to make content * structurally compatible with HTML. Specifically, it does not perform entity * replacement (symbolic or numeric), so it does not replace non-ASCII code * points with character references. This escaper escapes only the following * five ASCII characters: {@code '"&<>}. */ public static Escaper htmlEscaper() { return HTML_ESCAPER; } // For each xxxEscaper() method, please add links to external reference pages // that are considered authoritative for the behavior of that escaper. private static final Escaper HTML_ESCAPER = Escapers.builder() .addEscape('"', "&quot;") // Note: "&apos;" is not defined in HTML 4.01. .addEscape('\'', "&#39;") .addEscape('&', "&amp;") .addEscape('<', "&lt;") .addEscape('>', "&gt;") .build(); private HtmlEscapers() {} }
zzhhhhh-aw4rwer
guava/src/com/google/common/html/HtmlEscapers.java
Java
asf20
2,943
/* * Copyright (C) 2012 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ /* * SipHash-c-d was designed by Jean-Philippe Aumasson and Daniel J. Bernstein and is described in * "SipHash: a fast short-input PRF" (available at https://131002.net/siphash/siphash.pdf). */ package com.google.common.hash; import static com.google.common.base.Preconditions.checkArgument; import java.io.Serializable; import java.nio.ByteBuffer; import javax.annotation.Nullable; /** * {@link HashFunction} implementation of SipHash-c-d. * * @author Kurt Alfred Kluever * @author Jean-Philippe Aumasson * @author Daniel J. Bernstein */ final class SipHashFunction extends AbstractStreamingHashFunction implements Serializable { // The number of compression rounds. private final int c; // The number of finalization rounds. private final int d; // Two 64-bit keys (represent a single 128-bit key). private final long k0; private final long k1; /** * @param c the number of compression rounds (must be positive) * @param d the number of finalization rounds (must be positive) * @param k0 the first half of the key * @param k1 the second half of the key */ SipHashFunction(int c, int d, long k0, long k1) { checkArgument(c > 0, "The number of SipRound iterations (c=%s) during Compression must be positive.", c); checkArgument(d > 0, "The number of SipRound iterations (d=%s) during Finalization must be positive.", d); this.c = c; this.d = d; this.k0 = k0; this.k1 = k1; } @Override public int bits() { return 64; } @Override public Hasher newHasher() { return new SipHasher(c, d, k0, k1); } // TODO(user): Implement and benchmark the hashFoo() shortcuts. @Override public String toString() { return "Hashing.sipHash" + c + "" + d + "(" + k0 + ", " + k1 + ")"; } @Override public boolean equals(@Nullable Object object) { if (object instanceof SipHashFunction) { SipHashFunction other = (SipHashFunction) object; return (c == other.c) && (d == other.d) && (k0 == other.k0) && (k1 == other.k1); } return false; } @Override public int hashCode() { return (int) (getClass().hashCode() ^ c ^ d ^ k0 ^ k1); } private static final class SipHasher extends AbstractStreamingHasher { private static final int CHUNK_SIZE = 8; // The number of compression rounds. private final int c; // The number of finalization rounds. private final int d; // Four 64-bit words of internal state. // The initial state corresponds to the ASCII string "somepseudorandomlygeneratedbytes", // big-endian encoded. There is nothing special about this value; the only requirement // was some asymmetry so that the initial v0 and v1 differ from v2 and v3. private long v0 = 0x736f6d6570736575L; private long v1 = 0x646f72616e646f6dL; private long v2 = 0x6c7967656e657261L; private long v3 = 0x7465646279746573L; // The number of bytes in the input. private long b = 0; // The final 64-bit chunk includes the last 0 through 7 bytes of m followed by null bytes // and ending with a byte encoding the positive integer b mod 256. private long finalM = 0; SipHasher(int c, int d, long k0, long k1) { super(CHUNK_SIZE); this.c = c; this.d = d; this.v0 ^= k0; this.v1 ^= k1; this.v2 ^= k0; this.v3 ^= k1; } @Override protected void process(ByteBuffer buffer) { b += CHUNK_SIZE; processM(buffer.getLong()); } @Override protected void processRemaining(ByteBuffer buffer) { b += buffer.remaining(); for (int i = 0; buffer.hasRemaining(); i += 8) { finalM ^= (buffer.get() & 0xFFL) << i; } } @Override public HashCode makeHash() { // End with a byte encoding the positive integer b mod 256. finalM ^= b << 56; processM(finalM); // Finalization v2 ^= 0xFFL; sipRound(d); return HashCode.fromLong(v0 ^ v1 ^ v2 ^ v3); } private void processM(long m) { v3 ^= m; sipRound(c); v0 ^= m; } private void sipRound(int iterations) { for (int i = 0; i < iterations; i++) { v0 += v1; v2 += v3; v1 = Long.rotateLeft(v1, 13); v3 = Long.rotateLeft(v3, 16); v1 ^= v0; v3 ^= v2; v0 = Long.rotateLeft(v0, 32); v2 += v1; v0 += v3; v1 = Long.rotateLeft(v1, 17); v3 = Long.rotateLeft(v3, 21); v1 ^= v2; v3 ^= v0; v2 = Long.rotateLeft(v2, 32); } } } private static final long serialVersionUID = 0L; }
zzhhhhh-aw4rwer
guava/src/com/google/common/hash/SipHashFunction.java
Java
asf20
5,229
/* * Copyright (C) 2011 The Guava Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ // TODO(user): when things stabilize, flesh this out /** * Hash functions and related structures. * * <p>See the Guava User Guide article on <a href= * "http://code.google.com/p/guava-libraries/wiki/HashingExplained"> * hashing</a>. */ @ParametersAreNonnullByDefault package com.google.common.hash; import javax.annotation.ParametersAreNonnullByDefault;
zzhhhhh-aw4rwer
guava/src/com/google/common/hash/package-info.java
Java
asf20
958
/* * Copyright (C) 2011 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.common.hash; import com.google.common.annotations.Beta; import com.google.common.base.Preconditions; import java.io.OutputStream; import java.io.Serializable; import java.nio.charset.Charset; import javax.annotation.Nullable; /** * Funnels for common types. All implementations are serializable. * * @author Dimitris Andreou * @since 11.0 */ @Beta public final class Funnels { private Funnels() {} /** * Returns a funnel that extracts the bytes from a {@code byte} array. */ public static Funnel<byte[]> byteArrayFunnel() { return ByteArrayFunnel.INSTANCE; } private enum ByteArrayFunnel implements Funnel<byte[]> { INSTANCE; public void funnel(byte[] from, PrimitiveSink into) { into.putBytes(from); } @Override public String toString() { return "Funnels.byteArrayFunnel()"; } } /** * Returns a funnel that extracts the characters from a {@code CharSequence}, a character at a * time, without performing any encoding. If you need to use a specific encoding, use * {@link Funnels#stringFunnel(Charset)} instead. * * @since 15.0 (since 11.0 as {@code Funnels.stringFunnel()}. */ public static Funnel<CharSequence> unencodedCharsFunnel() { return UnencodedCharsFunnel.INSTANCE; } private enum UnencodedCharsFunnel implements Funnel<CharSequence> { INSTANCE; public void funnel(CharSequence from, PrimitiveSink into) { into.putUnencodedChars(from); } @Override public String toString() { return "Funnels.unencodedCharsFunnel()"; } } /** * Returns a funnel that encodes the characters of a {@code CharSequence} with the specified * {@code Charset}. * * @since 15.0 */ public static Funnel<CharSequence> stringFunnel(Charset charset) { return new StringCharsetFunnel(charset); } private static class StringCharsetFunnel implements Funnel<CharSequence>, Serializable { private final Charset charset; StringCharsetFunnel(Charset charset) { this.charset = Preconditions.checkNotNull(charset); } public void funnel(CharSequence from, PrimitiveSink into) { into.putString(from, charset); } @Override public String toString() { return "Funnels.stringFunnel(" + charset.name() + ")"; } @Override public boolean equals(@Nullable Object o) { if (o instanceof StringCharsetFunnel) { StringCharsetFunnel funnel = (StringCharsetFunnel) o; return this.charset.equals(funnel.charset); } return false; } @Override public int hashCode() { return StringCharsetFunnel.class.hashCode() ^ charset.hashCode(); } Object writeReplace() { return new SerializedForm(charset); } private static class SerializedForm implements Serializable { private final String charsetCanonicalName; SerializedForm(Charset charset) { this.charsetCanonicalName = charset.name(); } private Object readResolve() { return stringFunnel(Charset.forName(charsetCanonicalName)); } private static final long serialVersionUID = 0; } } /** * Returns a funnel for integers. * * @since 13.0 */ public static Funnel<Integer> integerFunnel() { return IntegerFunnel.INSTANCE; } private enum IntegerFunnel implements Funnel<Integer> { INSTANCE; public void funnel(Integer from, PrimitiveSink into) { into.putInt(from); } @Override public String toString() { return "Funnels.integerFunnel()"; } } /** * Returns a funnel that processes an {@code Iterable} by funneling its elements in iteration * order with the specified funnel. No separators are added between the elements. * * @since 15.0 */ public static <E> Funnel<Iterable<? extends E>> sequentialFunnel(Funnel<E> elementFunnel) { return new SequentialFunnel<E>(elementFunnel); } private static class SequentialFunnel<E> implements Funnel<Iterable<? extends E>>, Serializable { private final Funnel<E> elementFunnel; SequentialFunnel(Funnel<E> elementFunnel) { this.elementFunnel = Preconditions.checkNotNull(elementFunnel); } public void funnel(Iterable<? extends E> from, PrimitiveSink into) { for (E e : from) { elementFunnel.funnel(e, into); } } @Override public String toString() { return "Funnels.sequentialFunnel(" + elementFunnel + ")"; } @Override public boolean equals(@Nullable Object o) { if (o instanceof SequentialFunnel) { SequentialFunnel<?> funnel = (SequentialFunnel<?>) o; return elementFunnel.equals(funnel.elementFunnel); } return false; } @Override public int hashCode() { return SequentialFunnel.class.hashCode() ^ elementFunnel.hashCode(); } } /** * Returns a funnel for longs. * * @since 13.0 */ public static Funnel<Long> longFunnel() { return LongFunnel.INSTANCE; } private enum LongFunnel implements Funnel<Long> { INSTANCE; public void funnel(Long from, PrimitiveSink into) { into.putLong(from); } @Override public String toString() { return "Funnels.longFunnel()"; } } /** * Wraps a {@code PrimitiveSink} as an {@link OutputStream}, so it is easy to * {@link Funnel#funnel funnel} an object to a {@code PrimitiveSink} * if there is already a way to write the contents of the object to an {@code OutputStream}. * * <p>The {@code close} and {@code flush} methods of the returned {@code OutputStream} * do nothing, and no method throws {@code IOException}. * * @since 13.0 */ public static OutputStream asOutputStream(PrimitiveSink sink) { return new SinkAsStream(sink); } private static class SinkAsStream extends OutputStream { final PrimitiveSink sink; SinkAsStream(PrimitiveSink sink) { this.sink = Preconditions.checkNotNull(sink); } @Override public void write(int b) { sink.putByte((byte) b); } @Override public void write(byte[] bytes) { sink.putBytes(bytes); } @Override public void write(byte[] bytes, int off, int len) { sink.putBytes(bytes, off, len); } @Override public String toString() { return "Funnels.asOutputStream(" + sink + ")"; } } }
zzhhhhh-aw4rwer
guava/src/com/google/common/hash/Funnels.java
Java
asf20
6,969
/* * Copyright (C) 2011 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.common.hash; import static com.google.common.base.Preconditions.checkArgument; import com.google.common.base.Preconditions; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.nio.charset.Charset; /** * Skeleton implementation of {@link HashFunction}. Provides default implementations which * invokes the appropriate method on {@link #newHasher()}, then return the result of * {@link Hasher#hash}. * * <p>Invocations of {@link #newHasher(int)} also delegate to {@linkplain #newHasher()}, ignoring * the expected input size parameter. * * @author Kevin Bourrillion */ abstract class AbstractStreamingHashFunction implements HashFunction { @Override public <T> HashCode hashObject(T instance, Funnel<? super T> funnel) { return newHasher().putObject(instance, funnel).hash(); } @Override public HashCode hashUnencodedChars(CharSequence input) { return newHasher().putUnencodedChars(input).hash(); } @Override public HashCode hashString(CharSequence input, Charset charset) { return newHasher().putString(input, charset).hash(); } @Override public HashCode hashInt(int input) { return newHasher().putInt(input).hash(); } @Override public HashCode hashLong(long input) { return newHasher().putLong(input).hash(); } @Override public HashCode hashBytes(byte[] input) { return newHasher().putBytes(input).hash(); } @Override public HashCode hashBytes(byte[] input, int off, int len) { return newHasher().putBytes(input, off, len).hash(); } @Override public Hasher newHasher(int expectedInputSize) { Preconditions.checkArgument(expectedInputSize >= 0); return newHasher(); } /** * A convenience base class for implementors of {@code Hasher}; handles accumulating data * until an entire "chunk" (of implementation-dependent length) is ready to be hashed. * * @author Kevin Bourrillion * @author Dimitris Andreou */ // TODO(kevinb): this class still needs some design-and-document-for-inheritance love protected static abstract class AbstractStreamingHasher extends AbstractHasher { /** Buffer via which we pass data to the hash algorithm (the implementor) */ private final ByteBuffer buffer; /** Number of bytes to be filled before process() invocation(s). */ private final int bufferSize; /** Number of bytes processed per process() invocation. */ private final int chunkSize; /** * Constructor for use by subclasses. This hasher instance will process chunks of the specified * size. * * @param chunkSize the number of bytes available per {@link #process(ByteBuffer)} invocation; * must be at least 4 */ protected AbstractStreamingHasher(int chunkSize) { this(chunkSize, chunkSize); } /** * Constructor for use by subclasses. This hasher instance will process chunks of the specified * size, using an internal buffer of {@code bufferSize} size, which must be a multiple of * {@code chunkSize}. * * @param chunkSize the number of bytes available per {@link #process(ByteBuffer)} invocation; * must be at least 4 * @param bufferSize the size of the internal buffer. Must be a multiple of chunkSize */ protected AbstractStreamingHasher(int chunkSize, int bufferSize) { // TODO(kevinb): check more preconditions (as bufferSize >= chunkSize) if this is ever public checkArgument(bufferSize % chunkSize == 0); // TODO(user): benchmark performance difference with longer buffer this.buffer = ByteBuffer .allocate(bufferSize + 7) // always space for a single primitive .order(ByteOrder.LITTLE_ENDIAN); this.bufferSize = bufferSize; this.chunkSize = chunkSize; } /** * Processes the available bytes of the buffer (at most {@code chunk} bytes). */ protected abstract void process(ByteBuffer bb); /** * This is invoked for the last bytes of the input, which are not enough to * fill a whole chunk. The passed {@code ByteBuffer} is guaranteed to be * non-empty. * * <p>This implementation simply pads with zeros and delegates to * {@link #process(ByteBuffer)}. */ protected void processRemaining(ByteBuffer bb) { bb.position(bb.limit()); // move at the end bb.limit(chunkSize + 7); // get ready to pad with longs while (bb.position() < chunkSize) { bb.putLong(0); } bb.limit(chunkSize); bb.flip(); process(bb); } @Override public final Hasher putBytes(byte[] bytes) { return putBytes(bytes, 0, bytes.length); } @Override public final Hasher putBytes(byte[] bytes, int off, int len) { return putBytes(ByteBuffer.wrap(bytes, off, len).order(ByteOrder.LITTLE_ENDIAN)); } private Hasher putBytes(ByteBuffer readBuffer) { // If we have room for all of it, this is easy if (readBuffer.remaining() <= buffer.remaining()) { buffer.put(readBuffer); munchIfFull(); return this; } // First add just enough to fill buffer size, and munch that int bytesToCopy = bufferSize - buffer.position(); for (int i = 0; i < bytesToCopy; i++) { buffer.put(readBuffer.get()); } munch(); // buffer becomes empty here, since chunkSize divides bufferSize // Now process directly from the rest of the input buffer while (readBuffer.remaining() >= chunkSize) { process(readBuffer); } // Finally stick the remainder back in our usual buffer buffer.put(readBuffer); return this; } @Override public final Hasher putUnencodedChars(CharSequence charSequence) { for (int i = 0; i < charSequence.length(); i++) { putChar(charSequence.charAt(i)); } return this; } @Override public final Hasher putByte(byte b) { buffer.put(b); munchIfFull(); return this; } @Override public final Hasher putShort(short s) { buffer.putShort(s); munchIfFull(); return this; } @Override public final Hasher putChar(char c) { buffer.putChar(c); munchIfFull(); return this; } @Override public final Hasher putInt(int i) { buffer.putInt(i); munchIfFull(); return this; } @Override public final Hasher putLong(long l) { buffer.putLong(l); munchIfFull(); return this; } @Override public final <T> Hasher putObject(T instance, Funnel<? super T> funnel) { funnel.funnel(instance, this); return this; } @Override public final HashCode hash() { munch(); buffer.flip(); if (buffer.remaining() > 0) { processRemaining(buffer); } return makeHash(); } abstract HashCode makeHash(); // Process pent-up data in chunks private void munchIfFull() { if (buffer.remaining() < 8) { // buffer is full; not enough room for a primitive. We have at least one full chunk. munch(); } } private void munch() { buffer.flip(); while (buffer.remaining() >= chunkSize) { // we could limit the buffer to ensure process() does not read more than // chunkSize number of bytes, but we trust the implementations process(buffer); } buffer.compact(); // preserve any remaining data that do not make a full chunk } } }
zzhhhhh-aw4rwer
guava/src/com/google/common/hash/AbstractStreamingHashFunction.java
Java
asf20
8,110
/* * Copyright (C) 2011 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ /* * MurmurHash3 was written by Austin Appleby, and is placed in the public * domain. The author hereby disclaims copyright to this source code. */ /* * Source: * http://code.google.com/p/smhasher/source/browse/trunk/MurmurHash3.cpp * (Modified to adapt to Guava coding conventions and to use the HashFunction interface) */ package com.google.common.hash; import static com.google.common.primitives.UnsignedBytes.toInt; import java.io.Serializable; import java.nio.ByteBuffer; import java.nio.ByteOrder; import javax.annotation.Nullable; /** * See http://smhasher.googlecode.com/svn/trunk/MurmurHash3.cpp * MurmurHash3_x64_128 * * @author Austin Appleby * @author Dimitris Andreou */ final class Murmur3_128HashFunction extends AbstractStreamingHashFunction implements Serializable { // TODO(user): when the shortcuts are implemented, update BloomFilterStrategies private final int seed; Murmur3_128HashFunction(int seed) { this.seed = seed; } @Override public int bits() { return 128; } @Override public Hasher newHasher() { return new Murmur3_128Hasher(seed); } @Override public String toString() { return "Hashing.murmur3_128(" + seed + ")"; } @Override public boolean equals(@Nullable Object object) { if (object instanceof Murmur3_128HashFunction) { Murmur3_128HashFunction other = (Murmur3_128HashFunction) object; return seed == other.seed; } return false; } @Override public int hashCode() { return getClass().hashCode() ^ seed; } private static final class Murmur3_128Hasher extends AbstractStreamingHasher { private static final int CHUNK_SIZE = 16; private static final long C1 = 0x87c37b91114253d5L; private static final long C2 = 0x4cf5ad432745937fL; private long h1; private long h2; private int length; Murmur3_128Hasher(int seed) { super(CHUNK_SIZE); this.h1 = seed; this.h2 = seed; this.length = 0; } @Override protected void process(ByteBuffer bb) { long k1 = bb.getLong(); long k2 = bb.getLong(); bmix64(k1, k2); length += CHUNK_SIZE; } private void bmix64(long k1, long k2) { h1 ^= mixK1(k1); h1 = Long.rotateLeft(h1, 27); h1 += h2; h1 = h1 * 5 + 0x52dce729; h2 ^= mixK2(k2); h2 = Long.rotateLeft(h2, 31); h2 += h1; h2 = h2 * 5 + 0x38495ab5; } @Override protected void processRemaining(ByteBuffer bb) { long k1 = 0; long k2 = 0; length += bb.remaining(); switch (bb.remaining()) { case 15: k2 ^= (long) toInt(bb.get(14)) << 48; // fall through case 14: k2 ^= (long) toInt(bb.get(13)) << 40; // fall through case 13: k2 ^= (long) toInt(bb.get(12)) << 32; // fall through case 12: k2 ^= (long) toInt(bb.get(11)) << 24; // fall through case 11: k2 ^= (long) toInt(bb.get(10)) << 16; // fall through case 10: k2 ^= (long) toInt(bb.get(9)) << 8; // fall through case 9: k2 ^= (long) toInt(bb.get(8)); // fall through case 8: k1 ^= bb.getLong(); break; case 7: k1 ^= (long) toInt(bb.get(6)) << 48; // fall through case 6: k1 ^= (long) toInt(bb.get(5)) << 40; // fall through case 5: k1 ^= (long) toInt(bb.get(4)) << 32; // fall through case 4: k1 ^= (long) toInt(bb.get(3)) << 24; // fall through case 3: k1 ^= (long) toInt(bb.get(2)) << 16; // fall through case 2: k1 ^= (long) toInt(bb.get(1)) << 8; // fall through case 1: k1 ^= (long) toInt(bb.get(0)); break; default: throw new AssertionError("Should never get here."); } h1 ^= mixK1(k1); h2 ^= mixK2(k2); } @Override public HashCode makeHash() { h1 ^= length; h2 ^= length; h1 += h2; h2 += h1; h1 = fmix64(h1); h2 = fmix64(h2); h1 += h2; h2 += h1; return HashCode.fromBytesNoCopy(ByteBuffer .wrap(new byte[CHUNK_SIZE]) .order(ByteOrder.LITTLE_ENDIAN) .putLong(h1) .putLong(h2) .array()); } private static long fmix64(long k) { k ^= k >>> 33; k *= 0xff51afd7ed558ccdL; k ^= k >>> 33; k *= 0xc4ceb9fe1a85ec53L; k ^= k >>> 33; return k; } private static long mixK1(long k1) { k1 *= C1; k1 = Long.rotateLeft(k1, 31); k1 *= C2; return k1; } private static long mixK2(long k2) { k2 *= C2; k2 = Long.rotateLeft(k2, 33); k2 *= C1; return k2; } } private static final long serialVersionUID = 0L; }
zzhhhhh-aw4rwer
guava/src/com/google/common/hash/Murmur3_128HashFunction.java
Java
asf20
5,403
/* * Copyright (C) 2011 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.common.hash; import static com.google.common.base.Preconditions.checkArgument; import com.google.common.math.LongMath; import com.google.common.primitives.Ints; import java.math.RoundingMode; import java.util.Arrays; /** * Collections of strategies of generating the k * log(M) bits required for an element to * be mapped to a BloomFilter of M bits and k hash functions. These * strategies are part of the serialized form of the Bloom filters that use them, thus they must be * preserved as is (no updates allowed, only introduction of new versions). * * Important: the order of the constants cannot change, and they cannot be deleted - we depend * on their ordinal for BloomFilter serialization. * * @author Dimitris Andreou */ enum BloomFilterStrategies implements BloomFilter.Strategy { /** * See "Less Hashing, Same Performance: Building a Better Bloom Filter" by Adam Kirsch and * Michael Mitzenmacher. The paper argues that this trick doesn't significantly deteriorate the * performance of a Bloom filter (yet only needs two 32bit hash functions). */ MURMUR128_MITZ_32() { @Override public <T> boolean put(T object, Funnel<? super T> funnel, int numHashFunctions, BitArray bits) { long hash64 = Hashing.murmur3_128().hashObject(object, funnel).asLong(); int hash1 = (int) hash64; int hash2 = (int) (hash64 >>> 32); boolean bitsChanged = false; for (int i = 1; i <= numHashFunctions; i++) { int nextHash = hash1 + i * hash2; if (nextHash < 0) { nextHash = ~nextHash; } bitsChanged |= bits.set(nextHash % bits.bitSize()); } return bitsChanged; } @Override public <T> boolean mightContain(T object, Funnel<? super T> funnel, int numHashFunctions, BitArray bits) { long hash64 = Hashing.murmur3_128().hashObject(object, funnel).asLong(); int hash1 = (int) hash64; int hash2 = (int) (hash64 >>> 32); for (int i = 1; i <= numHashFunctions; i++) { int nextHash = hash1 + i * hash2; if (nextHash < 0) { nextHash = ~nextHash; } if (!bits.get(nextHash % bits.bitSize())) { return false; } } return true; } }; // Note: We use this instead of java.util.BitSet because we need access to the long[] data field static class BitArray { final long[] data; int bitCount; BitArray(long bits) { this(new long[Ints.checkedCast(LongMath.divide(bits, 64, RoundingMode.CEILING))]); } // Used by serialization BitArray(long[] data) { checkArgument(data.length > 0, "data length is zero!"); this.data = data; int bitCount = 0; for (long value : data) { bitCount += Long.bitCount(value); } this.bitCount = bitCount; } /** Returns true if the bit changed value. */ boolean set(int index) { if (!get(index)) { data[index >> 6] |= (1L << index); bitCount++; return true; } return false; } boolean get(int index) { return (data[index >> 6] & (1L << index)) != 0; } /** Number of bits */ int bitSize() { return data.length * Long.SIZE; } /** Number of set bits (1s) */ int bitCount() { return bitCount; } BitArray copy() { return new BitArray(data.clone()); } /** Combines the two BitArrays using bitwise OR. */ void putAll(BitArray array) { checkArgument(data.length == array.data.length, "BitArrays must be of equal length (%s != %s)", data.length, array.data.length); bitCount = 0; for (int i = 0; i < data.length; i++) { data[i] |= array.data[i]; bitCount += Long.bitCount(data[i]); } } @Override public boolean equals(Object o) { if (o instanceof BitArray) { BitArray bitArray = (BitArray) o; return Arrays.equals(data, bitArray.data); } return false; } @Override public int hashCode() { return Arrays.hashCode(data); } } }
zzhhhhh-aw4rwer
guava/src/com/google/common/hash/BloomFilterStrategies.java
Java
asf20
4,694
/* * Copyright (C) 2011 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.common.hash; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; import com.google.common.annotations.Beta; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Objects; import com.google.common.base.Predicate; import com.google.common.hash.BloomFilterStrategies.BitArray; import java.io.Serializable; import javax.annotation.Nullable; /** * A Bloom filter for instances of {@code T}. A Bloom filter offers an approximate containment test * with one-sided error: if it claims that an element is contained in it, this might be in error, * but if it claims that an element is <i>not</i> contained in it, then this is definitely true. * * <p>If you are unfamiliar with Bloom filters, this nice * <a href="http://llimllib.github.com/bloomfilter-tutorial/">tutorial</a> may help you understand * how they work. * * <p>The false positive probability ({@code FPP}) of a bloom filter is defined as the probability * that {@linkplain #mightContain(Object)} will erroneously return {@code true} for an object that * has not actually been put in the {@code BloomFilter}. * * * @param <T> the type of instances that the {@code BloomFilter} accepts * @author Dimitris Andreou * @author Kevin Bourrillion * @since 11.0 */ @Beta public final class BloomFilter<T> implements Predicate<T>, Serializable { /** * A strategy to translate T instances, to {@code numHashFunctions} bit indexes. * * <p>Implementations should be collections of pure functions (i.e. stateless). */ interface Strategy extends java.io.Serializable { /** * Sets {@code numHashFunctions} bits of the given bit array, by hashing a user element. * * <p>Returns whether any bits changed as a result of this operation. */ <T> boolean put(T object, Funnel<? super T> funnel, int numHashFunctions, BitArray bits); /** * Queries {@code numHashFunctions} bits of the given bit array, by hashing a user element; * returns {@code true} if and only if all selected bits are set. */ <T> boolean mightContain( T object, Funnel<? super T> funnel, int numHashFunctions, BitArray bits); /** * Identifier used to encode this strategy, when marshalled as part of a BloomFilter. * Only values in the [-128, 127] range are valid for the compact serial form. * Non-negative values are reserved for enums defined in BloomFilterStrategies; * negative values are reserved for any custom, stateful strategy we may define * (e.g. any kind of strategy that would depend on user input). */ int ordinal(); } /** The bit set of the BloomFilter (not necessarily power of 2!)*/ private final BitArray bits; /** Number of hashes per element */ private final int numHashFunctions; /** The funnel to translate Ts to bytes */ private final Funnel<T> funnel; /** * The strategy we employ to map an element T to {@code numHashFunctions} bit indexes. */ private final Strategy strategy; /** * Creates a BloomFilter. */ private BloomFilter(BitArray bits, int numHashFunctions, Funnel<T> funnel, Strategy strategy) { checkArgument(numHashFunctions > 0, "numHashFunctions (%s) must be > 0", numHashFunctions); checkArgument(numHashFunctions <= 255, "numHashFunctions (%s) must be <= 255", numHashFunctions); this.bits = checkNotNull(bits); this.numHashFunctions = numHashFunctions; this.funnel = checkNotNull(funnel); this.strategy = checkNotNull(strategy); } /** * Creates a new {@code BloomFilter} that's a copy of this instance. The new instance is equal to * this instance but shares no mutable state. * * @since 12.0 */ public BloomFilter<T> copy() { return new BloomFilter<T>(bits.copy(), numHashFunctions, funnel, strategy); } /** * Returns {@code true} if the element <i>might</i> have been put in this Bloom filter, * {@code false} if this is <i>definitely</i> not the case. */ public boolean mightContain(T object) { return strategy.mightContain(object, funnel, numHashFunctions, bits); } /** * @deprecated Provided only to satisfy the {@link Predicate} interface; use {@link #mightContain} * instead. */ @Deprecated @Override public boolean apply(T input) { return mightContain(input); } /** * Puts an element into this {@code BloomFilter}. Ensures that subsequent invocations of * {@link #mightContain(Object)} with the same element will always return {@code true}. * * @return true if the bloom filter's bits changed as a result of this operation. If the bits * changed, this is <i>definitely</i> the first time {@code object} has been added to the * filter. If the bits haven't changed, this <i>might</i> be the first time {@code object} * has been added to the filter. Note that {@code put(t)} always returns the * <i>opposite</i> result to what {@code mightContain(t)} would have returned at the time * it is called." * @since 12.0 (present in 11.0 with {@code void} return type}) */ public boolean put(T object) { return strategy.put(object, funnel, numHashFunctions, bits); } /** * Returns the probability that {@linkplain #mightContain(Object)} will erroneously return * {@code true} for an object that has not actually been put in the {@code BloomFilter}. * * <p>Ideally, this number should be close to the {@code fpp} parameter * passed in {@linkplain #create(Funnel, int, double)}, or smaller. If it is * significantly higher, it is usually the case that too many elements (more than * expected) have been put in the {@code BloomFilter}, degenerating it. * * @since 14.0 (since 11.0 as expectedFalsePositiveProbability()) */ public double expectedFpp() { // You down with FPP? (Yeah you know me!) Who's down with FPP? (Every last homie!) return Math.pow((double) bits.bitCount() / bitSize(), numHashFunctions); } /** * Returns the number of bits in the underlying bit array. */ @VisibleForTesting long bitSize() { return bits.bitSize(); } /** * Determines whether a given bloom filter is compatible with this bloom filter. For two * bloom filters to be compatible, they must: * * <ul> * <li>not be the same instance * <li>have the same number of hash functions * <li>have the same bit size * <li>have the same strategy * <li>have equal funnels * <ul> * * @param that The bloom filter to check for compatibility. * @since 15.0 */ public boolean isCompatible(BloomFilter<T> that) { checkNotNull(that); return (this != that) && (this.numHashFunctions == that.numHashFunctions) && (this.bitSize() == that.bitSize()) && (this.strategy.equals(that.strategy)) && (this.funnel.equals(that.funnel)); } /** * Combines this bloom filter with another bloom filter by performing a bitwise OR of the * underlying data. The mutations happen to <b>this</b> instance. Callers must ensure the * bloom filters are appropriately sized to avoid saturating them. * * @param that The bloom filter to combine this bloom filter with. It is not mutated. * @throws IllegalArgumentException if {@code isCompatible(that) == false} * * @since 15.0 */ public void putAll(BloomFilter<T> that) { checkNotNull(that); checkArgument(this != that, "Cannot combine a BloomFilter with itself."); checkArgument(this.numHashFunctions == that.numHashFunctions, "BloomFilters must have the same number of hash functions (%s != %s)", this.numHashFunctions, that.numHashFunctions); checkArgument(this.bitSize() == that.bitSize(), "BloomFilters must have the same size underlying bit arrays (%s != %s)", this.bitSize(), that.bitSize()); checkArgument(this.strategy.equals(that.strategy), "BloomFilters must have equal strategies (%s != %s)", this.strategy, that.strategy); checkArgument(this.funnel.equals(that.funnel), "BloomFilters must have equal funnels (%s != %s)", this.funnel, that.funnel); this.bits.putAll(that.bits); } @Override public boolean equals(@Nullable Object object) { if (object == this) { return true; } if (object instanceof BloomFilter) { BloomFilter<?> that = (BloomFilter<?>) object; return this.numHashFunctions == that.numHashFunctions && this.funnel.equals(that.funnel) && this.bits.equals(that.bits) && this.strategy.equals(that.strategy); } return false; } @Override public int hashCode() { return Objects.hashCode(numHashFunctions, funnel, strategy, bits); } /** * Creates a {@link BloomFilter BloomFilter<T>} with the expected number of * insertions and expected false positive probability. * * <p>Note that overflowing a {@code BloomFilter} with significantly more elements * than specified, will result in its saturation, and a sharp deterioration of its * false positive probability. * * <p>The constructed {@code BloomFilter<T>} will be serializable if the provided * {@code Funnel<T>} is. * * <p>It is recommended that the funnel be implemented as a Java enum. This has the * benefit of ensuring proper serialization and deserialization, which is important * since {@link #equals} also relies on object identity of funnels. * * @param funnel the funnel of T's that the constructed {@code BloomFilter<T>} will use * @param expectedInsertions the number of expected insertions to the constructed * {@code BloomFilter<T>}; must be positive * @param fpp the desired false positive probability (must be positive and less than 1.0) * @return a {@code BloomFilter} */ public static <T> BloomFilter<T> create( Funnel<T> funnel, int expectedInsertions /* n */, double fpp) { checkNotNull(funnel); checkArgument(expectedInsertions >= 0, "Expected insertions (%s) must be >= 0", expectedInsertions); checkArgument(fpp > 0.0, "False positive probability (%s) must be > 0.0", fpp); checkArgument(fpp < 1.0, "False positive probability (%s) must be < 1.0", fpp); if (expectedInsertions == 0) { expectedInsertions = 1; } /* * TODO(user): Put a warning in the javadoc about tiny fpp values, * since the resulting size is proportional to -log(p), but there is not * much of a point after all, e.g. optimalM(1000, 0.0000000000000001) = 76680 * which is less than 10kb. Who cares! */ long numBits = optimalNumOfBits(expectedInsertions, fpp); int numHashFunctions = optimalNumOfHashFunctions(expectedInsertions, numBits); try { return new BloomFilter<T>(new BitArray(numBits), numHashFunctions, funnel, BloomFilterStrategies.MURMUR128_MITZ_32); } catch (IllegalArgumentException e) { throw new IllegalArgumentException("Could not create BloomFilter of " + numBits + " bits", e); } } /** * Creates a {@link BloomFilter BloomFilter<T>} with the expected number of * insertions and a default expected false positive probability of 3%. * * <p>Note that overflowing a {@code BloomFilter} with significantly more elements * than specified, will result in its saturation, and a sharp deterioration of its * false positive probability. * * <p>The constructed {@code BloomFilter<T>} will be serializable if the provided * {@code Funnel<T>} is. * * @param funnel the funnel of T's that the constructed {@code BloomFilter<T>} will use * @param expectedInsertions the number of expected insertions to the constructed * {@code BloomFilter<T>}; must be positive * @return a {@code BloomFilter} */ public static <T> BloomFilter<T> create(Funnel<T> funnel, int expectedInsertions /* n */) { return create(funnel, expectedInsertions, 0.03); // FYI, for 3%, we always get 5 hash functions } /* * Cheat sheet: * * m: total bits * n: expected insertions * b: m/n, bits per insertion * p: expected false positive probability * * 1) Optimal k = b * ln2 * 2) p = (1 - e ^ (-kn/m))^k * 3) For optimal k: p = 2 ^ (-k) ~= 0.6185^b * 4) For optimal k: m = -nlnp / ((ln2) ^ 2) */ /** * Computes the optimal k (number of hashes per element inserted in Bloom filter), given the * expected insertions and total number of bits in the Bloom filter. * * See http://en.wikipedia.org/wiki/File:Bloom_filter_fp_probability.svg for the formula. * * @param n expected insertions (must be positive) * @param m total number of bits in Bloom filter (must be positive) */ @VisibleForTesting static int optimalNumOfHashFunctions(long n, long m) { return Math.max(1, (int) Math.round(m / n * Math.log(2))); } /** * Computes m (total bits of Bloom filter) which is expected to achieve, for the specified * expected insertions, the required false positive probability. * * See http://en.wikipedia.org/wiki/Bloom_filter#Probability_of_false_positives for the formula. * * @param n expected insertions (must be positive) * @param p false positive rate (must be 0 < p < 1) */ @VisibleForTesting static long optimalNumOfBits(long n, double p) { if (p == 0) { p = Double.MIN_VALUE; } return (long) (-n * Math.log(p) / (Math.log(2) * Math.log(2))); } private Object writeReplace() { return new SerialForm<T>(this); } private static class SerialForm<T> implements Serializable { final long[] data; final int numHashFunctions; final Funnel<T> funnel; final Strategy strategy; SerialForm(BloomFilter<T> bf) { this.data = bf.bits.data; this.numHashFunctions = bf.numHashFunctions; this.funnel = bf.funnel; this.strategy = bf.strategy; } Object readResolve() { return new BloomFilter<T>(new BitArray(data), numHashFunctions, funnel, strategy); } private static final long serialVersionUID = 1; } }
zzhhhhh-aw4rwer
guava/src/com/google/common/hash/BloomFilter.java
Java
asf20
14,753
/* * Copyright (C) 2011 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.common.hash; import com.google.common.annotations.Beta; import java.nio.charset.Charset; /** * A {@link PrimitiveSink} that can compute a hash code after reading the input. Each hasher should * translate all multibyte values ({@link #putInt(int)}, {@link #putLong(long)}, etc) to bytes * in little-endian order. * * <p><b>Warning:</b> The result of calling any methods after calling {@link #hash} is undefined. * * <p><b>Warning:</b> Using a specific character encoding when hashing a {@link CharSequence} with * {@link #putString(CharSequence, Charset)} is generally only useful for cross-language * compatibility (otherwise prefer {@link #putUnencodedChars}). However, the character encodings * must be identical across languages. Also beware that {@link Charset} definitions may occasionally * change between Java releases. * * <p><b>Warning:</b> Chunks of data that are put into the {@link Hasher} are not delimited. * The resulting {@link HashCode} is dependent only on the bytes inserted, and the order in which * they were inserted, not how those bytes were chunked into discrete put() operations. For example, * the following three expressions all generate colliding hash codes: <pre> {@code * * newHasher().putByte(b1).putByte(b2).putByte(b3).hash() * newHasher().putByte(b1).putBytes(new byte[] { b2, b3 }).hash() * newHasher().putBytes(new byte[] { b1, b2, b3 }).hash()}</pre> * * <p>If you wish to avoid this, you should either prepend or append the size of each chunk. Keep in * mind that when dealing with char sequences, the encoded form of two concatenated char sequences * is not equivalent to the concatenation of their encoded form. Therefore, * {@link #putString(CharSequence, Charset)} should only be used consistently with <i>complete</i> * sequences and not broken into chunks. * * @author Kevin Bourrillion * @since 11.0 */ @Beta public interface Hasher extends PrimitiveSink { @Override Hasher putByte(byte b); @Override Hasher putBytes(byte[] bytes); @Override Hasher putBytes(byte[] bytes, int off, int len); @Override Hasher putShort(short s); @Override Hasher putInt(int i); @Override Hasher putLong(long l); /** * Equivalent to {@code putInt(Float.floatToRawIntBits(f))}. */ @Override Hasher putFloat(float f); /** * Equivalent to {@code putLong(Double.doubleToRawLongBits(d))}. */ @Override Hasher putDouble(double d); /** * Equivalent to {@code putByte(b ? (byte) 1 : (byte) 0)}. */ @Override Hasher putBoolean(boolean b); @Override Hasher putChar(char c); /** * Equivalent to processing each {@code char} value in the {@code CharSequence}, in order. * The input must not be updated while this method is in progress. * * @since 15.0 (since 11.0 as putString(CharSequence)). */ @Override Hasher putUnencodedChars(CharSequence charSequence); /** * Equivalent to {@code putBytes(charSequence.toString().getBytes(charset))}. */ @Override Hasher putString(CharSequence charSequence, Charset charset); /** * A simple convenience for {@code funnel.funnel(object, this)}. */ <T> Hasher putObject(T instance, Funnel<? super T> funnel); /** * Computes a hash code based on the data that have been provided to this hasher. The result is * unspecified if this method is called more than once on the same instance. */ HashCode hash(); }
zzhhhhh-aw4rwer
guava/src/com/google/common/hash/Hasher.java
Java
asf20
4,015
/* * Copyright (C) 2011 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.common.hash; import com.google.common.annotations.Beta; import java.nio.charset.Charset; /** * An object which can receive a stream of primitive values. * * @author Kevin Bourrillion * @since 12.0 (in 11.0 as {@code Sink}) */ @Beta public interface PrimitiveSink { /** * Puts a byte into this sink. * * @param b a byte * @return this instance */ PrimitiveSink putByte(byte b); /** * Puts an array of bytes into this sink. * * @param bytes a byte array * @return this instance */ PrimitiveSink putBytes(byte[] bytes); /** * Puts a chunk of an array of bytes into this sink. {@code bytes[off]} is the first byte written, * {@code bytes[off + len - 1]} is the last. * * @param bytes a byte array * @param off the start offset in the array * @param len the number of bytes to write * @return this instance * @throws IndexOutOfBoundsException if {@code off < 0} or {@code off + len > bytes.length} or * {@code len < 0} */ PrimitiveSink putBytes(byte[] bytes, int off, int len); /** * Puts a short into this sink. */ PrimitiveSink putShort(short s); /** * Puts an int into this sink. */ PrimitiveSink putInt(int i); /** * Puts a long into this sink. */ PrimitiveSink putLong(long l); /** * Puts a float into this sink. */ PrimitiveSink putFloat(float f); /** * Puts a double into this sink. */ PrimitiveSink putDouble(double d); /** * Puts a boolean into this sink. */ PrimitiveSink putBoolean(boolean b); /** * Puts a character into this sink. */ PrimitiveSink putChar(char c); /** * Puts each 16-bit code unit from the {@link CharSequence} into this sink. * * @since 15.0 (since 11.0 as putString(CharSequence)) */ PrimitiveSink putUnencodedChars(CharSequence charSequence); /** * Puts a string into this sink using the given charset. */ PrimitiveSink putString(CharSequence charSequence, Charset charset); }
zzhhhhh-aw4rwer
guava/src/com/google/common/hash/PrimitiveSink.java
Java
asf20
2,609
/* * Copyright (C) 2012 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.hash; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Preconditions.checkPositionIndexes; import com.google.common.primitives.Chars; import com.google.common.primitives.Ints; import com.google.common.primitives.Longs; import com.google.common.primitives.Shorts; import java.nio.ByteBuffer; import java.nio.ByteOrder; /** * Abstract {@link Hasher} that handles converting primitives to bytes using a scratch {@code * ByteBuffer} and streams all bytes to a sink to compute the hash. * * @author Colin Decker */ abstract class AbstractByteHasher extends AbstractHasher { private final ByteBuffer scratch = ByteBuffer.allocate(8).order(ByteOrder.LITTLE_ENDIAN); /** * Updates this hasher with the given byte. */ protected abstract void update(byte b); /** * Updates this hasher with the given bytes. */ protected void update(byte[] b) { update(b, 0, b.length); } /** * Updates this hasher with {@code len} bytes starting at {@code off} in the given buffer. */ protected void update(byte[] b, int off, int len) { for (int i = off; i < off + len; i++) { update(b[i]); } } @Override public Hasher putByte(byte b) { update(b); return this; } @Override public Hasher putBytes(byte[] bytes) { checkNotNull(bytes); update(bytes); return this; } @Override public Hasher putBytes(byte[] bytes, int off, int len) { checkPositionIndexes(off, off + len, bytes.length); update(bytes, off, len); return this; } /** * Updates the sink with the given number of bytes from the buffer. */ private Hasher update(int bytes) { try { update(scratch.array(), 0, bytes); } finally { scratch.clear(); } return this; } @Override public Hasher putShort(short s) { scratch.putShort(s); return update(Shorts.BYTES); } @Override public Hasher putInt(int i) { scratch.putInt(i); return update(Ints.BYTES); } @Override public Hasher putLong(long l) { scratch.putLong(l); return update(Longs.BYTES); } @Override public Hasher putChar(char c) { scratch.putChar(c); return update(Chars.BYTES); } @Override public <T> Hasher putObject(T instance, Funnel<? super T> funnel) { funnel.funnel(instance, this); return this; } }
zzhhhhh-aw4rwer
guava/src/com/google/common/hash/AbstractByteHasher.java
Java
asf20
3,001
/* * Copyright (C) 2011 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ /* * MurmurHash3 was written by Austin Appleby, and is placed in the public * domain. The author hereby disclaims copyright to this source code. */ /* * Source: * http://code.google.com/p/smhasher/source/browse/trunk/MurmurHash3.cpp * (Modified to adapt to Guava coding conventions and to use the HashFunction interface) */ package com.google.common.hash; import static com.google.common.primitives.UnsignedBytes.toInt; import com.google.common.primitives.Chars; import com.google.common.primitives.Ints; import com.google.common.primitives.Longs; import java.io.Serializable; import java.nio.ByteBuffer; import javax.annotation.Nullable; /** * See http://smhasher.googlecode.com/svn/trunk/MurmurHash3.cpp * MurmurHash3_x86_32 * * @author Austin Appleby * @author Dimitris Andreou * @author Kurt Alfred Kluever */ final class Murmur3_32HashFunction extends AbstractStreamingHashFunction implements Serializable { private static final int C1 = 0xcc9e2d51; private static final int C2 = 0x1b873593; private final int seed; Murmur3_32HashFunction(int seed) { this.seed = seed; } @Override public int bits() { return 32; } @Override public Hasher newHasher() { return new Murmur3_32Hasher(seed); } @Override public String toString() { return "Hashing.murmur3_32(" + seed + ")"; } @Override public boolean equals(@Nullable Object object) { if (object instanceof Murmur3_32HashFunction) { Murmur3_32HashFunction other = (Murmur3_32HashFunction) object; return seed == other.seed; } return false; } @Override public int hashCode() { return getClass().hashCode() ^ seed; } @Override public HashCode hashInt(int input) { int k1 = mixK1(input); int h1 = mixH1(seed, k1); return fmix(h1, Ints.BYTES); } @Override public HashCode hashLong(long input) { int low = (int) input; int high = (int) (input >>> 32); int k1 = mixK1(low); int h1 = mixH1(seed, k1); k1 = mixK1(high); h1 = mixH1(h1, k1); return fmix(h1, Longs.BYTES); } // TODO(user): Maybe implement #hashBytes instead? @Override public HashCode hashUnencodedChars(CharSequence input) { int h1 = seed; // step through the CharSequence 2 chars at a time for (int i = 1; i < input.length(); i += 2) { int k1 = input.charAt(i - 1) | (input.charAt(i) << 16); k1 = mixK1(k1); h1 = mixH1(h1, k1); } // deal with any remaining characters if ((input.length() & 1) == 1) { int k1 = input.charAt(input.length() - 1); k1 = mixK1(k1); h1 ^= k1; } return fmix(h1, Chars.BYTES * input.length()); } private static int mixK1(int k1) { k1 *= C1; k1 = Integer.rotateLeft(k1, 15); k1 *= C2; return k1; } private static int mixH1(int h1, int k1) { h1 ^= k1; h1 = Integer.rotateLeft(h1, 13); h1 = h1 * 5 + 0xe6546b64; return h1; } // Finalization mix - force all bits of a hash block to avalanche private static HashCode fmix(int h1, int length) { h1 ^= length; h1 ^= h1 >>> 16; h1 *= 0x85ebca6b; h1 ^= h1 >>> 13; h1 *= 0xc2b2ae35; h1 ^= h1 >>> 16; return HashCode.fromInt(h1); } private static final class Murmur3_32Hasher extends AbstractStreamingHasher { private static final int CHUNK_SIZE = 4; private int h1; private int length; Murmur3_32Hasher(int seed) { super(CHUNK_SIZE); this.h1 = seed; this.length = 0; } @Override protected void process(ByteBuffer bb) { int k1 = Murmur3_32HashFunction.mixK1(bb.getInt()); h1 = Murmur3_32HashFunction.mixH1(h1, k1); length += CHUNK_SIZE; } @Override protected void processRemaining(ByteBuffer bb) { length += bb.remaining(); int k1 = 0; for (int i = 0; bb.hasRemaining(); i += 8) { k1 ^= toInt(bb.get()) << i; } h1 ^= Murmur3_32HashFunction.mixK1(k1); } @Override public HashCode makeHash() { return Murmur3_32HashFunction.fmix(h1, length); } } private static final long serialVersionUID = 0L; }
zzhhhhh-aw4rwer
guava/src/com/google/common/hash/Murmur3_32HashFunction.java
Java
asf20
4,716
/* * Copyright (C) 2011 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.common.hash; import static com.google.common.base.Preconditions.checkArgument; import com.google.common.annotations.Beta; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Supplier; import java.security.MessageDigest; import java.util.Iterator; import java.util.zip.Adler32; import java.util.zip.CRC32; import java.util.zip.Checksum; import javax.annotation.Nullable; /** * Static methods to obtain {@link HashFunction} instances, and other static hashing-related * utilities. * * <p>A comparison of the various hash functions can be found * <a href="http://goo.gl/jS7HH">here</a>. * * @author Kevin Bourrillion * @author Dimitris Andreou * @author Kurt Alfred Kluever * @since 11.0 */ @Beta public final class Hashing { /** * Returns a general-purpose, <b>temporary-use</b>, non-cryptographic hash function. The algorithm * the returned function implements is unspecified and subject to change without notice. * * <p><b>Warning:</b> a new random seed for these functions is chosen each time the {@code * Hashing} class is loaded. <b>Do not use this method</b> if hash codes may escape the current * process in any way, for example being sent over RPC, or saved to disk. * * <p>Repeated calls to this method on the same loaded {@code Hashing} class, using the same value * for {@code minimumBits}, will return identically-behaving {@link HashFunction} instances. * * @param minimumBits a positive integer (can be arbitrarily large) * @return a hash function, described above, that produces hash codes of length {@code * minimumBits} or greater */ public static HashFunction goodFastHash(int minimumBits) { int bits = checkPositiveAndMakeMultipleOf32(minimumBits); if (bits == 32) { return Murmur3_32Holder.GOOD_FAST_HASH_FUNCTION_32; } if (bits <= 128) { return Murmur3_128Holder.GOOD_FAST_HASH_FUNCTION_128; } // Otherwise, join together some 128-bit murmur3s int hashFunctionsNeeded = (bits + 127) / 128; HashFunction[] hashFunctions = new HashFunction[hashFunctionsNeeded]; hashFunctions[0] = Murmur3_128Holder.GOOD_FAST_HASH_FUNCTION_128; int seed = GOOD_FAST_HASH_SEED; for (int i = 1; i < hashFunctionsNeeded; i++) { seed += 1500450271; // a prime; shouldn't matter hashFunctions[i] = murmur3_128(seed); } return new ConcatenatedHashFunction(hashFunctions); } /** * Used to randomize {@link #goodFastHash} instances, so that programs which persist anything * dependent on the hash codes they produce will fail sooner. */ private static final int GOOD_FAST_HASH_SEED = (int) System.currentTimeMillis(); /** * Returns a hash function implementing the * <a href="http://smhasher.googlecode.com/svn/trunk/MurmurHash3.cpp"> * 32-bit murmur3 algorithm, x86 variant</a> (little-endian variant), * using the given seed value. * * <p>The exact C++ equivalent is the MurmurHash3_x86_32 function (Murmur3A). */ public static HashFunction murmur3_32(int seed) { return new Murmur3_32HashFunction(seed); } /** * Returns a hash function implementing the * <a href="http://smhasher.googlecode.com/svn/trunk/MurmurHash3.cpp"> * 32-bit murmur3 algorithm, x86 variant</a> (little-endian variant), * using a seed value of zero. * * <p>The exact C++ equivalent is the MurmurHash3_x86_32 function (Murmur3A). */ public static HashFunction murmur3_32() { return Murmur3_32Holder.MURMUR3_32; } private static class Murmur3_32Holder { static final HashFunction MURMUR3_32 = new Murmur3_32HashFunction(0); /** Returned by {@link #goodFastHash} when {@code minimumBits <= 32}. */ static final HashFunction GOOD_FAST_HASH_FUNCTION_32 = murmur3_32(GOOD_FAST_HASH_SEED); } /** * Returns a hash function implementing the * <a href="http://smhasher.googlecode.com/svn/trunk/MurmurHash3.cpp"> * 128-bit murmur3 algorithm, x64 variant</a> (little-endian variant), * using the given seed value. * * <p>The exact C++ equivalent is the MurmurHash3_x64_128 function (Murmur3F). */ public static HashFunction murmur3_128(int seed) { return new Murmur3_128HashFunction(seed); } /** * Returns a hash function implementing the * <a href="http://smhasher.googlecode.com/svn/trunk/MurmurHash3.cpp"> * 128-bit murmur3 algorithm, x64 variant</a> (little-endian variant), * using a seed value of zero. * * <p>The exact C++ equivalent is the MurmurHash3_x64_128 function (Murmur3F). */ public static HashFunction murmur3_128() { return Murmur3_128Holder.MURMUR3_128; } private static class Murmur3_128Holder { static final HashFunction MURMUR3_128 = new Murmur3_128HashFunction(0); /** Returned by {@link #goodFastHash} when {@code 32 < minimumBits <= 128}. */ static final HashFunction GOOD_FAST_HASH_FUNCTION_128 = murmur3_128(GOOD_FAST_HASH_SEED); } /** * Returns a hash function implementing the * <a href="https://131002.net/siphash/">64-bit SipHash-2-4 algorithm</a> * using a seed value of {@code k = 00 01 02 ...}. * * @since 15.0 */ public static HashFunction sipHash24() { return SipHash24Holder.SIP_HASH_24; } private static class SipHash24Holder { static final HashFunction SIP_HASH_24 = new SipHashFunction(2, 4, 0x0706050403020100L, 0x0f0e0d0c0b0a0908L); } /** * Returns a hash function implementing the * <a href="https://131002.net/siphash/">64-bit SipHash-2-4 algorithm</a> * using the given seed. * * @since 15.0 */ public static HashFunction sipHash24(long k0, long k1) { return new SipHashFunction(2, 4, k0, k1); } /** * Returns a hash function implementing the MD5 hash algorithm (128 hash bits) by delegating to * the MD5 {@link MessageDigest}. */ public static HashFunction md5() { return Md5Holder.MD5; } private static class Md5Holder { static final HashFunction MD5 = new MessageDigestHashFunction("MD5", "Hashing.md5()"); } /** * Returns a hash function implementing the SHA-1 algorithm (160 hash bits) by delegating to the * SHA-1 {@link MessageDigest}. */ public static HashFunction sha1() { return Sha1Holder.SHA_1; } private static class Sha1Holder { static final HashFunction SHA_1 = new MessageDigestHashFunction("SHA-1", "Hashing.sha1()"); } /** * Returns a hash function implementing the SHA-256 algorithm (256 hash bits) by delegating to * the SHA-256 {@link MessageDigest}. */ public static HashFunction sha256() { return Sha256Holder.SHA_256; } private static class Sha256Holder { static final HashFunction SHA_256 = new MessageDigestHashFunction("SHA-256", "Hashing.sha256()"); } /** * Returns a hash function implementing the SHA-512 algorithm (512 hash bits) by delegating to the * SHA-512 {@link MessageDigest}. */ public static HashFunction sha512() { return Sha512Holder.SHA_512; } private static class Sha512Holder { static final HashFunction SHA_512 = new MessageDigestHashFunction("SHA-512", "Hashing.sha512()"); } /** * Returns a hash function implementing the CRC-32 checksum algorithm (32 hash bits) by delegating * to the {@link CRC32} {@link Checksum}. * * <p>To get the {@code long} value equivalent to {@link Checksum#getValue()} for a * {@code HashCode} produced by this function, use {@link HashCode#padToLong()}. * * @since 14.0 */ public static HashFunction crc32() { return Crc32Holder.CRC_32; } private static class Crc32Holder { static final HashFunction CRC_32 = checksumHashFunction(ChecksumType.CRC_32, "Hashing.crc32()"); } /** * Returns a hash function implementing the Adler-32 checksum algorithm (32 hash bits) by * delegating to the {@link Adler32} {@link Checksum}. * * <p>To get the {@code long} value equivalent to {@link Checksum#getValue()} for a * {@code HashCode} produced by this function, use {@link HashCode#padToLong()}. * * @since 14.0 */ public static HashFunction adler32() { return Adler32Holder.ADLER_32; } private static class Adler32Holder { static final HashFunction ADLER_32 = checksumHashFunction(ChecksumType.ADLER_32, "Hashing.adler32()"); } private static HashFunction checksumHashFunction(ChecksumType type, String toString) { return new ChecksumHashFunction(type, type.bits, toString); } enum ChecksumType implements Supplier<Checksum> { CRC_32(32) { @Override public Checksum get() { return new CRC32(); } }, ADLER_32(32) { @Override public Checksum get() { return new Adler32(); } }; private final int bits; ChecksumType(int bits) { this.bits = bits; } @Override public abstract Checksum get(); } /** * Assigns to {@code hashCode} a "bucket" in the range {@code [0, buckets)}, in a uniform * manner that minimizes the need for remapping as {@code buckets} grows. That is, * {@code consistentHash(h, n)} equals: * * <ul> * <li>{@code n - 1}, with approximate probability {@code 1/n} * <li>{@code consistentHash(h, n - 1)}, otherwise (probability {@code 1 - 1/n}) * </ul> * * <p>See the <a href="http://en.wikipedia.org/wiki/Consistent_hashing">wikipedia * article on consistent hashing</a> for more information. */ public static int consistentHash(HashCode hashCode, int buckets) { return consistentHash(hashCode.padToLong(), buckets); } /** * Assigns to {@code input} a "bucket" in the range {@code [0, buckets)}, in a uniform * manner that minimizes the need for remapping as {@code buckets} grows. That is, * {@code consistentHash(h, n)} equals: * * <ul> * <li>{@code n - 1}, with approximate probability {@code 1/n} * <li>{@code consistentHash(h, n - 1)}, otherwise (probability {@code 1 - 1/n}) * </ul> * * <p>See the <a href="http://en.wikipedia.org/wiki/Consistent_hashing">wikipedia * article on consistent hashing</a> for more information. */ public static int consistentHash(long input, int buckets) { checkArgument(buckets > 0, "buckets must be positive: %s", buckets); LinearCongruentialGenerator generator = new LinearCongruentialGenerator(input); int candidate = 0; int next; // Jump from bucket to bucket until we go out of range while (true) { next = (int) ((candidate + 1) / generator.nextDouble()); if (next >= 0 && next < buckets) { candidate = next; } else { return candidate; } } } /** * Returns a hash code, having the same bit length as each of the input hash codes, * that combines the information of these hash codes in an ordered fashion. That * is, whenever two equal hash codes are produced by two calls to this method, it * is <i>as likely as possible</i> that each was computed from the <i>same</i> * input hash codes in the <i>same</i> order. * * @throws IllegalArgumentException if {@code hashCodes} is empty, or the hash codes * do not all have the same bit length */ public static HashCode combineOrdered(Iterable<HashCode> hashCodes) { Iterator<HashCode> iterator = hashCodes.iterator(); checkArgument(iterator.hasNext(), "Must be at least 1 hash code to combine."); int bits = iterator.next().bits(); byte[] resultBytes = new byte[bits / 8]; for (HashCode hashCode : hashCodes) { byte[] nextBytes = hashCode.asBytes(); checkArgument(nextBytes.length == resultBytes.length, "All hashcodes must have the same bit length."); for (int i = 0; i < nextBytes.length; i++) { resultBytes[i] = (byte) (resultBytes[i] * 37 ^ nextBytes[i]); } } return HashCode.fromBytesNoCopy(resultBytes); } /** * Returns a hash code, having the same bit length as each of the input hash codes, * that combines the information of these hash codes in an unordered fashion. That * is, whenever two equal hash codes are produced by two calls to this method, it * is <i>as likely as possible</i> that each was computed from the <i>same</i> * input hash codes in <i>some</i> order. * * @throws IllegalArgumentException if {@code hashCodes} is empty, or the hash codes * do not all have the same bit length */ public static HashCode combineUnordered(Iterable<HashCode> hashCodes) { Iterator<HashCode> iterator = hashCodes.iterator(); checkArgument(iterator.hasNext(), "Must be at least 1 hash code to combine."); byte[] resultBytes = new byte[iterator.next().bits() / 8]; for (HashCode hashCode : hashCodes) { byte[] nextBytes = hashCode.asBytes(); checkArgument(nextBytes.length == resultBytes.length, "All hashcodes must have the same bit length."); for (int i = 0; i < nextBytes.length; i++) { resultBytes[i] += nextBytes[i]; } } return HashCode.fromBytesNoCopy(resultBytes); } /** * Checks that the passed argument is positive, and ceils it to a multiple of 32. */ static int checkPositiveAndMakeMultipleOf32(int bits) { checkArgument(bits > 0, "Number of bits must be positive"); return (bits + 31) & ~31; } // TODO(kevinb): Maybe expose this class via a static Hashing method? @VisibleForTesting static final class ConcatenatedHashFunction extends AbstractCompositeHashFunction { private final int bits; ConcatenatedHashFunction(HashFunction... functions) { super(functions); int bitSum = 0; for (HashFunction function : functions) { bitSum += function.bits(); } this.bits = bitSum; } @Override HashCode makeHash(Hasher[] hashers) { byte[] bytes = new byte[bits / 8]; int i = 0; for (Hasher hasher : hashers) { HashCode newHash = hasher.hash(); i += newHash.writeBytesTo(bytes, i, newHash.bits() / 8); } return HashCode.fromBytesNoCopy(bytes); } @Override public int bits() { return bits; } @Override public boolean equals(@Nullable Object object) { if (object instanceof ConcatenatedHashFunction) { ConcatenatedHashFunction other = (ConcatenatedHashFunction) object; if (bits != other.bits || functions.length != other.functions.length) { return false; } for (int i = 0; i < functions.length; i++) { if (!functions[i].equals(other.functions[i])) { return false; } } return true; } return false; } @Override public int hashCode() { int hash = bits; for (HashFunction function : functions) { hash ^= function.hashCode(); } return hash; } } /** * Linear CongruentialGenerator to use for consistent hashing. * See http://en.wikipedia.org/wiki/Linear_congruential_generator */ private static final class LinearCongruentialGenerator { private long state; public LinearCongruentialGenerator(long seed) { this.state = seed; } public double nextDouble() { state = 2862933555777941757L * state + 1; return ((double) ((int) (state >>> 33) + 1)) / (0x1.0p31); } } private Hashing() {} }
zzhhhhh-aw4rwer
guava/src/com/google/common/hash/Hashing.java
Java
asf20
16,000
/* * Copyright (C) 2011 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.hash; import com.google.common.base.Preconditions; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.nio.charset.Charset; /** * Skeleton implementation of {@link HashFunction}, appropriate for non-streaming algorithms. * All the hash computation done using {@linkplain #newHasher()} are delegated to the {@linkplain * #hashBytes(byte[], int, int)} method. * * @author Dimitris Andreou */ abstract class AbstractNonStreamingHashFunction implements HashFunction { @Override public Hasher newHasher() { return new BufferingHasher(32); } @Override public Hasher newHasher(int expectedInputSize) { Preconditions.checkArgument(expectedInputSize >= 0); return new BufferingHasher(expectedInputSize); } @Override public <T> HashCode hashObject(T instance, Funnel<? super T> funnel) { return newHasher().putObject(instance, funnel).hash(); } @Override public HashCode hashUnencodedChars(CharSequence input) { int len = input.length(); Hasher hasher = newHasher(len * 2); for (int i = 0; i < len; i++) { hasher.putChar(input.charAt(i)); } return hasher.hash(); } @Override public HashCode hashString(CharSequence input, Charset charset) { return hashBytes(input.toString().getBytes(charset)); } @Override public HashCode hashInt(int input) { return newHasher(4).putInt(input).hash(); } @Override public HashCode hashLong(long input) { return newHasher(8).putLong(input).hash(); } @Override public HashCode hashBytes(byte[] input) { return hashBytes(input, 0, input.length); } /** * In-memory stream-based implementation of Hasher. */ private final class BufferingHasher extends AbstractHasher { final ExposedByteArrayOutputStream stream; static final int BOTTOM_BYTE = 0xFF; BufferingHasher(int expectedInputSize) { this.stream = new ExposedByteArrayOutputStream(expectedInputSize); } @Override public Hasher putByte(byte b) { stream.write(b); return this; } @Override public Hasher putBytes(byte[] bytes) { try { stream.write(bytes); } catch (IOException e) { throw new RuntimeException(e); } return this; } @Override public Hasher putBytes(byte[] bytes, int off, int len) { stream.write(bytes, off, len); return this; } @Override public Hasher putShort(short s) { stream.write(s & BOTTOM_BYTE); stream.write((s >>> 8) & BOTTOM_BYTE); return this; } @Override public Hasher putInt(int i) { stream.write(i & BOTTOM_BYTE); stream.write((i >>> 8) & BOTTOM_BYTE); stream.write((i >>> 16) & BOTTOM_BYTE); stream.write((i >>> 24) & BOTTOM_BYTE); return this; } @Override public Hasher putLong(long l) { for (int i = 0; i < 64; i += 8) { stream.write((byte) ((l >>> i) & BOTTOM_BYTE)); } return this; } @Override public Hasher putChar(char c) { stream.write(c & BOTTOM_BYTE); stream.write((c >>> 8) & BOTTOM_BYTE); return this; } @Override public <T> Hasher putObject(T instance, Funnel<? super T> funnel) { funnel.funnel(instance, this); return this; } @Override public HashCode hash() { return hashBytes(stream.byteArray(), 0, stream.length()); } } // Just to access the byte[] without introducing an unnecessary copy private static final class ExposedByteArrayOutputStream extends ByteArrayOutputStream { ExposedByteArrayOutputStream(int expectedInputSize) { super(expectedInputSize); } byte[] byteArray() { return buf; } int length() { return count; } } }
zzhhhhh-aw4rwer
guava/src/com/google/common/hash/AbstractNonStreamingHashFunction.java
Java
asf20
4,387
/* * Copyright (C) 2011 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.common.hash; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Preconditions.checkState; import java.io.Serializable; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.Arrays; /** * {@link HashFunction} adapter for {@link MessageDigest} instances. * * @author Kevin Bourrillion * @author Dimitris Andreou */ final class MessageDigestHashFunction extends AbstractStreamingHashFunction implements Serializable { private final MessageDigest prototype; private final int bytes; private final boolean supportsClone; private final String toString; MessageDigestHashFunction(String algorithmName, String toString) { this.prototype = getMessageDigest(algorithmName); this.bytes = prototype.getDigestLength(); this.toString = checkNotNull(toString); this.supportsClone = supportsClone(); } MessageDigestHashFunction(String algorithmName, int bytes, String toString) { this.toString = checkNotNull(toString); this.prototype = getMessageDigest(algorithmName); int maxLength = prototype.getDigestLength(); checkArgument(bytes >= 4 && bytes <= maxLength, "bytes (%s) must be >= 4 and < %s", bytes, maxLength); this.bytes = bytes; this.supportsClone = supportsClone(); } private boolean supportsClone() { try { prototype.clone(); return true; } catch (CloneNotSupportedException e) { return false; } } @Override public int bits() { return bytes * Byte.SIZE; } @Override public String toString() { return toString; } private static MessageDigest getMessageDigest(String algorithmName) { try { return MessageDigest.getInstance(algorithmName); } catch (NoSuchAlgorithmException e) { throw new AssertionError(e); } } @Override public Hasher newHasher() { if (supportsClone) { try { return new MessageDigestHasher((MessageDigest) prototype.clone(), bytes); } catch (CloneNotSupportedException e) { // falls through } } return new MessageDigestHasher(getMessageDigest(prototype.getAlgorithm()), bytes); } private static final class SerializedForm implements Serializable { private final String algorithmName; private final int bytes; private final String toString; private SerializedForm(String algorithmName, int bytes, String toString) { this.algorithmName = algorithmName; this.bytes = bytes; this.toString = toString; } private Object readResolve() { return new MessageDigestHashFunction(algorithmName, bytes, toString); } private static final long serialVersionUID = 0; } Object writeReplace() { return new SerializedForm(prototype.getAlgorithm(), bytes, toString); } /** * Hasher that updates a message digest. */ private static final class MessageDigestHasher extends AbstractByteHasher { private final MessageDigest digest; private final int bytes; private boolean done; private MessageDigestHasher(MessageDigest digest, int bytes) { this.digest = digest; this.bytes = bytes; } @Override protected void update(byte b) { checkNotDone(); digest.update(b); } @Override protected void update(byte[] b) { checkNotDone(); digest.update(b); } @Override protected void update(byte[] b, int off, int len) { checkNotDone(); digest.update(b, off, len); } private void checkNotDone() { checkState(!done, "Cannot use Hasher after calling #hash() on it"); } @Override public HashCode hash() { done = true; return (bytes == digest.getDigestLength()) ? HashCode.fromBytesNoCopy(digest.digest()) : HashCode.fromBytesNoCopy(Arrays.copyOf(digest.digest(), bytes)); } } }
zzhhhhh-aw4rwer
guava/src/com/google/common/hash/MessageDigestHashFunction.java
Java
asf20
4,589
/* * Copyright (C) 2011 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.hash; import static com.google.common.base.Preconditions.checkNotNull; import java.nio.charset.Charset; /** * An abstract composition of multiple hash functions. {@linkplain #newHasher()} delegates to the * {@code Hasher} objects of the delegate hash functions, and in the end, they are used by * {@linkplain #makeHash(Hasher[])} that constructs the final {@code HashCode}. * * @author Dimitris Andreou */ abstract class AbstractCompositeHashFunction extends AbstractStreamingHashFunction { final HashFunction[] functions; AbstractCompositeHashFunction(HashFunction... functions) { for (HashFunction function : functions) { checkNotNull(function); } this.functions = functions; } /** * Constructs a {@code HashCode} from the {@code Hasher} objects of the functions. Each of them * has consumed the entire input and they are ready to output a {@code HashCode}. The order of * the hashers are the same order as the functions given to the constructor. */ // this could be cleaner if it passed HashCode[], but that would create yet another array... /* protected */ abstract HashCode makeHash(Hasher[] hashers); @Override public Hasher newHasher() { final Hasher[] hashers = new Hasher[functions.length]; for (int i = 0; i < hashers.length; i++) { hashers[i] = functions[i].newHasher(); } return new Hasher() { @Override public Hasher putByte(byte b) { for (Hasher hasher : hashers) { hasher.putByte(b); } return this; } @Override public Hasher putBytes(byte[] bytes) { for (Hasher hasher : hashers) { hasher.putBytes(bytes); } return this; } @Override public Hasher putBytes(byte[] bytes, int off, int len) { for (Hasher hasher : hashers) { hasher.putBytes(bytes, off, len); } return this; } @Override public Hasher putShort(short s) { for (Hasher hasher : hashers) { hasher.putShort(s); } return this; } @Override public Hasher putInt(int i) { for (Hasher hasher : hashers) { hasher.putInt(i); } return this; } @Override public Hasher putLong(long l) { for (Hasher hasher : hashers) { hasher.putLong(l); } return this; } @Override public Hasher putFloat(float f) { for (Hasher hasher : hashers) { hasher.putFloat(f); } return this; } @Override public Hasher putDouble(double d) { for (Hasher hasher : hashers) { hasher.putDouble(d); } return this; } @Override public Hasher putBoolean(boolean b) { for (Hasher hasher : hashers) { hasher.putBoolean(b); } return this; } @Override public Hasher putChar(char c) { for (Hasher hasher : hashers) { hasher.putChar(c); } return this; } @Override public Hasher putUnencodedChars(CharSequence chars) { for (Hasher hasher : hashers) { hasher.putUnencodedChars(chars); } return this; } @Override public Hasher putString(CharSequence chars, Charset charset) { for (Hasher hasher : hashers) { hasher.putString(chars, charset); } return this; } @Override public <T> Hasher putObject(T instance, Funnel<? super T> funnel) { for (Hasher hasher : hashers) { hasher.putObject(instance, funnel); } return this; } @Override public HashCode hash() { return makeHash(hashers); } }; } private static final long serialVersionUID = 0L; }
zzhhhhh-aw4rwer
guava/src/com/google/common/hash/AbstractCompositeHashFunction.java
Java
asf20
4,408
/* * Copyright (C) 2013 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.common.hash; import static com.google.common.base.Preconditions.checkNotNull; import com.google.common.annotations.Beta; import java.io.FilterInputStream; import java.io.IOException; import java.io.InputStream; /** * An {@link InputStream} that maintains a hash of the data read from it. * * @author Qian Huang * @since 16.0 */ @Beta public final class HashingInputStream extends FilterInputStream { private final Hasher hasher; /** * Creates an input stream that hashes using the given {@link HashFunction} and delegates all data * read from it to the underlying {@link InputStream}. * * <p>The {@link InputStream} should not be read from before or after the hand-off. */ public HashingInputStream(HashFunction hashFunction, InputStream in) { super(checkNotNull(in)); this.hasher = checkNotNull(hashFunction.newHasher()); } /** * Reads the next byte of data from the underlying input stream and updates the hasher with * the byte read. */ @Override public int read() throws IOException { int b = in.read(); if (b != -1) { hasher.putByte((byte) b); } return b; } /** * Reads the specified bytes of data from the underlying input stream and updates the hasher with * the bytes read. */ @Override public int read(byte[] bytes, int off, int len) throws IOException { int numOfBytesRead = in.read(bytes, off, len); if (numOfBytesRead != -1) { hasher.putBytes(bytes, off, numOfBytesRead); } return numOfBytesRead; } /** * mark() is not supported for HashingInputStream * @return {@code false} always */ @Override public boolean markSupported() { return false; } /** * mark() is not supported for HashingInputStream */ @Override public void mark(int readlimit) {} /** * reset() is not supported for HashingInputStream. * @throws IOException this operation is not supported */ @Override public void reset() throws IOException { throw new IOException("reset not supported"); } /** * Returns the {@link HashCode} based on the data read from this stream. The result is * unspecified if this method is called more than once on the same instance. */ public HashCode hash() { return hasher.hash(); } }
zzhhhhh-aw4rwer
guava/src/com/google/common/hash/HashingInputStream.java
Java
asf20
2,902
/* * Copyright (C) 2011 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.common.hash; import com.google.common.annotations.Beta; import com.google.common.primitives.Ints; import java.nio.charset.Charset; /** * A hash function is a collision-averse pure function that maps an arbitrary block of * data to a number called a <i>hash code</i>. * * <h3>Definition</h3> * * <p>Unpacking this definition: * * <ul> * <li><b>block of data:</b> the input for a hash function is always, in concept, an * ordered byte array. This hashing API accepts an arbitrary sequence of byte and * multibyte values (via {@link Hasher}), but this is merely a convenience; these are * always translated into raw byte sequences under the covers. * * <li><b>hash code:</b> each hash function always yields hash codes of the same fixed bit * length (given by {@link #bits}). For example, {@link Hashing#sha1} produces a * 160-bit number, while {@link Hashing#murmur3_32()} yields only 32 bits. Because a * {@code long} value is clearly insufficient to hold all hash code values, this API * represents a hash code as an instance of {@link HashCode}. * * <li><b>pure function:</b> the value produced must depend only on the input bytes, in * the order they appear. Input data is never modified. {@link HashFunction} instances * should always be stateless, and therefore thread-safe. * * <li><b>collision-averse:</b> while it can't be helped that a hash function will * sometimes produce the same hash code for distinct inputs (a "collision"), every * hash function strives to <i>some</i> degree to make this unlikely. (Without this * condition, a function that always returns zero could be called a hash function. It * is not.) * </ul> * * <p>Summarizing the last two points: "equal yield equal <i>always</i>; unequal yield * unequal <i>often</i>." This is the most important characteristic of all hash functions. * * <h3>Desirable properties</h3> * * <p>A high-quality hash function strives for some subset of the following virtues: * * <ul> * <li><b>collision-resistant:</b> while the definition above requires making at least * <i>some</i> token attempt, one measure of the quality of a hash function is <i>how * well</i> it succeeds at this goal. Important note: it may be easy to achieve the * theoretical minimum collision rate when using completely <i>random</i> sample * input. The true test of a hash function is how it performs on representative * real-world data, which tends to contain many hidden patterns and clumps. The goal * of a good hash function is to stamp these patterns out as thoroughly as possible. * * <li><b>bit-dispersing:</b> masking out any <i>single bit</i> from a hash code should * yield only the expected <i>twofold</i> increase to all collision rates. Informally, * the "information" in the hash code should be as evenly "spread out" through the * hash code's bits as possible. The result is that, for example, when choosing a * bucket in a hash table of size 2^8, <i>any</i> eight bits could be consistently * used. * * <li><b>cryptographic:</b> certain hash functions such as {@link Hashing#sha512} are * designed to make it as infeasible as possible to reverse-engineer the input that * produced a given hash code, or even to discover <i>any</i> two distinct inputs that * yield the same result. These are called <i>cryptographic hash functions</i>. But, * whenever it is learned that either of these feats has become computationally * feasible, the function is deemed "broken" and should no longer be used for secure * purposes. (This is the likely eventual fate of <i>all</i> cryptographic hashes.) * * <li><b>fast:</b> perhaps self-explanatory, but often the most important consideration. * We have published <a href="#noWeHaventYet">microbenchmark results</a> for many * common hash functions. * </ul> * * <h3>Providing input to a hash function</h3> * * <p>The primary way to provide the data that your hash function should act on is via a * {@link Hasher}. Obtain a new hasher from the hash function using {@link #newHasher}, * "push" the relevant data into it using methods like {@link Hasher#putBytes(byte[])}, * and finally ask for the {@code HashCode} when finished using {@link Hasher#hash}. (See * an {@linkplain #newHasher example} of this.) * * <p>If all you want to hash is a single byte array, string or {@code long} value, there * are convenient shortcut methods defined directly on {@link HashFunction} to make this * easier. * * <p>Hasher accepts primitive data types, but can also accept any Object of type {@code * T} provided that you implement a {@link Funnel Funnel<T>} to specify how to "feed" data * from that object into the function. (See {@linkplain Hasher#putObject an example} of * this.) * * <p><b>Compatibility note:</b> Throughout this API, multibyte values are always * interpreted in <i>little-endian</i> order. That is, hashing the byte array {@code * {0x01, 0x02, 0x03, 0x04}} is equivalent to hashing the {@code int} value {@code * 0x04030201}. If this isn't what you need, methods such as {@link Integer#reverseBytes} * and {@link Ints#toByteArray} will help. * * <h3>Relationship to {@link Object#hashCode}</h3> * * <p>Java's baked-in concept of hash codes is constrained to 32 bits, and provides no * separation between hash algorithms and the data they act on, so alternate hash * algorithms can't be easily substituted. Also, implementations of {@code hashCode} tend * to be poor-quality, in part because they end up depending on <i>other</i> existing * poor-quality {@code hashCode} implementations, including those in many JDK classes. * * <p>{@code Object.hashCode} implementations tend to be very fast, but have weak * collision prevention and <i>no</i> expectation of bit dispersion. This leaves them * perfectly suitable for use in hash tables, because extra collisions cause only a slight * performance hit, while poor bit dispersion is easily corrected using a secondary hash * function (which all reasonable hash table implementations in Java use). For the many * uses of hash functions beyond data structures, however, {@code Object.hashCode} almost * always falls short -- hence this library. * * @author Kevin Bourrillion * @since 11.0 */ @Beta public interface HashFunction { /** * Begins a new hash code computation by returning an initialized, stateful {@code * Hasher} instance that is ready to receive data. Example: <pre> {@code * * HashFunction hf = Hashing.md5(); * HashCode hc = hf.newHasher() * .putLong(id) * .putBoolean(isActive) * .hash();}</pre> */ Hasher newHasher(); /** * Begins a new hash code computation as {@link #newHasher()}, but provides a hint of the * expected size of the input (in bytes). This is only important for non-streaming hash * functions (hash functions that need to buffer their whole input before processing any * of it). */ Hasher newHasher(int expectedInputSize); /** * Shortcut for {@code newHasher().putInt(input).hash()}; returns the hash code for the given * {@code int} value, interpreted in little-endian byte order. The implementation <i>might</i> * perform better than its longhand equivalent, but should not perform worse. * * @since 12.0 */ HashCode hashInt(int input); /** * Shortcut for {@code newHasher().putLong(input).hash()}; returns the hash code for the * given {@code long} value, interpreted in little-endian byte order. The implementation * <i>might</i> perform better than its longhand equivalent, but should not perform worse. */ HashCode hashLong(long input); /** * Shortcut for {@code newHasher().putBytes(input).hash()}. The implementation * <i>might</i> perform better than its longhand equivalent, but should not perform * worse. */ HashCode hashBytes(byte[] input); /** * Shortcut for {@code newHasher().putBytes(input, off, len).hash()}. The implementation * <i>might</i> perform better than its longhand equivalent, but should not perform * worse. * * @throws IndexOutOfBoundsException if {@code off < 0} or {@code off + len > bytes.length} * or {@code len < 0} */ HashCode hashBytes(byte[] input, int off, int len); /** * Shortcut for {@code newHasher().putUnencodedChars(input).hash()}. The implementation * <i>might</i> perform better than its longhand equivalent, but should not perform worse. * Note that no character encoding is performed; the low byte and high byte of each {@code char} * are hashed directly (in that order). * * @since 15.0 (since 11.0 as hashString(CharSequence)). */ HashCode hashUnencodedChars(CharSequence input); /** * Shortcut for {@code newHasher().putString(input, charset).hash()}. Characters are encoded * using the given {@link Charset}. The implementation <i>might</i> perform better than its * longhand equivalent, but should not perform worse. */ HashCode hashString(CharSequence input, Charset charset); /** * Shortcut for {@code newHasher().putObject(instance, funnel).hash()}. The implementation * <i>might</i> perform better than its longhand equivalent, but should not perform worse. * * @since 14.0 */ <T> HashCode hashObject(T instance, Funnel<? super T> funnel); /** * Returns the number of bits (a multiple of 32) that each hash code produced by this * hash function has. */ int bits(); }
zzhhhhh-aw4rwer
guava/src/com/google/common/hash/HashFunction.java
Java
asf20
10,189
/* * Copyright (C) 2011 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.common.hash; import static com.google.common.base.Preconditions.checkNotNull; import com.google.common.annotations.Beta; import java.io.FilterOutputStream; import java.io.IOException; import java.io.OutputStream; /** * An {@link OutputStream} that maintains a hash of the data written to it. * * @author Nick Piepmeier * @since 16.0 */ @Beta public final class HashingOutputStream extends FilterOutputStream { private final Hasher hasher; /** * Creates an output stream that hashes using the given {@link HashFunction}, and forwards all * data written to it to the underlying {@link OutputStream}. * * <p>The {@link OutputStream} should not be written to before or after the hand-off. */ // TODO(user): Evaluate whether it makes sense to always piggyback the computation of a // HashCode on an existing OutputStream, compared to creating a separate OutputStream that could // be (optionally) be combined with another if needed (with something like // MultiplexingOutputStream). public HashingOutputStream(HashFunction hashFunction, OutputStream out) { super(checkNotNull(out)); this.hasher = checkNotNull(hashFunction.newHasher()); } @Override public void write(int b) throws IOException { hasher.putByte((byte) b); out.write(b); } @Override public void write(byte[] bytes, int off, int len) throws IOException { hasher.putBytes(bytes, off, len); out.write(bytes, off, len); } /** * Returns the {@link HashCode} based on the data written to this stream. The result is * unspecified if this method is called more than once on the same instance. */ public HashCode hash() { return hasher.hash(); } // Overriding close() because FilterOutputStream's close() method pre-JDK8 has bad behavior: // it silently ignores any exception thrown by flush(). Instead, just close the delegate stream. // It should flush itself if necessary. @Override public void close() throws IOException { out.close(); } }
zzhhhhh-aw4rwer
guava/src/com/google/common/hash/HashingOutputStream.java
Java
asf20
2,619
/* * Copyright (C) 2011 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.common.hash; import com.google.common.annotations.Beta; import java.io.Serializable; /** * An object which can send data from an object of type {@code T} into a {@code PrimitiveSink}. * Implementations for common types can be found in {@link Funnels}. * * <p>Note that serialization of {@linkplain BloomFilter bloom filters} requires the proper * serialization of funnels. When possible, it is recommended that funnels be implemented as a * single-element enum to maintain serialization guarantees. See Effective Java (2nd Edition), * Item 3: "Enforce the singleton property with a private constructor or an enum type". For example: * <pre> {@code * public enum PersonFunnel implements Funnel<Person> { * INSTANCE; * public void funnel(Person person, PrimitiveSink into) { * into.putUnencodedChars(person.getFirstName()) * .putUnencodedChars(person.getLastName()) * .putInt(person.getAge()); * } * }}</pre> * * @author Dimitris Andreou * @since 11.0 */ @Beta public interface Funnel<T> extends Serializable { /** * Sends a stream of data from the {@code from} object into the sink {@code into}. There * is no requirement that this data be complete enough to fully reconstitute the object * later. * * @since 12.0 (in Guava 11.0, {@code PrimitiveSink} was named {@code Sink}) */ void funnel(T from, PrimitiveSink into); }
zzhhhhh-aw4rwer
guava/src/com/google/common/hash/Funnel.java
Java
asf20
2,026
/* * Copyright (C) 2012 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.common.hash; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; import com.google.common.base.Supplier; import java.io.Serializable; import java.util.zip.Checksum; /** * {@link HashFunction} adapter for {@link Checksum} instances. * * @author Colin Decker */ final class ChecksumHashFunction extends AbstractStreamingHashFunction implements Serializable { private final Supplier<? extends Checksum> checksumSupplier; private final int bits; private final String toString; ChecksumHashFunction(Supplier<? extends Checksum> checksumSupplier, int bits, String toString) { this.checksumSupplier = checkNotNull(checksumSupplier); checkArgument(bits == 32 || bits == 64, "bits (%s) must be either 32 or 64", bits); this.bits = bits; this.toString = checkNotNull(toString); } @Override public int bits() { return bits; } @Override public Hasher newHasher() { return new ChecksumHasher(checksumSupplier.get()); } @Override public String toString() { return toString; } /** * Hasher that updates a checksum. */ private final class ChecksumHasher extends AbstractByteHasher { private final Checksum checksum; private ChecksumHasher(Checksum checksum) { this.checksum = checkNotNull(checksum); } @Override protected void update(byte b) { checksum.update(b); } @Override protected void update(byte[] bytes, int off, int len) { checksum.update(bytes, off, len); } @Override public HashCode hash() { long value = checksum.getValue(); if (bits == 32) { /* * The long returned from a 32-bit Checksum will have all 0s for its second word, so the * cast won't lose any information and is necessary to return a HashCode of the correct * size. */ return HashCode.fromInt((int) value); } else { return HashCode.fromLong(value); } } } private static final long serialVersionUID = 0L; }
zzhhhhh-aw4rwer
guava/src/com/google/common/hash/ChecksumHashFunction.java
Java
asf20
2,699
/* * Copyright (C) 2011 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.common.hash; import java.nio.charset.Charset; /** * An abstract hasher, implementing {@link #putBoolean(boolean)}, {@link #putDouble(double)}, * {@link #putFloat(float)}, {@link #putUnencodedChars(CharSequence)}, and * {@link #putString(CharSequence, Charset)} as prescribed by {@link Hasher}. * * @author Dimitris Andreou */ abstract class AbstractHasher implements Hasher { @Override public final Hasher putBoolean(boolean b) { return putByte(b ? (byte) 1 : (byte) 0); } @Override public final Hasher putDouble(double d) { return putLong(Double.doubleToRawLongBits(d)); } @Override public final Hasher putFloat(float f) { return putInt(Float.floatToRawIntBits(f)); } @Override public Hasher putUnencodedChars(CharSequence charSequence) { for (int i = 0, len = charSequence.length(); i < len; i++) { putChar(charSequence.charAt(i)); } return this; } @Override public Hasher putString(CharSequence charSequence, Charset charset) { return putBytes(charSequence.toString().getBytes(charset)); } }
zzhhhhh-aw4rwer
guava/src/com/google/common/hash/AbstractHasher.java
Java
asf20
1,676
/* * Copyright (C) 2011 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.common.hash; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Preconditions.checkState; import com.google.common.annotations.Beta; import com.google.common.base.Preconditions; import com.google.common.primitives.Ints; import com.google.common.primitives.UnsignedInts; import java.io.Serializable; import java.security.MessageDigest; import javax.annotation.Nullable; /** * An immutable hash code of arbitrary bit length. * * @author Dimitris Andreou * @author Kurt Alfred Kluever * @since 11.0 */ @Beta public abstract class HashCode { HashCode() {} /** * Returns the number of bits in this hash code; a positive multiple of 8. */ public abstract int bits(); /** * Returns the first four bytes of {@linkplain #asBytes() this hashcode's bytes}, converted to * an {@code int} value in little-endian order. * * @throws IllegalStateException if {@code bits() < 32} */ public abstract int asInt(); /** * Returns the first eight bytes of {@linkplain #asBytes() this hashcode's bytes}, converted to * a {@code long} value in little-endian order. * * @throws IllegalStateException if {@code bits() < 64} */ public abstract long asLong(); /** * If this hashcode has enough bits, returns {@code asLong()}, otherwise returns a {@code long} * value with {@code asBytes()} as the least-significant bytes and {@code 0x00} as the remaining * most-significant bytes. * * @since 14.0 (since 11.0 as {@code Hashing.padToLong(HashCode)}) */ public abstract long padToLong(); /** * Returns the value of this hash code as a byte array. The caller may modify the byte array; * changes to it will <i>not</i> be reflected in this {@code HashCode} object or any other arrays * returned by this method. */ // TODO(user): consider ByteString here, when that is available public abstract byte[] asBytes(); /** * Copies bytes from this hash code into {@code dest}. * * @param dest the byte array into which the hash code will be written * @param offset the start offset in the data * @param maxLength the maximum number of bytes to write * @return the number of bytes written to {@code dest} * @throws IndexOutOfBoundsException if there is not enough room in {@code dest} */ public int writeBytesTo(byte[] dest, int offset, int maxLength) { maxLength = Ints.min(maxLength, bits() / 8); Preconditions.checkPositionIndexes(offset, offset + maxLength, dest.length); writeBytesToImpl(dest, offset, maxLength); return maxLength; } abstract void writeBytesToImpl(byte[] dest, int offset, int maxLength); /** * Creates a 32-bit {@code HashCode} representation of the given int value. The underlying bytes * are interpreted in little endian order. * * @since 15.0 (since 12.0 in HashCodes) */ public static HashCode fromInt(int hash) { return new IntHashCode(hash); } private static final class IntHashCode extends HashCode implements Serializable { final int hash; IntHashCode(int hash) { this.hash = hash; } @Override public int bits() { return 32; } @Override public byte[] asBytes() { return new byte[] { (byte) hash, (byte) (hash >> 8), (byte) (hash >> 16), (byte) (hash >> 24)}; } @Override public int asInt() { return hash; } @Override public long asLong() { throw new IllegalStateException("this HashCode only has 32 bits; cannot create a long"); } @Override public long padToLong() { return UnsignedInts.toLong(hash); } @Override void writeBytesToImpl(byte[] dest, int offset, int maxLength) { for (int i = 0; i < maxLength; i++) { dest[offset + i] = (byte) (hash >> (i * 8)); } } private static final long serialVersionUID = 0; } /** * Creates a 64-bit {@code HashCode} representation of the given long value. The underlying bytes * are interpreted in little endian order. * * @since 15.0 (since 12.0 in HashCodes) */ public static HashCode fromLong(long hash) { return new LongHashCode(hash); } private static final class LongHashCode extends HashCode implements Serializable { final long hash; LongHashCode(long hash) { this.hash = hash; } @Override public int bits() { return 64; } @Override public byte[] asBytes() { return new byte[] { (byte) hash, (byte) (hash >> 8), (byte) (hash >> 16), (byte) (hash >> 24), (byte) (hash >> 32), (byte) (hash >> 40), (byte) (hash >> 48), (byte) (hash >> 56)}; } @Override public int asInt() { return (int) hash; } @Override public long asLong() { return hash; } @Override public long padToLong() { return hash; } @Override void writeBytesToImpl(byte[] dest, int offset, int maxLength) { for (int i = 0; i < maxLength; i++) { dest[offset + i] = (byte) (hash >> (i * 8)); } } private static final long serialVersionUID = 0; } /** * Creates a {@code HashCode} from a byte array. The array is defensively copied to preserve * the immutability contract of {@code HashCode}. The array cannot be empty. * * @since 15.0 (since 12.0 in HashCodes) */ public static HashCode fromBytes(byte[] bytes) { checkArgument(bytes.length >= 1, "A HashCode must contain at least 1 byte."); return fromBytesNoCopy(bytes.clone()); } /** * Creates a {@code HashCode} from a byte array. The array is <i>not</i> copied defensively, * so it must be handed-off so as to preserve the immutability contract of {@code HashCode}. */ static HashCode fromBytesNoCopy(byte[] bytes) { return new BytesHashCode(bytes); } private static final class BytesHashCode extends HashCode implements Serializable { final byte[] bytes; BytesHashCode(byte[] bytes) { this.bytes = checkNotNull(bytes); } @Override public int bits() { return bytes.length * 8; } @Override public byte[] asBytes() { return bytes.clone(); } @Override public int asInt() { checkState(bytes.length >= 4, "HashCode#asInt() requires >= 4 bytes (it only has %s bytes).", bytes.length); return (bytes[0] & 0xFF) | ((bytes[1] & 0xFF) << 8) | ((bytes[2] & 0xFF) << 16) | ((bytes[3] & 0xFF) << 24); } @Override public long asLong() { checkState(bytes.length >= 8, "HashCode#asLong() requires >= 8 bytes (it only has %s bytes).", bytes.length); return padToLong(); } @Override public long padToLong() { long retVal = (bytes[0] & 0xFF); for (int i = 1; i < Math.min(bytes.length, 8); i++) { retVal |= (bytes[i] & 0xFFL) << (i * 8); } return retVal; } @Override void writeBytesToImpl(byte[] dest, int offset, int maxLength) { System.arraycopy(bytes, 0, dest, offset, maxLength); } private static final long serialVersionUID = 0; } /** * Creates a {@code HashCode} from a hexadecimal ({@code base 16}) encoded string. The string must * be at least 2 characters long, and contain only valid, lower-cased hexadecimal characters. * * <p>This method accepts the exact format generated by {@link #toString}. If you require more * lenient {@code base 16} decoding, please use * {@link com.google.common.io.BaseEncoding#decode} (and pass the result to {@link #fromBytes}). * * @since 15.0 */ public static HashCode fromString(String string) { checkArgument(string.length() >= 2, "input string (%s) must have at least 2 characters", string); checkArgument(string.length() % 2 == 0, "input string (%s) must have an even number of characters", string); byte[] bytes = new byte[string.length() / 2]; for (int i = 0; i < string.length(); i += 2) { int ch1 = decode(string.charAt(i)) << 4; int ch2 = decode(string.charAt(i + 1)); bytes[i / 2] = (byte) (ch1 + ch2); } return fromBytesNoCopy(bytes); } private static int decode(char ch) { if (ch >= '0' && ch <= '9') { return ch - '0'; } if (ch >= 'a' && ch <= 'f') { return ch - 'a' + 10; } throw new IllegalArgumentException("Illegal hexadecimal character: " + ch); } @Override public final boolean equals(@Nullable Object object) { if (object instanceof HashCode) { HashCode that = (HashCode) object; // Undocumented: this is a non-short-circuiting equals(), in case this is a cryptographic // hash code, in which case we don't want to leak timing information return MessageDigest.isEqual(this.asBytes(), that.asBytes()); } return false; } /** * Returns a "Java hash code" for this {@code HashCode} instance; this is well-defined * (so, for example, you can safely put {@code HashCode} instances into a {@code * HashSet}) but is otherwise probably not what you want to use. */ @Override public final int hashCode() { // If we have at least 4 bytes (32 bits), just take the first 4 bytes. Since this is // already a (presumably) high-quality hash code, any four bytes of it will do. if (bits() >= 32) { return asInt(); } // If we have less than 4 bytes, use them all. byte[] bytes = asBytes(); int val = (bytes[0] & 0xFF); for (int i = 1; i < bytes.length; i++) { val |= ((bytes[i] & 0xFF) << (i * 8)); } return val; } /** * Returns a string containing each byte of {@link #asBytes}, in order, as a two-digit unsigned * hexadecimal number in lower case. * * <p>Note that if the output is considered to be a single hexadecimal number, this hash code's * bytes are the <i>big-endian</i> representation of that number. This may be surprising since * everything else in the hashing API uniformly treats multibyte values as little-endian. But * this format conveniently matches that of utilities such as the UNIX {@code md5sum} command. * * <p>To create a {@code HashCode} from its string representation, see {@link #fromString}. */ @Override public final String toString() { byte[] bytes = asBytes(); StringBuilder sb = new StringBuilder(2 * bytes.length); for (byte b : bytes) { sb.append(hexDigits[(b >> 4) & 0xf]).append(hexDigits[b & 0xf]); } return sb.toString(); } private static final char[] hexDigits = "0123456789abcdef".toCharArray(); }
zzhhhhh-aw4rwer
guava/src/com/google/common/hash/HashCode.java
Java
asf20
11,381
#!/bin/bash # # This script checks the java version and bails if it's less # than Java6 (because we use @Override annotations on interface # overriding methods. It then proceeds to do a maven build that # first cleans, then builds the normal lifecycle through compilation # unit testing (if available) up to packaging. It then packages # the source, javadocs, and maven site. It then signs the # artifacts with whatever pgp signature is the default of the # user executing it, and then deploys to the repository contained # in the distributionManagement section of the pom. # # author: cgruber@google.com (Christian Edward Gruber) # if [[ -n ${JAVA_HOME} ]] ; then JAVA_CMD=${JAVA_HOME}/bin/java else JAVA_CMD=java fi java_version="$(${JAVA_CMD} -version 2>&1 | grep -e 'java version' | awk '{ print $3 }')" # This test sucks, but it's short term # TODO(cgruber) strip the quotes and patch version and do version comparison. greater_than_java5="$(echo ${java_version} | grep -e '^"1.[67]')" if [[ -z ${greater_than_java5} ]] ; then echo "Your java version is ${java_version}." echo "You must use at least a java 6 JVM to build and deploy this software." exit 1 else echo "Building with java ${java_version}" fi if [[ $# > 0 ]]; then params+=" -Dgpg.keyname=${1}" gpg_sign_plugin=" gpg:sign" fi cmd="mvn clean package source:jar site:jar javadoc:jar ${gpg_sign_plugin} deploy ${params}" echo "Executing ${cmd}" ${cmd}
zzhhhhh-aw4rwer
mvn-deploy.sh
Shell
asf20
1,443
/* * Copyright (C) 2012 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.io; import static com.google.common.base.Preconditions.checkNotNull; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Lists; import junit.framework.TestCase; import java.io.IOException; import java.io.Reader; import java.io.StringReader; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.List; /** * @param <S> the source or sink type * @param <T> the data type (byte[] or String) * @param <F> the factory type * @author Colin Decker */ public class SourceSinkTester<S, T, F extends SourceSinkFactory<S, T>> extends TestCase { static final String LOREM_IPSUM = "Lorem ipsum dolor sit amet, consectetur adipiscing " + "elit. Cras fringilla elit ac ipsum adipiscing vulputate. Maecenas in lorem nulla, ac " + "sollicitudin quam. Praesent neque elit, sodales quis vestibulum vel, pellentesque nec " + "erat. Proin cursus commodo lacus eget congue. Aliquam erat volutpat. Fusce ut leo sed " + "risus tempor vehicula et a odio. Nam aliquet dolor viverra libero rutrum accumsan quis " + "in augue. Suspendisse id dui in lorem tristique placerat eget vel risus. Sed metus neque, " + "scelerisque in molestie ac, mattis quis lectus. Pellentesque viverra justo commodo quam " + "bibendum ut gravida leo accumsan. Nullam malesuada sagittis diam, quis suscipit mauris " + "euismod vulputate. Pellentesque ultrices tellus sed lorem aliquet pulvinar. Nam lorem " + "nunc, ultrices at auctor non, scelerisque eget turpis. Nullam eget varius erat. Sed a " + "lorem id arcu dictum euismod. Fusce lectus odio, elementum ullamcorper mattis viverra, " + "dictum sit amet lacus.\n" + "\n" + "Nunc quis lacus est. Sed aliquam pretium cursus. Sed eu libero eros. In hac habitasse " + "platea dictumst. Pellentesque molestie, nibh nec iaculis luctus, justo sem lobortis enim, " + "at feugiat leo magna nec libero. Mauris quis odio eget nisl rutrum cursus nec eget augue. " + "Sed nec arcu sem. In hac habitasse platea dictumst."; static final ImmutableMap<String, String> TEST_STRINGS = ImmutableMap.<String, String>builder() .put("empty", "") .put("1 char", "0") .put("1 word", "hello") .put("2 words", "hello world") .put("\\n line break", "hello\nworld") .put("\\r line break", "hello\rworld") .put("\\r\\n line break", "hello\r\nworld") .put("\\n at EOF", "hello\nworld\n") .put("\\r at EOF", "hello\nworld\r") .put("lorem ipsum", LOREM_IPSUM) .build(); protected final F factory; protected final T data; protected final T expected; private final String suiteName; private final String caseDesc; SourceSinkTester(F factory, T data, String suiteName, String caseDesc, Method method) { super(method.getName()); this.factory = checkNotNull(factory); this.data = checkNotNull(data); this.expected = checkNotNull(factory.getExpected(data)); this.suiteName = checkNotNull(suiteName); this.caseDesc = checkNotNull(caseDesc); } @Override public String getName() { return super.getName() + " [" + suiteName + " [" + caseDesc + "]]"; } protected static ImmutableList<String> getLines(final String string) { try { return new CharSource() { @Override public Reader openStream() throws IOException { return new StringReader(string); } }.readLines(); } catch (IOException e) { throw new AssertionError(); } } @Override public void tearDown() throws IOException { factory.tearDown(); } static ImmutableList<Method> getTestMethods(Class<?> testClass) { List<Method> result = Lists.newArrayList(); for (Method method : testClass.getDeclaredMethods()) { if (Modifier.isPublic(method.getModifiers()) && method.getReturnType() == void.class && method.getParameterTypes().length == 0 && method.getName().startsWith("test")) { result.add(method); } } return ImmutableList.copyOf(result); } }
zzhhhhh-aw4rwer
guava-tests/test/com/google/common/io/SourceSinkTester.java
Java
asf20
4,780
/* * Copyright (C) 2012 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.io; import static com.google.common.io.SourceSinkFactory.ByteSinkFactory; import static com.google.common.io.SourceSinkFactory.CharSinkFactory; import static org.junit.Assert.assertArrayEquals; import com.google.common.base.Charsets; import com.google.common.collect.ImmutableList; import junit.framework.TestSuite; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.OutputStream; import java.lang.reflect.Method; import java.util.Map; /** * A generator of {@code TestSuite} instances for testing {@code ByteSink} implementations. * Generates tests of a all methods on a {@code ByteSink} given various inputs written to it as well * as sub-suites for testing the {@code CharSink} view in the same way. * * @author Colin Decker */ public class ByteSinkTester extends SourceSinkTester<ByteSink, byte[], ByteSinkFactory> { private static final ImmutableList<Method> testMethods = getTestMethods(ByteSinkTester.class); static TestSuite tests(String name, ByteSinkFactory factory) { TestSuite suite = new TestSuite(name); for (Map.Entry<String, String> entry : TEST_STRINGS.entrySet()) { String desc = entry.getKey(); TestSuite stringSuite = suiteForString(name, factory, entry.getValue(), desc); suite.addTest(stringSuite); } return suite; } private static TestSuite suiteForString(String name, ByteSinkFactory factory, String string, String desc) { byte[] bytes = string.getBytes(Charsets.UTF_8); TestSuite suite = suiteForBytes(name, factory, desc, bytes); CharSinkFactory charSinkFactory = SourceSinkFactories.asCharSinkFactory(factory); suite.addTest(CharSinkTester.suiteForString(name + ".asCharSink[Charset]", charSinkFactory, string, desc)); return suite; } private static TestSuite suiteForBytes(String name, ByteSinkFactory factory, String desc, byte[] bytes) { TestSuite suite = new TestSuite(name + " [" + desc + "]"); for (final Method method : testMethods) { suite.addTest(new ByteSinkTester(factory, bytes, name, desc, method)); } return suite; } private ByteSink sink; ByteSinkTester(ByteSinkFactory factory, byte[] data, String suiteName, String caseDesc, Method method) { super(factory, data, suiteName, caseDesc, method); } @Override protected void setUp() throws Exception { sink = factory.createSink(); } public void testOpenStream() throws IOException { OutputStream out = sink.openStream(); try { ByteStreams.copy(new ByteArrayInputStream(data), out); } finally { out.close(); } assertContainsExpectedBytes(); } public void testOpenBufferedStream() throws IOException { OutputStream out = sink.openBufferedStream(); try { ByteStreams.copy(new ByteArrayInputStream(data), out); } finally { out.close(); } assertContainsExpectedBytes(); } public void testWrite() throws IOException { sink.write(data); assertContainsExpectedBytes(); } public void testWriteFrom_inputStream() throws IOException { sink.writeFrom(new ByteArrayInputStream(data)); assertContainsExpectedBytes(); } private void assertContainsExpectedBytes() throws IOException { assertArrayEquals(expected, factory.getSinkContents()); } }
zzhhhhh-aw4rwer
guava-tests/test/com/google/common/io/ByteSinkTester.java
Java
asf20
3,947
/* * Copyright (C) 2012 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.io; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.io.SourceSinkFactory.ByteSinkFactory; import static com.google.common.io.SourceSinkFactory.ByteSourceFactory; import static com.google.common.io.SourceSinkFactory.CharSinkFactory; import static com.google.common.io.SourceSinkFactory.CharSourceFactory; import com.google.common.base.Charsets; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.Reader; import java.io.Writer; import java.nio.CharBuffer; import java.util.Arrays; import java.util.logging.Logger; import javax.annotation.Nullable; /** * {@link SourceSinkFactory} implementations. * * @author Colin Decker */ public class SourceSinkFactories { private SourceSinkFactories() {} public static CharSourceFactory stringCharSourceFactory() { return new StringSourceFactory(); } public static ByteSourceFactory byteArraySourceFactory() { return new ByteArraySourceFactory(); } public static ByteSourceFactory emptyByteSourceFactory() { return new EmptyByteSourceFactory(); } public static CharSourceFactory emptyCharSourceFactory() { return new EmptyCharSourceFactory(); } public static ByteSourceFactory fileByteSourceFactory() { return new FileByteSourceFactory(); } public static ByteSinkFactory fileByteSinkFactory() { return new FileByteSinkFactory(null); } public static ByteSinkFactory appendingFileByteSinkFactory() { String initialString = IoTestCase.ASCII + IoTestCase.I18N; return new FileByteSinkFactory(initialString.getBytes(Charsets.UTF_8)); } public static CharSourceFactory fileCharSourceFactory() { return new FileCharSourceFactory(); } public static CharSinkFactory fileCharSinkFactory() { return new FileCharSinkFactory(null); } public static CharSinkFactory appendingFileCharSinkFactory() { String initialString = IoTestCase.ASCII + IoTestCase.I18N; return new FileCharSinkFactory(initialString); } public static ByteSourceFactory urlByteSourceFactory() { return new UrlByteSourceFactory(); } public static CharSourceFactory urlCharSourceFactory() { return new UrlCharSourceFactory(); } public static CharSourceFactory asCharSourceFactory(final ByteSourceFactory factory) { checkNotNull(factory); return new CharSourceFactory() { @Override public CharSource createSource(String string) throws IOException { return factory.createSource(string.getBytes(Charsets.UTF_8)) .asCharSource(Charsets.UTF_8); } @Override public String getExpected(String data) { return new String(factory.getExpected(data.getBytes(Charsets.UTF_8)), Charsets.UTF_8); } @Override public void tearDown() throws IOException { factory.tearDown(); } }; } public static CharSinkFactory asCharSinkFactory(final ByteSinkFactory factory) { checkNotNull(factory); return new CharSinkFactory() { @Override public CharSink createSink() throws IOException { return factory.createSink().asCharSink(Charsets.UTF_8); } @Override public String getSinkContents() throws IOException { return new String(factory.getSinkContents(), Charsets.UTF_8); } @Override public String getExpected(String data) { /* * Get what the byte sink factory would expect for no written bytes, then append expected * string to that. */ byte[] factoryExpectedForNothing = factory.getExpected(new byte[0]); return new String(factoryExpectedForNothing, Charsets.UTF_8) + checkNotNull(data); } @Override public void tearDown() throws IOException { factory.tearDown(); } }; } public static ByteSourceFactory asSlicedByteSourceFactory(final ByteSourceFactory factory, final int off, final int len) { checkNotNull(factory); return new ByteSourceFactory() { @Override public ByteSource createSource(byte[] bytes) throws IOException { return factory.createSource(bytes).slice(off, len); } @Override public byte[] getExpected(byte[] bytes) { byte[] baseExpected = factory.getExpected(bytes); return Arrays.copyOfRange(baseExpected, off, Math.min(baseExpected.length, off + len)); } @Override public void tearDown() throws IOException { factory.tearDown(); } }; } private static class StringSourceFactory implements CharSourceFactory { @Override public CharSource createSource(String data) throws IOException { return CharSource.wrap(data); } @Override public String getExpected(String data) { return data; } @Override public void tearDown() throws IOException { } } private static class ByteArraySourceFactory implements ByteSourceFactory { @Override public ByteSource createSource(byte[] bytes) throws IOException { return ByteSource.wrap(bytes); } @Override public byte[] getExpected(byte[] bytes) { return bytes; } @Override public void tearDown() throws IOException { } } private static class EmptyCharSourceFactory implements CharSourceFactory { @Override public CharSource createSource(String data) throws IOException { return CharSource.empty(); } @Override public String getExpected(String data) { return ""; } @Override public void tearDown() throws IOException { } } private static class EmptyByteSourceFactory implements ByteSourceFactory { @Override public ByteSource createSource(byte[] bytes) throws IOException { return ByteSource.empty(); } @Override public byte[] getExpected(byte[] bytes) { return new byte[0]; } @Override public void tearDown() throws IOException { } } private abstract static class FileFactory { private static final Logger logger = Logger.getLogger(FileFactory.class.getName()); private final ThreadLocal<File> fileThreadLocal = new ThreadLocal<File>(); protected File createFile() throws IOException { File file = File.createTempFile("SinkSourceFile", "txt"); fileThreadLocal.set(file); return file; } protected File getFile() { return fileThreadLocal.get(); } public final void tearDown() throws IOException { if (!fileThreadLocal.get().delete()) { logger.warning("Unable to delete file: " + fileThreadLocal.get()); } fileThreadLocal.remove(); } } private static class FileByteSourceFactory extends FileFactory implements ByteSourceFactory { @Override public ByteSource createSource(byte[] bytes) throws IOException { checkNotNull(bytes); File file = createFile(); OutputStream out = new FileOutputStream(file); try { out.write(bytes); } finally { out.close(); } return Files.asByteSource(file); } @Override public byte[] getExpected(byte[] bytes) { return checkNotNull(bytes); } } private static class FileByteSinkFactory extends FileFactory implements ByteSinkFactory { private final byte[] initialBytes; private FileByteSinkFactory(@Nullable byte[] initialBytes) { this.initialBytes = initialBytes; } @Override public ByteSink createSink() throws IOException { File file = createFile(); if (initialBytes != null) { FileOutputStream out = new FileOutputStream(file); try { out.write(initialBytes); } finally { out.close(); } return Files.asByteSink(file, FileWriteMode.APPEND); } return Files.asByteSink(file); } @Override public byte[] getExpected(byte[] bytes) { if (initialBytes == null) { return checkNotNull(bytes); } else { byte[] result = new byte[initialBytes.length + bytes.length]; System.arraycopy(initialBytes, 0, result, 0, initialBytes.length); System.arraycopy(bytes, 0, result, initialBytes.length, bytes.length); return result; } } @Override public byte[] getSinkContents() throws IOException { File file = getFile(); InputStream in = new FileInputStream(file); ByteArrayOutputStream out = new ByteArrayOutputStream(); byte[] buffer = new byte[100]; int read; while ((read = in.read(buffer)) != -1) { out.write(buffer, 0, read); } return out.toByteArray(); } } private static class FileCharSourceFactory extends FileFactory implements CharSourceFactory { @Override public CharSource createSource(String string) throws IOException { checkNotNull(string); File file = createFile(); Writer writer = new OutputStreamWriter(new FileOutputStream(file), Charsets.UTF_8); try { writer.write(string); } finally { writer.close(); } return Files.asCharSource(file, Charsets.UTF_8); } @Override public String getExpected(String string) { return checkNotNull(string); } } private static class FileCharSinkFactory extends FileFactory implements CharSinkFactory { private final String initialString; private FileCharSinkFactory(@Nullable String initialString) { this.initialString = initialString; } @Override public CharSink createSink() throws IOException { File file = createFile(); if (initialString != null) { Writer writer = new OutputStreamWriter(new FileOutputStream(file), Charsets.UTF_8); try { writer.write(initialString); } finally { writer.close(); } return Files.asCharSink(file, Charsets.UTF_8, FileWriteMode.APPEND); } return Files.asCharSink(file, Charsets.UTF_8); } @Override public String getExpected(String string) { checkNotNull(string); return initialString == null ? string : initialString + string; } @Override public String getSinkContents() throws IOException { File file = getFile(); Reader reader = new InputStreamReader(new FileInputStream(file), Charsets.UTF_8); StringBuilder builder = new StringBuilder(); CharBuffer buffer = CharBuffer.allocate(100); while (reader.read(buffer) != -1) { buffer.flip(); builder.append(buffer); buffer.clear(); } return builder.toString(); } } private static class UrlByteSourceFactory extends FileByteSourceFactory { @Override public ByteSource createSource(byte[] bytes) throws IOException { super.createSource(bytes); return Resources.asByteSource(getFile().toURI().toURL()); } } private static class UrlCharSourceFactory extends FileCharSourceFactory { @Override public CharSource createSource(String string) throws IOException { super.createSource(string); // just ignore returned CharSource return Resources.asCharSource(getFile().toURI().toURL(), Charsets.UTF_8); } } }
zzhhhhh-aw4rwer
guava-tests/test/com/google/common/io/SourceSinkFactories.java
Java
asf20
12,042
/* * Copyright (C) 2012 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.io; import java.io.File; import java.io.IOException; /** * A test factory for byte or char sources or sinks. In addition to creating sources or sinks, the * factory specifies what content should be expected to be read from a source or contained in a sink * given the content data that was used to create the source or that was written to the sink. * * <p>A single {@code SourceSinkFactory} implementation generally corresponds to one specific way of * creating a source or sink, such as {@link Files#asByteSource(File)}. Implementations of * {@code SourceSinkFactory} for common.io are found in {@link SourceSinkFactories}. * * @param <S> the source or sink type * @param <T> the data type (byte[] or String) * @author Colin Decker */ public interface SourceSinkFactory<S, T> { /** * Returns the data to expect the source or sink to contain given the data that was used to create * the source or written to the sink. Typically, this will just return the input directly, but in * some cases it may alter the input. For example, if the factory returns a sliced view of a * source created with some given bytes, this method would return a subsequence of the given * (byte[]) data. */ T getExpected(T data); /** * Cleans up anything created when creating the source or sink. */ public abstract void tearDown() throws IOException; /** * Factory for byte or char sources. */ public interface SourceFactory<S, T> extends SourceSinkFactory<S, T> { /** * Creates a new source containing some or all of the given data. */ S createSource(T data) throws IOException; } /** * Factory for byte or char sinks. */ public interface SinkFactory<S, T> extends SourceSinkFactory<S, T> { /** * Creates a new sink. */ S createSink() throws IOException; /** * Gets the current content of the created sink. */ T getSinkContents() throws IOException; } /** * Factory for {@link ByteSource} instances. */ public interface ByteSourceFactory extends SourceFactory<ByteSource, byte[]> { } /** * Factory for {@link ByteSink} instances. */ public interface ByteSinkFactory extends SinkFactory<ByteSink, byte[]> { } /** * Factory for {@link CharSource} instances. */ public interface CharSourceFactory extends SourceFactory<CharSource, String> { } /** * Factory for {@link CharSink} instances. */ public interface CharSinkFactory extends SinkFactory<CharSink, String> { } }
zzhhhhh-aw4rwer
guava-tests/test/com/google/common/io/SourceSinkFactory.java
Java
asf20
3,153
/* * Copyright (C) 2012 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.io; import static com.google.common.io.SourceSinkFactory.CharSinkFactory; import com.google.common.base.Joiner; import com.google.common.collect.ImmutableList; import junit.framework.TestSuite; import java.io.IOException; import java.io.Writer; import java.lang.reflect.Method; import java.util.Map; /** * A generator of {@code TestSuite} instances for testing {@code CharSink} implementations. * Generates tests of a all methods on a {@code CharSink} given various inputs written to it. * * @author Colin Decker */ public class CharSinkTester extends SourceSinkTester<CharSink, String, CharSinkFactory> { private static final ImmutableList<Method> testMethods = getTestMethods(CharSinkTester.class); static TestSuite tests(String name, CharSinkFactory factory) { TestSuite suite = new TestSuite(name); for (Map.Entry<String, String> entry : TEST_STRINGS.entrySet()) { String desc = entry.getKey(); TestSuite stringSuite = suiteForString(name, factory, entry.getValue(), desc); suite.addTest(stringSuite); } return suite; } static TestSuite suiteForString(String name, CharSinkFactory factory, String string, String desc) { TestSuite stringSuite = new TestSuite(name + " [" + desc + "]"); for (final Method method : testMethods) { stringSuite.addTest(new CharSinkTester(factory, string, name, desc, method)); } return stringSuite; } private final ImmutableList<String> lines; private final ImmutableList<String> expectedLines; private CharSink sink; public CharSinkTester(CharSinkFactory factory, String string, String suiteName, String caseDesc, Method method) { super(factory, string, suiteName, caseDesc, method); this.lines = getLines(string); this.expectedLines = getLines(expected); } @Override protected void setUp() throws Exception { this.sink = factory.createSink(); } public void testOpenStream() throws IOException { Writer writer = sink.openStream(); try { writer.write(data); } finally { writer.close(); } assertContainsExpectedString(); } public void testOpenBufferedStream() throws IOException { Writer writer = sink.openBufferedStream(); try { writer.write(data); } finally { writer.close(); } assertContainsExpectedString(); } public void testWrite() throws IOException { sink.write(data); assertContainsExpectedString(); } public void testWriteLines_systemDefaultSeparator() throws IOException { String separator = System.getProperty("line.separator"); sink.writeLines(lines); assertContainsExpectedLines(separator); } public void testWriteLines_specificSeparator() throws IOException { String separator = "\r\n"; sink.writeLines(lines, separator); assertContainsExpectedLines(separator); } private void assertContainsExpectedString() throws IOException { assertEquals(expected, factory.getSinkContents()); } private void assertContainsExpectedLines(String separator) throws IOException { String expected = expectedLines.isEmpty() ? "" : Joiner.on(separator).join(expectedLines); if (!lines.isEmpty()) { // if we wrote any lines in writeLines(), there will be a trailing newline expected += separator; } assertEquals(expected, factory.getSinkContents()); } }
zzhhhhh-aw4rwer
guava-tests/test/com/google/common/io/CharSinkTester.java
Java
asf20
4,023
/* * Copyright (C) 2007 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.io; import com.google.common.collect.Sets; import junit.framework.TestCase; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.URL; import java.util.Set; import java.util.logging.Level; import java.util.logging.Logger; /** * Base test case class for I/O tests. * * @author Chris Nokleberg * @author Colin Decker */ public abstract class IoTestCase extends TestCase { private static final Logger logger = Logger.getLogger(IoTestCase.class.getName()); static final String I18N = "\u00CE\u00F1\u0163\u00E9\u0072\u00F1\u00E5\u0163\u00EE\u00F6" + "\u00F1\u00E5\u013C\u00EE\u017E\u00E5\u0163\u00EE\u00F6\u00F1"; static final String ASCII = " !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ" + "[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~"; private File testDir; private File tempDir; private final Set<File> filesToDelete = Sets.newHashSet(); @Override protected void tearDown() { for (File file : filesToDelete) { if (file.exists()) { delete(file); } } filesToDelete.clear(); } private File getTestDir() throws IOException { if (testDir != null) { return testDir; } URL testFileUrl = IoTestCase.class.getResource("testdata/i18n.txt"); if (testFileUrl == null) { throw new RuntimeException("unable to locate testdata directory"); } if (testFileUrl.getProtocol().equals("file")) { try { File testFile = new File(testFileUrl.toURI()); testDir = testFile.getParentFile(); // the testdata directory } catch (Exception ignore) { // probably URISyntaxException or IllegalArgumentException // fall back to copying URLs to files in the testDir == null block below } } if (testDir == null) { // testdata resources aren't file:// urls, so create a directory to store them in and then // copy the resources to the filesystem as needed testDir = createTempDir(); } return testDir; } /** * Returns the file with the given name under the testdata directory. */ protected final File getTestFile(String name) throws IOException { File file = new File(getTestDir(), name); if (!file.exists()) { URL resourceUrl = IoTestCase.class.getResource("testdata/" + name); if (resourceUrl == null) { return null; } copy(resourceUrl, file); } return file; } /** * Creates a new temp dir for testing. The returned directory and all contents of it will be * deleted in the tear-down for this test. */ protected final File createTempDir() throws IOException { File tempFile = File.createTempFile("IoTestCase", ""); if (!tempFile.delete() || !tempFile.mkdir()) { throw new IOException("failed to create temp dir"); } filesToDelete.add(tempFile); return tempFile; } /** * Gets a temp dir for testing. The returned directory and all contents of it will be deleted in * the tear-down for this test. Subsequent invocations of this method will return the same * directory. */ protected final File getTempDir() throws IOException { if (tempDir == null) { tempDir = createTempDir(); } return tempDir; } /** * Creates a new temp file in the temp directory returned by {@link #getTempDir()}. The file will * be deleted in the tear-down for this test. */ protected final File createTempFile() throws IOException { return File.createTempFile("test", null, getTempDir()); } /** * Returns a byte array of length size that has values 0 .. size - 1. */ static byte[] newPreFilledByteArray(int size) { return newPreFilledByteArray(0, size); } /** * Returns a byte array of length size that has values offset .. offset + size - 1. */ static byte[] newPreFilledByteArray(int offset, int size) { byte[] array = new byte[size]; for (int i = 0; i < size; i++) { array[i] = (byte) (offset + i); } return array; } private static void copy(URL url, File file) throws IOException { InputStream in = url.openStream(); try { OutputStream out = new FileOutputStream(file); try { byte[] buf = new byte[4096]; for (int read = in.read(buf); read != -1; read = in.read(buf)) { out.write(buf, 0, read); } } finally { out.close(); } } finally { in.close(); } } private boolean delete(File file) { if (file.isDirectory()) { File[] files = file.listFiles(); if (files != null) { for (File f : files) { if (!delete(f)) { return false; } } } } if (!file.delete()) { logger.log(Level.WARNING, "couldn't delete file: {0}", new Object[] {file}); return false; } return true; } }
zzhhhhh-aw4rwer
guava-tests/test/com/google/common/io/IoTestCase.java
Java
asf20
5,568
/* * Copyright (C) 2012 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.io; import static com.google.common.io.SourceSinkFactory.CharSourceFactory; import com.google.common.collect.ImmutableList; import com.google.common.collect.Lists; import junit.framework.TestSuite; import java.io.BufferedReader; import java.io.IOException; import java.io.Reader; import java.io.StringWriter; import java.lang.reflect.Method; import java.util.List; import java.util.Map; /** * A generator of {@code TestSuite} instances for testing {@code CharSource} implementations. * Generates tests of a all methods on a {@code CharSource} given various inputs the source is * expected to contain. * * @author Colin Decker */ public class CharSourceTester extends SourceSinkTester<CharSource, String, CharSourceFactory> { private static final ImmutableList<Method> testMethods = getTestMethods(CharSourceTester.class); static TestSuite tests(String name, CharSourceFactory factory) { TestSuite suite = new TestSuite(name); for (Map.Entry<String, String> entry : TEST_STRINGS.entrySet()) { suite.addTest(suiteForString(factory, entry.getValue(), name, entry.getKey())); } return suite; } static TestSuite suiteForString(CharSourceFactory factory, String string, String name, String desc) { TestSuite suite = new TestSuite(name + " [" + desc + "]"); for (Method method : testMethods) { suite.addTest(new CharSourceTester(factory, string, name, desc, method)); } return suite; } private final ImmutableList<String> expectedLines; private CharSource source; public CharSourceTester(CharSourceFactory factory, String string, String suiteName, String caseDesc, Method method) { super(factory, string, suiteName, caseDesc, method); this.expectedLines = getLines(expected); } @Override protected void setUp() throws Exception { this.source = factory.createSource(data); } public void testOpenStream() throws IOException { Reader reader = source.openStream(); StringWriter writer = new StringWriter(); char[] buf = new char[64]; int read; while ((read = reader.read(buf)) != -1) { writer.write(buf, 0, read); } reader.close(); writer.close(); assertExpectedString(writer.toString()); } public void testOpenBufferedStream() throws IOException { BufferedReader reader = source.openBufferedStream(); StringWriter writer = new StringWriter(); char[] buf = new char[64]; int read; while ((read = reader.read(buf)) != -1) { writer.write(buf, 0, read); } reader.close(); writer.close(); assertExpectedString(writer.toString()); } public void testCopyTo_appendable() throws IOException { StringBuilder builder = new StringBuilder(); assertEquals(expected.length(), source.copyTo(builder)); assertExpectedString(builder.toString()); } public void testCopyTo_charSink() throws IOException { TestCharSink sink = new TestCharSink(); assertEquals(expected.length(), source.copyTo(sink)); assertExpectedString(sink.getString()); } public void testRead_toString() throws IOException { String string = source.read(); assertExpectedString(string); } public void testReadFirstLine() throws IOException { if (expectedLines.isEmpty()) { assertNull(source.readFirstLine()); } else { assertEquals(expectedLines.get(0), source.readFirstLine()); } } public void testReadLines_toList() throws IOException { assertExpectedLines(source.readLines()); } public void testIsEmpty() throws IOException { assertEquals(expected.isEmpty(), source.isEmpty()); } public void testReadLines_withProcessor() throws IOException { List<String> list = source.readLines(new LineProcessor<List<String>>() { List<String> list = Lists.newArrayList(); @Override public boolean processLine(String line) throws IOException { list.add(line); return true; } @Override public List<String> getResult() { return list; } }); assertExpectedLines(list); } public void testReadLines_withProcessor_stopsOnFalse() throws IOException { List<String> list = source.readLines(new LineProcessor<List<String>>() { List<String> list = Lists.newArrayList(); @Override public boolean processLine(String line) throws IOException { list.add(line); return false; } @Override public List<String> getResult() { return list; } }); if (expectedLines.isEmpty()) { assertTrue(list.isEmpty()); } else { assertEquals(expectedLines.subList(0, 1), list); } } private void assertExpectedString(String string) { assertEquals(expected, string); } private void assertExpectedLines(List<String> list) { assertEquals(expectedLines, list); } }
zzhhhhh-aw4rwer
guava-tests/test/com/google/common/io/CharSourceTester.java
Java
asf20
5,498
/* * Copyright (C) 2012 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.io; import static com.google.common.io.SourceSinkFactory.ByteSourceFactory; import static com.google.common.io.SourceSinkFactory.CharSourceFactory; import static org.junit.Assert.assertArrayEquals; import com.google.common.base.Charsets; import com.google.common.collect.ImmutableList; import com.google.common.hash.HashCode; import com.google.common.hash.Hashing; import junit.framework.TestSuite; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.lang.reflect.Method; import java.util.Map; import java.util.Random; /** * A generator of {@code TestSuite} instances for testing {@code ByteSource} implementations. * Generates tests of a all methods on a {@code ByteSource} given various inputs the source is * expected to contain as well as as sub-suites for testing the {@code CharSource} view and * {@code slice()} views in the same way. * * @author Colin Decker */ public class ByteSourceTester extends SourceSinkTester<ByteSource, byte[], ByteSourceFactory> { private static final ImmutableList<Method> testMethods = getTestMethods(ByteSourceTester.class); static TestSuite tests(String name, ByteSourceFactory factory, boolean testAsCharSource) { TestSuite suite = new TestSuite(name); for (Map.Entry<String, String> entry : TEST_STRINGS.entrySet()) { if (testAsCharSource) { suite.addTest(suiteForString(factory, entry.getValue(), name, entry.getKey())); } else { suite.addTest(suiteForBytes( factory, entry.getValue().getBytes(Charsets.UTF_8), name, entry.getKey(), true)); } } return suite; } private static TestSuite suiteForString(ByteSourceFactory factory, String string, String name, String desc) { TestSuite suite = suiteForBytes(factory, string.getBytes(Charsets.UTF_8), name, desc, true); CharSourceFactory charSourceFactory = SourceSinkFactories.asCharSourceFactory(factory); suite.addTest(CharSourceTester.suiteForString(charSourceFactory, string, name + ".asCharSource[Charset]", desc)); return suite; } private static TestSuite suiteForBytes(ByteSourceFactory factory, byte[] bytes, String name, String desc, boolean slice) { TestSuite suite = new TestSuite(name + " [" + desc + "]"); for (Method method : testMethods) { suite.addTest(new ByteSourceTester(factory, bytes, name, desc, method)); } if (slice && bytes.length > 0) { // test a random slice() of the ByteSource Random random = new Random(); byte[] expected = factory.getExpected(bytes); // if expected.length == 0, off has to be 0 but length doesn't matter--result will be empty int off = expected.length == 0 ? 0 : random.nextInt(expected.length); int len = expected.length == 0 ? 4 : random.nextInt(expected.length - off); ByteSourceFactory sliced = SourceSinkFactories.asSlicedByteSourceFactory(factory, off, len); suite.addTest(suiteForBytes(sliced, bytes, name + ".slice[int, int]", desc, false)); } return suite; } private ByteSource source; public ByteSourceTester(ByteSourceFactory factory, byte[] bytes, String suiteName, String caseDesc, Method method) { super(factory, bytes, suiteName, caseDesc, method); } @Override public void setUp() throws IOException { source = factory.createSource(data); } public void testOpenStream() throws IOException { InputStream in = source.openStream(); try { byte[] readBytes = ByteStreams.toByteArray(in); assertExpectedBytes(readBytes); } finally { in.close(); } } public void testOpenBufferedStream() throws IOException { InputStream in = source.openBufferedStream(); try { byte[] readBytes = ByteStreams.toByteArray(in); assertExpectedBytes(readBytes); } finally { in.close(); } } public void testRead() throws IOException { byte[] readBytes = source.read(); assertExpectedBytes(readBytes); } public void testCopyTo_outputStream() throws IOException { ByteArrayOutputStream out = new ByteArrayOutputStream(); source.copyTo(out); assertExpectedBytes(out.toByteArray()); } public void testCopyTo_byteSink() throws IOException { final ByteArrayOutputStream out = new ByteArrayOutputStream(); // HERESY! but it's ok just for this I guess source.copyTo(new ByteSink() { @Override public OutputStream openStream() throws IOException { return out; } }); assertExpectedBytes(out.toByteArray()); } public void testIsEmpty() throws IOException { assertEquals(expected.length == 0, source.isEmpty()); } public void testSize() throws IOException { assertEquals(expected.length, source.size()); } public void testContentEquals() throws IOException { assertTrue(source.contentEquals(new ByteSource() { @Override public InputStream openStream() throws IOException { return new RandomAmountInputStream( new ByteArrayInputStream(expected), new Random()); } })); } public void testRead_usingByteProcessor() throws IOException { byte[] readBytes = source.read(new ByteProcessor<byte[]>() { final ByteArrayOutputStream out = new ByteArrayOutputStream(); @Override public boolean processBytes(byte[] buf, int off, int len) throws IOException { out.write(buf, off, len); return true; } @Override public byte[] getResult() { return out.toByteArray(); } }); assertExpectedBytes(readBytes); } public void testHash() throws IOException { HashCode expectedHash = Hashing.md5().hashBytes(expected); assertEquals(expectedHash, source.hash(Hashing.md5())); } public void testSlice_illegalArguments() { try { source.slice(-1, 0); fail("expected IllegalArgumentException for call to slice with offset -1: " + source); } catch (IllegalArgumentException expected) { } try { source.slice(0, -1); fail("expected IllegalArgumentException for call to slice with length -1: " + source); } catch (IllegalArgumentException expected) { } } private void assertExpectedBytes(byte[] readBytes) { assertArrayEquals(expected, readBytes); } }
zzhhhhh-aw4rwer
guava-tests/test/com/google/common/io/ByteSourceTester.java
Java
asf20
7,016
/* * Copyright (C) 2007 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.io; import static com.google.common.base.Preconditions.checkNotNull; import java.io.FilterInputStream; import java.io.IOException; import java.io.InputStream; import java.util.Random; /** Returns a random portion of the requested bytes on each call. */ class RandomAmountInputStream extends FilterInputStream { private final Random random; public RandomAmountInputStream(InputStream in, Random random) { super(checkNotNull(in)); this.random = checkNotNull(random); } @Override public int read(byte[] b, int off, int len) throws IOException { return super.read(b, off, random.nextInt(len) + 1); } }
zzhhhhh-aw4rwer
guava-tests/test/com/google/common/io/RandomAmountInputStream.java
Java
asf20
1,253
/* * Written by Doug Lea with assistance from members of JCP JSR-166 * Expert Group and released to the public domain, as explained at * http://creativecommons.org/publicdomain/zero/1.0/ * Other contributors include Andrew Wright, Jeffrey Hayes, * Pat Fisher, Mike Judd. */ /* * Source: * http://gee.cs.oswego.edu/cgi-bin/viewcvs.cgi/jsr166/src/test/tck/JSR166TestCase.java?revision=1.90 * (We have made some trivial local modifications (commented out * uncompilable code).) */ package com.google.common.util.concurrent; import static java.util.concurrent.TimeUnit.MILLISECONDS; import static java.util.concurrent.TimeUnit.NANOSECONDS; import junit.framework.*; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.security.CodeSource; import java.security.Permission; import java.security.PermissionCollection; import java.security.Permissions; import java.security.Policy; import java.security.ProtectionDomain; import java.security.SecurityPermission; import java.util.Arrays; import java.util.Date; import java.util.NoSuchElementException; import java.util.PropertyPermission; import java.util.concurrent.*; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicReference; /** * Base class for JSR166 Junit TCK tests. Defines some constants, * utility methods and classes, as well as a simple framework for * helping to make sure that assertions failing in generated threads * cause the associated test that generated them to itself fail (which * JUnit does not otherwise arrange). The rules for creating such * tests are: * * <ol> * * <li> All assertions in code running in generated threads must use * the forms {@link #threadFail}, {@link #threadAssertTrue}, {@link * #threadAssertEquals}, or {@link #threadAssertNull}, (not * {@code fail}, {@code assertTrue}, etc.) It is OK (but not * particularly recommended) for other code to use these forms too. * Only the most typically used JUnit assertion methods are defined * this way, but enough to live with.</li> * * <li> If you override {@link #setUp} or {@link #tearDown}, make sure * to invoke {@code super.setUp} and {@code super.tearDown} within * them. These methods are used to clear and check for thread * assertion failures.</li> * * <li>All delays and timeouts must use one of the constants {@code * SHORT_DELAY_MS}, {@code SMALL_DELAY_MS}, {@code MEDIUM_DELAY_MS}, * {@code LONG_DELAY_MS}. The idea here is that a SHORT is always * discriminable from zero time, and always allows enough time for the * small amounts of computation (creating a thread, calling a few * methods, etc) needed to reach a timeout point. Similarly, a SMALL * is always discriminable as larger than SHORT and smaller than * MEDIUM. And so on. These constants are set to conservative values, * but even so, if there is ever any doubt, they can all be increased * in one spot to rerun tests on slower platforms.</li> * * <li> All threads generated must be joined inside each test case * method (or {@code fail} to do so) before returning from the * method. The {@code joinPool} method can be used to do this when * using Executors.</li> * * </ol> * * <p> <b>Other notes</b> * <ul> * * <li> Usually, there is one testcase method per JSR166 method * covering "normal" operation, and then as many exception-testing * methods as there are exceptions the method can throw. Sometimes * there are multiple tests per JSR166 method when the different * "normal" behaviors differ significantly. And sometimes testcases * cover multiple methods when they cannot be tested in * isolation.</li> * * <li> The documentation style for testcases is to provide as javadoc * a simple sentence or two describing the property that the testcase * method purports to test. The javadocs do not say anything about how * the property is tested. To find out, read the code.</li> * * <li> These tests are "conformance tests", and do not attempt to * test throughput, latency, scalability or other performance factors * (see the separate "jtreg" tests for a set intended to check these * for the most central aspects of functionality.) So, most tests use * the smallest sensible numbers of threads, collection sizes, etc * needed to check basic conformance.</li> * * <li>The test classes currently do not declare inclusion in * any particular package to simplify things for people integrating * them in TCK test suites.</li> * * <li> As a convenience, the {@code main} of this class (JSR166TestCase) * runs all JSR166 unit tests.</li> * * </ul> */ abstract class JSR166TestCase extends TestCase { private static final boolean useSecurityManager = Boolean.getBoolean("jsr166.useSecurityManager"); protected static final boolean expensiveTests = Boolean.getBoolean("jsr166.expensiveTests"); /** * If true, report on stdout all "slow" tests, that is, ones that * take more than profileThreshold milliseconds to execute. */ private static final boolean profileTests = Boolean.getBoolean("jsr166.profileTests"); /** * The number of milliseconds that tests are permitted for * execution without being reported, when profileTests is set. */ private static final long profileThreshold = Long.getLong("jsr166.profileThreshold", 100); protected void runTest() throws Throwable { if (profileTests) runTestProfiled(); else super.runTest(); } protected void runTestProfiled() throws Throwable { long t0 = System.nanoTime(); try { super.runTest(); } finally { long elapsedMillis = (System.nanoTime() - t0) / (1000L * 1000L); if (elapsedMillis >= profileThreshold) System.out.printf("%n%s: %d%n", toString(), elapsedMillis); } } // /** // * Runs all JSR166 unit tests using junit.textui.TestRunner // */ // public static void main(String[] args) { // if (useSecurityManager) { // System.err.println("Setting a permissive security manager"); // Policy.setPolicy(permissivePolicy()); // System.setSecurityManager(new SecurityManager()); // } // int iters = (args.length == 0) ? 1 : Integer.parseInt(args[0]); // Test s = suite(); // for (int i = 0; i < iters; ++i) { // junit.textui.TestRunner.run(s); // System.gc(); // System.runFinalization(); // } // System.exit(0); // } // public static TestSuite newTestSuite(Object... suiteOrClasses) { // TestSuite suite = new TestSuite(); // for (Object suiteOrClass : suiteOrClasses) { // if (suiteOrClass instanceof TestSuite) // suite.addTest((TestSuite) suiteOrClass); // else if (suiteOrClass instanceof Class) // suite.addTest(new TestSuite((Class<?>) suiteOrClass)); // else // throw new ClassCastException("not a test suite or class"); // } // return suite; // } // /** // * Collects all JSR166 unit tests as one suite. // */ // public static Test suite() { // return newTestSuite( // ForkJoinPoolTest.suite(), // ForkJoinTaskTest.suite(), // RecursiveActionTest.suite(), // RecursiveTaskTest.suite(), // LinkedTransferQueueTest.suite(), // PhaserTest.suite(), // ThreadLocalRandomTest.suite(), // AbstractExecutorServiceTest.suite(), // AbstractQueueTest.suite(), // AbstractQueuedSynchronizerTest.suite(), // AbstractQueuedLongSynchronizerTest.suite(), // ArrayBlockingQueueTest.suite(), // ArrayDequeTest.suite(), // AtomicBooleanTest.suite(), // AtomicIntegerArrayTest.suite(), // AtomicIntegerFieldUpdaterTest.suite(), // AtomicIntegerTest.suite(), // AtomicLongArrayTest.suite(), // AtomicLongFieldUpdaterTest.suite(), // AtomicLongTest.suite(), // AtomicMarkableReferenceTest.suite(), // AtomicReferenceArrayTest.suite(), // AtomicReferenceFieldUpdaterTest.suite(), // AtomicReferenceTest.suite(), // AtomicStampedReferenceTest.suite(), // ConcurrentHashMapTest.suite(), // ConcurrentLinkedDequeTest.suite(), // ConcurrentLinkedQueueTest.suite(), // ConcurrentSkipListMapTest.suite(), // ConcurrentSkipListSubMapTest.suite(), // ConcurrentSkipListSetTest.suite(), // ConcurrentSkipListSubSetTest.suite(), // CopyOnWriteArrayListTest.suite(), // CopyOnWriteArraySetTest.suite(), // CountDownLatchTest.suite(), // CyclicBarrierTest.suite(), // DelayQueueTest.suite(), // EntryTest.suite(), // ExchangerTest.suite(), // ExecutorsTest.suite(), // ExecutorCompletionServiceTest.suite(), // FutureTaskTest.suite(), // LinkedBlockingDequeTest.suite(), // LinkedBlockingQueueTest.suite(), // LinkedListTest.suite(), // LockSupportTest.suite(), // PriorityBlockingQueueTest.suite(), // PriorityQueueTest.suite(), // ReentrantLockTest.suite(), // ReentrantReadWriteLockTest.suite(), // ScheduledExecutorTest.suite(), // ScheduledExecutorSubclassTest.suite(), // SemaphoreTest.suite(), // SynchronousQueueTest.suite(), // SystemTest.suite(), // ThreadLocalTest.suite(), // ThreadPoolExecutorTest.suite(), // ThreadPoolExecutorSubclassTest.suite(), // ThreadTest.suite(), // TimeUnitTest.suite(), // TreeMapTest.suite(), // TreeSetTest.suite(), // TreeSubMapTest.suite(), // TreeSubSetTest.suite()); // } public static long SHORT_DELAY_MS; public static long SMALL_DELAY_MS; public static long MEDIUM_DELAY_MS; public static long LONG_DELAY_MS; /** * Returns the shortest timed delay. This could * be reimplemented to use for example a Property. */ protected long getShortDelay() { return 50; } /** * Sets delays as multiples of SHORT_DELAY. */ protected void setDelays() { SHORT_DELAY_MS = getShortDelay(); SMALL_DELAY_MS = SHORT_DELAY_MS * 5; MEDIUM_DELAY_MS = SHORT_DELAY_MS * 10; LONG_DELAY_MS = SHORT_DELAY_MS * 200; } /** * Returns a timeout in milliseconds to be used in tests that * verify that operations block or time out. */ long timeoutMillis() { return SHORT_DELAY_MS / 4; } /** * Returns a new Date instance representing a time delayMillis * milliseconds in the future. */ Date delayedDate(long delayMillis) { return new Date(System.currentTimeMillis() + delayMillis); } /** * The first exception encountered if any threadAssertXXX method fails. */ private final AtomicReference<Throwable> threadFailure = new AtomicReference<Throwable>(null); /** * Records an exception so that it can be rethrown later in the test * harness thread, triggering a test case failure. Only the first * failure is recorded; subsequent calls to this method from within * the same test have no effect. */ public void threadRecordFailure(Throwable t) { threadFailure.compareAndSet(null, t); } public void setUp() { setDelays(); } /** * Extra checks that get done for all test cases. * * Triggers test case failure if any thread assertions have failed, * by rethrowing, in the test harness thread, any exception recorded * earlier by threadRecordFailure. * * Triggers test case failure if interrupt status is set in the main thread. */ public void tearDown() throws Exception { Throwable t = threadFailure.getAndSet(null); if (t != null) { if (t instanceof Error) throw (Error) t; else if (t instanceof RuntimeException) throw (RuntimeException) t; else if (t instanceof Exception) throw (Exception) t; else { AssertionFailedError afe = new AssertionFailedError(t.toString()); afe.initCause(t); throw afe; } } if (Thread.interrupted()) throw new AssertionFailedError("interrupt status set in main thread"); } /** * Just like fail(reason), but additionally recording (using * threadRecordFailure) any AssertionFailedError thrown, so that * the current testcase will fail. */ public void threadFail(String reason) { try { fail(reason); } catch (AssertionFailedError t) { threadRecordFailure(t); fail(reason); } } /** * Just like assertTrue(b), but additionally recording (using * threadRecordFailure) any AssertionFailedError thrown, so that * the current testcase will fail. */ public void threadAssertTrue(boolean b) { try { assertTrue(b); } catch (AssertionFailedError t) { threadRecordFailure(t); throw t; } } /** * Just like assertFalse(b), but additionally recording (using * threadRecordFailure) any AssertionFailedError thrown, so that * the current testcase will fail. */ public void threadAssertFalse(boolean b) { try { assertFalse(b); } catch (AssertionFailedError t) { threadRecordFailure(t); throw t; } } /** * Just like assertNull(x), but additionally recording (using * threadRecordFailure) any AssertionFailedError thrown, so that * the current testcase will fail. */ public void threadAssertNull(Object x) { try { assertNull(x); } catch (AssertionFailedError t) { threadRecordFailure(t); throw t; } } /** * Just like assertEquals(x, y), but additionally recording (using * threadRecordFailure) any AssertionFailedError thrown, so that * the current testcase will fail. */ public void threadAssertEquals(long x, long y) { try { assertEquals(x, y); } catch (AssertionFailedError t) { threadRecordFailure(t); throw t; } } /** * Just like assertEquals(x, y), but additionally recording (using * threadRecordFailure) any AssertionFailedError thrown, so that * the current testcase will fail. */ public void threadAssertEquals(Object x, Object y) { try { assertEquals(x, y); } catch (AssertionFailedError t) { threadRecordFailure(t); throw t; } catch (Throwable t) { threadUnexpectedException(t); } } /** * Just like assertSame(x, y), but additionally recording (using * threadRecordFailure) any AssertionFailedError thrown, so that * the current testcase will fail. */ public void threadAssertSame(Object x, Object y) { try { assertSame(x, y); } catch (AssertionFailedError t) { threadRecordFailure(t); throw t; } } /** * Calls threadFail with message "should throw exception". */ public void threadShouldThrow() { threadFail("should throw exception"); } /** * Calls threadFail with message "should throw" + exceptionName. */ public void threadShouldThrow(String exceptionName) { threadFail("should throw " + exceptionName); } /** * Records the given exception using {@link #threadRecordFailure}, * then rethrows the exception, wrapping it in an * AssertionFailedError if necessary. */ public void threadUnexpectedException(Throwable t) { threadRecordFailure(t); t.printStackTrace(); if (t instanceof RuntimeException) throw (RuntimeException) t; else if (t instanceof Error) throw (Error) t; else { AssertionFailedError afe = new AssertionFailedError("unexpected exception: " + t); afe.initCause(t); throw afe; } } /** * Delays, via Thread.sleep, for the given millisecond delay, but * if the sleep is shorter than specified, may re-sleep or yield * until time elapses. */ static void delay(long millis) throws InterruptedException { long startTime = System.nanoTime(); long ns = millis * 1000 * 1000; for (;;) { if (millis > 0L) Thread.sleep(millis); else // too short to sleep Thread.yield(); long d = ns - (System.nanoTime() - startTime); if (d > 0L) millis = d / (1000 * 1000); else break; } } /** * Waits out termination of a thread pool or fails doing so. */ void joinPool(ExecutorService exec) { try { exec.shutdown(); assertTrue("ExecutorService did not terminate in a timely manner", exec.awaitTermination(2 * LONG_DELAY_MS, MILLISECONDS)); } catch (SecurityException ok) { // Allowed in case test doesn't have privs } catch (InterruptedException ie) { fail("Unexpected InterruptedException"); } } /** * Checks that thread does not terminate within the default * millisecond delay of {@code timeoutMillis()}. */ void assertThreadStaysAlive(Thread thread) { assertThreadStaysAlive(thread, timeoutMillis()); } /** * Checks that thread does not terminate within the given millisecond delay. */ void assertThreadStaysAlive(Thread thread, long millis) { try { // No need to optimize the failing case via Thread.join. delay(millis); assertTrue(thread.isAlive()); } catch (InterruptedException ie) { fail("Unexpected InterruptedException"); } } /** * Checks that the threads do not terminate within the default * millisecond delay of {@code timeoutMillis()}. */ void assertThreadsStayAlive(Thread... threads) { assertThreadsStayAlive(timeoutMillis(), threads); } /** * Checks that the threads do not terminate within the given millisecond delay. */ void assertThreadsStayAlive(long millis, Thread... threads) { try { // No need to optimize the failing case via Thread.join. delay(millis); for (Thread thread : threads) assertTrue(thread.isAlive()); } catch (InterruptedException ie) { fail("Unexpected InterruptedException"); } } /** * Checks that future.get times out, with the default timeout of * {@code timeoutMillis()}. */ void assertFutureTimesOut(Future future) { assertFutureTimesOut(future, timeoutMillis()); } /** * Checks that future.get times out, with the given millisecond timeout. */ void assertFutureTimesOut(Future future, long timeoutMillis) { long startTime = System.nanoTime(); try { future.get(timeoutMillis, MILLISECONDS); shouldThrow(); } catch (TimeoutException success) { } catch (Exception e) { threadUnexpectedException(e); } finally { future.cancel(true); } assertTrue(millisElapsedSince(startTime) >= timeoutMillis); } /** * Fails with message "should throw exception". */ public void shouldThrow() { fail("Should throw exception"); } /** * Fails with message "should throw " + exceptionName. */ public void shouldThrow(String exceptionName) { fail("Should throw " + exceptionName); } /** * The number of elements to place in collections, arrays, etc. */ public static final int SIZE = 20; // Some convenient Integer constants public static final Integer zero = new Integer(0); public static final Integer one = new Integer(1); public static final Integer two = new Integer(2); public static final Integer three = new Integer(3); public static final Integer four = new Integer(4); public static final Integer five = new Integer(5); public static final Integer six = new Integer(6); public static final Integer seven = new Integer(7); public static final Integer eight = new Integer(8); public static final Integer nine = new Integer(9); public static final Integer m1 = new Integer(-1); public static final Integer m2 = new Integer(-2); public static final Integer m3 = new Integer(-3); public static final Integer m4 = new Integer(-4); public static final Integer m5 = new Integer(-5); public static final Integer m6 = new Integer(-6); public static final Integer m10 = new Integer(-10); /** * Runs Runnable r with a security policy that permits precisely * the specified permissions. If there is no current security * manager, the runnable is run twice, both with and without a * security manager. We require that any security manager permit * getPolicy/setPolicy. */ public void runWithPermissions(Runnable r, Permission... permissions) { SecurityManager sm = System.getSecurityManager(); if (sm == null) { r.run(); Policy savedPolicy = Policy.getPolicy(); try { Policy.setPolicy(permissivePolicy()); System.setSecurityManager(new SecurityManager()); runWithPermissions(r, permissions); } finally { System.setSecurityManager(null); Policy.setPolicy(savedPolicy); } } else { Policy savedPolicy = Policy.getPolicy(); AdjustablePolicy policy = new AdjustablePolicy(permissions); Policy.setPolicy(policy); try { r.run(); } finally { policy.addPermission(new SecurityPermission("setPolicy")); Policy.setPolicy(savedPolicy); } } } /** * Runs a runnable without any permissions. */ public void runWithoutPermissions(Runnable r) { runWithPermissions(r); } /** * A security policy where new permissions can be dynamically added * or all cleared. */ public static class AdjustablePolicy extends java.security.Policy { Permissions perms = new Permissions(); AdjustablePolicy(Permission... permissions) { for (Permission permission : permissions) perms.add(permission); } void addPermission(Permission perm) { perms.add(perm); } void clearPermissions() { perms = new Permissions(); } public PermissionCollection getPermissions(CodeSource cs) { return perms; } public PermissionCollection getPermissions(ProtectionDomain pd) { return perms; } public boolean implies(ProtectionDomain pd, Permission p) { return perms.implies(p); } public void refresh() {} } /** * Returns a policy containing all the permissions we ever need. */ public static Policy permissivePolicy() { return new AdjustablePolicy // Permissions j.u.c. needs directly (new RuntimePermission("modifyThread"), new RuntimePermission("getClassLoader"), new RuntimePermission("setContextClassLoader"), // Permissions needed to change permissions! new SecurityPermission("getPolicy"), new SecurityPermission("setPolicy"), new RuntimePermission("setSecurityManager"), // Permissions needed by the junit test harness new RuntimePermission("accessDeclaredMembers"), new PropertyPermission("*", "read"), new java.io.FilePermission("<<ALL FILES>>", "read")); } /** * Sleeps until the given time has elapsed. * Throws AssertionFailedError if interrupted. */ void sleep(long millis) { try { delay(millis); } catch (InterruptedException ie) { AssertionFailedError afe = new AssertionFailedError("Unexpected InterruptedException"); afe.initCause(ie); throw afe; } } /** * Spin-waits up to the specified number of milliseconds for the given * thread to enter a wait state: BLOCKED, WAITING, or TIMED_WAITING. */ void waitForThreadToEnterWaitState(Thread thread, long timeoutMillis) { long startTime = System.nanoTime(); for (;;) { Thread.State s = thread.getState(); if (s == Thread.State.BLOCKED || s == Thread.State.WAITING || s == Thread.State.TIMED_WAITING) return; else if (s == Thread.State.TERMINATED) fail("Unexpected thread termination"); else if (millisElapsedSince(startTime) > timeoutMillis) { threadAssertTrue(thread.isAlive()); return; } Thread.yield(); } } /** * Waits up to LONG_DELAY_MS for the given thread to enter a wait * state: BLOCKED, WAITING, or TIMED_WAITING. */ void waitForThreadToEnterWaitState(Thread thread) { waitForThreadToEnterWaitState(thread, LONG_DELAY_MS); } /** * Returns the number of milliseconds since time given by * startNanoTime, which must have been previously returned from a * call to {@link System.nanoTime()}. */ long millisElapsedSince(long startNanoTime) { return NANOSECONDS.toMillis(System.nanoTime() - startNanoTime); } /** * Returns a new started daemon Thread running the given runnable. */ Thread newStartedThread(Runnable runnable) { Thread t = new Thread(runnable); t.setDaemon(true); t.start(); return t; } /** * Waits for the specified time (in milliseconds) for the thread * to terminate (using {@link Thread#join(long)}), else interrupts * the thread (in the hope that it may terminate later) and fails. */ void awaitTermination(Thread t, long timeoutMillis) { try { t.join(timeoutMillis); } catch (InterruptedException ie) { threadUnexpectedException(ie); } finally { if (t.getState() != Thread.State.TERMINATED) { t.interrupt(); fail("Test timed out"); } } } /** * Waits for LONG_DELAY_MS milliseconds for the thread to * terminate (using {@link Thread#join(long)}), else interrupts * the thread (in the hope that it may terminate later) and fails. */ void awaitTermination(Thread t) { awaitTermination(t, LONG_DELAY_MS); } // Some convenient Runnable classes public abstract class CheckedRunnable implements Runnable { protected abstract void realRun() throws Throwable; public final void run() { try { realRun(); } catch (Throwable t) { threadUnexpectedException(t); } } } public abstract class RunnableShouldThrow implements Runnable { protected abstract void realRun() throws Throwable; final Class<?> exceptionClass; <T extends Throwable> RunnableShouldThrow(Class<T> exceptionClass) { this.exceptionClass = exceptionClass; } public final void run() { try { realRun(); threadShouldThrow(exceptionClass.getSimpleName()); } catch (Throwable t) { if (! exceptionClass.isInstance(t)) threadUnexpectedException(t); } } } public abstract class ThreadShouldThrow extends Thread { protected abstract void realRun() throws Throwable; final Class<?> exceptionClass; <T extends Throwable> ThreadShouldThrow(Class<T> exceptionClass) { this.exceptionClass = exceptionClass; } public final void run() { try { realRun(); threadShouldThrow(exceptionClass.getSimpleName()); } catch (Throwable t) { if (! exceptionClass.isInstance(t)) threadUnexpectedException(t); } } } public abstract class CheckedInterruptedRunnable implements Runnable { protected abstract void realRun() throws Throwable; public final void run() { try { realRun(); threadShouldThrow("InterruptedException"); } catch (InterruptedException success) { threadAssertFalse(Thread.interrupted()); } catch (Throwable t) { threadUnexpectedException(t); } } } public abstract class CheckedCallable<T> implements Callable<T> { protected abstract T realCall() throws Throwable; public final T call() { try { return realCall(); } catch (Throwable t) { threadUnexpectedException(t); return null; } } } public abstract class CheckedInterruptedCallable<T> implements Callable<T> { protected abstract T realCall() throws Throwable; public final T call() { try { T result = realCall(); threadShouldThrow("InterruptedException"); return result; } catch (InterruptedException success) { threadAssertFalse(Thread.interrupted()); } catch (Throwable t) { threadUnexpectedException(t); } return null; } } public static class NoOpRunnable implements Runnable { public void run() {} } public static class NoOpCallable implements Callable { public Object call() { return Boolean.TRUE; } } public static final String TEST_STRING = "a test string"; public static class StringTask implements Callable<String> { public String call() { return TEST_STRING; } } public Callable<String> latchAwaitingStringTask(final CountDownLatch latch) { return new CheckedCallable<String>() { protected String realCall() { try { latch.await(); } catch (InterruptedException quittingTime) {} return TEST_STRING; }}; } public Runnable awaiter(final CountDownLatch latch) { return new CheckedRunnable() { public void realRun() throws InterruptedException { await(latch); }}; } public void await(CountDownLatch latch) { try { assertTrue(latch.await(LONG_DELAY_MS, MILLISECONDS)); } catch (Throwable t) { threadUnexpectedException(t); } } public void await(Semaphore semaphore) { try { assertTrue(semaphore.tryAcquire(LONG_DELAY_MS, MILLISECONDS)); } catch (Throwable t) { threadUnexpectedException(t); } } // /** // * Spin-waits up to LONG_DELAY_MS until flag becomes true. // */ // public void await(AtomicBoolean flag) { // await(flag, LONG_DELAY_MS); // } // /** // * Spin-waits up to the specified timeout until flag becomes true. // */ // public void await(AtomicBoolean flag, long timeoutMillis) { // long startTime = System.nanoTime(); // while (!flag.get()) { // if (millisElapsedSince(startTime) > timeoutMillis) // throw new AssertionFailedError("timed out"); // Thread.yield(); // } // } public static class NPETask implements Callable<String> { public String call() { throw new NullPointerException(); } } public static class CallableOne implements Callable<Integer> { public Integer call() { return one; } } public class ShortRunnable extends CheckedRunnable { protected void realRun() throws Throwable { delay(SHORT_DELAY_MS); } } public class ShortInterruptedRunnable extends CheckedInterruptedRunnable { protected void realRun() throws InterruptedException { delay(SHORT_DELAY_MS); } } public class SmallRunnable extends CheckedRunnable { protected void realRun() throws Throwable { delay(SMALL_DELAY_MS); } } public class SmallPossiblyInterruptedRunnable extends CheckedRunnable { protected void realRun() { try { delay(SMALL_DELAY_MS); } catch (InterruptedException ok) {} } } public class SmallCallable extends CheckedCallable { protected Object realCall() throws InterruptedException { delay(SMALL_DELAY_MS); return Boolean.TRUE; } } public class MediumRunnable extends CheckedRunnable { protected void realRun() throws Throwable { delay(MEDIUM_DELAY_MS); } } public class MediumInterruptedRunnable extends CheckedInterruptedRunnable { protected void realRun() throws InterruptedException { delay(MEDIUM_DELAY_MS); } } public Runnable possiblyInterruptedRunnable(final long timeoutMillis) { return new CheckedRunnable() { protected void realRun() { try { delay(timeoutMillis); } catch (InterruptedException ok) {} }}; } public class MediumPossiblyInterruptedRunnable extends CheckedRunnable { protected void realRun() { try { delay(MEDIUM_DELAY_MS); } catch (InterruptedException ok) {} } } public class LongPossiblyInterruptedRunnable extends CheckedRunnable { protected void realRun() { try { delay(LONG_DELAY_MS); } catch (InterruptedException ok) {} } } /** * For use as ThreadFactory in constructors */ public static class SimpleThreadFactory implements ThreadFactory { public Thread newThread(Runnable r) { return new Thread(r); } } public interface TrackedRunnable extends Runnable { boolean isDone(); } public static TrackedRunnable trackedRunnable(final long timeoutMillis) { return new TrackedRunnable() { private volatile boolean done = false; public boolean isDone() { return done; } public void run() { try { delay(timeoutMillis); done = true; } catch (InterruptedException ok) {} } }; } public static class TrackedShortRunnable implements Runnable { public volatile boolean done = false; public void run() { try { delay(SHORT_DELAY_MS); done = true; } catch (InterruptedException ok) {} } } public static class TrackedSmallRunnable implements Runnable { public volatile boolean done = false; public void run() { try { delay(SMALL_DELAY_MS); done = true; } catch (InterruptedException ok) {} } } public static class TrackedMediumRunnable implements Runnable { public volatile boolean done = false; public void run() { try { delay(MEDIUM_DELAY_MS); done = true; } catch (InterruptedException ok) {} } } public static class TrackedLongRunnable implements Runnable { public volatile boolean done = false; public void run() { try { delay(LONG_DELAY_MS); done = true; } catch (InterruptedException ok) {} } } public static class TrackedNoOpRunnable implements Runnable { public volatile boolean done = false; public void run() { done = true; } } public static class TrackedCallable implements Callable { public volatile boolean done = false; public Object call() { try { delay(SMALL_DELAY_MS); done = true; } catch (InterruptedException ok) {} return Boolean.TRUE; } } // /** // * Analog of CheckedRunnable for RecursiveAction // */ // public abstract class CheckedRecursiveAction extends RecursiveAction { // protected abstract void realCompute() throws Throwable; // public final void compute() { // try { // realCompute(); // } catch (Throwable t) { // threadUnexpectedException(t); // } // } // } // /** // * Analog of CheckedCallable for RecursiveTask // */ // public abstract class CheckedRecursiveTask<T> extends RecursiveTask<T> { // protected abstract T realCompute() throws Throwable; // public final T compute() { // try { // return realCompute(); // } catch (Throwable t) { // threadUnexpectedException(t); // return null; // } // } // } /** * For use as RejectedExecutionHandler in constructors */ public static class NoOpREHandler implements RejectedExecutionHandler { public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {} } /** * A CyclicBarrier that uses timed await and fails with * AssertionFailedErrors instead of throwing checked exceptions. */ public class CheckedBarrier extends CyclicBarrier { public CheckedBarrier(int parties) { super(parties); } public int await() { try { return super.await(2 * LONG_DELAY_MS, MILLISECONDS); } catch (TimeoutException e) { throw new AssertionFailedError("timed out"); } catch (Exception e) { AssertionFailedError afe = new AssertionFailedError("Unexpected exception: " + e); afe.initCause(e); throw afe; } } } void checkEmpty(BlockingQueue q) { try { assertTrue(q.isEmpty()); assertEquals(0, q.size()); assertNull(q.peek()); assertNull(q.poll()); assertNull(q.poll(0, MILLISECONDS)); assertEquals(q.toString(), "[]"); assertTrue(Arrays.equals(q.toArray(), new Object[0])); assertFalse(q.iterator().hasNext()); try { q.element(); shouldThrow(); } catch (NoSuchElementException success) {} try { q.iterator().next(); shouldThrow(); } catch (NoSuchElementException success) {} try { q.remove(); shouldThrow(); } catch (NoSuchElementException success) {} } catch (InterruptedException ie) { threadUnexpectedException(ie); } } @SuppressWarnings("unchecked") <T> T serialClone(T o) { try { ByteArrayOutputStream bos = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(bos); oos.writeObject(o); oos.flush(); oos.close(); ObjectInputStream ois = new ObjectInputStream (new ByteArrayInputStream(bos.toByteArray())); T clone = (T) ois.readObject(); assertSame(o.getClass(), clone.getClass()); return clone; } catch (Throwable t) { threadUnexpectedException(t); return null; } } }
zzhhhhh-aw4rwer
guava-tests/test/com/google/common/util/concurrent/JSR166TestCase.java
Java
asf20
41,264
/* * Copyright (C) 2011 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.util.concurrent; import static com.google.common.base.Preconditions.checkNotNull; import static java.util.concurrent.TimeUnit.MILLISECONDS; import static java.util.concurrent.TimeUnit.NANOSECONDS; import static junit.framework.Assert.fail; import com.google.common.testing.TearDown; import com.google.common.testing.TearDownAccepter; import java.util.concurrent.TimeUnit; import java.util.logging.Logger; /** * Utilities for performing thread interruption in tests * * @author Kevin Bourrillion * @author Chris Povirk */ final class InterruptionUtil { private static final Logger logger = Logger.getLogger(InterruptionUtil.class.getName()); /** * Runnable which will interrupt the target thread repeatedly when run. */ private static final class Interruptenator implements Runnable { private final long everyMillis; private final Thread interruptee; private volatile boolean shouldStop = false; Interruptenator(Thread interruptee, long everyMillis) { this.everyMillis = everyMillis; this.interruptee = interruptee; } @Override public void run() { while (true) { try { Thread.sleep(everyMillis); } catch (InterruptedException e) { // ok. just stop sleeping. } if (shouldStop) { break; } interruptee.interrupt(); } } void stopInterrupting() { shouldStop = true; } } /** * Interrupts the current thread after sleeping for the specified delay. */ static void requestInterruptIn(final long time, final TimeUnit unit) { checkNotNull(unit); final Thread interruptee = Thread.currentThread(); new Thread(new Runnable() { @Override public void run() { try { unit.sleep(time); } catch (InterruptedException wontHappen) { throw new AssertionError(wontHappen); } interruptee.interrupt(); } }).start(); } static void repeatedlyInterruptTestThread( long interruptPeriodMillis, TearDownAccepter tearDownAccepter) { final Interruptenator interruptingTask = new Interruptenator(Thread.currentThread(), interruptPeriodMillis); final Thread interruptingThread = new Thread(interruptingTask); interruptingThread.start(); tearDownAccepter.addTearDown(new TearDown() { @Override public void tearDown() throws Exception { interruptingTask.stopInterrupting(); interruptingThread.interrupt(); joinUninterruptibly(interruptingThread, 2500, MILLISECONDS); Thread.interrupted(); if (interruptingThread.isAlive()) { // This will be hidden by test-output redirection: logger.severe( "InterruptenatorTask did not exit; future tests may be affected"); /* * This won't do any good under JUnit 3, but I'll leave it around in * case we ever switch to JUnit 4: */ fail(); } } }); } // TODO(cpovirk): promote to Uninterruptibles, and add untimed version private static void joinUninterruptibly( Thread thread, long timeout, TimeUnit unit) { boolean interrupted = false; try { long remainingNanos = unit.toNanos(timeout); long end = System.nanoTime() + remainingNanos; while (true) { try { // TimeUnit.timedJoin() treats negative timeouts just like zero. NANOSECONDS.timedJoin(thread, remainingNanos); return; } catch (InterruptedException e) { interrupted = true; remainingNanos = end - System.nanoTime(); } } } finally { if (interrupted) { Thread.currentThread().interrupt(); } } } }
zzhhhhh-aw4rwer
guava-tests/test/com/google/common/util/concurrent/InterruptionUtil.java
Java
asf20
4,391
/* * Copyright (C) 2012 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.util.concurrent; import com.google.common.base.Function; import com.google.common.base.Throwables; import com.google.common.collect.ForwardingObject; import com.google.common.collect.Iterables; import com.google.common.testing.ForwardingWrapperTester; import org.easymock.EasyMock; import java.lang.reflect.Method; import java.util.Arrays; /** * Tester for typical subclass of {@link ForwardingObject} by using EasyMock partial mocks. * * @author Ben Yu */ final class ForwardingObjectTester { private static final Method DELEGATE_METHOD; static { try { DELEGATE_METHOD = ForwardingObject.class.getDeclaredMethod("delegate"); DELEGATE_METHOD.setAccessible(true); } catch (SecurityException e) { throw new RuntimeException(e); } catch (NoSuchMethodException e) { throw new AssertionError(e); } } /** * Ensures that all interface methods of {@code forwarderClass} are forwarded to the * {@link ForwardingObject#delegate}. {@code forwarderClass} is assumed to only implement one * interface. */ static <T extends ForwardingObject> void testForwardingObject(final Class<T> forwarderClass) { @SuppressWarnings("unchecked") // super interface type of T Class<? super T> interfaceType = (Class<? super T>) Iterables.getOnlyElement(Arrays.asList(forwarderClass.getInterfaces())); new ForwardingWrapperTester().testForwarding(interfaceType, new Function<Object, T>() { @Override public T apply(Object delegate) { T mock = EasyMock.createMockBuilder(forwarderClass) .addMockedMethod(DELEGATE_METHOD) .createMock(); try { DELEGATE_METHOD.invoke(mock); } catch (Exception e) { throw Throwables.propagate(e); } EasyMock.expectLastCall().andStubReturn(delegate); EasyMock.replay(mock); return mock; } }); } }
zzhhhhh-aw4rwer
guava-tests/test/com/google/common/util/concurrent/ForwardingObjectTester.java
Java
asf20
2,533
/* * Copyright (C) 2009 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.util.concurrent; import static com.google.common.base.Preconditions.checkNotNull; import static junit.framework.Assert.assertEquals; import static junit.framework.Assert.assertFalse; import static junit.framework.Assert.assertTrue; import static junit.framework.Assert.fail; import java.util.concurrent.CancellationException; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import javax.annotation.Nullable; /** * Used to test listenable future implementations. * * @author Sven Mawson */ public class ListenableFutureTester { private final ExecutorService exec; private final ListenableFuture<?> future; private final CountDownLatch latch; public ListenableFutureTester(ListenableFuture<?> future) { this.exec = Executors.newCachedThreadPool(); this.future = checkNotNull(future); this.latch = new CountDownLatch(1); } public void setUp() { future.addListener(new Runnable() { @Override public void run() { latch.countDown(); } }, exec); assertEquals(1, latch.getCount()); assertFalse(future.isDone()); assertFalse(future.isCancelled()); } public void tearDown() { exec.shutdown(); } public void testCompletedFuture(@Nullable Object expectedValue) throws InterruptedException, ExecutionException { assertTrue(future.isDone()); assertFalse(future.isCancelled()); assertTrue(latch.await(5, TimeUnit.SECONDS)); assertTrue(future.isDone()); assertFalse(future.isCancelled()); assertEquals(expectedValue, future.get()); } public void testCancelledFuture() throws InterruptedException, ExecutionException { assertTrue(future.isDone()); assertTrue(future.isCancelled()); assertTrue(latch.await(5, TimeUnit.SECONDS)); assertTrue(future.isDone()); assertTrue(future.isCancelled()); try { future.get(); fail("Future should throw CancellationException on cancel."); } catch (CancellationException expected) {} } public void testFailedFuture(@Nullable String message) throws InterruptedException { assertTrue(future.isDone()); assertFalse(future.isCancelled()); assertTrue(latch.await(5, TimeUnit.SECONDS)); assertTrue(future.isDone()); assertFalse(future.isCancelled()); try { future.get(); fail("Future should rethrow the exception."); } catch (ExecutionException e) { assertEquals(message, e.getCause().getMessage()); } } }
zzhhhhh-aw4rwer
guava-tests/test/com/google/common/util/concurrent/ListenableFutureTester.java
Java
asf20
3,250
/* * Copyright (C) 2011 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.math; import static java.math.BigInteger.ONE; import static java.math.BigInteger.ZERO; import static java.math.RoundingMode.CEILING; import static java.math.RoundingMode.DOWN; import static java.math.RoundingMode.FLOOR; import static java.math.RoundingMode.HALF_DOWN; import static java.math.RoundingMode.HALF_EVEN; import static java.math.RoundingMode.HALF_UP; import static java.math.RoundingMode.UP; import static java.util.Arrays.asList; import com.google.common.annotations.GwtCompatible; import com.google.common.base.Function; import com.google.common.base.Predicate; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Iterables; import com.google.common.primitives.Doubles; import java.math.BigInteger; import java.math.RoundingMode; /** * Exhaustive input sets for every integral type. * * @author Louis Wasserman */ @GwtCompatible public class MathTesting { static final ImmutableSet<RoundingMode> ALL_ROUNDING_MODES = ImmutableSet.copyOf(RoundingMode .values()); static final ImmutableList<RoundingMode> ALL_SAFE_ROUNDING_MODES = ImmutableList.of(DOWN, UP, FLOOR, CEILING, HALF_EVEN, HALF_UP, HALF_DOWN); // Exponents to test for the pow() function. static final ImmutableList<Integer> EXPONENTS = ImmutableList.of(0, 1, 2, 3, 4, 7, 10, 15, 20, 25, 40, 70); /* Helper function to make a Long value from an Integer. */ private static final Function<Integer, Long> TO_LONG = new Function<Integer, Long>() { @Override public Long apply(Integer n) { return Long.valueOf(n); } }; /* Helper function to make a BigInteger value from a Long. */ private static final Function<Long, BigInteger> TO_BIGINTEGER = new Function<Long, BigInteger>() { @Override public BigInteger apply(Long n) { return BigInteger.valueOf(n); } }; private static final Function<Integer, Integer> NEGATE_INT = new Function<Integer, Integer>() { @Override public Integer apply(Integer x) { return -x; } }; private static final Function<Long, Long> NEGATE_LONG = new Function<Long, Long>() { @Override public Long apply(Long x) { return -x; } }; private static final Function<BigInteger, BigInteger> NEGATE_BIGINT = new Function<BigInteger, BigInteger>() { @Override public BigInteger apply(BigInteger x) { return x.negate(); } }; /* * This list contains values that attempt to provoke overflow in integer operations. It contains * positive values on or near 2^N for N near multiples of 8 (near byte boundaries). */ static final ImmutableSet<Integer> POSITIVE_INTEGER_CANDIDATES; static final Iterable<Integer> NEGATIVE_INTEGER_CANDIDATES; static final Iterable<Integer> NONZERO_INTEGER_CANDIDATES; static final Iterable<Integer> ALL_INTEGER_CANDIDATES; static { ImmutableSet.Builder<Integer> intValues = ImmutableSet.builder(); // Add boundary values manually to avoid over/under flow (this covers 2^N for 0 and 31). intValues.add(Integer.MAX_VALUE - 1, Integer.MAX_VALUE); // Add values up to 40. This covers cases like "square of a prime" and such. for (int i = 1; i <= 40; i++) { intValues.add(i); } // Now add values near 2^N for lots of values of N. for (int exponent : asList(2, 3, 4, 9, 15, 16, 17, 24, 25, 30)) { int x = 1 << exponent; intValues.add(x, x + 1, x - 1); } intValues.add(9999).add(10000).add(10001).add(1000000); // near powers of 10 intValues.add(5792).add(5793); // sqrt(2^25) rounded up and down POSITIVE_INTEGER_CANDIDATES = intValues.build(); NEGATIVE_INTEGER_CANDIDATES = ImmutableList.copyOf(Iterables.concat( Iterables.transform(POSITIVE_INTEGER_CANDIDATES, NEGATE_INT), ImmutableList.of(Integer.MIN_VALUE))); NONZERO_INTEGER_CANDIDATES = ImmutableList.copyOf( Iterables.concat(POSITIVE_INTEGER_CANDIDATES, NEGATIVE_INTEGER_CANDIDATES)); ALL_INTEGER_CANDIDATES = Iterables.concat(NONZERO_INTEGER_CANDIDATES, ImmutableList.of(0)); } /* * This list contains values that attempt to provoke overflow in long operations. It contains * positive values on or near 2^N for N near multiples of 8 (near byte boundaries). This list is * a superset of POSITIVE_INTEGER_CANDIDATES. */ static final ImmutableSet<Long> POSITIVE_LONG_CANDIDATES; static final Iterable<Long> NEGATIVE_LONG_CANDIDATES; static final Iterable<Long> NONZERO_LONG_CANDIDATES; static final Iterable<Long> ALL_LONG_CANDIDATES; static { ImmutableSet.Builder<Long> longValues = ImmutableSet.builder(); // First of all add all the integer candidate values. longValues.addAll(Iterables.transform(POSITIVE_INTEGER_CANDIDATES, TO_LONG)); // Add boundary values manually to avoid over/under flow (this covers 2^N for 31 and 63). longValues.add(Integer.MAX_VALUE + 1L, Long.MAX_VALUE - 1L, Long.MAX_VALUE); // Now add values near 2^N for lots of values of N. for (int exponent : asList(32, 33, 39, 40, 41, 47, 48, 49, 55, 56, 57)) { long x = 1L << exponent; longValues.add(x, x + 1, x - 1); } longValues.add(194368031998L).add(194368031999L); // sqrt(2^75) rounded up and down POSITIVE_LONG_CANDIDATES = longValues.build(); NEGATIVE_LONG_CANDIDATES = Iterables.concat(Iterables.transform(POSITIVE_LONG_CANDIDATES, NEGATE_LONG), ImmutableList.of(Long.MIN_VALUE)); NONZERO_LONG_CANDIDATES = Iterables.concat(POSITIVE_LONG_CANDIDATES, NEGATIVE_LONG_CANDIDATES); ALL_LONG_CANDIDATES = Iterables.concat(NONZERO_LONG_CANDIDATES, ImmutableList.of(0L)); } /* * This list contains values that attempt to provoke overflow in big integer operations. It * contains positive values on or near 2^N for N near multiples of 8 (near byte boundaries). This * list is a superset of POSITIVE_LONG_CANDIDATES. */ static final ImmutableSet<BigInteger> POSITIVE_BIGINTEGER_CANDIDATES; static final Iterable<BigInteger> NEGATIVE_BIGINTEGER_CANDIDATES; static final Iterable<BigInteger> NONZERO_BIGINTEGER_CANDIDATES; static final Iterable<BigInteger> ALL_BIGINTEGER_CANDIDATES; static { ImmutableSet.Builder<BigInteger> bigValues = ImmutableSet.builder(); // First of all add all the long candidate values. bigValues.addAll(Iterables.transform(POSITIVE_LONG_CANDIDATES, TO_BIGINTEGER)); // Add boundary values manually to avoid over/under flow. bigValues.add(BigInteger.valueOf(Long.MAX_VALUE).add(ONE)); // Now add values near 2^N for lots of values of N. for (int exponent : asList(64, 65, 71, 72, 73, 79, 80, 81, 255, 256, 257, 511, 512, 513, Double.MAX_EXPONENT - 1, Double.MAX_EXPONENT, Double.MAX_EXPONENT + 1)) { BigInteger x = ONE.shiftLeft(exponent); bigValues.add(x, x.add(ONE), x.subtract(ONE)); } bigValues.add(new BigInteger("218838949120258359057546633")); // sqrt(2^175) rounded up and // down bigValues.add(new BigInteger("218838949120258359057546634")); POSITIVE_BIGINTEGER_CANDIDATES = bigValues.build(); NEGATIVE_BIGINTEGER_CANDIDATES = Iterables.transform(POSITIVE_BIGINTEGER_CANDIDATES, NEGATE_BIGINT); NONZERO_BIGINTEGER_CANDIDATES = Iterables.concat(POSITIVE_BIGINTEGER_CANDIDATES, NEGATIVE_BIGINTEGER_CANDIDATES); ALL_BIGINTEGER_CANDIDATES = Iterables.concat(NONZERO_BIGINTEGER_CANDIDATES, ImmutableList.of(ZERO)); } static final ImmutableSet<Double> INTEGRAL_DOUBLE_CANDIDATES; static final ImmutableSet<Double> FRACTIONAL_DOUBLE_CANDIDATES; static final Iterable<Double> INFINITIES = Doubles.asList( Double.POSITIVE_INFINITY, Double.NEGATIVE_INFINITY); static final Iterable<Double> FINITE_DOUBLE_CANDIDATES; static final Iterable<Double> POSITIVE_FINITE_DOUBLE_CANDIDATES; static final Iterable<Double> ALL_DOUBLE_CANDIDATES; static final Iterable<Double> DOUBLE_CANDIDATES_EXCEPT_NAN; static { ImmutableSet.Builder<Double> integralBuilder = ImmutableSet.builder(); ImmutableSet.Builder<Double> fractionalBuilder = ImmutableSet.builder(); integralBuilder.addAll(Doubles.asList(0.0, -0.0, Double.MAX_VALUE, -Double.MAX_VALUE)); // Add small multiples of MIN_VALUE and MIN_NORMAL for (int scale = 1; scale <= 4; scale++) { for (double d : Doubles.asList(Double.MIN_VALUE, Double.MIN_NORMAL)) { fractionalBuilder.add(d * scale).add(-d * scale); } } for (double d : Doubles.asList(0, 1, 2, 7, 51, 102, Math.scalb(1.0, 53), Integer.MIN_VALUE, Integer.MAX_VALUE, Long.MIN_VALUE, Long.MAX_VALUE)) { for (double delta : Doubles.asList(0.0, 1.0, 2.0)) { integralBuilder.addAll(Doubles.asList(d + delta, d - delta, -d - delta, -d + delta)); } for (double delta : Doubles.asList(0.01, 0.1, 0.25, 0.499, 0.5, 0.501, 0.7, 0.8)) { double x = d + delta; if (x != Math.round(x)) { fractionalBuilder.add(x); } } } INTEGRAL_DOUBLE_CANDIDATES = integralBuilder.build(); fractionalBuilder.add(1.414).add(1.415).add(Math.sqrt(2)); fractionalBuilder.add(5.656).add(5.657).add(4 * Math.sqrt(2)); for (double d : INTEGRAL_DOUBLE_CANDIDATES) { double x = 1 / d; if (x != Math.rint(x)) { fractionalBuilder.add(x); } } FRACTIONAL_DOUBLE_CANDIDATES = fractionalBuilder.build(); FINITE_DOUBLE_CANDIDATES = Iterables.concat(FRACTIONAL_DOUBLE_CANDIDATES, INTEGRAL_DOUBLE_CANDIDATES); POSITIVE_FINITE_DOUBLE_CANDIDATES = Iterables.filter(FINITE_DOUBLE_CANDIDATES, new Predicate<Double>() { @Override public boolean apply(Double input) { return input.doubleValue() > 0.0; } }); DOUBLE_CANDIDATES_EXCEPT_NAN = Iterables.concat(FINITE_DOUBLE_CANDIDATES, INFINITIES); ALL_DOUBLE_CANDIDATES = Iterables.concat(DOUBLE_CANDIDATES_EXCEPT_NAN, asList(Double.NaN)); } }
zzhhhhh-aw4rwer
guava-tests/test/com/google/common/math/MathTesting.java
Java
asf20
10,738
/* * Copyright (C) 2011 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.math; import java.math.BigInteger; import java.util.Random; /** * Utilities for benchmarks. * * @author Louis Wasserman */ final class MathBenchmarking { static final int ARRAY_SIZE = 0x10000; static final int ARRAY_MASK = 0x0ffff; static final Random RANDOM_SOURCE = new Random(314159265358979L); static final int MAX_EXPONENT = 100; /* * Duplicated from LongMath. * binomial(biggestBinomials[k], k) fits in a long, but not * binomial(biggestBinomials[k] + 1, k). */ static final int[] biggestBinomials = {Integer.MAX_VALUE, Integer.MAX_VALUE, Integer.MAX_VALUE, 3810779, 121977, 16175, 4337, 1733, 887, 534, 361, 265, 206, 169, 143, 125, 111, 101, 94, 88, 83, 79, 76, 74, 72, 70, 69, 68, 67, 67, 66, 66, 66, 66}; static BigInteger randomPositiveBigInteger(int numBits) { int digits = RANDOM_SOURCE.nextInt(numBits) + 1; return new BigInteger(digits, RANDOM_SOURCE).add(BigInteger.ONE); } static BigInteger randomNonNegativeBigInteger(int numBits) { int digits = RANDOM_SOURCE.nextInt(numBits) + 1; return new BigInteger(digits, RANDOM_SOURCE); } static BigInteger randomNonZeroBigInteger(int numBits) { BigInteger result = randomPositiveBigInteger(numBits); return RANDOM_SOURCE.nextBoolean() ? result : result.negate(); } static BigInteger randomBigInteger(int numBits) { BigInteger result = randomNonNegativeBigInteger(numBits); return RANDOM_SOURCE.nextBoolean() ? result : result.negate(); } static double randomDouble(int maxExponent) { double result = RANDOM_SOURCE.nextDouble(); result = Math.scalb(result, RANDOM_SOURCE.nextInt(maxExponent + 1)); return RANDOM_SOURCE.nextBoolean() ? result : -result; } /** * Returns a random integer between zero and {@code MAX_EXPONENT}. */ static int randomExponent() { return RANDOM_SOURCE.nextInt(MAX_EXPONENT + 1); } static double randomPositiveDouble() { return Math.exp(randomDouble(6)); } }
zzhhhhh-aw4rwer
guava-tests/test/com/google/common/math/MathBenchmarking.java
Java
asf20
2,624
/* * Copyright (C) 2007 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.eventbus; import com.google.common.collect.Lists; import junit.framework.Assert; import java.util.List; import javax.annotation.Nullable; /** * A simple EventSubscriber mock that records Strings. * * For testing fun, also includes a landmine method that EventBus tests are * required <em>not</em> to call ({@link #methodWithoutAnnotation(String)}). * * @author Cliff Biffle */ public class StringCatcher { private List<String> events = Lists.newArrayList(); @Subscribe public void hereHaveAString(@Nullable String string) { events.add(string); } public void methodWithoutAnnotation(@Nullable String string) { Assert.fail("Event bus must not call methods without @Subscribe!"); } public List<String> getEvents() { return events; } }
zzhhhhh-aw4rwer
guava-tests/test/com/google/common/eventbus/StringCatcher.java
Java
asf20
1,403
/* * Copyright (C) 2012 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.common.base; /** * Common benchmarking utilities. * * @author Christopher Swenson * @author Louis Wasserman */ class BenchmarkHelpers { private static final String WHITESPACE_CHARACTERS = "\u00a0\u180e\u202f\t\n\013\f\r \u0085" + "\u1680\u2028\u2029\u205f\u3000\u2000\u2001\u2002\u2003\u2004\u2005" + "\u2006\u2007\u2008\u2009\u200a"; private static final String ASCII_CHARACTERS; static { int spaceInAscii = 32; int sevenBitAsciiMax = 128; StringBuilder sb = new StringBuilder(sevenBitAsciiMax - spaceInAscii); for (int ch = spaceInAscii; ch < sevenBitAsciiMax; ch++) { sb.append((char) ch); } ASCII_CHARACTERS = sb.toString(); } private static final String ALL_DIGITS; static { StringBuilder sb = new StringBuilder(); String zeros = "0\u0660\u06f0\u07c0\u0966\u09e6\u0a66\u0ae6\u0b66\u0be6\u0c66" + "\u0ce6\u0d66\u0e50\u0ed0\u0f20\u1040\u1090\u17e0\u1810\u1946" + "\u19d0\u1b50\u1bb0\u1c40\u1c50\ua620\ua8d0\ua900\uaa50\uff10"; for (char base : zeros.toCharArray()) { for (int offset = 0; offset < 10; offset++) { sb.append((char) (base + offset)); } } ALL_DIGITS = sb.toString(); } /** * Sample CharMatcher instances for benchmarking. */ public enum SampleMatcherConfig { WHITESPACE(CharMatcher.WHITESPACE, WHITESPACE_CHARACTERS), HASH(CharMatcher.is('#'), "#"), ASCII(CharMatcher.ASCII, ASCII_CHARACTERS), WESTERN_DIGIT("0123456789"), ALL_DIGIT(CharMatcher.DIGIT, ALL_DIGITS), OPS_5("+-*/%"), HEX_16(CharMatcher.inRange('0', '9').or(CharMatcher.inRange('A', 'F')), "0123456789ABCDEF"), HEX_22(CharMatcher.inRange('0', '9') .or(CharMatcher.inRange('A', 'F')).or(CharMatcher.inRange('a', 'f')), "0123456789ABCDEFabcdef"), GERMAN_59(CharMatcher.inRange('a', 'z') .or(CharMatcher.inRange('A', 'Z')).or(CharMatcher.anyOf("äöüßÄÖÜ")), "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZäöüßÄÖÜ"); public final CharMatcher matcher; public final String matchingChars; SampleMatcherConfig(String matchingChars) { this(CharMatcher.anyOf(matchingChars), matchingChars); } SampleMatcherConfig(CharMatcher matcher, String matchingChars) { this.matcher = matcher; this.matchingChars = matchingChars; } } }
zzhhhhh-aw4rwer
guava-tests/test/com/google/common/base/BenchmarkHelpers.java
Java
asf20
3,005
/* * Copyright (C) 2007 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import com.google.common.base.Function; import com.google.common.base.Joiner; import junit.framework.TestCase; import java.lang.reflect.Array; import java.lang.reflect.InvocationHandler; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Proxy; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.Set; /** * Base test case for testing the variety of forwarding classes. * * @author Robert Konigsberg * @author Louis Wasserman */ public abstract class ForwardingTestCase extends TestCase { private final List<String> calls = new ArrayList<String>(); private void called(String id) { calls.add(id); } protected String getCalls() { return calls.toString(); } protected boolean isCalled() { return !calls.isEmpty(); } @SuppressWarnings("unchecked") protected <T> T createProxyInstance(Class<T> c) { /* * This invocation handler only registers that a method was called, * and then returns a bogus, but acceptable, value. */ InvocationHandler handler = new InvocationHandler() { @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { called(asString(method)); return getDefaultValue(method.getReturnType()); } }; return (T) Proxy.newProxyInstance(c.getClassLoader(), new Class[] { c }, handler); } private static final Joiner COMMA_JOINER = Joiner.on(","); /* * Returns string representation of a method. * * If the method takes no parameters, it returns the name (e.g. * "isEmpty". If the method takes parameters, it returns the simple names * of the parameters (e.g. "put(Object,Object)".) */ private String asString(Method method) { String methodName = method.getName(); Class<?>[] parameterTypes = method.getParameterTypes(); if (parameterTypes.length == 0) { return methodName; } Iterable<String> parameterNames = Iterables.transform( Arrays.asList(parameterTypes), new Function<Class<?>, String>() { @Override public String apply(Class<?> from) { return from.getSimpleName(); } }); return methodName + "(" + COMMA_JOINER.join(parameterNames) + ")"; } private static Object getDefaultValue(Class<?> returnType) { if (returnType == boolean.class || returnType == Boolean.class) { return Boolean.FALSE; } else if (returnType == int.class || returnType == Integer.class) { return 0; } else if ((returnType == Set.class) || (returnType == Collection.class)) { return Collections.emptySet(); } else if (returnType == Iterator.class) { return Iterators.emptyModifiableIterator(); } else if (returnType.isArray()) { return Array.newInstance(returnType.getComponentType(), 0); } else { return null; } } protected static <T> void callAllPublicMethods(Class<T> theClass, T object) throws InvocationTargetException { for (Method method : theClass.getMethods()) { Class<?>[] parameterTypes = method.getParameterTypes(); Object[] parameters = new Object[parameterTypes.length]; for (int i = 0; i < parameterTypes.length; i++) { parameters[i] = getDefaultValue(parameterTypes[i]); } try { try { method.invoke(object, parameters); } catch (InvocationTargetException ex) { try { throw ex.getCause(); } catch (UnsupportedOperationException unsupported) { // this is a legit exception } } } catch (Throwable cause) { throw new InvocationTargetException(cause, method + " with args: " + Arrays.toString(parameters)); } } } }
zzhhhhh-aw4rwer
guava-tests/test/com/google/common/collect/ForwardingTestCase.java
Java
asf20
4,570
/* * Copyright (C) 2010 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import static com.google.common.base.Preconditions.checkNotNull; import com.google.common.primitives.Ints; import java.util.Collections; import java.util.List; import java.util.Set; /** * Package up sample data for common collections benchmarking. * * @author Nicholaus Shupe */ class CollectionBenchmarkSampleData { private final boolean isUserTypeFast; private final SpecialRandom random; private final double hitRate; private final int size; private final Set<Element> valuesInSet; private final Element[] queries; CollectionBenchmarkSampleData(int size) { this(true, new SpecialRandom(), 1.0, size); } CollectionBenchmarkSampleData( boolean isUserTypeFast, SpecialRandom random, double hitRate, int size) { this.isUserTypeFast = isUserTypeFast; this.random = checkNotNull(random); this.hitRate = hitRate; this.size = size; this.valuesInSet = createData(); this.queries = createQueries(valuesInSet, 1024); } Set<Element> getValuesInSet() { return valuesInSet; } Element[] getQueries() { return queries; } private Element[] createQueries(Set<Element> elementsInSet, int numQueries) { List<Element> queryList = Lists.newArrayListWithCapacity(numQueries); int numGoodQueries = (int) (numQueries * hitRate + 0.5); // add good queries int size = elementsInSet.size(); if (size > 0) { int minCopiesOfEachGoodQuery = numGoodQueries / size; int extras = numGoodQueries % size; for (int i = 0; i < minCopiesOfEachGoodQuery; i++) { queryList.addAll(elementsInSet); } List<Element> tmp = Lists.newArrayList(elementsInSet); Collections.shuffle(tmp, random); queryList.addAll(tmp.subList(0, extras)); } // now add bad queries while (queryList.size() < numQueries) { Element candidate = newElement(); if (!elementsInSet.contains(candidate)) { queryList.add(candidate); } } Collections.shuffle(queryList, random); return queryList.toArray(new Element[0]); } private Set<Element> createData() { Set<Element> set = Sets.newHashSetWithExpectedSize(size); while (set.size() < size) { set.add(newElement()); } return set; } private Element newElement() { int value = random.nextInt(); return isUserTypeFast ? new Element(value) : new SlowElement(value); } static class Element implements Comparable<Element> { final int hash; Element(int hash) { this.hash = hash; } @Override public boolean equals(Object obj) { return this == obj || (obj instanceof Element && ((Element) obj).hash == hash); } @Override public int hashCode() { return hash; } @Override public int compareTo(Element that) { return Ints.compare(hash, that.hash); } @Override public String toString() { return String.valueOf(hash); } } static class SlowElement extends Element { SlowElement(int hash) { super(hash); } @Override public boolean equals(Object obj) { return slowItDown() != 1 && super.equals(obj); } @Override public int hashCode() { return slowItDown() + hash; } @Override public int compareTo(Element e) { int x = slowItDown(); return x + super.compareTo(e) - x; // silly attempt to prevent opt } static int slowItDown() { int result = 0; for (int i = 1; i <= 1000; i++) { result += i; } return result; } } }
zzhhhhh-aw4rwer
guava-tests/test/com/google/common/collect/CollectionBenchmarkSampleData.java
Java
asf20
4,214
/* * Copyright (C) 2011 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import static com.google.common.testing.SerializableTester.reserialize; import static junit.framework.Assert.assertEquals; import static junit.framework.Assert.assertTrue; import com.google.common.annotations.GwtCompatible; import com.google.common.annotations.GwtIncompatible; import com.google.common.testing.SerializableTester; import java.util.Set; /** * Variant of {@link SerializableTester} that does not require the reserialized object's class to be * identical to the original. * * @author Chris Povirk */ /* * The whole thing is really @GwtIncompatible, but GwtJUnitConvertedTestModule doesn't have a * parameter for non-GWT, non-test files, and it didn't seem worth adding one for this unusual case. */ @GwtCompatible(emulated = true) final class LenientSerializableTester { /* * TODO(cpovirk): move this to c.g.c.testing if we allow for c.g.c.annotations dependencies so * that it can be GWTified? */ @GwtIncompatible("SerializableTester") static <E> Set<E> reserializeAndAssertLenient(Set<E> original) { Set<E> copy = reserialize(original); assertEquals(original, copy); assertTrue(copy instanceof ImmutableSet); return copy; } @GwtIncompatible("SerializableTester") static <E> Multiset<E> reserializeAndAssertLenient(Multiset<E> original) { Multiset<E> copy = reserialize(original); assertEquals(original, copy); assertTrue(copy instanceof ImmutableMultiset); return copy; } private LenientSerializableTester() {} }
zzhhhhh-aw4rwer
guava-tests/test/com/google/common/collect/LenientSerializableTester.java
Java
asf20
2,138
/* * Copyright (C) 2009 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import com.google.common.annotations.GwtCompatible; import java.io.Serializable; import java.util.Arrays; /** * A class that implements {@code Comparable} without generics, such as those * found in libraries that support Java 1.4 and before. Our library needs to * do the bare minimum to accommodate such types, though their use may still * require an explicit type parameter and/or warning suppression. * * @author Kevin Bourrillion */ @GwtCompatible class LegacyComparable implements Comparable, Serializable { static final LegacyComparable X = new LegacyComparable("x"); static final LegacyComparable Y = new LegacyComparable("y"); static final LegacyComparable Z = new LegacyComparable("z"); static final Iterable<LegacyComparable> VALUES_FORWARD = Arrays.asList(X, Y, Z); static final Iterable<LegacyComparable> VALUES_BACKWARD = Arrays.asList(Z, Y, X); private final String value; LegacyComparable(String value) { this.value = value; } @Override public int compareTo(Object object) { // This method is spec'd to throw CCE if object is of the wrong type LegacyComparable that = (LegacyComparable) object; return this.value.compareTo(that.value); } @Override public boolean equals(Object object) { if (object instanceof LegacyComparable) { LegacyComparable that = (LegacyComparable) object; return this.value.equals(that.value); } return false; } @Override public int hashCode() { return value.hashCode(); } private static final long serialVersionUID = 0; }
zzhhhhh-aw4rwer
guava-tests/test/com/google/common/collect/LegacyComparable.java
Java
asf20
2,204
/* * Copyright (C) 2010 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import java.util.Random; /** * Utility class for being able to seed a {@link Random} value with a passed * in seed from a benchmark parameter. * * TODO: Remove this class once Caliper has a better way. * * @author Nicholaus Shupe */ public final class SpecialRandom extends Random { public static SpecialRandom valueOf(String s) { return (s.length() == 0) ? new SpecialRandom() : new SpecialRandom(Long.parseLong(s)); } private final boolean hasSeed; private final long seed; public SpecialRandom() { this.hasSeed = false; this.seed = 0; } public SpecialRandom(long seed) { super(seed); this.hasSeed = true; this.seed = seed; } @Override public String toString() { return hasSeed ? "(seed:" + seed : "(default seed)"; } private static final long serialVersionUID = 0; }
zzhhhhh-aw4rwer
guava-tests/test/com/google/common/collect/SpecialRandom.java
Java
asf20
1,489
/* * Copyright (C) 2012 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.LinkedHashSet; import java.util.Map; import java.util.Random; import java.util.Set; import java.util.SortedMap; import java.util.TreeSet; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentSkipListMap; /** * Helper classes for various benchmarks. * * @author Christopher Swenson */ final class BenchmarkHelpers { /** * So far, this is the best way to test various implementations of {@link Set} subclasses. */ public enum SetImpl { Hash { @Override <E extends Comparable<E>> Set<E> create(Collection<E> contents) { return new HashSet<E>(contents); } }, LinkedHash { @Override <E extends Comparable<E>> Set<E> create(Collection<E> contents) { return new LinkedHashSet<E>(contents); } }, Tree { @Override <E extends Comparable<E>> Set<E> create(Collection<E> contents) { return new TreeSet<E>(contents); } }, Unmodifiable { @Override <E extends Comparable<E>> Set<E> create(Collection<E> contents) { return Collections.unmodifiableSet(new HashSet<E>(contents)); } }, Synchronized { @Override <E extends Comparable<E>> Set<E> create(Collection<E> contents) { return Collections.synchronizedSet(new HashSet<E>(contents)); } }, Immutable { @Override <E extends Comparable<E>> Set<E> create(Collection<E> contents) { return ImmutableSet.copyOf(contents); } }, ImmutableSorted { @Override <E extends Comparable<E>> Set<E> create(Collection<E> contents) { return ImmutableSortedSet.copyOf(contents); } }, ; abstract <E extends Comparable<E>> Set<E> create(Collection<E> contents); } public enum ListMultimapImpl { ArrayList { @Override <K, V> ListMultimap<K, V> create(Multimap<K, V> contents) { return ArrayListMultimap.create(contents); } }, LinkedList { @Override <K, V> ListMultimap<K, V> create(Multimap<K, V> contents) { return LinkedListMultimap.create(contents); } }, ImmutableList { @Override <K, V> ListMultimap<K, V> create(Multimap<K, V> contents) { return ImmutableListMultimap.copyOf(contents); } }; abstract <K, V> ListMultimap<K, V> create(Multimap<K, V> contents); } public enum SetMultimapImpl { Hash { @Override <K extends Comparable<K>, V extends Comparable<V>> SetMultimap<K, V> create( Multimap<K, V> contents) { return HashMultimap.create(contents); } }, LinkedHash { @Override <K extends Comparable<K>, V extends Comparable<V>> SetMultimap<K, V> create( Multimap<K, V> contents) { return LinkedHashMultimap.create(contents); } }, Tree { @Override <K extends Comparable<K>, V extends Comparable<V>> SetMultimap<K, V> create( Multimap<K, V> contents) { return TreeMultimap.create(contents); } }, ImmutableSet { @Override <K extends Comparable<K>, V extends Comparable<V>> SetMultimap<K, V> create( Multimap<K, V> contents) { return ImmutableSetMultimap.copyOf(contents); } }; abstract <K extends Comparable<K>, V extends Comparable<V>> SetMultimap<K, V> create( Multimap<K, V> contents); } public enum MapImpl { Hash { @Override <K, V> Map<K, V> create(Map<K, V> map) { return Maps.newHashMap(map); } }, LinkedHash { @Override <K, V> Map<K, V> create(Map<K, V> map) { return Maps.newLinkedHashMap(map); } }, ConcurrentHash { @Override <K, V> Map<K, V> create(Map<K, V> map) { return new ConcurrentHashMap<K, V>(map); } }, Immutable { @Override <K, V> Map<K, V> create(Map<K, V> map) { return ImmutableMap.copyOf(map); } }; abstract <K, V> Map<K, V> create(Map<K, V> map); } enum SortedMapImpl { Tree { @Override <K extends Comparable<K>, V> SortedMap<K, V> create(Map<K, V> map) { SortedMap<K, V> result = Maps.newTreeMap(); result.putAll(map); return result; } }, ConcurrentSkipList { @Override <K extends Comparable<K>, V> SortedMap<K, V> create(Map<K, V> map) { return new ConcurrentSkipListMap<K, V>(map); } }, ImmutableSorted { @Override <K extends Comparable<K>, V> SortedMap<K, V> create(Map<K, V> map) { return ImmutableSortedMap.copyOf(map); } }; abstract <K extends Comparable<K>, V> SortedMap<K, V> create(Map<K, V> map); } enum BiMapImpl { Hash{ @Override <K, V> BiMap<K, V> create(BiMap<K, V> map) { return HashBiMap.create(map); } }, Immutable { @Override <K, V> BiMap<K, V> create(BiMap<K, V> map) { return ImmutableBiMap.copyOf(map); } }; abstract <K, V> BiMap<K, V> create(BiMap<K, V> map); } enum MultisetImpl { Hash { @Override <E> Multiset<E> create(Multiset<E> contents) { return HashMultiset.create(contents); } }, LinkedHash { @Override <E> Multiset<E> create(Multiset<E> contents) { return LinkedHashMultiset.create(contents); } }, ConcurrentHash { @Override <E> Multiset<E> create(Multiset<E> contents) { return ConcurrentHashMultiset.create(contents); } }, Immutable { @Override <E> Multiset<E> create(Multiset<E> contents) { return ImmutableMultiset.copyOf(contents); } }; abstract <E> Multiset<E> create(Multiset<E> contents); } enum SortedMultisetImpl { Tree { @Override <E extends Comparable<E>> SortedMultiset<E> create(Multiset<E> contents) { return TreeMultiset.create(contents); } }, ImmutableSorted { @Override <E extends Comparable<E>> SortedMultiset<E> create(Multiset<E> contents) { return ImmutableSortedMultiset.copyOf(contents); } }; abstract <E extends Comparable<E>> SortedMultiset<E> create(Multiset<E> contents); } enum TableImpl { HashBased { @Override <R extends Comparable<R>, C extends Comparable<C>, V> Table<R, C, V> create( Table<R, C, V> contents) { return HashBasedTable.create(contents); } }, TreeBased { @Override <R extends Comparable<R>, C extends Comparable<C>, V> Table<R, C, V> create( Table<R, C, V> contents) { Table<R, C, V> table = TreeBasedTable.create(); table.putAll(contents); return table; } }, Array { @Override <R extends Comparable<R>, C extends Comparable<C>, V> Table<R, C, V> create( Table<R, C, V> contents) { if (contents.isEmpty()) { return ImmutableTable.of(); } else { return ArrayTable.create(contents); } } }, Immutable { @Override <R extends Comparable<R>, C extends Comparable<C>, V> Table<R, C, V> create( Table<R, C, V> contents) { return ImmutableTable.copyOf(contents); } }; abstract <R extends Comparable<R>, C extends Comparable<C>, V> Table<R, C, V> create(Table<R, C, V> contents); } public enum Value { INSTANCE; } public enum ListSizeDistribution { UNIFORM_0_TO_2(0, 2), UNIFORM_0_TO_9(0, 9), ALWAYS_0(0, 0), ALWAYS_10(10, 10); final int min; final int max; private ListSizeDistribution(int min, int max) { this.min = min; this.max = max; } public int chooseSize(Random random) { return random.nextInt(max - min + 1) + min; } } }
zzhhhhh-aw4rwer
guava-tests/test/com/google/common/collect/BenchmarkHelpers.java
Java
asf20
8,526
/* * Copyright (C) 2012 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.reflect.subpackage; public class ClassInSubPackage {}
zzhhhhh-aw4rwer
guava-tests/test/com/google/common/reflect/subpackage/ClassInSubPackage.java
Java
asf20
683
/* * Copyright (C) 2011 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.hash; import static org.junit.Assert.assertEquals; import com.google.common.base.Charsets; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Sets; import com.google.common.primitives.Ints; import com.google.common.testing.EqualsTester; import org.junit.Assert; import java.nio.charset.Charset; import java.util.Arrays; import java.util.Random; import java.util.Set; /** * Various utilities for testing {@link HashFunction}s. * * @author Dimitris Andreou * @author Kurt Alfred Kluever */ final class HashTestUtils { private HashTestUtils() {} /** * Converts a string, which should contain only ascii-representable characters, to a byte[]. */ static byte[] ascii(String string) { byte[] bytes = new byte[string.length()]; for (int i = 0; i < string.length(); i++) { bytes[i] = (byte) string.charAt(i); } return bytes; } interface HashFn { byte[] hash(byte[] input, int seed); } static void verifyHashFunction(HashFn hashFunction, int hashbits, int expected) { int hashBytes = hashbits / 8; byte[] key = new byte[256]; byte[] hashes = new byte[hashBytes * 256]; // Hash keys of the form {}, {0}, {0,1}, {0,1,2}... up to N=255,using 256-N as the seed for (int i = 0; i < 256; i++) { key[i] = (byte) i; int seed = 256 - i; byte[] hash = hashFunction.hash(Arrays.copyOf(key, i), seed); System.arraycopy(hash, 0, hashes, i * hashBytes, hash.length); } // Then hash the result array byte[] result = hashFunction.hash(hashes, 0); // interpreted in little-endian order. int verification = Integer.reverseBytes(Ints.fromByteArray(result)); if (expected != verification) { throw new AssertionError("Expected: " + Integer.toHexString(expected) + " got: " + Integer.toHexString(verification)); } } static final Funnel<Object> BAD_FUNNEL = new Funnel<Object>() { @Override public void funnel(Object object, PrimitiveSink bytePrimitiveSink) { bytePrimitiveSink.putInt(object.hashCode()); } }; static enum RandomHasherAction { PUT_BOOLEAN() { @Override void performAction(Random random, Iterable<? extends PrimitiveSink> sinks) { boolean value = random.nextBoolean(); for (PrimitiveSink sink : sinks) { sink.putBoolean(value); } } }, PUT_BYTE() { @Override void performAction(Random random, Iterable<? extends PrimitiveSink> sinks) { int value = random.nextInt(); for (PrimitiveSink sink : sinks) { sink.putByte((byte) value); } } }, PUT_SHORT() { @Override void performAction(Random random, Iterable<? extends PrimitiveSink> sinks) { short value = (short) random.nextInt(); for (PrimitiveSink sink : sinks) { sink.putShort(value); } } }, PUT_CHAR() { @Override void performAction(Random random, Iterable<? extends PrimitiveSink> sinks) { char value = (char) random.nextInt(); for (PrimitiveSink sink : sinks) { sink.putChar(value); } } }, PUT_INT() { @Override void performAction(Random random, Iterable<? extends PrimitiveSink> sinks) { int value = random.nextInt(); for (PrimitiveSink sink : sinks) { sink.putInt(value); } } }, PUT_LONG() { @Override void performAction(Random random, Iterable<? extends PrimitiveSink> sinks) { long value = random.nextLong(); for (PrimitiveSink sink : sinks) { sink.putLong(value); } } }, PUT_FLOAT() { @Override void performAction(Random random, Iterable<? extends PrimitiveSink> sinks) { float value = random.nextFloat(); for (PrimitiveSink sink : sinks) { sink.putFloat(value); } } }, PUT_DOUBLE() { @Override void performAction(Random random, Iterable<? extends PrimitiveSink> sinks) { double value = random.nextDouble(); for (PrimitiveSink sink : sinks) { sink.putDouble(value); } } }, PUT_BYTES() { @Override void performAction(Random random, Iterable<? extends PrimitiveSink> sinks) { byte[] value = new byte[random.nextInt(128)]; random.nextBytes(value); for (PrimitiveSink sink : sinks) { sink.putBytes(value); } } }, PUT_BYTES_INT_INT() { @Override void performAction(Random random, Iterable<? extends PrimitiveSink> sinks) { byte[] value = new byte[random.nextInt(128)]; random.nextBytes(value); int off = random.nextInt(value.length + 1); int len = random.nextInt(value.length - off + 1); for (PrimitiveSink sink : sinks) { sink.putBytes(value); } } }, PUT_STRING() { @Override void performAction(Random random, Iterable<? extends PrimitiveSink> sinks) { char[] value = new char[random.nextInt(128)]; for (int i = 0; i < value.length; i++) { value[i] = (char) random.nextInt(); } String s = new String(value); for (PrimitiveSink sink : sinks) { sink.putUnencodedChars(s); } } }, PUT_STRING_LOW_SURROGATE() { @Override void performAction(Random random, Iterable<? extends PrimitiveSink> sinks) { String s = new String(new char[] { randomLowSurrogate(random) }); for (PrimitiveSink sink : sinks) { sink.putUnencodedChars(s); } } }, PUT_STRING_HIGH_SURROGATE() { @Override void performAction(Random random, Iterable<? extends PrimitiveSink> sinks) { String s = new String(new char[] { randomHighSurrogate(random) }); for (PrimitiveSink sink : sinks) { sink.putUnencodedChars(s); } } }, PUT_STRING_LOW_HIGH_SURROGATE() { @Override void performAction(Random random, Iterable<? extends PrimitiveSink> sinks) { String s = new String(new char[] { randomLowSurrogate(random), randomHighSurrogate(random)}); for (PrimitiveSink sink : sinks) { sink.putUnencodedChars(s); } } }, PUT_STRING_HIGH_LOW_SURROGATE() { @Override void performAction(Random random, Iterable<? extends PrimitiveSink> sinks) { String s = new String(new char[] { randomHighSurrogate(random), randomLowSurrogate(random)}); for (PrimitiveSink sink : sinks) { sink.putUnencodedChars(s); } } }; abstract void performAction(Random random, Iterable<? extends PrimitiveSink> sinks); private static final RandomHasherAction[] actions = values(); static RandomHasherAction pickAtRandom(Random random) { return actions[random.nextInt(actions.length)]; } } /** * Test that the hash function contains no funnels. A funnel is a situation where a set of input * (key) bits 'affects' a strictly smaller set of output bits. Funneling is bad because it can * result in more-than-ideal collisions for a non-uniformly distributed key space. In practice, * most key spaces are ANYTHING BUT uniformly distributed. A bit(i) in the input is said to * 'affect' a bit(j) in the output if two inputs, identical but for bit(i), will differ at output * bit(j) about half the time * * <p>Funneling is pretty simple to detect. The key idea is to find example keys which * unequivocably demonstrate that funneling cannot be occuring. This is done bit-by-bit. For * each input bit(i) and output bit(j), two pairs of keys must be found with all bits identical * except bit(i). One pair must differ in output bit(j), and one pair must not. This proves that * input bit(i) can alter output bit(j). */ static void checkNoFunnels(HashFunction function) { Random rand = new Random(0); int keyBits = 32; int hashBits = function.bits(); // output loop tests input bit for (int i = 0; i < keyBits; i++) { int same = 0x0; // bitset for output bits with same values int diff = 0x0; // bitset for output bits with different values int count = 0; // originally was 2 * Math.log(...), making it try more times to avoid flakiness issues int maxCount = (int) (4 * Math.log(2 * keyBits * hashBits) + 1); while (same != 0xffffffff || diff != 0xffffffff) { int key1 = rand.nextInt(); // flip input bit for key2 int key2 = key1 ^ (1 << i); // get hashes int hash1 = function.hashInt(key1).asInt(); int hash2 = function.hashInt(key2).asInt(); // test whether the hash values have same output bits same |= ~(hash1 ^ hash2); // test whether the hash values have different output bits diff |= (hash1 ^ hash2); count++; // check whether we've exceeded the probabilistically // likely number of trials to have proven no funneling if (count > maxCount) { Assert.fail("input bit(" + i + ") was found not to affect all " + hashBits + " output bits; The unaffected bits are " + "as follows: " + ~(same & diff) + ". This was " + "determined after " + count + " trials."); } } } } /** * Test for avalanche. Avalanche means that output bits differ with roughly 1/2 probability on * different input keys. This test verifies that each possible 1-bit key delta achieves avalanche. * * <p>For more information: http://burtleburtle.net/bob/hash/avalanche.html */ static void checkAvalanche(HashFunction function, int trials, double epsilon) { Random rand = new Random(0); int keyBits = 32; int hashBits = function.bits(); for (int i = 0; i < keyBits; i++) { int[] same = new int[hashBits]; int[] diff = new int[hashBits]; // go through trials to compute probability for (int j = 0; j < trials; j++) { int key1 = rand.nextInt(); // flip input bit for key2 int key2 = key1 ^ (1 << i); // compute hash values int hash1 = function.hashInt(key1).asInt(); int hash2 = function.hashInt(key2).asInt(); for (int k = 0; k < hashBits; k++) { if ((hash1 & (1 << k)) == (hash2 & (1 << k))) { same[k] += 1; } else { diff[k] += 1; } } } // measure probability and assert it's within margin of error for (int j = 0; j < hashBits; j++) { double prob = (double) diff[j] / (double) (diff[j] + same[j]); Assert.assertEquals(0.50d, prob, epsilon); } } } /** * Test for 2-bit characteristics. A characteristic is a delta in the input which is repeated in * the output. For example, if f() is a block cipher and c is a characteristic, then * f(x^c) = f(x)^c with greater than expected probability. The test for funneling is merely a test * for 1-bit characteristics. * * <p>There is more general code provided by Bob Jenkins to test arbitrarily sized characteristics * using the magic of gaussian elimination: http://burtleburtle.net/bob/crypto/findingc.html. */ static void checkNo2BitCharacteristics(HashFunction function) { Random rand = new Random(0); int keyBits = 32; // get every one of (keyBits choose 2) deltas: for (int i = 0; i < keyBits; i++) { for (int j = 0; j < keyBits; j++) { if (j <= i) continue; int count = 0; int maxCount = 20; // the probability of error here is miniscule boolean diff = false; while (!diff) { int delta = (1 << i) | (1 << j); int key1 = rand.nextInt(); // apply delta int key2 = key1 ^ delta; // get hashes int hash1 = function.hashInt(key1).asInt(); int hash2 = function.hashInt(key2).asInt(); // this 2-bit candidate delta is not a characteristic // if deltas are different if ((hash1 ^ hash2) != delta) { diff = true; continue; } // check if we've exceeded the probabilistically // likely number of trials to have proven 2-bit candidate // is not a characteristic count++; if (count > maxCount) { Assert.fail("2-bit delta (" + i + ", " + j + ") is likely a " + "characteristic for this hash. This was " + "determined after " + count + " trials"); } } } } } /** * Test for avalanche with 2-bit deltas. Most probabilities of output bit(j) differing are well * within 50%. */ static void check2BitAvalanche(HashFunction function, int trials, double epsilon) { Random rand = new Random(0); int keyBits = 32; int hashBits = function.bits(); for (int bit1 = 0; bit1 < keyBits; bit1++) { for (int bit2 = 0; bit2 < keyBits; bit2++) { if (bit2 <= bit1) continue; int delta = (1 << bit1) | (1 << bit2); int[] same = new int[hashBits]; int[] diff = new int[hashBits]; // go through trials to compute probability for (int j = 0; j < trials; j++) { int key1 = rand.nextInt(); // flip input bit for key2 int key2 = key1 ^ delta; // compute hash values int hash1 = function.hashInt(key1).asInt(); int hash2 = function.hashInt(key2).asInt(); for (int k = 0; k < hashBits; k++) { if ((hash1 & (1 << k)) == (hash2 & (1 << k))) { same[k] += 1; } else { diff[k] += 1; } } } // measure probability and assert it's within margin of error for (int j = 0; j < hashBits; j++) { double prob = (double) diff[j] / (double) (diff[j] + same[j]); Assert.assertEquals(0.50d, prob, epsilon); } } } } /** * Checks that a Hasher returns the same HashCode when given the same input, and also * that the collision rate looks sane. */ static void assertInvariants(HashFunction hashFunction) { int objects = 100; Set<HashCode> hashcodes = Sets.newHashSetWithExpectedSize(objects); for (int i = 0; i < objects; i++) { Object o = new Object(); HashCode hashcode1 = hashFunction.hashObject(o, HashTestUtils.BAD_FUNNEL); HashCode hashcode2 = hashFunction.hashObject(o, HashTestUtils.BAD_FUNNEL); Assert.assertEquals(hashcode1, hashcode2); // idempotent Assert.assertEquals(hashFunction.bits(), hashcode1.bits()); Assert.assertEquals(hashFunction.bits(), hashcode1.asBytes().length * 8); hashcodes.add(hashcode1); } Assert.assertTrue(hashcodes.size() > objects * 0.95); // quite relaxed test assertHashBytesThrowsCorrectExceptions(hashFunction); assertIndependentHashers(hashFunction); assertShortcutsAreEquivalent(hashFunction, 512); } static void assertHashBytesThrowsCorrectExceptions(HashFunction hashFunction) { hashFunction.hashBytes(new byte[64], 0, 0); try { hashFunction.hashBytes(new byte[128], -1, 128); Assert.fail(); } catch (IndexOutOfBoundsException expected) {} try { hashFunction.hashBytes(new byte[128], 64, 256 /* too long len */); Assert.fail(); } catch (IndexOutOfBoundsException expected) {} try { hashFunction.hashBytes(new byte[64], 0, -1); Assert.fail(); } catch (IndexOutOfBoundsException expected) {} } static void assertIndependentHashers(HashFunction hashFunction) { int numActions = 100; // hashcodes from non-overlapping hash computations HashCode expected1 = randomHash(hashFunction, new Random(1L), numActions); HashCode expected2 = randomHash(hashFunction, new Random(2L), numActions); // equivalent, but overlapping, computations (should produce the same results as above) Random random1 = new Random(1L); Random random2 = new Random(2L); Hasher hasher1 = hashFunction.newHasher(); Hasher hasher2 = hashFunction.newHasher(); for (int i = 0; i < numActions; i++) { RandomHasherAction.pickAtRandom(random1).performAction(random1, ImmutableSet.of(hasher1)); RandomHasherAction.pickAtRandom(random2).performAction(random2, ImmutableSet.of(hasher2)); } Assert.assertEquals(expected1, hasher1.hash()); Assert.assertEquals(expected2, hasher2.hash()); } static HashCode randomHash(HashFunction hashFunction, Random random, int numActions) { Hasher hasher = hashFunction.newHasher(); for (int i = 0; i < numActions; i++) { RandomHasherAction.pickAtRandom(random).performAction(random, ImmutableSet.of(hasher)); } return hasher.hash(); } private static void assertShortcutsAreEquivalent(HashFunction hashFunction, int trials) { Random random = new Random(42085L); for (int i = 0; i < trials; i++) { assertHashBytesEquivalence(hashFunction, random); assertHashIntEquivalence(hashFunction, random); assertHashLongEquivalence(hashFunction, random); assertHashStringEquivalence(hashFunction, random); assertHashStringWithSurrogatesEquivalence(hashFunction, random); } } private static void assertHashBytesEquivalence(HashFunction hashFunction, Random random) { int size = random.nextInt(2048); byte[] bytes = new byte[size]; random.nextBytes(bytes); assertEquals(hashFunction.hashBytes(bytes), hashFunction.newHasher(size).putBytes(bytes).hash()); int off = random.nextInt(size); int len = random.nextInt(size - off); assertEquals(hashFunction.hashBytes(bytes, off, len), hashFunction.newHasher(size).putBytes(bytes, off, len).hash()); } private static void assertHashIntEquivalence(HashFunction hashFunction, Random random) { int i = random.nextInt(); assertEquals(hashFunction.hashInt(i), hashFunction.newHasher().putInt(i).hash()); } private static void assertHashLongEquivalence(HashFunction hashFunction, Random random) { long l = random.nextLong(); assertEquals(hashFunction.hashLong(l), hashFunction.newHasher().putLong(l).hash()); } private static final ImmutableSet<Charset> CHARSETS = ImmutableSet.of( Charsets.ISO_8859_1, Charsets.US_ASCII, Charsets.UTF_16, Charsets.UTF_16BE, Charsets.UTF_16LE, Charsets.UTF_8); private static void assertHashStringEquivalence(HashFunction hashFunction, Random random) { // Test that only data and data-order is important, not the individual operations. new EqualsTester() .addEqualityGroup( hashFunction.hashUnencodedChars("abc"), hashFunction.newHasher().putUnencodedChars("abc").hash(), hashFunction.newHasher().putUnencodedChars("ab").putUnencodedChars("c").hash(), hashFunction.newHasher().putUnencodedChars("a").putUnencodedChars("bc").hash(), hashFunction.newHasher().putUnencodedChars("a").putUnencodedChars("b") .putUnencodedChars("c").hash(), hashFunction.newHasher().putChar('a').putUnencodedChars("bc").hash(), hashFunction.newHasher().putUnencodedChars("ab").putChar('c').hash(), hashFunction.newHasher().putChar('a').putChar('b').putChar('c').hash()) .testEquals(); int size = random.nextInt(2048); byte[] bytes = new byte[size]; random.nextBytes(bytes); String string = new String(bytes); assertEquals(hashFunction.hashUnencodedChars(string), hashFunction.newHasher().putUnencodedChars(string).hash()); for (Charset charset : CHARSETS) { assertEquals(hashFunction.hashString(string, charset), hashFunction.newHasher().putString(string, charset).hash()); } } /** * This verifies that putUnencodedChars(String) and hashUnencodedChars(String) are equivalent, * even for funny strings composed by (possibly unmatched, and mostly illegal) surrogate * characters. (But doesn't test that they do the right thing - just their consistency). */ private static void assertHashStringWithSurrogatesEquivalence( HashFunction hashFunction, Random random) { int size = random.nextInt(8) + 1; char[] chars = new char[size]; for (int i = 0; i < chars.length; i++) { chars[i] = random.nextBoolean() ? randomLowSurrogate(random) : randomHighSurrogate(random); } String string = new String(chars); assertEquals(hashFunction.hashUnencodedChars(string), hashFunction.newHasher().putUnencodedChars(string).hash()); } static char randomLowSurrogate(Random random) { return (char) (Character.MIN_LOW_SURROGATE + random.nextInt(Character.MAX_LOW_SURROGATE - Character.MIN_LOW_SURROGATE + 1)); } static char randomHighSurrogate(Random random) { return (char) (Character.MIN_HIGH_SURROGATE + random.nextInt(Character.MAX_HIGH_SURROGATE - Character.MIN_HIGH_SURROGATE + 1)); } }
zzhhhhh-aw4rwer
guava-tests/test/com/google/common/hash/HashTestUtils.java
Java
asf20
21,679
/* * Copyright (C) 2013 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.hash; /** * An enum that contains all of the known hash functions. * * @author Kurt Alfred Kluever */ enum HashFunctionEnum { ADLER32(Hashing.adler32()), CRC32(Hashing.crc32()), GOOD_FAST_HASH_32(Hashing.goodFastHash(32)), GOOD_FAST_HASH_64(Hashing.goodFastHash(64)), GOOD_FAST_HASH_128(Hashing.goodFastHash(128)), GOOD_FAST_HASH_256(Hashing.goodFastHash(256)), MD5(Hashing.md5()), MURMUR3_128(Hashing.murmur3_128()), MURMUR3_32(Hashing.murmur3_32()), SHA1(Hashing.sha1()), SHA256(Hashing.sha256()), SHA512(Hashing.sha512()), SIP_HASH24(Hashing.sipHash24()), // Hash functions found in //javatests for comparing against current implementation of CityHash. // These can probably be removed sooner or later. ; private final HashFunction hashFunction; private HashFunctionEnum(HashFunction hashFunction) { this.hashFunction = hashFunction; } HashFunction getHashFunction() { return hashFunction; } }
zzhhhhh-aw4rwer
guava-tests/test/com/google/common/hash/HashFunctionEnum.java
Java
asf20
1,584
/* * Copyright (C) 2013 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.util.concurrent; import com.google.caliper.AfterExperiment; import com.google.caliper.BeforeExperiment; import com.google.caliper.Benchmark; import com.google.caliper.Param; import com.google.caliper.api.Footprint; import com.google.caliper.api.VmOptions; import com.google.common.base.Preconditions; import com.google.common.collect.Lists; import java.util.Queue; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.CountDownLatch; import java.util.concurrent.Executor; import java.util.concurrent.ExecutorService; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import java.util.logging.Level; import java.util.logging.Logger; import javax.annotation.Nullable; import javax.annotation.concurrent.GuardedBy; /** * Benchmarks for {@link ExecutionList}. */ @VmOptions({"-Xms3g", "-Xmx3g"}) public class ExecutionListBenchmark { private static final int NUM_THREADS = 10; // make a param? // We execute the listeners on the sameThreadExecutor because we don't really care about what the // listeners are doing, and they aren't doing much. private static final Executor SAME_THREAD_EXECUTOR = MoreExecutors.sameThreadExecutor(); // simple interface to wrap our two implementations. interface ExecutionListWrapper { void add(Runnable runnable, Executor executor); void execute(); /** Returns the underlying implementation, useful for the Footprint benchmark. */ Object getImpl(); } enum Impl { NEW { @Override ExecutionListWrapper newExecutionList() { return new ExecutionListWrapper() { final ExecutionList list = new ExecutionList(); @Override public void add(Runnable runnable, Executor executor) { list.add(runnable, executor); } @Override public void execute() { list.execute(); } @Override public Object getImpl() { return list; } }; } }, NEW_WITH_CAS { @Override ExecutionListWrapper newExecutionList() { return new ExecutionListWrapper() { final ExecutionListCAS list = new ExecutionListCAS(); @Override public void add(Runnable runnable, Executor executor) { list.add(runnable, executor); } @Override public void execute() { list.execute(); } @Override public Object getImpl() { return list; } }; } }, NEW_WITH_QUEUE { @Override ExecutionListWrapper newExecutionList() { return new ExecutionListWrapper() { final NewExecutionListQueue list = new NewExecutionListQueue(); @Override public void add(Runnable runnable, Executor executor) { list.add(runnable, executor); } @Override public void execute() { list.execute(); } @Override public Object getImpl() { return list; } }; } }, NEW_WITHOUT_REVERSE { @Override ExecutionListWrapper newExecutionList() { return new ExecutionListWrapper() { final NewExecutionListWithoutReverse list = new NewExecutionListWithoutReverse(); @Override public void add(Runnable runnable, Executor executor) { list.add(runnable, executor); } @Override public void execute() { list.execute(); } @Override public Object getImpl() { return list; } }; } }, OLD { @Override ExecutionListWrapper newExecutionList() { return new ExecutionListWrapper() { final OldExecutionList list = new OldExecutionList(); @Override public void add(Runnable runnable, Executor executor) { list.add(runnable, executor); } @Override public void execute() { list.execute(); } @Override public Object getImpl() { return list; } }; } }; abstract ExecutionListWrapper newExecutionList(); } private ExecutorService executorService; private CountDownLatch listenerLatch; private ExecutionListWrapper list; @Param Impl impl; @Param({"1", "5", "10"}) int numListeners; private final Runnable listener = new Runnable() { @Override public void run() { listenerLatch.countDown(); } }; @BeforeExperiment void setUp() throws Exception { executorService = new ThreadPoolExecutor(NUM_THREADS, NUM_THREADS, Long.MAX_VALUE, TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(1000)); final AtomicInteger integer = new AtomicInteger(); // Execute a bunch of tasks to ensure that our threads are allocated and hot for (int i = 0; i < NUM_THREADS * 10; i++) { executorService.submit(new Runnable() { @Override public void run() { integer.getAndIncrement(); }}); } } @AfterExperiment void tearDown() throws Exception { executorService.shutdown(); } @Footprint(exclude = {Runnable.class, Executor.class}) public Object measureSize() { list = impl.newExecutionList(); for (int i = 0; i < numListeners; i++) { list.add(listener, SAME_THREAD_EXECUTOR); } return list.getImpl(); } @Benchmark int addThenExecute_singleThreaded(int reps) { int returnValue = 0; for (int i = 0; i < reps; i++) { list = impl.newExecutionList(); listenerLatch = new CountDownLatch(numListeners); for (int j = 0; j < numListeners; j++) { list.add(listener, SAME_THREAD_EXECUTOR); returnValue += listenerLatch.getCount(); } list.execute(); returnValue += listenerLatch.getCount(); } return returnValue; } @Benchmark int executeThenAdd_singleThreaded(int reps) { int returnValue = 0; for (int i = 0; i < reps; i++) { list = impl.newExecutionList(); list.execute(); listenerLatch = new CountDownLatch(numListeners); for (int j = 0; j < numListeners; j++) { list.add(listener, SAME_THREAD_EXECUTOR); returnValue += listenerLatch.getCount(); } returnValue += listenerLatch.getCount(); } return returnValue; } private final Runnable executeTask = new Runnable() { @Override public void run() { list.execute(); } }; @Benchmark int addThenExecute_multiThreaded(final int reps) throws InterruptedException { Runnable addTask = new Runnable() { @Override public void run() { for (int i = 0; i < numListeners; i++) { list.add(listener, SAME_THREAD_EXECUTOR); } } }; int returnValue = 0; for (int i = 0; i < reps; i++) { list = impl.newExecutionList(); listenerLatch = new CountDownLatch(numListeners * NUM_THREADS); for (int j = 0; j < NUM_THREADS; j++) { executorService.submit(addTask); } executorService.submit(executeTask); returnValue = (int) listenerLatch.getCount(); listenerLatch.await(); } return returnValue; } @Benchmark int executeThenAdd_multiThreaded(final int reps) throws InterruptedException { Runnable addTask = new Runnable() { @Override public void run() { for (int i = 0; i < numListeners; i++) { list.add(listener, SAME_THREAD_EXECUTOR); } } }; int returnValue = 0; for (int i = 0; i < reps; i++) { list = impl.newExecutionList(); listenerLatch = new CountDownLatch(numListeners * NUM_THREADS); executorService.submit(executeTask); for (int j = 0; j < NUM_THREADS; j++) { executorService.submit(addTask); } returnValue = (int) listenerLatch.getCount(); listenerLatch.await(); } return returnValue; } // This is the old implementation of ExecutionList using a LinkedList. private static final class OldExecutionList { static final Logger log = Logger.getLogger(OldExecutionList.class.getName()); final Queue<OldExecutionList.RunnableExecutorPair> runnables = Lists.newLinkedList(); boolean executed = false; public void add(Runnable runnable, Executor executor) { Preconditions.checkNotNull(runnable, "Runnable was null."); Preconditions.checkNotNull(executor, "Executor was null."); boolean executeImmediate = false; synchronized (runnables) { if (!executed) { runnables.add(new RunnableExecutorPair(runnable, executor)); } else { executeImmediate = true; } } if (executeImmediate) { new RunnableExecutorPair(runnable, executor).execute(); } } public void execute() { synchronized (runnables) { if (executed) { return; } executed = true; } while (!runnables.isEmpty()) { runnables.poll().execute(); } } private static class RunnableExecutorPair { final Runnable runnable; final Executor executor; RunnableExecutorPair(Runnable runnable, Executor executor) { this.runnable = runnable; this.executor = executor; } void execute() { try { executor.execute(runnable); } catch (RuntimeException e) { log.log(Level.SEVERE, "RuntimeException while executing runnable " + runnable + " with executor " + executor, e); } } } } // A version of the execution list that doesn't reverse the stack in execute(). private static final class NewExecutionListWithoutReverse { static final Logger log = Logger.getLogger(NewExecutionListWithoutReverse.class.getName()); @GuardedBy("this") private RunnableExecutorPair runnables; @GuardedBy("this") private boolean executed; public void add(Runnable runnable, Executor executor) { Preconditions.checkNotNull(runnable, "Runnable was null."); Preconditions.checkNotNull(executor, "Executor was null."); synchronized (this) { if (!executed) { runnables = new RunnableExecutorPair(runnable, executor, runnables); return; } } executeListener(runnable, executor); } public void execute() { RunnableExecutorPair list; synchronized (this) { if (executed) { return; } executed = true; list = runnables; runnables = null; // allow GC to free listeners even if this stays around for a while. } while (list != null) { executeListener(list.runnable, list.executor); list = list.next; } } private static void executeListener(Runnable runnable, Executor executor) { try { executor.execute(runnable); } catch (RuntimeException e) { log.log(Level.SEVERE, "RuntimeException while executing runnable " + runnable + " with executor " + executor, e); } } private static final class RunnableExecutorPair { final Runnable runnable; final Executor executor; @Nullable RunnableExecutorPair next; RunnableExecutorPair(Runnable runnable, Executor executor, RunnableExecutorPair next) { this.runnable = runnable; this.executor = executor; this.next = next; } } } // A version of the ExecutionList that uses an explicit tail pointer to keep the nodes in order // rather than flipping the stack in execute(). private static final class NewExecutionListQueue { static final Logger log = Logger.getLogger(NewExecutionListQueue.class.getName()); @GuardedBy("this") private RunnableExecutorPair head; @GuardedBy("this") private RunnableExecutorPair tail; @GuardedBy("this") private boolean executed; public void add(Runnable runnable, Executor executor) { Preconditions.checkNotNull(runnable, "Runnable was null."); Preconditions.checkNotNull(executor, "Executor was null."); synchronized (this) { if (!executed) { RunnableExecutorPair newTail = new RunnableExecutorPair(runnable, executor); if (head == null) { head = newTail; tail = newTail; } else { tail.next = newTail; tail = newTail; } return; } } executeListener(runnable, executor); } public void execute() { RunnableExecutorPair list; synchronized (this) { if (executed) { return; } executed = true; list = head; head = null; // allow GC to free listeners even if this stays around for a while. tail = null; } while (list != null) { executeListener(list.runnable, list.executor); list = list.next; } } private static void executeListener(Runnable runnable, Executor executor) { try { executor.execute(runnable); } catch (RuntimeException e) { log.log(Level.SEVERE, "RuntimeException while executing runnable " + runnable + " with executor " + executor, e); } } private static final class RunnableExecutorPair { Runnable runnable; Executor executor; @Nullable RunnableExecutorPair next; RunnableExecutorPair(Runnable runnable, Executor executor) { this.runnable = runnable; this.executor = executor; } } } // A version of the list that uses compare and swap to manage the stack without locks. private static final class ExecutionListCAS { static final Logger log = Logger.getLogger(ExecutionListCAS.class.getName()); private static final sun.misc.Unsafe UNSAFE; private static final long HEAD_OFFSET; /** * A special instance of {@link RunnableExecutorPair} that is used as a sentinel value for the * bottom of the stack. */ private static final RunnableExecutorPair NULL_PAIR = new RunnableExecutorPair(null, null); static { try { UNSAFE = getUnsafe(); HEAD_OFFSET = UNSAFE.objectFieldOffset(ExecutionListCAS.class.getDeclaredField("head")); } catch (Exception ex) { throw new Error(ex); } } /** * TODO(user): This was copied verbatim from Striped64.java... standardize this? */ private static sun.misc.Unsafe getUnsafe() { try { return sun.misc.Unsafe.getUnsafe(); } catch (SecurityException tryReflectionInstead) {} try { return java.security.AccessController.doPrivileged (new java.security.PrivilegedExceptionAction<sun.misc.Unsafe>() { @Override public sun.misc.Unsafe run() throws Exception { Class<sun.misc.Unsafe> k = sun.misc.Unsafe.class; for (java.lang.reflect.Field f : k.getDeclaredFields()) { f.setAccessible(true); Object x = f.get(null); if (k.isInstance(x)) return k.cast(x); } throw new NoSuchFieldError("the Unsafe"); }}); } catch (java.security.PrivilegedActionException e) { throw new RuntimeException("Could not initialize intrinsics", e.getCause()); } } private volatile RunnableExecutorPair head = NULL_PAIR; public void add(Runnable runnable, Executor executor) { Preconditions.checkNotNull(runnable, "Runnable was null."); Preconditions.checkNotNull(executor, "Executor was null."); RunnableExecutorPair newHead = new RunnableExecutorPair(runnable, executor); RunnableExecutorPair oldHead; do { oldHead = head; if (oldHead == null) { // If runnables == null then execute() has been called so we should just execute our // listener immediately. newHead.execute(); return; } // Try to make newHead the new head of the stack at runnables. newHead.next = oldHead; } while (!UNSAFE.compareAndSwapObject(this, HEAD_OFFSET, oldHead, newHead)); } public void execute() { RunnableExecutorPair stack; do { stack = head; if (stack == null) { // If head == null then execute() has been called so we should just return return; } // try to swap null into head. } while (!UNSAFE.compareAndSwapObject(this, HEAD_OFFSET, stack, null)); RunnableExecutorPair reversedStack = null; while (stack != NULL_PAIR) { RunnableExecutorPair head = stack; stack = stack.next; head.next = reversedStack; reversedStack = head; } stack = reversedStack; while (stack != null) { stack.execute(); stack = stack.next; } } private static class RunnableExecutorPair { final Runnable runnable; final Executor executor; // Volatile because this is written on one thread and read on another with no synchronization. @Nullable volatile RunnableExecutorPair next; RunnableExecutorPair(Runnable runnable, Executor executor) { this.runnable = runnable; this.executor = executor; } void execute() { try { executor.execute(runnable); } catch (RuntimeException e) { log.log(Level.SEVERE, "RuntimeException while executing runnable " + runnable + " with executor " + executor, e); } } } } }
zzhhhhh-aw4rwer
guava-tests/benchmark/com/google/common/util/concurrent/ExecutionListBenchmark.java
Java
asf20
18,307
/* * Copyright (C) 2011 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.util.concurrent; import com.google.caliper.BeforeExperiment; import com.google.caliper.Benchmark; import com.google.caliper.Param; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; /** * Benchmarks for {@link CycleDetectingLockFactory}. * * @author Darick Tong */ public class CycleDetectingLockFactoryBenchmark { @Param({"2","3","4","5","10"}) int lockNestingDepth; CycleDetectingLockFactory factory; private Lock[] plainLocks; private Lock[] detectingLocks; @BeforeExperiment void setUp() throws Exception { this.factory = CycleDetectingLockFactory.newInstance( CycleDetectingLockFactory.Policies.WARN); this.plainLocks = new Lock[lockNestingDepth]; for (int i = 0; i < lockNestingDepth; i++) { plainLocks[i] = new ReentrantLock(); } this.detectingLocks = new Lock[lockNestingDepth]; for (int i = 0; i < lockNestingDepth; i++) { detectingLocks[i] = factory.newReentrantLock("Lock" + i); } } @Benchmark void unorderedPlainLocks(int reps) { lockAndUnlock(new ReentrantLock(), reps); } @Benchmark void unorderedCycleDetectingLocks(int reps) { lockAndUnlock(factory.newReentrantLock("foo"), reps); } private void lockAndUnlock(Lock lock, int reps) { for (int i = 0; i < reps; i++) { lock.lock(); lock.unlock(); } } @Benchmark void orderedPlainLocks(int reps) { lockAndUnlockNested(plainLocks, reps); } @Benchmark void orderedCycleDetectingLocks(int reps) { lockAndUnlockNested(detectingLocks, reps); } private void lockAndUnlockNested(Lock[] locks, int reps) { for (int i = 0; i < reps; i++) { for (int j = 0; j < locks.length; j++) { locks[j].lock(); } for (int j = locks.length - 1; j >= 0; j--) { locks[j].unlock(); } } } }
zzhhhhh-aw4rwer
guava-tests/benchmark/com/google/common/util/concurrent/CycleDetectingLockFactoryBenchmark.java
Java
asf20
2,478
/* * Copyright (C) 2010 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.util.concurrent; import com.google.common.collect.ObjectArrays; import java.util.AbstractQueue; import java.util.Collection; import java.util.ConcurrentModificationException; import java.util.Iterator; import java.util.NoSuchElementException; import java.util.concurrent.BlockingQueue; import java.util.concurrent.TimeUnit; import javax.annotation.Nullable; /** * A bounded {@linkplain BlockingQueue blocking queue} backed by an * array. This queue orders elements FIFO (first-in-first-out). The * <em>head</em> of the queue is that element that has been on the * queue the longest time. The <em>tail</em> of the queue is that * element that has been on the queue the shortest time. New elements * are inserted at the tail of the queue, and the queue retrieval * operations obtain elements at the head of the queue. * * <p>This is a classic &quot;bounded buffer&quot;, in which a * fixed-sized array holds elements inserted by producers and * extracted by consumers. Once created, the capacity cannot be * increased. Attempts to <tt>put</tt> an element into a full queue * will result in the operation blocking; attempts to <tt>take</tt> an * element from an empty queue will similarly block. * * <p> This class supports an optional fairness policy for ordering * waiting producer and consumer threads. By default, this ordering * is not guaranteed. However, a queue constructed with fairness set * to <tt>true</tt> grants threads access in FIFO order. Fairness * generally decreases throughput but reduces variability and avoids * starvation. * * <p>This class and its iterator implement all of the * <em>optional</em> methods of the {@link Collection} and {@link * Iterator} interfaces. * * @author Doug Lea * @author Justin T. Sampson * @param <E> the type of elements held in this collection */ public class MonitorBasedArrayBlockingQueue<E> extends AbstractQueue<E> implements BlockingQueue<E> { // Based on revision 1.58 of ArrayBlockingQueue by Doug Lea, from // http://gee.cs.oswego.edu/cgi-bin/viewcvs.cgi/jsr166/src/main/java/util/concurrent/ /** The queued items */ final E[] items; /** items index for next take, poll or remove */ int takeIndex; /** items index for next put, offer, or add. */ int putIndex; /** Number of items in the queue */ private int count; /* * Concurrency control uses the classic two-condition algorithm * found in any textbook. */ /** Monitor guarding all access */ final Monitor monitor; /** Guard for waiting takes */ private final Monitor.Guard notEmpty; /** Guard for waiting puts */ private final Monitor.Guard notFull; // Internal helper methods /** * Circularly increment i. */ final int inc(int i) { return (++i == items.length) ? 0 : i; } /** * Inserts element at current put position, advances, and signals. * Call only when occupying monitor. */ private void insert(E x) { items[putIndex] = x; putIndex = inc(putIndex); ++count; } /** * Extracts element at current take position, advances, and signals. * Call only when occupying monitor. */ private E extract() { final E[] items = this.items; E x = items[takeIndex]; items[takeIndex] = null; takeIndex = inc(takeIndex); --count; return x; } /** * Utility for remove and iterator.remove: Delete item at position i. * Call only when occupying monitor. */ void removeAt(int i) { final E[] items = this.items; // if removing front item, just advance if (i == takeIndex) { items[takeIndex] = null; takeIndex = inc(takeIndex); } else { // slide over all others up through putIndex. for (;;) { int nexti = inc(i); if (nexti != putIndex) { items[i] = items[nexti]; i = nexti; } else { items[i] = null; putIndex = i; break; } } } --count; } /** * Creates an <tt>MonitorBasedArrayBlockingQueue</tt> with the given (fixed) * capacity and default access policy. * * @param capacity the capacity of this queue * @throws IllegalArgumentException if <tt>capacity</tt> is less than 1 */ public MonitorBasedArrayBlockingQueue(int capacity) { this(capacity, false); } /** * Creates an <tt>MonitorBasedArrayBlockingQueue</tt> with the given (fixed) * capacity and the specified access policy. * * @param capacity the capacity of this queue * @param fair if <tt>true</tt> then queue accesses for threads blocked * on insertion or removal, are processed in FIFO order; * if <tt>false</tt> the access order is unspecified. * @throws IllegalArgumentException if <tt>capacity</tt> is less than 1 */ public MonitorBasedArrayBlockingQueue(int capacity, boolean fair) { if (capacity <= 0) throw new IllegalArgumentException(); this.items = newEArray(capacity); monitor = new Monitor(fair); notEmpty = new Monitor.Guard(monitor) { @Override public boolean isSatisfied() { return count > 0; } }; notFull = new Monitor.Guard(monitor) { @Override public boolean isSatisfied() { return count < items.length; } }; } @SuppressWarnings("unchecked") // please don't try this home, kids private static <E> E[] newEArray(int capacity) { return (E[]) new Object[capacity]; } /** * Creates an <tt>MonitorBasedArrayBlockingQueue</tt> with the given (fixed) * capacity, the specified access policy and initially containing the * elements of the given collection, * added in traversal order of the collection's iterator. * * @param capacity the capacity of this queue * @param fair if <tt>true</tt> then queue accesses for threads blocked * on insertion or removal, are processed in FIFO order; * if <tt>false</tt> the access order is unspecified. * @param c the collection of elements to initially contain * @throws IllegalArgumentException if <tt>capacity</tt> is less than * <tt>c.size()</tt>, or less than 1. * @throws NullPointerException if the specified collection or any * of its elements are null */ public MonitorBasedArrayBlockingQueue(int capacity, boolean fair, Collection<? extends E> c) { this(capacity, fair); if (capacity < c.size()) throw new IllegalArgumentException(); for (E e : c) add(e); } /** * Inserts the specified element at the tail of this queue if it is * possible to do so immediately without exceeding the queue's capacity, * returning <tt>true</tt> upon success and throwing an * <tt>IllegalStateException</tt> if this queue is full. * * @param e the element to add * @return <tt>true</tt> (as specified by {@link Collection#add}) * @throws IllegalStateException if this queue is full * @throws NullPointerException if the specified element is null */ @Override public boolean add(E e) { return super.add(e); } /** * Inserts the specified element at the tail of this queue if it is * possible to do so immediately without exceeding the queue's capacity, * returning <tt>true</tt> upon success and <tt>false</tt> if this queue * is full. This method is generally preferable to method {@link #add}, * which can fail to insert an element only by throwing an exception. * * @throws NullPointerException if the specified element is null */ @Override public boolean offer(E e) { if (e == null) throw new NullPointerException(); final Monitor monitor = this.monitor; if (monitor.enterIf(notFull)) { try { insert(e); return true; } finally { monitor.leave(); } } else { return false; } } /** * Inserts the specified element at the tail of this queue, waiting * for space to become available if the queue is full. * * @throws InterruptedException {@inheritDoc} * @throws NullPointerException {@inheritDoc} */ @Override public void put(E e) throws InterruptedException { if (e == null) throw new NullPointerException(); final Monitor monitor = this.monitor; monitor.enterWhen(notFull); try { insert(e); } finally { monitor.leave(); } } /** * Inserts the specified element at the tail of this queue, waiting * up to the specified wait time for space to become available if * the queue is full. * * @throws InterruptedException {@inheritDoc} * @throws NullPointerException {@inheritDoc} */ @Override public boolean offer(E e, long timeout, TimeUnit unit) throws InterruptedException { if (e == null) throw new NullPointerException(); final Monitor monitor = this.monitor; if (monitor.enterWhen(notFull, timeout, unit)) { try { insert(e); return true; } finally { monitor.leave(); } } else { return false; } } @Override public E poll() { final Monitor monitor = this.monitor; if (monitor.enterIf(notEmpty)) { try { return extract(); } finally { monitor.leave(); } } else { return null; } } @Override public E take() throws InterruptedException { final Monitor monitor = this.monitor; monitor.enterWhen(notEmpty); try { return extract(); } finally { monitor.leave(); } } @Override public E poll(long timeout, TimeUnit unit) throws InterruptedException { final Monitor monitor = this.monitor; if (monitor.enterWhen(notEmpty, timeout, unit)) { try { return extract(); } finally { monitor.leave(); } } else { return null; } } @Override public E peek() { final Monitor monitor = this.monitor; if (monitor.enterIf(notEmpty)) { try { return items[takeIndex]; } finally { monitor.leave(); } } else { return null; } } // this doc comment is overridden to remove the reference to collections // greater in size than Integer.MAX_VALUE /** * Returns the number of elements in this queue. * * @return the number of elements in this queue */ @Override public int size() { final Monitor monitor = this.monitor; monitor.enter(); try { return count; } finally { monitor.leave(); } } // this doc comment is a modified copy of the inherited doc comment, // without the reference to unlimited queues. /** * Returns the number of additional elements that this queue can ideally * (in the absence of memory or resource constraints) accept without * blocking. This is always equal to the initial capacity of this queue * less the current <tt>size</tt> of this queue. * * <p>Note that you <em>cannot</em> always tell if an attempt to insert * an element will succeed by inspecting <tt>remainingCapacity</tt> * because it may be the case that another thread is about to * insert or remove an element. */ @Override public int remainingCapacity() { final Monitor monitor = this.monitor; monitor.enter(); try { return items.length - count; } finally { monitor.leave(); } } /** * Removes a single instance of the specified element from this queue, * if it is present. More formally, removes an element <tt>e</tt> such * that <tt>o.equals(e)</tt>, if this queue contains one or more such * elements. * Returns <tt>true</tt> if this queue contained the specified element * (or equivalently, if this queue changed as a result of the call). * * @param o element to be removed from this queue, if present * @return <tt>true</tt> if this queue changed as a result of the call */ @Override public boolean remove(@Nullable Object o) { if (o == null) return false; final E[] items = this.items; final Monitor monitor = this.monitor; monitor.enter(); try { int i = takeIndex; int k = 0; for (;;) { if (k++ >= count) return false; if (o.equals(items[i])) { removeAt(i); return true; } i = inc(i); } } finally { monitor.leave(); } } /** * Returns <tt>true</tt> if this queue contains the specified element. * More formally, returns <tt>true</tt> if and only if this queue contains * at least one element <tt>e</tt> such that <tt>o.equals(e)</tt>. * * @param o object to be checked for containment in this queue * @return <tt>true</tt> if this queue contains the specified element */ @Override public boolean contains(@Nullable Object o) { if (o == null) return false; final E[] items = this.items; final Monitor monitor = this.monitor; monitor.enter(); try { int i = takeIndex; int k = 0; while (k++ < count) { if (o.equals(items[i])) return true; i = inc(i); } return false; } finally { monitor.leave(); } } /** * Returns an array containing all of the elements in this queue, in * proper sequence. * * <p>The returned array will be "safe" in that no references to it are * maintained by this queue. (In other words, this method must allocate * a new array). The caller is thus free to modify the returned array. * * <p>This method acts as bridge between array-based and collection-based * APIs. * * @return an array containing all of the elements in this queue */ @Override public Object[] toArray() { final E[] items = this.items; final Monitor monitor = this.monitor; monitor.enter(); try { Object[] a = new Object[count]; int k = 0; int i = takeIndex; while (k < count) { a[k++] = items[i]; i = inc(i); } return a; } finally { monitor.leave(); } } /** * Returns an array containing all of the elements in this queue, in * proper sequence; the runtime type of the returned array is that of * the specified array. If the queue fits in the specified array, it * is returned therein. Otherwise, a new array is allocated with the * runtime type of the specified array and the size of this queue. * * <p>If this queue fits in the specified array with room to spare * (i.e., the array has more elements than this queue), the element in * the array immediately following the end of the queue is set to * <tt>null</tt>. * * <p>Like the {@link #toArray()} method, this method acts as bridge between * array-based and collection-based APIs. Further, this method allows * precise control over the runtime type of the output array, and may, * under certain circumstances, be used to save allocation costs. * * <p>Suppose <tt>x</tt> is a queue known to contain only strings. * The following code can be used to dump the queue into a newly * allocated array of <tt>String</tt>: * * <pre> * String[] y = x.toArray(new String[0]);</pre> * * <p>Note that <tt>toArray(new Object[0])</tt> is identical in function to * <tt>toArray()</tt>. * * @param a the array into which the elements of the queue are to * be stored, if it is big enough; otherwise, a new array of the * same runtime type is allocated for this purpose * @return an array containing all of the elements in this queue * @throws ArrayStoreException if the runtime type of the specified array * is not a supertype of the runtime type of every element in * this queue * @throws NullPointerException if the specified array is null */ @Override public <T> T[] toArray(T[] a) { final E[] items = this.items; final Monitor monitor = this.monitor; monitor.enter(); try { if (a.length < count) a = ObjectArrays.newArray(a, count); int k = 0; int i = takeIndex; while (k < count) { // This cast is not itself safe, but the following statement // will fail if the runtime type of items[i] is not assignable // to the runtime type of a[k++], which is all that the method // contract requires (see @throws ArrayStoreException above). @SuppressWarnings("unchecked") T t = (T) items[i]; a[k++] = t; i = inc(i); } if (a.length > count) a[count] = null; return a; } finally { monitor.leave(); } } @Override public String toString() { final Monitor monitor = this.monitor; monitor.enter(); try { return super.toString(); } finally { monitor.leave(); } } /** * Atomically removes all of the elements from this queue. * The queue will be empty after this call returns. */ @Override public void clear() { final E[] items = this.items; final Monitor monitor = this.monitor; monitor.enter(); try { int i = takeIndex; int k = count; while (k-- > 0) { items[i] = null; i = inc(i); } count = 0; putIndex = 0; takeIndex = 0; } finally { monitor.leave(); } } /** * @throws UnsupportedOperationException {@inheritDoc} * @throws ClassCastException {@inheritDoc} * @throws NullPointerException {@inheritDoc} * @throws IllegalArgumentException {@inheritDoc} */ @Override public int drainTo(Collection<? super E> c) { if (c == null) throw new NullPointerException(); if (c == this) throw new IllegalArgumentException(); final E[] items = this.items; final Monitor monitor = this.monitor; monitor.enter(); try { int i = takeIndex; int n = 0; int max = count; while (n < max) { c.add(items[i]); items[i] = null; i = inc(i); ++n; } if (n > 0) { count = 0; putIndex = 0; takeIndex = 0; } return n; } finally { monitor.leave(); } } /** * @throws UnsupportedOperationException {@inheritDoc} * @throws ClassCastException {@inheritDoc} * @throws NullPointerException {@inheritDoc} * @throws IllegalArgumentException {@inheritDoc} */ @Override public int drainTo(Collection<? super E> c, int maxElements) { if (c == null) throw new NullPointerException(); if (c == this) throw new IllegalArgumentException(); if (maxElements <= 0) return 0; final E[] items = this.items; final Monitor monitor = this.monitor; monitor.enter(); try { int i = takeIndex; int n = 0; int max = (maxElements < count) ? maxElements : count; while (n < max) { c.add(items[i]); items[i] = null; i = inc(i); ++n; } if (n > 0) { count -= n; takeIndex = i; } return n; } finally { monitor.leave(); } } /** * Returns an iterator over the elements in this queue in proper sequence. * The returned <tt>Iterator</tt> is a "weakly consistent" iterator that * will never throw {@link ConcurrentModificationException}, * and guarantees to traverse elements as they existed upon * construction of the iterator, and may (but is not guaranteed to) * reflect any modifications subsequent to construction. * * @return an iterator over the elements in this queue in proper sequence */ @Override public Iterator<E> iterator() { final Monitor monitor = this.monitor; monitor.enter(); try { return new Itr(); } finally { monitor.leave(); } } /** * Iterator for MonitorBasedArrayBlockingQueue */ private class Itr implements Iterator<E> { /** * Index of element to be returned by next, * or a negative number if no such. */ private int nextIndex; /** * nextItem holds on to item fields because once we claim * that an element exists in hasNext(), we must return it in * the following next() call even if it was in the process of * being removed when hasNext() was called. */ private E nextItem; /** * Index of element returned by most recent call to next. * Reset to -1 if this element is deleted by a call to remove. */ private int lastRet; Itr() { lastRet = -1; if (count == 0) nextIndex = -1; else { nextIndex = takeIndex; nextItem = items[takeIndex]; } } @Override public boolean hasNext() { /* * No sync. We can return true by mistake here * only if this iterator passed across threads, * which we don't support anyway. */ return nextIndex >= 0; } /** * Checks whether nextIndex is valid; if so setting nextItem. * Stops iterator when either hits putIndex or sees null item. */ private void checkNext() { if (nextIndex == putIndex) { nextIndex = -1; nextItem = null; } else { nextItem = items[nextIndex]; if (nextItem == null) nextIndex = -1; } } @Override public E next() { final Monitor monitor = MonitorBasedArrayBlockingQueue.this.monitor; monitor.enter(); try { if (nextIndex < 0) throw new NoSuchElementException(); lastRet = nextIndex; E x = nextItem; nextIndex = inc(nextIndex); checkNext(); return x; } finally { monitor.leave(); } } @Override public void remove() { final Monitor monitor = MonitorBasedArrayBlockingQueue.this.monitor; monitor.enter(); try { int i = lastRet; if (i == -1) throw new IllegalStateException(); lastRet = -1; int ti = takeIndex; removeAt(i); // back up cursor (reset to front if was first element) nextIndex = (i == ti) ? takeIndex : i; checkNext(); } finally { monitor.leave(); } } } }
zzhhhhh-aw4rwer
guava-tests/benchmark/com/google/common/util/concurrent/MonitorBasedArrayBlockingQueue.java
Java
asf20
25,500