Java 类java.time.Instant 实例源码

项目:filter-sort-jooq-api    文件:TransferTimingPageResource.java   
/**
 * Export result to csv
 *
 * @param requestParams the query of the transfer timing search
 * @param pageable      the pagination information
 * @return downloadable csv
 */
@GetMapping(value = "/transfer-timings.csv", produces = CsvMediaType.TEXT_CSV_VALUE)
@Timed
public ResponseEntity<List<TransferTimingListingDTO>> exportCsv(@RequestParam Map<String, String> requestParams, @ApiParam Pageable pageable) {
    /* ==========================
     * In this example you might not understand as I did not put the other part of code but I have a AbstractHttpMessageConverter
     * that converts object or list of objects to a CSV
     * ==========================
     */
    final List<TransferTimingListingDTO> list;

    if (requestParams != null) {
        list = transferTimingPageService.searchWithoutPaging(requestParams, pageable);
    } else {
        list = transferTimingPageService.getAllWithoutPaging(pageable);
    }

    String filename = "visual-timings-" + Instant.now().getEpochSecond() + ".csv";

    HttpHeaders headers = new HttpHeaders();
    headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment;filename=" + filename);
    headers.add("X-Save-As", filename);

    return new ResponseEntity<>(list, headers, HttpStatus.OK);
}
项目:yuvi    文件:OffHeapVarBitMetricStoreTest.java   
@Test(expected = ChronicleHashClosedException.class)
public void testCloseWithoutPersistedFile() {
  MetricStore heapStore = new VarBitMetricStore();
  long uuid1 = 1;
  long ts = Instant.now().getEpochSecond();
  double value = 100;

  heapStore.addPoint(uuid1, ts, value);
  OffHeapVarBitMetricStore offheapStore1 =
      OffHeapVarBitMetricStore.toOffHeapStore(getSeriesMap(heapStore), testFileName, "");

  assertEquals(1, offheapStore1.getSeriesMap().size());
  List<Point> points = offheapStore1.getSeries(uuid1);
  assertEquals(1, points.size());
  assertEquals(ts, points.get(0).getTs());
  assertEquals(value, points.get(0).getVal(), delta);

  offheapStore1.close();
  offheapStore1.getSeriesMap().size();
}
项目:matrix-appservice-email    文件:SubscriptionManager.java   
private synchronized _BridgeSubscription build(String subId, String sourceMxId, Instant timestamp, String email, String threadId, String mxId, String roomId) {
    log.info("Creating new subscription {} for email {} with threadId {} and matrix id {} in room {}",
            subId,
            email,
            threadId,
            mxId,
            roomId);

    _EmailEndPoint emEp = emMgr.getEndpoint(email, threadId);
    _MatrixEndPoint mxEp = mxMgr.getEndpoint(mxId, roomId);
    String eKey = emMgr.getKey(email, threadId);
    String mKey = mxMgr.getKey(mxId, roomId);

    _BridgeSubscription sub = new BridgeSubscription(subId, sourceMxId, timestamp, formatter, eKey, emEp, mKey, mxEp);
    sub.addListener(this::remove);

    subs.put(subId, sub);
    subsEmailKey.put(eKey, new WeakReference<>(sub));
    subsMatrixKey.put(mKey, new WeakReference<>(sub));

    return sub;
}
项目:vars-annotation    文件:AVFImageCaptureServiceTest.java   
@Test
public void testImageCapture2() throws IOException {
    AVFImageCaptureService service = AVFImageCaptureService.getInstance();
    AVFImageCapture ic = service.getImageCapture();
    String[] devices = ic.videoDevicesAsStrings();
    if (devices.length > 0) {
        ic.startSessionWithNamedDevice(devices[0]);
        Path path = Paths.get("target",
                getClass().getSimpleName() + "-1-" + Instant.now() + ".png");
        Optional<Image> png = ic.capture(path.toFile());
        ic.stopSession();
        Assert.assertTrue(png.isPresent());

    }
    else {
        System.err.println("No frame capture devices were found");
    }
}
项目:trading4j    文件:TradeTracker.java   
@Override
public Optional<Failed> changeCloseConditionsOfOrder(final CloseConditions conditions) {
    final Optional<Failed> failed = orderManagement.changeCloseConditionsOfOrder(conditions);

    final Instant time = currentTime.get();
    events.add(new TradeEvent(CLOSE_CONDITIONS_CHANGED, time, "expert advisor changed close conditions",
            conditions));
    if (failed.isPresent()) {
        events.add(new TradeEvent(CLOSE_CONDITIONS_CHANGED, time,
                "broker faild to changed close conditions of expert advisor: " + failed.get(),
                currentCloseConditions));
    } else {
        currentCloseConditions = conditions;
    }

    return failed;
}
项目:swblocks-decisiontree    文件:CommisionRuleSetSupplier.java   
/**
 * Helper method to add a DateRange Commission Rule to the Commission ruleset.
 * Should only be called from getCommissionRuleSetWithDateRanges.
 */
