Java Code Examples for com.google.common.base.Preconditions#checkState()

The following examples show how to use com.google.common.base.Preconditions#checkState() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: SampleQuantiles.java    From hadoop with Apache License 2.0 8 votes vote down vote up
/**
 * Get the estimated value at the specified quantile.
 * 
 * @param quantile Queried quantile, e.g. 0.50 or 0.99.
 * @return Estimated value at that quantile.
 */
private long query(double quantile) {
  Preconditions.checkState(!samples.isEmpty(), "no data in estimator");

  int rankMin = 0;
  int desired = (int) (quantile * count);

  ListIterator<SampleItem> it = samples.listIterator();
  SampleItem prev = null;
  SampleItem cur = it.next();
  for (int i = 1; i < samples.size(); i++) {
    prev = cur;
    cur = it.next();

    rankMin += prev.g;

    if (rankMin + cur.g + cur.delta > desired + (allowableError(i) / 2)) {
      return prev.value;
    }
  }

  // edge case of wanting max value
  return samples.get(samples.size() - 1).value;
}
 
Example 2
Source File: AlpacaAPI.java    From alpaca-java with MIT License 6 votes vote down vote up
/**
 * Create a new watchlist with initial set of assets.
 *
 * @param name    arbitrary name string, up to 64 characters
 * @param symbols set of symbol string
 *
 * @return the created watchlist
 *
 * @throws AlpacaAPIRequestException the alpaca api exception
 * @see <a href="https://docs.alpaca.markets/api-documentation/api-v2/watchlist/">Watchlists</a>
 */
public Watchlist createWatchlist(String name, String... symbols) throws AlpacaAPIRequestException {
    Preconditions.checkNotNull(name);
    Preconditions.checkState(name.length() <= 64);

    AlpacaRequestBuilder urlBuilder = new AlpacaRequestBuilder(baseAPIURL, apiVersion,
            AlpacaConstants.WATCHLISTS_ENDPOINT);

    urlBuilder.appendJSONBodyProperty("name", name);

    if (symbols != null) {
        JsonArray symbolsArray = new JsonArray();
        Arrays.stream(symbols).forEach(symbolsArray::add);

        urlBuilder.appendJSONBodyJSONProperty("symbols", symbolsArray);
    }

    HttpResponse<InputStream> response = alpacaRequest.invokePost(urlBuilder);

    if (response.getStatus() != 200) {
        throw new AlpacaAPIRequestException(response);
    }

    return alpacaRequest.getResponseObject(response, Watchlist.class);
}
 
Example 3
Source File: DefaultKeyGenerator.java    From sharding-jdbc-1.5.1 with Apache License 2.0 6 votes vote down vote up
/**
 * 生成Id.
 * 
 * @return 返回@{@link Long}类型的Id
 */
