com.google.common.base.Verify#verify ( )源码实例Demo

下面列出了com.google.common.base.Verify#verify ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: google-java-format   文件: TypeNameClassifier.java
/** Classifies an identifier's case format. */
static JavaCaseFormat from(String name) {
  Verify.verify(!name.isEmpty());
  boolean firstUppercase = false;
  boolean hasUppercase = false;
  boolean hasLowercase = false;
  boolean first = true;
  for (int i = 0; i < name.length(); i++) {
    char c = name.charAt(i);
    if (!Character.isAlphabetic(c)) {
      continue;
    }
    if (first) {
      firstUppercase = Character.isUpperCase(c);
      first = false;
    }
    hasUppercase |= Character.isUpperCase(c);
    hasLowercase |= Character.isLowerCase(c);
  }
  if (firstUppercase) {
    return hasLowercase ? UPPER_CAMEL : UPPERCASE;
  } else {
    return hasUppercase ? LOWER_CAMEL : LOWERCASE;
  }
}
 
源代码2 项目: yangtools   文件: OffsetMapCache.java
static <K, V> V[] adjustedArray(final Map<K, Integer> offsets, final List<K> keys, final V[] array) {
    Verify.verify(offsets.size() == keys.size(), "Offsets %s do not match keys %s", offsets, keys);

    // This relies on the fact that offsets has an ascending iterator
    final Iterator<K> oi = offsets.keySet().iterator();
    final Iterator<K> ki = keys.iterator();

    while (oi.hasNext()) {
        final K o = oi.next();
        final K k = ki.next();
        if (!k.equals(o)) {
            return adjustArray(offsets, keys, array);
        }
    }

    return array;
}
 
YangDataEffectiveStatementImpl(final StmtContext<String, YangDataStatement, ?> ctx) {
    super(ctx);

    QName maybeQNameArgumentInit;
    try {
        maybeQNameArgumentInit = StmtContextUtils.parseIdentifier(ctx, argument());
    } catch (IllegalArgumentException e) {
        maybeQNameArgumentInit = getNodeType();
    }
    this.maybeQNameArgument = maybeQNameArgumentInit;

    path = ctx.coerceParentContext().getSchemaPath().get().createChild(maybeQNameArgument);
    container = findFirstEffectiveSubstatement(ContainerEffectiveStatement.class).get();

    // TODO: this is strong binding of two API contracts. Unfortunately ContainerEffectiveStatement design is
    //       incomplete.
    Verify.verify(container instanceof ContainerSchemaNode);
}
 
@Override
protected TreeNode applyMerge(final ModifiedNode modification, final TreeNode currentMeta, final Version version) {
    /*
     * The node which we are merging exists. We now need to expand any child operations implied by the value. Once
     * we do that, ModifiedNode children will look like this node were a TOUCH and we will let applyTouch() do the
     * heavy lifting of applying the children recursively (either through here or through applyWrite().
     */
    final NormalizedNode<?, ?> value = modification.getWrittenValue();

    Verify.verify(value instanceof NormalizedNodeContainer, "Attempted to merge non-container %s", value);
    for (final NormalizedNode<?, ?> c : ((NormalizedNodeContainer<?, ?, ?>) value).getValue()) {
        final PathArgument id = c.getIdentifier();
        modification.modifyChild(id, resolveChildOperation(id), version);
    }
    return applyTouch(modification, currentMeta, version);
}
 
源代码5 项目: curiostack   文件: FluentEqualityConfig.java
@Override
public final void validate(
    Descriptor rootDescriptor, FieldDescriptorValidator fieldDescriptorValidator) {
  // FluentEqualityConfig should never be validated other than as a root entity.
  Verify.verify(fieldDescriptorValidator == FieldDescriptorValidator.ALLOW_ALL);

  ignoreFieldAbsenceScope()
      .validate(rootDescriptor, FieldDescriptorValidator.IS_FIELD_WITH_ABSENCE);
  ignoreRepeatedFieldOrderScope()
      .validate(rootDescriptor, FieldDescriptorValidator.IS_FIELD_WITH_ORDER);
  ignoreExtraRepeatedFieldElementsScope()
      .validate(rootDescriptor, FieldDescriptorValidator.IS_FIELD_WITH_EXTRA_ELEMENTS);
  doubleCorrespondenceMap().validate(rootDescriptor, FieldDescriptorValidator.IS_DOUBLE_FIELD);
  floatCorrespondenceMap().validate(rootDescriptor, FieldDescriptorValidator.IS_FLOAT_FIELD);
  compareFieldsScope().validate(rootDescriptor, FieldDescriptorValidator.ALLOW_ALL);
}
 
