Java Code Examples for com.google.common.base.Preconditions

The following are top voted examples for showing how to use com.google.common.base.Preconditions. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: clearwsd   File: KMeans.java   Source Code and License 7 votes vote down vote up
private void initialize() {
    Preconditions.checkState(points.size() > kVal,
            "k-value is greater than or equal to number of points (%d >= %d).", kVal, points.size());
    Stopwatch sw = Stopwatch.createStarted();
    List<KmeansPoint<T>> pool = new ArrayList<>(points);
    KmeansPoint<T> sample = VectorMathUtils.sampleUniform(pool, random);
    pool.remove(sample);

    KmeansCentroid point = KmeansCentroid.centroid(sample, 0);
    centroids = Lists.newArrayList(point);
    for (int i = 1; i < kVal; ++i) {
        if (kMeansPlusPlus) {
            KmeansCentroid current = point;
            pool.parallelStream().forEach(p -> distanceToCentroid(p, current));
            sample = samplePoint(i - 1);
        } else {
            sample = VectorMathUtils.sampleUniform(pool, random);
        }
        pool.remove(sample);

        point = KmeansCentroid.centroid(sample, i);
        centroids.add(point);
    }
    log.info("Initialized centroids in {}.", sw);
}
 
Example 2
Project: chvote-protocol-poc   File: DefaultAuthority.java   Source Code and License 6 votes vote down vote up
@Override
public FinalizationCodePart handleConfirmation(Integer voterIndex, Confirmation confirmation)
        throws IncorrectConfirmationRuntimeException {
    Preconditions.checkState(publicCredentials != null,
            "The public credentials need to have been retrieved first");
    Stopwatch stopwatch = Stopwatch.createStarted();
    List<BigInteger> publicConfirmationCredentials =
            publicCredentials.stream().map(p -> p.y).collect(Collectors.toList());

    if (!voteConfirmationAuthorityAlgorithms.checkConfirmation(voterIndex, confirmation,
            publicConfirmationCredentials, ballotEntries, confirmationEntries)) {
        throw new IncorrectConfirmationRuntimeException("Confirmation for voter " + voterIndex + " was deemed invalid");
    }
    stopwatch.stop();
    confirmationVerificationTimes.add(stopwatch.elapsed(TimeUnit.MILLISECONDS));

    confirmationEntries.add(new ConfirmationEntry(voterIndex, confirmation));

    stopwatch.reset().start();
    FinalizationCodePart finalization = voteConfirmationAuthorityAlgorithms.getFinalization(voterIndex, electorateData.getP(), ballotEntries);
    stopwatch.stop();
    finalizationComputationTimes.add(stopwatch.elapsed(TimeUnit.MILLISECONDS));

    return finalization;
}
 
Example 3
Project: chvote-protocol-poc   File: Conversion.java   Source Code and License 6 votes vote down vote up
/**
 * Algorithm 4.6: ToString
 *
 * @param x       the integer to convert
 * @param k       the required String size
 * @param upper_a the alphabet to be used
 * @return a string of length k, using alphabet A, and representing x
 */
public String toString(BigInteger x, int k, List<Character> upper_a) {
    Preconditions.checkArgument(x.signum() >= 0, "x should be a non-negative integer");
    int alphabetSize = upper_a.size();
    BigInteger N = BigInteger.valueOf(alphabetSize);
    Preconditions.checkArgument(N.pow(k).compareTo(x) >= 0,
            "x is too large to be encoded with k characters of alphabet upper_a");

    StringBuilder sb = new StringBuilder(k);
    BigInteger current = x;
    for (int i = 1; i <= k; i++) {
        BigInteger[] divideAndRemainder = current.divideAndRemainder(N);
        current = divideAndRemainder[0];
        // always insert before the previous character
        sb.insert(0, upper_a.get(divideAndRemainder[1].intValue()));
    }

    return sb.toString();
}
 
Example 4
Project: integrations   File: CaseChargesWithDispo2010.java   Source Code and License 6 votes vote down vote up
public static String getMiddleName( Row row ) {
    String name = row.getAs( "Defendant Name" );
    if ( name == null ) { return null; }
    name = name.replace( " Jr", "" );
    name = name.replace( " JR", "" );
    name = name.replace( " Sr", "" );
    name = name.replace( " SR", "" );

    List<String> names = nameSplitter.splitToList( name );
    Preconditions.checkState( names.size() > 0, "Must have at least some parts of name" );
    StringBuilder sb = new StringBuilder();
    for ( int i = 2; i < names.size(); ++i ) {
        sb.append( names.get( i ) ).append( " " );
    }

    return sb.toString().trim();
}
 
Example 5
Project: hashsdn-controller   File: ConfigurationImpl.java   Source Code and License 6 votes vote down vote up
@Override
public ShardStrategy getStrategyForPrefix(@Nonnull final DOMDataTreeIdentifier prefix) {
    Preconditions.checkNotNull(prefix, "Prefix cannot be null");
    // FIXME using prefix tables like in mdsal will be better
    Entry<DOMDataTreeIdentifier, PrefixShardConfiguration> bestMatchEntry =
            new SimpleEntry<>(
                    new DOMDataTreeIdentifier(prefix.getDatastoreType(), YangInstanceIdentifier.EMPTY), null);

    for (Entry<DOMDataTreeIdentifier, PrefixShardConfiguration> entry : prefixConfigMap.entrySet()) {
        if (entry.getKey().contains(prefix) && entry.getKey().getRootIdentifier().getPathArguments().size()
                > bestMatchEntry.getKey().getRootIdentifier().getPathArguments().size()) {
            bestMatchEntry = entry;
        }
    }

    if (bestMatchEntry.getValue() == null) {
        return null;
    }
    return new PrefixShardStrategy(ClusterUtils
            .getCleanShardName(bestMatchEntry.getKey().getRootIdentifier()),
            bestMatchEntry.getKey().getRootIdentifier());
}
 
Example 6
Project: mynlp   File: ViterbiBestPathComputer.java   Source Code and License 6 votes vote down vote up
/**
 * 从后到前。根据权重获取最优路径
 *
 * @param wordnet
 * @return
 */