@Override
public synchronized Number generateKey() {
    long currentMillis = timeService.getCurrentMillis();
    Preconditions.checkState(lastTime <= currentMillis, "Clock is moving backwards, last time is %d milliseconds, current time is %d milliseconds", lastTime, currentMillis);
    if (lastTime == currentMillis) {
        if (0L == (sequence = ++sequence & SEQUENCE_MASK)) {
            currentMillis = waitUntilNextTime(currentMillis);
        }
    } else {
        sequence = 0;
    }
    lastTime = currentMillis;
    if (log.isDebugEnabled()) {
        log.debug("{}-{}-{}", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS").format(new Date(lastTime)), workerId, sequence);
    }
    return ((currentMillis - EPOCH) << TIMESTAMP_LEFT_SHIFT_BITS) | (workerId << WORKER_ID_LEFT_SHIFT_BITS) | sequence;
}
 
Example 4
Source File: CustomGeneratorWithSV2.java    From dremio-oss with Apache License 2.0 6 votes vote down vote up
public CustomGeneratorWithSV2(int numRows, BufferAllocator allocator, SelectionVariant variant) {
  Preconditions.checkState(numRows > 0);
  this.numRows = numRows;
  this.stringValues = listOfStrings(numRows);
  this.intValues = randomListOfInts(numRows);
  this.longValues = randomListOfLongs(numRows);
  this.decimalValues = randomListOfDecimals(numRows);
  this.listValues = listOfLists(numRows);
  this.bitValues = randomBits(numRows);
  this.selectedBitSet = new BitSet(numRows);
  this.totalSelectedRows = 0;
  computeSelection(variant);

  this.sv2 = new SelectionVector2(allocator);
  this.container = new VectorContainerWithSV(allocator, sv2);
  this.bitVector = container.addOrGet(BITF);
  this.intVector = container.addOrGet(INTF);
  this.bigIntVector = container.addOrGet(BIGINTF);
  this.decimalVector = container.addOrGet(DECIMALF);
  this.stringVector = container.addOrGet(STRINGF);
  this.listVector = container.addOrGet(LISTF);
  container.buildSchema(SelectionVectorMode.TWO_BYTE);
  listVector.addOrGetVector(FieldType.nullable(MinorType.BIGINT.getType()));
}
 
Example 5
Source File: ByteStringWriteReader.java    From bazel-buildfarm with Apache License 2.0 5 votes vote down vote up
public ByteStringWriteReader(InputStream input, Write write, int dataLimit) {
  this.input = input;
  this.write = write;
  this.dataLimit = dataLimit;
  Preconditions.checkState(dataLimit > 0);
  completed = false;
}
 
Example 6
Source File: AthenaQuerySteps.java    From realworld-serverless-application with Apache License 2.0 5 votes vote down vote up
@Then("^a new application should be created|the application should be updated$")
public void a_new_application_should_be_created() {
  assertThat(TestEnv.getLastException()).isNull();
  Preconditions.checkState(TestEnv.getApplicationId() != null, "Step assumes previous application id exists");

  GetApplicationResult result = appRepo.getApplication(new GetApplicationRequest().applicationId(TestEnv.getApplicationId()));
  assertThat(result.getApplication())
      .isNotNull()
      .isEqualTo(TestEnv.getApplication());
}
 
Example 7
Source File: SSTableImpl.java    From Distributed-KV with Apache License 2.0 5 votes vote down vote up
@Override
public Block openBlock(int blockOffset, int blockSize) throws IOException {
	Preconditions.checkState(!isClosed);
	Preconditions.checkArgument(blockOffset >= 0 && blockOffset < metaBlockOffset, String.format("block offset = %d 越界", blockOffset));
	Preconditions.checkArgument(blockSize > 0);
	// 为data block分配内存
	ByteBuf blockBuffer = PooledByteBufAllocator.DEFAULT.buffer(blockSize);
	// 读入数据
	ByteBufUtils.read(channel.position(blockOffset), blockBuffer);
	Block block = new BlockImpl(blockBuffer);
	return block;
}
 
Example 8
Source File: XDR.java    From hadoop with Apache License 2.0 5 votes vote down vote up
/** Write an XDR message to a TCP ChannelBuffer */
public static ChannelBuffer writeMessageTcp(XDR request, boolean last) {
  Preconditions.checkState(request.state == XDR.State.WRITING);
  ByteBuffer b = request.buf.duplicate();
  b.flip();
  byte[] fragmentHeader = XDR.recordMark(b.limit(), last);
  ByteBuffer headerBuf = ByteBuffer.wrap(fragmentHeader);

  // TODO: Investigate whether making a copy of the buffer is necessary.
  return ChannelBuffers.copiedBuffer(headerBuf, b);
}
 
Example 9
Source File: NodeStateManager.java    From hadoop-ozone with Apache License 2.0 5 votes vote down vote up
/**
 * Constructs a NodeStateManager instance with the given configuration.
 *
 * @param conf Configuration
 */
public NodeStateManager(ConfigurationSource conf,
    EventPublisher eventPublisher) {
  this.nodeStateMap = new NodeStateMap();
  this.node2PipelineMap = new Node2PipelineMap();
  this.eventPublisher = eventPublisher;
  this.state2EventMap = new HashMap<>();
  initialiseState2EventMap();
  Set<NodeState> finalStates = new HashSet<>();
  finalStates.add(NodeState.DECOMMISSIONED);
  this.stateMachine = new StateMachine<>(NodeState.HEALTHY, finalStates);
  initializeStateMachine();
  heartbeatCheckerIntervalMs = HddsServerUtil
      .getScmheartbeatCheckerInterval(conf);
  staleNodeIntervalMs = HddsServerUtil.getStaleNodeInterval(conf);
  deadNodeIntervalMs = HddsServerUtil.getDeadNodeInterval(conf);
  Preconditions.checkState(heartbeatCheckerIntervalMs > 0,
      OZONE_SCM_HEARTBEAT_PROCESS_INTERVAL + " should be greater than 0.");
  Preconditions.checkState(staleNodeIntervalMs < deadNodeIntervalMs,
      OZONE_SCM_STALENODE_INTERVAL + " should be less than" +
          OZONE_SCM_DEADNODE_INTERVAL);
  executorService = HadoopExecutors.newScheduledThreadPool(1,
      new ThreadFactoryBuilder().setDaemon(true)
          .setNameFormat("SCM Heartbeat Processing Thread - %d").build());

  skippedHealthChecks = 0;
  checkPaused = false; // accessed only from test functions

  scheduleNextHealthCheck();
}
 
Example 10
Source File: BlockManagerImpl.java    From hadoop-ozone with Apache License 2.0 5 votes vote down vote up
/**
 * Deletes an existing block.
 *
 * @param container - Container from which block need to be deleted.
 * @param blockID - ID of the block.
 * @throws StorageContainerException
 */
public void deleteBlock(Container container, BlockID blockID) throws
    IOException {
  Preconditions.checkNotNull(blockID, "block ID cannot be null.");
  Preconditions.checkState(blockID.getContainerID() >= 0,
      "Container ID cannot be negative.");
  Preconditions.checkState(blockID.getLocalID() >= 0,
      "Local ID cannot be negative.");

  KeyValueContainerData cData = (KeyValueContainerData) container
      .getContainerData();
  try(ReferenceCountedDB db = BlockUtils.getDB(cData, config)) {
    // This is a post condition that acts as a hint to the user.
    // Should never fail.
    Preconditions.checkNotNull(db, DB_NULL_ERR_MSG);
    // Note : There is a race condition here, since get and delete
    // are not atomic. Leaving it here since the impact is refusing
    // to delete a Block which might have just gotten inserted after
    // the get check.
    byte[] blockKey = Longs.toByteArray(blockID.getLocalID());

    getBlockByID(db, blockID);

    // Update DB to delete block and set block count and bytes used.
    BatchOperation batch = new BatchOperation();
    batch.delete(blockKey);
    // Update DB to delete block and set block count.
    // No need to set bytes used here, as bytes used is taken care during
    // delete chunk.
    batch.put(DB_BLOCK_COUNT_KEY,
        Longs.toByteArray(container.getContainerData().getKeyCount() - 1));
    db.getStore().writeBatch(batch);

    // Decrement block count here
    container.getContainerData().decrKeyCount();
  }
}
 
Example 11
Source File: DefaultBulletinBoard.java    From chvote-protocol-poc with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public List<EncryptionPublicKey> getPublicKeyParts() {
    Preconditions.checkState(publicParameters != null,
            "The public parameters need to have been defined first");
    Preconditions.checkState(publicKeyParts.size() == publicParameters.getS(),
            "There should be as many key parts as authorities...");

    return publicKeyParts.entrySet().stream().sorted(Comparator.comparing(Map.Entry::getKey))
            .map(Map.Entry::getValue).collect(Collectors.toList());
}
 
Example 12
Source File: ParquetRecordWriter.java    From dremio-oss with Apache License 2.0 5 votes vote down vote up
private MessageType getParquetMessageTypeWithIds(BatchSchema batchSchema, String name) {
  List<Type> types = Lists.newArrayList();
  for (Field field : batchSchema) {
    if (field.getName().equalsIgnoreCase(WriterPrel.PARTITION_COMPARATOR_FIELD)) {
      continue;
    }
    Type childType = getTypeWithId(field, field.getName());
    if (childType != null) {
      types.add(childType);
    }
  }
  Preconditions.checkState(types.size() > 0, "No types for parquet schema");
  return new MessageType(name, types);
}
 
Example 13
Source File: UpgradeStore.java    From dremio-oss with Apache License 2.0 5 votes vote down vote up
public UpgradeTaskStore updateLastUpgradeRun(String upgradeTaskID, String upgradeTaskName, UpgradeTaskRun
  upgradeTaskRun) {
  UpgradeTaskId upgradeTaskId = new UpgradeTaskId();
  upgradeTaskId.setId(upgradeTaskID);
  UpgradeTaskStore upgradeTaskStore = store.get(upgradeTaskId);
  if (upgradeTaskStore == null) {
    return createUpgradeTaskStoreEntry(upgradeTaskID, upgradeTaskName, upgradeTaskRun);
  }

  List<UpgradeTaskRun> runs = upgradeTaskStore.getRunsList();
  if (runs == null || runs.isEmpty()) {
    // this woudl be really strange
    System.out.println("WARN: No Runs found for task: " + upgradeTaskName + " . Adding one.");
    runs = Collections.singletonList(upgradeTaskRun);
  } else {
    final UpgradeTaskRun lastRun = runs.get(runs.size() - 1);

    // should not upgrade run in terminal state
    Preconditions.checkState(
      !isTerminalState(lastRun.getStatus()),
      String.format("Can not upgrade task: '%s' as it is in state: '%s' which is not terminal state",
        upgradeTaskName, lastRun.getStatus()));

    runs.set(runs.size() - 1, upgradeTaskRun);
  }
  upgradeTaskStore.setRunsList(runs);
  store.put(upgradeTaskId, upgradeTaskStore);
  return getByTaskId(upgradeTaskID);
}
 
Example 14
Source File: BaseTask.java    From javaide with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Returns the androidBuilder.
 *
 * @throws IllegalStateException if androidBuilder has not been set,
 */
@NonNull
protected AndroidBuilder getBuilder() {
    Preconditions.checkState(androidBuilder != null,
            "androidBuilder required for task '%s'.", getName());
    return androidBuilder;
}
 
Example 15
Source File: ExecTunnel.java    From dremio-oss with Apache License 2.0 4 votes vote down vote up
private static void checkFragmentHandle(FragmentHandle handle) {
  Preconditions.checkState(handle.hasQueryId(), "must set query id");
  Preconditions.checkState(handle.hasMajorFragmentId(), "must set major fragment id");
  Preconditions.checkState(handle.hasMinorFragmentId(), "must set minor fragment id");
}
 
Example 16
Source File: ArgumentResolverFactoryChain.java    From arcusplatform with Apache License 2.0 4 votes vote down vote up
public ArgumentResolverFactory<I, R> build() {
	Preconditions.checkState(!factories.isEmpty(), "Must add at least one factory");
	return new ArgumentResolverFactoryChain<>(new ArrayList<>(factories));
}
 
Example 17
Source File: VerifierNone.java    From hadoop with Apache License 2.0 4 votes vote down vote up
@Override
public void read(XDR xdr) {
  int length = xdr.readInt();
  Preconditions.checkState(length == 0);
}
 
Example 18
Source File: PackageChunk.java    From android-chunk-utils with Apache License 2.0 4 votes vote down vote up
/**
 * Returns the string pool that contains the names of the resources in this package.
 */
public StringPoolChunk getKeyStringPool() {
  Chunk chunk = Preconditions.checkNotNull(getChunks().get(keyStringsOffset + offset));
  Preconditions.checkState(chunk instanceof StringPoolChunk, "Key string pool not found.");
  return (StringPoolChunk) chunk;
}
 
Example 19
Source File: EngineImpl.java    From Distributed-KV with Apache License 2.0 4 votes vote down vote up
/**
 * 为写线程确保空间,适当地为合并线程让出系统资源
 * @throws IOException
 */
private void mkRoomForWrite() throws IOException {
	// 确保写入线程持有锁
	Preconditions.checkState(engineLock.isHeldByCurrentThread());
	while(true) {
		// 当level0 文件数量超过slow down 指标时,慢行// 当level0 文件数量超过slow down 指标时,慢行
		if(versions.getCurrent().files(0) > Options.L0_SLOW_DOWN_COUNT) {
			try {
				// 延缓生产
				// 释放锁,交由写线程和compaction线程竞争
				engineLock.unlock();
				Thread.sleep(1);
			} catch (InterruptedException e) {
				e.printStackTrace();
			} finally {
				// 重新竞争锁
				engineLock.lock();
			}
		}
		// 当memtable未超过限制,跳出循环
		if(memTable.size() < Options.MEMTABLE_LIMIT) {
			break;
		}
		// 如果immutable不为空,说明上一次minor compaction未结束,需要等待
		if(immutableMemTable != null) {
			backgroundCondition.awaitUninterruptibly();
		}
		// 如果level0文件数量超过限制,需要等待major compaction
		if(versions.getCurrent().files(0) > Options.LEVEL0_LIMIT_COUNT) {
			backgroundCondition.awaitUninterruptibly();
		}
		// 如果mem table达到阈值,则进行minor compaction
		else if(memTable.size() >= Options.MEMTABLE_LIMIT) {
			// 关闭旧的log,开启新的log
			log.close();
			// 获取文件编号
			long logNumber = versions.getNextFileNumber();
			// 新建log
			log = new LogWriterImpl(databaseDir, logNumber, false);
			// 新建memtable,原有的memtable转变为immutable memtable
			immutableMemTable = memTable;
			memTable = new MemTableImpl();
			// 触发compaction
			maybeCompaction();
		}
		
	}
}
 
Example 20
Source File: Loot.java    From osbuddy-community with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
public int npcId() {
    Preconditions.checkState(source == Source.BOSS || source == Source.NPC);
    return npcId;
}