@Override
 public byte[] serializeWalletExtension() {
   lock.lock();
   try {
     ClientState.StoredClientPaymentChannels.Builder builder =
         ClientState.StoredClientPaymentChannels.newBuilder();
     for (StoredClientChannel channel : mapChannels.values()) {
       // First a few asserts to make sure things won't break
       checkState(
           channel.valueToMe.signum() >= 0
               && channel.valueToMe.compareTo(NetworkParameters.MAX_MONEY) < 0);
       checkState(
           channel.refundFees.signum() >= 0
               && channel.refundFees.compareTo(NetworkParameters.MAX_MONEY) < 0);
       checkNotNull(channel.myKey.getPrivKeyBytes());
       checkState(channel.refund.getConfidence().getSource() == TransactionConfidence.Source.SELF);
       final ClientState.StoredClientPaymentChannel.Builder value =
           ClientState.StoredClientPaymentChannel.newBuilder()
               .setId(ByteString.copyFrom(channel.id.getBytes()))
               .setContractTransaction(ByteString.copyFrom(channel.contract.bitcoinSerialize()))
               .setRefundTransaction(ByteString.copyFrom(channel.refund.bitcoinSerialize()))
               .setMyKey(ByteString.copyFrom(channel.myKey.getPrivKeyBytes()))
               .setValueToMe(channel.valueToMe.longValue())
               .setRefundFees(channel.refundFees.longValue());
       if (channel.close != null)
         value.setCloseTransactionHash(ByteString.copyFrom(channel.close.getHash().getBytes()));
       builder.addChannels(value);
     }
     return builder.build().toByteArray();
   } finally {
     lock.unlock();
   }
 }
  private static void writeBeliefSet(
      MarshallerWriteContext context,
      BeliefSet beliefSet,
      org.drools.core.marshalling.impl.ProtobufMessages.EqualityKey.Builder _key)
      throws IOException {

    ProtobufMessages.BeliefSet.Builder _beliefSet = ProtobufMessages.BeliefSet.newBuilder();
    _beliefSet.setHandleId(beliefSet.getFactHandle().getId());

    ObjectMarshallingStrategyStore objectMarshallingStrategyStore =
        context.objectMarshallingStrategyStore;

    // for ( LinkedListEntry node = (LinkedListEntry) beliefSet.getFirst(); node != null; node =
    // (LinkedListEntry) node.getNext() ) {
    FastIterator it = beliefSet.iterator();
    for (LinkedListEntry node = (LinkedListEntry) beliefSet.getFirst();
        node != null;
        node = (LinkedListEntry) it.next(node)) {
      LogicalDependency belief = (LogicalDependency) node.getObject();
      ProtobufMessages.LogicalDependency.Builder _logicalDependency =
          ProtobufMessages.LogicalDependency.newBuilder();
      // _belief.setActivation( value )

      LogicalDependency dependency = (LogicalDependency) node.getObject();
      org.drools.core.spi.Activation activation = dependency.getJustifier();
      ProtobufMessages.Activation _activation =
          ProtobufMessages.Activation.newBuilder()
              .setPackageName(activation.getRule().getPackage())
              .setRuleName(activation.getRule().getName())
              .setTuple(PersisterHelper.createTuple(activation.getTuple()))
              .build();
      _logicalDependency.setActivation(_activation);

      if (belief.getObject() != null) {
        ObjectMarshallingStrategy strategy =
            objectMarshallingStrategyStore.getStrategyObject(belief.getObject());

        Integer index = context.getStrategyIndex(strategy);
        _logicalDependency.setObjectStrategyIndex(index.intValue());
        _logicalDependency.setObject(
            ByteString.copyFrom(
                strategy.marshal(
                    context.strategyContext.get(strategy), context, belief.getObject())));
      }

      if (belief.getValue() != null) {
        ObjectMarshallingStrategy strategy =
            objectMarshallingStrategyStore.getStrategyObject(belief.getValue());

        Integer index = context.getStrategyIndex(strategy);
        _logicalDependency.setValueStrategyIndex(index.intValue());
        _logicalDependency.setValue(
            ByteString.copyFrom(
                strategy.marshal(
                    context.strategyContext.get(strategy), context, belief.getValue())));
      }
      _beliefSet.addLogicalDependency(_logicalDependency.build());
    }
    _key.setBeliefSet(_beliefSet);
  }
 public byte[] serialize() {
   return IdentityKeyPairStructure.newBuilder()
       .setPublicKey(ByteString.copyFrom(publicKey.serialize()))
       .setPrivateKey(ByteString.copyFrom(privateKey.serialize()))
       .build()
       .toByteArray();
 }
 @Override
 public byte[] createProtobufOutput() {
   Scanner.Builder builder = Scanner.newBuilder();
   if (!Bytes.equals(startRow, HConstants.EMPTY_START_ROW)) {
     builder.setStartRow(ByteString.copyFrom(startRow));
   }
   if (!Bytes.equals(endRow, HConstants.EMPTY_START_ROW)) {
     builder.setEndRow(ByteString.copyFrom(endRow));
   }
   for (byte[] column : columns) {
     builder.addColumns(ByteString.copyFrom(column));
   }
   builder.setBatch(batch);
   if (startTime != 0) {
     builder.setStartTime(startTime);
   }
   if (endTime != 0) {
     builder.setEndTime(endTime);
   }
   builder.setBatch(getBatch());
   builder.setMaxVersions(maxVersions);
   if (filter != null) {
     builder.setFilter(filter);
   }
   return builder.build().toByteArray();
 }
 private ProtocolSignature getRealSignature() throws Exception {
   return ProtocolSignature.newBuilder()
       .setSignerId(ByteString.copyFrom(Certificates.getRealSignerInfo().getSignerId()))
       .setSignatureAlgorithm(SignatureAlgorithm.SHA1_RSA)
       .setSignatureBytes(ByteString.copyFrom(Certificates.REAL_SIGNATURE))
       .build();
 }
  /**
   * Test Increment Mutate conversions.
   *
   * @throws IOException
   */
  @Test
  public void testIncrement() throws IOException {
    Mutate.Builder mutateBuilder = Mutate.newBuilder();
    mutateBuilder.setRow(ByteString.copyFromUtf8("row"));
    mutateBuilder.setMutateType(MutateType.INCREMENT);
    ColumnValue.Builder valueBuilder = ColumnValue.newBuilder();
    valueBuilder.setFamily(ByteString.copyFromUtf8("f1"));
    QualifierValue.Builder qualifierBuilder = QualifierValue.newBuilder();
    qualifierBuilder.setQualifier(ByteString.copyFromUtf8("c1"));
    qualifierBuilder.setValue(ByteString.copyFrom(Bytes.toBytes(11L)));
    valueBuilder.addQualifierValue(qualifierBuilder.build());
    qualifierBuilder.setQualifier(ByteString.copyFromUtf8("c2"));
    qualifierBuilder.setValue(ByteString.copyFrom(Bytes.toBytes(22L)));
    valueBuilder.addQualifierValue(qualifierBuilder.build());
    mutateBuilder.addColumnValue(valueBuilder.build());

    Mutate proto = mutateBuilder.build();
    // default fields
    assertEquals(true, proto.getWriteToWAL());

    // set the default value for equal comparison
    mutateBuilder = Mutate.newBuilder(proto);
    mutateBuilder.setWriteToWAL(true);

    Increment increment = ProtobufUtil.toIncrement(proto);
    assertEquals(mutateBuilder.build(), ProtobufUtil.toMutate(increment));
  }
  /**
   * Sign the provided payment request.
   *
   * @param paymentRequest Payment request to sign, in its builder form.
   * @param certificateChain Certificate chain to send with the payment request, ordered from client
   *     certificate to root certificate. The root certificate itself may be omitted.
   * @param privateKey The key to sign with. Must match the public key from the first certificate of
   *     the certificate chain.
   */
  public static void signPaymentRequest(
      Protos.PaymentRequest.Builder paymentRequest,
      X509Certificate[] certificateChain,
      PrivateKey privateKey) {
    try {
      final Protos.X509Certificates.Builder certificates = Protos.X509Certificates.newBuilder();
      for (final Certificate certificate : certificateChain)
        certificates.addCertificate(ByteString.copyFrom(certificate.getEncoded()));

      paymentRequest.setPkiType("x509+sha256");
      paymentRequest.setPkiData(certificates.build().toByteString());
      paymentRequest.setSignature(ByteString.EMPTY);
      final Protos.PaymentRequest paymentRequestToSign = paymentRequest.build();

      final String algorithm;
      if ("RSA".equalsIgnoreCase(privateKey.getAlgorithm())) algorithm = "SHA256withRSA";
      else throw new IllegalStateException(privateKey.getAlgorithm());

      final Signature signature = Signature.getInstance(algorithm);
      signature.initSign(privateKey);
      signature.update(paymentRequestToSign.toByteArray());

      paymentRequest.setSignature(ByteString.copyFrom(signature.sign()));
    } catch (final GeneralSecurityException x) {
      // Should never happen so don't make users have to think about it.
      throw new RuntimeException(x);
    }
  }
 /**
  * Constructs a builder for a StoreBucketPropsOperation.
  *
  * @param namespace The namespace in Riak.
  */
 public Builder(Namespace namespace) {
   if (namespace == null) {
     throw new IllegalArgumentException("Namespace cannot be null");
   }
   reqBuilder.setBucket(ByteString.copyFrom(namespace.getBucketName().unsafeGetValue()));
   reqBuilder.setType(ByteString.copyFrom(namespace.getBucketType().unsafeGetValue()));
   this.namespace = namespace;
 }
 public static HdfsProtos.BlockTokenIdentifierProto toProto(Token<?> blockToken) {
   return HdfsProtos.BlockTokenIdentifierProto.newBuilder()
       .setIdentifier(ByteString.copyFrom(blockToken.getIdentifier()))
       .setPassword(ByteString.copyFrom(blockToken.getPassword()))
       .setKind(blockToken.getKind().toString())
       .setService(blockToken.getService().toString())
       .build();
 }
