com.google.protobuf.FieldMask#com.google.protobuf.Timestamp源码实例Demo

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

@Test
public void testEncodesDates() {
  Calendar date1 = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
  date1.set(2016, 0, 2, 10, 20, 50);
  date1.set(Calendar.MILLISECOND, 500);

  Calendar date2 = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
  date2.set(2016, 5, 17, 10, 50, 15);
  date2.set(Calendar.MILLISECOND, 0);

  List<Date> tests = asList(date1.getTime(), date2.getTime());

  Timestamp ts1 = Timestamp.newBuilder().setNanos(500000000).setSeconds(1451730050).build();

  Timestamp ts2 = Timestamp.newBuilder().setNanos(0).setSeconds(1466160615).build();
  List<Value> expected =
      asList(
          Value.newBuilder().setTimestampValue(ts1).build(),
          Value.newBuilder().setTimestampValue(ts2).build());

  for (int i = 0; i < tests.size(); i++) {
    Value value = wrap(tests.get(i));
    assertRoundTrip(value, expected.get(i), Value.ValueTypeCase.TIMESTAMP_VALUE);
  }
}
 
@Test
public void testConvertsDocumentChangeWithDeletions() {
  WatchChange.DocumentChange expected =
      new WatchChange.DocumentChange(
          asList(), asList(1, 2), key("coll/1"), deletedDoc("coll/1", 5));
  WatchChange.DocumentChange actual =
      (WatchChange.DocumentChange)
          serializer.decodeWatchChange(
              ListenResponse.newBuilder()
                  .setDocumentDelete(
                      DocumentDelete.newBuilder()
                          .setDocument(serializer.encodeKey(key("coll/1")))
                          .setReadTime(
                              serializer.encodeTimestamp(
                                  new com.google.firebase.Timestamp(0, 5000)))
                          .addRemovedTargetIds(1)
                          .addRemovedTargetIds(2))
                  .build());
  assertEquals(expected, actual);
}
 
源代码3 项目: julongchain   文件: EnvelopeHelper.java
/**
 * 构造GroupHeader对象
 *
 * @param type
 * @param version
 * @param timestamp
 * @param groupId
 * @param txId
 * @param epoch
 * @param extension
 * @return
 */
public static Common.GroupHeader buildGroupHeader(
        int type, int version, Timestamp timestamp, String groupId, String txId, long epoch, ProposalPackage
        .SmartContractHeaderExtension extension) {
    //首先构造GroupHeader对象
    Common.GroupHeader.Builder groupHeaderBuilder = Common.GroupHeader.newBuilder();
    groupHeaderBuilder.setType(type);
    groupHeaderBuilder.setVersion(version);
    if (timestamp != null) {
        groupHeaderBuilder.setTimestamp(timestamp);
    }
    if (StringUtils.isNotBlank(groupId)) {
        groupHeaderBuilder.setGroupId(groupId);
    }
    if (StringUtils.isNotBlank(txId)) {
        groupHeaderBuilder.setTxId(txId);
    }
    groupHeaderBuilder.setEpoch(epoch);

    if (extension != null) {
        groupHeaderBuilder.setExtension(extension.toByteString());
    }

    return groupHeaderBuilder.build();
}
 
源代码4 项目: julongchain   文件: SmartContractStubTest.java
@Test
public void getSignedProposal() {
    final ProposalPackage.SignedProposal signedProposal = ProposalPackage.SignedProposal.newBuilder()
            .setProposalBytes(ProposalPackage.Proposal.newBuilder()
                    .setHeader(Common.Header.newBuilder()
                            .setGroupHeader(Common.GroupHeader.newBuilder()
                                    .setType(ENDORSER_TRANSACTION_VALUE)
                                    .setTimestamp(Timestamp.getDefaultInstance())
                                    .build().toByteString()
                            )
                            .build().toByteString()
                    )
                    .build().toByteString()
            ).build();
    final SmartContractStub stub = new SmartContractStub("myc", "txId", handler, Collections.emptyList(), signedProposal);
    assertThat(stub.getSignedProposal(), is(signedProposal));
}
 
