com.google.common.base.Verify类的使用及代码示例

x33g5p2x  于2022-01-31 转载在 其他  
字(16.8k)|赞(0)|评价(0)|浏览(101)

本文整理了Java中com.google.common.base.Verify类的一些代码示例,展示了Verify类的具体用法。这些代码示例主要来源于Github/Stackoverflow/Maven等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。Verify类的具体详情如下:
包路径:com.google.common.base.Verify
类名称:Verify

Verify介绍

[英]Static convenience methods that serve the same purpose as Java language assertions, except that they are always enabled. These methods should be used instead of Java assertions whenever there is a chance the check may fail "in real life". Example:

Bill bill = remoteService.getLastUnpaidBill();

Comparison to alternatives

Note: In some cases the differences explained below can be subtle. When it's unclear which approach to use, don't worry too much about it; just pick something that seems reasonable and it will be fine.

  • If checking whether the caller has violated your method or constructor's contract (such as by passing an invalid argument), use the utilities of the Preconditionsclass instead.
  • If checking an impossible condition (which cannot happen unless your own class or its trusted dependencies is badly broken), this is what ordinary Java assertions are for. Note that assertions are not enabled by default; they are essentially considered "compiled comments."
  • An explicit if/throw (as illustrated below) is always acceptable; we still recommend using our VerifyException exception type. Throwing a plain RuntimeException is frowned upon.
  • Use of java.util.Objects#requireNonNull(Object) is generally discouraged, since #verifyNotNull(Object) and Preconditions#checkNotNull(Object) perform the same function with more clarity.

Warning about performance

Remember that parameter values for message construction must all be computed eagerly, and autoboxing and varargs array creation may happen as well, even when the verification succeeds and the message ends up unneeded. Performance-sensitive verification checks should continue to use usual form:

Bill bill = remoteService.getLastUnpaidBill();}

Only %s is supported

As with Preconditions error message template strings, only the "%s" specifier is supported, not the full range of java.util.Formatter specifiers. However, note that if the number of arguments does not match the number of occurrences of "%s" in the format string, Verify will still behave as expected, and will still include all argument values in the error message; the message will simply not be formatted exactly as intended.

More information

See Conditional failures explained in the Guava User Guide for advice on when this class should be used.
[中]静态便利方法的用途与Java语言assertions相同,只是它们始终处于启用状态。只要“在现实生活中”检查有可能失败,就应该使用这些方法,而不是Java断言。示例:

Bill bill = remoteService.getLastUnpaidBill();

####与替代品的比较
注意:在某些情况下,下面解释的差异可能很微妙。当不清楚使用哪种方法时,不要太担心;只要选择一些似乎合理的东西就好了。
*如果检查调用方是否违反了方法或构造函数的约定(例如通过传递无效参数),请使用PremissionsClass的实用程序。
*如果检查一个不可能的条件(除非您自己的类或其受信任的依赖关系被严重破坏,否则不可能发生),这就是普通Java断言的目的。请注意,默认情况下不会启用断言;它们基本上被视为“汇编评论”
*明确的if/throw(如下所示)总是可以接受的;我们仍然建议使用VerifyException类型。抛出普通的RuntimeException是不可取的。
*java的使用。util。通常不鼓励使用对象#requirennoull(对象),因为#verifyNotNull(对象)和前提条件#checkNotNull(对象)更清晰地执行相同的功能。
####关于性能的警告
请记住,消息构造的参数值都必须急切地计算出来,而且自动装箱和varargs数组创建也可能发生,即使验证成功,消息最终不再需要。性能敏感验证检查应继续使用常规形式:

Bill bill = remoteService.getLastUnpaidBill();}

####仅支持%s
与Premissions错误消息模板字符串一样,只支持“%s”说明符,而不支持java的全部范围。util。格式化程序说明符。但是,请注意,如果参数的数量与格式字符串中出现“%s”的次数不匹配,则Verify仍将按预期运行,并且仍将在错误消息中包含所有参数值;消息的格式将完全不符合预期。
####更多信息
请参阅《Guava用户指南》中的{$1$},以获取关于何时应使用此类的建议。