private Wordpath buildPath(Wordnet wordnet) {
    //从后到前,获得完整的路径
    Wordpath wordPath = new Wordpath(wordnet, this);

    Vertex last = null;

    Vertex point = wordnet.getEndRow().first();

    while (point != null) {
        last = point;
        wordPath.combine(point);
        point = point.from;
    }

    // 最后一个point必定指向start节点
    Preconditions.checkState(last == wordnet.getBeginRow().first(), "非完整路径");

    return wordPath;
}
 
Example 7
Project: QDrill   File: AbstractMuxExchange.java   Source Code and License 6 votes vote down vote up
@Override
public ParallelizationInfo getReceiverParallelizationInfo(List<DrillbitEndpoint> senderFragmentEndpoints) {
  Preconditions.checkArgument(senderFragmentEndpoints != null && senderFragmentEndpoints.size() > 0,
      "Sender fragment endpoint list should not be empty");

  // We want to run one mux receiver per Drillbit endpoint.
  // Identify the number of unique Drillbit endpoints in sender fragment endpoints.
  List<DrillbitEndpoint> drillbitEndpoints = ImmutableSet.copyOf(senderFragmentEndpoints).asList();

  List<EndpointAffinity> affinities = Lists.newArrayList();
  for(DrillbitEndpoint ep : drillbitEndpoints) {
    affinities.add(new EndpointAffinity(ep, Double.POSITIVE_INFINITY));
  }

  return ParallelizationInfo.create(affinities.size(), affinities.size(), affinities);
}
 
Example 8
Project: dremio-oss   File: ProvisioningServiceImpl.java   Source Code and License 6 votes vote down vote up
@Override
public ClusterEnriched resizeCluster(ClusterId clusterId, int newContainersCount) throws ProvisioningHandlingException {
  // get info about cluster
  // children should do the rest
  Preconditions.checkNotNull(clusterId, "id is required");
  final Cluster cluster = store.get(clusterId);
  if (cluster == null) {
    throw new ProvisioningHandlingException("Cluster " + clusterId + " is not found. Nothing to resize");
  }

  cluster.getClusterConfig().getClusterSpec().setContainerCount(newContainersCount);
  final ProvisioningServiceDelegate service = concreteServices.get(cluster.getClusterConfig().getClusterType());
  if (service == null) {
    throw new ProvisioningHandlingException("Can not find service implementation for: " + cluster.getClusterConfig().getClusterType());
  }

  if (newContainersCount <= 0) {
    logger.info("Since number of requested containers to resize == 0. Stopping cluster");
    service.stopCluster(cluster);
  } else {
    service.resizeCluster(cluster);
  }
  store.put(clusterId, cluster);
  return service.getClusterInfo(cluster);
}
 
Example 9
Project: hadoop   File: ByteArrayManager.java   Source Code and License 6 votes vote down vote up
/**
 * Recycle the given byte array.
 * 
 * The byte array may or may not be allocated
 * by the {@link Impl#newByteArray(int)} method.
 * 
 * This is a non-blocking call.
 */
@Override
public int release(final byte[] array) {
  Preconditions.checkNotNull(array);
  if (LOG.isDebugEnabled()) {
    debugMessage.get().append("recycle: array.length=").append(array.length);
  }
  
  final int freeQueueSize;
  if (array.length == 0) {
    freeQueueSize = -1;
  } else {
    final FixedLengthManager manager = managers.get(array.length, false);
    freeQueueSize = manager == null? -1: manager.recycle(array);
  }
  
  if (LOG.isDebugEnabled()) {
    debugMessage.get().append(", freeQueueSize=").append(freeQueueSize);
    logDebugMessage();
  }
  return freeQueueSize;
}
 
Example 10
Project: hadoop-oss   File: CryptoInputStream.java   Source Code and License 6 votes vote down vote up
/**
 * Do the decryption using inBuffer as input and outBuffer as output.
 * Upon return, inBuffer is cleared; the decrypted data starts at 
 * outBuffer.position() and ends at outBuffer.limit();
 */
private void decrypt(Decryptor decryptor, ByteBuffer inBuffer, 
    ByteBuffer outBuffer, byte padding) throws IOException {
  Preconditions.checkState(inBuffer.position() >= padding);
  if(inBuffer.position() == padding) {
    // There is no real data in inBuffer.
    return;
  }
  inBuffer.flip();
  outBuffer.clear();
  decryptor.decrypt(inBuffer, outBuffer);
  inBuffer.clear();
  outBuffer.flip();
  if (padding > 0) {
    /*
     * The plain text and cipher text have a 1:1 mapping, they start at the 
     * same position.
     */
    outBuffer.position(padding);
  }
}
 
Example 11
Project: spark_deep   File: MessageWithHeader.java   Source Code and License 6 votes vote down vote up
/**
 * This code is more complicated than you would think because we might require multiple
 * transferTo invocations in order to transfer a single MessageWithHeader to avoid busy waiting.
 *
 * The contract is that the caller will ensure position is properly set to the total number
 * of bytes transferred so far (i.e. value returned by transfered()).
 */
@Override
public long transferTo(final WritableByteChannel target, final long position) throws IOException {
  Preconditions.checkArgument(position == totalBytesTransferred, "Invalid position.");
  // Bytes written for header in this call.
  long writtenHeader = 0;
  if (header.readableBytes() > 0) {
    writtenHeader = copyByteBuf(header, target);
    totalBytesTransferred += writtenHeader;
    if (header.readableBytes() > 0) {
      return writtenHeader;
    }
  }

  // Bytes written for body in this call.
  long writtenBody = 0;
  if (body instanceof FileRegion) {
    writtenBody = ((FileRegion) body).transferTo(target, totalBytesTransferred - headerLength);
  } else if (body instanceof ByteBuf) {
    writtenBody = copyByteBuf((ByteBuf) body, target);
  }
  totalBytesTransferred += writtenBody;

  return writtenHeader + writtenBody;
}
 
