Java 类com.google.protobuf.util.Timestamps 实例源码

项目:curiostack    文件:MessageMarshallerTest.java   
@Test
public void anyInMaps() throws Exception {
  TestAny.Builder testAny = TestAny.newBuilder();
  testAny.putAnyMap("int32_wrapper", Any.pack(Int32Value.newBuilder().setValue(123).build()));
  testAny.putAnyMap("int64_wrapper", Any.pack(Int64Value.newBuilder().setValue(456).build()));
  testAny.putAnyMap("timestamp", Any.pack(Timestamps.parse("1969-12-31T23:59:59Z")));
  testAny.putAnyMap("duration", Any.pack(Durations.parse("12345.1s")));
  testAny.putAnyMap("field_mask", Any.pack(FieldMaskUtil.fromString("foo.bar,baz")));
  Value numberValue = Value.newBuilder().setNumberValue(1.125).build();
  Struct.Builder struct = Struct.newBuilder();
  struct.putFields("number", numberValue);
  testAny.putAnyMap("struct", Any.pack(struct.build()));
  Value nullValue = Value.newBuilder().setNullValue(NullValue.NULL_VALUE).build();
  testAny.putAnyMap(
      "list_value",
      Any.pack(ListValue.newBuilder().addValues(numberValue).addValues(nullValue).build()));
  testAny.putAnyMap("number_value", Any.pack(numberValue));
  testAny.putAnyMap("any_value_number", Any.pack(Any.pack(numberValue)));
  testAny.putAnyMap("any_value_default", Any.pack(Any.getDefaultInstance()));
  testAny.putAnyMap("default", Any.getDefaultInstance());

  assertMatchesUpstream(testAny.build(), TestAllTypes.getDefaultInstance());
}
项目:pubsub    文件:LoadTestRunner.java   
private static boolean shouldContinue(StartRequest request) {
  // If the test has been running for at least a minute, and we have been idle for a minute, we
  // should stop.
  if (System.currentTimeMillis() - Timestamps.toMillis(request.getStartTime()) > MAX_IDLE_MILLIS
      && System.currentTimeMillis() - task.getLastUpdateMillis() > MAX_IDLE_MILLIS) {
    return false;
  }
  switch (request.getStopConditionsCase()) {
    case TEST_DURATION:
      return System.currentTimeMillis()
          < (request.getStartTime().getSeconds()
                  + request.getBurnInDuration().getSeconds()
                  + request.getTestDuration().getSeconds())
              * 1000;
    case NUMBER_OF_MESSAGES:
      return task.getNumberOfMessages() < request.getNumberOfMessages();
    default:
      return false;
  }
}
项目:pubsub    文件:Driver.java   
private void printStats(Map<ClientType, Controller.LoadtestStats> results) {
  long startMillis = Timestamps.toMillis(Timestamps.add(Client.startTime, Client.burnInDuration));
  if (System.currentTimeMillis() < startMillis) {
    log.info(
        "Still under burn in time, will start in "
            + ((startMillis - System.currentTimeMillis()) / 1000)
            + " seconds.");
    return;
  }
  log.info("===============================================");
  results.forEach(
      (type, stats) -> {
        log.info("Results for " + type + ":");
        log.info("50%: " + LatencyDistribution.getNthPercentile(stats.bucketValues, 50.0));
        log.info("99%: " + LatencyDistribution.getNthPercentile(stats.bucketValues, 99.0));
        log.info("99.9%: " + LatencyDistribution.getNthPercentile(stats.bucketValues, 99.9));
        log.info(
            "Average throughput: "
                + new DecimalFormat("#.##").format(stats.getQPS() * messageSize / 1000000.0)
                + " MB/s");
      });
  log.info("===============================================");
}
项目:core-java    文件:QueryParametersShould.java   
@Test
public void keep_multiple_filters_for_single_column() throws ParseException {
    final String columnName = "time";
    final EntityColumn column = mock(EntityColumn.class);

    // Some valid Timestamp values
    final Timestamp startTime = Timestamps.parse("2000-01-01T10:00:00.000-05:00");
    final Timestamp deadline = Timestamps.parse("2017-01-01T10:00:00.000-05:00");

    final ColumnFilter startTimeFilter = gt(columnName, startTime);
    final ColumnFilter deadlineFilter = le(columnName, deadline);
    final Multimap<EntityColumn, ColumnFilter> columnFilters =
            ImmutableMultimap.<EntityColumn, ColumnFilter>builder()
                             .put(column, startTimeFilter)
                             .put(column, deadlineFilter)
                             .build();
    final CompositeQueryParameter parameter = from(columnFilters, ALL);
    final QueryParameters parameters = newBuilder().add(parameter)
                                                   .build();
    final List<CompositeQueryParameter> aggregatingParameters = newArrayList(parameters);
    assertSize(1, aggregatingParameters);
    final Multimap<EntityColumn, ColumnFilter> actualColumnFilters = aggregatingParameters.get(0).getFilters();
    final Collection<ColumnFilter> timeFilters = actualColumnFilters.get(column);
    assertSize(2, timeFilters);
    assertContainsAll(timeFilters, startTimeFilter, deadlineFilter);
}
项目:core-java    文件:AggregateStorageShould.java   
@Test
public void sort_by_version_rather_then_by_timestamp() {
    final Project state = Project.getDefaultInstance();
    final Version minVersion = zero();
    final Version maxVersion = increment(minVersion);
    final Timestamp minTimestamp = Timestamps.MIN_VALUE;
    final Timestamp maxTimestamp = Timestamps.MAX_VALUE;

    // The first event is an event, which is the oldest, i.e. with the minimal version.
    final Event expectedFirst = eventFactory.createEvent(state, minVersion, maxTimestamp);
    final Event expectedSecond = eventFactory.createEvent(state, maxVersion, minTimestamp);

    storage.writeEvent(id, expectedSecond);
    storage.writeEvent(id, expectedFirst);

    final List<Event> events = storage.read(newReadRequest(id))
                                      .get()
                                      .getEventList();
    assertTrue(events.indexOf(expectedFirst) < events.indexOf(expectedSecond));
}
项目:secor    文件:ProtobufTimestampParserTest.java   
@Test
public void testExtractNestedTimestampMillis() throws Exception {
    Map<String, String> classPerTopic = new HashMap<String, String>();
    classPerTopic.put("*", TimestampedMessages.UnitTestTimestamp2.class.getName());
    Mockito.when(mConfig.getMessageTimestampName()).thenReturn("internal.timestamp");
    Mockito.when(mConfig.getProtobufMessageClassPerTopic()).thenReturn(classPerTopic);

    ProtobufMessageParser parser = new ProtobufMessageParser(mConfig);

    Timestamp timestamp = Timestamps.fromMillis(1405970352000L);

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

    timestamp = Timestamps.fromMillis(1405970352123l);
    message = TimestampedMessages.UnitTestTimestamp2.newBuilder()
            .setInternal(TimestampedMessages.UnitTestTimestamp2.Internal.newBuilder().setTimestamp(timestamp).build()).build();
    assertEquals(1405970352123l,
            parser.extractTimestampMillis(new Message("test", 0, 0, null, message.toByteArray(), timestamp.getSeconds())));
}
项目:bazel    文件:BuildEventServiceProtoUtil.java   
@VisibleForTesting
public PublishBuildToolEventStreamRequest publishBuildToolEventStreamRequest(
    int sequenceNumber, BuildEvent.Builder besEvent) {
  PublishBuildToolEventStreamRequest.Builder builder =
      PublishBuildToolEventStreamRequest.newBuilder()
          .setOrderedBuildEvent(
              OrderedBuildEvent.newBuilder()
                  .setSequenceNumber(sequenceNumber)
                  .setEvent(
                      besEvent.setEventTime(Timestamps.fromMillis(clock.currentTimeMillis())))
                  .setStreamId(streamId(besEvent.getEventCase())));
  if (sequenceNumber == 1) {
    builder.addAllNotificationKeywords(getKeywords());
  }
  return builder.build();
}
项目:bazel    文件:BuildEventServiceProtoUtilTest.java   
@Test
public void testBuildEnqueued() {
  long expected = clock.advanceMillis(100);
  assertThat(besProtocol.buildEnqueued())
      .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(Timestamps.fromMillis(expected))
                              .setBuildEnqueued(BuildEnqueued.newBuilder())))
              .build());
}
项目:bazel    文件:BuildEventServiceProtoUtilTest.java   
@Test
public void testInvocationAttemptStarted() {
  long expected = clock.advanceMillis(100);
  assertThat(besProtocol.invocationStarted())
      .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(Timestamps.fromMillis(expected))
                              .setInvocationAttemptStarted(
                                  InvocationAttemptStarted.newBuilder().setAttemptNumber(1))))
              .build());
}
项目:bazel    文件:BuildEventServiceProtoUtilTest.java   
@Test
public void testInvocationAttemptFinished() {
  long expected = clock.advanceMillis(100);
  assertThat(besProtocol.invocationFinished(Result.COMMAND_SUCCEEDED))
      .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(2)
                      .setEvent(
                          BuildEvent.newBuilder()
                              .setEventTime(Timestamps.fromMillis(expected))
                              .setInvocationAttemptFinished(
                                  InvocationAttemptFinished.newBuilder()
                                      .setInvocationStatus(
                                          BuildStatus.newBuilder()
                                              .setResult(Result.COMMAND_SUCCEEDED)))))
              .build());
}
项目:bazel    文件:BuildEventServiceProtoUtilTest.java   
@Test
public void testBuildFinished() {
  long expected = clock.advanceMillis(100);
  assertThat(besProtocol.buildFinished(Result.COMMAND_SUCCEEDED))
      .isEqualTo(
          PublishLifecycleEventRequest.newBuilder()
              .setServiceLevel(ServiceLevel.INTERACTIVE)
              .setProjectId(PROJECT_ID)
              .setBuildEvent(
                  OrderedBuildEvent.newBuilder()
                      .setStreamId(
                          StreamId.newBuilder()
                              .setBuildId(BUILD_REQUEST_ID)
                              .setComponent(BuildComponent.CONTROLLER))
                      .setSequenceNumber(2)
                      .setEvent(
                          BuildEvent.newBuilder()
                              .setEventTime(Timestamps.fromMillis(expected))
                              .setBuildFinished(
                                  BuildFinished.newBuilder()
                                      .setStatus(
                                          BuildStatus.newBuilder()
                                              .setResult(Result.COMMAND_SUCCEEDED)))))
              .build());
}
项目:grpc-java    文件:GrpclbClientLoadRecorder.java   
/**
 * Generate the report with the data recorded this LB stream since the last report.
 */