源代码5 项目: julongchain   文件: SmartContractStubTest.java
@Test
public void getCreator() {
    final Instant instant = Instant.now();
    final byte[] creator = "CREATOR".getBytes(UTF_8);
    final Timestamp timestamp = Timestamp.newBuilder().setSeconds(instant.getEpochSecond()).setNanos(instant.getNano()).build();
    final ProposalPackage.SignedProposal signedProposal = ProposalPackage.SignedProposal.newBuilder()
            .setProposalBytes(ProposalPackage.Proposal.newBuilder()
                    .setHeader(Common.Header.newBuilder()
                            .setGroupHeader(Common.GroupHeader.newBuilder()
                                    .setType(ENDORSER_TRANSACTION_VALUE)
                                    .setTimestamp(timestamp)
                                    .build().toByteString()
                            )
                            .setSignatureHeader(Common.SignatureHeader.newBuilder()
                                    .setCreator(ByteString.copyFrom(creator))
                                    .build().toByteString()
                            )
                            .build().toByteString()
                    )
                    .build().toByteString()
            ).build();
    final SmartContractStub stub = new SmartContractStub("myc", "txid", handler, new ArrayList<>(), signedProposal);
    assertThat(stub.getCreator(), is(creator));
}
 
源代码6 项目: bazel   文件: BuildEventServiceProtoUtilTest.java
@Test
public void testBuildEnqueued() {
  Timestamp expected = Timestamps.fromMillis(clock.advanceMillis(100));
  assertThat(BES_PROTO_UTIL.buildEnqueued(expected))
      .isEqualTo(
          PublishLifecycleEventRequest.newBuilder()
              .setServiceLevel(ServiceLevel.INTERACTIVE)
              .setProjectId(PROJECT_ID)
              .setBuildEvent(
                  OrderedBuildEvent.newBuilder()
                      .setStreamId(
                          StreamId.newBuilder()
                              .setBuildId(BUILD_REQUEST_ID)
                              .setComponent(BuildComponent.CONTROLLER))
                      .setSequenceNumber(1)
                      .setEvent(
                          BuildEvent.newBuilder()
                              .setEventTime(expected)
                              .setBuildEnqueued(BuildEnqueued.newBuilder())))
              .build());
}
 
源代码7 项目: julongchain   文件: SmartContractStubTest.java
@Test
public void getBinding() {
    final byte[] expectedDigest = DatatypeConverter.parseHexBinary("5093dd4f4277e964da8f4afbde0a9674d17f2a6a5961f0670fc21ae9b67f2983");
    final ProposalPackage.SignedProposal signedProposal = ProposalPackage.SignedProposal.newBuilder()
            .setProposalBytes(ProposalPackage.Proposal.newBuilder()
                    .setHeader(Common.Header.newBuilder()
                            .setGroupHeader(Common.GroupHeader.newBuilder()
                                    .setType(ENDORSER_TRANSACTION_VALUE)
                                    .setTimestamp(Timestamp.getDefaultInstance())
                                    .setEpoch(10)
                                    .build().toByteString()
                            )
                            .setSignatureHeader(Common.SignatureHeader.newBuilder()
                                    .setNonce(ByteString.copyFromUtf8("nonce"))
                                    .setCreator(ByteString.copyFromUtf8("creator"))
                                    .build().toByteString()
                            )
                            .build().toByteString()
                    )
                    .build().toByteString()
            ).build();
    final SmartContractStub stub = new SmartContractStub("myc", "txid", handler, new ArrayList<>(), signedProposal);
    assertThat(stub.getBinding(), is(expectedDigest));
}
 
源代码8 项目: kafka-pubsub-emulator   文件: StatisticsManager.java
void computeSubscriber(String subscription, ByteString messageData, Timestamp publishTime) {
  Optional<Subscription> subscriptionByName =
      configurationManager.getSubscriptionByName(subscription);
  if (subscriptionByName.isPresent()) {
    StatisticsInformation statisticsInformation =
        subscriberInformationByTopic.get(subscriptionByName.get().getTopic());
    if (statisticsInformation == null) {
      logger.atWarning().log(
          "Unable to record subscriber statistics error for Subscription %s (Topic %s not found)",
          subscription, subscriberInformationByTopic.get(subscriptionByName.get().getTopic()));
      return;
    }
    Instant publishTimeToInstant =
        Instant.ofEpochSecond(publishTime.getSeconds(), publishTime.getNanos());
    long subscriptionLatency = clock.millis() - publishTimeToInstant.toEpochMilli();
    statisticsInformation.compute(subscriptionLatency, messageData.toStringUtf8().length());
  } else {
    logger.atWarning().log(
        "Unable to record subscriber statistics error for Subscription %s", subscription);
  }
}
 