代码示例

代码示例来源:origin: prestodb/presto

public List<String> getIndices(ElasticsearchTableDescription tableDescription)
{
  if (tableDescription.getIndexExactMatch()) {
    return ImmutableList.of(tableDescription.getIndex());
  }
  TransportClient client = clients.get(tableDescription.getClusterName());
  verify(client != null, "client is null");
  String[] indices = getIndices(client, new GetIndexRequest());
  return Arrays.stream(indices)
        .filter(index -> index.startsWith(tableDescription.getIndex()))
        .collect(toImmutableList());
}

代码示例来源:origin: google/guava

/**
 * Ensures that {@code reference} is non-null, throwing a {@code VerifyException} with a default
 * message otherwise.
 *
 * @return {@code reference}, guaranteed to be non-null, for convenience
 * @throws VerifyException if {@code reference} is {@code null}
 * @see Preconditions#checkNotNull Preconditions.checkNotNull()
 */
@CanIgnoreReturnValue
public static <T> T verifyNotNull(@Nullable T reference) {
 return verifyNotNull(reference, "expected a non-null reference");
}

代码示例来源:origin: prestodb/presto

List<RemoteTask> newTasks = ImmutableList.of();
if (!scheduledTasks) {
  OptionalInt totalPartitions = OptionalInt.of(nodes.size());
      nodes.stream(),
      (node, id) -> stage.scheduleTask(node, toIntExact(id), totalPartitions))
      .filter(Optional::isPresent)
      .map(Optional::get)
      .collect(toImmutableList());
  scheduledTasks = true;