private static Builder<RuleSetBuilder, DecisionTreeRuleSet> addDateRangeRule(
        final Builder<RuleSetBuilder, DecisionTreeRuleSet> ruleSetBuilder,
        final String startDate, final String endDate,
        final String exmethod, final String exchange,
        final String product, final String region,
        final String asset, final Instant start,
        final Instant finish, final long ruleId, final String rate) {
    return ruleSetBuilder.with(RuleSetBuilder::rule, RuleBuilder.creator()
            .with(RuleBuilder::input, Arrays.asList("DR:" + startDate + "|" + endDate,
                    exmethod, exchange, product, region, asset))
            .with(RuleBuilder::start, start)
            .with(RuleBuilder::end, finish)
            .with(RuleBuilder::setId, new UUID(0L, ruleId))
            .with(RuleBuilder::setCode, new UUID(0L, ruleId))
            .with(RuleBuilder::output, Collections.singletonMap("Rate", rate)));
}
项目:JAddOn    文件:Client.java   
private final int connect(int times) {
    times++;
    if(times > reconnection_tries) {
        instant_started = null;
        return times;
    }
    try {
        StaticStandard.log(String.format("[CLIENT] Started connecting to %s (Try: %d)", formatAddressAndPort(), times));
        socket = new Socket(inetaddress, port);
        setSocket(socket);
        instant_started = Instant.now();
        connected = true;
        if(!isServerClient) {
            send(MessageState.LOGIN);
        }
        disconnected = false;
        StaticStandard.log("[CLIENT] Connected successfully to " + formatAddressAndPort());
    } catch (Exception ex) {
        StaticStandard.logErr("[CLIENT] Error while connecting to server: " + ex);
        instant_started = null;
    }
    isConnected(times);
    return times;
}
项目:setra    文件:MessageSenderService.java   
/**
 * Stores a new secure message and return the senderId.
 */
