com.google.protobuf.Timestamp Java Examples

The following examples show how to use com.google.protobuf.Timestamp. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: BuildEventServiceProtoUtilTest.java    From bazel with Apache License 2.0 6 votes vote down vote up
@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());
}
 
Example #2
Source File: RemoteSerializerTest.java    From firebase-android-sdk with Apache License 2.0 6 votes vote down vote up
@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);
  }
}
 
Example #3
Source File: SmartContractStubTest.java    From julongchain with Apache License 2.0 6 votes vote down vote up
@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));
}
 
Example #4
Source File: SmartContractStubTest.java    From julongchain with Apache License 2.0 6 votes vote down vote up
@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));
}
 
Example #5
Source File: BuildEventServiceProtoUtilTest.java    From bazel with Apache License 2.0 6 votes vote down vote up
@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());
}
 
Example #6
Source File: SmartContractStubTest.java    From julongchain with Apache License 2.0 6 votes vote down vote up
@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));
}
 
Example #7
Source File: StatisticsManager.java    From kafka-pubsub-emulator with Apache License 2.0 6 votes vote down vote up
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);
  }
}
 
Example #8
Source File: RemoteSerializerTest.java    From firebase-android-sdk with Apache License 2.0 6 votes vote down vote up
@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);
}
 
Example #9
Source File: EnvelopeHelper.java    From julongchain with Apache License 2.0 6 votes vote down vote up
/**
 * 构造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();
}
 
Example #10
Source File: UserProviderImpl.java    From dubbo-samples with Apache License 2.0 6 votes vote down vote up
@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();
}
 
Example #11
Source File: DateTest.java    From jprotobuf with Apache License 2.0 6 votes vote down vote up
/**
 * 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());
    }
}
 
Example #12
Source File: ServingServiceGRpcControllerTest.java    From feast with Apache License 2.0 6 votes vote down vote up
@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);
}
 
Example #13
Source File: OnlineServingServiceTest.java    From feast with Apache License 2.0 6 votes vote down vote up
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();
}
 
Example #14
Source File: ProtobufTimestampParserTest.java    From secor with Apache License 2.0 6 votes vote down vote up
@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)));
}
 
Example #15
Source File: BqIntegrationTest.java    From beast with Apache License 2.0 5 votes vote down vote up
@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());
}
 
Example #16
Source File: CreateTask.java    From java-docs-samples with Apache License 2.0 5 votes vote down vote up
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());
  }
}
 
Example #17
Source File: InvocationStubImpl.java    From fabric-chaincode-java with Apache License 2.0 5 votes vote down vote up
/**
 *
 * @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);
        }
    }
}
 
Example #18
Source File: ConvertersTest.java    From dropwizard-protobuf with Apache License 2.0 5 votes vote down vote up
@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);
}
 
Example #19
Source File: FindingSnippets.java    From google-cloud-java with Apache License 2.0 5 votes vote down vote up
/**
 * 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);
  }
}
 
Example #20
Source File: TransactionContext.java    From fabric-sdk-java with Apache License 2.0 5 votes vote down vote up
public Timestamp getFabricTimestamp() {
    if (currentTimeStamp == null) {

        currentTimeStamp = ProtoUtils.getCurrentFabricTimestamp();
    }
    return currentTimeStamp;
}
 
Example #21
Source File: TimestampTest.java    From jackson-datatype-protobuf with Apache License 2.0 5 votes vote down vote up
@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());
}
 
Example #22
Source File: FeatureRowDecoderTest.java    From feast with Apache License 2.0 5 votes vote down vote up
@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));
}
 
Example #23
Source File: TimestampDeserializer.java    From jackson-datatype-protobuf with Apache License 2.0 5 votes vote down vote up
@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();
  }
}
 
Example #24
Source File: SubscriptionManager.java    From kafka-pubsub-emulator with Apache License 2.0 5 votes vote down vote up
/**
 * Fills the {@code returnedMessages} List with up to {@code maxMessages} Message objects by
 * retrieving ConsumerRecords from the head of the buffered queue.
 */
private void fillFromBuffer(List<PubsubMessage> returnedMessages, int maxMessages) {
  ConsumerRecord<String, ByteBuffer> record;
  int dequeued = 0;
  String messageId;
  while (returnedMessages.size() < maxMessages && !buffer.isEmpty()) {
    try {
      record = buffer.remove();
      dequeued++;
      messageId = record.partition() + "-" + record.offset();
      queueSizeBytes.addAndGet(-record.serializedValueSize());
      returnedMessages.add(
          PubsubMessage.newBuilder()
              .putAllAttributes(buildAttributesMap(record.headers()))
              .setData(ByteString.copyFrom(record.value()))
              .setMessageId(messageId)
              .setPublishTime(
                  Timestamp.newBuilder()
                      .setSeconds(record.timestamp() / 1000)
                      .setNanos((int) ((record.timestamp() % 1000) * 1000000))
                      .build())
              .build());
    } catch (NoSuchElementException e) {
      break;
    }
  }
  logger.atFine().log("Dequeued %d messages from buffer", dequeued);
}
 
