示例#1
0
  private void handleDataTuple(HeronTuples.HeronDataTuple dataTuple, TopologyAPI.StreamId stream) {
    long startTime = System.nanoTime();

    List<Object> values = new ArrayList<>();
    for (ByteString b : dataTuple.getValuesList()) {
      values.add(serializer.deserialize(b.toByteArray()));
    }

    // Decode the tuple
    TupleImpl t =
        new TupleImpl(
            helper.getTopologyContext(),
            stream,
            dataTuple.getKey(),
            dataTuple.getRootsList(),
            values);

    long deserializedTime = System.nanoTime();

    // Delegate to the use defined bolt
    bolt.execute(t);

    long executeLatency = System.nanoTime() - deserializedTime;

    // Invoke user-defined execute task hook
    helper.getTopologyContext().invokeHookBoltExecute(t, executeLatency);

    boltMetrics.deserializeDataTuple(
        stream.getId(), stream.getComponentName(), deserializedTime - startTime);

    // Update metrics
    boltMetrics.executeTuple(stream.getId(), stream.getComponentName(), executeLatency);
  }
  /**
   * Test basic Get conversions.
   *
   * @throws IOException
   */
  @Test
  public void testGet() throws IOException {
    ClientProtos.Get.Builder getBuilder = ClientProtos.Get.newBuilder();
    getBuilder.setRow(ByteString.copyFromUtf8("row"));
    Column.Builder columnBuilder = Column.newBuilder();
    columnBuilder.setFamily(ByteString.copyFromUtf8("f1"));
    columnBuilder.addQualifier(ByteString.copyFromUtf8("c1"));
    columnBuilder.addQualifier(ByteString.copyFromUtf8("c2"));
    getBuilder.addColumn(columnBuilder.build());

    columnBuilder.clear();
    columnBuilder.setFamily(ByteString.copyFromUtf8("f2"));
    getBuilder.addColumn(columnBuilder.build());

    ClientProtos.Get proto = getBuilder.build();
    // default fields
    assertEquals(1, proto.getMaxVersions());
    assertEquals(true, proto.getCacheBlocks());

    // set the default value for equal comparison
    getBuilder = ClientProtos.Get.newBuilder(proto);
    getBuilder.setMaxVersions(1);
    getBuilder.setCacheBlocks(true);

    Get get = ProtobufUtil.toGet(proto);
    assertEquals(getBuilder.build(), ProtobufUtil.toGet(get));
  }
 @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();
   }
 }
