Java Code Examples for java.time.Instant

The following are top voted examples for showing how to use java.time.Instant. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: filter-sort-jooq-api   File: TransferTimingPageResource.java   Source Code and License 8 votes vote down vote up
/**
 * 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);
}
 
Example 2
Project: yuvi   File: OffHeapVarBitMetricStoreTest.java   Source Code and License 6 votes vote down vote up
@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();
}
 
Example 3
Project: matrix-appservice-email   File: SubscriptionManager.java   Source Code and License 6 votes vote down vote up
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;
}
 
Example 4
Project: vars-annotation   File: AVFImageCaptureServiceTest.java   Source Code and License 6 votes vote down vote up
@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");
    }
}
 
Example 5
Project: trading4j   File: TradeTracker.java   Source Code and License 6 votes vote down vote up
@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;
}
 
Example 6
Project: swblocks-decisiontree   File: CommisionRuleSetSupplier.java   Source Code and License 6 votes vote down vote up
/**
 * 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)));
}
 
Example 7
Project: JAddOn   File: Client.java   Source Code and License 6 votes vote down vote up
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;
}
 
Example 8
Project: setra   File: MessageSenderService.java   Source Code and License 6 votes vote down vote up
/**
 * 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;
}
 
Example 9
Project: Chronetic   File: ChronoRangeTest.java   Source Code and License 6 votes vote down vote up
@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));
}
 
Example 10
Project: trellis-rosid-file   File: LdpContainerTest.java   Source Code and License 6 votes vote down vote up
@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());
}
 
Example 11
Project: BeamTeamDiscordBot   File: JDAManager.java   Source Code and License 6 votes vote down vote up
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();
}
 
Example 12
Project: carnotzet   File: DockerRegistry.java   Source Code and License 5 votes vote down vote up
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;
	}
}
 
Example 13
Project: cloud-dataflow-nyc-taxi-tycoon   File: RidePoint.java   Source Code and License 5 votes vote down vote up
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;
}
 
Example 14
Project: java-debug   File: UsageDataStore.java   Source Code and License 5 votes vote down vote up
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);
    }
}
 
Example 15
Project: Supreme-Bot   File: GuildVoiceLogger.java   Source Code and License 5 votes vote down vote up
@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"));
}
 
Example 16
Project: cactoos   File: DateAsText.java   Source Code and License 5 votes vote down vote up
/**
 * 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)
    );
}
 
Example 17
Project: jdk8u-jdk   File: TCKInstant.java   Source Code and License 5 votes vote down vote up
@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);
}
 
Example 18
Project: xm-ms-entity   File: TypeKeyValidatorIntTest.java   Source Code and License 5 votes vote down vote up
@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());
}
 
Example 19
Project: aws-sdk-java-v2   File: SdkIonGenerator.java   Source Code and License 5 votes vote down vote up
@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;
}
 
Example 20
Project: jdk8u-jdk   File: TCKInstant.java   Source Code and License 5 votes vote down vote up
@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);
}
 
Example 21
Project: jdk8u-jdk   File: TCKZoneRules.java   Source Code and License 5 votes vote down vote up
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);
    }
}
 
Example 22
Project: JAddOn   File: JLogger.java   Source Code and License 5 votes vote down vote up
/**
 * 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);
    }
}
 
Example 23
Project: L2J-Global   File: ClanHall.java   Source Code and License 5 votes vote down vote up
@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();
		}
	}
}
 
Example 24
Project: jdk8u-jdk   File: TCKInstant.java   Source Code and License 5 votes vote down vote up
@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);
}
 
Example 25
Project: Mastering-Java-9   File: DumpProcessToLog.java   Source Code and License 5 votes vote down vote up
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());
}
 
Example 26
Project: sentry   File: PlayerCountResource.java   Source Code and License 5 votes vote down vote up
@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);
}
 
Example 27
Project: setra   File: MessageSenderService.java   Source Code and License 5 votes vote down vote up
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);
}
 
Example 28
Project: aws-sdk-java-v2   File: DateUtils.java   Source Code and License 5 votes vote down vote up
/**
 * 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);
    }
}
 
Example 29
Project: jdk8u-jdk   File: TCKZonedDateTime.java   Source Code and License 5 votes vote down vote up
@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);
}
 
Example 30
Project: swblocks-decisiontree   File: TimeSlicedEvaluationTest.java   Source Code and License 5 votes vote down vote up
@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());
}
 
Example 31
Project: JAddOn   File: JLogger.java   Source Code and License 5 votes vote down vote up
/**
 * 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);
    }
}
 
Example 32
Project: aws-sdk-java-v2   File: SdkJsonGenerator.java   Source Code and License 5 votes vote down vote up
@Override
public StructuredJsonGenerator writeValue(Instant instant) {
    try {
        generator.writeNumber(DateUtils.formatServiceSpecificDate(instant));
    } catch (IOException e) {
        throw new JsonGenerationException(e);
    }
    return this;
}
 
Example 33
Project: jdk8u-jdk   File: TCKLocalDateTime.java   Source Code and License 5 votes vote down vote up
@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);
    }
}
 
Example 34
Project: verify-matching-service-adapter   File: NotInTheFutureValidator.java   Source Code and License 5 votes vote down vote up
/**
 * 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;
}
 
Example 35
Project: setra   File: MessageReceiverService.java   Source Code and License 5 votes vote down vote up
private void updateSenderMessageInvalidated(final String senderId) {
    final SenderMessage senderMessage = senderMsgRepository.read(senderId);
    if (senderMessage.getInvalidated() == null) {
        senderMessage.setInvalidated(Instant.now());
        senderMsgRepository.update(senderId, senderMessage);
    }
}
 
Example 36
Project: swblocks-decisiontree   File: DatedNodeKeyTest.java   Source Code and License 5 votes vote down vote up
@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));
}
 
Example 37
Project: NioImapClient   File: ImapClientTest.java   Source Code and License 5 votes vote down vote up
@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);
}
 
Example 38
Project: swblocks-decisiontree   File: ValueGroupChangeBuilder.java   Source Code and License 5 votes vote down vote up
@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));
}
 
Example 39
Project: highfrequencyrobots   File: ConnectionStatus.java   Source Code and License 5 votes vote down vote up
public ConnectionStatus attemptingConnection() {
  mIsConnected = false;
  mState = EConnectionState.ATTEMPTING;
  if(mFirstConnectionAttempt == null) {
    mFirstConnectionAttempt = Instant.now();
  }
  mLatestConnectionAttempt = Instant.now();
  return this;
}
 
Example 40
Project: trellis-rosid   File: RDFPatchTest.java   Source Code and License 5 votes vote down vote up
@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));
}
 
Example 41
Project: swblocks-decisiontree   File: TimeSlicedEvaluationTest.java   Source Code and License 5 votes vote down vote up
@Test
public void thirdEvaluation() {
    /**
     * Applicable time slice: 2013-04-01T00:00:00Z to 2013-04-01T00:00:01Z.
     */
    final Instant evaluation = Instant.parse("2013-04-01T00:00:00.Z");
    final Optional<UUID> result = Evaluator.singleEvaluate(this.inputA, evaluation, this.rootNode);
    assertTrue(result.isPresent());

    assertEquals(new UUID(0, 9L), result.get());
}
 
