Java Code Examples for java.time.Instant.now()

The following are Jave code examples for showing how to use now() of the java.time.Instant class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
Example 1
Project: swblocks-decisiontree   File: AuditTest.java   Source Code and License Vote up 6 votes
@Test
public void equalsCorrect() {
    final Instant now = Instant.now();
    final Audit audit = new Audit("USER1", now, "USER2", now);

    assertTrue(audit.equals(audit));
    assertFalse(audit.equals(null));
    assertFalse(audit.equals(Boolean.TRUE));

    Audit other = new Audit("USER1", now, "USER2", now);
    assertTrue(audit.equals(other));

    other = new Audit(null, now, "USER2", now);
    assertFalse(audit.equals(other));

    other = new Audit(null, null, "USER2", now);
    assertFalse(audit.equals(other));

    other = new Audit(null, null, null, now);
    assertFalse(audit.equals(other));

    other = new Audit(null, null, null, null);
    assertFalse(audit.equals(other));
}
 
Example 2
Project: trading4j   File: MailSenderIT.java   Source Code and License Vote up 6 votes
/**
 * The cut can send mails.
 * 
 * @throws MailSendingException
 *             not expected to leave the test.
 * @throws ParseException
 *             When the date of the mail could not be parsed.
 */
@Test
public void canSendMails() throws MailSendingException, ParseException {
    final ServerOptions options = new ServerOptions();
    options.port = TEST_PORT;
    server = SmtpServerFactory.startServer(options);
    final MailSender cut = new MailSender("localhost", TEST_PORT);
    final Instant beforeSent = Instant.now();

    cut.sendMail("[email protected]", "[email protected]", "some subject", "some text");

    assertThat(server.getEmailCount()).isEqualTo(1);
    final MailMessage mail = server.getMessage(0);
    assertThat(mail.getFirstHeaderValue("From")).isEqualTo("[email protected]");
    assertThat(mail.getFirstHeaderValue("To")).isEqualTo("[email protected]");
    assertThat(mail.getFirstHeaderValue("Subject")).isEqualTo("some subject");
    assertThat(mail.getBody()).isEqualTo("some text");

    assertCorrectDate(mail.getFirstHeaderValue("Date"), beforeSent, Instant.now());
}
 
Example 3
Project: Supreme-Bot   File: GuildLogger.java   Source Code and License Vote up 5 votes
@Override
public void onGuildLeave(GuildLeaveEvent event) {
    final Instant timestamp = Instant.now();
    if (Standard.getConsoleTextChannel() != null) {
        Standard.getConsoleTextChannel().sendMessage(String.format("[%s] Left guild %s", LocalDateTime.ofInstant(timestamp, getZoneId()).format(DateTimeFormatter.ofPattern(Standard.STANDARD_DATE_TIME_FORMAT)), Standard.getCompleteName(event.getGuild()))).queue();
    }
}
 
Example 4
Project: ProjectAres   File: Scheduler.java   Source Code and License Vote up 5 votes
public Task createDelayedTask(Instant when, Runnable task) {
    final Instant now = Instant.now();
    if(when.isAfter(Instant.now())) {
        return createDelayedTask(Duration.between(now, when), task);
    } else {
        return createTask(task);
    }
}
 
Example 5
Project: GiveawayBot   File: StartCommand.java   Source Code and License Vote up 5 votes
@Override
protected void execute(CommandEvent event) {
    if(!Constants.canSendGiveaway(event.getTextChannel()))
    {
        event.replyError("I cannot start a giveaway here; please make sure I have the following permissions:\n\n"+Constants.PERMS);
        return;
    }
    String[] parts = event.getArgs().split("\\s+",2);
    boolean minutes;
    if(parts[0].toLowerCase().endsWith("m")) {
        parts[0] = parts[0].substring(0,parts[0].length()-1);
        minutes = true;
    } else if (parts[0].toLowerCase().endsWith("s")) {
        parts[0] = parts[0].substring(0,parts[0].length()-1);
        minutes = false;
    } else
        minutes = false;
    try {
        int value = (int)(Double.parseDouble(parts[0]) * (minutes ? 60 : 1) );
        if(!Constants.validTime(value))
        {
            event.replyWarning("Time must be at least 10 seconds and can't be longer than a week!");
            return;
        }
        try{ event.getMessage().delete().queue(); }catch(PermissionException ex){}
        Instant now = Instant.now();
        String item = parts.length==1 ? null : (parts[1].length()>Constants.PRIZE_MAX ? parts[1].substring(0,Constants.PRIZE_MAX) : parts[1]);
        bot.startGiveaway(event.getTextChannel(), now, value, 1, item);
    } catch(NumberFormatException e) {
        event.replyWarning("Failed to parse "+(minutes ? "minutes" : "seconds")+" from `"+parts[0]+"`.");
    }
}
 
