当前位置: 首页>>代码示例>>Java>>正文


Java Preconditions.checkState方法代码示例

本文整理汇总了Java中com.google.common.base.Preconditions.checkState方法的典型用法代码示例。如果您正苦于以下问题:Java Preconditions.checkState方法的具体用法?Java Preconditions.checkState怎么用?Java Preconditions.checkState使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在com.google.common.base.Preconditions的用法示例。


在下文中一共展示了Preconditions.checkState方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: createTransaction

import com.google.common.base.Preconditions; //导入方法依赖的package包/类
@Override
protected BasicTransactionSemantics createTransaction() {
  if (!open) {
    String msg = "Channel closed " + channelNameDescriptor;
    if (startupError != null) {
      msg += ". Due to " + startupError.getClass().getName() + ": " +
          startupError.getMessage();
      throw new IllegalStateException(msg, startupError);
    }
    throw new IllegalStateException(msg);
  }

  FileBackedTransaction trans = transactions.get();
  if (trans != null && !trans.isClosed()) {
    Preconditions.checkState(false,
        "Thread has transaction which is still open: " +
            trans.getStateAsString() + channelNameDescriptor);
  }
  trans = new FileBackedTransaction(log, TransactionIDOracle.next(),
      transactionCapacity, keepAlive, queueRemaining, getName(),
      fsyncPerTransaction, channelCounter);
  transactions.set(trans);
  return trans;
}
 
开发者ID:moueimei,项目名称:flume-release-1.7.0,代码行数:25,代码来源:FileChannel.java

示例2: getGrpcEngine

import com.google.common.base.Preconditions; //导入方法依赖的package包/类
private GrpcEngine getGrpcEngine(String registryAddress, int registryPort) {
    String key = registryAddress + ":" + registryPort;
    LOCK.lock();
    try {
        GrpcEngine engine = ENGINES.get(key);
        if (engine != null) {
            return engine;
        }
        Preconditions.checkNotNull(registryAddress, "registryAddress  is not Null", registryAddress);
        Preconditions.checkState(registryPort != 0, "RegistryPort can not be zero", registryPort);
        GrpcURL registryUrl = new GrpcURL(Constants.REGISTRY_PROTOCOL, registryAddress, registryPort);
        engine = new GrpcEngine(registryUrl);
        ENGINES.put(key, engine);
        return engine;
    } finally {
        LOCK.unlock();
    }
}
 
开发者ID:venus-boot,项目名称:saluki,代码行数:19,代码来源:RpcBaseConfig.java

示例3: close

import com.google.common.base.Preconditions; //导入方法依赖的package包/类
/**
 * Close the replica.
 *
 * Must be called after there are no more references to the replica in the
 * cache or elsewhere.
 */
void close() {
  String suffix = "";
  
  Preconditions.checkState(refCount == 0,
      "tried to close replica with refCount %d: %s", refCount, this);
  refCount = -1;
  Preconditions.checkState(purged,
      "tried to close unpurged replica %s", this);
  if (hasMmap()) {
    munmap();
    if (LOG.isTraceEnabled()) {
      suffix += "  munmapped.";
    }
  }
  IOUtils.cleanup(LOG, dataStream, metaStream);
  if (slot != null) {
    cache.scheduleSlotReleaser(slot);
    if (LOG.isTraceEnabled()) {
      suffix += "  scheduling " + slot + " for later release.";
    }
  }
  if (LOG.isTraceEnabled()) {
    LOG.trace("closed " + this + suffix);
  }
}
 
开发者ID:naver,项目名称:hadoop,代码行数:32,代码来源:ShortCircuitReplica.java

示例4: readyTransaction