Example 12
Project: helper   File: FunctionalCommandBuilderImpl.java   Source Code and License 6 votes vote down vote up
@Override
public FunctionalCommandBuilder<T> assertSender(Predicate<T> test, String failureMessage) {
    Preconditions.checkNotNull(test, "test");
    Preconditions.checkNotNull(failureMessage, "failureMessage");
    predicates.add(context -> {
        //noinspection unchecked
        T sender = (T) context.sender();
        if (test.test(sender)) {
            return true;
        }

        context.reply(failureMessage);
        return false;
    });
    return this;
}
 
Example 13
Project: gitplex-mit   File: ReceiveCommand.java   Source Code and License 6 votes vote down vote up
@Override
public Void call() {
	Preconditions.checkNotNull(input);
	Preconditions.checkNotNull(output);
	
	Commandline cmd = cmd();
	cmd.addArgs("receive-pack", "--stateless-rpc", ".");
	
	cmd.execute(output, new LineConsumer() {

		@Override
		public void consume(String line) {
			logger.error(line);
		}
		
	}, input).checkReturnCode();
	
	return null;
}
 
Example 14
Project: FirstAid   File: FirstAidRegistryImpl.java   Source Code and License 6 votes vote down vote up
@Override
public void registerDebuff(@Nonnull EnumDebuffSlot slot, @Nonnull IDebuffBuilder abstractBuilder) {
    DebuffBuilder builder;
    try {
        builder = (DebuffBuilder) abstractBuilder;
    } catch (ClassCastException e) {
        throw new IllegalArgumentException("Builder must an instance of the default builder received via DebuffBuilderFactory!", e);
    }
    //Build the finished debuff
    FirstAid.logger.debug("Building debuff from mod {} for slot {} with potion effect {}, type = {}", CommonUtils.getActiveModidSafe(), slot, builder.potionName, builder.isOnHit ? "OnHit" : "Constant");
    BooleanSupplier isEnabled = builder.isEnabledSupplier;
    if (isEnabled == null)
        isEnabled = () -> true;

    Preconditions.checkArgument(!builder.map.isEmpty(), "Failed to register debuff with condition has set");
    IDebuff debuff;
    if (builder.isOnHit) {
        debuff = new OnHitDebuff(builder.potionName, builder.map, isEnabled, builder.sound);
    } else {
        Preconditions.checkArgument(builder.sound == null, "Tried to register constant debuff with sound effect.");
        debuff = new ConstantDebuff(builder.potionName, builder.map, isEnabled);
    }
    registerDebuff(slot, debuff);
}
 
Example 15
Project: Elasticsearch   File: BigLongArray.java   Source Code and License 6 votes vote down vote up
@Override
public void fill(long fromIndex, long toIndex, long value) {
    Preconditions.checkArgument(fromIndex <= toIndex);
    if (fromIndex == toIndex) {
        return; // empty range
    }
    final int fromPage = pageIndex(fromIndex);
    final int toPage = pageIndex(toIndex - 1);
    if (fromPage == toPage) {
        Arrays.fill(pages[fromPage], indexInPage(fromIndex), indexInPage(toIndex - 1) + 1, value);
    } else {
        Arrays.fill(pages[fromPage], indexInPage(fromIndex), pages[fromPage].length, value);
        for (int i = fromPage + 1; i < toPage; ++i) {
            Arrays.fill(pages[i], value);
        }
        Arrays.fill(pages[toPage], 0, indexInPage(toIndex - 1) + 1, value);
    }
}
 
Example 16
Project: gitplex-mit   File: DependencyUtils.java   Source Code and License 6 votes vote down vote up
public static <K, T extends DependencyAware<K>> Set<K> getTransitiveDependents(
		Map<K, Set<K>> dependentMap, K dependency) {
	Set<K> transitiveDependents = new HashSet<>();
	
	transitiveDependents.addAll(Preconditions.checkNotNull(dependentMap.get(dependency)));
	while (true) {
		Set<K> newTransitiveDependents = new HashSet<>(transitiveDependents);
		for (K dependent: transitiveDependents) {
			newTransitiveDependents.addAll(Preconditions.checkNotNull(dependentMap.get(dependent)));
		}
		if (!transitiveDependents.equals(newTransitiveDependents)) {
			transitiveDependents = newTransitiveDependents;
		} else {
			break;
		}
	}
	return transitiveDependents;
}
 
Example 17
Project: cucumber-framework-java   File: RecoverFromStaleElement.java   Source Code and License 6 votes vote down vote up
@Override
public List<String> getLocatorsList( WebElement element )
{
    Preconditions.checkNotNull( element, "WebElement cannot be null" );
    logger.trace( "parsing locator list for element -> {}", toString() );
    String[] str = toString().replaceAll( "(\\[{1,20}(FirefoxDriver.*?|ChromeDriver.*?|SafariDriver.*?|InternetExplorerDriver.*?)\\] -> )", "" )
            .replaceAll( "(])\\1+", "$1" )
            .replaceAll( "(])\\1+", "$1" )
            .replaceAll( " -> ", "|" )
            .split( "\\|", -1 );

    List<String> list = Lists.newArrayList();
    for( String s : str )
    {
        if( !s.contains( "[" ) && s.endsWith( "]" ) )
        {
            list.add( s.replaceFirst( "\\]", "" ) );
        } else
        {
            list.add( s );
        }
    }

    return list;
}
 
Example 18
Project: dremio-oss   File: HashAggTemplate.java   Source Code and License 6 votes vote down vote up
public HashAggTemplate(){
  try{
    Class<?> clazz = null;
    for(Class<?> c : getClass().getDeclaredClasses()){
      if(c.getSimpleName().equals("BatchHolder")){
        clazz = c;
        break;
      }
    }

    Preconditions.checkNotNull(clazz);
    this.innerConstructor = (Constructor<BatchHolder>) clazz.getConstructor(this.getClass());
    innerConstructor.setAccessible(true);
  }catch(Exception ex){
    throw Throwables.propagate(ex);
  }
}
 