BlockedReason blockedReason = BlockedReason.NO_ACTIVE_DRIVER_GROUP;
if (groupedLifespanScheduler.isPresent()) {
  blocked.add(groupedLifespanScheduler.get().schedule(sourceSchedulers.get(0)));
List<Lifespan> driverGroupsToStart = ImmutableList.of();
boolean shouldInvokeNoMoreDriverGroups = false;
while (schedulerIterator.hasNext()) {
  if (schedule.getBlockedReason().isPresent()) {
    blocked.add(schedule.getBlocked());
    blockedReason = blockedReason.combineWith(schedule.getBlockedReason().get());
    verify(schedule.getBlocked().isDone(), "blockedReason not provided when scheduler is blocked");
    allBlocked = false;

代码示例来源:origin: prestodb/presto

.map(Slice::getBytes)
    .map(partitionUpdateCodec::fromJson)
    .collect(toList());
if (handle.getBucketProperty().isPresent()) {
  ImmutableList<PartitionUpdate> partitionUpdatesForMissingBuckets = computePartitionUpdatesForMissingBuckets(session, handle, table, partitionUpdates);
    Optional<Partition> partition = table.getPartitionColumns().isEmpty() ? Optional.empty() : Optional.of(buildPartitionObject(session, table, partitionUpdate));
    createEmptyFile(session, partitionUpdate.getWritePath(), table, partition, partitionUpdate.getFileNames());
      .reduce((first, second) -> reduce(first, second, ADD))
      .orElse(createZeroStatistics());
  tableStatistics = createPartitionStatistics(session, basicStatistics, ImmutableList.of(), columnTypes, partitionComputedStatistics);
    Verify.verify(handle.getPartitionStorageFormat() == handle.getTableStorageFormat());

代码示例来源:origin: prestodb/presto

@VisibleForTesting
static Estimate calculateDistinctValuesCount(List<HiveColumnStatistics> columnStatistics)
{
  return columnStatistics.stream()
      .map(MetastoreHiveStatisticsProvider::getDistinctValuesCount)
      .filter(OptionalLong::isPresent)
      .map(OptionalLong::getAsLong)
      .peek(distinctValuesCount -> verify(distinctValuesCount >= 0, "distinctValuesCount must be greater than or equal to zero"))
      .max(Long::compare)
      .map(Estimate::of)
      .orElse(Estimate.unknown());
}

代码示例来源:origin: prestodb/presto

public static StreamProperties deriveProperties(PlanNode node, List<StreamProperties> inputProperties, Metadata metadata, Session session, TypeProvider types, SqlParser parser)
{
  requireNonNull(node, "node is null");
  requireNonNull(inputProperties, "inputProperties is null");
  requireNonNull(metadata, "metadata is null");
  requireNonNull(session, "session is null");
  requireNonNull(types, "types is null");
  requireNonNull(parser, "parser is null");
  // properties.otherActualProperties will never be null here because the only way
  // an external caller should obtain StreamProperties is from this method, and the
  // last line of this method assures otherActualProperties is set.
  ActualProperties otherProperties = PropertyDerivations.streamBackdoorDeriveProperties(
      node,
      inputProperties.stream()
          .map(properties -> properties.otherActualProperties)
          .collect(toImmutableList()),
      metadata,
      session,
      types,
      parser);
  StreamProperties result = node.accept(new Visitor(metadata, session), inputProperties)
      .withOtherActualProperties(otherProperties);
  result.getPartitioningColumns().ifPresent(columns ->
      verify(node.getOutputSymbols().containsAll(columns), "Stream-level partitioning properties contain columns not present in node's output"));
  Set<Symbol> localPropertyColumns = result.getLocalProperties().stream()
      .flatMap(property -> property.getColumns().stream())
      .collect(Collectors.toSet());
  verify(node.getOutputSymbols().containsAll(localPropertyColumns), "Stream-level local properties contain columns not present in node's output");
  return result;
}

代码示例来源:origin: prestodb/presto

implements Rule<JoinNode>
private static final Pattern<JoinNode> PATTERN = join().matching(node -> node.getCriteria().isEmpty() && node.getFilter().isPresent() && node.getType() == LEFT);

代码示例来源:origin: prestodb/presto

void run(@Language("SQL") String query, QueryRunner runner)
  {
    List<Metric> metrics = checks.stream()
        .map(check -> check.metric)
        .collect(toImmutableList());
    List<MetricComparison> metricComparisons = getMetricComparisons(query, runner, metrics);
    verify(checks.size() == metricComparisons.size());
    for (int i = 0; i < checks.size(); i++) {
      MetricsCheck check = checks.get(i);
      MetricComparison metricComparison = metricComparisons.get(i);
      assertSame(metricComparison.result(check.strategy), check.expectedComparisonResult, "Metric doesn't match: " + metricComparison);
    }
  }
}

代码示例来源:origin: prestodb/presto

.map(columnToSymbolMap::get)
  .collect(toImmutableList());
    new FunctionCall(count, ImmutableList.of()),
    functionRegistry.resolveFunction(count, ImmutableList.of()),
    Optional.empty());
Symbol symbol = symbolAllocator.newSymbol("rowCount", BIGINT);
aggregations.put(symbol, aggregation);
ColumnStatisticType statisticType = columnStatisticMetadata.getStatisticType();
Symbol inputSymbol = columnToSymbolMap.get(columnName);
verify(inputSymbol != null, "inputSymbol is null");
Type inputType = symbolAllocator.getTypes().get(inputSymbol);
verify(inputType != null, "inputType is null for symbol: %s", inputSymbol);
ColumnStatisticsAggregation aggregation = createColumnAggregation(statisticType, inputSymbol, inputType);
Symbol symbol = symbolAllocator.newSymbol(statisticType + ":" + columnName, aggregation.getOutputType());

代码示例来源:origin: prestodb/presto

protected final OperatorFactory createHashProjectOperator(int operatorId, PlanNodeId planNodeId, List<Type> types)
{
  ImmutableMap.Builder<Symbol, Type> symbolTypes = ImmutableMap.builder();
  ImmutableMap.Builder<Symbol, Integer> symbolToInputMapping = ImmutableMap.builder();
  ImmutableList.Builder<PageProjection> projections = ImmutableList.builder();
  for (int channel = 0; channel < types.size(); channel++) {
    Symbol symbol = new Symbol("h" + channel);
    symbolTypes.put(symbol, types.get(channel));
    symbolToInputMapping.put(symbol, channel);
    projections.add(new InputPageProjection(channel, types.get(channel)));
  }
  Optional<Expression> hashExpression = HashGenerationOptimizer.getHashExpression(ImmutableList.copyOf(symbolTypes.build().keySet()));
  verify(hashExpression.isPresent());
  projections.add(new InterpretedPageProjection(
      hashExpression.get(),
      TypeProvider.copyOf(symbolTypes.build()),
      symbolToInputMapping.build(),
      localQueryRunner.getMetadata(),
      localQueryRunner.getSqlParser(),
      session));
  return new FilterAndProjectOperator.FilterAndProjectOperatorFactory(
      operatorId,
      planNodeId,
      () -> new PageProcessor(Optional.empty(), projections.build()),
      ImmutableList.copyOf(Iterables.concat(types, ImmutableList.of(BIGINT))),
      getFilterAndProjectMinOutputPageSize(session),
      getFilterAndProjectMinOutputPageRowCount(session));
}

代码示例来源:origin: prestodb/presto

ImmutableList.Builder<Expression> maskSymbols = ImmutableList.builder();
boolean aggregateWithoutFilterPresent = false;
  Optional<Symbol> mask = entry.getValue().getMask();
  if (call.getFilter().isPresent()) {
    Expression filter = call.getFilter().get();
    Symbol symbol = context.getSymbolAllocator().newSymbol(filter, BOOLEAN);
    verify(!mask.isPresent(), "Expected aggregation without mask symbols, see Rule pattern");
    newAssignments.put(symbol, filter);
    mask = Optional.of(symbol);
    maskSymbols.add(symbol.toSymbolReference());
  predicate = combineDisjunctsWithDefault(maskSymbols.build(), TRUE_LITERAL);
        aggregations.build(),
        aggregation.getGroupingSets(),
        ImmutableList.of(),
        aggregation.getStep(),
        aggregation.getHashSymbol(),

代码示例来源:origin: prestodb/presto

.map(columnHandlesByName::get)
    .map(column -> new Column(column.getName(), column.getHiveType(), column.getComment()))
    .collect(toList());
ImmutableList.Builder<Column> columns = ImmutableList.builder();
for (HiveColumnHandle columnHandle : columnHandles) {
  String name = columnHandle.getName();
  HiveType type = columnHandle.getHiveType();
  if (!partitionColumnNames.contains(name)) {
    verify(!columnHandle.isPartitionKey(), "Column handles are not consistent with partitioned by property");
    columns.add(new Column(name, type, columnHandle.getComment()));
    verify(columnHandle.isPartitionKey(), "Column handles are not consistent with partitioned by property");
    .setOwner(tableOwner)
    .setTableType((external ? EXTERNAL_TABLE : MANAGED_TABLE).name())
    .setDataColumns(columns.build())
    .setPartitionColumns(partitionColumns)
    .setParameters(tableParameters.build());

代码示例来源:origin: prestodb/presto

private static boolean isColumnPredicate(ColumnDescriptor columnDescriptor, TupleDomain<ColumnDescriptor> parquetTupleDomain)
{
  verify(parquetTupleDomain.getDomains().isPresent(), "parquetTupleDomain is empty");
  return parquetTupleDomain.getDomains().get().keySet().contains(columnDescriptor);
}

代码示例来源:origin: prestodb/presto

public static ActualProperties deriveProperties(PlanNode node, List<ActualProperties> inputProperties, Metadata metadata, Session session, TypeProvider types, SqlParser parser)
{
  ActualProperties output = node.accept(new Visitor(metadata, session, types, parser), inputProperties);
  output.getNodePartitioning().ifPresent(partitioning ->
      verify(node.getOutputSymbols().containsAll(partitioning.getColumns()), "Node-level partitioning properties contain columns not present in node's output"));
  verify(node.getOutputSymbols().containsAll(output.getConstants().keySet()), "Node-level constant properties contain columns not present in node's output");
  Set<Symbol> localPropertyColumns = output.getLocalProperties().stream()
      .flatMap(property -> property.getColumns().stream())
      .collect(Collectors.toSet());
  verify(node.getOutputSymbols().containsAll(localPropertyColumns), "Node-level local properties contain columns not present in node's output");
  return output;
}

代码示例来源:origin: prestodb/presto

private PlanNodeCostEstimate getGroupCost(GroupReference groupReference)
{
  int group = groupReference.getGroupId();
  Memo memo = this.memo.orElseThrow(() -> new IllegalStateException("CachingCostProvider without memo cannot handle GroupReferences"));
  Optional<PlanNodeCostEstimate> cost = memo.getCumulativeCost(group);
  if (cost.isPresent()) {
    return cost.get();
  }
  PlanNodeCostEstimate cumulativeCost = calculateCumulativeCost(memo.getNode(group));
  verify(!memo.getCumulativeCost(group).isPresent(), "Group cost already set");
  memo.storeCumulativeCost(group, cumulativeCost);
  return cumulativeCost;
}

代码示例来源:origin: prestodb/presto

if (!lambdaArgumentTypes.isPresent()) {
  return SolverReturnStatus.UNCHANGED_NOT_SATISFIED;
if (!typeSignatureProvider.hasDependency()) {
  actualLambdaTypeSignature = typeSignatureProvider.getTypeSignature();
  if (!FunctionType.NAME.equals(actualLambdaTypeSignature.getBase()) || !getLambdaArgumentTypeSignatures(actualLambdaTypeSignature).equals(toTypeSignatures(lambdaArgumentTypes.get()))) {
    return SolverReturnStatus.UNSOLVABLE;
  actualLambdaTypeSignature = typeSignatureProvider.getTypeSignature(lambdaArgumentTypes.get());
  if (!FunctionType.NAME.equals(actualLambdaTypeSignature.getBase())) {
    return SolverReturnStatus.UNSOLVABLE;
  verify(getLambdaArgumentTypeSignatures(actualLambdaTypeSignature).equals(toTypeSignatures(lambdaArgumentTypes.get())));
Type actualReturnType = ((FunctionType) actualLambdaType).getReturnType();
ImmutableList.Builder<TypeConstraintSolver> constraintsBuilder = ImmutableList.builder();
for (TypeConstraintSolver constraint : constraintsBuilder.build()) {
  statusMerger.add(constraint.update(bindings));
  if (statusMerger.getCurrent() == SolverReturnStatus.UNSOLVABLE) {

代码示例来源:origin: prestodb/presto

@Override
public ColumnStatistics buildColumnStatistics()
{
  Optional<StringStatistics> stringStatistics = buildStringStatistics();
  stringStatistics.ifPresent(s -> verify(nonNullValueCount > 0));
  return new ColumnStatistics(
      nonNullValueCount,
      stringStatistics.map(s -> STRING_VALUE_BYTES_OVERHEAD + sum / nonNullValueCount).orElse(0L),
      null,
      null,
      null,
      stringStatistics.orElse(null),
      null,
      null,
      null,
      null);
}

代码示例来源:origin: prestodb/presto

@Nullable
public static Envelope deserializeEnvelope(Slice shape)
{
  requireNonNull(shape, "shape is null");
  BasicSliceInput input = shape.getInput();
  verify(input.available() > 0);
  int length = input.available() - 1;
  GeometrySerializationType type = GeometrySerializationType.getForCode(input.readByte());
  return getEnvelope(input, type, length);
}

代码示例来源:origin: prestodb/presto

ChildAggregatedMemoryContext(AggregatedMemoryContext parentMemoryContext)
{
  verify(parentMemoryContext instanceof AbstractAggregatedMemoryContext);
  this.parentMemoryContext = (AbstractAggregatedMemoryContext) requireNonNull(parentMemoryContext, "parentMemoryContext is null");
}

代码示例来源:origin: prestodb/presto

.limit(y)
      .collect(toImmutableList());
  return codePointsToSliceUtf8(codePointsTruncated);
codePoints.addAll(nCopies(toIntExact(y) - codePoints.size(), Character.MAX_CODE_POINT));
verify(codePoints.get(codePoints.size() - 1) != ' '); // no trailing spaces to trim

相关文章

微信公众号

最新文章

更多