Example 42
Project: charts   File: ChartItem.java   Source Code and License 4 votes vote down vote up
public ChartItem(final String NAME, final double VALUE, final Color FILL, final Instant TIMESTAMP) {
    this(NAME, VALUE, FILL, Color.TRANSPARENT, Color.BLACK, TIMESTAMP, false, 800);
}
 
Example 43
Project: ProjectAres   File: Dropped.java   Source Code and License 4 votes vote down vote up
@Override
protected boolean canPickup(MatchPlayer player) {
    return super.canPickup(player) && (player != this.dropper || this.enterTime.plus(PICKUP_DELAY).isBefore(Instant.now()));
}
 
Example 44
Project: setra   File: SenderMessage.java   Source Code and License 4 votes vote down vote up
public void setBurned(final Instant burned) {
    this.burned = burned;
}
 
Example 45
Project: jdk8u-jdk   File: TCKFixedZoneRules.java   Source Code and License 4 votes vote down vote up
@Test(dataProvider="rules")
public void test_getOffset_Instant(ZoneRules test, ZoneOffset expectedOffset) {
    assertEquals(test.getOffset(INSTANT), expectedOffset);
    assertEquals(test.getOffset((Instant) null), expectedOffset);
}
 
Example 46
Project: scalable-coffee-shop   File: CoffeeBrewFinished.java   Source Code and License 4 votes vote down vote up
public CoffeeBrewFinished(final UUID orderId, Instant instant) {
    super(instant);
    this.orderId = orderId;
}
 