示例#4
0
 @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();
 }
  @Test
  public void testLastBlockSeenHash() throws Exception {
    // Test the lastBlockSeenHash field works.

    // LastBlockSeenHash should be empty if never set.
    Wallet wallet = new Wallet(params);
    Protos.Wallet walletProto = new WalletProtobufSerializer().walletToProto(wallet);
    ByteString lastSeenBlockHash = walletProto.getLastSeenBlockHash();
    assertTrue(lastSeenBlockHash.isEmpty());

    // Create a block.
    Block block = params.getDefaultSerializer().makeBlock(BlockTest.blockBytes);
    Sha256Hash blockHash = block.getHash();
    wallet.setLastBlockSeenHash(blockHash);
    wallet.setLastBlockSeenHeight(1);

    // Roundtrip the wallet and check it has stored the blockHash.
    Wallet wallet1 = roundTrip(wallet);
    assertEquals(blockHash, wallet1.getLastBlockSeenHash());
    assertEquals(1, wallet1.getLastBlockSeenHeight());

    // Test the Satoshi genesis block (hash of all zeroes) is roundtripped ok.
    Block genesisBlock = MainNetParams.get().getGenesisBlock();
    wallet.setLastBlockSeenHash(genesisBlock.getHash());
    Wallet wallet2 = roundTrip(wallet);
    assertEquals(genesisBlock.getHash(), wallet2.getLastBlockSeenHash());
  }
  /**
   * Test compatability between version 4.1.0 and the current version.
   *
   * <p>Server side throttling does't work when current client connects to old version server.
   */
  @Test(timeout = 60000)
  public void testServerSideThrottleCompat410() throws Exception {
    ByteString topic = ByteString.copyFromUtf8("TestServerSideThrottleCompat410");
    ByteString subid = ByteString.copyFromUtf8("mysub");

    // start bookkeeper
    BookKeeperCluster410 bkc410 = new BookKeeperCluster410(3);
    bkc410.start();

    int port = PortManager.nextFreePort();
    int sslPort = PortManager.nextFreePort();

    // start hub server 410
    Server410 s410 = new Server410(zkUtil.getZooKeeperConnectString(), port, sslPort);
    s410.start();

    ClientCurrent ccur = new ClientCurrent(false, "localhost:" + port + ":" + sslPort);
    ccur.throttleX41(topic, subid, 10);

    ccur.close();

    // stop 410 server
    s410.stop();
    // stop bookkeeper cluster
    bkc410.stop();
  }
  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);
  }
  /**
   * Test compatability between version 4.1.0 and the current version.
   *
   * <p>A current client running message filter would fail on 4.1.0 hub servers.
   */
  @Test(timeout = 60000)
  public void testClientMessageFilterCompat410() throws Exception {
    ByteString topic = ByteString.copyFromUtf8("TestUpdateMessageBoundCompat410");
    ByteString subid = ByteString.copyFromUtf8("mysub");

    // start bookkeeper
    BookKeeperCluster410 bkc410 = new BookKeeperCluster410(3);
    bkc410.start();

    int port = PortManager.nextFreePort();
    int sslPort = PortManager.nextFreePort();

    // start hub server 410
    Server410 s410 = new Server410(zkUtil.getZooKeeperConnectString(), port, sslPort);
    s410.start();

    ClientCurrent ccur = new ClientCurrent("localhost:" + port + ":" + sslPort);
    ccur.subscribe(topic, subid);
    ccur.closeSubscription(topic, subid);

    ccur.publishInts(topic, 0, 100);
    try {
      ccur.receiveNumModM(topic, subid, 0, 50, 2);
      fail("client-side filter could not run on 4.1.0 hub server");
    } catch (Exception e) {
      logger.info("Should fail to run client-side message filter on 4.1.0 hub server.", e);
      ccur.closeSubscription(topic, subid);
    }

    // stop 410 server
    s410.stop();
    // stop bookkeeper cluster
    bkc410.stop();
  }
  @Test
  public void testNullClientMessageFilter() throws Exception {
    ByteString topic = ByteString.copyFromUtf8("TestNullClientMessageFilter");
    ByteString subid = ByteString.copyFromUtf8("mysub");
    subscriber.subscribe(topic, subid, CreateOrAttach.CREATE_OR_ATTACH);
    try {
      subscriber.startDeliveryWithFilter(topic, subid, null, new ModMessageFilter());
      fail("Should fail start delivery with filter using null message handler.");
    } catch (NullPointerException npe) {
    }

    try {
      subscriber.startDeliveryWithFilter(
          topic,
          subid,
          new MessageHandler() {
            public void deliver(
                ByteString topic,
                ByteString subscriberId,
                Message msg,
                Callback<Void> callback,
                Object context) {
              // do nothing
            }
          },
          null);
      fail("Should fail start delivery with filter using null message filter.");
    } catch (NullPointerException npe) {
    }
  }
示例#10
0
  private byte[] writePartialFile(DataOutputStream out) throws IOException {
    MessageQueue.Message m1 =
        MessageQueue.Message.newBuilder()
            .setTime(1)
            .setPayload(ByteString.copyFromUtf8("test 1"))
            .build();

    out.writeInt(m1.getSerializedSize());
    m1.writeTo(out);

    MessageQueue.Message m2 =
        MessageQueue.Message.newBuilder()
            .setTime(2)
            .setPayload(ByteString.copyFromUtf8("test 2"))
            .build();

    out.writeInt(m2.getSerializedSize());
    m2.writeTo(out);

    MessageQueue.Message m3 =
        MessageQueue.Message.newBuilder()
            .setTime(3)
            .setPayload(ByteString.copyFromUtf8("test 3"))
            .build();

    byte[] bytes = m3.toByteArray();

    out.writeInt(bytes.length);
    out.write(bytes, 0, 6);
    out.flush();
    return bytes;
  }