源代码9 项目: bazel   文件: BuildEventServiceProtoUtilTest.java
@Test
public void testInvocationAttemptStarted() {
  Timestamp expected = Timestamps.fromMillis(clock.advanceMillis(100));
  assertThat(BES_PROTO_UTIL.invocationStarted(expected))
      .isEqualTo(
          PublishLifecycleEventRequest.newBuilder()
              .setServiceLevel(ServiceLevel.INTERACTIVE)
              .setProjectId(PROJECT_ID)
              .setBuildEvent(
                  OrderedBuildEvent.newBuilder()
                      .setStreamId(
                          StreamId.newBuilder()
                              .setBuildId(BUILD_REQUEST_ID)
                              .setInvocationId(BUILD_INVOCATION_ID)
                              .setComponent(BuildComponent.CONTROLLER))
                      .setSequenceNumber(1)
                      .setEvent(
                          BuildEvent.newBuilder()
                              .setEventTime(expected)
                              .setInvocationAttemptStarted(
                                  InvocationAttemptStarted.newBuilder().setAttemptNumber(1))))
              .build());
}
 
源代码10 项目: dubbo-samples   文件: UserProviderImpl.java
@Override
public void getUserList(UserIdList request, StreamObserver<UserList> responseObserver){
    ProtocolStringList protocolStringList = request.getIdList();
    UserList.Builder userListBuilder = UserList.newBuilder();
    for (String id : protocolStringList) {
        User user = User.newBuilder().setId(id)
                .setTime(Timestamp.getDefaultInstance())
                .setAge(11)
                .setName("Hello")
                .setId(id)
                .build();
        userListBuilder.addUser(user);
    }
    responseObserver.onNext(userListBuilder.build());
    responseObserver.onCompleted();
}
 
源代码11 项目: jprotobuf   文件: DateTest.java
/**
 * Test time stamp.
 */
@Test
public void testTimeStamp() {
    long secs = System.currentTimeMillis() / 1000;
    int nanos = (int) (System.currentTimeMillis() % 1000) * 1000000;

    Timestamp ts = Timestamp.newBuilder().setSeconds(secs).setNanos(nanos).build();

    com.baidu.bjf.remoting.protobuf.Timestamp ts2 = new com.baidu.bjf.remoting.protobuf.Timestamp();
    ts2.setSeconds(secs);
    ts2.setNanos(nanos);

    Codec<com.baidu.bjf.remoting.protobuf.Timestamp> codec =
            ProtobufProxy.create(com.baidu.bjf.remoting.protobuf.Timestamp.class);

    try {
        byte[] encode = codec.encode(ts2);
        Assert.assertEquals(Arrays.toString(encode), Arrays.toString(ts.toByteArray()));
    } catch (IOException e) {
        Assert.fail(e.getMessage());
    }
}
 
源代码12 项目: feast   文件: ServingServiceGRpcControllerTest.java
@Before
public void setUp() {
  initMocks(this);

  validRequest =
      GetOnlineFeaturesRequest.newBuilder()
          .addFeatures(FeatureReference.newBuilder().setName("feature1").build())
          .addFeatures(FeatureReference.newBuilder().setName("feature2").build())
          .addEntityRows(
              EntityRow.newBuilder()
                  .setEntityTimestamp(Timestamp.newBuilder().setSeconds(100))
                  .putFields("entity1", Value.newBuilder().setInt64Val(1).build())
                  .putFields("entity2", Value.newBuilder().setInt64Val(1).build()))
          .build();

  Tracer tracer = Configuration.fromEnv("dummy").getTracer();
  FeastProperties feastProperties = new FeastProperties();
  service = new ServingServiceGRpcController(mockServingService, feastProperties, tracer);
}
 