Example 19
Project: NBANDROID-V2   File: AndroidConfigProvider.java   Source Code and License 6 votes vote down vote up
private static void saveConfig(AuxiliaryProperties props, LaunchConfiguration l, String suffix) {
    Preconditions.checkNotNull(props);
    switch (l.getLaunchAction()) {
        case DO_NOTHING:
            props.put(AndroidProjectProperties.PROP_LAUNCH_ACTION + suffix,
                    AndroidProjectProperties.LAUNCH_ACTION_DO_NOTHING, false);
            break;
        case MAIN:
            props.put(AndroidProjectProperties.PROP_LAUNCH_ACTION + suffix,
                    AndroidProjectProperties.LAUNCH_ACTION_MAIN, false);
            break;
        case ACTIVITY:
            props.put(AndroidProjectProperties.PROP_LAUNCH_ACTION + suffix,
                    l.getActivityName(), false);
            break;
    }
    if (!LaunchConfiguration.MODE_DEBUG.equals(l.getMode())) {
        props.put(AndroidProjectProperties.PROP_LAUNCH_MODE + suffix, l.getMode(), false);
    }
    props.put(AndroidProjectProperties.PROP_LAUNCH_TARGET_MODE + suffix, l.getTargetMode().toString(), false);
    props.put(AndroidProjectProperties.PROP_EMULATOR_OPTIONS + suffix, l.getEmulatorOptions(), false);
    props.put(AndroidProjectProperties.PROP_INSTR_RUNNER + suffix, l.getInstrumentationRunner(), false);
}
 
Example 20
Project: sstable-adaptor   File: SyncUtil.java   Source Code and License 5 votes vote down vote up
public static void force(FileChannel fc, boolean metaData) throws IOException
{
    Preconditions.checkNotNull(fc);
    if (SKIP_SYNC)
    {
        if (!fc.isOpen())
            throw new ClosedChannelException();
    }
    else
    {
        fc.force(metaData);
    }
}
 
Example 21
Project: helper   File: JsonBuilder.java   Source Code and License 5 votes vote down vote up
default JsonArrayBuilder addStrings(Iterable<String> iterable) {
    Preconditions.checkNotNull(iterable, "iterable");
    for (String e : iterable) {
        add(e);
    }
    return this;
}
 
Example 22
Project: hashsdn-controller   File: DataTreeChangeListenerProxy.java   Source Code and License 5 votes vote down vote up
DataTreeChangeListenerProxy(final ActorContext actorContext, final T listener,
        final YangInstanceIdentifier registeredPath) {
    super(listener);
    this.actorContext = Preconditions.checkNotNull(actorContext);
    this.registeredPath = Preconditions.checkNotNull(registeredPath);
    this.dataChangeListenerActor = actorContext.getActorSystem().actorOf(
            DataTreeChangeListenerActor.props(getInstance(), registeredPath)
                .withDispatcher(actorContext.getNotificationDispatcherPath()));

    LOG.debug("{}: Created actor {} for DTCL {}", actorContext.getDatastoreContext().getLogicalStoreType(),
            dataChangeListenerActor, listener);
}
 
Example 23
Project: dremio-oss   File: YarnController.java   Source Code and License 5 votes vote down vote up
public TwillRunnerService startTwillRunner(YarnConfiguration yarnConfiguration) {
  String zkStr = dremioConfig.getString(DremioConfig.ZOOKEEPER_QUORUM);
  String clusterId = yarnConfiguration.get(YARN_CLUSTER_ID);
  Preconditions.checkNotNull(clusterId, "Cluster ID can not be null");
  TwillRunnerService twillRunner = new YarnTwillRunnerService(yarnConfiguration, zkStr);
  TwillRunnerService previousOne = twillRunners.putIfAbsent(new ClusterId(clusterId), twillRunner);
  if (previousOne == null) {
    // start one we are planning to add - if it is already in collection it should be started
    twillRunner.start();
    return twillRunner;
  }
  return previousOne;
}
 
Example 24
Project: EchoPet   File: PetRegistry.java   Source Code and License 5 votes vote down vote up
public IPet spawn(PetType petType, final Player owner){
	Preconditions.checkNotNull(petType, "Pet type must not be null.");
	Preconditions.checkNotNull(owner, "Owner type must not be null.");
	final PetRegistrationEntry registrationEntry = getRegistrationEntry(petType);
	if(registrationEntry == null){
		// Pet type not registered
		return null;
	}
	return performRegistration(registrationEntry, new Callable<IPet>(){

		public IPet call() throws Exception{
			return registrationEntry.createFor(owner);
		}
	});
}
 
Example 25
Project: apkfile   File: ResourceConfiguration.java   Source Code and License 5 votes vote down vote up
private String unpackLanguageOrRegion(byte[] value, int base) {
    Preconditions.checkState(value.length == 2, "Language or region value must be 2 bytes.");
    if (value[0] == 0 && value[1] == 0) {
        return "";
    }
    if ((UnsignedBytes.toInt(value[0]) & 0x80) != 0) {
        byte[] result = new byte[3];
        result[0] = (byte) (base + (value[1] & 0x1F));
        result[1] = (byte) (base + ((value[1] & 0xE0) >>> 5) + ((value[0] & 0x03) << 3));
        result[2] = (byte) (base + ((value[0] & 0x7C) >>> 2));
        return new String(result, US_ASCII);
    }
    return new String(value, US_ASCII);
}
 
Example 26
Project: de.flapdoodle.solid   File: Sites.java   Source Code and License 5 votes vote down vote up
public static FormatterOfProperty formatterOfProperty(Site site) {
	DefaultObjectFormatter defaultFormatter=new DefaultObjectFormatter();
	return (name,formatterName) -> {
		if (formatterName.isPresent()) {
			return Preconditions.checkNotNull(site.config().formatters().formatters().get(formatterName.get()),"could not get formatter %s",formatterName.get());
		}
		Maybe<String> defaultFormatterName = Maybe.ofNullable(site.config().defaultFormatter().get(name));
		if (defaultFormatterName.isPresent()) {
			return Preconditions.checkNotNull(site.config().formatters().formatters().get(defaultFormatterName.get()),"could not get formatter %s",defaultFormatterName.get());
		}
		return defaultFormatter;
	};
}
 
