示例#1
0
 @Override
 protected void parseLong(CacheBuilderSpec spec, long value) {
   checkArgument(
       spec.maximumWeight == null, "maximum weight was already set to ", spec.maximumWeight);
   checkArgument(spec.maximumSize == null, "maximum size was already set to ", spec.maximumSize);
   spec.maximumWeight = value;
 }
示例#2
0
    @Override
    public void parse(CacheBuilderSpec spec, String key, @Nullable String value) {
      checkArgument(value == null, "key %s does not take values", key);
      checkArgument(
          spec.valueStrength == null, "%s was already set to %s", key, spec.valueStrength);

      spec.valueStrength = strength;
    }
示例#3
0
 /** 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);
 }
示例#4
0
    @Override
    public void parse(CacheBuilderSpec spec, String key, String value) {
      checkArgument(value != null && !value.isEmpty(), "value of key %s omitted", key);
      try {
        char lastChar = value.charAt(value.length() - 1);
        TimeUnit timeUnit;
        switch (lastChar) {
          case 'd':
            timeUnit = TimeUnit.DAYS;
            break;
          case 'h':
            timeUnit = TimeUnit.HOURS;
            break;
          case 'm':
            timeUnit = TimeUnit.MINUTES;
            break;
          case 's':
            timeUnit = TimeUnit.SECONDS;
            break;
          default:
            throw new IllegalArgumentException(
                String.format(
                    "key %s invalid format.  was %s, must end with one of [dDhHmMsS]", key, value));
        }

        long duration = Long.parseLong(value.substring(0, value.length() - 1));
        parseDuration(spec, duration, timeUnit);
      } catch (NumberFormatException e) {
        throw new IllegalArgumentException(
            String.format("key %s value set to %s, must be integer", key, value));
      }
    }
示例#5
0
 /**
  * Constructs a new instance for managing the given services.
  *
  * @param services The services to manage
  * @throws IllegalArgumentException if not all services are {@linkplain State#NEW new} or if there
  *     are any duplicate services.
  */
 public ServiceManager(Iterable<? extends Service> services) {
   ImmutableList<Service> copy = ImmutableList.copyOf(services);
   if (copy.isEmpty()) {
     // Having no services causes the manager to behave strangely. Notably, listeners are never
     // fired.  To avoid this we substitute a placeholder service.
     logger.log(
         Level.WARNING,
         "ServiceManager configured with no services.  Is your application configured properly?",
         new EmptyServiceManagerWarning());
     copy = ImmutableList.<Service>of(new NoOpService());
   }
   this.state = new ServiceManagerState(copy);
   this.services = copy;
   WeakReference<ServiceManagerState> stateReference =
       new WeakReference<ServiceManagerState>(state);
   for (Service service : copy) {
     service.addListener(new ServiceListener(service, stateReference), directExecutor());
     // We check the state after adding the listener as a way to ensure that our listener was added
     // to a NEW service.
     checkArgument(service.state() == NEW, "Can only manage NEW services, %s", service);
   }
   // We have installed all of our listeners and after this point any state transition should be
   // correct.
   this.state.markReady();
 }
示例#6
0
 @Override
 protected void parseInteger(CacheBuilderSpec spec, int value) {
   checkArgument(
       spec.concurrencyLevel == null,
       "concurrency level was already set to ",
       spec.concurrencyLevel);
   spec.concurrencyLevel = value;
 }
示例#7
0
 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);
     }
   }
 }
示例#8
0
 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);
 }
示例#9
0
 @Override
 protected void parseInteger(CacheBuilderSpec spec, int value) {
   checkArgument(
       spec.initialCapacity == null,
       "initial capacity was already set to ",
       spec.initialCapacity);
   spec.initialCapacity = value;
 }
 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();
 }
示例#11
0
 /** @since 12.0 */
 @GwtIncompatible("NavigableSet")
 @Override
 public ImmutableSortedSet<E> subSet(
     E fromElement, boolean fromInclusive, E toElement, boolean toInclusive) {
   checkNotNull(fromElement);
   checkNotNull(toElement);
   checkArgument(comparator.compare(fromElement, toElement) <= 0);
   return subSetImpl(fromElement, fromInclusive, toElement, toInclusive);
 }