源代码13 项目: feast   文件: OnlineServingServiceTest.java
private GetOnlineFeaturesRequest getOnlineFeaturesRequest(
    List<FeatureReference> featureReferences) {
  return GetOnlineFeaturesRequest.newBuilder()
      .setOmitEntitiesInResponse(false)
      .addAllFeatures(featureReferences)
      .addEntityRows(
          EntityRow.newBuilder()
              .setEntityTimestamp(Timestamp.newBuilder().setSeconds(100))
              .putFields("entity1", intValue(1))
              .putFields("entity2", strValue("a")))
      .addEntityRows(
          EntityRow.newBuilder()
              .setEntityTimestamp(Timestamp.newBuilder().setSeconds(100))
              .putFields("entity1", intValue(2))
              .putFields("entity2", strValue("b")))
      .build();
}
 
源代码14 项目: secor   文件: ProtobufTimestampParserTest.java
@Test
public void testExtractPathTimestampMillis() throws Exception {
    Map<String, String> classPerTopic = new HashMap<String, String>();
    System.out.println(TimestampedMessages.UnitTestTimestamp1.class.getName());
    classPerTopic.put("test", TimestampedMessages.UnitTestTimestamp1.class.getName());
    Mockito.when(mConfig.getMessageTimestampName()).thenReturn("timestamp");
    Mockito.when(mConfig.getProtobufMessageClassPerTopic()).thenReturn(classPerTopic);

    ProtobufMessageParser parser = new ProtobufMessageParser(mConfig);


    Timestamp timestamp = Timestamp.newBuilder().setSeconds(1405970352l)
            .setNanos(0).build();

    TimestampedMessages.UnitTestTimestamp1 message = TimestampedMessages.UnitTestTimestamp1.newBuilder().setTimestamp(timestamp).build();
    assertEquals(1405970352000l,
            parser.extractTimestampMillis(new Message("test", 0, 0, null, message.toByteArray(), timestamp.getSeconds(), null)));

    Timestamp timestampWithNano = Timestamp.newBuilder().setSeconds(1405970352l)
            .setNanos(123000000).build();
    message = TimestampedMessages.UnitTestTimestamp1.newBuilder().setTimestamp(timestampWithNano).build();
    assertEquals(1405970352123l,
            parser.extractTimestampMillis(new Message("test", 0, 0, null, message.toByteArray(), timestamp.getSeconds(), null)));
}
 
源代码15 项目: jackson-datatype-protobuf   文件: TimestampTest.java
@Test
public void itSetsTimestampWhenZeroInJson() throws IOException {
  String json = "{\"timestamp\":\"1970-01-01T00:00:00Z\"}";
  HasTimestamp message = camelCase().readValue(json, HasTimestamp.class);
  assertThat(message.hasTimestamp()).isTrue();
  assertThat(message.getTimestamp()).isEqualTo(Timestamp.getDefaultInstance());
}
 
源代码16 项目: fabric-sdk-java   文件: ProtoUtilsTest.java
@Test
public void timeStampDrill() throws Exception {

    final long millis = System.currentTimeMillis();

    //Test values over 2seconds
    for (long start = millis; start < millis + 2010; ++start) {
        Timestamp ts = Timestamp.newBuilder().setSeconds(start / 1000)
                .setNanos((int) ((start % 1000) * 1000000)).build();

        Date dateFromTimestamp = getDateFromTimestamp(ts);
        //    System.out.println(dateFromTimestamp);
        Date expectedDate = new Date(start);
        //Test various formats to make sure...
        Assert.assertEquals(expectedDate, dateFromTimestamp);
        Assert.assertEquals(expectedDate.getTime(), dateFromTimestamp.getTime());
        Assert.assertEquals(expectedDate.toString(), dateFromTimestamp.toString());
        //Now reverse it
        Timestamp timestampFromDate = getTimestampFromDate(expectedDate);
        Assert.assertEquals(ts, timestampFromDate);
        Assert.assertEquals(ts.getNanos(), timestampFromDate.getNanos());
        Assert.assertEquals(ts.getSeconds(), timestampFromDate.getSeconds());
        Assert.assertEquals(ts.toString(), timestampFromDate.toString());

    }

}
 
源代码17 项目: dropwizard-protobuf   文件: ConvertersTest.java
@Test
public void testToOffsetDateTime() {
  final Timestamp timestamp =
      Timestamp.newBuilder().setSeconds(1515761132).setNanos(123000000).build();

  final OffsetDateTime actual = Converters.toOffsetDateTimeUTC.convert(timestamp);
  final OffsetDateTime expected = OffsetDateTime.parse("2018-01-12T12:45:32.123Z");

  assertThat(actual).isEqualTo(expected);
}
 