public String storeMessage(final String message, final List<SecretFile> files,
                           final KeyIv encryptionKey,
                           final byte[] linkSecret,
                           final String password,
                           final Instant expiration) {

    final boolean isMessagePasswordProtected = password != null;

    final String senderId = newRandomId();

    final String receiverId = storeMessage(
        senderId, message, encryptionKey, files,
        linkSecret, password, expiration);

    saveSenderMessage(senderId,
        new SenderMessage(senderId, receiverId, isMessagePasswordProtected, expiration));

    return senderId;
}
项目:Chronetic    文件:ChronoRangeTest.java   
@Test
public void chronoRangeCompareTest10() {
    ChronoSeries chronoSeries = ChronoSeries.of(
            Instant.parse("2017-02-28T08:48:11Z"),
            Instant.parse("2017-02-28T08:48:12Z"),
            Instant.parse("2017-02-28T08:48:13Z"),
            Instant.parse("2017-02-28T08:48:14Z"),
            Instant.parse("2017-02-28T08:48:15Z")
    );
    ISeq<ChronoGene> genes = ISeq.of(
            new ChronoGene(new ChronoPattern(ChronoScaleUnit.asFactual(chronoSeries, ChronoUnit.SECONDS), 0, 10)),
            new ChronoGene(new ChronoPattern(ChronoScaleUnit.asFactual(chronoSeries, ChronoUnit.SECONDS), 0, 11))
    );
    ChronoRange chronoRange = ChronoRange.getChronoRange(chronoSeries, genes);

    genes = ISeq.of(
            new ChronoGene(new ChronoPattern(ChronoScaleUnit.asFactual(chronoSeries, ChronoUnit.SECONDS), 0, 11)),
            new ChronoGene(new ChronoPattern(ChronoScaleUnit.asFactual(chronoSeries, ChronoUnit.SECONDS), 0, 10))
    );
    ChronoRange chronoRange2 = ChronoRange.getChronoRange(chronoSeries, genes);

    assertTrue(chronoRange.isSameChronoRange(chronoRange2));
}
项目:trellis-rosid-file    文件:LdpContainerTest.java   
@Test
public void testResourcePast() {
    final Instant time = parse("2017-02-15T11:00:00Z");
    final Resource res = VersionedResource.find(file, identifier, time).get();
    assertEquals(identifier, res.getIdentifier());
    assertFalse(res.hasAcl());
    assertEquals(LDP.Container, res.getInteractionModel());
    assertFalse(res.getMembershipResource().isPresent());
    assertFalse(res.getMemberRelation().isPresent());
    assertFalse(res.getMemberOfRelation().isPresent());
    assertFalse(res.getInsertedContentRelation().isPresent());
    assertFalse(res.getBinary().isPresent());
    assertTrue(res.isMemento());
    assertFalse(res.getInbox().isPresent());
    assertEquals(parse("2017-02-15T10:05:00Z"), res.getModified());
    assertEquals(0L, res.getTypes().size());
    assertEquals(0L, res.stream().filter(TestUtils.isContainment.or(TestUtils.isMembership)).count());

    final List<Triple> triples = res.stream().filter(TestUtils.isUserManaged).map(Quad::asTriple).collect(toList());
    assertEquals(0L, triples.size());

    final List<VersionRange> mementos = res.getMementos();
    assertEquals(1L, mementos.size());
    assertEquals(parse("2017-02-15T10:05:00Z"), mementos.get(0).getFrom());
    assertEquals(parse("2017-02-15T11:15:00Z"), mementos.get(0).getUntil());
}
项目:BeamTeamDiscordBot    文件:JDAManager.java   
public static MessageEmbed buildGoLiveEmbed(BTBBeamChannel channel) {
    return new EmbedBuilder()
            .setTitle(String.format("%s is now live!", channel.user.username),
                    String.format("https://beam.pro/%s", channel.user.username))
            .setThumbnail(String.format("https://beam.pro/api/v1/users/%d/avatar?_=%d", channel.user.id,
                    new Random().nextInt()))
            .setDescription(StringUtils.isBlank(channel.user.bio) ? "No bio" : channel.user.bio)
            .addField(channel.name, channel.type == null ? "No game selected" : channel.type.name, false)
            .addField("Followers", Integer.toString(channel.numFollowers), true)
            .addField("Views", Integer.toString(channel.viewersTotal), true)
            .addField("Rating", Enums.serializedName(channel.audience), true)
            .setImage(String.format("https://thumbs.beam.pro/channel/%d.small.jpg?_=%d", channel.id,
                    new Random().nextInt()))
            .setFooter("Beam.pro", CommandHelper.BEAM_LOGO_URL).setTimestamp(Instant.now())
            .setColor(CommandHelper.COLOR).build();
}
项目:carnotzet    文件:DockerRegistry.java   
private static Instant getLocalImageTimestamp(String imageName) {
    // Use docker inspect
    try {
        String isoDatetime = DefaultCommandRunner.INSTANCE.runCommandAndCaptureOutput("docker", "inspect", "-f", "{{.Created}}", imageName);
        return Instant.from(DateTimeFormatter.ISO_ZONED_DATE_TIME.parse(isoDatetime));
    }
    catch (RuntimeException e) {
        log.debug("Could not determine timestamp of local image [" + imageName + "], assuming it doesn't exist on the local docker host", e);
        return null;
    }
}
项目:cloud-dataflow-nyc-taxi-tycoon    文件:RidePoint.java   
public TableRow toTableRow() {
  TableRow result = new TableRow();
  result.set("latitude", lat);
  result.set("longitude", lon);
  result.set("ride_id", rideId);
  result.set("timestamp", Instant.ofEpochMilli(timestamp).toString());
  result.set("ride_status", status);
  return result;
}
项目:java-debug    文件:UsageDataStore.java   
private synchronized void enqueue(Map<String, String> entry) {
    if (queue.size() > QUEUE_MAX_SIZE) {
        queue.poll();
    }
    if (entry != null) {
        entry.put(TIMESTAMP_NAME, Instant.now().toString());
        queue.add(entry);
    }
}
项目:Supreme-Bot    文件:GuildVoiceLogger.java   
@Override
public final void onGuildVoiceMute(GuildVoiceMuteEvent event) {
    if (!LOG_MUTES) {
        return;
    }
    Standard.log(Instant.now(), event.getGuild(), LOG_NAME, LOG_CHANNEL_ID_VOICE, LOG_TEXT_VOICE_MUTE, "[%1$s] [%2$s] %3$s was %4$s", LOG_DATE_TIME_FORMAT, Config.CONFIG.getUserNameForUser(event.getMember().getUser(), event.getGuild(), true), (event.isMuted() ? "muted" : "unmuted"));
}
项目:cactoos    文件:DateAsText.java   
/**
 * Formats the milliseconds as date using the format and the locale.
 * @param milliseconds Milliseconds to format as date.
 * @param format The format to use.
 * @param locale The locale to use for the format.
 */