Example 6
Project: vars-annotation   File: Annotation.java   Source Code and License Vote up 5 votes
public Annotation(String concept,
                  String observer,
                  VideoIndex videoIndex,
                  UUID videoReferenceUuid) {
    this.concept = concept;
    this.observer = observer;
    this.observationTimestamp = Instant.now();
    this.videoReferenceUuid = videoReferenceUuid;
    videoIndex.getElapsedTime().ifPresent(this::setElapsedTime);
    videoIndex.getTimestamp().ifPresent(this::setRecordedTimestamp);
    videoIndex.getTimecode().ifPresent(this::setTimecode);
}
 
Example 7
Project: swage   File: RollingFileWriter.java   Source Code and License Vote up 5 votes
/**
 * If necessary, close the current logfile and open a new one,
 * updating {@link #writer}.
 */
private void rollIfNeeded() throws IOException {
    // Do not roll unless record is complete, as indicated by flush
    if (!flushed) return;
    flushed = false;

    // If we have not yet passed the roll over mark do nothing
    Instant now = Instant.now();
    if (now.isBefore(rollAt)) {
        return;
    }

    // New file time, may not be the rollAt time if one or more intervals
    // have passed without anything being written
    Instant rollTime = now.truncatedTo(rollInterval);

    // Determine the name of the file that will be written to
    String name = this.baseName + format.format(LocalDateTime.ofInstant(rollTime, timeZone));
    this.outPath = this.directory.resolve(name);

    // Finish writing to previous log
    if (writer != null) {
        writer.flush();
        writer.close();
    }

    // Ensure the parent directory always exists, even if it was removed out from under us.
    // A no-op if the directory already exists.
    Files.createDirectories(outPath.getParent());

    // Create new file, set it as our write destination
    writer = Files.newBufferedWriter(
                outPath,
                StandardCharsets.UTF_8,
                StandardOpenOption.CREATE,
                StandardOpenOption.APPEND);

    // Point to the next time we want to roll the log, update rollAt
    this.rollAt = rollTime.plus(1, rollInterval);
}
 
Example 8
Project: cakes   File: PerformanceTest4Simple.java   Source Code and License Vote up 5 votes
/**
 * 循环10000000次
 * 131 毫秒
 */
@Test
public void testStream() throws InterruptedException {
    Instant start = Instant.now();

    IntStream.range(0, 10000000).forEach(i -> {

    });

    Instant end = Instant.now();
    long millis = Duration.between(start, end).toMillis();
    System.out.println(millis);
}
 
Example 9
Project: swage   File: MetricRecorderTest.java   Source Code and License Vote up 5 votes
@Test
public void sample() throws Exception {
    final List<Event> output = new ArrayList<>(2);
    final MetricRecorder mr = testRecorder(output);

    final UUID id = UUID.randomUUID();
    final TypedMap metadata = makeContext(id.toString());
    final MetricRecorder.Context context = mr.context(metadata);

    final Number time = Integer.valueOf(23);
    final Instant timestamp = Instant.now();

    context.record(M_TIME, time, Unit.MILLISECOND, timestamp);

    assertEquals("Unexpected number of metrics output", 1, output.size());
    final Event e1 = output.get(0);
    assertEquals("Wrong metric", M_TIME, e1.metric);
    assertEquals("Wrong value", time, e1.value);
    assertEquals("Wrong unit", Unit.MILLISECOND, e1.unit);
    assertTrue("Wrong timestamp", e1.timestamp.equals(timestamp));
    assertEquals("Wrong benchmark", metadata, e1.metadata);
    assertEquals("Wrong REQUEST_ID", id.toString(), e1.metadata.get(ContextData.ID));

    final Number load = Integer.valueOf(87);
    context.record(M_PERC, load, Unit.PERCENT, timestamp);

    assertEquals("Unexpected number of metrics output", 2, output.size());
    final Event e2 = output.get(1);
    assertEquals("Wrong metric", M_PERC, e2.metric);
    assertEquals("Wrong value", load, e2.value);
    assertEquals("Wrong unit", Unit.PERCENT, e2.unit);
    assertTrue("Wrong timestamp", e2.timestamp.equals(timestamp));
    assertEquals("Wrong benchmark", metadata, e2.metadata);
    assertEquals("Wrong REQUEST_ID", id.toString(), e2.metadata.get(ContextData.ID));
}
 