源代码18 项目: beast   文件: BqIntegrationTest.java
@Ignore
@Test
public void shouldPushNestedMessage() {
    Instant now = Instant.now();
    long second = now.getEpochSecond();
    int nano = now.getNano();
    Timestamp createdAt = Timestamp.newBuilder().setSeconds(second).setNanos(nano).build();
    TestMessage testMessage = TestMessage.newBuilder()
            .setOrderNumber("order-1")
            .setOrderUrl("order-url")
            .setOrderDetails("order-details")
            .setCreatedAt(createdAt)
            .setStatus(com.gojek.beast.Status.COMPLETED)
            .build();
    ProtoParser protoParser = new ProtoParser(StencilClientFactory.getClient(), TestNestedMessage.class.getName());
    TestNestedMessage nestedMsg = TestNestedMessage.newBuilder()
            .setSingleMessage(testMessage)
            .setNestedId("nested-id")
            .build();
    TableId tableId = TableId.of("bqsinktest", "test_nested_messages");
    BqSink bqSink = new BqSink(authenticatedBQ(), tableId, new BQResponseParser(), gcsSinkHandler, bqRow);


    OffsetInfo offsetInfo = new OffsetInfo("topic", 1, 1, Instant.now().toEpochMilli());
    Map<String, Object> columns = new HashMap<>();
    HashMap<String, Object> nested = new HashMap<>();
    nested.put("order_number", nestedMsg.getSingleMessage().getOrderNumber());
    nested.put("order_url", nestedMsg.getSingleMessage().getOrderUrl());

    columns.put("id", nestedMsg.getNestedId());
    columns.put("msg", nested);

    Status push = bqSink.push(new Records(Arrays.asList(new Record(offsetInfo, columns))));
    assertTrue(push.isSuccess());
}
 
源代码19 项目: beast   文件: ProtoUtil.java
public static TestMessage generateTestMessage(Instant now) {
    call++;
    Timestamp createdAt = Timestamp.newBuilder().setSeconds(now.getEpochSecond()).setNanos(now.getNano()).build();
    return TestMessage.newBuilder()
            .setOrderNumber("order-" + call)
            .setOrderUrl("order-url-" + call)
            .setOrderDetails("order-details-" + call)
            .setCreatedAt(createdAt)
            .setStatus(Status.COMPLETED)
            .setTripDuration(Duration.newBuilder().setSeconds(1).setNanos(TRIP_DURATION_NANOS).build())
            .build();

}
 
源代码20 项目: feast   文件: FeatureSet.java
public FeatureSetProto.FeatureSet toProto() throws InvalidProtocolBufferException {
  List<EntitySpec> entitySpecs = new ArrayList<>();
  for (Entity entityField : entities) {
    entitySpecs.add(entityField.toProto());
  }

  List<FeatureSpec> featureSpecs = new ArrayList<>();
  for (Feature featureField : features) {
    if (!featureField.isArchived()) {
      featureSpecs.add(featureField.toProto());
    }
  }

  FeatureSetMeta.Builder meta =
      FeatureSetMeta.newBuilder()
          .setCreatedTimestamp(
              Timestamp.newBuilder().setSeconds(super.getCreated().getTime() / 1000L))
          .setStatus(status);

  FeatureSetSpec.Builder spec =
      FeatureSetSpec.newBuilder()
          .setName(getName())
          .setProject(project.getName())
          .setMaxAge(Duration.newBuilder().setSeconds(maxAgeSeconds))
          .addAllEntities(entitySpecs)
          .addAllFeatures(featureSpecs)
          .putAllLabels(TypeConversion.convertJsonStringToMap(labels))
          .setSource(source.toProto())
          .setVersion(version);

  return FeatureSetProto.FeatureSet.newBuilder().setMeta(meta).setSpec(spec).build();
}
 
源代码21 项目: bazel   文件: BuildEventServiceProtoUtil.java
public PublishLifecycleEventRequest buildFinished(Timestamp timestamp, Result result) {
  return lifecycleEvent(
          projectId,
          2,
          com.google.devtools.build.v1.BuildEvent.newBuilder()
              .setEventTime(timestamp)
              .setBuildFinished(
                  BuildFinished.newBuilder()
                      .setStatus(BuildStatus.newBuilder().setResult(result))))
      .build();
}
 