ClientStats generateLoadReport() {
  ClientStats.Builder statsBuilder =
      ClientStats.newBuilder()
      .setTimestamp(Timestamps.fromMillis(time.currentTimeMillis()))
      .setNumCallsStarted(callsStartedUpdater.getAndSet(this, 0))
      .setNumCallsFinished(callsFinishedUpdater.getAndSet(this, 0))
      .setNumCallsFinishedWithClientFailedToSend(callsFailedToSendUpdater.getAndSet(this, 0))
      .setNumCallsFinishedKnownReceived(callsFinishedKnownReceivedUpdater.getAndSet(this, 0));

  Map<String, LongHolder> localCallsDroppedPerToken = Collections.emptyMap();
  synchronized (this) {
    if (!callsDroppedPerToken.isEmpty()) {
      localCallsDroppedPerToken = callsDroppedPerToken;
      callsDroppedPerToken = new HashMap<String, LongHolder>(localCallsDroppedPerToken.size());
    }
  }
  for (Entry<String, LongHolder> entry : localCallsDroppedPerToken.entrySet()) {
    statsBuilder.addCallsFinishedWithDrop(
        ClientStatsPerToken.newBuilder()
            .setLoadBalanceToken(entry.getKey())
            .setNumCalls(entry.getValue().num)
            .build());
  }
  return statsBuilder.build();
}
项目:teleport    文件:EntityBQTransform.java   
@Nullable
private String valueToTimestamp(Value v) {
  boolean isTimestampValue = v.getValueTypeCase().equals(ValueTypeCase.TIMESTAMP_VALUE);
  if (!isTimestampValue) {
    return null;
  }

  return Timestamps.toString(v.getTimestampValue());
}
项目:curiostack    文件:WellKnownTypeMarshaller.java   
@Override
public void doMerge(JsonParser parser, int unused, Message.Builder messageBuilder)
    throws IOException {
  Timestamp.Builder builder = (Timestamp.Builder) messageBuilder;
  try {
    builder.mergeFrom(Timestamps.parse(ParseSupport.parseString(parser)));
  } catch (ParseException e) {
    throw new InvalidProtocolBufferException(
        "Failed to readValue timestamp: " + parser.getText());
  }
}
项目:curiostack    文件:MessageMarshallerTest.java   
@Test
public void timestamp() throws Exception {
  TestTimestamp message =
      TestTimestamp.newBuilder()
          .setTimestampValue(Timestamps.parse("1970-01-01T00:00:00Z"))
          .build();
  assertMatchesUpstream(message);
}
项目:seldon-core    文件:TimeUtils.java   
@Override
public void merge(JsonElement json, Builder builder) throws InvalidProtocolBufferException {
    try {
        Timestamp value = Timestamps.parse(json.getAsString());
        builder.mergeFrom(value.toByteString());
      } catch (ParseException e) {
        throw new InvalidProtocolBufferException("Failed to parse timestamp: " + json);
      }
}
项目:seldon-core    文件:JsonFormat.java   
private void mergeTimestamp(JsonElement json, Message.Builder builder)
    throws InvalidProtocolBufferException {
  try {
    Timestamp value = Timestamps.parse(json.getAsString());
    builder.mergeFrom(value.toByteString());
  } catch (ParseException e) {
    throw new InvalidProtocolBufferException("Failed to parse timestamp: " + json);
  }
}
项目:seldon-core    文件:TimeUtils.java   
@Override
public void merge(JsonElement json, Builder builder) throws InvalidProtocolBufferException {
    try {
        Timestamp value = Timestamps.parse(json.getAsString());
        builder.mergeFrom(value.toByteString());
      } catch (ParseException e) {
        throw new InvalidProtocolBufferException("Failed to parse timestamp: " + json);
      }
}
项目:seldon-core    文件:JsonFormat.java   
private void mergeTimestamp(JsonElement json, Message.Builder builder)
    throws InvalidProtocolBufferException {
  try {
    Timestamp value = Timestamps.parse(json.getAsString());
    builder.mergeFrom(value.toByteString());
  } catch (ParseException e) {
    throw new InvalidProtocolBufferException("Failed to parse timestamp: " + json);
  }
}
项目:seldon-core    文件:TimeUtils.java   
@Override
public void merge(JsonElement json, Builder builder) throws InvalidProtocolBufferException {
    try {
        Timestamp value = Timestamps.parse(json.getAsString());
        builder.mergeFrom(value.toByteString());
      } catch (ParseException e) {
        throw new InvalidProtocolBufferException("Failed to parse timestamp: " + json);
      }
}
项目:seldon-core    文件:JsonFormat.java   
private void mergeTimestamp(JsonElement json, Message.Builder builder)
    throws InvalidProtocolBufferException {
  try {
    Timestamp value = Timestamps.parse(json.getAsString());
    builder.mergeFrom(value.toByteString());
  } catch (ParseException e) {
    throw new InvalidProtocolBufferException("Failed to parse timestamp: " + json);
  }
}
项目:pubsub    文件:Task.java   
protected Task(StartRequest request, String type, MetricsHandler.MetricName metricName) {
  this.metricsHandler = new MetricsHandler(request.getProject(), type, metricName);
  this.burnInTimeMillis =
      Timestamps.toMillis(Timestamps.add(request.getStartTime(), request.getBurnInDuration()));
  rateLimiter = RateLimiter.create(request.getRequestRate());
  outstandingRequestLimiter = new Semaphore(request.getMaxOutstandingRequests(), false);
}
项目:core-java    文件:LoggingObserverShould.java   
private void assertAtLevel(Level level) {
    final LoggingObserver<Object> observer = getObserver(level);

    assertNotNull(observer);

    // Since we're in the tests mode `Environment` returns `SubstituteLogger` instance.
    final SubstituteLogger log = (SubstituteLogger) observer.log();

    // Restrict the queue size only to the number of calls we want to make.
    final Queue<SubstituteLoggingEvent> queue = Queues.newArrayBlockingQueue(3);
    log.setDelegate(new EventRecodingLogger(log, queue));

    SubstituteLoggingEvent loggingEvent;

    final String value = newUuid();
    observer.onNext(value);
    loggingEvent = queue.poll();
    assertNotNull(loggingEvent);
    assertLogLevel(loggingEvent, level);
    assertContains(loggingEvent, value);
    assertContains(loggingEvent, "onNext");

    final Timestamp currentTime = Time.getCurrentTime();
    final String timeStr = Timestamps.toString(currentTime);
    observer.onNext(currentTime);
    loggingEvent = queue.poll();
    assertNotNull(loggingEvent);
    assertLogLevel(loggingEvent, level);
    assertContains(loggingEvent, timeStr);

    observer.onCompleted();
    loggingEvent = queue.poll();
    assertNotNull(loggingEvent);
    assertLogLevel(loggingEvent, level);
    assertContains(loggingEvent, "onCompleted");
}
项目:core-java    文件:EnricherBuilderShould.java   
@Before
public void setUp() {
    this.builder = EventEnricher.newBuilder();
    this.function = new Function<Timestamp, StringValue>() {
        @Nullable
        @Override
        public StringValue apply(@Nullable Timestamp input) {
            if (input == null) {
                return null;
            }
            return toMessage(Timestamps.toString(input));
        }
    };
    this.fieldEnrichment = FieldEnrichment.of(Timestamp.class, StringValue.class, function);
}
项目:core-java    文件:ERepositoryShould.java   
@Test
public void convert_time_query_to_EntityFilters() {
    final EventStreamQuery query = EventStreamQuery.newBuilder()
                                                   .setAfter(Timestamps.MIN_VALUE)
                                                   .setBefore(Timestamps.MAX_VALUE)
                                                   .build();
    final EntityFilters entityFilters = toEntityFilters(query);
    assertEquals(1, entityFilters.getFilterCount());

    final CompositeColumnFilter compositeFilter = entityFilters.getFilter(0);
    final List<ColumnFilter> columnFilters = compositeFilter.getFilterList();
    assertEquals(CompositeOperator.ALL, compositeFilter.getOperator());
    assertEquals(2, columnFilters.size());
}
项目:core-java    文件:RejectionsShould.java   
@Test
public void convert_throwable_message_to_rejection_message() {
    assertEquals(rejectionMessage, AnyPacker.unpack(rejection.getMessage()));
    assertFalse(rejection.getContext()
                         .getStacktrace()
                         .isEmpty());
    assertTrue(Timestamps.isValid(rejection.getContext()
                                           .getTimestamp()));
    final Command commandFromContext = rejection.getContext()
                                                .getCommand();
    assertEquals(command, commandFromContext);
}
项目:core-java    文件:AggregateMessageDispatcherTestEnv.java   
private static StringValue logItem(String digitalPart) {
    final String str =
            Timestamps.toString(Time.getCurrentTime())
                    + " - "
                    + digitalPart;
    return StringValue.newBuilder()
                      .setValue(str)
                      .build();
}
项目:java-docs-samples    文件:Snippets.java   
/**
 * Demonstrates listing time series headers.
 */