Beispiel #10
0
 private JournalEntry newCompletePartitionEntry(long fileId, PartitionInfo info) {
   CompletePartitionEntry completePartition =
       CompletePartitionEntry.newBuilder()
           .setStoreId(fileId)
           .setBlockId(info.blockId)
           .setKeyStartBytes(ByteString.copyFrom(info.keyStart))
           .setKeyLimitBytes(ByteString.copyFrom(info.keyLimit))
           .build();
   return JournalEntry.newBuilder().setCompletePartition(completePartition).build();
 }
  @Override
  protected RiakMessage createChannelMessage() {
    RiakPB.RpbGetBucketReq.Builder builder = RiakPB.RpbGetBucketReq.newBuilder();

    if (bucketType != null) {
      builder.setType(ByteString.copyFrom(bucketType.unsafeGetValue()));
    }
    builder.setBucket(ByteString.copyFrom(bucketName.unsafeGetValue()));
    RiakPB.RpbGetBucketReq req = builder.build();
    return new RiakMessage(RiakMessageCodes.MSG_GetBucketReq, req.toByteArray());
  }
  @Override
  public Builder adapt(Scan scan, ReadHooks readHooks) {
    throwIfUnsupportedScan(scan);
    // For gets, startRow == stopRow.  There's no need to create a new ByteString for stopRow
    RowFilter filter = buildFilter(scan, readHooks);

    return ReadRowsRequest.newBuilder()
        .setFilter(filter)
        .setRowRange(
            RowRange.newBuilder()
                .setStartKey(ByteString.copyFrom(scan.getStartRow()))
                .setEndKey(ByteString.copyFrom(scan.getStopRow())));
  }
  @Override
  public void run(ClientResponseImpl parameter) {
    if (debug.get())
      LOG.debug(
          String.format(
              "Got ClientResponse callback for txn #%d! Sending back to %s",
              parameter.getTransactionId(), HStoreThreadManager.formatSiteName(this.destSiteId)));
    FastSerializer fs = new FastSerializer();
    try {
      parameter.writeExternal(fs);
    } catch (IOException ex) {
      throw new RuntimeException(ex);
    }
    ByteString bs = ByteString.copyFrom(fs.getBuffer());
    TransactionRedirectResponse response =
        TransactionRedirectResponse.newBuilder()
            .setSenderSite(this.sourceSiteId)
            .setOutput(bs)
            .build();
    this.orig_callback.run(response);
    if (debug.get())
      LOG.debug(
          String.format(
              "Sent back ClientResponse for txn #%d to %s [bytes=%d]",
              parameter.getTransactionId(), HStoreThreadManager.formatSiteName(this.destSiteId)));

    // IMPORTANT: Since we're the only one that knows that we're finished (and actually even
    // cares), we need to be polite and clean-up after ourselves...
    try {
      this.finish();
      hstore_site.getObjectPools().CALLBACKS_TXN_REDIRECT_RESPONSE.returnObject(this);
    } catch (Exception ex) {
      throw new RuntimeException("Funky failure", ex);
    }
  }
 /*
  * (non-Javadoc)
  *
  * @see com.basho.riak.client.raw.RawClient#setClientId()
  */
 public void setClientId(byte[] clientId) throws IOException {
   if (clientId == null || clientId.length != 4) {
     throw new IllegalArgumentException(
         "clientId must be 4 bytes. generateAndSetClientId() can do this for you");
   }
   client.setClientID(ByteString.copyFrom(clientId));
 }
  private static List<ReadRowsResponse> createResponses() {
    List<ReadRowsResponse> responses = new ArrayList<>(1);
    for (int i = 0; i < 1; i++) {
      String rowKey = String.format("rowKey-%s", i);
      byte[] value = RandomStringUtils.randomAlphanumeric(10000).getBytes();
      Preconditions.checkArgument(
          !Strings.isNullOrEmpty("Family1"), "Family name may not be null or empty");

      Family.Builder familyBuilder = Family.newBuilder().setName("Family1");

      Column.Builder columnBuilder = Column.newBuilder();
      columnBuilder.setQualifier(ByteString.copyFromUtf8("Qaulifier"));

      if (value != null) {
        Cell.Builder cellBuilder = Cell.newBuilder();
        cellBuilder.setTimestampMicros(0L);
        cellBuilder.setValue(ByteString.copyFrom(value));
        columnBuilder.addCells(cellBuilder);
      }
      familyBuilder.addColumns(columnBuilder);
      Chunk contentChunk = Chunk.newBuilder().setRowContents(familyBuilder).build();
      Chunk rowCompleteChunk = Chunk.newBuilder().setCommitRow(true).build();

      ReadRowsResponse response =
          ReadRowsResponse.newBuilder()
              .addChunks(contentChunk)
              .addChunks(rowCompleteChunk)
              .setRowKey(ByteString.copyFromUtf8(rowKey))
              .build();

      responses.add(response);
    }
    return responses;
  }
  /**
   * Perform a GET operation on the Riak database
   *
   * @param msg The received message containing all parameters
   * @return The generated reply message of the operation on the database
   * @throws IllegalArgumentException if no key is specified
   */
  private byte[] processGet(Request.RequestMessage msg) throws IllegalArgumentException {
    if (!msg.getKey().isEmpty()) {
      byte[] reply;

      System.out.println("Executing a GET command to the Riak cluster for key: " + msg.getKey());

      byte[] value = riakConnection.get(msg.getKey());
      String string = new String(value);
      System.out.println(string);

      // If the object was not found, return a "NOTFOUND" response. Else, return an "OK" + value
      // response
      if (value == null) {
        reply = Request.RequestMessage.newBuilder().setCommand("NOTFOUND").build().toByteArray();
      } else {
        ByteString valueBuf = ByteString.copyFrom(value);
        reply =
            Request.RequestMessage.newBuilder()
                .setCommand("OK")
                .setDatasource("Riak")
                .setValue(valueBuf)
                .build()
                .toByteArray();
      }

      return reply;
    } else {
      throw new IllegalArgumentException();
    }
  }
  @Override
  public void catchUp(List<BID> inventory, int limit, boolean headers, final TrunkListener listener)
      throws BCSAPIException {
    log.trace("catchUp");
    ConnectorMessage m;
    try (ConnectorSession session = connection.createSession()) {
      ConnectorProducer transactionRequestProducer =
          session.createProducer(session.createQueue("catchUpRequest"));

      m = session.createMessage();
      BCSAPIMessage.CatchUpRequest.Builder builder = BCSAPIMessage.CatchUpRequest.newBuilder();
      builder.setLimit(limit);
      builder.setHeaders(true);
      for (BID hash : inventory) {
        builder.addInventory(ByteString.copyFrom(hash.unsafeGetArray()));
      }
      m.setPayload(builder.build().toByteArray());
      byte[] response = synchronousRequest(session, transactionRequestProducer, m);
      if (response != null) {
        BCSAPIMessage.TrunkUpdate blockMessage = BCSAPIMessage.TrunkUpdate.parseFrom(response);
        List<APIBlock> blockList = new ArrayList<>();
        for (BCSAPIMessage.BLK b : blockMessage.getAddedList()) {
          blockList.add(APIBlock.fromProtobuf(b));
        }
        listener.trunkUpdate(blockList);
      }
    } catch (ConnectorException | HyperLedgerException | InvalidProtocolBufferException e) {
      throw new BCSAPIException(e);
    }
  }
  public void testPushingLotsOfData() throws IOException {
    RiakClient riak = new RiakClient("127.0.0.1", RiakConnection.DEFAULT_RIAK_PB_PORT);

    long before = System.currentTimeMillis();

    byte[] val = new byte[419];
    ByteString value = ByteString.copyFrom(val);

    for (int i = 0; i < 100; i++) {

      long before2 = System.currentTimeMillis();

      String cpr = "" + (1000000000 + i);
      ByteString cpr_key = ByteString.copyFromUtf8(cpr);

      for (int rid = 0; rid < 1000; rid++) {

        ByteString rid_key = ByteString.copyFromUtf8("" + (200000 + i));

        RiakObject ro = new RiakObject(cpr_key, rid_key, value);
        riak.store(ro);
      }

      long after2 = System.currentTimeMillis();

      System.out.println("" + i + " x 1000 INSERTS: " + (after2 - before2) + "ms");
    }

    long after = System.currentTimeMillis();

    System.out.println("TOTAL TIME: " + (1.0 * (after - before) / 1000.0) + "s");
  }
  @Override
  public List<ByteString> getNextRows(int fetchRowNum) throws IOException {
    List<ByteString> rows = new ArrayList<ByteString>();
    int startRow = currentRow;
    int endRow = startRow + fetchRowNum;

    if (physicalExec == null) {
      return rows;
    }

    while (currentRow < endRow) {
      Tuple currentTuple = physicalExec.next();

      if (currentTuple == null) {
        physicalExec.close();
        physicalExec = null;
        break;
      }

      currentRow++;
      rows.add(ByteString.copyFrom(encoder.toBytes(currentTuple)));

      if (currentRow >= maxRow) {
        physicalExec.close();
        physicalExec = null;
        break;
      }
    }

    return rows;
  }
 private AppInfo.Builder buildAppInfo(Tuple tuple) {
   AppInfo.Builder aiBuilder = AppInfo.newBuilder();
   aiBuilder.setPkgName(tuple.pkgName);
   aiBuilder.setAppName(tuple.appName);
   if (tuple.icon != null) aiBuilder.setIcon(ByteString.copyFrom(tuple.icon));
   return aiBuilder;
 }
  @Override
  public APIBlockIdList getBlockIds(BID blockId, int count) throws BCSAPIException {
    try (ConnectorSession session = connection.createSession()) {
      log.trace("get " + count + " block ids from " + blockId);

      ConnectorProducer blockIdsRequestProducer =
          session.createProducer(session.createQueue("blockIdsRequest"));

      ConnectorMessage m = session.createMessage();
      BCSAPIMessage.BLKIDSREQ.Builder builder = BCSAPIMessage.BLKIDSREQ.newBuilder();
      if (blockId != null) {
        builder.setBlockHash(ByteString.copyFrom(blockId.unsafeGetArray()));
      }
      if (count <= 0) count = 20;
      builder.setCount(count);
      m.setPayload(builder.build().toByteArray());
      byte[] response = synchronousRequest(session, blockIdsRequestProducer, m);
      if (response != null) {
        BCSAPIMessage.BLKIDS message = BCSAPIMessage.BLKIDS.parseFrom(response);
        List<ByteString> blockIdsList = message.getBlockIdsList();
        List<BID> blockIds =
            blockIdsList.stream().map(bs -> new BID(bs.toByteArray())).collect(Collectors.toList());
        return new APIBlockIdList(
            blockIds,
            message.getHeight(),
            message.hasPreviousBlockId()
                ? new BID(message.getPreviousBlockId().toByteArray())
                : null);
      }
    } catch (ConnectorException | InvalidProtocolBufferException e) {
      throw new BCSAPIException(e);
    }

    return null;
  }
  @Override
  public List<APITransaction> getInputTransactions(TID txId) throws BCSAPIException {
    log.trace("get input transactions " + txId);
    ConnectorMessage m;
    try (ConnectorSession session = connection.createSession()) {
      ConnectorProducer transactionRequestProducer =
          session.createProducer(session.createQueue("inputTransactionsRequest"));

      m = session.createMessage();
      BCSAPIMessage.Hash.Builder builder = BCSAPIMessage.Hash.newBuilder();
      builder.addHash(ByteString.copyFrom(txId.unsafeGetArray()));
      m.setPayload(builder.build().toByteArray());
      byte[] response = synchronousRequest(session, transactionRequestProducer, m);
      if (response != null) {
        List<BCSAPIMessage.OPTIONAL_TX> txsList =
            BCSAPIMessage.TXS.parseFrom(response).getTxsList();
        List<APITransaction> txs = new ArrayList<>(txsList.size());
        for (BCSAPIMessage.OPTIONAL_TX tx : txsList) {
          if (tx.getIsNull()) {
            txs.add(null);
          } else {
            txs.add(APITransaction.fromProtobuf(tx.getTransaction()));
          }
        }
        return txs;
      }
    } catch (ConnectorException | HyperLedgerException | InvalidProtocolBufferException e) {
      throw new BCSAPIException(e);
    }

    return null;
  }
 /** 添加消息,为了保证添加顺序,这里不得不加锁 */
 @Override
 public void addMessage(
     final MessageStore store, final long msgId, final PutCommand putCmd, JournalLocation location)
     throws IOException {
   if (location == null) {
     // 非重放,添加put日志
     final AppendMessageCommand appendCmd =
         AppendMessageCommand.newBuilder()
             .setMessageId(msgId)
             .setPutCommand(ByteString.copyFrom(putCmd.encode().array()))
             .build();
     final TxCommand txCommand =
         TxCommand.newBuilder()
             .setCmdType(TxCommandType.APPEND_MSG)
             .setCmdContent(appendCmd.toByteString())
             .build();
     final Tx tx = this.getInflyTx(putCmd.getTransactionId());
     if (tx != null) {
       location = this.journalStore.write(txCommand, null, tx.location, false);
     } else {
       location = this.journalStore.write(txCommand, null, null, false);
     }
   }
   final Tx tx = this.getTx(putCmd.getTransactionId(), location);
   tx.add(store, msgId, putCmd);
 }
 private void serializeFileDiffList(INodeFile file, OutputStream out) throws IOException {
   FileWithSnapshotFeature sf = file.getFileWithSnapshotFeature();
   if (sf != null) {
     List<FileDiff> diffList = sf.getDiffs().asList();
     SnapshotDiffSection.DiffEntry entry =
         SnapshotDiffSection.DiffEntry.newBuilder()
             .setInodeId(file.getId())
             .setType(Type.FILEDIFF)
             .setNumOfDiff(diffList.size())
             .build();
     entry.writeDelimitedTo(out);
     for (int i = diffList.size() - 1; i >= 0; i--) {
       FileDiff diff = diffList.get(i);
       SnapshotDiffSection.FileDiff.Builder fb =
           SnapshotDiffSection.FileDiff.newBuilder()
               .setSnapshotId(diff.getSnapshotId())
               .setFileSize(diff.getFileSize());
       INodeFileAttributes copy = diff.snapshotINode;
       if (copy != null) {
         fb.setName(ByteString.copyFrom(copy.getLocalNameBytes()))
             .setSnapshotCopy(buildINodeFile(copy, parent.getSaverContext()));
       }
       fb.build().writeDelimitedTo(out);
     }
   }
 }
  /**
   * Convert a ClutserStatus to a protobuf ClusterStatus
   *
   * @return the protobuf ClusterStatus
   */
  public ClusterStatusProtos.ClusterStatus convert() {
    ClusterStatusProtos.ClusterStatus.Builder builder =
        ClusterStatusProtos.ClusterStatus.newBuilder();
    builder.setHbaseVersion(HBaseVersionFileContent.newBuilder().setVersion(getHBaseVersion()));

    for (Map.Entry<ServerName, ServerLoad> entry : liveServers.entrySet()) {
      LiveServerInfo.Builder lsi =
          LiveServerInfo.newBuilder().setServer(ProtobufUtil.toServerName(entry.getKey()));
      lsi.setServerLoad(entry.getValue().obtainServerLoadPB());
      builder.addLiveServers(lsi.build());
    }
    for (ServerName deadServer : getDeadServerNames()) {
      builder.addDeadServers(ProtobufUtil.toServerName(deadServer));
    }
    for (Map.Entry<String, RegionState> rit : getRegionsInTransition().entrySet()) {
      ClusterStatusProtos.RegionState rs = rit.getValue().convert();
      RegionSpecifier.Builder spec =
          RegionSpecifier.newBuilder().setType(RegionSpecifierType.REGION_NAME);
      spec.setValue(ByteString.copyFrom(Bytes.toBytes(rit.getKey())));

      RegionInTransition pbRIT =
          RegionInTransition.newBuilder().setSpec(spec.build()).setRegionState(rs).build();
      builder.addRegionsInTransition(pbRIT);
    }
    builder.setClusterId(new ClusterId(getClusterId()).convert());
    for (String coprocessor : getMasterCoprocessors()) {
      builder.addMasterCoprocessors(HBaseProtos.Coprocessor.newBuilder().setName(coprocessor));
    }
    builder.setMaster(ProtobufUtil.toServerName(getMaster()));
    for (ServerName backup : getBackupMasters()) {
      builder.addBackupMasters(ProtobufUtil.toServerName(backup));
    }
    builder.setBalancerOn(balancerOn);
    return builder.build();
  }