import com.google.common.base.Preconditions; //导入方法依赖的package包/类
void readyTransaction(@Nonnull final PingPongTransaction tx) {
    // First mark the transaction as not locked.
    final boolean lockedMatch = LOCKED_UPDATER.compareAndSet(this, tx, null);
    Preconditions.checkState(lockedMatch, "Attempted to submit transaction %s while we have %s", tx, lockedTx);
    LOG.debug("Transaction {} unlocked", tx);

    /*
     * The transaction is ready. It will then be picked up by either next allocation,
     * or a background transaction completion callback.
     */
    final boolean success = READY_UPDATER.compareAndSet(this, null, tx);
    Preconditions.checkState(success, "Transaction %s collided on ready state", tx, readyTx);
    LOG.debug("Transaction {} readied", tx);

    /*
     * We do not see a transaction being in-flight, so we need to take care of dispatching
     * the transaction to the backend. We are in the ready case, we cannot short-cut
     * the checking of readyTx, as an in-flight transaction may have completed between us
     * setting the field above and us checking.
     */
    if (inflightTx == null) {
        synchronized (this) {
            processIfReady();
        }
    }
}
 
开发者ID:hashsdn,项目名称:hashsdn-controller,代码行数:27,代码来源:PingPongTransactionChain.java

示例5: selectInputStreams

import com.google.common.base.Preconditions; //导入方法依赖的package包/类
/**
 * Select a list of input streams.
 * 
 * @param fromTxId first transaction in the selected streams
 * @param toAtLeastTxId the selected streams must contain this transaction
 * @param recovery recovery context
 * @param inProgressOk set to true if in-progress streams are OK
 */
public Collection<EditLogInputStream> selectInputStreams(
    long fromTxId, long toAtLeastTxId, MetaRecoveryContext recovery,
    boolean inProgressOk) throws IOException {

  List<EditLogInputStream> streams = new ArrayList<EditLogInputStream>();
  synchronized(journalSetLock) {
    Preconditions.checkState(journalSet.isOpen(), "Cannot call " +
        "selectInputStreams() on closed FSEditLog");
    selectInputStreams(streams, fromTxId, inProgressOk);
  }

  try {
    checkForGaps(streams, fromTxId, toAtLeastTxId, inProgressOk);
  } catch (IOException e) {
    if (recovery != null) {
      // If recovery mode is enabled, continue loading even if we know we
      // can't load up to toAtLeastTxId.
      LOG.error(e);
    } else {
      closeAllStreams(streams);
      throw e;
    }
  }
  return streams;
}
 
开发者ID:naver,项目名称:hadoop,代码行数:34,代码来源:FSEditLog.java

示例6: sumbitVote

import com.google.common.base.Preconditions; //导入方法依赖的package包/类
@Override
public List<String> sumbitVote(String identificationCredentials, List<Integer> selections) throws VoteCastingException {
    Preconditions.checkState(publicParameters != null,
            "The public parameters need to have been retrieved first");
    Preconditions.checkState(electionSet != null,
            "The electionSet needs to have been retrieved first");

    Stopwatch stopwatch = Stopwatch.createStarted();
    List<EncryptionPublicKey> publicKeyParts = bulletinBoardService.getPublicKeyParts();
    EncryptionPublicKey systemPublicKey = keyEstablishmentAlgorithms.getPublicKey(publicKeyParts);

    BallotQueryAndRand ballotQueryAndRand = computeBallot(identificationCredentials, selections, systemPublicKey);
    randomizations = ballotQueryAndRand.getBold_r();
    stopwatch.stop();
    stats.voteEncodingTime = stopwatch.elapsed(TimeUnit.MILLISECONDS);

    List<ObliviousTransferResponse> obliviousTransferResponses = sentBallotAndQuery(ballotQueryAndRand.getAlpha());

    stopwatch.reset().start();
    pointMatrix = computePointMatrix(selections, obliviousTransferResponses);
    List<String> returnCodes = voteCastingClientAlgorithms.getReturnCodes(selections, pointMatrix);
    stopwatch.stop();
    stats.verificationCodesComputationTime = stopwatch.elapsed(TimeUnit.MILLISECONDS);

    return returnCodes;
}
 
开发者ID:republique-et-canton-de-geneve,项目名称:chvote-protocol-poc,代码行数:27,代码来源:DefaultVotingClient.java

示例7: crossValidate