示例#12
0
 /**
  * Divides an iterable into unmodifiable sublists of the given size, padding the final iterable
  * with null values if necessary. For example, partitioning an iterable containing {@code [a, b,
  * c, d, e]} with a partition size of 3 yields {@code [[a, b, c], [d, e, null]]} -- an outer
  * iterable containing two inner lists of three elements each, all in the original order.
  *
  * <p>Iterators returned by the returned iterable do not support the {@link Iterator#remove()}
  * method.
  *
  * @param iterable the iterable to return a partitioned view of
  * @param size the desired size of each partition
  * @return an iterable of unmodifiable lists containing the elements of {@code iterable} divided
  *     into partitions (the final iterable may have trailing null elements)
  * @throws IllegalArgumentException if {@code size} is nonpositive
  */
 public static <T> Iterable<List<T>> paddedPartition(final Iterable<T> iterable, final int size) {
   checkNotNull(iterable);
   checkArgument(size > 0);
   return new FluentIterable<List<T>>() {
     @Override
     public Iterator<List<T>> iterator() {
       return Iterators.paddedPartition(iterable.iterator(), size);
     }
   };
 }
示例#13
0
 @Override
 public void parse(CacheBuilderSpec spec, String key, String value) {
   checkArgument(value != null && !value.isEmpty(), "value of key %s omitted", key);
   try {
     parseLong(spec, Long.parseLong(value));
   } catch (NumberFormatException e) {
     throw new IllegalArgumentException(
         String.format("key %s value set to %s, must be integer", key, value), e);
   }
 }
示例#14
0
 /**
  * Returns the least value present in {@code array}.
  *
  * @param array a <i>nonempty</i> array of {@code short} values
  * @return the value present in {@code array} that is less than or equal to every other value in
  *     the array
  * @throws IllegalArgumentException if {@code array} is empty
  */
 public static short min(short... array) {
   checkArgument(array.length > 0);
   short min = array[0];
   for (int i = 1; i < array.length; i++) {
     if (array[i] < min) {
       min = array[i];
     }
   }
   return min;
 }
示例#15
0
 /**
  * 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);
 }
示例#16
0
 /**
  * Creates an iterable with the first {@code limitSize} elements of the given iterable. If the
  * original iterable does not contain that many elements, the returned iterable will have the same
  * behavior as the original iterable. The returned iterable's iterator supports {@code remove()}
  * if the original iterator does.
  *
  * @param iterable the iterable to limit
  * @param limitSize the maximum number of elements in the returned iterable
  * @throws IllegalArgumentException if {@code limitSize} is negative
  * @since 3.0
  */
 public static <T> Iterable<T> limit(final Iterable<T> iterable, final int limitSize) {
   checkNotNull(iterable);
   checkArgument(limitSize >= 0, "limit is negative");
   return new FluentIterable<T>() {
     @Override
     public Iterator<T> iterator() {
       return Iterators.limit(iterable.iterator(), limitSize);
     }
   };
 }
示例#17
0
 /**
  * Returns the greatest value present in {@code array}.
  *
  * @param array a <i>nonempty</i> array of {@code short} values
  * @return the value present in {@code array} that is greater than or equal to every other value
  *     in the array
  * @throws IllegalArgumentException if {@code array} is empty
  */
 public static short max(short... array) {
   checkArgument(array.length > 0);
   short max = array[0];
   for (int i = 1; i < array.length; i++) {
     if (array[i] > max) {
       max = array[i];
     }
   }
   return max;
 }
示例#18
0
    /**
     * Updates the state with the given service transition.
     *
     * <p>This method performs the main logic of ServiceManager in the following steps.
     *
     * <ol>
     *   <li>Update the {@link #servicesByState()}
     *   <li>Update the {@link #startupTimers}
     *   <li>Based on the new state queue listeners to run
     *   <li>Run the listeners (outside of the lock)
     * </ol>
     */
    void transitionService(final Service service, State from, State to) {
      checkNotNull(service);
      checkArgument(from != to);
      monitor.enter();
      try {
        transitioned = true;
        if (!ready) {
          return;
        }
        // Update state.
        checkState(
            servicesByState.remove(from, service),
            "Service %s not at the expected location in the state map %s",
            service,
            from);
        checkState(
            servicesByState.put(to, service),
            "Service %s in the state map unexpectedly at %s",
            service,
            to);
        // Update the timer
        Stopwatch stopwatch = startupTimers.get(service);
        if (stopwatch == null) {
          // This means the service was started by some means other than ServiceManager.startAsync
          stopwatch = Stopwatch.createStarted();
          startupTimers.put(service, stopwatch);
        }
        if (to.compareTo(RUNNING) >= 0 && stopwatch.isRunning()) {
          // N.B. if we miss the STARTING event then we may never record a startup time.
          stopwatch.stop();
          if (!(service instanceof NoOpService)) {
            logger.log(Level.FINE, "Started {0} in {1}.", new Object[] {service, stopwatch});
          }
        }
        // Queue our listeners

        // Did a service fail?
        if (to == FAILED) {
          fireFailedListeners(service);
        }

        if (states.count(RUNNING) == numberOfServices) {
          // This means that the manager is currently healthy. N.B. If other threads call isHealthy
          // they are not guaranteed to get 'true', because any service could fail right now.
          fireHealthyListeners();
        } else if (states.count(TERMINATED) + states.count(FAILED) == numberOfServices) {
          fireStoppedListeners();
        }
      } finally {
        monitor.leave();
        // Run our executors outside of the lock
        executeListeners();
      }
    }