void listTimeSeriesHeaders() throws IOException {
  // [START monitoring_read_timeseries_fields]
  MetricServiceClient metricServiceClient = MetricServiceClient.create();
  String projectId = System.getProperty("projectId");
  ProjectName name = ProjectName.create(projectId);

  // Restrict time to last 20 minutes
  long startMillis = System.currentTimeMillis() - ((60 * 20) * 1000);
  TimeInterval interval = TimeInterval.newBuilder()
      .setStartTime(Timestamps.fromMillis(startMillis))
      .setEndTime(Timestamps.fromMillis(System.currentTimeMillis()))
      .build();

  ListTimeSeriesRequest.Builder requestBuilder = ListTimeSeriesRequest.newBuilder()
      .setNameWithProjectName(name)
      .setFilter("metric.type=\"compute.googleapis.com/instance/cpu/utilization\"")
      .setInterval(interval)
      .setView(ListTimeSeriesRequest.TimeSeriesView.HEADERS);

  ListTimeSeriesRequest request = requestBuilder.build();

  PagedResponseWrappers.ListTimeSeriesPagedResponse response = metricServiceClient
      .listTimeSeries(request);

  System.out.println("Got timeseries headers: ");
  for (TimeSeries ts : response.iterateAll()) {
    System.out.println(ts);
  }
  // [END monitoring_read_timeseries_fields]
}
项目:java-docs-samples    文件:Snippets.java   
/**
 * Demonstrates listing time series using a filter.
 */