Example #25
Source File: UserProviderImpl.java    From dubbo-samples with Apache License 2.0 5 votes vote down vote up
@Override
public void getUser(UserId request, io.grpc.stub.StreamObserver<User> responseObserver) {
    String id = request.getId();
    User user = User.newBuilder().setId(id)
            .setTime(Timestamp.getDefaultInstance())
            .setAge(11)
            .setName("Hello")
            .setId(id)
            .build();
    responseObserver.onNext(user);
    responseObserver.onCompleted();
}
 
Example #26
Source File: FindingSnippets.java    From google-cloud-java with Apache License 2.0 5 votes vote down vote up
/**
 * Create a finding under a source.
 *
 * @param sourceName The source for the finding.
 */
// [START create_finding]
static Finding createFinding(SourceName sourceName, String findingId) {
  try (SecurityCenterClient client = SecurityCenterClient.create()) {
    // SourceName sourceName = SourceName.of(/*organization=*/"123234324",/*source=*/
    // "423432321");
    // String findingId = "samplefindingid";

    // Use the current time as the finding "event time".
    Instant eventTime = Instant.now();

    // The resource this finding applies to.  The CSCC UI can link
    // the findings for a resource to the corresponding Asset of a resource
    // if there are matches.
    String resourceName = "//cloudresourcemanager.googleapis.com/organizations/11232";

    // Start setting up a request to create a finding in a source.
    Finding finding =
        Finding.newBuilder()
            .setParent(sourceName.toString())
            .setState(State.ACTIVE)
            .setResourceName(resourceName)
            .setEventTime(
                Timestamp.newBuilder()
                    .setSeconds(eventTime.getEpochSecond())
                    .setNanos(eventTime.getNano()))
            .setCategory("MEDIUM_RISK_ONE")
            .build();

    // Call the API.
    Finding response = client.createFinding(sourceName, findingId, finding);

    System.out.println("Created Finding: " + response);
    return response;
  } catch (IOException e) {
    throw new RuntimeException("Couldn't create client.", e);
  }
}
 
Example #27
Source File: MatchStage.java    From bazel-buildfarm with Apache License 2.0 5 votes vote down vote up
private OperationContext match(OperationContext operationContext) {
  Timestamp workerStartTimestamp = Timestamps.fromMillis(System.currentTimeMillis());

  ExecuteEntry executeEntry = operationContext.queueEntry.getExecuteEntry();
  // this may be superfluous - we can probably just set the name and action digest
  Operation operation =
      Operation.newBuilder()
          .setName(executeEntry.getOperationName())
          .setMetadata(
              Any.pack(
                  ExecuteOperationMetadata.newBuilder()
                      .setActionDigest(executeEntry.getActionDigest())
                      .setStage(QUEUED)
                      .setStdoutStreamName(executeEntry.getStdoutStreamName())
                      .setStderrStreamName(executeEntry.getStderrStreamName())
                      .build()))
          .build();

  OperationContext matchedOperationContext =
      operationContext.toBuilder().setOperation(operation).build();

  matchedOperationContext
      .executeResponse
      .getResultBuilder()
      .getExecutionMetadataBuilder()
      .setWorker(workerContext.getName())
      .setQueuedTimestamp(executeEntry.getQueuedTimestamp())
      .setWorkerStartTimestamp(workerStartTimestamp);
  return matchedOperationContext;
}
 
Example #28
Source File: ConvertersTest.java    From dropwizard-protobuf with Apache License 2.0 5 votes vote down vote up
@Test
public void testFromZonedDateTime() {
  final ZonedDateTime offset = ZonedDateTime.parse("2018-01-12T12:45:32.123Z");

  final Timestamp actual = Converters.toZonedDateTimeUTC.reverse().convert(offset);
  final Timestamp expected =
      Timestamp.newBuilder().setSeconds(1515761132).setNanos(123000000).build();

  assertThat(actual).isEqualTo(expected);
}
 
Example #29
Source File: TimestampSerializer.java    From jackson-datatype-protobuf with Apache License 2.0 5 votes vote down vote up
@Override
public void serialize(
        Timestamp timestamp,
        JsonGenerator generator,
        SerializerProvider serializerProvider
) throws IOException {
  generator.writeString(Timestamps.toString(timestamp));
}
 
Example #30
Source File: ConvertersTest.java    From dropwizard-protobuf with Apache License 2.0 5 votes vote down vote up
@Test
public void testFromOffsetDateTime() {
  final OffsetDateTime offset = OffsetDateTime.parse("2018-01-12T12:45:32.123Z");

  final Timestamp actual = Converters.toOffsetDateTimeUTC.reverse().convert(offset);
  final Timestamp expected =
      Timestamp.newBuilder().setSeconds(1515761132).setNanos(123000000).build();

  assertThat(actual).isEqualTo(expected);
}