public DateAsText(final long milliseconds, final String format,
    final Locale locale) {
    this(
        ZonedDateTime.ofInstant(
            Instant.ofEpochMilli(milliseconds), ZoneId.of("UTC")
        ),
        DateTimeFormatter.ofPattern(format, locale)
    );
}
项目:jdk8u-jdk    文件:TCKInstant.java   
@Test(dataProvider="periodUntilUnit")
public void test_until_TemporalUnit_between(long seconds1, int nanos1, long seconds2, long nanos2, TemporalUnit unit, long expected) {
    Instant i1 = Instant.ofEpochSecond(seconds1, nanos1);
    Instant i2 = Instant.ofEpochSecond(seconds2, nanos2);
    long amount = unit.between(i1, i2);
    assertEquals(amount, expected);
}
项目:xm-ms-entity    文件:TypeKeyValidatorIntTest.java   
@Test
public void testEntityTypeKeyValidationIsValid() {
    XmEntity entity = new XmEntity().key("TYPE1.SUBTYPE1-1").typeKey("TYPE1.SUBTYPE1").name("Entity name")
            .startDate(Instant.now()).updateDate(Instant.now()).stateKey("STATE1");
    Set<ConstraintViolation<XmEntity>> constraintViolations = validator.validate(entity);

    assertEquals(0, constraintViolations.size());
}
项目:aws-sdk-java-v2    文件:SdkIonGenerator.java   
@Override
public StructuredJsonGenerator writeValue(Instant instant) {
    try {
        Date d = instant != null ? Date.from(instant) : null;
        writer.writeTimestamp(Timestamp.forDateZ(d));
    } catch (IOException e) {
        throw new SdkClientException(e);
    }
    return this;
}
项目:jdk8u-jdk    文件:TCKInstant.java   
@Test
public void test_getLong_TemporalField() {
    Instant test = TEST_12345_123456789;
    assertEquals(test.getLong(ChronoField.NANO_OF_SECOND), 123456789);
    assertEquals(test.getLong(ChronoField.MICRO_OF_SECOND), 123456);
    assertEquals(test.getLong(ChronoField.MILLI_OF_SECOND), 123);
    assertEquals(test.getLong(ChronoField.INSTANT_SECONDS), 12345);
}
项目:jdk8u-jdk    文件:TCKZoneRules.java   
public void test_London_getStandardOffset() {
    ZoneRules test = europeLondon();
    ZonedDateTime zdt = createZDT(1840, 1, 1, ZoneOffset.UTC);
    while (zdt.getYear() < 2010) {
        Instant instant = zdt.toInstant();
        if (zdt.getYear() < 1848) {
            assertEquals(test.getStandardOffset(instant), ZoneOffset.ofHoursMinutesSeconds(0, -1, -15));
        } else if (zdt.getYear() >= 1969 && zdt.getYear() < 1972) {
            assertEquals(test.getStandardOffset(instant), OFFSET_PONE);
        } else {
            assertEquals(test.getStandardOffset(instant), OFFSET_ZERO);
        }
        zdt = zdt.plusMonths(6);
    }
}
项目:JAddOn    文件:JLogger.java   
/**
 * Error loggs an object with settable showing dialog
 * @param msg Object Error to log
 * @param show Boolean True if a dialog should be shown, False if not
 * @param ex Exception to be logged
 */
