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


Java Duration类代码示例

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


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

示例1: setSchedule

import com.google.protobuf.Duration; //导入依赖的package包/类
/**
 * Updates {@linkplain CommandContext.Schedule command schedule}.
 *
 * @param command        a command to update
 * @param delay          a {@linkplain CommandContext.Schedule#getDelay() delay} to set
 * @param schedulingTime the time when the command was scheduled by the {@code CommandScheduler}
 * @return an updated command
 */
static Command setSchedule(Command command, Duration delay, Timestamp schedulingTime) {
    checkNotNull(command);
    checkNotNull(delay);
    checkNotNull(schedulingTime);
    checkValid(schedulingTime);

    final CommandContext context = command.getContext();
    final CommandContext.Schedule scheduleUpdated = context.getSchedule()
                                                           .toBuilder()
                                                           .setDelay(delay)
                                                           .build();
    final CommandContext contextUpdated = context.toBuilder()
                                                 .setSchedule(scheduleUpdated)
                                                 .build();

    final Command.SystemProperties sysProps = command.getSystemProperties()
                                                     .toBuilder()
                                                     .setSchedulingTime(schedulingTime)
                                                     .build();
    final Command result = command.toBuilder()
                                  .setContext(contextUpdated)
                                  .setSystemProperties(sysProps)
                                  .build();
    return result;
}
 
开发者ID:SpineEventEngine,项目名称:core-java,代码行数:34,代码来源:CommandScheduler.java

示例2: getDelayMilliseconds

import com.google.protobuf.Duration; //导入依赖的package包/类
private static long getDelayMilliseconds(Command command) {
    final Schedule schedule = command.getContext().getSchedule();
    final Duration delay = schedule.getDelay();
    final long delaySec = delay.getSeconds();
    final long delayMillisFraction = delay.getNanos() / NANOS_IN_MILLISECOND;

    /**
     * Maximum value of {@link Duration#getSeconds()} is
     * <a href="https://github.com/google/protobuf/blob/master/src/google/protobuf/duration.proto"+315,576,000,000.</a>.
     *
     * {@link Long.MAX_VALUE} is +9,223,372,036,854,775,807. That's why it is safe to multiply
     * {@code delaySec * MILLIS_IN_SECOND}.
     */
    final long absoluteMillis = delaySec * MILLIS_IN_SECOND + delayMillisFraction;
    return absoluteMillis;
}
 
开发者ID:SpineEventEngine,项目名称:core-java,代码行数:17,代码来源:ExecutorCommandScheduler.java

示例3: sequenceFor

import com.google.protobuf.Duration; //导入依赖的package包/类
/**
 * Returns several records sorted by timestamp ascending.
 *
 * @param timestamp1 the timestamp of first record.
 */
public static List<AggregateEventRecord> sequenceFor(ProjectId id, Timestamp timestamp1) {
    final Duration delta = seconds(10);
    final Timestamp timestamp2 = add(timestamp1, delta);
    final Timestamp timestamp3 = add(timestamp2, delta);

    final TestEventFactory eventFactory = newInstance(Given.class);

    final Event e1 = eventFactory.createEvent(projectCreated(id, projectName(id)),
                                              null,
                                              timestamp1);
    final AggregateEventRecord record1 = StorageRecord.create(timestamp1, e1);

    final Event e2 = eventFactory.createEvent(taskAdded(id),
                                              null,
                                              timestamp2);
    final AggregateEventRecord record2 = StorageRecord.create(timestamp2, e2);

    final Event e3 = eventFactory.createEvent(EventMessage.projectStarted(id),
                                              null,
                                              timestamp3);
    final AggregateEventRecord record3 = StorageRecord.create(timestamp3, e3);

    return newArrayList(record1, record2, record3);
}
 
开发者ID:SpineEventEngine,项目名称:core-java,代码行数:30,代码来源:Given.java

示例4: reschedule_commands_from_storage

