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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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);
    }
  }
}