示例#19
0
 /** Returns a new {@code TypeResolver} with {@code variable} mapping to {@code type}. */
 final TypeTable where(Map<? extends TypeVariable<?>, ? extends Type> mappings) {
   ImmutableMap.Builder<TypeVariable<?>, Type> builder = ImmutableMap.builder();
   builder.putAll(map);
   for (Map.Entry<? extends TypeVariable<?>, ? extends Type> mapping : mappings.entrySet()) {
     TypeVariable<?> variable = mapping.getKey();
     Type type = mapping.getValue();
     checkArgument(!variable.equals(type), "Type variable %s bound to itself", variable);
     builder.put(variable, type);
   }
   return new TypeTable(builder.build());
 }
示例#20
0
  /**
   * Returns a view of {@code iterable} that skips its first {@code numberToSkip} elements. If
   * {@code iterable} contains fewer than {@code numberToSkip} elements, the returned iterable skips
   * all of its elements.
   *
   * <p>Modifications to the underlying {@link Iterable} before a call to {@code iterator()} are
   * reflected in the returned iterator. That is, the iterator skips the first {@code numberToSkip}
   * elements that exist when the {@code Iterator} is created, not when {@code skip()} is called.
   *
   * <p>The returned iterable's iterator supports {@code remove()} if the iterator of the underlying
   * iterable supports it. Note that it is <i>not</i> possible to delete the last skipped element by
   * immediately calling {@code remove()} on that iterator, as the {@code Iterator} contract states
   * that a call to {@code remove()} before a call to {@code next()} will throw an {@link
   * IllegalStateException}.
   *
   * @since 3.0
   */
  public static <T> Iterable<T> skip(final Iterable<T> iterable, final int numberToSkip) {
    checkNotNull(iterable);
    checkArgument(numberToSkip >= 0, "number to skip cannot be negative");

    if (iterable instanceof List) {
      final List<T> list = (List<T>) iterable;
      return new FluentIterable<T>() {
        @Override
        public Iterator<T> iterator() {
          // TODO(kevinb): Support a concurrently modified collection?
          int toSkip = Math.min(list.size(), numberToSkip);
          return list.subList(toSkip, list.size()).iterator();
        }
      };
    }

    return new FluentIterable<T>() {
      @Override
      public Iterator<T> iterator() {
        final Iterator<T> iterator = iterable.iterator();

        Iterators.advance(iterator, numberToSkip);

        /*
         * We can't just return the iterator because an immediate call to its
         * remove() method would remove one of the skipped elements instead of
         * throwing an IllegalStateException.
         */
        return new Iterator<T>() {
          boolean atStart = true;

          @Override
          public boolean hasNext() {
            return iterator.hasNext();
          }

          @Override
          public T next() {
            T result = iterator.next();
            atStart = false; // not called if next() fails
            return result;
          }

          @Override
          public void remove() {
            checkRemove(!atStart);
            iterator.remove();
          }
        };
      }
    };
  }
示例#21
0
  /**
   * Creates a CacheBuilderSpec from a string.
   *
   * @param cacheBuilderSpecification the string form
   */
  public static CacheBuilderSpec parse(String cacheBuilderSpecification) {
    CacheBuilderSpec spec = new CacheBuilderSpec(cacheBuilderSpecification);
    if (!cacheBuilderSpecification.isEmpty()) {
      for (String keyValuePair : KEYS_SPLITTER.split(cacheBuilderSpecification)) {
        List<String> keyAndValue = ImmutableList.copyOf(KEY_VALUE_SPLITTER.split(keyValuePair));
        checkArgument(!keyAndValue.isEmpty(), "blank key-value pair");
        checkArgument(
            keyAndValue.size() <= 2,
            "key-value pair %s with more than one equals sign",
            keyValuePair);

        // Find the ValueParser for the current key.
        String key = keyAndValue.get(0);
        ValueParser valueParser = VALUE_PARSERS.get(key);
        checkArgument(valueParser != null, "unknown key %s", key);

        String value = keyAndValue.size() == 1 ? null : keyAndValue.get(1);
        valueParser.parse(spec, key, value);
      }
    }

    return spec;
  }