源代码6 项目: yangtools   文件: JaxenXPath.java
@Override
public Optional<? extends XPathResult<?>> evaluate(final XPathDocument document,
        final YangInstanceIdentifier path) throws XPathExpressionException {
    checkArgument(document instanceof JaxenDocument);

    final NormalizedNodeContextSupport contextSupport = NormalizedNodeContextSupport.create(
        (JaxenDocument)document, converter);

    final Object result = evaluate(contextSupport.createContext(path));
    if (result instanceof String) {
        return Optional.of((XPathStringResult) () -> (String) result);
    } else if (result instanceof Number) {
        return Optional.of((XPathNumberResult) () -> (Number) result);
    } else if (result instanceof Boolean) {
        return Optional.of((XPathBooleanResult) () -> (Boolean) result);
    } else if (result == null) {
        return Optional.empty();
    }

    Verify.verify(result instanceof List, "Unhandled result %s", result);
    @SuppressWarnings("unchecked")
    final List<NormalizedNodeContext> resultList = (List<NormalizedNodeContext>) result;
    return Optional.of((XPathNodesetResult) () -> {
        // XXX: Will this really work, or do we need to perform deep transformation?
        return Lists.transform(resultList,
            context -> new SimpleImmutableEntry<>(context.getPath(), context.getNode()));
    });
}
 
源代码7 项目: grpc-java   文件: ErrorHandlingClient.java
void asyncCall() {
  GreeterStub stub = GreeterGrpc.newStub(channel);
  HelloRequest request = HelloRequest.newBuilder().setName("Homer").build();
  final CountDownLatch latch = new CountDownLatch(1);
  StreamObserver<HelloReply> responseObserver = new StreamObserver<HelloReply>() {

    @Override
    public void onNext(HelloReply value) {
      // Won't be called.
    }

    @Override
    public void onError(Throwable t) {
      Status status = Status.fromThrowable(t);
      Verify.verify(status.getCode() == Status.Code.INTERNAL);
      Verify.verify(status.getDescription().contains("Overbite"));
      // Cause is not transmitted over the wire..
      latch.countDown();
    }

    @Override
    public void onCompleted() {
      // Won't be called, since the server in this example always fails.
    }
  };
  stub.sayHello(request, responseObserver);

  if (!Uninterruptibles.awaitUninterruptibly(latch, 1, TimeUnit.SECONDS)) {
    throw new RuntimeException("timeout!");
  }
}
 
源代码8 项目: mail-importer   文件: ThunderbirdLocalMessage.java
@Override
public String getFromHeader() {
  String[] fromHeader = message.getHeader("From");
  Verify.verify(fromHeader.length == 1,
      "Expected 1 From header, got: %s", Arrays.toString(fromHeader));
  return fromHeader[0];
}
 
源代码9 项目: yangtools   文件: EffectiveSchemaContext.java
static EffectiveSchemaContext create(final List<DeclaredStatement<?>> rootDeclaredStatements,
        final List<EffectiveStatement<?, ?>> rootEffectiveStatements) {
    final Set<Module> modules = new HashSet<>();
    for (EffectiveStatement<?, ?> stmt : rootEffectiveStatements) {
        if (stmt.getDeclared() instanceof ModuleStatement) {
            Verify.verify(stmt instanceof Module);
            modules.add((Module) stmt);
        }
    }

    return new EffectiveSchemaContext(modules, rootDeclaredStatements, rootEffectiveStatements);
}
 
源代码10 项目: DataflowTemplates   文件: ImportTransform.java
private void validateLocalFiles(ProcessContext c, String table, TableManifest manifest) {
  for (TableManifest.File file : manifest.getFilesList()) {
    Path filePath = Paths.get(importDirectory.get(), file.getName());
    String actualHash = FileChecksum.getLocalFileChecksum(filePath);
    String expectedHash = file.getMd5();
    Verify.verify(
        expectedHash.equals(actualHash),
        "Inconsistent file: %s expected hash %s actual hash %s",
        filePath,
        expectedHash,
        actualHash);
    c.output(KV.of(table, filePath.toString()));
  }
}
 