void listTimeSeries(String filter) throws IOException {
  // [START monitoring_read_timeseries_simple]
  MetricServiceClient metricServiceClient = MetricServiceClient.create();
  String projectId = System.getProperty("projectId");
  ProjectName name = ProjectName.create(projectId);

  // Restrict time to last 20 minutes
  long startMillis = System.currentTimeMillis() - ((60 * 20) * 1000);
  TimeInterval interval = TimeInterval.newBuilder()
      .setStartTime(Timestamps.fromMillis(startMillis))
      .setEndTime(Timestamps.fromMillis(System.currentTimeMillis()))
      .build();

  ListTimeSeriesRequest.Builder requestBuilder = ListTimeSeriesRequest.newBuilder()
      .setNameWithProjectName(name)
      .setFilter(filter)
      .setInterval(interval);

  ListTimeSeriesRequest request = requestBuilder.build();

  PagedResponseWrappers.ListTimeSeriesPagedResponse response = metricServiceClient
      .listTimeSeries(request);

  System.out.println("Got timeseries: ");
  for (TimeSeries ts : response.iterateAll()) {
    System.out.println(ts);
  }
  // [END monitoring_read_timeseries_simple]
}
项目:java-docs-samples    文件:Snippets.java   
/**
 * Demonstrates listing time series and aggregating them.
 */