public void logErr(Object msg, boolean show, Exception ex) {
    Instant instant = Instant.now();
    Thread thread = getThread();
    StackTraceElement e = getStackTraceElement();
    LogEntry logentry = getLogEntry(msg, instant, LogEntry.LEVELERROR, datetimeformat, thread, e);
    logentry.setException(ex);
    logLogEntry(logentry, false, show, false);
    if(loggingOnFile) {
        logFile(logentry, true, instant);
    }
}
项目:L2J-Global    文件:ClanHall.java   
@Override
public void run()
{
    final L2Clan clan = getOwner();
    if (clan != null)
    {
        if (clan.getWarehouse().getAdena() < getLease())
        {
            if (getCostFailDay() > 8)
            {
                setOwner(null);
                clan.broadcastToOnlineMembers(SystemMessage.getSystemMessage(SystemMessageId.THE_CLAN_HALL_FEE_IS_ONE_WEEK_OVERDUE_THEREFORE_THE_CLAN_HALL_OWNERSHIP_HAS_BEEN_REVOKED));
            }
            else
            {
                _checkPaymentTask = ThreadPoolManager.getInstance().scheduleGeneral(new CheckPaymentTask(), 1, TimeUnit.DAYS);
                final SystemMessage sm = SystemMessage.getSystemMessage(SystemMessageId.PAYMENT_FOR_YOUR_CLAN_HALL_HAS_NOT_BEEN_MADE_PLEASE_MAKE_PAYMENT_TO_YOUR_CLAN_WAREHOUSE_BY_S1_TOMORROW);
                sm.addInt(getLease());
                clan.broadcastToOnlineMembers(sm);
            }
        }
        else
        {
            clan.getWarehouse().destroyItem("Clan Hall Lease", Inventory.ADENA_ID, getLease(), null, null);
            setPaidUntil(Instant.ofEpochMilli(getPaidUntil()).plus(Duration.ofDays(7)).toEpochMilli());
            _checkPaymentTask = ThreadPoolManager.getInstance().scheduleGeneral(new CheckPaymentTask(), getPaidUntil() - System.currentTimeMillis());
            updateDB();
        }
    }
}
项目:jdk8u-jdk    文件:TCKInstant.java   
@Test
public void minusMillis_long_max() {
    Instant i = Instant.ofEpochSecond(MAX_SECOND, 998999999);
    i = i.minusMillis(-1);
    assertEquals(i.getEpochSecond(), MAX_SECOND);
    assertEquals(i.getNano(), 999999999);
}
项目:Mastering-Java-9    文件:DumpProcessToLog.java   
public static void dump(ProcessHandle handle) {
    ProcessHandle.Info info = handle.info();
    StringBuffer sb = new StringBuffer();
    sb.append("Command: " + info.command().orElse("??") + "\n");
    sb.append("Command Line: " + info.commandLine().orElse("not present") + "\n");
    sb.append("Arguments: " + String.join(" ", info.arguments().orElse(new String[0])) + "\n");
    sb.append("Number of commandLine: " + info.arguments().orElse(new String[0]).length + "\n");
    sb.append("CPU: " + info.totalCpuDuration().orElse(Duration.ZERO) + "\n");
    sb.append("Start time: " + info.startInstant().orElse(Instant.EPOCH) + "\n");
    sb.append("User: " + info.user().orElse("??") + "\n");
    sb.append("Pid: " + handle.getPid() + "\n");
    sb.append("Children" + "\n");
    handle.children().forEach(child -> sb.append("child pid:" + child.getPid() + "\n"));
    sb.append("Descendants" + "\n");
    handle.descendants().forEach(descendant -> sb.append("descendant pid:" + descendant.getPid() + "\n"));

    handle.parent().ifPresentOrElse(parent -> sb.append("Parent: " + parent.info()), () -> sb.append("no parent\n"));

    if (handle.parent().isPresent() &&
            handle.parent().get().info().startInstant().isPresent() &&
            handle.info().startInstant().isPresent()) {
        sb.append("Parent started me after " +
                Duration.between(handle.parent().get().info().startInstant().get(),
                        handle.info().startInstant().get()).toMillis() + "ms" + "\n");
    }
    sb.append("toString " + handle.info().toString() + "\n");

    log.log(DEBUG, sb.toString());
}
项目:sentry    文件:PlayerCountResource.java   
@GetMapping("/player-counts/points")
@Timed
@Secured(AuthoritiesConstants.SUPPORT)
public ResponseEntity<List<Series>> getPlayerCountsBetween(@RequestParam Long from,
                                                           @RequestParam Long to) throws URISyntaxException {

    ZonedDateTime fromTime = Instant.ofEpochMilli(from).atZone(ZoneId.systemDefault());
    ZonedDateTime toTime = Instant.ofEpochMilli(to).atZone(ZoneId.systemDefault());
    log.debug("GET PlayerCounts between {} and {}", fromTime, toTime);
    List<Series> series = playerCountService.getGroupedPointsBetween(fromTime, toTime);
    return new ResponseEntity<>(series, null, HttpStatus.OK);
}
项目:setra    文件:MessageSenderService.java   
public SecretFile encryptFile(final String name, final InputStream in,
                              final KeyIv encryptionKey, final Instant expiration) {

    final byte[] fileIv = cryptor.newIv();
    final KeyIv fileKey = new KeyIv(encryptionKey.getKey(), fileIv);

    final byte[] encryptedFilename = cryptor.encryptString(name, fileKey);

    return fileRepository.storeFile(newRandomId(),
        new CryptedData(encryptedFilename, fileIv), in, fileKey, expiration);
}
项目:aws-sdk-java-v2    文件:DateUtils.java   
/**
 * Parses the specified date string as an ISO 8601 date (yyyy-MM-dd'T'HH:mm:ss.SSSZZ)
 * and returns the {@link Instant} object.
 *
 * @param dateString
 *            The date string to parse.
 *
 * @return The parsed Instant object.
 */