Example 47
Project: tg-eventstore   File: TimeReader.java   Source Code and License 4 votes vote down vote up
public static NamedReaderWithCodec timePassedEventStream(Instant start, Duration accuracy, Clock clock) {
    TimeReader timeReader = new TimeReader(start, accuracy, clock);
    return new NamedReaderWithCodec("Clock", timeReader, timeReader);
}
 
Example 48
Project: spring-boot-gae   File: OffsetDateTimeDateTranslatorFactoryTest.java   Source Code and License 4 votes vote down vote up
private Date date(String val) {
    return Date.from(Instant.parse(val));
}
 
Example 49
Project: generator-thundr-gae-react   File: ZonedDateTimeDateTranslatorFactoryTest.java   Source Code and License 4 votes vote down vote up
private Date date(String val) {
    return Date.from(Instant.parse(val));
}
 
Example 50
Project: TorgCRM-Server   File: UserDTO.java   Source Code and License 4 votes vote down vote up
public void setLastModifiedDate(Instant lastModifiedDate) {
    this.lastModifiedDate = lastModifiedDate;
}
 
Example 51
Project: rockscript   File: Time.java   Source Code and License 4 votes vote down vote up
public static Instant now() {
  return now!=null ? now : Instant.now();
}
 
Example 52
Project: WavesJ   File: SpreadBot.java   Source Code and License 4 votes vote down vote up
private void round() throws IOException, InterruptedException {
    System.out.println();
    System.out.println(Instant.now());

    // Cancel all orders filed at our market
    for (Order order: matcher.getOrders(account, market)) {
        if (order.isActive()) {
            cancelOrder(order.id);
        }
    }

    // Read order book
    OrderBook book = matcher.getOrderBook(market);
    if (book.bids.size() <= 0) {
        System.out.println("There are no bids, skipping this round");
        return;
    }
    if (book.asks.size() <= 0) {
        System.out.println("There are no asks, skipping this round");
        return;
    }

    // Determine buy and sell prices
    long bestBid = book.bids.get(0).price;
    long bestAsk = book.asks.get(0).price;
    System.out.printf("Spread %d : %d\n", bestBid, bestAsk);
    long meanPrice = (bestBid + bestAsk) / 2;
    long buyPrice = (long) (meanPrice * (1 - halfSpread));
    long sellPrice = (long) (meanPrice * (1 + halfSpread));

    // Find out how much we want to buy, and file an order
    long priceAssetAvail = node.getBalance(account.getAddress(), market.priceAsset) - 2 * fee;
    if (priceAssetAvail > 0) {
        long buyOrderSize = Math.min(priceAssetAvail, maxOrderSize) * Asset.TOKEN / buyPrice;
        fileOrder(Order.Type.BUY, buyPrice, buyOrderSize);
    }

    // Same for sell order
    long amountAssetAvail = node.getBalance(account.getAddress(), market.amountAsset) - 2 * fee;
    if (amountAssetAvail > 0) {
        long sellOrderSize = Math.min(amountAssetAvail, maxOrderSize * Asset.TOKEN / sellPrice);
        fileOrder(Order.Type.SELL, sellPrice, sellOrderSize);
    }
}
 