public SimpleColumnCombination combineWith(SimpleColumnCombination other, Map<SimpleColumnCombination, SimpleColumnCombination> columnCombinations) {
    Verify.verify(table == other.table, "only merge inside a table");
    SimpleColumnCombination combinedCombination = new SimpleColumnCombination(table, columns, other.lastColumn());
    if (columnCombinations != null) {
        SimpleColumnCombination existingCombination = columnCombinations.get(combinedCombination);
        if (existingCombination == null) {
            columnCombinations.put(combinedCombination, combinedCombination);
        } else {
            combinedCombination = existingCombination;
        }
    }
    return combinedCombination;
}
 
源代码12 项目: bazel   文件: WorkspaceFactoryHelper.java
private static void overwriteRule(Package.Builder pkg, Rule rule)
    throws Package.NameConflictException {
  Preconditions.checkArgument(rule.getOutputFiles().isEmpty());
  Target old = pkg.getTarget(rule.getName());
  if (old != null) {
    if (old instanceof Rule) {
      Verify.verify(((Rule) old).getOutputFiles().isEmpty());
    }

    pkg.removeTarget(rule);
  }

  pkg.addRule(rule);
}
 
源代码13 项目: bgpcep   文件: ApplicationPeer.java
/**
 * Routes come from application RIB that is identified by (configurable) name.
 * Each route is pushed into AdjRibsInWriter with it's whole context. In this
 * method, it doesn't matter if the routes are removed or added, this will
 * be determined in LocRib.
 */
@Override
public synchronized void onDataTreeChanged(final Collection<DataTreeCandidate> changes) {
    if (getDomChain() == null) {
        LOG.trace("Skipping data changed called to Application Peer. Change : {}", changes);
        return;
    }
    final DOMDataTreeWriteTransaction tx = getDomChain().newWriteOnlyTransaction();
    LOG.debug("Received data change to ApplicationRib {}", changes);
    for (final DataTreeCandidate tc : changes) {
        LOG.debug("Modification Type {}", tc.getRootNode().getModificationType());
        final YangInstanceIdentifier path = tc.getRootPath();
        final PathArgument lastArg = path.getLastPathArgument();
        Verify.verify(lastArg instanceof NodeIdentifierWithPredicates,
                "Unexpected type %s in path %s", lastArg.getClass(), path);
        final NodeIdentifierWithPredicates tableKey = (NodeIdentifierWithPredicates) lastArg;
        if (!this.supportedTables.contains(tableKey)) {
            LOG.trace("Skipping received data change for non supported family {}.", tableKey);
            continue;
        }
        for (final DataTreeCandidateNode child : tc.getRootNode().getChildNodes()) {
            final PathArgument childIdentifier = child.getIdentifier();
            final YangInstanceIdentifier tableId = this.adjRibsInId.node(tableKey).node(childIdentifier);
            switch (child.getModificationType()) {
                case DELETE:
                case DISAPPEARED:
                    LOG.trace("App peer -> AdjRibsIn path delete: {}", childIdentifier);
                    tx.delete(LogicalDatastoreType.OPERATIONAL, tableId);
                    break;
                case UNMODIFIED:
                    // No-op
                    break;
                case SUBTREE_MODIFIED:
                    if (ROUTES_NID.equals(childIdentifier)) {
                        processRoutesTable(child, tableId, tx, tableId);
                    } else {
                        processWrite(child, tableId, tx);
                    }
                    break;
                case WRITE:
                case APPEARED:
                    processWrite(child, tableId, tx);
                    break;
                default:
                    break;
            }
        }
    }
    tx.commit().addCallback(new FutureCallback<CommitInfo>() {
        @Override
        public void onSuccess(final CommitInfo result) {
            LOG.trace("Successful commit");
        }

        @Override
        public void onFailure(final Throwable trw) {
            LOG.error("Failed commit", trw);
        }
    }, MoreExecutors.directExecutor());
}
 
源代码14 项目: grpc-nebula-java   文件: DnsNameResolver.java
/**
 * Determines if a given Service Config choice applies, and if so, returns it.
 *
 * @see <a href="https://github.com/grpc/proposal/blob/master/A2-service-configs-in-dns.md">
 *   Service Config in DNS</a>
 * @param choice The service config choice.
 * @return The service config object or {@code null} if this choice does not apply.
 */