Example 10
Project: wall-t   File: ApiMonitoringService.java   Source Code and License Vote up 5 votes
private Runnable checkRunningBuildStatus( ) {
    return ( ) -> {
        if ( !isActive( ) )
            return;

        final Instant before = Instant.now( );
        final List<BuildTypeData> monitoredBuilds = getAllMonitoredBuildTypes( ).stream( )
                .filter( BuildTypeData::hasRunningBuild )
                .collect( Collectors.toList( ) );

        checkBuildStatus( monitoredBuilds );
        LOGGER.info( "Checking running build status: done in {} s", Duration.between( before, Instant.now( ) ).getSeconds( ) );
    };
}
 
Example 11
Project: pure-bliss-with-pure-java-functions   File: OfflineDevicesJobTests.java   Source Code and License Vote up 5 votes
@Test(expected = IllegalArgumentException.class)
public void thatCalculateLastPassedThresholdThrowsExceptionWhenCurrentIsSameAsStart() {
    Instant start = Instant.now();
    List<Duration> thresholds = Collections.singletonList(Duration.ofDays(1));

    OfflineDevicesJobImpl.calculateLastPassedThreshold(start, start, thresholds);
}
 
Example 12
Project: ProjectAres   File: TeleportListener.java   Source Code and License Vote up 4 votes
@Override
public void tick() {
    final Instant now = Instant.now();
    requests.values().removeIf(received -> received.timestamp.plus(TIMEOUT).isBefore(now));
}
 
Example 13
Project: cryptotrader   File: VwapEstimatorTest.java   Source Code and License Vote up 4 votes
@Test
public void testEstimate() throws Exception {

    Instant now = Instant.now();
    Instant from = now.minus(LONG_ONE, HOURS);
    Request request = Request.builder().currentTime(now).build();
    Key key = Key.from(request);

    Trade t1 = mock(Trade.class); // Valid
    Trade t2 = mock(Trade.class); // Valid
    Trade t3 = mock(Trade.class); // Null Timestamp
    Trade t4 = mock(Trade.class); // Null Price
    Trade t5 = mock(Trade.class); // Null Size
    Trade t6 = mock(Trade.class); // Negative Size
    Trade t7 = mock(Trade.class); // Valid
    Trade t8 = mock(Trade.class); // Valid
    when(t1.getTimestamp()).thenReturn(from.plus(10, MINUTES));
    when(t2.getTimestamp()).thenReturn(from.plus(20, MINUTES));
    when(t3.getTimestamp()).thenReturn(null);
    when(t4.getTimestamp()).thenReturn(from.plus(30, MINUTES));
    when(t5.getTimestamp()).thenReturn(from.plus(40, MINUTES));
    when(t6.getTimestamp()).thenReturn(from.plus(50, MINUTES));
    when(t7.getTimestamp()).thenReturn(from.plus(60, MINUTES));
    when(t8.getTimestamp()).thenReturn(from.plus(70, MINUTES));
    when(t1.getPrice()).thenReturn(new BigDecimal("54.20735492"));
    when(t2.getPrice()).thenReturn(new BigDecimal("46.21598752"));
    when(t3.getPrice()).thenReturn(new BigDecimal("34.56789012"));
    when(t4.getPrice()).thenReturn(null);
    when(t5.getPrice()).thenReturn(new BigDecimal("56.78901234"));
    when(t6.getPrice()).thenReturn(new BigDecimal("67.89012345"));
    when(t7.getPrice()).thenReturn(new BigDecimal("52.06059242"));
    when(t8.getPrice()).thenReturn(new BigDecimal("48.56048341"));
    when(t1.getSize()).thenReturn(new BigDecimal("+1"));
    when(t2.getSize()).thenReturn(new BigDecimal("+2"));
    when(t3.getSize()).thenReturn(new BigDecimal("+3"));
    when(t4.getSize()).thenReturn(new BigDecimal("+4"));
    when(t5.getSize()).thenReturn(new BigDecimal("-5"));
    when(t6.getSize()).thenReturn(null);
    when(t7.getSize()).thenReturn(new BigDecimal("+3"));
    when(t8.getSize()).thenReturn(new BigDecimal("+4"));

    // All ticks
    when(context.listTrades(key, from)).thenReturn(asList(t1, t3, t5, t7, null, t2, t4, t6, t8));
    Estimation estimation = target.estimate(context, request);
    assertEquals(estimation.getPrice(), new BigDecimal("49.9231910345"));
    assertEquals(estimation.getConfidence(), new BigDecimal("0.9388342018"));

    // Two points
    when(context.listTrades(key, from)).thenReturn(asList(t1, null, t2));
    estimation = target.estimate(context, request);
    assertEquals(estimation.getPrice(), new BigDecimal("48.8298179723"));
    assertEquals(estimation.getConfidence().signum(), 0);

    // One point
    when(context.listTrades(key, from)).thenReturn(asList(null, t1));
    estimation = target.estimate(context, request);
    assertEquals(estimation.getPrice(), t1.getPrice());
    assertEquals(estimation.getConfidence(), ZERO);

    // Zero point
    when(context.listTrades(key, from)).thenReturn(emptyList());
    estimation = target.estimate(context, request);
    assertEquals(estimation.getPrice(), null);
    assertEquals(estimation.getConfidence(), ZERO);

    // Null
    when(context.listTrades(key, from)).thenReturn(null);
    estimation = target.estimate(context, request);
    assertEquals(estimation.getPrice(), null);
    assertEquals(estimation.getConfidence(), ZERO);

}
 