Example 53
Project: ProjectAres   File: MatchPlayer.java   Source Code and License 4 votes vote down vote up
/**
 * Reverse-chronological list of match commitments within the last 24 hours
 */
public List<Instant> recentMatchCommitments() {
    final List<Instant> instants = getDocument().recent_match_joins_by_family_id().get(localServer.family());
    return instants == null ? Collections.emptyList() : instants;
}
 
Example 54
Project: spring-data-gclouddatastore   File: UnmarshallerTests.java   Source Code and License 4 votes vote down vote up
@Test
public void testUnmarshalToObject_Timestamp() {
	// Setup
	Key key = Key.newBuilder("project", "kind", 1).build();
	Entity entity = Entity.newBuilder(key)
			.set("object", Timestamp.parseTimestamp("2017-07-09T12:34:56Z"))
			.set("primitiveLong", Timestamp.parseTimestamp("2017-07-09T12:34:56Z"))
			.set("boxedLong", Timestamp.parseTimestamp("2017-07-09T12:34:56Z"))
			.set("date", Timestamp.parseTimestamp("2017-07-09T12:34:56Z"))
			.set("calendar", Timestamp.parseTimestamp("2017-07-09T12:34:56Z"))
			.set("sqlTimestamp", Timestamp.parseTimestamp("2017-07-09T12:34:56Z"))
			.set("localDateTime", Timestamp.parseTimestamp("2017-07-09T12:34:56Z"))
			.set("offsetDateTime", Timestamp.parseTimestamp("2017-07-09T12:34:56Z"))
			.set("zonedDateTime", Timestamp.parseTimestamp("2017-07-09T12:34:56Z"))
			.build();
	Unmarshaller unmarshaller = new Unmarshaller();
	TestBean bean = new TestBean();

	// Exercise
	unmarshaller.unmarshalToObject(entity, bean);

	// Verify
	Assert.assertEquals(OffsetDateTime.parse("2017-07-09T12:34:56Z").toInstant(),
			(Instant) bean.object);
	Assert.assertEquals(OffsetDateTime.parse("2017-07-09T12:34:56Z").toEpochSecond(),
			bean.primitiveLong);
	Assert.assertEquals(
			Long.valueOf(
					OffsetDateTime.parse("2017-07-09T12:34:56Z").toEpochSecond()),
			bean.boxedLong);
	Assert.assertEquals(
			Date.from(OffsetDateTime.parse("2017-07-09T12:34:56Z").toInstant()),
			bean.date);
	Assert.assertEquals(new Calendar.Builder()
			.setInstant(Date
					.from(OffsetDateTime.parse("2017-07-09T12:34:56Z").toInstant()))
			.build(), bean.calendar);
	Assert.assertEquals(
			java.sql.Timestamp
					.from(OffsetDateTime.parse("2017-07-09T12:34:56Z").toInstant()),
			bean.sqlTimestamp);
	Assert.assertEquals(
			OffsetDateTime.parse("2017-07-09T12:34:56Z")
					.atZoneSameInstant(ZoneId.systemDefault()).toLocalDateTime(),
			bean.localDateTime);
	Assert.assertEquals(OffsetDateTime.parse("2017-07-09T12:34:56Z"),
			bean.offsetDateTime);
	Assert.assertEquals(ZonedDateTime.parse("2017-07-09T12:34:56Z"),
			bean.zonedDateTime);
}
 
Example 55
Project: morpheus-core   File: LongCoding.java   Source Code and License 4 votes vote down vote up
@Override
public final long getCode(Instant value) {
    return value == null ? Long.MIN_VALUE : value.toEpochMilli();
}
 
Example 56
Project: xm-ms-entity   File: Vote.java   Source Code and License 4 votes vote down vote up
public void setEntryDate(Instant entryDate) {
    this.entryDate = entryDate;
}
 
Example 57
Project: mux2fs   File: UnixFileStatImpl.java   Source Code and License 4 votes vote down vote up
private void setInodeTime(Instant inodeTime) {
	this.inodeTime = inodeTime;
}
 
