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


Java ByteString.copyFrom方法代码示例

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


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

示例1: parseBytes

import com.google.protobuf.ByteString; //导入方法依赖的package包/类
/** Parsers a bytes value out of the input. */
static ByteString parseBytes(JsonParser parser) throws IOException {
  JsonToken json = parser.currentToken();
  byte[] result = null;
  try {
    // Use Guava to decode base64, which can handle more variants than Jackson.
    result =
        BaseEncoding.base64()
            .decode(
                CharBuffer.wrap(
                    parser.getTextCharacters(), parser.getTextOffset(), parser.getTextLength()));
  } catch (IllegalArgumentException e) {
    // Fall through
  }
  if (result == null) {
    throw new InvalidProtocolBufferException("Not a bytes value: " + json);
  }
  return ByteString.copyFrom(result);
}
 
开发者ID:curioswitch,项目名称:curiostack,代码行数:20,代码来源:ParseSupport.java

示例2: convert

import com.google.protobuf.ByteString; //导入方法依赖的package包/类
public static SnapshotDiffReportEntryProto convert(DiffReportEntry entry) {
  if (entry == null) {
    return null;
  }
  ByteString sourcePath = ByteString
      .copyFrom(entry.getSourcePath() == null ? DFSUtil.EMPTY_BYTES : entry
          .getSourcePath());
  String modification = entry.getType().getLabel();
  SnapshotDiffReportEntryProto.Builder builder = SnapshotDiffReportEntryProto
      .newBuilder().setFullpath(sourcePath)
      .setModificationLabel(modification);
  if (entry.getType() == DiffType.RENAME) {
    ByteString targetPath = ByteString
        .copyFrom(entry.getTargetPath() == null ? DFSUtil.EMPTY_BYTES : entry
            .getTargetPath());
    builder.setTargetPath(targetPath);
  }
  return builder.build();
}
 
开发者ID:naver,项目名称:hadoop,代码行数:20,代码来源:PBHelper.java

示例3: setup

import com.google.protobuf.ByteString; //导入方法依赖的package包/类
@Before
public void setup() {
    MockitoAnnotations.initMocks(this);

    data = new HashMap<>();
    data.put("key1", "value1");
    data.put("key2", "value2");
    data.put("key3", "value3");

    byteString = ByteString.copyFrom(SerializationUtils.serialize((Serializable) data));
    chunk1 = getNextChunk(byteString, 0, 10);
    chunk2 = getNextChunk(byteString, 10, 10);
    chunk3 = getNextChunk(byteString, 20, byteString.size());

    fbos = spy(new FileBackedOutputStream(100000000, "target"));
    FileBackedOutputStreamFactory mockFactory = mock(FileBackedOutputStreamFactory.class);
    doReturn(fbos).when(mockFactory).newInstance();
    doReturn(mockFactory).when(mockContext).getFileBackedOutputStreamFactory();
}
 
开发者ID:hashsdn,项目名称:hashsdn-controller,代码行数:20,代码来源:SnapshotTrackerTest.java

示例4: testThreeBytes

import com.google.protobuf.ByteString; //导入方法依赖的package包/类
public void testThreeBytes() {
  // Travis' OOM killer doesn't like this test
  if (System.getenv("TRAVIS") == null) {
    int count = 0;
    int valid = 0;
    for (int i = Byte.MIN_VALUE; i <= Byte.MAX_VALUE; i++) {
      for (int j = Byte.MIN_VALUE; j <= Byte.MAX_VALUE; j++) {
        for (int k = Byte.MIN_VALUE; k <= Byte.MAX_VALUE; k++) {
          byte[] bytes = new byte[]{(byte) i, (byte) j, (byte) k};
          ByteString bs = ByteString.copyFrom(bytes);
          if (!bs.isValidUtf8()) {
            assertInvalid(bytes);
          } else {
            valid++;
          }
          count++;
          if ((count % 1000000L) == 0) {
            println("Processed " + (count / 1000000L) + " million characters");
          }
        }
      }
    }
    assertEquals(IsValidUtf8TestUtil.EXPECTED_THREE_BYTE_ROUNDTRIPPABLE_COUNT, valid);
  }
}
 
开发者ID:DataSketches,项目名称:memory,代码行数:26,代码来源:Utf8Test.java

示例5: testSimplePayment

import com.google.protobuf.ByteString; //导入方法依赖的package包/类
@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("test"));
    assertEquals(paymentRequestMemo, paymentSession.getMemo());
    assertEquals(coin, 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<>();
    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(coin.getValue(), payment.getRefundTo(0).getAmount());
    TransactionOutput refundOutput = new TransactionOutput(PARAMS, null, coin, refundAddr);
    ByteString refundScript = ByteString.copyFrom(refundOutput.getScriptBytes());
    assertTrue(refundScript.equals(payment.getRefundTo(0).getScript()));
}
 