Example 14
Project: minijax   File: DefaultBaseEntity.java   Source Code and License Vote up 4 votes
@PreUpdate
public void onPreUpdate() {
    updatedDateTime = Instant.now();
}
 
Example 15
Project: bitflyer4j   File: EnvironmentImpl.java   Source Code and License Vote up 4 votes
@Override
public Instant getNow() {
    return Instant.now();
}
 
Example 16
Project: JAddOn   File: ArrayListUtils.java   Source Code and License Vote up 4 votes
public static ArrayListPosition contains(final ArrayList<?> arraylist, final Object object, final int threadPoolSize, TimerPlus timer) {
    final Instant instant_start = Instant.now();
    final ExecutorService executor = Executors.newFixedThreadPool(threadPoolSize);
    final ArrayListPosition alp = new ArrayListPosition();
    if(arraylist.size() >= threadPoolSize && arraylist.size() >= MINARRAYLISTSIZE) {
        final int steps = arraylist.size() / threadPoolSize;
        for(int i = 0; i < threadPoolSize; i++) {
            final int u = i;
            Runnable run = new Runnable() {
                
                @Override
                public void run() {
                    final int extra = ((u == threadPoolSize - 1) ? (steps * threadPoolSize) - arraylist.size() : 0);
                    for(int z = 0; z < steps + extra; z++) {
                        timer.all++;
                        if(arraylist.get(u * steps + z).equals(object)) {
                            final Instant instant_stop = Instant.now();
                            final Duration duration = Duration.between(instant_start, instant_stop);
                            alp.setContains(true);
                            alp.setObject(object);
                            alp.setPosition((u * steps + z));
                            alp.setDuration(duration);
                            executor.shutdownNow();
                        }
                        //StaticStandard.log(String.format("[%s] Step: %d, Overall: %d, Percentage: %.2f", Thread.currentThread().getName(), z, (u * steps + z), ((z * 1.0) / (steps * 1.0) * 100.0)));
                    }
                }
                
            };
            executor.execute(run);
        }
        executor.shutdown();
        try {
            executor.awaitTermination(1, TimeUnit.DAYS);
        } catch (Exception ex) {
        }
        return alp;
    } else {
        alp.setContains(arraylist.contains(object));
        alp.setObject(alp.isContains() ? object : null);
        alp.setPosition(alp.isContains() ? arraylist.indexOf(object) : -1);
        return alp;
    }
}
 
Example 17
Project: charts   File: Location.java   Source Code and License Vote up 4 votes
public Location(final double LATITUDE, final double LONGITUDE, final String NAME, final Color COLOR) {
    this(LATITUDE, LONGITUDE, 0, Instant.now() ,NAME, "", COLOR);
}
 
Example 18
Project: tg-eventstore   File: JavaEventStoreTest.java   Source Code and License Vote up 4 votes
@Before
public void captureTime() {
    timeBeforeTest = Instant.now();
}
 
Example 19
Project: SunburstChart   File: ChartData.java   Source Code and License Vote up 4 votes
public ChartData() {
    this("", 0, Color.rgb(233, 30, 99), Color.TRANSPARENT, Color.BLACK, Instant.now(), true, 800);
}
 
Example 20
Project: mid-tier   File: Transaction.java   Source Code and License Vote up 4 votes
public Transaction(Account account, BigDecimal amount, String description) {
    // The semantic key might as well be generated as a hash value of the transaction values
    // for simplicity it is just a unique id here.
    this(account, UUID.randomUUID().toString(), amount, description, Instant.now());
}