void listTimeSeriesAggregrate() throws IOException {
  // [START monitoring_read_timeseries_align]
  MetricServiceClient metricServiceClient = MetricServiceClient.create();
  String projectId = System.getProperty("projectId");
  ProjectName name = ProjectName.create(projectId);

  // Restrict time to last 20 minutes
  long startMillis = System.currentTimeMillis() - ((60 * 20) * 1000);
  TimeInterval interval = TimeInterval.newBuilder()
      .setStartTime(Timestamps.fromMillis(startMillis))
      .setEndTime(Timestamps.fromMillis(System.currentTimeMillis()))
      .build();

  Aggregation aggregation = Aggregation.newBuilder()
      .setAlignmentPeriod(Duration.newBuilder().setSeconds(600).build())
      .setPerSeriesAligner(Aggregation.Aligner.ALIGN_MEAN)
      .build();

  ListTimeSeriesRequest.Builder requestBuilder = ListTimeSeriesRequest.newBuilder()
      .setNameWithProjectName(name)
      .setFilter("metric.type=\"compute.googleapis.com/instance/cpu/utilization\"")
      .setInterval(interval)
      .setAggregation(aggregation);

  ListTimeSeriesRequest request = requestBuilder.build();

  PagedResponseWrappers.ListTimeSeriesPagedResponse response = metricServiceClient
      .listTimeSeries(request);

  System.out.println("Got timeseries: ");
  for (TimeSeries ts : response.iterateAll()) {
    System.out.println(ts);
  }
  // [END monitoring_read_timeseries_align]
}
项目:java-docs-samples    文件:Snippets.java   
/**
 * Demonstrates listing time series and aggregating and reducing them.
 */