import com.google.common.base.Preconditions; //导入方法依赖的package包/类
private void crossValidate() {
    if (folds <= 0) {
        return;
    }
    Preconditions.checkState(trainPath != null,
            "Specified %s-fold cross validation, but did not provide training instances. "
                    + "Please include the train input option as well, e.g. \"-train path/to/train.txt\"", folds);
    Preconditions.checkState(trainPer < 1 && trainPer > 0,
            "Percentage of training data must be between 0 and 1 (got %f). "
                    + "Please set ratio of percentage of training instances per fold (e.g. \"-per 0.8\")", trainPer);
    List<NlpFocus<DepNode, DepTree>> trainInstances = getParseTrees(trainPath, parsed(trainPath)
            ? corpusType.corpusReader(getKeyPath(trainPath)) : corpusType.corpusParser(getKeyPath(trainPath), getParser()));
    log.info("Performing {}-fold cross validation on {} instances in training corpus at {}", folds,
            trainInstances.size(), trainPath);
    CrossValidation<NlpFocus<DepNode, DepTree>> cv = new CrossValidation<>(seed, i -> i.feature(FeatureType.Gold));
    List<Evaluation> evaluations = cv.crossValidate(newClassifier(), cv.createFolds(trainInstances, folds, trainPer));
    int index = 0;
    for (Evaluation evaluation : evaluations) {
        log.info("Fold {} results:\n{}", index++, evaluation);
    }
    log.info("Overall {}-fold cross validation results on corpus at {}:\n{}", folds, trainPath, new Evaluation(evaluations));
}
 
开发者ID:clearwsd,项目名称:clearwsd,代码行数:23,代码来源:WordSenseCLI.java

示例8: getEscapeMapping

import com.google.common.base.Preconditions; //导入方法依赖的package包/类
@VisibleForTesting
  @Deprecated
  public static Map<String, String> getEscapeMapping(String in,
      Map<String, String> headers, boolean needRounding,
      int unit, int roundDown) {
    Map<String, String> mapping = new HashMap<String, String>();
    Matcher matcher = tagPattern.matcher(in);
    while (matcher.find()) {
      String replacement = "";
      // Group 2 is the %{...} pattern
      if (matcher.group(2) != null) {

        replacement = headers.get(matcher.group(2));

        if (replacement == null) {
          replacement = "";
//          LOG.warn("Tag " + matcher.group(2) + " not found");
        }
        mapping.put(matcher.group(2), replacement);
      } else {
        // The %x pattern.
        // Since we know the match is a single character, we can
        // switch on that rather than the string.
        Preconditions.checkState(matcher.group(1) != null
            && matcher.group(1).length() == 1,
            "Expected to match single character tag in string " + in);
        char c = matcher.group(1).charAt(0);
        replacement = replaceShorthand(c, headers,
            needRounding, unit, roundDown);
        mapping.put(expandShorthand(c), replacement);
      }
    }
    return mapping;

  }
 
开发者ID:moueimei,项目名称:flume-release-1.7.0,代码行数:36,代码来源:BucketPath.java

示例9: read

import com.google.common.base.Preconditions; //导入方法依赖的package包/类
@Override
public CheckedFuture<Optional<NormalizedNode<?, ?>>, ReadFailedException> read(final YangInstanceIdentifier path) {
    Preconditions.checkState(type != TransactionType.WRITE_ONLY,
            "Reads from write-only transactions are not allowed");

    LOG.debug("Tx {} read {}", getIdentifier(), path);

    if (YangInstanceIdentifier.EMPTY.equals(path)) {
        return readAllData();
    } else {
        return singleShardRead(shardNameFromIdentifier(path), path);
    }
}
 
开发者ID:hashsdn,项目名称:hashsdn-controller,代码行数:14,代码来源:TransactionProxy.java

示例10: read