Beispiel #26
0
  private void imageRun() {
    while (running) {
      try {
        if (imageMsgReady) {
          imageMsgReady = !(sendImage());
          Thread.sleep(IMAGE_DELAY);
        } else {
          byte[] serialImage = new byte[(channels * sizeX * sizeY)];

          Random generator = new Random();
          int index = 0;
          for (int i = 0; i < channels; i++) {
            for (int j = 0; j < sizeY; j++) {
              for (int k = 0; k < sizeX; k++) {
                serialImage[index++] =
                    (byte) generator.nextInt(128); // Generate random number 0-127 MAX_SIZE for byte
              }
            }
          }
          imageMsgReady =
              setImage(
                  System.currentTimeMillis(),
                  channels,
                  sizeX,
                  sizeY,
                  com.google.protobuf.ByteString.copyFrom(serialImage)); // setup status message
        }
      } catch (InterruptedException e) {
        e.printStackTrace();
      } catch (IOException e) {
        e.printStackTrace();
      }
    } // end while loop
  } // End tracksRun method
Beispiel #27
0
  public void testReadHugeBlob() throws Exception {
    // Allocate and initialize a 1MB blob.
    byte[] blob = new byte[1 << 20];
    for (int i = 0; i < blob.length; i++) {
      blob[i] = (byte) i;
    }

    // Make a message containing it.
    TestAllTypes.Builder builder = TestAllTypes.newBuilder();
    TestUtil.setAllFields(builder);
    builder.setOptionalBytes(ByteString.copyFrom(blob));
    TestAllTypes message = builder.build();

    // Serialize and parse it.  Make sure to parse from an InputStream, not
    // directly from a ByteString, so that CodedInputStream uses buffered
    // reading.
    TestAllTypes message2 = TestAllTypes.parseFrom(message.toByteString().newInput());

    assertEquals(message.getOptionalBytes(), message2.getOptionalBytes());

    // Make sure all the other fields were parsed correctly.
    TestAllTypes message3 =
        TestAllTypes.newBuilder(message2)
            .setOptionalBytes(TestUtil.getAllSet().getOptionalBytes())
            .build();
    TestUtil.assertAllFieldsSet(message3);
  }
  private static void setProtoKuraMetricValue(
      final KuraPayloadProto.KuraPayload.KuraMetric.Builder metric, final Object o)
      throws Exception {

    if (o instanceof String) {
      metric.setType(KuraPayloadProto.KuraPayload.KuraMetric.ValueType.STRING);
      metric.setStringValue((String) o);
    } else if (o instanceof Double) {
      metric.setType(KuraPayloadProto.KuraPayload.KuraMetric.ValueType.DOUBLE);
      metric.setDoubleValue((Double) o);
    } else if (o instanceof Integer) {
      metric.setType(KuraPayloadProto.KuraPayload.KuraMetric.ValueType.INT32);
      metric.setIntValue((Integer) o);
    } else if (o instanceof Float) {
      metric.setType(KuraPayloadProto.KuraPayload.KuraMetric.ValueType.FLOAT);
      metric.setFloatValue((Float) o);
    } else if (o instanceof Long) {
      metric.setType(KuraPayloadProto.KuraPayload.KuraMetric.ValueType.INT64);
      metric.setLongValue((Long) o);
    } else if (o instanceof Boolean) {
      metric.setType(KuraPayloadProto.KuraPayload.KuraMetric.ValueType.BOOL);
      metric.setBoolValue((Boolean) o);
    } else if (o instanceof byte[]) {
      metric.setType(KuraPayloadProto.KuraPayload.KuraMetric.ValueType.BYTES);
      metric.setBytesValue(ByteString.copyFrom((byte[]) o));
    } else if (o == null) {
      throw new Exception("null value");
    } else {
      throw new Exception(o.getClass().getName());
    }
  }