@Nullable
@SuppressWarnings("BetaApi") // Verify isn't all that beta
@VisibleForTesting
static Map<String, Object> maybeChooseServiceConfig(
    Map<String, Object> choice, Random random, String hostname) {
  for (Entry<String, ?> entry : choice.entrySet()) {
    Verify.verify(SERVICE_CONFIG_CHOICE_KEYS.contains(entry.getKey()), "Bad key: %s", entry);
  }

  List<String> clientLanguages = getClientLanguagesFromChoice(choice);
  if (clientLanguages != null && !clientLanguages.isEmpty()) {
    boolean javaPresent = false;
    for (String lang : clientLanguages) {
      if ("java".equalsIgnoreCase(lang)) {
        javaPresent = true;
        break;
      }
    }
    if (!javaPresent) {
      return null;
    }
  }
  Double percentage = getPercentageFromChoice(choice);
  if (percentage != null) {
    int pct = percentage.intValue();
    Verify.verify(pct >= 0 && pct <= 100, "Bad percentage: %s", percentage);
    if (random.nextInt(100) >= pct) {
      return null;
    }
  }
  List<String> clientHostnames = getHostnamesFromChoice(choice);
  if (clientHostnames != null && !clientHostnames.isEmpty()) {
    boolean hostnamePresent = false;
    for (String clientHostname : clientHostnames) {
      if (clientHostname.equals(hostname)) {
        hostnamePresent = true;
        break;
      }
    }
    if (!hostnamePresent) {
      return null;
    }
  }
  return ServiceConfigUtil.getObject(choice, SERVICE_CONFIG_CHOICE_SERVICE_CONFIG_KEY);
}
 
源代码15 项目: presto   文件: TestScalarFunctionAdapter.java
private static List<Object> toCallArgumentValues(InvocationConvention callingConvention, BitSet nullArguments, Target target)
{
    List<Object> callArguments = new ArrayList<>();
    callArguments.add(target);
    for (int i = 0; i < callingConvention.getArgumentConventions().size(); i++) {
        Type argumentType = ARGUMENT_TYPES.get(i);
        boolean nullArgument = nullArguments.get(i);

        Object testValue;
        if (nullArgument) {
            testValue = null;
        }
        else {
            testValue = getTestValue(argumentType);
        }

        InvocationArgumentConvention argumentConvention = callingConvention.getArgumentConvention(i);
        switch (argumentConvention) {
            case NEVER_NULL:
                Verify.verify(testValue != null, "null can not be passed to a never null argument");
                callArguments.add(testValue);
                break;
            case BOXED_NULLABLE:
                callArguments.add(testValue);
                break;
            case NULL_FLAG:
                callArguments.add(testValue == null ? Defaults.defaultValue(argumentType.getJavaType()) : testValue);
                callArguments.add(testValue == null);
                break;
            case BLOCK_POSITION:
                BlockBuilder blockBuilder = argumentType.createBlockBuilder(null, 3);
                blockBuilder.appendNull();
                writeNativeValue(argumentType, blockBuilder, testValue);
                blockBuilder.appendNull();

                callArguments.add(blockBuilder.build());
                callArguments.add(1);
                break;
            default:
                throw new IllegalArgumentException("Unsupported argument convention: " + argumentConvention);
        }
    }
    return callArguments;
}
 
源代码16 项目: yangtools   文件: NormalizedNodeNavigator.java
private static NormalizedNodeContext cast(final Object context) {
    Verify.verify(context instanceof NormalizedNodeContext, "Unhandled context node %s", context);
    return (NormalizedNodeContext) context;
}
 
源代码17 项目: bazel   文件: AggregatingAttributeMapper.java
/**
 * Binds the given config key set to the specified path. There should be no previous binding
 * for this key set.
 */
public void bind(Set<Label> allKeys, Label chosenKey) {
  Preconditions.checkState(allKeys.contains(chosenKey));
  Verify.verify(bindings.put(allKeys, chosenKey) == null);
}
 
源代码18 项目: fdb-record-layer   文件: RecordQueryScanPlan.java
/**
 * Rewrite the planner graph for better visualization of a query scan plan.
 * @param childGraphs planner graphs of children expression that already have been computed
 * @return the rewritten planner graph that models scanned storage as a separate node that is connected to the
 *         actual scan plan node.
 */