源代码22 项目: firebase-android-sdk   文件: Values.java
private static int compareTimestamps(Timestamp left, Timestamp right) {
  int cmp = Util.compareLongs(left.getSeconds(), right.getSeconds());
  if (cmp != 0) {
    return cmp;
  }
  return Util.compareIntegers(left.getNanos(), right.getNanos());
}
 
源代码23 项目: google-cloud-java   文件: FindingSnippets.java
/**
 * Group active findings under an organization and a source by their specified properties (e.g.
 * category) at a specified time.
 *
 * @param sourceName The source to limit the findings to.
 */
// [START group_active_findings_with_source_at_time]
static ImmutableList<GroupResult> groupActiveFindingsWithSourceAtTime(SourceName sourceName) {
  try (SecurityCenterClient client = SecurityCenterClient.create()) {
    // SourceName sourceName = SourceName.of(/*organization=*/"123234324",/*source=*/
    // "423432321");

    // 1 day ago
    Instant oneDayAgo = Instant.now().minusSeconds(60 * 60 * 24);

    GroupFindingsRequest.Builder request =
        GroupFindingsRequest.newBuilder()
            .setParent(sourceName.toString())
            .setGroupBy("category")
            .setFilter("state=\"ACTIVE\"")
            .setReadTime(
                Timestamp.newBuilder()
                    .setSeconds(oneDayAgo.getEpochSecond())
                    .setNanos(oneDayAgo.getNano()));

    // Call the API.
    GroupFindingsPagedResponse response = client.groupFindings(request.build());

    // This creates one list for all findings.  If your organization has a large number of
    // findings
    // this can cause out of memory issues.  You can process them batches by returning
    // the Iterable returned response.iterateAll() directly.
    ImmutableList<GroupResult> results = ImmutableList.copyOf(response.iterateAll());
    System.out.println("Findings:");
    System.out.println(results);
    return results;
  } catch (IOException e) {
    throw new RuntimeException("Couldn't create client.", e);
  }
}
 
源代码24 项目: feast   文件: StatsServiceTest.java
@Test
public void shouldThrowExceptionIfInvalidDatesProvided() throws IOException {
  GetFeatureStatisticsRequest request =
      GetFeatureStatisticsRequest.newBuilder()
          .setStartDate(Timestamp.newBuilder().setSeconds(1))
          .setEndDate(Timestamp.newBuilder().setSeconds(0))
          .build();

  expectedException.expect(IllegalArgumentException.class);
  expectedException.expectMessage(
      "Invalid request. Start timestamp 1 is greater than the end timestamp 0");
  statsService.getFeatureStatistics(request);
}
 
源代码25 项目: bazel   文件: BuildEventServiceUploaderCommands.java
SendRegularBuildEventCommand(
    BuildEvent event,
    ListenableFuture<PathConverter> localFileUpload,
    long sequenceNumber,
    Timestamp creationTime) {
  this.event = event;
  this.localFileUpload = localFileUpload;
  this.sequenceNumber = sequenceNumber;
  this.creationTime = creationTime;
}
 
源代码26 项目: java-docs-samples   文件: CreateTask.java
public static void main(String... args) throws Exception {
  // Instantiates a client.
  try (CloudTasksClient client = CloudTasksClient.create()) {
    // Variables provided by system variables.
    String projectId = System.getenv("GOOGLE_CLOUD_PROJECT");
    String queueName = System.getenv("QUEUE_ID");
    String location = System.getenv("LOCATION_ID");
    // Optional variables.
    String payload = "hello";
    int seconds = 0; // Scheduled delay for the task in seconds

    // Construct the fully qualified queue name.
    String queuePath = QueueName.of(projectId, location, queueName).toString();

    // Construct the task body.
    Task.Builder taskBuilder =
        Task.newBuilder()
            .setAppEngineHttpRequest(
                AppEngineHttpRequest.newBuilder()
                    .setBody(ByteString.copyFrom(payload, Charset.defaultCharset()))
                    .setRelativeUri("/tasks/create")
                    .setHttpMethod(HttpMethod.POST)
                    .build());

    // Add the scheduled time to the request.
    taskBuilder.setScheduleTime(
        Timestamp.newBuilder()
            .setSeconds(Instant.now(Clock.systemUTC()).plusSeconds(seconds).getEpochSecond()));

    // Send create task request.
    Task task = client.createTask(queuePath, taskBuilder.build());
    System.out.println("Task created: " + task.getName());
  }
}
 