开发者ID:creativechain,项目名称:creacoinj,代码行数:30,代码来源:PaymentSessionTest.java

示例6: transactionRedirect

import com.google.protobuf.ByteString; //导入方法依赖的package包/类
/**
 * Forward a StoredProcedureInvocation request to a remote site for execution
 * @param serializedRequest
 * @param callback
 * @param partition
 */
public void transactionRedirect(byte[] serializedRequest, RpcCallback<TransactionRedirectResponse> callback, int partition) {
    int dest_site_id = catalogContext.getSiteIdForPartitionId(partition);
    if (debug.val)
        LOG.debug(String.format("Redirecting transaction request to partition #%d on %s",
                  partition, HStoreThreadManager.formatSiteName(dest_site_id)));
    
    ByteString bs = ByteString.copyFrom(serializedRequest);
    TransactionRedirectRequest mr = TransactionRedirectRequest.newBuilder()
                                    .setSenderSite(this.local_site_id)
                                    .setWork(bs)
                                    .build();
    this.channels[dest_site_id].transactionRedirect(new ProtoRpcController(), mr, callback);
}
 
开发者ID:s-store,项目名称:sstore-soft,代码行数:20,代码来源:HStoreCoordinator.java

示例7: run

import com.google.protobuf.ByteString; //导入方法依赖的package包/类
@Override
    public void run(ClientResponseImpl parameter) {
        if (debug.val)
            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.val)
            LOG.debug(String.format("Sent back ClientResponse for txn #%d to %s [bytes=%d]",
                      parameter.getTransactionId(), HStoreThreadManager.formatSiteName(this.destSiteId),
                      bs.size()));
        
        // 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);
//        }
    }
 
开发者ID:s-store,项目名称:sstore-soft,代码行数:32,代码来源:TransactionRedirectResponseCallback.java

示例8: testSerializeToBuffer

import com.google.protobuf.ByteString; //导入方法依赖的package包/类
public void testSerializeToBuffer() throws Exception {
        SerializableException error = null;
        try {
            throw new NullPointerException();
        } catch (Exception ex) {
            error = new SerializableException(ex);
        }
        assertNotNull(error);
        
        int size = error.getSerializedSize();
        ByteBuffer b = ByteBuffer.allocate(size);
        error.serializeToBuffer(b);
        b.rewind();
        int expected = b.getInt();
        assertTrue(expected > 0);
        assertTrue(expected <= size);
        b.rewind();

        // Make sure we can still do this with a BufferPool
        DBBPool buffer_pool = new DBBPool(false, false);
        BBContainer bc = buffer_pool.acquire(size);
        error.serializeToBuffer(bc.b);
        bc.b.rewind();
        assertEquals(expected, bc.b.getInt());
        bc.b.rewind();
        
        ByteString bs = ByteString.copyFrom(b);
        ByteBuffer bs_b = bs.asReadOnlyByteBuffer();
//        System.err.println("NEW: " + StringUtil.md5sum(b));
        
        assertEquals(expected, bs_b.getInt());
    }
 
开发者ID:s-store,项目名称:sstore-soft,代码行数:33,代码来源:TestSerializableException.java

示例9: toByteString

import com.google.protobuf.ByteString; //导入方法依赖的package包/类
protected ByteString toByteString(final Map<String, String> state) {
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    try (ObjectOutputStream oos = new ObjectOutputStream(bos)) {
        oos.writeObject(state);
        return ByteString.copyFrom(bos.toByteArray());
    } catch (IOException e) {
        throw new AssertionError("IOException occurred converting Map to Bytestring", e);
    }
}
 
开发者ID:hashsdn,项目名称:hashsdn-controller,代码行数:10,代码来源:AbstractRaftActorBehaviorTest.java

示例10: testOneByte

import com.google.protobuf.ByteString; //导入方法依赖的package包/类
@Test
public void testOneByte() {
  int valid = 0;
  for (int i = Byte.MIN_VALUE; i <= Byte.MAX_VALUE; i++) {
    ByteString bs = ByteString.copyFrom(new byte[] {(byte) i });
    if (!bs.isValidUtf8()) { //from -128 to -1
      assertInvalid(bs.toByteArray());
    } else {
      valid++; //from 0 to 127
    }
  }
  assertEquals(IsValidUtf8TestUtil.EXPECTED_ONE_BYTE_ROUNDTRIPPABLE_COUNT, valid);
}
 