示例#22
0
 /**
  * Configures this builder to build min-max priority queues with an initial expected size of
  * {@code expectedSize}.
  */
 @CanIgnoreReturnValue
 public Builder<B> expectedSize(int expectedSize) {
   checkArgument(expectedSize >= 0);
   this.expectedSize = expectedSize;
   return this;
 }
示例#23
0
 public static final FaultLevel valueOf(int ordinal) {
   checkArgument(ordinal > __unsmnp__.ordinal() && ordinal < values.size());
   return values.get(ordinal);
 }
示例#24
0
 @Override
 protected void parseDuration(CacheBuilderSpec spec, long duration, TimeUnit unit) {
   checkArgument(spec.refreshTimeUnit == null, "refreshAfterWrite already set");
   spec.refreshDuration = duration;
   spec.refreshTimeUnit = unit;
 }
示例#25
0
 @Override
 protected void parseDuration(CacheBuilderSpec spec, long duration, TimeUnit unit) {
   checkArgument(spec.writeExpirationTimeUnit == null, "expireAfterWrite already set");
   spec.writeExpirationDuration = duration;
   spec.writeExpirationTimeUnit = unit;
 }
示例#26
0
 /**
  * Returns the {@code short} value whose big-endian representation is stored in the first 2 bytes
  * of {@code bytes}; equivalent to {@code ByteBuffer.wrap(bytes).getShort()}. For example, the
  * input byte array {@code {0x54, 0x32}} would yield the {@code short} value {@code 0x5432}.
  *
  * <p>Arguably, it's preferable to use {@link java.nio.ByteBuffer}; that library exposes much more
  * flexibility at little cost in readability.
  *
  * @throws IllegalArgumentException if {@code bytes} has fewer than 2 elements
  */
 @GwtIncompatible("doesn't work")
 public static short fromByteArray(byte[] bytes) {
   checkArgument(bytes.length >= BYTES, "array too small: %s < %s", bytes.length, BYTES);
   return fromBytes(bytes[0], bytes[1]);
 }
示例#27
0
 @Override
 public void parse(CacheBuilderSpec spec, String key, @Nullable String value) {
   checkArgument(value == null, "recordStats does not take values");
   checkArgument(spec.recordStats == null, "recordStats already set");
   spec.recordStats = true;
 }
示例#28
0
 /**
  * Returns an array containing the same values as {@code array}, but guaranteed to be of a
  * specified minimum length. If {@code array} already has a length of at least {@code minLength},
  * it is returned directly. Otherwise, a new array of size {@code minLength + padding} is
  * returned, containing the values of {@code array}, and zeroes in the remaining places.
  *
  * @param array the source array
  * @param minLength the minimum length the returned array must guarantee
  * @param padding an extra amount to "grow" the array by if growth is necessary
  * @throws IllegalArgumentException if {@code minLength} or {@code padding} is negative
  * @return an array containing the values of {@code array}, with guaranteed minimum length {@code
  *     minLength}
  */
 public static short[] ensureCapacity(short[] array, int minLength, int padding) {
   checkArgument(minLength >= 0, "Invalid minLength: %s", minLength);
   checkArgument(padding >= 0, "Invalid padding: %s", padding);
   return (array.length < minLength) ? copyOf(array, minLength + padding) : array;
 }
示例#29
0
 public StreamSnapshotSink(Mailbox mb) {
   Preconditions.checkArgument(mb != null);
   m_mb = mb;
 }
示例#30
0
 /**
  * Configures this builder to build {@code MinMaxPriorityQueue} instances that are limited to
  * {@code maximumSize} elements. Each time a queue grows beyond this bound, it immediately
  * removes its greatest element (according to its comparator), which might be the element that
  * was just added.
  */
 @CanIgnoreReturnValue
 public Builder<B> maximumSize(int maximumSize) {
   checkArgument(maximumSize > 0);
   this.maximumSize = maximumSize;
   return this;
 }