public static Instant parseIso8601Date(String dateString) {
    // For EC2 Spot Fleet.
    if (dateString.endsWith("+0000")) {
        dateString = dateString
                         .substring(0, dateString.length() - 5)
                         .concat("Z");
    }

    try {
        return parseInstant(dateString, ISO_INSTANT);
    } catch (DateTimeParseException e) {
        return parseInstant(dateString, ALTERNATE_ISO_8601_DATE_FORMAT);
    }
}
项目:jdk8u-jdk    文件:TCKZonedDateTime.java   
@Test(expectedExceptions=DateTimeException.class)
public void factory_ofInstant_tooLow() {
    long days_0000_to_1970 = (146097 * 5) - (30 * 365 + 7);
    int year = Year.MIN_VALUE - 1;
    long days = (year * 365L + (year / 4 - year / 100 + year / 400)) - days_0000_to_1970;
    Instant instant = Instant.ofEpochSecond(days * 24L * 60L * 60L);
    ZonedDateTime.ofInstant(instant, ZoneOffset.UTC);
}
项目:swblocks-decisiontree    文件:TimeSlicedEvaluationTest.java   
@Test
public void fourthEvaluation() {
    /**
     * Applicable time slice: 2013-04-15T00:00:00Z to 2023-01-01T00:00:00Z.
     */
    final Instant evaluation = Instant.parse("2016-12-01T00:00:00.Z");
    final Optional<UUID> result = Evaluator.singleEvaluate(this.inputB, evaluation, this.rootNode);
    assertFalse(result.isPresent());
}
项目:JAddOn    文件:JLogger.java   
/**
 * Error loggs an object with settable showing dialog
 * @param msg Object Error to log
 * @param ex Exception to be logged
 */