import com.google.common.base.Preconditions; //导入方法依赖的package包/类
public static RpcReply read(XDR xdr) {
  int xid = xdr.readInt();
  final Type messageType = Type.fromValue(xdr.readInt());
  Preconditions.checkState(messageType == RpcMessage.Type.RPC_REPLY);
  
  ReplyState stat = ReplyState.fromValue(xdr.readInt());
  switch (stat) {
  case MSG_ACCEPTED:
    return RpcAcceptedReply.read(xid, stat, xdr);
  case MSG_DENIED:
    return RpcDeniedReply.read(xid, stat, xdr);
  }
  return null;
}
 
开发者ID:naver,项目名称:hadoop,代码行数:15,代码来源:RpcReply.java

示例11: ensureParentZNode

import com.google.common.base.Preconditions; //导入方法依赖的package包/类
/**
 * Utility function to ensure that the configured base znode exists.
 * This recursively creates the znode as well as all of its parents.
 */
public synchronized void ensureParentZNode()
    throws IOException, InterruptedException {
  Preconditions.checkState(!wantToBeInElection,
      "ensureParentZNode() may not be called while in the election");

  String pathParts[] = znodeWorkingDir.split("/");
  Preconditions.checkArgument(pathParts.length >= 1 &&
      pathParts[0].isEmpty(),
      "Invalid path: %s", znodeWorkingDir);
  
  StringBuilder sb = new StringBuilder();
  for (int i = 1; i < pathParts.length; i++) {
    sb.append("/").append(pathParts[i]);
    String prefixPath = sb.toString();
    LOG.debug("Ensuring existence of " + prefixPath);
    try {
      createWithRetries(prefixPath, new byte[]{}, zkAcl, CreateMode.PERSISTENT);
    } catch (KeeperException e) {
      if (isNodeExists(e.code())) {
        // This is OK - just ensuring existence.
        continue;
      } else {
        throw new IOException("Couldn't create " + prefixPath, e);
      }
    }
  }
  
  LOG.info("Successfully created " + znodeWorkingDir + " in ZK.");
}
 
开发者ID:naver,项目名称:hadoop,代码行数:34,代码来源:ActiveStandbyElector.java

示例12: write

import com.google.common.base.Preconditions; //导入方法依赖的package包/类
@Override
public void write(int b) throws IOException {
  Preconditions.checkState(!closed, "Attempted to write on a closed stream");
  byte b0 = (byte) b;
  if (b0 == '\n') {
    lines.add(stream.toString(StandardCharsets.UTF_8.name()));
    stream.reset();
  } else {
    stream.write(b);
  }
}
 
开发者ID:bazelbuild,项目名称:bazel-integration-testing,代码行数:12,代码来源:LineListOutputStream.java

示例13: unpackLanguageOrRegion

import com.google.common.base.Preconditions; //导入方法依赖的package包/类
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);
}
 
开发者ID:xyxyLiu,项目名称:AndResM,代码行数:15,代码来源:ResourceConfiguration.java

示例14: of

import com.google.common.base.Preconditions; //导入方法依赖的package包/类
/**
 * Creates an instance ensuring {@link SqlOperator operators} from {@link SqlStdOperatorTable} are prepopulated.
 */
public static SqlOperatorSerializer of(final Kryo kryo, final Class<?> type) {
  final SqlOperatorSerializer serializer = new SqlOperatorSerializer(kryo, type);
  Preconditions.checkState(!OperatorPopulator.FORWARD.isEmpty(), "operator table cannot be empty");
  return serializer;
}
 
开发者ID:dremio,项目名称:dremio-oss,代码行数:9,代码来源:SqlOperatorSerializer.java

示例15: sendCodeSheet

import com.google.common.base.Preconditions; //导入方法依赖的package包/类
public void sendCodeSheet(VotingCard votingCard) {
    Preconditions.checkState(this.votingCard == null,
            String.format("The code sheet may not be updated once set (at voter %d)", voterIndex));
    Preconditions.checkArgument(votingCard.getI() == voterIndex, "Voter received the wrong code list.é");
    this.votingCard = votingCard;
}
 
开发者ID:republique-et-canton-de-geneve,项目名称:chvote-protocol-poc,代码行数:7,代码来源:VoterSimulator.java


注:本文中的com.google.common.base.Preconditions.checkState方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。