Beispiel #29
0
  public void testRpc(int packetSize) throws Exception {
    TestRpcRequest.Builder builder = TestRpcRequest.newBuilder();
    byte[] bytes = new byte[packetSize];
    builder.setData(ByteString.copyFrom(bytes));

    stub.testRpc(null, builder.build());
  }
  @Test
  public void testSimplePayment() throws Exception {
    // Create a PaymentRequest and make sure the correct values are parsed by the PaymentSession.
    MockPaymentSession paymentSession = new MockPaymentSession(newSimplePaymentRequest());
    assertEquals(paymentRequestMemo, paymentSession.getMemo());
    assertEquals(nanoCoins, paymentSession.getValue());
    assertEquals(simplePaymentUrl, paymentSession.getPaymentUrl());
    assertTrue(new Date(time * 1000L).equals(paymentSession.getDate()));
    assertTrue(paymentSession.getSendRequest().tx.equals(tx));
    assertFalse(paymentSession.isExpired());

    // Send the payment and verify that the correct information is sent.
    // Add a dummy input to tx so it is considered valid.
    tx.addInput(new TransactionInput(params, tx, outputToMe.getScriptBytes()));
    ArrayList<Transaction> txns = new ArrayList<Transaction>();
    txns.add(tx);
    Address refundAddr = new Address(params, serverKey.getPubKeyHash());
    paymentSession.sendPayment(txns, refundAddr, paymentMemo);
    assertEquals(1, paymentSession.getPaymentLog().size());
    assertEquals(simplePaymentUrl, paymentSession.getPaymentLog().get(0).getUrl().toString());
    Protos.Payment payment = paymentSession.getPaymentLog().get(0).getPayment();
    assertEquals(paymentMemo, payment.getMemo());
    assertEquals(merchantData, payment.getMerchantData());
    assertEquals(1, payment.getRefundToCount());
    assertEquals(nanoCoins.longValue(), payment.getRefundTo(0).getAmount());
    TransactionOutput refundOutput = new TransactionOutput(params, null, nanoCoins, refundAddr);
    ByteString refundScript = ByteString.copyFrom(refundOutput.getScriptBytes());
    assertTrue(refundScript.equals(payment.getRefundTo(0).getScript()));
  }