import com.google.protobuf.Duration; //导入依赖的package包/类
@Test
public void reschedule_commands_from_storage() {
    final Timestamp schedulingTime = minutesAgo(3);
    final Duration delayPrimary = Durations2.fromMinutes(5);
    final Duration newDelayExpected = Durations2.fromMinutes(2); // = 5 - 3
    final List<Command> commandsPrimary = newArrayList(createProject(),
                                                       addTask(),
                                                       startProject());
    storeAsScheduled(commandsPrimary, delayPrimary, schedulingTime);

    commandBus.rescheduleCommands();

    final ArgumentCaptor<Command> commandCaptor = ArgumentCaptor.forClass(Command.class);
    verify(scheduler, times(commandsPrimary.size())).schedule(commandCaptor.capture());
    final List<Command> commandsRescheduled = commandCaptor.getAllValues();
    for (Command cmd : commandsRescheduled) {
        final long actualDelay = getDelaySeconds(cmd);
        Tests.assertSecondsEqual(newDelayExpected.getSeconds(), actualDelay, /*maxDiffSec=*/1);
    }
}
 
开发者ID:SpineEventEngine,项目名称:core-java,代码行数:21,代码来源:CommandSchedulingShould.java

示例5: set_expired_scheduled_command_status_to_error_if_time_to_post_them_passed

import com.google.protobuf.Duration; //导入依赖的package包/类
@Test
public void set_expired_scheduled_command_status_to_error_if_time_to_post_them_passed() {
    final List<Command> commands = newArrayList(createProject(),
                                                addTask(),
                                                startProject());
    final Duration delay = fromMinutes(5);
    final Timestamp schedulingTime = TimeTests.Past.minutesAgo(10); // time to post passed
    storeAsScheduled(commands, delay, schedulingTime);

    commandBus.rescheduleCommands();

    for (Command cmd : commands) {
        final CommandEnvelope envelope = CommandEnvelope.of(cmd);
        final Message msg = envelope.getMessage();
        final CommandId id = envelope.getId();

        // Check the expired status error was set.
        final ProcessingStatus status = getProcessingStatus(envelope);

        // Check that the logging was called.
        verify(log).errorExpiredCommand(msg, id);

        final Error expected = CommandExpiredException.commandExpired(cmd);
        assertEquals(expected, status.getError());
    }
}
 
开发者ID:SpineEventEngine,项目名称:core-java,代码行数:27,代码来源:CommandStoreShould.java

示例6: toString

import com.google.protobuf.Duration; //导入依赖的package包/类
/**
 * Convert Duration to string format. The string format will contains 3, 6, or 9 fractional digits
 * depending on the precision required to represent the exact Duration value. For example: "1s",
 * "1.010s", "1.000000100s", "-3.100s" The range that can be represented by Duration is from
 * -315,576,000,000 to +315,576,000,000 inclusive (in seconds).
 *
 * @return The string representation of the given duration.
 * @throws IllegalArgumentException if the given duration is not in the valid range.
 */
public static String toString(Duration duration) {
  checkValid(duration);

  long seconds = duration.getSeconds();
  int nanos = duration.getNanos();

  StringBuilder result = new StringBuilder();
  if (seconds < 0 || nanos < 0) {
    result.append("-");
    seconds = -seconds;
    nanos = -nanos;
  }
  result.append(seconds);
  if (nanos != 0) {
    result.append(".");
    result.append(Timestamps.formatNanos(nanos));
  }
  result.append("s");
  return result.toString();
}
 
开发者ID:bazelbuild,项目名称:bazel,代码行数:30,代码来源:Durations.java

示例7: normalizedDuration

import com.google.protobuf.Duration; //导入依赖的package包/类
static Duration normalizedDuration(long seconds, int nanos) {
  if (nanos <= -NANOS_PER_SECOND || nanos >= NANOS_PER_SECOND) {
    seconds = checkedAdd(seconds, nanos / NANOS_PER_SECOND);
    nanos %= NANOS_PER_SECOND;
  }
  if (seconds > 0 && nanos < 0) {
    nanos += NANOS_PER_SECOND; // no overflow since nanos is negative (and we're adding)
    seconds--; // no overflow since seconds is positive (and we're decrementing)
  }
  if (seconds < 0 && nanos > 0) {
    nanos -= NANOS_PER_SECOND; // no overflow since nanos is positive (and we're subtracting)
    seconds++; // no overflow since seconds is negative (and we're incrementing)
  }
  Duration duration = Duration.newBuilder().setSeconds(seconds).setNanos(nanos).build();
  return checkValid(duration);
}
 