Example 58
Project: powsybl-core   File: RegularTimeSeriesIndex.java   Source Code and License 4 votes vote down vote up
@Override
public String toString() {
    return "RegularTimeSeriesIndex(startTime=" + Instant.ofEpochMilli(startTime) + ", endTime=" + Instant.ofEpochMilli(endTime) +
            ", spacing=" + Duration.ofMillis(spacing) + ")";
}
 
Example 59
Project: stroom-stats   File: TestCountStatToAggregateFlatMapper.java   Source Code and License 4 votes vote down vote up
@Test
public void flatMap_CustomRollups() throws Exception {

    Statistics.Statistic statistic = buildStatistic();

    RollUpBitMask mask0 = RollUpBitMask.ZERO_MASK;
    RollUpBitMask mask1 = RollUpBitMask.fromTagPositions(Collections.singletonList(0));
    RollUpBitMask mask2 = RollUpBitMask.fromTagPositions(Arrays.asList(0, 1));

    StatisticConfiguration statisticConfiguration = new MockStatisticConfiguration()
            .setUuid(statUuid)
            .setName(statName)
            .setStatisticType(StatisticType.COUNT)
            .setRollUpType(StatisticRollUpType.CUSTOM)
            .addCustomRollupMask(new MockCustomRollupMask(mask1.getTagPositionsAsList()))
            .addCustomRollupMask(new MockCustomRollupMask(mask2.getTagPositionsAsList()))
            .addFieldNames(tag1, tag2)
            .setPrecision(EventStoreTimeIntervalEnum.SECOND);


    mockStatisticConfigurationService.addStatisticConfiguration(statisticConfiguration);

    StatisticWrapper statisticWrapper = new StatisticWrapper(statistic, Optional.of(statisticConfiguration));

    //will throw a RTE as there is no StatConfig
    Instant start = Instant.now();
    Iterable<KeyValue<StatEventKey, StatAggregate>> iterable = countStatToAggregateMapper.flatMap(statUuid, statisticWrapper);
    Duration executionTime = Duration.between(start, Instant.now());
    LOGGER.debug("Execution time: {}ms", executionTime.toMillis());

    List<KeyValue<StatEventKey, StatAggregate>> keyValues = (List<KeyValue<StatEventKey, StatAggregate>>) iterable;

    //2 custom masks and the zero mask will always be generated so expect 3 events in total
    assertThat(keyValues).hasSize(3);

    assertThat(keyValues.stream()
            .map(keyValue -> keyValue.key.getRollupMask())
            .collect(Collectors.toList()))
            .containsExactlyInAnyOrder(
                    mask0,
                    mask1,
                    mask2);

    List<Tuple2<TagValue, TagValue>> tagValuePairs = keyValues.stream()
            .map(kv -> new Tuple2<>(kv.key.getTagValues().get(0), kv.key.getTagValues().get(1)))
            .collect(Collectors.toList());

    assertThat(tagValuePairs).containsExactlyInAnyOrder(
            new Tuple2<>(new TagValue(tag1Uid, tag1val1Uid), new TagValue(tag2Uid, tag2val1Uid)),
            new Tuple2<>(new TagValue(tag1Uid, rolledUpUid), new TagValue(tag2Uid, tag2val1Uid)),
            new Tuple2<>(new TagValue(tag1Uid, rolledUpUid), new TagValue(tag2Uid, rolledUpUid)));

    keyValues.forEach(keyValue -> assertOnKeyValue(keyValue, statistic, statisticConfiguration));
}
 
Example 60
Project: courgette-jvm   File: CourgetteProperties.java   Source Code and License 4 votes vote down vote up
public CourgetteProperties(CourgetteOptions courgetteOptions, String sessionId, Integer maxThreads) {
    this.courgetteOptions = courgetteOptions;
    this.sessionId = sessionId;
    this.sessionStartTime = Instant.now();
    this.maxThreads = maxThreads;
}