示例#11
0
  /**
   * 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);
    }
  }
 public byte[] serialize() {
   return IdentityKeyPairStructure.newBuilder()
       .setPublicKey(ByteString.copyFrom(publicKey.serialize()))
       .setPrivateKey(ByteString.copyFrom(privateKey.serialize()))
       .build()
       .toByteArray();
 }
  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;
  }
  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");
  }
示例#15
0
 @Override
 public boolean runCmd(String[] args) throws Exception {
   if (args.length < 7) {
     return false;
   }
   String topicPrefix = args[1];
   int startTopic = Integer.parseInt(args[2]);
   int endTopic = Integer.parseInt(args[3]);
   String subPrefix = args[4];
   int startSub = Integer.parseInt(args[5]);
   int endSub = Integer.parseInt(args[6]);
   if (startTopic > endTopic || endSub < startSub) {
     return false;
   }
   for (int i = startTopic; i <= endTopic; i++) {
     ByteString topic = ByteString.copyFromUtf8(topicPrefix + i);
     try {
       for (int j = startSub; j <= endSub; j++) {
         ByteString sub = ByteString.copyFromUtf8(subPrefix + j);
         subscriber.subscribe(topic, sub, CreateOrAttach.CREATE_OR_ATTACH);
         subscriber.unsubscribe(topic, sub);
       }
       System.out.println("RMSUB " + topic.toStringUtf8() + " DONE");
     } catch (Exception e) {
       System.err.println("RMSUB " + topic.toStringUtf8() + " FAILED");
       e.printStackTrace();
     }
   }
   return true;
 }
示例#16
0
 @Override
 public boolean runCmd(String[] args) throws Exception {
   if (args.length < 4) {
     return false;
   }
   long lastConsumedId = 0;
   SubscriptionData subData =
       admin.getSubscription(ByteString.copyFromUtf8(args[1]), ByteString.copyFromUtf8(args[2]));
   if (null == subData) {
     System.err.println(
         "Failed to read subscription for topic: " + args[1] + " subscriber: " + args[2]);
     return true;
   }
   lastConsumedId = subData.getState().getMsgId().getLocalComponent();
   long numMessagesToConsume = Long.parseLong(args[3]);
   long idToConsumed = lastConsumedId + numMessagesToConsume;
   System.out.println(
       "Try to move subscriber("
           + args[2]
           + ") consume ptr of topic("
           + args[1]
           + ") from "
           + lastConsumedId
           + " to "
           + idToConsumed);
   MessageSeqId consumeId = MessageSeqId.newBuilder().setLocalComponent(idToConsumed).build();
   ByteString topic = ByteString.copyFromUtf8(args[1]);
   ByteString subId = ByteString.copyFromUtf8(args[2]);
   try {
     subscriber.consume(topic, subId, consumeId);
   } catch (Exception e) {
     System.err.println("CONSUME FAILED");
   }
   return true;
 }
 @Override
 public HdfsBlocksMetadata getHdfsBlocksMetadata(
     String blockPoolId, long[] blockIds, List<Token<BlockTokenIdentifier>> tokens)
     throws IOException {
   List<TokenProto> tokensProtos = new ArrayList<TokenProto>(tokens.size());
   for (Token<BlockTokenIdentifier> t : tokens) {
     tokensProtos.add(PBHelper.convert(t));
   }
   // Build the request
   GetHdfsBlockLocationsRequestProto request =
       GetHdfsBlockLocationsRequestProto.newBuilder()
           .setBlockPoolId(blockPoolId)
           .addAllBlockIds(Longs.asList(blockIds))
           .addAllTokens(tokensProtos)
           .build();
   // Send the RPC
   GetHdfsBlockLocationsResponseProto response;
   try {
     response = rpcProxy.getHdfsBlockLocations(NULL_CONTROLLER, request);
   } catch (ServiceException e) {
     throw ProtobufHelper.getRemoteException(e);
   }
   // List of volumes in the response
   List<ByteString> volumeIdsByteStrings = response.getVolumeIdsList();
   List<byte[]> volumeIds = new ArrayList<byte[]>(volumeIdsByteStrings.size());
   for (ByteString bs : volumeIdsByteStrings) {
     volumeIds.add(bs.toByteArray());
   }
   // Array of indexes into the list of volumes, one per block
   List<Integer> volumeIndexes = response.getVolumeIndexesList();
   // Parsed HdfsVolumeId values, one per block
   return new HdfsBlocksMetadata(blockPoolId, blockIds, volumeIds, volumeIndexes);
 }
示例#18
0
    @Override
    public boolean runCmd(String[] args) throws Exception {
      if (args.length < 3) {
        return false;
      }
      ByteString topic = ByteString.copyFromUtf8(args[1]);

      StringBuilder sb = new StringBuilder();
      for (int i = 2; i < args.length; i++) {
        sb.append(args[i]);
        if (i != args.length - 1) {
          sb.append(' ');
        }
      }
      ByteString msgBody = ByteString.copyFromUtf8(sb.toString());
      Message msg = Message.newBuilder().setBody(msgBody).build();
      try {
        publisher.publish(topic, msg);
        System.out.println("PUB DONE");
      } catch (Exception e) {
        System.err.println("PUB FAILED");
        e.printStackTrace();
      }
      return true;
    }
示例#19
0
    /**
     * Check equality of the substring of given length of this object starting at zero with another
     * {@code LiteralByteString} substring starting at offset.
     *
     * @param other what to compare a substring in
     * @param offset offset into other
     * @param length number of bytes to compare
     * @return true for equality of substrings, else false.
     */
    @Override
    final boolean equalsRange(ByteString other, int offset, int length) {
      if (length > other.size()) {
        throw new IllegalArgumentException("Length too large: " + length + size());
      }
      if (offset + length > other.size()) {
        throw new IllegalArgumentException(
            "Ran off end of other: " + offset + ", " + length + ", " + other.size());
      }

      if (other instanceof LiteralByteString) {
        LiteralByteString lbsOther = (LiteralByteString) other;
        byte[] thisBytes = bytes;
        byte[] otherBytes = lbsOther.bytes;
        int thisLimit = getOffsetIntoBytes() + length;
        for (int thisIndex = getOffsetIntoBytes(),
                otherIndex = lbsOther.getOffsetIntoBytes() + offset;
            (thisIndex < thisLimit);
            ++thisIndex, ++otherIndex) {
          if (thisBytes[thisIndex] != otherBytes[otherIndex]) {
            return false;
          }
        }
        return true;
      }

      return other.substring(offset, offset + length).equals(substring(0, length));
    }