void listTimeSeriesReduce() throws IOException {
  // [START monitoring_read_timeseries_reduce]
  MetricServiceClient metricServiceClient = MetricServiceClient.create();
  String projectId = System.getProperty("projectId");
  ProjectName name = ProjectName.create(projectId);

  // Restrict time to last 20 minutes
  long startMillis = System.currentTimeMillis() - ((60 * 20) * 1000);
  TimeInterval interval = TimeInterval.newBuilder()
      .setStartTime(Timestamps.fromMillis(startMillis))
      .setEndTime(Timestamps.fromMillis(System.currentTimeMillis()))
      .build();

  Aggregation aggregation = Aggregation.newBuilder()
      .setAlignmentPeriod(Duration.newBuilder().setSeconds(600).build())
      .setPerSeriesAligner(Aggregation.Aligner.ALIGN_MEAN)
      .setCrossSeriesReducer(Aggregation.Reducer.REDUCE_MEAN)
      .build();

  ListTimeSeriesRequest.Builder requestBuilder = ListTimeSeriesRequest.newBuilder()
      .setNameWithProjectName(name)
      .setFilter("metric.type=\"compute.googleapis.com/instance/cpu/utilization\"")
      .setInterval(interval)
      .setAggregation(aggregation);

  ListTimeSeriesRequest request = requestBuilder.build();

  PagedResponseWrappers.ListTimeSeriesPagedResponse response = metricServiceClient
      .listTimeSeries(request);

  System.out.println("Got timeseries: ");
  for (TimeSeries ts : response.iterateAll()) {
    System.out.println(ts);
  }
  // [END monitoring_read_timeseries_reduce]
}
项目:secor    文件:ProtobufMessageParser.java   
public long extractTimestampMillis(String topic, final byte[] bytes) throws IOException {
    if (timestampFieldPath != null) {
        com.google.protobuf.Message decodedMessage = protobufUtil.decodeProtobufOrJsonMessage(topic,
                bytes);
        int i = 0;
        for (; i < timestampFieldPath.length - 1; ++i) {
            decodedMessage = (com.google.protobuf.Message) decodedMessage
                    .getField(decodedMessage.getDescriptorForType().findFieldByName(timestampFieldPath[i]));
        }
        Object timestampObject = decodedMessage
                .getField(decodedMessage.getDescriptorForType().findFieldByName(timestampFieldPath[i]));
        if (timestampObject instanceof com.google.protobuf.Timestamp){
            return Timestamps.toMillis((com.google.protobuf.Timestamp) timestampObject);
        }else {
            return toMillis((Long) timestampObject);
        }
    } else {
        // Assume that the timestamp field is the first field, is required,
        // and is a uint64.

        CodedInputStream input = CodedInputStream.newInstance(bytes);
        // Don't really care about the tag, but need to read it to get, to
        // the payload.
        input.readTag();
        return toMillis(input.readUInt64());
    }
}
项目:bazel    文件:BuildEventServiceProtoUtil.java   
public PublishLifecycleEventRequest buildEnqueued() {
  return lifecycleEvent(projectId, 1,
          com.google.devtools.build.v1.BuildEvent.newBuilder()
              .setEventTime(Timestamps.fromMillis(clock.currentTimeMillis()))
              .setBuildEnqueued(BuildEnqueued.newBuilder()))
      .build();
}
项目:bazel    文件:BuildEventServiceProtoUtil.java   
public PublishLifecycleEventRequest buildFinished(Result result) {
  return lifecycleEvent(projectId, 2,
          com.google.devtools.build.v1.BuildEvent.newBuilder()
              .setEventTime(Timestamps.fromMillis(clock.currentTimeMillis()))
              .setBuildFinished(
                  BuildFinished.newBuilder()
                      .setStatus(BuildStatus.newBuilder().setResult(result))))
      .build();
}
项目:bazel    文件:BuildEventServiceProtoUtil.java   
public PublishLifecycleEventRequest invocationStarted() {
  return lifecycleEvent(projectId, 1,
          com.google.devtools.build.v1.BuildEvent.newBuilder()
              .setEventTime(Timestamps.fromMillis(clock.currentTimeMillis()))
              .setInvocationAttemptStarted(
                  InvocationAttemptStarted.newBuilder().setAttemptNumber(1)))
      .build();
}
项目:bazel    文件:BuildEventServiceProtoUtil.java   
public PublishLifecycleEventRequest invocationFinished(Result result) {
  return lifecycleEvent(projectId, 2,
          com.google.devtools.build.v1.BuildEvent.newBuilder()
              .setEventTime(Timestamps.fromMillis(clock.currentTimeMillis()))
              .setInvocationAttemptFinished(
                  InvocationAttemptFinished.newBuilder()
                      .setInvocationStatus(BuildStatus.newBuilder().setResult(result))))
      .build();
}
项目:grpc-java    文件:GrpclbLoadBalancerTest.java   
private void assertNextReport(
    InOrder inOrder, StreamObserver<LoadBalanceRequest> lbRequestObserver,
    long loadReportIntervalMillis, ClientStats expectedReport) {
  assertEquals(0, fakeClock.forwardTime(loadReportIntervalMillis - 1, TimeUnit.MILLISECONDS));
  inOrder.verifyNoMoreInteractions();
  assertEquals(1, fakeClock.forwardTime(1, TimeUnit.MILLISECONDS));
  assertEquals(1, fakeClock.numPendingTasks());
  inOrder.verify(lbRequestObserver).onNext(
      eq(LoadBalanceRequest.newBuilder()
          .setClientStats(
              ClientStats.newBuilder(expectedReport)
              .setTimestamp(Timestamps.fromMillis(fakeClock.currentTimeMillis()))
              .build())
          .build()));
}
项目:curiostack    文件:ProtoTimestamps.java   
/** Converts a {@link Timestamp} to {@link LocalDateTime}. */
public static LocalDateTime toLocalDateTime(Timestamp timestamp, ZoneOffset zone) {
  return LocalDateTime.ofEpochSecond(Timestamps.toSeconds(timestamp), timestamp.getNanos(), zone);
}
项目:curiostack    文件:ProtoTimestamps.java   
/** Converts a {@link LocalDateTime} to {@link Timestamp}. */
public static Timestamp fromLocalDateTime(LocalDateTime localDateTime, ZoneOffset zone) {
  return Timestamps.fromNanos(
      TimeUnit.SECONDS.toNanos(localDateTime.toEpochSecond(zone)) + localDateTime.getNano());
}
项目:curiostack    文件:WellKnownTypeMarshaller.java   
@Override
public void doWrite(Timestamp message, JsonGenerator gen) throws IOException {
  gen.writeString(Timestamps.toString(message));
}