Example 27
Project: gitplex-mit   File: ProjectBranchesPage.java   Source Code and License 5 votes vote down vote up
public ProjectBranchesPage(PageParameters params) {
	super(params);
	
	baseBranch = params.get(PARAM_BASE).toString();
	if (baseBranch == null)
		baseBranch = Preconditions.checkNotNull(getProject().getDefaultBranch());
	
	if (getProject().getDefaultBranch() == null) 
		throw new RestartResponseException(NoBranchesPage.class, paramsOf(getProject()));
}
 
Example 28
Project: hadoop   File: AMRMClientImpl.java   Source Code and License 5 votes vote down vote up
@Override
public synchronized void releaseAssignedContainer(ContainerId containerId) {
  Preconditions.checkArgument(containerId != null,
      "ContainerId can not be null.");
  pendingRelease.add(containerId);
  release.add(containerId);
}
 
Example 29
Project: stroom-stats   File: MultiPartIdentifier.java   Source Code and License 5 votes vote down vote up
public MultiPartIdentifier(Object... values) {
    Preconditions.checkNotNull(values);
    if (values.length == 0){
        String valuesStr = values == null ? "NULL" : toHumanReadable();
        throw new IllegalArgumentException(String.format("values %s must contain at least one element", valuesStr));
    }
    this.values = values;
}
 
Example 30
Project: vscrawler   File: AnnotationSeedProcessor.java   Source Code and License 5 votes vote down vote up
private void judgeDownloader(Class<? extends AbstractAutoProcessModel> aClass) {
    Method[] methods = aClass.getMethods();
    for (final Method method : methods) {
        if (method.getAnnotation(DownLoadMethod.class) == null) {
            continue;
        }
        Preconditions.checkArgument(String.class.isAssignableFrom(method.getReturnType()));
        Preconditions.checkArgument(method.getParameterTypes().length >= 2);
        Preconditions.checkArgument(method.getParameterTypes()[0].isAssignableFrom(Seed.class));
        Preconditions.checkArgument(method.getParameterTypes()[1].isAssignableFrom(CrawlerSession.class));

        downloader = new Downloader() {
            @Override
            public String download(Seed seed, AbstractAutoProcessModel model, CrawlerSession crawlerSession) {
                try {
                    return (String) method.invoke(model, seed, crawlerSession);
                } catch (Exception e) {
                    throw new RuntimeException("invoke download method :" + method.toGenericString() + " failed", e);
                }
            }
        };
        return;
    }

    downloader = new Downloader() {
        @Override
        public String download(Seed seed, AbstractAutoProcessModel model, CrawlerSession crawlerSession) {
            return crawlerSession.getCrawlerHttpClient().get(seed.getData());
        }
    };
}
 
Example 31
Project: hashsdn-controller   File: AbstractClientConnection.java   Source Code and License 5 votes vote down vote up
private AbstractClientConnection(final AbstractClientConnection<T> oldConn, final TransmitQueue newQueue) {
    this.context = Preconditions.checkNotNull(oldConn.context);
    this.cookie = Preconditions.checkNotNull(oldConn.cookie);
    this.queue = Preconditions.checkNotNull(newQueue);
    // Will be updated in finishReplay if needed.
    this.lastReceivedTicks = oldConn.lastReceivedTicks;
}
 
Example 32
Project: buckaroo   File: RenderableException.java   Source Code and License 5 votes vote down vote up
static Component render(final Throwable throwable) {
    Preconditions.checkNotNull(throwable);
    if (throwable instanceof RenderableException) {
        return ((RenderableException) throwable).render();
    }
    final String message = throwable.getMessage() == null ?
        throwable.toString() :
        throwable.getMessage();
    return Text.of(message, Color.RED);
}
 
Example 33
Project: hashsdn-controller   File: ResolveDataChangeState.java   Source Code and License 5 votes vote down vote up
private ResolveDataChangeState(final YangInstanceIdentifier nodeId,
        final Iterable<Builder> inheritedSub, final Collection<Builder> inheritedOne,
        final Collection<RegistrationTreeNode<DataChangeListenerRegistration<?>>> nodes) {
    this.nodeId = Preconditions.checkNotNull(nodeId);
    this.nodes = Preconditions.checkNotNull(nodes);
    this.inheritedSub = Preconditions.checkNotNull(inheritedSub);
    this.inheritedOne = Preconditions.checkNotNull(inheritedOne);

    /*
     * Collect the nodes which need to be propagated from us to the child.
     */
    final Map<DataChangeListenerRegistration<?>, Builder> sub = new HashMap<>();
    final Map<DataChangeListenerRegistration<?>, Builder> one = new HashMap<>();
    final Map<DataChangeListenerRegistration<?>, Builder> base = new HashMap<>();
    for (RegistrationTreeNode<DataChangeListenerRegistration<?>> n : nodes) {
        for (DataChangeListenerRegistration<?> l : n.getRegistrations()) {
            final Builder b = DOMImmutableDataChangeEvent.builder(DataChangeScope.BASE);
            switch (l.getScope()) {
            case BASE:
                base.put(l, b);
                break;
            case ONE:
                one.put(l, b);
                break;
            case SUBTREE:
                sub.put(l, b);
                break;
            }
        }
    }

    baseBuilders = maybeEmpty(base);
    oneBuilders = maybeEmpty(one);
    subBuilders = maybeEmpty(sub);
}
 
Example 34
Project: dremio-oss   File: PipelineCreator.java   Source Code and License 5 votes vote down vote up
private Pipeline get(PhysicalOperator operator) throws Exception {
  try(RollbackCloseable closeable = AutoCloseables.rollbackable(AutoCloseables.all(operators))) {
    final CreatorVisitor visitor = new CreatorVisitor();
    OpPipe opPipe = operator.accept(visitor, null);
    Preconditions.checkNotNull(opPipe.getPipe());
    Pipeline driver = new Pipeline(opPipe.getPipe(), visitor.terminal, operators, sharedResourcesContext);
    closeable.commit();
    return driver;
  }
}
 