示例#20
0
  @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()));
  }
示例#21
0
 @Override
 public ProtobufMessageHandler getObjectFromMessage(byte[] message) throws IOException {
   Scanner.Builder builder = Scanner.newBuilder();
   builder.mergeFrom(message);
   if (builder.hasStartRow()) {
     startRow = builder.getStartRow().toByteArray();
   }
   if (builder.hasEndRow()) {
     endRow = builder.getEndRow().toByteArray();
   }
   for (ByteString column : builder.getColumnsList()) {
     addColumn(column.toByteArray());
   }
   if (builder.hasBatch()) {
     batch = builder.getBatch();
   }
   if (builder.hasStartTime()) {
     startTime = builder.getStartTime();
   }
   if (builder.hasEndTime()) {
     endTime = builder.getEndTime();
   }
   if (builder.hasMaxVersions()) {
     maxVersions = builder.getMaxVersions();
   }
   if (builder.hasFilter()) {
     filter = builder.getFilter();
   }
   return this;
 }
    /**
     * Helper method to get the contents of the visitor message, save the image, and save the event
     *
     * @param msg
     */
    private void saveVisitor(StateDeviceProtos.StateDeviceMessage msg) {
      Log.i(TAG, "Logging Event");
      Visitor visitor = new Visitor();
      Long time = System.currentTimeMillis();
      ByteString data = msg.getData();
      String filename = "visitor" + System.currentTimeMillis() + ".jpg";
      visitor.setImagePath(filename);
      File imageDirectory = new File(mContext.getFilesDir() + ConstantManager.IMAGE_DIR);

      // create the image directory if it doesn't exist
      if (!imageDirectory.exists()) {
        Log.i(TAG, "Directory being created? " + imageDirectory.mkdirs());
      }

      // save the image file
      File image = new File(imageDirectory, filename);
      try {
        if (!image.exists()) {
          Log.i(TAG, "File being created? " + image.createNewFile());
        }
        FileOutputStream fos = new FileOutputStream(image, true);
        fos.write(data.toByteArray());
        fos.close();
      } catch (IOException e) {
        e.printStackTrace();
      }

      // Log the visitor
      visitor.setTime(time);
      visitor.setLocation(msg.getName());
      VisitorLog.logVisitor(visitor, mContext);
    }
 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();
 }
 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();
 }