开发者ID:DataSketches,项目名称:memory,代码行数:14,代码来源:Utf8Test.java

示例11: planCompleted

import com.google.protobuf.ByteString; //导入方法依赖的package包/类
@Override
public void planCompleted(ExecutionPlan plan) {
  if (plan != null) {
    try {
      schema = RootSchemaFinder.getSchema(plan.getRootOperator(), funcRegistry);
    } catch (Exception e) {
      logger.warn("Failed to capture query output schema", e);
    }
  }

  accelerationDetails = ByteString.copyFrom(detailsPopulator.computeAcceleration());
}
 
开发者ID:dremio,项目名称:dremio-oss,代码行数:13,代码来源:PlanCaptureAttemptObserver.java

示例12: testBytes

import com.google.protobuf.ByteString; //导入方法依赖的package包/类
private void testBytes(byte[] lhs, byte[] rhs, Function<Integer, Boolean> tester) {
  ByteString lhsBS = ByteString.copyFrom(lhs);
  ByteString rhsBS = ByteString.copyFrom(rhs);

  Comparable lhsComp = Comparables.wrap(lhsBS);
  Comparable rhsComp = Comparables.wrap(rhsBS);

  assertTrue(tester.apply(lhsComp.compareTo(rhsComp)));

  lhsComp = Comparables.wrap(lhs);
  rhsComp = Comparables.wrap(rhs);

  assertTrue(tester.apply(lhsComp.compareTo(rhsComp)));
}
 
开发者ID:pingcap,项目名称:tikv-client-lib-java,代码行数:15,代码来源:ComparablesTest.java

示例13: getByteString

import com.google.protobuf.ByteString; //导入方法依赖的package包/类
public static ByteString getByteString(byte[] bytes) {
	// return singleton to reduce object allocation
	return (bytes.length == 0) ? ByteString.EMPTY : ByteString.copyFrom(bytes);
}
 
开发者ID:nucypher,项目名称:hadoop-oss,代码行数:5,代码来源:KeyRotationBC.java

示例14: getByteString

import com.google.protobuf.ByteString; //导入方法依赖的package包/类
public static ByteString getByteString(byte[] bytes) {
  // return singleton to reduce object allocation
  return (bytes.length == 0) ? ByteString.EMPTY : ByteString.copyFrom(bytes);
}
 
开发者ID:nucypher,项目名称:hadoop-oss,代码行数:5,代码来源:NuCypherExtPBHelperClient.java

示例15: next

import com.google.protobuf.ByteString; //导入方法依赖的package包/类
/**
 * Returns the next {@link Chunk} or throws a {@link NoSuchElementException} if no data is left.
 *
 * <p>Always call {@link #hasNext()} before calling this method.
 *
 * <p>Zero byte inputs are treated special. Instead of throwing a {@link NoSuchElementException}
 * on the first call to {@link #next()}, a {@link Chunk} with an empty {@link ByteString} is
 * returned.
 */
public Chunk next() throws IOException {
  if (!hasNext()) {
    throw new NoSuchElementException();
  }

  maybeInitialize();

  if (digest.getSizeBytes() == 0) {
    data = null;
    return EMPTY_CHUNK;
  }

  // The cast to int is safe, because the return value is capped at chunkSize.
  int bytesToRead = (int) Math.min(bytesLeft(), chunkSize);
  if (bytesToRead == 0) {
    chunkCache = null;
    data = null;
    throw new NoSuchElementException();
  }

  if (chunkCache == null) {
    // Lazily allocate it in order to save memory on small data.
    // 1) bytesToRead < chunkSize: There will only ever be one next() call.
    // 2) bytesToRead == chunkSize: chunkCache will be set to its biggest possible value.
    // 3) bytestoRead > chunkSize: Not possible, due to Math.min above.
    chunkCache = new byte[bytesToRead];
  }

  long offsetBefore = offset;
  try {
    ByteStreams.readFully(data, chunkCache, 0, bytesToRead);
  } catch (EOFException e) {
    throw new IllegalStateException("Reached EOF, but expected "
        + bytesToRead + " bytes.", e);
  }
  offset += bytesToRead;

  ByteString blob = ByteString.copyFrom(chunkCache, 0, bytesToRead);

  if (bytesLeft() == 0) {
    data.close();
    data = null;
    chunkCache = null;
  }

  return new Chunk(digest, blob, offsetBefore);
}
 
开发者ID:bazelbuild,项目名称:bazel-buildfarm,代码行数:57,代码来源:Chunker.java


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