Example 35
Project: CustomWorldGen   File: ContextKey.java   Source Code and License 5 votes vote down vote up
public static <E> ContextKey<E> create(String id, Class<E> c)
{
    Preconditions.checkNotNull(id, "ContextKey's ID can't be null!");
    Preconditions.checkNotNull(c, "ContextKey's Type can't be null!");

    if(id.isEmpty())
    {
        throw new IllegalArgumentException("ContextKey's ID can't be blank!");
    }

    return new ContextKey<E>(id, c);
}
 
Example 36
Project: android-chunk-utils   File: Chunk.java   Source Code and License 5 votes vote down vote up
/**
 * Writes the type and header size. We don't know how big this chunk will be (it could be
 * different since the last time we checked), so this needs to be passed in.
 *
 * @param output The buffer that will be written to.
 * @param chunkSize The total size of this chunk in bytes, including the header.
 */
protected final void writeHeader(ByteBuffer output, int chunkSize) {
  int start = output.position();
  output.putShort(getType().code());
  output.putShort((short) headerSize);
  output.putInt(chunkSize);
  writeHeader(output);
  int headerBytes = output.position() - start;
  Preconditions.checkState(headerBytes == getHeaderSize(),
      "Written header is wrong size. Got %s, want %s", headerBytes, getHeaderSize());
}
 
Example 37
Project: Reer   File: ReportDaemonStatusClient.java   Source Code and License 5 votes vote down vote up
public ReportDaemonStatusClient(DaemonRegistry daemonRegistry, DaemonConnector connector, IdGenerator<?> idGenerator, DocumentationRegistry documentationRegistry) {
    Preconditions.checkNotNull(daemonRegistry, "DaemonRegistry must not be null");
    Preconditions.checkNotNull(connector, "DaemonConnector must not be null");
    Preconditions.checkNotNull(idGenerator, "IdGenerator must not be null");
    Preconditions.checkNotNull(documentationRegistry, "DocumentationRegistry must not be null");

    this.daemonRegistry = daemonRegistry;
    this.connector = connector;
    this.idGenerator = idGenerator;
    this.reportStatusDispatcher = new ReportStatusDispatcher();
    this.documentationRegistry = documentationRegistry;
}
 
Example 38
Project: buckaroo   File: GenericEventRenderer.java   Source Code and License 5 votes vote down vote up
public static Component render(final DependencyInstallationEvent event) {
    Preconditions.checkNotNull(event);
    return StackLayout.of(
        FlowLayout.of(
            Text.of("Downloading: ", Color.CYAN),
            render(event.progress.getValue0().identifier)),
        ListLayout.of(render(event.progress.getValue1())));
}
 
Example 39
Project: chvote-protocol-poc   File: ByteArrayUtils.java   Source Code and License 5 votes vote down vote up
public static byte[] xor(byte[] a, byte[] b) {
    byte[] local_a = Arrays.copyOf(a, a.length);
    byte[] local_b = Arrays.copyOf(b, b.length);
    Preconditions.checkArgument(local_a.length == local_b.length,
            "The arrays should have the same size. |a| = [" + local_a.length + "], |b| = [" + local_b.length + "]");
    byte[] result = new byte[local_a.length];
    for (int i = 0; i < local_a.length; i++) {
        result[i] = (byte) (local_a[i] ^ local_b[i]);
    }
    return result;
}
 
Example 40
Project: hadoop   File: BlockPoolSliceStorage.java   Source Code and License 5 votes vote down vote up
/**
 * Delete all files and directories in the trash directories.
 */
public void restoreTrash() {
  for (StorageDirectory sd : storageDirs) {
    File trashRoot = getTrashRootDir(sd);
    try {
      Preconditions.checkState(!(trashRoot.exists() && sd.getPreviousDir().exists()));
      restoreBlockFilesFromTrash(trashRoot);
      FileUtil.fullyDelete(getTrashRootDir(sd));
    } catch (IOException ioe) {
      LOG.warn("Restoring trash failed for storage directory " + sd);
    }
  }
}
 
Example 41
Project: hashsdn-controller   File: SerializationUtils.java   Source Code and License 5 votes vote down vote up
public static void serializePathAndNode(YangInstanceIdentifier path, NormalizedNode<?, ?> node,
        DataOutput out) {
    Preconditions.checkNotNull(path);
    Preconditions.checkNotNull(node);
    try {
        NormalizedNodeDataOutput streamWriter = streamWriter(out);
        streamWriter.writeNormalizedNode(node);
        streamWriter.writeYangInstanceIdentifier(path);
    } catch (IOException e) {
        throw new IllegalArgumentException(String.format("Error serializing path %s and Node %s",
                path, node), e);
    }
}
 
Example 42
Project: hadoop-oss   File: DataOutputBuffer.java   Source Code and License 5 votes vote down vote up
/**
 * Set the count for the current buf.
 * @param newCount the new count to set
 * @return the original count
 */
private int setCount(int newCount) {
  Preconditions.checkArgument(newCount >= 0 && newCount <= buf.length);
  int oldCount = count;
  count = newCount;
  return oldCount;
}
 
Example 43
Project: hadoop   File: INodeWithAdditionalFields.java   Source Code and License 5 votes vote down vote up
protected void removeFeature(Feature f) {
  int size = features.length;
  Preconditions.checkState(size > 0, "Feature "
      + f.getClass().getSimpleName() + " not found.");

  if (size == 1) {
    Preconditions.checkState(features[0] == f, "Feature "
        + f.getClass().getSimpleName() + " not found.");
    features = EMPTY_FEATURE;
    return;
  }

  Feature[] arr = new Feature[size - 1];
  int j = 0;
  boolean overflow = false;
  for (Feature f1 : features) {
    if (f1 != f) {
      if (j == size - 1) {
        overflow = true;
        break;
      } else {
        arr[j++] = f1;
      }
    }
  }

  Preconditions.checkState(!overflow && j == size - 1, "Feature "
      + f.getClass().getSimpleName() + " not found.");
  features = arr;
}
 