开发者ID:bazelbuild,项目名称:bazel,代码行数:17,代码来源:Durations.java

示例8: normalizedDuration

import com.google.protobuf.Duration; //导入依赖的package包/类
private static Duration normalizedDuration(long seconds, int nanos) {
  if (nanos <= -NANOS_PER_SECOND || nanos >= NANOS_PER_SECOND) {
    seconds += nanos / NANOS_PER_SECOND;
    nanos %= NANOS_PER_SECOND;
  }
  if (seconds > 0 && nanos < 0) {
    nanos += NANOS_PER_SECOND;
    seconds -= 1;
  }
  if (seconds < 0 && nanos > 0) {
    nanos -= NANOS_PER_SECOND;
    seconds += 1;
  }
  if (seconds < DURATION_SECONDS_MIN || seconds > DURATION_SECONDS_MAX) {
    throw new IllegalArgumentException("Duration is out of valid range.");
  }
  return Duration.newBuilder().setSeconds(seconds).setNanos(nanos).build();
}
 
开发者ID:bazelbuild,项目名称:bazel,代码行数:19,代码来源:TimeUtil.java

示例9: testDurationConversion

import com.google.protobuf.Duration; //导入依赖的package包/类
public void testDurationConversion() throws Exception {
  Duration duration = TimeUtil.parseDuration("1.111111111s");
  assertEquals(1111111111, TimeUtil.toNanos(duration));
  assertEquals(1111111, TimeUtil.toMicros(duration));
  assertEquals(1111, TimeUtil.toMillis(duration));
  duration = TimeUtil.createDurationFromNanos(1111111111);
  assertEquals("1.111111111s", TimeUtil.toString(duration));
  duration = TimeUtil.createDurationFromMicros(1111111);
  assertEquals("1.111111s", TimeUtil.toString(duration));
  duration = TimeUtil.createDurationFromMillis(1111);
  assertEquals("1.111s", TimeUtil.toString(duration));

  duration = TimeUtil.parseDuration("-1.111111111s");
  assertEquals(-1111111111, TimeUtil.toNanos(duration));
  assertEquals(-1111111, TimeUtil.toMicros(duration));
  assertEquals(-1111, TimeUtil.toMillis(duration));
  duration = TimeUtil.createDurationFromNanos(-1111111111);
  assertEquals("-1.111111111s", TimeUtil.toString(duration));
  duration = TimeUtil.createDurationFromMicros(-1111111);
  assertEquals("-1.111111s", TimeUtil.toString(duration));
  duration = TimeUtil.createDurationFromMillis(-1111);
  assertEquals("-1.111s", TimeUtil.toString(duration));
}
 
开发者ID:bazelbuild,项目名称:bazel,代码行数:24,代码来源:TimeUtilTest.java

示例10: doMerge

import com.google.protobuf.Duration; //导入依赖的package包/类
@Override
public void doMerge(JsonParser parser, int unused, Message.Builder messageBuilder)
    throws IOException {
  Duration.Builder builder = (Duration.Builder) messageBuilder;
  try {
    builder.mergeFrom(Durations.parse(ParseSupport.parseString(parser)));
  } catch (ParseException e) {
    throw new InvalidProtocolBufferException(
        "Failed to readValue duration: " + parser.getText());
  }
}
 
开发者ID:curioswitch,项目名称:curiostack,代码行数:12,代码来源:WellKnownTypeMarshaller.java

示例11: mergeDuration

import com.google.protobuf.Duration; //导入依赖的package包/类
private void mergeDuration(JsonElement json, Message.Builder builder)
    throws InvalidProtocolBufferException {
  try {
    Duration value = Durations.parse(json.getAsString());
    builder.mergeFrom(value.toByteString());
  } catch (ParseException e) {
    throw new InvalidProtocolBufferException("Failed to parse duration: " + json);
  }
}
 
开发者ID:SeldonIO,项目名称:seldon-core,代码行数:10,代码来源:JsonFormat.java