public void logErr(Object msg, Exception ex) {
    Instant instant = Instant.now();
    Thread thread = getThread();
    StackTraceElement e = getStackTraceElement();
    LogEntry logentry = getLogEntry(msg, instant, LogEntry.LEVELERROR, datetimeformat, thread, e);
    logentry.setException(ex);
    logLogEntry(logentry, false, false, false);
    if(loggingOnFile) {
        logFile(logentry, true, instant);
    }
}
项目:aws-sdk-java-v2    文件:SdkJsonGenerator.java   
@Override
public StructuredJsonGenerator writeValue(Instant instant) {
    try {
        generator.writeNumber(DateUtils.formatServiceSpecificDate(instant));
    } catch (IOException e) {
        throw new JsonGenerationException(e);
    }
    return this;
}
项目:jdk8u-jdk    文件:TCKLocalDateTime.java   
@Test
public void now_Clock_allSecsInDay_utc() {
    for (int i = 0; i < (2 * 24 * 60 * 60); i++) {
        Instant instant = Instant.ofEpochSecond(i).plusNanos(123456789L);
        Clock clock = Clock.fixed(instant, ZoneOffset.UTC);
        LocalDateTime test = LocalDateTime.now(clock);
        assertEquals(test.getYear(), 1970);
        assertEquals(test.getMonth(), Month.JANUARY);
        assertEquals(test.getDayOfMonth(), (i < 24 * 60 * 60 ? 1 : 2));
        assertEquals(test.getHour(), (i / (60 * 60)) % 24);
        assertEquals(test.getMinute(), (i / 60) % 60);
        assertEquals(test.getSecond(), i % 60);
        assertEquals(test.getNano(), 123456789);
    }
}
项目:verify-matching-service-adapter    文件:NotInTheFutureValidator.java   
/**
 * Constructs a validator which ensures the provided date/time is not in the future, allowing for variations in clock
 * times around the world with the application of a delta/tolerance.
 *
 * @param message the message this validator will add to the error messages if the provided date/time is determined as in the future.
 * @param atInstantProvider a provider of the date/time to be tested.
 * @param clockDelta a delta/tolerance to allow for clocks on different machines having differing values for the 'current' time.
 */