示例#25
0
  /**
   * Concatenate the given {@code ByteString} to this one. Short concatenations, of total size
   * smaller than {@link ByteString#CONCATENATE_BY_COPY_SIZE}, are produced by copying the
   * underlying bytes (as per Rope.java, <a
   * href="http://www.cs.ubc.ca/local/reading/proceedings/spe91-95/spe/vol25/issue12/spe986.pdf">
   * BAP95 </a>. In general, the concatenate involves no copying.
   *
   * @param other string to concatenate
   * @return a new {@code ByteString} instance
   */
  public final ByteString concat(ByteString other) {
    if (Integer.MAX_VALUE - size() < other.size()) {
      throw new IllegalArgumentException(
          "ByteString would be too long: " + size() + "+" + other.size());
    }

    return RopeByteString.concatenate(this, other);
  }
示例#26
0
 /**
  * Parse transactions from payment message.
  *
  * @param params network parameters (needed for transaction deserialization)
  * @param paymentMessage payment message to parse
  * @return list of transactions
  */
 public static List<Transaction> parseTransactionsFromPaymentMessage(
     NetworkParameters params, Protos.Payment paymentMessage) {
   final List<Transaction> transactions =
       new ArrayList<Transaction>(paymentMessage.getTransactionsCount());
   for (final ByteString transaction : paymentMessage.getTransactionsList())
     transactions.add(params.getDefaultSerializer().makeTransaction(transaction.toByteArray()));
   return transactions;
 }
 /**
  * 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;
 }
  /*
   * (non-Javadoc)
   *
   * @see com.basho.riak.client.raw.RawClient#listBuckets()
   */
  public Set<String> listBuckets() throws IOException {
    final Set<String> response = new HashSet<String>();
    final ByteString[] buckets = client.listBuckets();

    for (ByteString b : buckets) {
      response.add(b.toStringUtf8());
    }
    return response;
  }
示例#29
0
  /**
   * Test compatability between version 4.1.0 and the current version.
   *
   * <p>A current server could read subscription data recorded by 4.1.0 server.
   */
  @Test(timeout = 60000)
  public void testSubscriptionDataCompat410() throws Exception {
    ByteString topic = ByteString.copyFromUtf8("TestCompat410");
    ByteString sub410 = ByteString.copyFromUtf8("sub410");
    ByteString subcur = ByteString.copyFromUtf8("subcur");

    // start bookkeeper 410
    BookKeeperCluster410 bkc410 = new BookKeeperCluster410(3);
    bkc410.start();

    int port = PortManager.nextFreePort();
    int sslPort = PortManager.nextFreePort();

    // start 410 server
    Server410 s410 = new Server410(zkUtil.getZooKeeperConnectString(), port, sslPort);
    s410.start();

    Client410 c410 = new Client410("localhost:" + port + ":" + sslPort);
    c410.subscribe(topic, sub410);
    c410.closeSubscription(topic, sub410);
    Thread.sleep(1000); // give server time to run disconnect logic (BOOKKEEPER-513)

    ClientCurrent ccur = new ClientCurrent("localhost:" + port + ":" + sslPort);
    ccur.subscribe(topic, subcur);
    ccur.closeSubscription(topic, subcur);

    // publish messages using old client
    c410.publishInts(topic, 0, 10);
    // stop 410 server
    s410.stop();

    // start 420 server
    Server420 s420 = new Server420(zkUtil.getZooKeeperConnectString(), port, sslPort);
    s420.start();

    c410.subscribe(topic, sub410);
    c410.receiveInts(topic, sub410, 0, 10);

    ccur.subscribe(topic, subcur);
    ccur.receiveInts(topic, subcur, 0, 10);

    // publish messages using current client
    ccur.publishInts(topic, 10, 10);

    c410.receiveInts(topic, sub410, 10, 10);
    ccur.receiveInts(topic, subcur, 10, 10);

    // stop 420 server
    s420.stop();

    c410.close();
    ccur.close();

    // stop bookkeeper cluster
    bkc410.stop();
  }
  @Test
  public void testClientSideMessageFilter() throws Exception {
    ByteString topic = ByteString.copyFromUtf8("TestClientMessageFilter");
    ByteString subid = ByteString.copyFromUtf8("mysub");

    subscriber.subscribe(topic, subid, CreateOrAttach.CREATE_OR_ATTACH);
    subscriber.closeSubscription(topic, subid);
    publishNums(topic, 0, 100, 2);
    receiveNumModM(topic, subid, null, new ModMessageFilter(), 0, 50, 2, true);
  }