示例12: Watchdog

import com.google.protobuf.Duration; //导入依赖的package包/类
public Watchdog(Duration petTimeout, Runnable runnable) {
  this.runnable = runnable;
  this.petTimeout = petTimeout;
  stopped = false;
  done = false;
  pet();
}
 
开发者ID:bazelbuild,项目名称:bazel-buildfarm,代码行数:8,代码来源:Watchdog.java

示例13: setUp

import com.google.protobuf.Duration; //导入依赖的package包/类
@Before
public void setUp() throws Exception {
  String uniqueServerName = "in-process server for " + getClass();

  memoryInstanceConfig = MemoryInstanceConfig.newBuilder()
      .setListOperationsDefaultPageSize(1024)
      .setListOperationsMaxPageSize(16384)
      .setTreeDefaultPageSize(1024)
      .setTreeMaxPageSize(16384)
      .setOperationPollTimeout(Duration.newBuilder()
          .setSeconds(10)
          .setNanos(0))
      .setOperationCompletedDelay(Duration.newBuilder()
          .setSeconds(10)
          .setNanos(0))
      .build();

  BuildFarmServerConfig.Builder configBuilder =
      BuildFarmServerConfig.newBuilder().setPort(0);
  configBuilder.addInstancesBuilder()
      .setName("memory")
      .setMemoryInstanceConfig(memoryInstanceConfig);

  server = new BuildFarmServer(
      InProcessServerBuilder.forName(uniqueServerName).directExecutor(),
      configBuilder.build());
  server.start();
  inProcessChannel = InProcessChannelBuilder.forName(uniqueServerName)
      .directExecutor().build();
}
 
开发者ID:bazelbuild,项目名称:bazel-buildfarm,代码行数:31,代码来源:BuildFarmServerTest.java

示例14: convert

import com.google.protobuf.Duration; //导入依赖的package包/类
@Override
public Duration convert(String value) {
  try {
    if (value.isEmpty()) {
      return Durations.fromMillis(0);
    }
    long millis = 0;
    boolean negative = value.startsWith("-");
    int index = negative ? 1 : 0;
    Pattern unitPattern =
        Pattern.compile(
            "(?x) (?<whole>[0-9]+)? (?<frac>\\.[0-9]*)? (?<unit>d|h|ms?|s)",
            Pattern.CASE_INSENSITIVE);
    Matcher matcher = unitPattern.matcher(value);
    while (matcher.find(index) && matcher.start() == index) {
      Preconditions.checkArgument(CharMatcher.inRange('0', '9').matchesAnyOf(matcher.group(0)));
      long whole = Long.parseLong(MoreObjects.firstNonNull(matcher.group("whole"), "0"));
      double frac =
          Double.parseDouble("0" + MoreObjects.firstNonNull(matcher.group("frac"), ""));
      int millisPerUnit = millisPerUnit(matcher.group("unit"));
      millis += millisPerUnit * whole;
      millis += (long) (millisPerUnit * frac);
      index = matcher.end();
    }
    if (index < value.length()) {
      throw new IllegalArgumentException("Could not parse entire duration");
    }
    if (negative) {
      millis = -millis;
    }
    return Durations.fromMillis(millis);
  } catch (Exception e) {
    throw new ParameterException(
        getErrorString(value, "A duration string must include units (d|h|m|s|ms)."));
  }
}
 
开发者ID:GoogleCloudPlatform,项目名称:pubsub,代码行数:37,代码来源:Driver.java

示例15: testDurationIsNotProto2

import com.google.protobuf.Duration; //导入依赖的package包/类
@Test
public void testDurationIsNotProto2() {
  // Duration is a core Protocol Buffers type that uses proto3 syntax.
  thrown.expect(IllegalArgumentException.class);
  thrown.expectMessage(Duration.class.getCanonicalName());
  thrown.expectMessage("in file " + Duration.getDescriptor().getFile().getName());

  checkProto2Syntax(Duration.class, ExtensionRegistry.getEmptyRegistry());
}
 
开发者ID:apache,项目名称:beam,代码行数:10,代码来源:ProtobufUtilTest.java


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