源代码27 项目: fabric-chaincode-java   文件: InvocationStubImpl.java
/**
 *
 * @param message
 * @param handler
 * @throws InvalidProtocolBufferException
 */
InvocationStubImpl(final ChaincodeMessage message, final ChaincodeInvocationTask handler)
        throws InvalidProtocolBufferException {
    this.channelId = message.getChannelId();
    this.txId = message.getTxid();
    this.handler = handler;
    final ChaincodeInput input = ChaincodeInput.parseFrom(message.getPayload());

    this.args = Collections.unmodifiableList(input.getArgsList());
    this.signedProposal = message.getProposal();
    if (this.signedProposal == null || this.signedProposal.getProposalBytes().isEmpty()) {
        this.creator = null;
        this.txTimestamp = null;
        this.transientMap = Collections.emptyMap();
        this.binding = null;
    } else {
        try {
            final Proposal proposal = Proposal.parseFrom(signedProposal.getProposalBytes());
            final Header header = Header.parseFrom(proposal.getHeader());
            final ChannelHeader channelHeader = ChannelHeader.parseFrom(header.getChannelHeader());
            validateProposalType(channelHeader);
            final SignatureHeader signatureHeader = SignatureHeader.parseFrom(header.getSignatureHeader());
            final ChaincodeProposalPayload chaincodeProposalPayload = ChaincodeProposalPayload
                    .parseFrom(proposal.getPayload());
            final Timestamp timestamp = channelHeader.getTimestamp();

            this.txTimestamp = Instant.ofEpochSecond(timestamp.getSeconds(), timestamp.getNanos());
            this.creator = signatureHeader.getCreator();
            this.transientMap = chaincodeProposalPayload.getTransientMapMap();
            this.binding = computeBinding(channelHeader, signatureHeader);
        } catch (InvalidProtocolBufferException | NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        }
    }
}
 
源代码28 项目: fabric-sdk-java   文件: TransactionContext.java
public Timestamp getFabricTimestamp() {
    if (currentTimeStamp == null) {

        currentTimeStamp = ProtoUtils.getCurrentFabricTimestamp();
    }
    return currentTimeStamp;
}
 
源代码29 项目: feast   文件: FeatureRowDecoderTest.java
@Test
public void shouldDecodeValidEncodedFeatureRow() {

  FeatureRowDecoder decoder = new FeatureRowDecoder("feature_set_ref", spec);

  FeatureRowProto.FeatureRow encodedFeatureRow =
      FeatureRowProto.FeatureRow.newBuilder()
          .setEventTimestamp(Timestamp.newBuilder().setNanos(1000))
          .addFields(Field.newBuilder().setValue(Value.newBuilder().setInt32Val(2)))
          .addFields(Field.newBuilder().setValue(Value.newBuilder().setFloatVal(1.0f)))
          .build();

  FeatureRowProto.FeatureRow expectedFeatureRow =
      FeatureRowProto.FeatureRow.newBuilder()
          .setFeatureSet("feature_set_ref")
          .setEventTimestamp(Timestamp.newBuilder().setNanos(1000))
          .addFields(
              Field.newBuilder().setName("feature1").setValue(Value.newBuilder().setInt32Val(2)))
          .addFields(
              Field.newBuilder()
                  .setName("feature2")
                  .setValue(Value.newBuilder().setFloatVal(1.0f)))
          .build();

  assertTrue(decoder.isEncoded(encodedFeatureRow));
  assertTrue(decoder.isEncodingValid(encodedFeatureRow));
  assertEquals(expectedFeatureRow, decoder.decode(encodedFeatureRow));
}
 
@Override
public Timestamp deserialize(JsonParser parser, DeserializationContext context) throws IOException {
  switch (parser.getCurrentToken()) {
    case VALUE_STRING:
      try {
        return Timestamps.parse(parser.getText());
      } catch (ParseException e) {
        throw context.weirdStringException(parser.getText(), Timestamp.class, e.getMessage());
      }
    default:
      context.reportWrongTokenException(Timestamp.class, JsonToken.VALUE_STRING, wrongTokenMessage(context));
      // the previous method should have thrown
      throw new AssertionError();
  }
}