Example 44
Project: hadoop   File: MiniKMS.java   Source Code and License 5 votes vote down vote up
public Builder setSslConf(File keyStoreFile, String keyStorePassword) {
  Preconditions.checkNotNull(keyStoreFile, "keystore file is NULL");
  Preconditions.checkNotNull(keyStorePassword, "keystore password is NULL");
  Preconditions.checkArgument(keyStoreFile.exists(),
      "keystore file does not exist");
  this.keyStoreFile = keyStoreFile;
  this.keyStorePassword = keyStorePassword;
  return this;
}
 
Example 45
Project: hashsdn-controller   File: DOMNotificationRouter.java   Source Code and License 5 votes vote down vote up
@SuppressWarnings("unchecked")
private DOMNotificationRouter(final ExecutorService executor, final int queueDepth, final WaitStrategy strategy) {
    this.executor = Preconditions.checkNotNull(executor);

    disruptor = new Disruptor<>(DOMNotificationRouterEvent.FACTORY, queueDepth, executor, ProducerType.MULTI, strategy);
    disruptor.handleEventsWith(DISPATCH_NOTIFICATIONS);
    disruptor.after(DISPATCH_NOTIFICATIONS).handleEventsWith(NOTIFY_FUTURE);
    disruptor.start();
}
 
Example 46
Project: hashsdn-controller   File: AbstractShardManagerCreator.java   Source Code and License 5 votes vote down vote up
protected void verify() {
    sealed = true;
    Preconditions.checkNotNull(cluster, "cluster should not be null");
    Preconditions.checkNotNull(configuration, "configuration should not be null");
    Preconditions.checkNotNull(datastoreContextFactory, "datastoreContextFactory should not be null");
    Preconditions.checkNotNull(distributedDataStore, "distributedDataStore should not be null");
    Preconditions.checkNotNull(waitTillReadyCountDownLatch, "waitTillReadyCountdownLatch should not be null");
    Preconditions.checkNotNull(primaryShardInfoCache, "primaryShardInfoCache should not be null");
}
 
Example 47
Project: QDrill   File: UnionExchange.java   Source Code and License 5 votes vote down vote up
@Override
public ParallelizationInfo getReceiverParallelizationInfo(List<DrillbitEndpoint> senderFragmentEndpoints) {
  Preconditions.checkArgument(senderFragmentEndpoints != null && senderFragmentEndpoints.size() > 0,
      "Sender fragment endpoint list should not be empty");

  return ParallelizationInfo.create(1, 1, getDefaultAffinityMap(senderFragmentEndpoints));
}
 
Example 48
Project: oryx2   File: ValueWritableConverter.java   Source Code and License 5 votes vote down vote up
/**
 * @param valueClass underlying value class, like {@link String} or {@link Integer}
 * @param writableClass must have a method whose return type matches {@code valueClass}
 *  and whose name starts with "get". Or, in the case of value class {@link String}, the
 *  {@link #toString()} method will be used if not present. Must also have a constructor
 *  with a single argument whose type is the value class, and a no-arg constructor.
 */
<W extends Writable> ValueWritableConverter(Class<V> valueClass, Class<W> writableClass) {
  Method fromWritableMethod = Arrays.stream(writableClass.getMethods()).
      filter(method -> method.getName().startsWith("get")).
      filter(method -> {
        Class<?> returnType = method.getReturnType();
        return returnType.equals(valueClass) || returnType.equals(WRAPPER_TO_PRIMITIVE.get(valueClass));
      }).findFirst().orElse(null);

  if (fromWritableMethod == null && String.class.equals(valueClass)) {
    // Special-case String
    try {
      fromWritableMethod = writableClass.getMethod("toString");
    } catch (NoSuchMethodException e) {
      throw new IllegalArgumentException(e);
    }
  }
  Preconditions.checkArgument(fromWritableMethod != null,
                              writableClass + " has no method returning " + valueClass);
  this.fromWritableMethod = fromWritableMethod;

  @SuppressWarnings("unchecked")
  Constructor<W>[] constructors = (Constructor<W>[]) writableClass.getConstructors();

  writableConstructor = Arrays.stream(constructors).
    filter(constructor -> constructor.getParameterTypes().length == 1).
    filter(constructor -> {
      Class<?> paramType = constructor.getParameterTypes()[0];
      return paramType.equals(valueClass) || paramType.equals(WRAPPER_TO_PRIMITIVE.get(valueClass));
    }).findFirst().orElse(null);
  Objects.requireNonNull(writableConstructor, writableClass + " has no constructor accepting " + valueClass);

  writableNoArgConstructor = Arrays.stream(constructors).
      filter(constructor -> constructor.getParameterTypes().length == 0).
      findFirst().orElse(null);
}
 
Example 49
Project: angel   File: ModelLoader.java   Source Code and License 5 votes vote down vote up
public static Int2DoubleOpenHashMap loadSparseDoubleRowFromPartition(FSDataInputStream input,
    ModelPartitionMeta partMeta, int rowId) throws IOException {
  RowOffset rowOffset = partMeta.getRowMetas().get(rowId);
  input.seek(rowOffset.getOffset());
  Preconditions.checkState (input.readInt() == rowId);
  int num = input.readInt();
  Int2DoubleOpenHashMap row = new Int2DoubleOpenHashMap();
  for (int i = 0; i < num; i++) {
    row.put(input.readInt(), input.readDouble());
  }
  return row;
}
 
Example 50
Project: iTAP-controller   File: PluginResult.java   Source Code and License 5 votes vote down vote up
public PluginResult(@Nonnull PluginResultType result, String reason) {
    Preconditions.checkNotNull(result, "result must not be null");

    if(result != PluginResultType.QUARANTINE && reason != null)
        throw new IllegalStateException("Reason can only be set for Quarantine PluginResult");

    this.result = result;
    this.reason = reason;
}
 
Example 51
Project: fresco_floodlight   File: OFChannelInfo.java   Source Code and License 5 votes vote down vote up
public OFChannelInfo(@Nonnull DatapathId id, @Nonnull OFAuxId auxId, @Nonnull SocketAddress address) {
    Preconditions.checkNotNull(id, "id should not be null");
    Preconditions.checkNotNull(auxId, "auxId should not be null");
    Preconditions.checkNotNull(address, "address should not be null");

    this.id = id;
    this.auxId = auxId;
    InetSocketAddress socketAddress = (InetSocketAddress) address;
    this.address = IPAddress.of(socketAddress.getHostString());
    this.port = socketAddress.getPort();
}
 