public NotInTheFutureValidator(@NotNull final Message message,
                               @NotNull final Function<T, Instant> atInstantProvider,
                               @NotNull final Duration clockDelta) {
    super(message, context -> {
        Instant atInstant = atInstantProvider.apply((T)context);

        return !atInstant.isAfter(Instant.now().plus(clockDelta));
    });
    this.atInstantProvider = atInstantProvider;
}
项目:setra    文件:MessageReceiverService.java   
private void updateSenderMessageInvalidated(final String senderId) {
    final SenderMessage senderMessage = senderMsgRepository.read(senderId);
    if (senderMessage.getInvalidated() == null) {
        senderMessage.setInvalidated(Instant.now());
        senderMsgRepository.update(senderId, senderMessage);
    }
}
项目:swblocks-decisiontree    文件:DatedNodeKeyTest.java   
@Test
public void equalsCorrect() {
    DatedNodeKey key = new DatedNodeKey("test1", new Range<>(DecisionTreeRule.EPOCH, DecisionTreeRule.MAX));
    final DatedNodeKey sameKey = new DatedNodeKey("test1",
            new Range<>(DecisionTreeRule.EPOCH, DecisionTreeRule.MAX));

    assertTrue(key.equals(key));
    assertTrue(key.equals(sameKey));
    assertFalse(key.equals(null));
    assertFalse(key.equals(new Integer(1)));

    DatedNodeKey otherKeyValue = new DatedNodeKey("test2",
            new Range<>(DecisionTreeRule.EPOCH, DecisionTreeRule.MAX));
    assertFalse(key.equals(otherKeyValue));

    otherKeyValue = new DatedNodeKey("test1", new Range<>(Instant.now(), DecisionTreeRule.MAX));
    assertFalse(key.equals(otherKeyValue));

    otherKeyValue = new DatedNodeKey("test1", new Range<>(DecisionTreeRule.EPOCH, Instant.now()));
    assertFalse(key.equals(otherKeyValue));

    otherKeyValue = new DatedNodeKey("test1", new Range<>(DecisionTreeRule.EPOCH, null));
    assertFalse(key.equals(otherKeyValue));

    otherKeyValue = new DatedNodeKey("test1", new Range<>(null, DecisionTreeRule.MAX));
    assertFalse(key.equals(otherKeyValue));

    otherKeyValue = new DatedNodeKey("test1", null);
    assertFalse(key.equals(otherKeyValue));

    key = new DatedNodeKey("test1", null);
    assertTrue(key.equals(otherKeyValue));

    otherKeyValue = new DatedNodeKey("test2", new Range<>(DecisionTreeRule.EPOCH, DecisionTreeRule.MAX));
    assertFalse(key.equals(otherKeyValue));
}
项目:NioImapClient    文件:ImapClientTest.java   
@Test
@Ignore
public void testSearchBefore_returnsAllEmailsBeforeDate() throws Exception {
  greenMail.purgeEmailFromAllMailboxes();
  deliverRandomMessages(2);
  ZonedDateTime before = Instant.now().atZone(ZoneId.systemDefault());

  Thread.sleep(100);
  deliverRandomMessages(1);

  SearchResponse searchResponse = client.uidsearch(DateSearches.searchBefore(before)).get();
  assertThat(searchResponse.getCode()).isEqualTo(ResponseCode.OK);

  assertThat(searchResponse.getMessageIds().size()).isEqualTo(2);
}
项目:swblocks-decisiontree    文件:ValueGroupChangeBuilder.java   
@Override
ValueGroup getNewSegmentBasedOnChange(final DomainBuilder<ValueGroupChange, ValueGroup> domainBuilder,
                                      final Instant start,
                                      final Instant end,
                                      final ValueGroup segment) {
    final ValueGroupChangeBuilder builder = (ValueGroupChangeBuilder) domainBuilder;
    return getValueGroup(builder, UUID.randomUUID(), segment.getName(),
            builder.drivers, new DateRange(start, end));
}
项目:highfrequencyrobots    文件:ConnectionStatus.java   
public ConnectionStatus attemptingConnection() {
  mIsConnected = false;
  mState = EConnectionState.ATTEMPTING;
  if(mFirstConnectionAttempt == null) {
    mFirstConnectionAttempt = Instant.now();
  }
  mLatestConnectionAttempt = Instant.now();
  return this;
}
项目:trellis-rosid    文件:RDFPatchTest.java   
@Test
public void testStream1() throws Exception {
    final File file = new File(getClass().getResource("/journal1.txt").toURI());
    final Instant time = parse("2017-02-11T02:51:35Z");
    final Graph graph = rdf.createGraph();
    RDFPatch.asStream(rdf, file, identifier, time).map(Quad::asTriple).forEach(graph::add);
    assertEquals(3L, graph.size());
    assertTrue(graph.contains(identifier, rdf.createIRI("http://www.w3.org/2004/02/skos/core#prefLabel"), null));
}