@SuppressWarnings("UnstableApiUsage")
@Nonnull
@Override
public PlannerGraph rewritePlannerGraph(@Nonnull List<? extends PlannerGraph> childGraphs) {
    Verify.verify(childGraphs.isEmpty());

    @Nullable final TupleRange tupleRange = comparisons.toTupleRangeWithoutContext();

    final ImmutableList.Builder<String> detailsBuilder = ImmutableList.builder();
    final ImmutableMap.Builder<String, Attribute> additionalAttributes = ImmutableMap.builder();

    if (tupleRange != null) {
        detailsBuilder.add("range: " + tupleRange.getLowEndpoint().toString(false) + "{{low}}, {{high}}" + tupleRange.getHighEndpoint().toString(true));
        additionalAttributes.put("low", Attribute.gml(tupleRange.getLow() == null ? "-∞" : tupleRange.getLow().toString()));
        additionalAttributes.put("high", Attribute.gml(tupleRange.getHigh() == null ? "∞" : tupleRange.getHigh().toString()));
    } else {
        detailsBuilder.add("comparisons: {{comparisons}}");
        additionalAttributes.put("comparisons", Attribute.gml(comparisons.toString()));
    }

    if (reverse) {
        detailsBuilder.add("direction: {{direction}}");
        additionalAttributes.put("direction", Attribute.gml("reversed"));
    }

    final PlannerGraph.DataNodeWithInfo dataNodeWithInfo;
    if (getRecordTypes() == null) {
        dataNodeWithInfo =
                new PlannerGraph.DataNodeWithInfo(NodeInfo.BASE_DATA,
                        ImmutableList.of("ALL"));
    } else {
        dataNodeWithInfo = new PlannerGraph.DataNodeWithInfo(NodeInfo.BASE_DATA,
                ImmutableList.of("record types: {{types}}"),
                ImmutableMap.of("types", Attribute.gml(getRecordTypes().stream().map(Attribute::gml).collect(ImmutableList.toImmutableList()))));
    }

    return PlannerGraph.fromNodeAndChildGraphs(
            new PlannerGraph.OperatorNodeWithInfo(this,
                    NodeInfo.SCAN_OPERATOR,
                    detailsBuilder.build(),
                    additionalAttributes.build()),
            ImmutableList.of(PlannerGraph.fromNodeAndChildGraphs(
                    dataNodeWithInfo,
                    childGraphs)));
}
 
源代码19 项目: copybara   文件: TransformWork.java
@StarlarkMethod(
    name = "create_symlink",
    doc = "Create a symlink",
    parameters = {
        @Param(name = "link", type = CheckoutPath.class, doc = "The link path"),
        @Param(name = "target", type = CheckoutPath.class, doc = "The target path"),
    })
public void createSymlink(CheckoutPath link, CheckoutPath target) throws EvalException {
  try {
    Path linkFullPath = asCheckoutPath(link);
    // Verify target is inside checkout dir
    asCheckoutPath(target);

    if (Files.exists(linkFullPath)) {
      throw Starlark.errorf(
          "'%s' already exist%s",
          link.getPath(),
          Files.isDirectory(linkFullPath)
              ? " and is a directory"
              : Files.isSymbolicLink(linkFullPath)
                  ? " and is a symlink"
                  : Files.isRegularFile(linkFullPath)
                      ? " and is a regular file"
                      // Shouldn't happen:
                      : " and we don't know what kind of file is");
    }

    Path relativized = link.getPath().getParent() == null
        ? target.getPath()
        : link.getPath().getParent().relativize(target.getPath());
    Files.createDirectories(linkFullPath.getParent());

    // Shouldn't happen.
    Verify.verify(
        linkFullPath.getParent().resolve(relativized).normalize().startsWith(checkoutDir),
        "%s path escapes the checkout dir", relativized);
    Files.createSymbolicLink(linkFullPath, relativized);
  } catch (IOException e) {
    String msg = "Cannot create symlink: " + e.getMessage();
    logger.atSevere().withCause(e).log(msg);
    throw Starlark.errorf("%s", msg);
  }
}
 
源代码20 项目: nomulus   文件: CreateOrUpdatePremiumListCommand.java
private static String stripJsonPrefix(String json) {
  Verify.verify(json.startsWith(JSON_SAFETY_PREFIX));
  return json.substring(JSON_SAFETY_PREFIX.length());
}