Example 52
Project: buckaroo   File: Serializers.java   Source Code and License 5 votes vote down vote up
private static <T> Either<JsonParseException, T> parse(final String x, final Class<T> clazz) {
    Preconditions.checkNotNull(x);
    Preconditions.checkNotNull(clazz);
    try {
        final T t = gson.fromJson(
                new EmptyStringFailFastJsonReader(new StringReader(x)), clazz);
        return Either.right(t);
    } catch (final JsonParseException e) {
        return Either.left(e);
    }
}
 
Example 53
Project: Elasticsearch   File: SimpleCaseExpression.java   Source Code and License 5 votes vote down vote up
public SimpleCaseExpression(Expression operand, List<WhenClause> whenClauses, Expression defaultValue)
{
    Preconditions.checkNotNull(operand, "operand is null");
    Preconditions.checkNotNull(whenClauses, "whenClauses is null");

    this.operand = operand;
    this.whenClauses = ImmutableList.copyOf(whenClauses);
    this.defaultValue = defaultValue;
}
 
Example 54
Project: flume-release-1.7.0   File: BLOBHandler.java   Source Code and License 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@SuppressWarnings("unchecked")
@Override
public List<Event> getEvents(HttpServletRequest request) throws Exception {
  Map<String, String> headers = new HashMap<String, String>();

  InputStream inputStream = request.getInputStream();

  Map<String, String[]> parameters = request.getParameterMap();
  for (String parameter : parameters.keySet()) {
    String value = parameters.get(parameter)[0];
    if (LOG.isDebugEnabled() && LogPrivacyUtil.allowLogRawData()) {
      LOG.debug("Setting Header [Key, Value] as [{},{}] ", parameter, value);
    }
    headers.put(parameter, value);
  }

  for (String header : mandatoryHeaders) {
    Preconditions.checkArgument(headers.containsKey(header),
        "Please specify " + header + " parameter in the request.");
  }

  ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
  try {
    IOUtils.copy(inputStream, outputStream);
    LOG.debug("Building an Event with stream of size -- {}", outputStream.size());
    Event event = EventBuilder.withBody(outputStream.toByteArray(), headers);
    event.setHeaders(headers);
    List<Event> eventList = new ArrayList<Event>();
    eventList.add(event);
    return eventList;
  } finally {
    outputStream.close();
    inputStream.close();
  }
}
 
Example 55
Project: dremio-oss   File: ParquetRowiseReader.java   Source Code and License 5 votes vote down vote up
private static Type getType(String[] pathSegments, int depth, MessageType schema) {
  Type type = schema.getType(Arrays.copyOfRange(pathSegments, 0, depth + 1));
  if (depth + 1 == pathSegments.length) {
    return type;
  } else {
    Preconditions.checkState(!type.isPrimitive());
    return new GroupType(type.getRepetition(), type.getName(), type.getOriginalType(), getType(pathSegments, depth + 1, schema));
  }
}
 
Example 56
Project: storm-dynamic-spout   File: FactoryManager.java   Source Code and License 5 votes vote down vote up
private synchronized <T> T createNewInstanceFromConfig(final String configKey) {
    Preconditions.checkState(
        spoutConfig.containsKey(configKey),
        "Class has not been specified for configuration key " + configKey
    );

    return createNewInstance(
        (String) spoutConfig.get(configKey)
    );
}
 
Example 57
Project: helper   File: Numbers.java   Source Code and License 5 votes vote down vote up
@Nullable
public static Integer parseIntegerNullable(@Nonnull String s) {
    Preconditions.checkNotNull(s);
    try {
        return Integer.parseInt(s);
    } catch (NumberFormatException e) {
        return null;
    }
}
 
Example 58
Project: hadoop   File: FSEditLog.java   Source Code and License 5 votes vote down vote up
/**
 * Set the transaction ID to use for the next transaction written.
 */
synchronized void setNextTxId(long nextTxId) {
  Preconditions.checkArgument(synctxid <= txid &&
     nextTxId >= txid,
     "May not decrease txid." +
    " synctxid=%s txid=%s nextTxId=%s",
    synctxid, txid, nextTxId);
    
  txid = nextTxId - 1;
}
 
Example 59
Project: okwallet   File: NativeSecp256k1.java   Source Code and License 5 votes vote down vote up
/**
 * libsecp256k1 create ECDH secret - constant time ECDH calculation
 *
 * @param seckey byte array of secret key used in exponentiaion
 * @param pubkey byte array of public key used in exponentiaion
 */
public static byte[] createECDHSecret(byte[] seckey, byte[] pubkey) throws AssertFailException {
    Preconditions.checkArgument(seckey.length <= 32 && pubkey.length <= 65);

    ByteBuffer byteBuff = nativeECDSABuffer.get();
    if (byteBuff == null || byteBuff.capacity() < 32 + pubkey.length) {
        byteBuff = ByteBuffer.allocateDirect(32 + pubkey.length);
        byteBuff.order(ByteOrder.nativeOrder());
        nativeECDSABuffer.set(byteBuff);
    }
    byteBuff.rewind();
    byteBuff.put(seckey);
    byteBuff.put(pubkey);

    byte[][] retByteArray;
    r.lock();
    try {
        retByteArray = secp256k1_ecdh(byteBuff, Secp256k1Context.getContext(), pubkey.length);
    } finally {
        r.unlock();
    }

    byte[] resArr = retByteArray[0];
    int retVal = new BigInteger(new byte[] { retByteArray[1][0] }).intValue();

    assertEquals(resArr.length, 32, "Got bad result length.");
    assertEquals(retVal, 1, "Failed return value check.");

    return resArr;
}
 
Example 60
Project: de.flapdoodle.solid   File: Filters.java   Source Code and License 5 votes vote down vote up
public static Operator of(String name) {
	switch (name) {
		case "eq":
			return Equals;
		case "!eq":
			return NotEquals;
	}
	
	return Preconditions.checkNotNull(null,"could not get operator for %s",name);
}