Java Examples for java.time.temporal.ChronoUnit

The following java examples will help you to understand the usage of java.time.temporal.ChronoUnit. These source code samples are taken from different open source projects.

Example 1
Project: cron-expression-master  File: CompareBehaviorToQuartzTest.java View source code
@Test
public void at_10_15am_on_the_last_day_of_every_month() throws Exception {
    string = "0 15 10 L * ?";
    List<ZonedDateTime> times = new ArrayList<>();
    ZonedDateTime t = ZonedDateTime.now().withDayOfYear(1).truncatedTo(ChronoUnit.DAYS).plusHours(10).plusMinutes(15);
    int year = t.getYear();
    while (t.getYear() == year) {
        times.add(t.with(TemporalAdjusters.lastDayOfMonth()));
        t = t.plusMonths(1);
    }
    check(times);
}
Example 2
Project: guide-master  File: LocalTime1.java View source code
public static void main(String[] args) {
    // get the current time
    Clock clock = Clock.systemDefaultZone();
    long t0 = clock.millis();
    System.out.println(t0);
    Instant instant = clock.instant();
    Date legacyDate = Date.from(instant);
    ZoneId zone1 = ZoneId.of("Europe/Berlin");
    ZoneId zone2 = ZoneId.of("Brazil/East");
    System.out.println(zone1.getRules());
    System.out.println(zone2.getRules());
    // time
    LocalTime now1 = LocalTime.now(zone1);
    LocalTime now2 = LocalTime.now(zone2);
    System.out.println(now1);
    System.out.println(now2);
    // false
    System.out.println(now1.isBefore(now2));
    long hoursBetween = ChronoUnit.HOURS.between(now1, now2);
    long minutesBetween = ChronoUnit.MINUTES.between(now1, now2);
    System.out.println(hoursBetween);
    System.out.println(minutesBetween);
    // create time
    LocalTime now = LocalTime.now();
    System.out.println(now);
    LocalTime late = LocalTime.of(23, 59, 59);
    System.out.println(late);
    DateTimeFormatter germanFormatter = DateTimeFormatter.ofLocalizedTime(FormatStyle.SHORT).withLocale(Locale.GERMAN);
    LocalTime leetTime = LocalTime.parse("13:37", germanFormatter);
    System.out.println(leetTime);
// to legacy date
}
Example 3
Project: java8-tutorial-master  File: LocalTime1.java View source code
public static void main(String[] args) {
    // get the current time
    Clock clock = Clock.systemDefaultZone();
    long t0 = clock.millis();
    System.out.println(t0);
    Instant instant = clock.instant();
    Date legacyDate = Date.from(instant);
    ZoneId zone1 = ZoneId.of("Europe/Berlin");
    ZoneId zone2 = ZoneId.of("Brazil/East");
    System.out.println(zone1.getRules());
    System.out.println(zone2.getRules());
    // time
    LocalTime now1 = LocalTime.now(zone1);
    LocalTime now2 = LocalTime.now(zone2);
    System.out.println(now1);
    System.out.println(now2);
    // false
    System.out.println(now1.isBefore(now2));
    long hoursBetween = ChronoUnit.HOURS.between(now1, now2);
    long minutesBetween = ChronoUnit.MINUTES.between(now1, now2);
    System.out.println(hoursBetween);
    System.out.println(minutesBetween);
    // create time
    LocalTime now = LocalTime.now();
    System.out.println(now);
    LocalTime late = LocalTime.of(23, 59, 59);
    System.out.println(late);
    DateTimeFormatter germanFormatter = DateTimeFormatter.ofLocalizedTime(FormatStyle.SHORT).withLocale(Locale.GERMAN);
    LocalTime leetTime = LocalTime.parse("13:37", germanFormatter);
    System.out.println(leetTime);
// to legacy date
}
Example 4
Project: hello-world-master  File: TcMonitorFilter.java View source code
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
    LocalDateTime now = LocalDateTime.now();
    filterChain.doFilter(request, response);
    long nanos = Duration.between(now, LocalDateTime.now()).get(ChronoUnit.NANOS);
    if (maxThan(nanos, errorTimeout)) {
        log.warn("request [{}] process take time [{}]", request.getRequestURI(), nanos / NANO_2_MS);
    } else if (maxThan(nanos, warnTimeout)) {
        log.error("request [{}] process take time [{}]", request.getRequestURI(), nanos / NANO_2_MS);
    }
}
Example 5
Project: Izou-master  File: MutingManager.java View source code
public synchronized MutingManager remove(IzouSoundLine line) {
    mutingLines.remove(line);
    if (mutingLines.isEmpty()) {
        limit = LocalTime.now().plus(2000L, ChronoUnit.MILLIS);
        limitFuture = soundManager.getMain().getThreadPoolManager().getAddOnsThreadPool().submit(() -> {
            try {
                Thread.sleep(2000);
                soundManager.unmute();
            } catch (InterruptedException ignored) {
            }
        });
        return this;
    }
    return this;
}
Example 6
Project: jfxtras-master  File: ByDayTest.java View source code
/*
    DTSTART:20160503T100000
    RRULE:FREQ=YEARLY;BYDAY=-1SU,2MO
     */
@Test
public void canStreamByDay() {
    ByDay element = ByDay.parse("-1SU,2MO");
    LocalDateTime dateTimeStart = LocalDateTime.of(2015, 12, 27, 10, 0);
    ChronoUnit frequency = ChronoUnit.YEARS;
    TemporalAdjuster adjuster = ( temporal) -> temporal.plus(1, frequency);
    Stream<Temporal> inStream = Stream.iterate(dateTimeStart,  a -> a.with(adjuster));
    Stream<Temporal> recurrenceStream = element.streamRecurrences(inStream, frequency, dateTimeStart);
    List<LocalDateTime> expectedRecurrences = new ArrayList<>(Arrays.asList(LocalDateTime.of(2015, 12, 27, 10, 0), LocalDateTime.of(2016, 1, 11, 10, 0), LocalDateTime.of(2016, 12, 25, 10, 0), LocalDateTime.of(2017, 1, 9, 10, 0), LocalDateTime.of(2017, 12, 31, 10, 0)));
    List<Temporal> madeRecurrences = recurrenceStream.filter(// filter is normally done in streamRecurrences in RecurrenceRule2
     r -> !DateTimeUtilities.isBefore(r, dateTimeStart)).limit(5).collect(Collectors.toList());
    assertEquals(expectedRecurrences, madeRecurrences);
}
Example 7
Project: levelup-java-examples-master  File: CalculateDateTimeDifference.java View source code
@Test
public void difference_between_two_dates_java8_chrono_period() {
    LocalDate sinceGraduation = LocalDate.of(1984, Month.JUNE, 4);
    LocalDate currentDate = LocalDate.now();
    long diffInDays = ChronoUnit.DAYS.between(sinceGraduation, currentDate);
    long diffInMonths = ChronoUnit.MONTHS.between(sinceGraduation, currentDate);
    long diffInYears = ChronoUnit.YEARS.between(sinceGraduation, currentDate);
    logger.info(diffInDays);
    logger.info(diffInMonths);
    logger.info(diffInYears);
    assertTrue(diffInDays >= anyLong());
    assertTrue(diffInMonths >= anyLong());
    assertTrue(diffInYears >= anyLong());
}
Example 8
Project: morphia-master  File: Java8EntityTest.java View source code
@Test
public void rangeQueries() {
    Instant instant = Instant.ofEpochMilli(System.currentTimeMillis());
    LocalDate localDate = LocalDate.of(1995, 10, 15);
    LocalDateTime localDateTime = LocalDateTime.of(2016, 4, 10, 14, 15, 16, 123 * 1000000);
    LocalTime localTime = LocalTime.of(10, 29, 15, 848493);
    for (int i = 0; i < 10; i++) {
        createEntity(getDs(), instant.plus(i, DAYS), localDate.plus(i, DAYS), localDateTime.plus(i, DAYS), localTime.plus(i, ChronoUnit.HOURS));
    }
    Assert.assertEquals(2L, getDs().find(Java8Entity.class).field("instant").lessThanOrEq(instant.plus(1, DAYS)).count());
    Assert.assertEquals(1L, getDs().find(Java8Entity.class).field("localDate").equal(localDate.plus(1, DAYS)).count());
    Assert.assertEquals(0L, getDs().find(Java8Entity.class).field("localDate").equal(localDate.minus(1, DAYS)).count());
    Assert.assertEquals(9L, getDs().find(Java8Entity.class).field("localDateTime").notEqual(localDateTime.plus(6, DAYS)).count());
}
Example 9
Project: AisStore-master  File: AisStoreSchemaTest.java View source code
@Test
public void testTimeBlock() throws Exception {
    assertEquals(0, AisStoreSchema.timeBlock(AisStoreSchema.Table.TABLE_PACKETS_TIME, Instant.EPOCH));
    assertEquals(0, AisStoreSchema.timeBlock(AisStoreSchema.Table.TABLE_PACKETS_TIME, Instant.EPOCH.plus(9, ChronoUnit.MINUTES)));
    assertEquals(1, AisStoreSchema.timeBlock(AisStoreSchema.Table.TABLE_PACKETS_TIME, Instant.EPOCH.plus(10, ChronoUnit.MINUTES)));
    assertEquals(1856448, AisStoreSchema.timeBlock(AisStoreSchema.Table.TABLE_PACKETS_TIME, Instant.parse("2005-04-19T00:00:00Z")));
    assertEquals(1856448, AisStoreSchema.timeBlock(AisStoreSchema.Table.TABLE_PACKETS_TIME, Instant.parse("2005-04-19T00:05:00Z")));
    assertEquals(1856449, AisStoreSchema.timeBlock(AisStoreSchema.Table.TABLE_PACKETS_TIME, Instant.parse("2005-04-19T00:10:00Z")));
    assertEquals(1856450, AisStoreSchema.timeBlock(AisStoreSchema.Table.TABLE_PACKETS_TIME, Instant.parse("2005-04-19T00:20:00Z")));
    assertEquals(1856506, AisStoreSchema.timeBlock(AisStoreSchema.Table.TABLE_PACKETS_TIME, Instant.parse("2005-04-19T09:49:38Z")));
    assertEquals(1856523, AisStoreSchema.timeBlock(AisStoreSchema.Table.TABLE_PACKETS_TIME, Instant.parse("2005-04-19T12:30:00Z")));
    assertEquals(1856523, AisStoreSchema.timeBlock(AisStoreSchema.Table.TABLE_PACKETS_TIME, Instant.parse("2005-04-19T12:39:59Z")));
    assertEquals(1856591, AisStoreSchema.timeBlock(AisStoreSchema.Table.TABLE_PACKETS_TIME, Instant.parse("2005-04-19T23:59:59Z")));
}
Example 10
Project: Cachoeira-master  File: TaskTooltip.java View source code
public void initTooltip(ITask task) {
    textProperty().bind(Bindings.concat("task_name" + ": ").concat(task.nameProperty()).concat("\n").concat(Bindings.when(task.descriptionProperty().isNull().or(task.descriptionProperty().isEmpty())).then("").otherwise(Bindings.concat("description" + ": ").concat(task.descriptionProperty()).concat("\n"))).concat("start_date" + ": ").concat(task.startDateProperty()).concat("\n").concat("finish_date" + ": ").concat(task.finishDateProperty()).concat("\n").concat("duration" + ": ").concat(ChronoUnit.DAYS.between(task.startDateProperty().getValue(), task.finishDateProperty().getValue())).concat("\n").concat("done_percent" + ": ").concat(task.donePercentProperty()).concat("\n").concat("cost" + ": ").concat(task.costProperty()));
}
Example 11
Project: core-ng-project-master  File: CleanupOldIndexJob.java View source code
private void process(ElasticSearchIndex index, LocalDate now) {
    createdDate(index.index).ifPresent( date -> {
        long days = ChronoUnit.DAYS.between(date, now);
        if (days >= 30) {
            deleteIndex(index.index);
        } else if (days >= 7 && index.state == IndexMetaData.State.OPEN) {
            closeIndex(index.index);
        }
    });
}
Example 12
Project: edison-microservice-master  File: JobRepresentationTest.java View source code
@Test()
public void shouldCalculateRuntime() throws InterruptedException {
    final JobInfo job = jobInfoWithRuntime(90, ChronoUnit.SECONDS);
    final JobRepresentation jobRepresentation = representationOf(job, null, true, "");
    assertThat(jobRepresentation.getStatus(), is("OK"));
    assertThat(jobRepresentation.getRuntime(), is("00:01:30"));
    assertThat(jobRepresentation.getHostname(), is("localhost"));
}
Example 13
Project: janus-master  File: HadoopConfiguration.java View source code
@Override
public <O> O get(String key, Class<O> datatype) {
    final String internalKey = getInternalKey(key);
    if (null == config.get(internalKey))
        return null;
    if (datatype.isArray()) {
        Preconditions.checkArgument(datatype.getComponentType() == String.class, "Only string arrays are supported: %s", datatype);
        return (O) config.getStrings(internalKey);
    } else if (Number.class.isAssignableFrom(datatype)) {
        String s = config.get(internalKey);
        return constructFromStringArgument(datatype, s);
    } else if (datatype == String.class) {
        return (O) config.get(internalKey);
    } else if (datatype == Boolean.class) {
        return (O) Boolean.valueOf(config.get(internalKey));
    } else if (datatype.isEnum()) {
        O[] constants = datatype.getEnumConstants();
        Preconditions.checkState(null != constants && 0 < constants.length, "Zero-length or undefined enum");
        String estr = config.get(internalKey);
        for (O c : constants) if (c.toString().equals(estr))
            return c;
        throw new IllegalArgumentException("No match for string \"" + estr + "\" in enum " + datatype);
    } else if (datatype == Object.class) {
        // Object.class must be supported for the sake of AbstractConfiguration's getSubset impl
        return (O) config.get(internalKey);
    } else if (Duration.class.isAssignableFrom(datatype)) {
        // This is a conceptual leak; the config layer should ideally only handle standard library types
        String s = config.get(internalKey);
        String[] comps = s.split("\\s");
        TemporalUnit unit = null;
        if (comps.length == 1) {
            //By default, times are in milli seconds
            unit = ChronoUnit.MILLIS;
        } else if (comps.length == 2) {
            unit = Durations.parse(comps[1]);
        } else {
            throw new IllegalArgumentException("Cannot parse time duration from: " + s);
        }
        return (O) Duration.of(Long.valueOf(comps[0]), unit);
    } else
        throw new IllegalArgumentException("Unsupported data type: " + datatype);
}
Example 14
Project: janusgraph-master  File: HadoopConfiguration.java View source code
@Override
public <O> O get(String key, Class<O> datatype) {
    final String internalKey = getInternalKey(key);
    if (null == config.get(internalKey))
        return null;
    if (datatype.isArray()) {
        Preconditions.checkArgument(datatype.getComponentType() == String.class, "Only string arrays are supported: %s", datatype);
        return (O) config.getStrings(internalKey);
    } else if (Number.class.isAssignableFrom(datatype)) {
        String s = config.get(internalKey);
        return constructFromStringArgument(datatype, s);
    } else if (datatype == String.class) {
        return (O) config.get(internalKey);
    } else if (datatype == Boolean.class) {
        return (O) Boolean.valueOf(config.get(internalKey));
    } else if (datatype.isEnum()) {
        O[] constants = datatype.getEnumConstants();
        Preconditions.checkState(null != constants && 0 < constants.length, "Zero-length or undefined enum");
        String estr = config.get(internalKey);
        for (O c : constants) if (c.toString().equals(estr))
            return c;
        throw new IllegalArgumentException("No match for string \"" + estr + "\" in enum " + datatype);
    } else if (datatype == Object.class) {
        // Object.class must be supported for the sake of AbstractConfiguration's getSubset impl
        return (O) config.get(internalKey);
    } else if (Duration.class.isAssignableFrom(datatype)) {
        // This is a conceptual leak; the config layer should ideally only handle standard library types
        String s = config.get(internalKey);
        String[] comps = s.split("\\s");
        TemporalUnit unit = null;
        if (comps.length == 1) {
            //By default, times are in milli seconds
            unit = ChronoUnit.MILLIS;
        } else if (comps.length == 2) {
            unit = Durations.parse(comps[1]);
        } else {
            throw new IllegalArgumentException("Cannot parse time duration from: " + s);
        }
        return (O) Duration.of(Long.valueOf(comps[0]), unit);
    } else
        throw new IllegalArgumentException("Unsupported data type: " + datatype);
}
Example 15
Project: javacuriosities-master  File: Lesson07PeriodAndDuration.java View source code
public static void main(String[] args) throws Exception {
    // Duration
    Instant start = Instant.now();
    Instant end = Instant.now();
    long nanoseconds = Duration.between(start, end).toNanos();
    System.out.println("Start: " + start);
    System.out.println("End: " + end);
    System.out.println("Diff: " + nanoseconds);
    Duration gap = Duration.ofSeconds(10);
    Instant later = start.plus(gap);
    System.out.println("Start + 10s : " + later);
    // Period
    LocalDate today = LocalDate.now();
    LocalDate birthday = LocalDate.of(1985, Month.MAY, 6);
    Period period = Period.between(birthday, today);
    long chronoUnit = ChronoUnit.DAYS.between(birthday, today);
    System.out.println("You are " + period.getYears() + " years, " + period.getMonths() + " months, and " + period.getDays() + " days old. (" + chronoUnit + " days total)");
}
Example 16
Project: javaone2015-cloudone-master  File: DurationMessageBodyWriter.java View source code
@Override
public void writeTo(Duration duration, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream) throws IOException, WebApplicationException {
    if (duration == null) {
        entityStream.write("00:00:00,000".getBytes());
        return;
    }
    StringBuilder result = new StringBuilder(20);
    long dur = duration.toMillis();
    //Days
    long l = dur / ChronoUnit.DAYS.getDuration().toMillis();
    if (l > 0) {
        result.append(l).append("D ");
        dur -= l * ChronoUnit.DAYS.getDuration().toMillis();
    }
    //Hours
    l = dur / ChronoUnit.HOURS.getDuration().toMillis();
    if (l < 10) {
        result.append('0');
    }
    result.append(l).append(':');
    dur -= l * ChronoUnit.HOURS.getDuration().toMillis();
    //Minutes
    l = dur / ChronoUnit.MINUTES.getDuration().toMillis();
    if (l < 10) {
        result.append('0');
    }
    result.append(l).append(':');
    dur -= l * ChronoUnit.MINUTES.getDuration().toMillis();
    //Seconds
    l = dur / ChronoUnit.SECONDS.getDuration().toMillis();
    if (l < 10) {
        result.append('0');
    }
    result.append(l).append(',');
    dur -= l * ChronoUnit.SECONDS.getDuration().toMillis();
    //Millis
    if (dur < 100) {
        result.append('0');
        if (dur < 10) {
            result.append('0');
        }
    }
    result.append(dur);
    //WRITE IT
    entityStream.write(result.toString().getBytes());
}
Example 17
Project: jBloomberg-master  File: IntradayBarDataTest.java View source code
@BeforeMethod
public void beforeMethod() {
    data = new IntradayBarData("ABC");
    int i = 0;
    data.add(NOW.minus(200, ChronoUnit.MILLIS), "open", values[i++]);
    data.add(NOW.minus(200, ChronoUnit.MILLIS), "high", values[i++]);
    data.add(NOW.minus(200, ChronoUnit.MILLIS), "low", values[i++]);
    data.add(NOW.minus(200, ChronoUnit.MILLIS), "close", values[i++]);
    data.add(NOW.minus(100, ChronoUnit.MILLIS), "open", values[i++]);
    data.add(NOW.minus(100, ChronoUnit.MILLIS), "high", values[i++]);
    data.add(NOW.minus(100, ChronoUnit.MILLIS), "low", values[i++]);
    data.add(NOW.minus(100, ChronoUnit.MILLIS), "close", values[i++]);
}
Example 18
Project: KinanCity-master  File: PtcCreationSummary.java View source code
private String getTimeInText() {
    StringBuilder sb = new StringBuilder();
    LocalDateTime tempDateTime = LocalDateTime.from(startTime);
    long hours = tempDateTime.until(endTime, ChronoUnit.HOURS);
    tempDateTime = tempDateTime.plusHours(hours);
    long minutes = tempDateTime.until(endTime, ChronoUnit.MINUTES);
    tempDateTime = tempDateTime.plusMinutes(minutes);
    long seconds = tempDateTime.until(endTime, ChronoUnit.SECONDS);
    if (hours > 0) {
        sb.append(hours).append("h ");
    }
    if (minutes > 0) {
        sb.append(minutes).append("m ");
    }
    sb.append(seconds).append("s ");
    return sb.toString();
}
Example 19
Project: MMDB-master  File: CommandPruneChannels.java View source code
@Override
public void processCommand(IMessage message, String[] params) {
    final LocalDateTime current = LocalDateTime.now();
    final int minDaysOfInactivity = params.length == 2 ? Integer.parseInt(params[1]) : 7;
    final EmbedBuilder embed = new EmbedBuilder();
    final Map<String, Integer> channels = new HashMap<>();
    for (final IChannel channel : message.getGuild().getChannels()) {
        if (channel.getName().equalsIgnoreCase("getting-started"))
            continue;
        try {
            final IMessage latest = channel.getMessages().getLatestMessage();
            if (latest != null) {
                final int daysSinceUsed = Math.toIntExact(ChronoUnit.DAYS.between(latest.getCreationDate(), current));
                if (daysSinceUsed >= minDaysOfInactivity)
                    channels.put("#" + channel.getName(), daysSinceUsed);
            }
        } catch (final ArrayIndexOutOfBoundsException e) {
            channels.put("#" + channel.getName(), -1);
        }
    }
    embed.ignoreNullEmptyFields();
    embed.withColor((int) (Math.random() * 0x1000000));
    embed.withDesc(Utilities.mapToString(Utilities.sortByValue(channels, true)));
    Utilities.sendMessage(message.getChannel(), "The following channels have not been used in " + minDaysOfInactivity + " days.", embed.build());
}
Example 20
Project: OpenLegislation-master  File: NotificationDigestFormatter.java View source code
/**
     * A default way of formatting a notification digest into text
     * @param digest NotificationDigest
     * @param getUrl Function<RegisteredNotification, String> - a function that gets the url for a notification
     * @return String
     */
public static String getDigestText(NotificationDigest digest, Function<RegisteredNotification, String> getUrl) {
    StringBuilder digestBuilder = new StringBuilder();
    digestBuilder.append("All ").append(digest.getType()).append(" notifications from ").append(digest.getStartDateTime().truncatedTo(ChronoUnit.SECONDS)).append(" to ").append(digest.getEndDateTime().truncatedTo(ChronoUnit.SECONDS)).append(":\n\n------------------------------------------------------------------------------------\n");
    digest.getNotifications().forEach( notification -> {
        digestBuilder.append("Occurred: ").append(notification.getOccurred()).append("\nId: ").append(notification.getId()).append("\nURL: ").append(getUrl.apply(notification)).append("\nType: ").append(notification.getType()).append("\nSummary: ").append(notification.getSummary());
        if (digest.isFull()) {
            digestBuilder.append("\nMessage: ").append(notification.getMessage());
        }
        digestBuilder.append("\n------------------------------------------------------------------------------------\n");
    });
    return digestBuilder.toString();
}
Example 21
Project: autopsy-master  File: TimeUnits.java View source code
public static TimeUnits fromChronoUnit(ChronoUnit chronoUnit) {
    switch(chronoUnit) {
        case FOREVER:
            return FOREVER;
        case ERAS:
        case MILLENNIA:
        case CENTURIES:
        case DECADES:
        case YEARS:
            return YEARS;
        case MONTHS:
            return MONTHS;
        case WEEKS:
        case DAYS:
            return DAYS;
        case HOURS:
        case HALF_DAYS:
            return HOURS;
        case MINUTES:
            return MINUTES;
        case SECONDS:
        case MILLIS:
        case MICROS:
        case NANOS:
            return SECONDS;
        default:
            return YEARS;
    }
}
Example 22
Project: diirt-master  File: ReportRateFrame.java View source code
@Override
public void pvChanged(PVReaderEvent<VDouble> event) {
    if (event.isValueChanged()) {
        valueLabel.setText(Double.toString(pv.getValue().getValue()));
        overallCounter++;
        Instant now = Instant.now();
        double avgRage = overallCounter / (overallTimestamp.until(now, ChronoUnit.SECONDS));
        avgRateLabel.setText("" + avgRage);
        if (now.compareTo(lastPeriodTimestamp.plus(measureInterval)) >= 0) {
            double currentRate = (overallCounter - lastPeriodCounter) / (lastPeriodTimestamp.until(now, ChronoUnit.SECONDS));
            currentRateLabel.setText("" + currentRate);
            lastPeriodTimestamp = now;
            lastPeriodCounter = overallCounter;
        }
    }
}
Example 23
Project: find-master  File: FindResult.java View source code
@SuppressWarnings("TypeMayBeWeakened")
private ZonedDateTime parseRelativeTime(final ZonedDateTime timeNow, final int timeAmount, final String timeUnit) {
    TemporalUnit temporalUnit = ChronoUnit.SECONDS;
    switch(timeUnit) {
        case "minute":
        case "minutes":
            temporalUnit = ChronoUnit.MINUTES;
            break;
        case "hour":
        case "hours":
            temporalUnit = ChronoUnit.HOURS;
            break;
        case "day":
        case "days":
            temporalUnit = ChronoUnit.DAYS;
            break;
        case "month":
        case "months":
            temporalUnit = ChronoUnit.MONTHS;
            break;
        case "year":
        case "years":
            temporalUnit = ChronoUnit.YEARS;
            break;
    }
    return timeNow.plus(timeAmount, temporalUnit);
}
Example 24
Project: forklift-master  File: ConsumerThread.java View source code
@Override
public void run() {
    running.set(true);
    LocalDateTime lastConnectAttemptTime;
    int connectAttempt = 0;
    do {
        lastConnectAttemptTime = LocalDateTime.now();
        log.info("starting consumer");
        try {
            consumer.listen();
        } catch (Exception e) {
            log.debug("Couldn't get connection", e);
        }
        synchronized (lock) {
            // If we are still running let's wait a little while and attempt to reconnect.
            if (running.get()) {
                // Reset connection attempts if we have been connected for longer than the max wait time.
                if (LocalDateTime.now().isAfter(lastConnectAttemptTime.plus(expoSeq[expoSeq.length - 1], ChronoUnit.SECONDS)))
                    connectAttempt = 0;
                try {
                    log.info("unexpected consumer shutdown - trying reconnect in {} seconds", expoSeq[connectAttempt]);
                    lock.wait(expoSeq[connectAttempt] * 1000);
                    // Never let the attempt number get bigger than the greatest backoff sequence number.
                    connectAttempt = Math.min(connectAttempt + 1, expoSeq.length - 1);
                } catch (InterruptedException ignored) {
                    log.error("", ignored);
                }
            }
        }
    } while (running.get());
}
Example 25
Project: kickr-master  File: RootResource.java View source code
@POST
@Path(Paths.LOGIN_PATH)
@UnitOfWork
public Response login(@FormData LoginForm loginForm) {
    String name = loginForm.name;
    String password = loginForm.password;
    String redirectTo = loginForm.redirectTo;
    Boolean rememberMe = loginForm.rememberMe;
    try {
        AccessToken token = authenticationService.authenticate(name, password, !rememberMe);
        Date validUntil = token.getValidUntil();
        // one year;
        long maxAge = 365 * 24 * 60 * 60;
        if (validUntil != null) {
            maxAge = Instant.now().until(validUntil.toInstant(), ChronoUnit.SECONDS);
        }
        if (redirectTo == null || redirectTo.isEmpty()) {
            redirectTo = "/?hello=1";
        }
        NewCookie userCookie = new NewCookie("__sid", token.getValue(), "/", null, null, (int) maxAge, false, true);
        return redirect(redirectTo).cookie(userCookie).build();
    } catch (AuthenticationException ex) {
        LoginView signinView = createView(LoginView.class).redirectTo(redirectTo).addError("Invalid credentials");
        return unauthorized().entity(signinView).build();
    }
}
Example 26
Project: openjdk-master  File: TestThaiBuddhistChronoImpl.java View source code
//-----------------------------------------------------------------------
// Verify  ThaiBuddhist Calendar matches java.util.Calendar for range
//-----------------------------------------------------------------------
@Test(dataProvider = "RangeVersusCalendar")
public void test_ThaiBuddhistChrono_vsCalendar(LocalDate isoStartDate, LocalDate isoEndDate) {
    Locale locale = Locale.forLanguageTag("th-TH--u-ca-buddhist");
    assertEquals(locale.toString(), "th_TH", "Unexpected locale");
    Calendar cal = java.util.Calendar.getInstance(locale);
    assertEquals(cal.getCalendarType(), "buddhist", "Unexpected calendar type");
    ThaiBuddhistDate thaiDate = ThaiBuddhistChronology.INSTANCE.date(isoStartDate);
    cal.setTimeZone(TimeZone.getTimeZone("GMT+00"));
    cal.set(Calendar.YEAR, thaiDate.get(ChronoField.YEAR));
    cal.set(Calendar.MONTH, thaiDate.get(ChronoField.MONTH_OF_YEAR) - 1);
    cal.set(Calendar.DAY_OF_MONTH, thaiDate.get(ChronoField.DAY_OF_MONTH));
    while (thaiDate.isBefore(isoEndDate)) {
        assertEquals(thaiDate.get(ChronoField.DAY_OF_MONTH), cal.get(Calendar.DAY_OF_MONTH), "Day mismatch in " + thaiDate + ";  cal: " + cal);
        assertEquals(thaiDate.get(ChronoField.MONTH_OF_YEAR), cal.get(Calendar.MONTH) + 1, "Month mismatch in " + thaiDate);
        assertEquals(thaiDate.get(ChronoField.YEAR_OF_ERA), cal.get(Calendar.YEAR), "Year mismatch in " + thaiDate);
        thaiDate = thaiDate.plus(1, ChronoUnit.DAYS);
        cal.add(Calendar.DAY_OF_MONTH, 1);
    }
}
Example 27
Project: openjdk8-jdk-master  File: TestThaiBuddhistChronoImpl.java View source code
//-----------------------------------------------------------------------
// Verify  ThaiBuddhist Calendar matches java.util.Calendar for range
//-----------------------------------------------------------------------
@Test(dataProvider = "RangeVersusCalendar")
public void test_ThaiBuddhistChrono_vsCalendar(LocalDate isoStartDate, LocalDate isoEndDate) {
    Locale locale = Locale.forLanguageTag("th-TH--u-ca-buddhist");
    assertEquals(locale.toString(), "th_TH", "Unexpected locale");
    Calendar cal = java.util.Calendar.getInstance(locale);
    assertEquals(cal.getCalendarType(), "buddhist", "Unexpected calendar type");
    ThaiBuddhistDate thaiDate = ThaiBuddhistChronology.INSTANCE.date(isoStartDate);
    cal.setTimeZone(TimeZone.getTimeZone("GMT+00"));
    cal.set(Calendar.YEAR, thaiDate.get(ChronoField.YEAR));
    cal.set(Calendar.MONTH, thaiDate.get(ChronoField.MONTH_OF_YEAR) - 1);
    cal.set(Calendar.DAY_OF_MONTH, thaiDate.get(ChronoField.DAY_OF_MONTH));
    while (thaiDate.isBefore(isoEndDate)) {
        assertEquals(thaiDate.get(ChronoField.DAY_OF_MONTH), cal.get(Calendar.DAY_OF_MONTH), "Day mismatch in " + thaiDate + ";  cal: " + cal);
        assertEquals(thaiDate.get(ChronoField.MONTH_OF_YEAR), cal.get(Calendar.MONTH) + 1, "Month mismatch in " + thaiDate);
        assertEquals(thaiDate.get(ChronoField.YEAR_OF_ERA), cal.get(Calendar.YEAR), "Year mismatch in " + thaiDate);
        thaiDate = thaiDate.plus(1, ChronoUnit.DAYS);
        cal.add(Calendar.DAY_OF_MONTH, 1);
    }
}
Example 28
Project: Raildelays-master  File: ExcelSheetItemWriterTest.java View source code
@Before
public void setUp() throws Exception {
    File directory = new File(CURRENT_PATH);
    if (!directory.exists()) {
        Assert.assertTrue("Cannot create a directory for the test", directory.mkdir());
    } else {
        cleanUp();
    }
    executionContext = MetaDataInstanceFactory.createStepExecution().getExecutionContext();
    writer = new ExcelSheetItemWriter<>();
    writer.setTemplate(new ClassPathResource("template.xls"));
    writer.setResource(new FileSystemResource(CURRENT_PATH + "output.xls"));
    writer.setRowAggregator(new ExcelRowAggregator());
    writer.setName("test");
    writer.setRowsToSkip(21);
    writer.setSheetIndex(0);
    writer.setShouldDeleteIfExists(false);
    writer.setUseItemIndex(true);
    writer.setCurrentItemIndex(0);
    writer.setMaxItemCount(40);
    writer.afterPropertiesSet();
    items = new ArrayList<>();
    List<LocalDate> dates = new ArrayList<>(80);
    for (int i = 0; i < 80; i++) {
        dates.add(LocalDate.now().minus(1, ChronoUnit.DAYS));
    }
    for (LocalDate date : dates) {
        BatchExcelRow from = //
        new BatchExcelRow.Builder(date, Sens.DEPARTURE).departureStation(//
        new Station("Liège-Guillemins")).arrivalStation(//
        new Station("Bruxelles-central")).expectedDepartureTime(//
        LocalTime.parse("08:00")).expectedArrivalTime(//
        LocalTime.parse("09:00")).expectedTrain1(//
        new TrainLine.Builder(466L).build()).effectiveDepartureTime(//
        LocalTime.parse("08:05")).effectiveArrivalTime(//
        LocalTime.parse("09:15")).effectiveTrain1(//
        new TrainLine.Builder(466L).build()).build();
        BatchExcelRow to = //
        new BatchExcelRow.Builder(date, Sens.ARRIVAL).departureStation(//
        new Station("Bruxelles-central")).arrivalStation(//
        new Station("Liège-Guillemins")).expectedDepartureTime(//
        LocalTime.parse("14:00")).expectedArrivalTime(//
        LocalTime.parse("15:00")).expectedTrain1(//
        new TrainLine.Builder(529L).build()).effectiveDepartureTime(//
        LocalTime.parse("14:05")).effectiveArrivalTime(//
        LocalTime.parse("15:15")).effectiveTrain1(//
        new TrainLine.Builder(529L).build()).build();
        items.add(from);
        items.add(to);
    }
}
Example 29
Project: sakuli-master  File: LogCleanUpResultServiceImplTest.java View source code
@Test
public void testTriggerAction() throws Exception {
    Files.createDirectories(tempLog);
    Path folder1 = Files.createDirectories(tempLog.resolve("folder1"));
    Path today = Files.createFile(folder1.resolve("today.log"));
    FileTime todayMinus15 = FileTime.from(Instant.now().minus(15, ChronoUnit.DAYS));
    Path toOld1 = createFileWithDate(folder1.resolve("today-15.log"), todayMinus15);
    Path toOld2 = createFileWithDate(tempLog.resolve("root-today-15.log"), todayMinus15);
    FileTime todayMinus13 = FileTime.from(Instant.now().minus(13, ChronoUnit.DAYS));
    Path notToOld = createFileWithDate(folder1.resolve("today-13.log"), todayMinus13);
    Path notToOld2 = createFileWithDate(tempLog.resolve("today-13.log"), todayMinus13);
    when(sakuliProperties.getLogFolder()).thenReturn(tempLog);
    testling.triggerAction();
    verify(testling, times(2)).cleanUpDirectory(any());
    assertTrue(Files.exists(folder1));
    assertTrue(Files.exists(today));
    assertTrue(Files.exists(notToOld));
    assertTrue(Files.exists(notToOld2));
    assertFalse(Files.exists(toOld1));
    assertFalse(Files.exists(toOld2));
}
Example 30
Project: tablesaw-master  File: DateMapUtils.java View source code
/**
     * Calculates the temporal difference between each element of the receiver and the respective element of the
     * argument
     * <p>
     * Missing values in either result in a Missing Value for the new column
     */
default FloatColumn difference(DateColumn column1, DateColumn column2, ChronoUnit unit) {
    FloatColumn newColumn = FloatColumn.create(column1.name() + " - " + column2.name());
    for (int r = 0; r < column1.size(); r++) {
        int c1 = column1.getInt(r);
        int c2 = column2.getInt(r);
        if (c1 == FloatColumn.MISSING_VALUE || c2 == FloatColumn.MISSING_VALUE) {
            newColumn.add(FloatColumn.MISSING_VALUE);
        } else {
            LocalDate value1 = PackedLocalDate.asLocalDate(c1);
            LocalDate value2 = PackedLocalDate.asLocalDate(c2);
            newColumn.add(unit.between(value1, value2));
        }
    }
    return newColumn;
}
Example 31
Project: buck-master  File: IdleKillerTest.java View source code
private static Duration toDuration(long time, TimeUnit timeUnit) {
    switch(timeUnit) {
        case DAYS:
            return Duration.ofDays(time);
        case HOURS:
            return Duration.ofHours(time);
        case MINUTES:
            return Duration.ofMinutes(time);
        case SECONDS:
            return Duration.ofSeconds(time);
        case MILLISECONDS:
            return Duration.ofMillis(time);
        case MICROSECONDS:
            return Duration.of(time, ChronoUnit.MICROS);
        case NANOSECONDS:
            return Duration.ofNanos(time);
    }
    throw new RuntimeException("unhandled TimeUnit case: " + timeUnit);
}
Example 32
Project: cas-master  File: DefaultAccountStateHandler.java View source code
/**
     * Handle an account state warning produced by ldaptive account state machinery.
     * <p>
     * Override this method to provide custom warning message handling.
     *
     * @param warning       the account state warning messages.
     * @param response      Ldaptive authentication response.
     * @param configuration Password policy configuration.
     * @param messages      Container for messages produced by account state warning handling.
     */
protected void handleWarning(final AccountState.Warning warning, final AuthenticationResponse response, final LdapPasswordPolicyConfiguration configuration, final List<MessageDescriptor> messages) {
    LOGGER.debug("Handling warning [{}]", warning);
    if (warning == null) {
        LOGGER.debug("Account state warning not defined");
        return;
    }
    final ZonedDateTime expDate = DateTimeUtils.zonedDateTimeOf(warning.getExpiration());
    final long ttl = ZonedDateTime.now(ZoneOffset.UTC).until(expDate, ChronoUnit.DAYS);
    LOGGER.debug("Password expires in [{}] days. Expiration warning threshold is [{}] days.", ttl, configuration.getPasswordWarningNumberOfDays());
    if (configuration.isAlwaysDisplayPasswordExpirationWarning() || ttl < configuration.getPasswordWarningNumberOfDays()) {
        messages.add(new PasswordExpiringWarningMessageDescriptor("Password expires in {0} days.", ttl));
    }
    if (warning.getLoginsRemaining() > 0) {
        messages.add(new DefaultMessageDescriptor("password.expiration.loginsRemaining", "You have {0} logins remaining before you MUST change your password.", warning.getLoginsRemaining()));
    }
}
Example 33
Project: collectors-master  File: TrackingJavaScriptResource.java View source code
private static ImmutableMap<String, Object> createScriptConstants(final BrowserSourceConfiguration browserSourceConfiguration) {
    final ImmutableMap.Builder<String, Object> builder = ImmutableMap.builder();
    builder.put("PARTY_COOKIE_NAME", browserSourceConfiguration.partyCookie);
    builder.put("PARTY_ID_TIMEOUT_SECONDS", trimLongToMaxInt(browserSourceConfiguration.partyTimeout.get(ChronoUnit.SECONDS)));
    builder.put("SESSION_COOKIE_NAME", browserSourceConfiguration.sessionCookie);
    builder.put("SESSION_ID_TIMEOUT_SECONDS", trimLongToMaxInt(browserSourceConfiguration.sessionTimeout.get(ChronoUnit.SECONDS)));
    browserSourceConfiguration.cookieDomain.ifPresent(( v) -> builder.put("COOKIE_DOMAIN", v));
    builder.put("LOGGING", browserSourceConfiguration.javascript.logging);
    builder.put(SCRIPT_CONSTANT_NAME, browserSourceConfiguration.javascript.name);
    builder.put("EVENT_SUFFIX", browserSourceConfiguration.eventSuffix);
    builder.put("AUTO_PAGE_VIEW_EVENT", browserSourceConfiguration.javascript.autoPageViewEvent);
    builder.put("EVENT_TIMEOUT_SECONDS", browserSourceConfiguration.javascript.eventTimeout.getSeconds() + browserSourceConfiguration.javascript.eventTimeout.getNano() / (double) NANOS_PER_SECOND);
    return builder.build();
}
Example 34
Project: controle-financeiro-master  File: UserMessage.java View source code
/**
     * Calcula o tempo que se passou desde o envio da mensagem
     */
public void calculateElapsedTime() {
    final LocalDateTime sentOn = LocalDateTime.ofInstant(this.message.getInclusion().toInstant(), ZoneId.systemDefault());
    if (sentOn.toLocalDate().isBefore(LocalDate.now())) {
        this.elapsedTime = DateTimeFormatter.ofPattern("dd/MM/yyyy HH:mm").format(sentOn);
    } else {
        long difference = ChronoUnit.MINUTES.between(sentOn.toLocalTime(), LocalTime.now());
        if (difference > 60) {
            difference = ChronoUnit.HOURS.between(sentOn.toLocalTime(), LocalTime.now());
            this.elapsedTime = String.valueOf(difference);
            this.timeUnit = "message-box.hours";
        } else {
            this.elapsedTime = String.valueOf(difference);
            this.timeUnit = "message-box.minutes";
        }
    }
}
Example 35
Project: cosigner-master  File: BasicValidator.java View source code
@Override
public boolean validateTransaction(CurrencyPackageInterface currency, String transaction) {
    LOGGER.debug("currency: " + currency.toString());
    LOGGER.debug("currency Wallet: " + currency.getWallet());
    LOGGER.debug("currency Wallet Class: " + currency.getWallet().getClass());
    if (!Validatable.class.isAssignableFrom(currency.getWallet().getClass())) {
        // Wallet can not be validated.
        LOGGER.debug("Tried validating: " + currency.getConfiguration().getCurrencySymbol() + ", was not Validatable.");
        return true;
    }
    if (!ValidatorConfiguration.class.isAssignableFrom(currency.getConfiguration().getClass())) {
        // Configuration is not set up, we can't validate.
        LOGGER.debug("Tried validating: " + currency.getConfiguration().getCurrencySymbol() + ", was not Configured.");
        return true;
    }
    LOGGER.debug("Attempting to validate: " + currency.getConfiguration().getCurrencySymbol());
    Wallet wallet = currency.getWallet();
    Validatable validatableWallet = (Validatable) currency.getWallet();
    ValidatorConfiguration validatorConfig = (ValidatorConfiguration) currency.getConfiguration();
    TransactionDetails txDetail = validatableWallet.decodeRawTransaction(transaction);
    if (validatorConfig.getMaxAmountPerTransaction().compareTo(BigDecimal.ZERO) != 0 && txDetail.getAmount().compareTo(validatorConfig.getMaxAmountPerTransaction()) > 0) {
        LOGGER.info("Transaction value too high for: " + txDetail.toString());
        return false;
    }
    // Build timed totals.
    BigDecimal hourlyTotal = BigDecimal.ZERO;
    BigDecimal dailyTotal = BigDecimal.ZERO;
    Instant oneHourAgo = Clock.systemUTC().instant().minus(1, ChronoUnit.HOURS);
    Instant oneDayAgo = Clock.systemUTC().instant().minus(1, ChronoUnit.DAYS);
    for (String senders : txDetail.getFromAddress()) {
        TransactionDetails[] txs = wallet.getTransactions(senders, 100, 0);
        for (TransactionDetails tx : txs) {
            if (tx.getTxDate().toInstant().isAfter(oneHourAgo)) {
                hourlyTotal = hourlyTotal.add(tx.getAmount());
            }
            if (tx.getTxDate().toInstant().isAfter(oneDayAgo)) {
                dailyTotal = dailyTotal.add(tx.getAmount());
            }
        }
    }
    // Verify that the tx + timed totals are within bounds.
    BigDecimal maxPerHour = validatorConfig.getMaxAmountPerHour();
    hourlyTotal = hourlyTotal.add(txDetail.getAmount());
    if (maxPerHour.compareTo(BigDecimal.ZERO) != 0 && hourlyTotal.compareTo(maxPerHour) > 0) {
        LOGGER.info("Transaction value exceeds hourly limit.");
        return false;
    }
    if (validatorConfig.getMaxAmountPerDay().compareTo(BigDecimal.ZERO) != 0 && dailyTotal.add(txDetail.getAmount()).compareTo(validatorConfig.getMaxAmountPerDay()) > 0) {
        LOGGER.info("Transaction value exceeds daily limit.");
        return false;
    }
    // Nothing failed, so it's ok.
    LOGGER.debug("Validation passed");
    return true;
}
Example 36
Project: divolte-collector-master  File: TrackingJavaScriptResource.java View source code
private static ImmutableMap<String, Object> createScriptConstants(final BrowserSourceConfiguration browserSourceConfiguration) {
    final ImmutableMap.Builder<String, Object> builder = ImmutableMap.builder();
    builder.put("PARTY_COOKIE_NAME", browserSourceConfiguration.partyCookie);
    builder.put("PARTY_ID_TIMEOUT_SECONDS", trimLongToMaxInt(browserSourceConfiguration.partyTimeout.get(ChronoUnit.SECONDS)));
    builder.put("SESSION_COOKIE_NAME", browserSourceConfiguration.sessionCookie);
    builder.put("SESSION_ID_TIMEOUT_SECONDS", trimLongToMaxInt(browserSourceConfiguration.sessionTimeout.get(ChronoUnit.SECONDS)));
    browserSourceConfiguration.cookieDomain.ifPresent(( v) -> builder.put("COOKIE_DOMAIN", v));
    builder.put("LOGGING", browserSourceConfiguration.javascript.logging);
    builder.put(SCRIPT_CONSTANT_NAME, browserSourceConfiguration.javascript.name);
    builder.put("EVENT_SUFFIX", browserSourceConfiguration.eventSuffix);
    builder.put("AUTO_PAGE_VIEW_EVENT", browserSourceConfiguration.javascript.autoPageViewEvent);
    return builder.build();
}
Example 37
Project: Enzo-master  File: Clock.java View source code
public final ObjectProperty<Duration> offsetProperty() {
    if (null == offset) {
        offset = new ObjectPropertyBase<Duration>() {

            @Override
            protected void invalidated() {
                set(clamp(Duration.of(-12, ChronoUnit.HOURS), Duration.of(12, ChronoUnit.HOURS), get()));
            }

            @Override
            public Object getBean() {
                return this;
            }

            @Override
            public String getName() {
                return "offset";
            }
        };
        offset = new SimpleObjectProperty<>(this, "offset", _offset);
    }
    return offset;
}
Example 38
Project: graphouse-master  File: MetricRowBinaryHttpEntity.java View source code
@VisibleForTesting
protected short getUnsignedDaysSinceEpoch(int timestampSeconds) {
    if (timestampSeconds >= todayStartSeconds && timestampSeconds < todayEndSeconds) {
        return currentDay;
    }
    LocalDate localDate = Instant.ofEpochSecond(timestampSeconds).atZone(ZoneId.systemDefault()).toLocalDate();
    short days = (short) ChronoUnit.DAYS.between(EPOCH, localDate);
    return (short) Short.toUnsignedInt(days);
}
Example 39
Project: gshell-master  File: HistoryAction.java View source code
private void renderEntry(final IO io, final History.Entry entry) {
    AttributedStringBuilder buff = new AttributedStringBuilder();
    if (timestamps) {
        LocalTime lt = LocalTime.from(entry.time().atZone(ZoneId.systemDefault())).truncatedTo(ChronoUnit.SECONDS);
        DateTimeFormatter.ISO_LOCAL_TIME.formatTo(lt, buff);
        buff.append(" ");
    }
    buff.style(buff.style().bold());
    buff.append(String.format("%3d", entry.index() + 1));
    buff.style(buff.style().boldOff());
    buff.append("  ").append(entry.line());
    io.println(buff.toAnsi(io.terminal));
}
Example 40
Project: HotSUploader-master  File: BattleLobbyWatcher.java View source code
private Runnable getInstantFileChecker() {
    return () -> {
        try {
            LocalDateTime end = LocalDateTime.now().plus(10, ChronoUnit.SECONDS);
            while (LocalDateTime.now().isBefore(end)) {
                File[] files = heroesDirectory.listFiles(fileNameFilter);
                for (File file : files != null ? files : new File[0]) {
                    File target = new File(file, REPLAY_SERVER_BATTLELOBBY);
                    if (target.exists()) {
                        handleFile(target);
                        return;
                    }
                }
                Thread.sleep(DELAY);
            }
        } catch (InterruptedException ignored) {
        }
    };
}
Example 41
Project: infinispan-master  File: HotRodAccessLoggingHandler.java View source code
@Override
public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
    if (startTime != null) {
        // We need the information from the context now, because we could clear the context soon after the write completes
        CacheDecodeContext cacheDecodeContext = ctx.channel().attr(LoggingContextHandler.DECODE_CONTEXT_KEY).get();
        HotRodOperation op;
        String cacheName;
        String status;
        String exception = ctx.channel().attr(LoggingContextHandler.EXCEPTION_MESSAGE_KEY).get();
        byte[] key;
        // This is only null if an exception was thrown before we could decode a proper message
        if (cacheDecodeContext != null && exception == null) {
            // Method
            op = cacheDecodeContext.getHeader().getOp();
            key = cacheDecodeContext.getKey();
            // Cache name
            cacheName = cacheDecodeContext.getHeader().getCacheName();
            status = "OK";
        } else {
            op = ctx.channel().attr(LoggingContextHandler.OPERATION_KEY).get();
            key = null;
            cacheName = ctx.channel().attr(LoggingContextHandler.CACHE_NAME_KEY).get();
            status = exception;
        }
        // IP
        String remoteAddress = ctx.channel().remoteAddress().toString();
        // Date of first byte read
        LocalDateTime startTime = this.startTime;
        this.startTime = null;
        // Request Length
        int bytesRead = this.bytesRead;
        this.bytesRead = 0;
        // Response Length - We rely on the fact that our encoder encodes the entire response in 1 write method
        int bytesWritten = getByteSize(msg);
        super.write(ctx, msg, promise.addListener( f -> {
            long ms;
            if (startTime == null) {
                ms = -1;
            } else {
                ms = ChronoUnit.MILLIS.between(startTime, LocalDateTime.now());
            }
            log.tracef("%s [%s] \"%s %s\" \"%s\" %s %d %d %d ms", remoteAddress, checkForNull(startTime), checkForNull(op), checkForNull(cacheName), status, checkForNull(key), bytesRead, bytesWritten, ms);
        }));
    } else {
        super.write(ctx, msg, promise);
    }
}
Example 42
Project: l2ahyura-master  File: TimeUtil.java View source code
/**
	 * Parses patterns like:
	 * <ul>
	 * <li>1min or 10mins</li>
	 * <li>1day or 10days</li>
	 * <li>1week or 4weeks</li>
	 * <li>1month or 12months</li>
	 * <li>1year or 5years</li>
	 * </ul>
	 * @param datePattern
	 * @return {@link Duration} object converted by the date pattern specified.
	 * @throws IllegalStateException when malformed pattern specified.
	 */
public static Duration parseDuration(String datePattern) {
    final int index = findIndexOfNonDigit(datePattern);
    if (index == -1) {
        throw new IllegalStateException("Incorrect time format given: " + datePattern);
    }
    try {
        int val = Integer.parseInt(datePattern.substring(0, index));
        final String type = datePattern.substring(index);
        final ChronoUnit unit;
        switch(type.toLowerCase()) {
            case "sec":
            case "secs":
                {
                    unit = ChronoUnit.SECONDS;
                    break;
                }
            case "min":
            case "mins":
                {
                    unit = ChronoUnit.MINUTES;
                    break;
                }
            case "hour":
            case "hours":
                {
                    unit = ChronoUnit.HOURS;
                    break;
                }
            case "day":
            case "days":
                {
                    unit = ChronoUnit.DAYS;
                    break;
                }
            case "week":
            case "weeks":
                {
                    unit = ChronoUnit.WEEKS;
                    break;
                }
            case "month":
            case "months":
                {
                    unit = ChronoUnit.MONTHS;
                    break;
                }
            case "year":
            case "years":
                {
                    unit = ChronoUnit.YEARS;
                    break;
                }
            default:
                {
                    unit = ChronoUnit.valueOf(type);
                    if (unit == null) {
                        throw new IllegalStateException("Incorrect format: " + type + " !!");
                    }
                }
        }
        return Duration.of(val, unit);
    } catch (Exception e) {
        throw new IllegalStateException("Incorrect time format given: " + datePattern + " val: " + datePattern.substring(0, index));
    }
}
Example 43
Project: L2J_LoginServer-master  File: TimeUtil.java View source code
/**
	 * Parses patterns like:
	 * <ul>
	 * <li>1min or 10mins</li>
	 * <li>1day or 10days</li>
	 * <li>1week or 4weeks</li>
	 * <li>1month or 12months</li>
	 * <li>1year or 5years</li>
	 * </ul>
	 * @param datePattern
	 * @return {@link Duration} object converted by the date pattern specified.
	 * @throws IllegalStateException when malformed pattern specified.
	 */
public static Duration parseDuration(String datePattern) {
    final int index = findIndexOfNonDigit(datePattern);
    if (index == -1) {
        throw new IllegalStateException("Incorrect time format given: " + datePattern);
    }
    try {
        int val = Integer.parseInt(datePattern.substring(0, index));
        final String type = datePattern.substring(index);
        final ChronoUnit unit;
        switch(type.toLowerCase()) {
            case "sec":
            case "secs":
                {
                    unit = ChronoUnit.SECONDS;
                    break;
                }
            case "min":
            case "mins":
                {
                    unit = ChronoUnit.MINUTES;
                    break;
                }
            case "hour":
            case "hours":
                {
                    unit = ChronoUnit.HOURS;
                    break;
                }
            case "day":
            case "days":
                {
                    unit = ChronoUnit.DAYS;
                    break;
                }
            case "week":
            case "weeks":
                {
                    unit = ChronoUnit.WEEKS;
                    break;
                }
            case "month":
            case "months":
                {
                    unit = ChronoUnit.MONTHS;
                    break;
                }
            case "year":
            case "years":
                {
                    unit = ChronoUnit.YEARS;
                    break;
                }
            default:
                {
                    unit = ChronoUnit.valueOf(type);
                    if (unit == null) {
                        throw new IllegalStateException("Incorrect format: " + type + " !!");
                    }
                }
        }
        return Duration.of(val, unit);
    } catch (Exception e) {
        throw new IllegalStateException("Incorrect time format given: " + datePattern + " val: " + datePattern.substring(0, index));
    }
}
Example 44
Project: platform_build-master  File: IdleKillerTest.java View source code
private static Duration toDuration(long time, TimeUnit timeUnit) {
    switch(timeUnit) {
        case DAYS:
            return Duration.ofDays(time);
        case HOURS:
            return Duration.ofHours(time);
        case MINUTES:
            return Duration.ofMinutes(time);
        case SECONDS:
            return Duration.ofSeconds(time);
        case MILLISECONDS:
            return Duration.ofMillis(time);
        case MICROSECONDS:
            return Duration.of(time, ChronoUnit.MICROS);
        case NANOSECONDS:
            return Duration.ofNanos(time);
    }
    throw new RuntimeException("unhandled TimeUnit case: " + timeUnit);
}
Example 45
Project: quickstart-master  File: DateService.java View source code
@GET
@Path("daysuntil/{targetdate}")
@Produces(MediaType.TEXT_PLAIN)
public long showDaysUntil(@PathParam("targetdate") String targetDate) {
    DateLogger.LOGGER.logDaysUntilRequest(targetDate);
    final long days;
    try {
        final LocalDate date = LocalDate.parse(targetDate, DateTimeFormatter.ISO_DATE);
        days = ChronoUnit.DAYS.between(LocalDate.now(), date);
    } catch (DateTimeParseException ex) {
        DateTimeParseException nex = DateExceptionsBundle.EXCEPTIONS.targetDateStringDidntParse(targetDate, ex.getParsedString(), ex.getErrorIndex());
        DateLogger.LOGGER.logStringCouldntParseAsDate(targetDate, nex);
        throw new WebApplicationException(Response.status(400).entity(nex.getLocalizedMessage()).type(MediaType.TEXT_PLAIN).build());
    }
    return days;
}
Example 46
Project: restheart-master  File: AuthTokenInjecterHandler.java View source code
private void injectTokenHeaders(HttpServerExchange exchange, HeadersManager headers, char[] token) {
    headers.addResponseHeader(AUTH_TOKEN_HEADER, new String(token));
    headers.addResponseHeader(AUTH_TOKEN_VALID_HEADER, Instant.now().plus(TTL, ChronoUnit.MINUTES).toString());
    headers.addResponseHeader(AUTH_TOKEN_LOCATION_HEADER, "/_authtokens/" + exchange.getSecurityContext().getAuthenticatedAccount().getPrincipal().getName());
}
Example 47
Project: sandboxes-master  File: BucketTest.java View source code
@Test
public void sample() throws Exception {
    Instant now = Instant.now();
    Instant earlier = now.minus(20, ChronoUnit.MINUTES);
    List<Event> events = Arrays.asList(new Event(now, "now"), new Event(earlier, "earlier"));
    List<Event> sortedEvents = events.stream().sorted(byTimeStamp()).collect(Collectors.toList());
    Duration samplingRate = Duration.ofMinutes(1);
    Duration inspectionRange = Duration.ofMinutes(10);
    Instant earliest = sortedEvents.get(0).timestamp;
    Instant latest = sortedEvents.get(sortedEvents.size() - 1).timestamp;
    BucketAssemblyLine bucketAssemblyLine = new BucketAssemblyLine(samplingRate, inspectionRange, earlier);
}
Example 48
Project: stocks-master  File: TimelineChart.java View source code
private void paintTimeGrid(PaintEvent e) {
    IAxis xAxis = getAxisSet().getXAxis(0);
    Range range = xAxis.getRange();
    ZoneId zoneId = ZoneId.systemDefault();
    LocalDate start = Instant.ofEpochMilli((long) range.lower).atZone(zoneId).toLocalDate();
    LocalDate end = Instant.ofEpochMilli((long) range.upper).atZone(zoneId).toLocalDate();
    LocalDate cursor = start.getDayOfMonth() == 1 ? start : start.plusMonths(1).withDayOfMonth(1);
    Period period;
    DateTimeFormatter format;
    long days = ChronoUnit.DAYS.between(start, end);
    if (days < 250) {
        period = Period.ofMonths(1);
        //$NON-NLS-1$
        format = DateTimeFormatter.ofPattern("MMMM yyyy");
    } else if (days < 800) {
        period = Period.ofMonths(3);
        //$NON-NLS-1$
        format = DateTimeFormatter.ofPattern("QQQ yyyy");
        cursor = cursor.plusMonths((12 - cursor.getMonthValue() + 1) % 3);
    } else if (days < 1200) {
        period = Period.ofMonths(6);
        //$NON-NLS-1$
        format = DateTimeFormatter.ofPattern("QQQ yyyy");
        cursor = cursor.plusMonths((12 - cursor.getMonthValue() + 1) % 6);
    } else {
        period = Period.ofYears(days > 5000 ? 2 : 1);
        //$NON-NLS-1$
        format = DateTimeFormatter.ofPattern("yyyy");
        if (cursor.getMonthValue() > 1)
            cursor = cursor.plusYears(1).withDayOfYear(1);
    }
    while (cursor.isBefore(end)) {
        int y = xAxis.getPixelCoordinate((double) cursor.atStartOfDay(zoneId).toInstant().toEpochMilli());
        e.gc.drawLine(y, 0, y, e.height);
        e.gc.drawText(format.format(cursor), y + 5, 5);
        cursor = cursor.plus(period);
    }
}
Example 49
Project: web-budget-master  File: UserMessage.java View source code
/**
     * Calcula o tempo que se passou desde o envio da mensagem
     */
public void calculateElapsedTime() {
    final LocalDateTime sentOn = LocalDateTime.ofInstant(this.message.getInclusion().toInstant(), ZoneId.systemDefault());
    if (sentOn.toLocalDate().isBefore(LocalDate.now())) {
        this.elapsedTime = DateTimeFormatter.ofPattern("dd/MM/yyyy HH:mm").format(sentOn);
    } else {
        long difference = ChronoUnit.MINUTES.between(sentOn.toLocalTime(), LocalTime.now());
        if (difference > 60) {
            difference = ChronoUnit.HOURS.between(sentOn.toLocalTime(), LocalTime.now());
            this.elapsedTime = String.valueOf(difference);
            this.timeUnit = "message-box.hours";
        } else {
            this.elapsedTime = String.valueOf(difference);
            this.timeUnit = "message-box.minutes";
        }
    }
}
Example 50
Project: wildfly-master  File: ImmutableHttpSessionAdapterTestCase.java View source code
@Test
public void getMaxInactiveInterval() {
    SessionMetaData metaData = mock(SessionMetaData.class);
    Duration interval = Duration.of(100L, ChronoUnit.SECONDS);
    when(this.session.getMetaData()).thenReturn(metaData);
    when(metaData.getMaxInactiveInterval()).thenReturn(interval);
    int result = this.httpSession.getMaxInactiveInterval();
    assertEquals(interval.getSeconds(), result);
}
Example 51
Project: XCoLab-master  File: LoginTokenController.java View source code
@PostMapping("/members/{memberId}/loginToken")
public LoginToken generateToken(@PathVariable long memberId) throws NotFoundException {
    String tokenId = Long.toHexString(SecureRandomUtil.nextLong());
    String tokenKey = Long.toHexString(SecureRandomUtil.nextLong());
    Instant tokenExpirationDate = Instant.now().plus(7, ChronoUnit.DAYS);
    final Member member = memberDao.getMember(memberId).orElseThrow(NotFoundException::new);
    member.setLoginTokenId(tokenId);
    member.setLoginTokenKey(memberService.hashPassword(tokenKey));
    member.setLoginTokenExpirationDate(Timestamp.from(tokenExpirationDate));
    memberDao.updateMember(member);
    return new LoginToken(tokenId, tokenKey, tokenExpirationDate);
}
Example 52
Project: business-hours-java-master  File: BusinessPeriodTest.java View source code
@Test
public void timeBeforeOpening() {
    assertEquals(new BusinessPeriod(BusinessTemporal.of(Collections.singletonMap(ChronoField.MINUTE_OF_HOUR, 10)), BusinessTemporal.of(Collections.singletonMap(ChronoField.MINUTE_OF_HOUR, 15))).timeBeforeOpening(LocalTime.of(0, 9, 1), ChronoUnit.SECONDS), 59);
    assertEquals(new BusinessPeriod(BusinessTemporal.of(Collections.singletonMap(ChronoField.MINUTE_OF_HOUR, 10)), BusinessTemporal.of(Collections.singletonMap(ChronoField.MINUTE_OF_HOUR, 15))).timeBeforeOpening(LocalTime.of(0, 10, 0), ChronoUnit.SECONDS), 0);
    assertEquals(new BusinessPeriod(BusinessTemporal.of(Collections.singletonMap(ChronoField.MINUTE_OF_HOUR, 10)), BusinessTemporal.of(Collections.singletonMap(ChronoField.MINUTE_OF_HOUR, 15))).timeBeforeOpening(LocalTime.of(0, 10, 1), ChronoUnit.SECONDS), 3599);
    assertEquals(new BusinessPeriod(BusinessTemporal.of(Collections.singletonMap(ChronoField.MINUTE_OF_HOUR, 0)), BusinessTemporal.of(Collections.singletonMap(ChronoField.MINUTE_OF_HOUR, 59))).timeBeforeOpening(LocalTime.of(0, 0), ChronoUnit.MINUTES), Long.MAX_VALUE);
}
Example 53
Project: cerebro-master  File: AlertService.java View source code
/**
     * Method to calc a from Instant with a e.g. "1d", "5h", etc.
     *
     * Can compute unit:
     * - m
     * - h
     * - d
     *
     * @param from from parameter with unit
     * @return An Instant, e.g. now minus 2 day with a from parameter = "2d"
     */
private Instant calcFromInstant(final String from) {
    Instant result = null;
    if (from.contains("m")) {
        final int nb = Integer.valueOf(from.replace("m", ""));
        result = Instant.now().minus(nb, ChronoUnit.MINUTES);
    }
    if (from.contains("d")) {
        final int nb = Integer.valueOf(from.replace("d", ""));
        result = Instant.now().minus(nb, ChronoUnit.DAYS);
    }
    if (from.contains("h")) {
        final int nb = Integer.valueOf(from.replace("h", ""));
        result = Instant.now().minus(nb, ChronoUnit.HOURS);
    }
    return result;
}
Example 54
Project: cloudbreak-master  File: UsageGeneratorService.java View source code
public CloudbreakUsage createFullClosed(CloudbreakUsage usage, Date day) {
    CloudbreakUsage newUsage = new CloudbreakUsage();
    newUsage.setStackUuid(usage.getStackUuid());
    newUsage.setParentUuid(parentUuid);
    newUsage.setOwner(usage.getOwner());
    newUsage.setAccount(usage.getAccount());
    newUsage.setProvider(usage.getProvider());
    newUsage.setRegion(usage.getRegion());
    newUsage.setAvailabilityZone(usage.getAvailabilityZone());
    newUsage.setInstanceHours(HOURS_IN_DAY * usage.getInstanceNum());
    newUsage.setDay(day);
    newUsage.setStackId(usage.getStackId());
    newUsage.setStackName(usage.getStackName());
    newUsage.setInstanceType(usage.getInstanceType());
    newUsage.setInstanceNum(usage.getInstanceNum());
    newUsage.setPeak(usage.getInstanceNum());
    newUsage.setInstanceGroup(usage.getInstanceGroup());
    newUsage.setBlueprintId(usage.getBlueprintId());
    newUsage.setBlueprintName(usage.getBlueprintName());
    newUsage.setPeriodStarted(day);
    newUsage.setDuration(Duration.of(HOURS_IN_DAY, ChronoUnit.HOURS).multipliedBy(usage.getInstanceNum()).toString());
    newUsage.setStatus(UsageStatus.CLOSED);
    newUsage.setCosts(usagePriceService.calculateCostOfUsage(newUsage));
    newUsage.setFlexId(usage.getFlexId());
    newUsage.setSmartSenseId(usage.getSmartSenseId());
    return newUsage;
}
Example 55
Project: data-quality-master  File: DurationConverter.java View source code
/**
     * get the days more exactly with what we want. because:
     * 1 year = 365 days = 12 months (!= 12 * 30)
     * 1 month = 30 days
     * 1 week = 7 days
     * 
     * for example:
     * 13 months = 1*365+1*30 != 13*30.
     * 5 weeks = 5*7 != 1*30+1*7
     * 
     * @param value
     * @param days
     * @return
     */
protected double getExactDays(double value, double days) {
    if (this.fromUnit == ChronoUnit.MONTHS) {
        int year = (int) (value / num_12);
        int month = (int) (value % num_12);
        return year * num_365 + month * num_30;
    } else if (this.fromUnit == ChronoUnit.WEEKS) {
        int year = (int) (value / num_52);
        int week = (int) (value % num_52);
        return year * num_365 + week * num_7;
    }
    return days;
}
Example 56
Project: finmath-lib-master  File: BusinessdayCalendar.java View source code
/**
	 * Create a new date by "adding" a year fraction to a given base date.
	 * 
	 * <p>
	 * The date offset may be given by codes like 1D, 2D, 1W, 2W, 1M, 2M, 3M,
	 * 1Y, 2Y, etc., where the letters denote the units as follows: D denotes days, W denotes weeks, M denotes month
	 * Y denotes years. If the date offset does not carry a letter code at the end, it will
	 * be interpreted as ACT/365 year fraction.
	 * </p>
	 * 
	 * <p>
	 * The function may be used to ease the creation of maturities in spreadsheets.
	 * </p>
	 * 
	 * @param baseDate The start date.
	 * @param dateOffsetCode String containing date offset codes (like 2D, 1W, 3M, etc.) or combination of them separated by spaces.
	 * @return A date corresponding the date adding the offset to the start date.
	 */
public static LocalDate createDateFromDateAndOffsetCode(LocalDate baseDate, String dateOffsetCode) {
    dateOffsetCode = dateOffsetCode.trim();
    StringTokenizer tokenizer = new StringTokenizer(dateOffsetCode);
    LocalDate maturity = baseDate;
    while (tokenizer.hasMoreTokens()) {
        String maturityCodeSingle = tokenizer.nextToken();
        char unitChar = maturityCodeSingle.toLowerCase().charAt(maturityCodeSingle.length() - 1);
        ChronoUnit unit;
        switch(unitChar) {
            case 'd':
                unit = ChronoUnit.DAYS;
                break;
            case 'w':
                unit = ChronoUnit.WEEKS;
                break;
            case 'm':
                unit = ChronoUnit.MONTHS;
                break;
            case 'y':
                unit = ChronoUnit.YEARS;
                break;
            default:
                unit = null;
        }
        if (unit != null) {
            int maturityValue = Integer.valueOf(maturityCodeSingle.substring(0, maturityCodeSingle.length() - 1));
            maturity = maturity.plus(maturityValue, unit);
        } else {
            // Try to parse a double as ACT/365
            double maturityValue = Double.valueOf(maturityCodeSingle);
            maturity = maturity.plusDays((int) Math.round(maturityValue * 365));
        }
    }
    return maturity;
}
Example 57
Project: fiware-cepheus-master  File: RegistrationsRepositoryTest.java View source code
@Test
public void saveRegistrationTest() throws URISyntaxException, RegistrationPersistenceException {
    RegisterContext registerContext = createRegisterContextTemperature();
    registerContext.setRegistrationId("12345");
    Registration registration = new Registration(Instant.now().plus(1, ChronoUnit.DAYS), registerContext);
    registrationsRepository.saveRegistration(registration);
    Map<String, Registration> registrations = registrationsRepository.getAllRegistrations();
    Assert.assertEquals(1, registrations.size());
    Assert.assertEquals(registration.getExpirationDate(), registrations.get("12345").getExpirationDate());
    Assert.assertEquals(registerContext.getDuration(), registrations.get("12345").getRegisterContext().getDuration());
}
Example 58
Project: framework-master  File: AbstractLocalDateTimeField.java View source code
private LocalDateTime getDate(LocalDateTime date, DateTimeResolution forResolution) {
    if (date == null) {
        return null;
    }
    switch(forResolution) {
        case YEAR:
            return date.withDayOfYear(1).toLocalDate().atStartOfDay();
        case MONTH:
            return date.withDayOfMonth(1).toLocalDate().atStartOfDay();
        case DAY:
            return date.toLocalDate().atStartOfDay();
        case HOUR:
            return date.truncatedTo(ChronoUnit.HOURS);
        case MINUTE:
            return date.truncatedTo(ChronoUnit.MINUTES);
        case SECOND:
            return date.truncatedTo(ChronoUnit.SECONDS);
        default:
            assert false : "Unexpected resolution argument " + forResolution;
            return null;
    }
}
Example 59
Project: graphhopper-master  File: GraphExplorer.java View source code
private boolean isValidOn(EdgeIteratorState edge, long instant) {
    GtfsStorage.EdgeType edgeType = flagEncoder.getEdgeType(edge.getFlags());
    if (edgeType == GtfsStorage.EdgeType.BOARD || edgeType == GtfsStorage.EdgeType.ALIGHT) {
        final int validityId = flagEncoder.getValidityId(edge.getFlags());
        final GtfsStorage.Validity validity = gtfsStorage.getValidities().get(validityId);
        final int trafficDay = (int) ChronoUnit.DAYS.between(validity.start, Instant.ofEpochMilli(instant).atZone(validity.zoneId).toLocalDate());
        return validity.validity.get(trafficDay);
    } else {
        return true;
    }
}
Example 60
Project: heron-master  File: BoltInstance.java View source code
private void PrepareTickTupleTimer() {
    Object tickTupleFreqSecs = helper.getTopologyContext().getTopologyConfig().get(Config.TOPOLOGY_TICK_TUPLE_FREQ_SECS);
    if (tickTupleFreqSecs != null) {
        Duration freq = TypeUtils.getDuration(tickTupleFreqSecs, ChronoUnit.SECONDS);
        Runnable r = new Runnable() {

            public void run() {
                SendTickTuple();
            }
        };
        looper.registerTimerEvent(freq, r);
    }
}
Example 61
Project: idnadrev-master  File: WorkOnTaskTest.java View source code
@Before
public void setUp() throws Exception {
    cleanup.cleanup();
    Context context = new Context("context");
    Task task = new Task("task").setProject(true);
    task.setContext(context);
    WorkUnit workUnit = new WorkUnit(task);
    workUnit.setStart(LocalDateTime.now().minus(7, ChronoUnit.MINUTES));
    workUnit.stop();
    task.setEstimatedTime(Duration.ofMinutes(10));
    PersistentWork.persist(context, task, workUnit);
    activityController.startOrResume(new ActivityHint(ViewTasksActvity.class));
    activityController.waitForTasks();
    FXPlatform.waitForFX();
    ActivityHint hint = new ActivityHint(WorkOnTaskActivity.class, activityController.getCurrentActivityId()).setDataSourceHint(() -> task);
    activityController.startOrResume(hint);
    activityController.waitForTasks();
    controller = activityController.getControllerInstance(WorkOnTask.class);
}
Example 62
Project: java-learning-master  File: DateTimeExamples.java View source code
private static void useLocalDate() {
    LocalDate date = LocalDate.of(2014, 3, 18);
    // 2014
    int year = date.getYear();
    // MARCH
    Month month = date.getMonth();
    // 18
    int day = date.getDayOfMonth();
    // TUESDAY
    DayOfWeek dow = date.getDayOfWeek();
    // 31 (days in March)
    int len = date.lengthOfMonth();
    // false (not a leap year)
    boolean leap = date.isLeapYear();
    System.out.println(date);
    int y = date.get(ChronoField.YEAR);
    int m = date.get(ChronoField.MONTH_OF_YEAR);
    int d = date.get(ChronoField.DAY_OF_MONTH);
    // 13:45:20
    LocalTime time = LocalTime.of(13, 45, 20);
    // 13
    int hour = time.getHour();
    // 45
    int minute = time.getMinute();
    // 20
    int second = time.getSecond();
    System.out.println(time);
    // 2014-03-18T13:45
    LocalDateTime dt1 = LocalDateTime.of(2014, Month.MARCH, 18, 13, 45, 20);
    LocalDateTime dt2 = LocalDateTime.of(date, time);
    LocalDateTime dt3 = date.atTime(13, 45, 20);
    LocalDateTime dt4 = date.atTime(time);
    LocalDateTime dt5 = time.atDate(date);
    System.out.println(dt1);
    LocalDate date1 = dt1.toLocalDate();
    System.out.println(date1);
    LocalTime time1 = dt1.toLocalTime();
    System.out.println(time1);
    Instant instant = Instant.ofEpochSecond(44 * 365 * 86400);
    Instant now = Instant.now();
    Duration d1 = Duration.between(LocalTime.of(13, 45, 10), time);
    Duration d2 = Duration.between(instant, now);
    System.out.println(d1.getSeconds());
    System.out.println(d2.getSeconds());
    Duration threeMinutes = Duration.of(3, ChronoUnit.MINUTES);
    System.out.println(threeMinutes);
    JapaneseDate japaneseDate = JapaneseDate.from(date);
    System.out.println(japaneseDate);
}
Example 63
Project: Java8InAction-master  File: DateTimeExamples.java View source code
private static void useLocalDate() {
    LocalDate date = LocalDate.of(2014, 3, 18);
    // 2014
    int year = date.getYear();
    // MARCH
    Month month = date.getMonth();
    // 18
    int day = date.getDayOfMonth();
    // TUESDAY
    DayOfWeek dow = date.getDayOfWeek();
    // 31 (days in March)
    int len = date.lengthOfMonth();
    // false (not a leap year)
    boolean leap = date.isLeapYear();
    System.out.println(date);
    int y = date.get(ChronoField.YEAR);
    int m = date.get(ChronoField.MONTH_OF_YEAR);
    int d = date.get(ChronoField.DAY_OF_MONTH);
    // 13:45:20
    LocalTime time = LocalTime.of(13, 45, 20);
    // 13
    int hour = time.getHour();
    // 45
    int minute = time.getMinute();
    // 20
    int second = time.getSecond();
    System.out.println(time);
    // 2014-03-18T13:45
    LocalDateTime dt1 = LocalDateTime.of(2014, Month.MARCH, 18, 13, 45, 20);
    LocalDateTime dt2 = LocalDateTime.of(date, time);
    LocalDateTime dt3 = date.atTime(13, 45, 20);
    LocalDateTime dt4 = date.atTime(time);
    LocalDateTime dt5 = time.atDate(date);
    System.out.println(dt1);
    LocalDate date1 = dt1.toLocalDate();
    System.out.println(date1);
    LocalTime time1 = dt1.toLocalTime();
    System.out.println(time1);
    Instant instant = Instant.ofEpochSecond(44 * 365 * 86400);
    Instant now = Instant.now();
    Duration d1 = Duration.between(LocalTime.of(13, 45, 10), time);
    Duration d2 = Duration.between(instant, now);
    System.out.println(d1.getSeconds());
    System.out.println(d2.getSeconds());
    Duration threeMinutes = Duration.of(3, ChronoUnit.MINUTES);
    System.out.println(threeMinutes);
    JapaneseDate japaneseDate = JapaneseDate.from(date);
    System.out.println(japaneseDate);
}
Example 64
Project: javamoney-examples-master  File: ConversionsTest.java View source code
@Test
public void testGetExchangeRatewithTime() throws Exception {
    long now = System.currentTimeMillis();
    LocalDate[] times = new LocalDate[] { LocalDate.now(), LocalDate.now().minus(1, ChronoUnit.YEARS), LocalDate.now().minus(2, ChronoUnit.YEARS), LocalDate.now().minus(3, ChronoUnit.YEARS) };
    CurrencyUnit[] units = new CurrencyUnit[] { Monetary.getCurrency("CHF"), Monetary.getCurrency("EUR"), Monetary.getCurrency("USD") };
    for (CurrencyUnit u1 : units) {
        for (CurrencyUnit u2 : units) {
            if (u1.equals(u2)) {
                continue;
            }
            for (LocalDate time : times) {
                boolean exception = false;
                ExchangeRate expected = null;
                try {
                    expected = MonetaryConversions.getExchangeRateProvider("IMF").getExchangeRate(ConversionQueryBuilder.of().set(time).setBaseCurrency(u1).setTermCurrency(u2).build());
                } catch (Exception e) {
                    exception = true;
                }
                ExchangeRate r = conv.getExchangeRateWithTime(u1, u2, time);
                try {
                    assertEquals(expected, r);
                } catch (Exception e) {
                    if (!exception) {
                        throw e;
                    }
                }
            }
        }
    }
}
Example 65
Project: jbpm-master  File: DateTimeUtils.java View source code
public static long[] parseRepeatableDateTime(String dateTimeStr) {
    long[] result = new long[3];
    if (isRepeatable(dateTimeStr)) {
        String[] parsed = parseISORepeatable(dateTimeStr);
        String repeats = parsed[0];
        String delayIn = parsed[1];
        String periodIn = parsed[2];
        Duration startAtDelayDur = null;
        Duration period = null;
        if (DateTimeUtils.isPeriod(delayIn)) {
            // If delay is specified as duration then period variable carry end time information
            OffsetDateTime endTime = OffsetDateTime.parse(periodIn, DateTimeFormatter.ISO_DATE_TIME);
            period = Duration.parse(delayIn);
            startAtDelayDur = Duration.between(OffsetDateTime.now(), endTime.minus(period));
        } else if (DateTimeUtils.isPeriod(periodIn)) {
            // If period is specified as duration then delay variable carry start time information
            OffsetDateTime startTime = OffsetDateTime.parse(delayIn, DateTimeFormatter.ISO_DATE_TIME);
            period = Duration.parse(periodIn);
            startAtDelayDur = Duration.between(OffsetDateTime.now(), startTime);
        } else {
            // Both delay and period are specified as start and end times
            OffsetDateTime startTime = OffsetDateTime.parse(delayIn, DateTimeFormatter.ISO_DATE_TIME);
            OffsetDateTime endTime = OffsetDateTime.parse(periodIn, DateTimeFormatter.ISO_DATE_TIME);
            startAtDelayDur = Duration.between(OffsetDateTime.now(), startTime);
            period = Duration.between(startTime, endTime);
        }
        if (startAtDelayDur.isNegative() || startAtDelayDur.isZero()) {
            // need to introduce delay to allow all initialization
            startAtDelayDur = Duration.of(1, ChronoUnit.SECONDS);
        }
        result[0] = Long.parseLong(repeats.length() == 0 ? "-1" : repeats);
        result[1] = startAtDelayDur.toMillis();
        result[2] = period.toMillis();
        return result;
    } else {
        int index = dateTimeStr.indexOf("###");
        if (index != -1) {
            String period = dateTimeStr.substring(index + 3);
            String delay = dateTimeStr.substring(0, index);
            result = new long[] { TimeUtils.parseTimeString(delay), TimeUtils.parseTimeString(period) };
            return result;
        }
        result = new long[] { TimeUtils.parseTimeString(dateTimeStr) };
        return result;
    }
}
Example 66
Project: jhipster-sample-app-elasticsearch-master  File: UserService.java View source code
/**
     * Not activated users should be automatically deleted after 3 days.
     * <p>
     * This is scheduled to get fired everyday, at 01:00 (am).
     * </p>
     */
@Scheduled(cron = "0 0 1 * * ?")
public void removeNotActivatedUsers() {
    List<User> users = userRepository.findAllByActivatedIsFalseAndCreatedDateBefore(Instant.now().minus(3, ChronoUnit.DAYS));
    for (User user : users) {
        log.debug("Deleting not activated user {}", user.getLogin());
        userRepository.delete(user);
        userSearchRepository.delete(user);
    }
}
Example 67
Project: jhipster-sample-app-gradle-master  File: UserServiceIntTest.java View source code
@Test
public void assertThatResetKeyMustNotBeOlderThan24Hours() {
    User user = userService.createUser("johndoe", "johndoe", "John", "Doe", "john.doe@localhost", "http://placehold.it/50x50", "en-US");
    Instant daysAgo = Instant.now().minus(25, ChronoUnit.HOURS);
    String resetKey = RandomUtil.generateResetKey();
    user.setActivated(true);
    user.setResetDate(daysAgo);
    user.setResetKey(resetKey);
    userRepository.save(user);
    Optional<User> maybeUser = userService.completePasswordReset("johndoe2", user.getResetKey());
    assertThat(maybeUser.isPresent()).isFalse();
    userRepository.delete(user);
}
Example 68
Project: jhipster-sample-app-master  File: UserServiceIntTest.java View source code
@Test
public void assertThatResetKeyMustNotBeOlderThan24Hours() {
    User user = userService.createUser("johndoe", "johndoe", "John", "Doe", "john.doe@localhost", "http://placehold.it/50x50", "en-US");
    Instant daysAgo = Instant.now().minus(25, ChronoUnit.HOURS);
    String resetKey = RandomUtil.generateResetKey();
    user.setActivated(true);
    user.setResetDate(daysAgo);
    user.setResetKey(resetKey);
    userRepository.save(user);
    Optional<User> maybeUser = userService.completePasswordReset("johndoe2", user.getResetKey());
    assertThat(maybeUser.isPresent()).isFalse();
    userRepository.delete(user);
}
Example 69
Project: jhipster-sample-app-mongodb-master  File: UserServiceIntTest.java View source code
@Test
public void assertThatResetKeyMustNotBeOlderThan24Hours() {
    User user = userService.createUser("johndoe", "johndoe", "John", "Doe", "john.doe@localhost", "http://placehold.it/50x50", "en-US");
    Instant daysAgo = Instant.now().minus(25, ChronoUnit.HOURS);
    String resetKey = RandomUtil.generateResetKey();
    user.setActivated(true);
    user.setResetDate(daysAgo);
    user.setResetKey(resetKey);
    userRepository.save(user);
    Optional<User> maybeUser = userService.completePasswordReset("johndoe2", user.getResetKey());
    assertThat(maybeUser.isPresent()).isFalse();
    userRepository.delete(user);
}
Example 70
Project: jhipster-sample-app-ng2-master  File: UserServiceIntTest.java View source code
@Test
public void assertThatResetKeyMustNotBeOlderThan24Hours() {
    User user = userService.createUser("johndoe", "johndoe", "John", "Doe", "john.doe@localhost", "http://placehold.it/50x50", "en-US");
    Instant daysAgo = Instant.now().minus(25, ChronoUnit.HOURS);
    String resetKey = RandomUtil.generateResetKey();
    user.setActivated(true);
    user.setResetDate(daysAgo);
    user.setResetKey(resetKey);
    userRepository.save(user);
    Optional<User> maybeUser = userService.completePasswordReset("johndoe2", user.getResetKey());
    assertThat(maybeUser.isPresent()).isFalse();
    userRepository.delete(user);
}
Example 71
Project: jmeter-master  File: TestTimeShiftFunction.java View source code
@Test
public void testDefault() throws Exception {
    Collection<CompoundVariable> params = makeParams("", "", "", "");
    function.setParameters(params);
    value = function.execute(result, null);
    long resultat = Long.parseLong(value);
    LocalDateTime nowFromFunction = LocalDateTime.ofInstant(Instant.ofEpochMilli(resultat), TimeZone.getDefault().toZoneId());
    assertThat(nowFromFunction, within(5, ChronoUnit.SECONDS, LocalDateTime.now()));
}
Example 72
Project: ldaptive-master  File: GeneralizedTimeValueTranscoder.java View source code
/**
   * Parses the supplied value and returns a date time.
   *
   * @param  value  of generalized time to parse
   *
   * @return  date time initialized to the correct time
   *
   * @throws  ParseException  if the value does not contain correct generalized time syntax
   */
protected ZonedDateTime parseGeneralizedTime(final String value) throws ParseException {
    if (value == null) {
        throw new IllegalArgumentException("String to parse cannot be null.");
    }
    final Matcher m = TIME_REGEX.matcher(value);
    if (!m.matches()) {
        throw new ParseException("Invalid generalized time string.", value.length());
    }
    // CheckStyle:MagicNumber OFF
    final ZoneId zoneId;
    final String tzString = m.group(9);
    if ("Z".equals(tzString)) {
        zoneId = ZoneOffset.UTC;
    } else {
        zoneId = ZoneId.of("GMT" + tzString);
    }
    // Set required time fields
    final int year = Integer.parseInt(m.group(1));
    final int month = Integer.parseInt(m.group(2));
    final int dayOfMonth = Integer.parseInt(m.group(3));
    final int hour = Integer.parseInt(m.group(4));
    FractionalPart fraction = FractionalPart.Hours;
    // Set optional minutes
    int minutes = 0;
    if (m.group(5) != null) {
        fraction = FractionalPart.Minutes;
        minutes = Integer.parseInt(m.group(5));
    }
    // Set optional seconds
    int seconds = 0;
    if (m.group(6) != null) {
        fraction = FractionalPart.Seconds;
        seconds = Integer.parseInt(m.group(6));
    }
    // Set optional fractional part
    int millis = 0;
    if (m.group(7) != null) {
        millis = fraction.toMillis(m.group(8));
    }
    return ZonedDateTime.of(LocalDateTime.of(year, month, dayOfMonth, hour, minutes, seconds).plus(millis, ChronoUnit.MILLIS), zoneId);
}
Example 73
Project: magarena-master  File: DeckGame.java View source code
String getGamePeriod() {
    LocalDateTime timeStart = getLocalTimeFromEpoch(gameInfo.timeStart);
    LocalDateTime timeEnd = LocalDateTime.now();
    long years = ChronoUnit.YEARS.between(timeStart, timeEnd);
    if (years > 0) {
        return years > 1 ? MText.get(_S7, years) : MText.get(_S8);
    }
    long months = ChronoUnit.MONTHS.between(timeStart, timeEnd);
    if (months > 0) {
        return months > 1 ? MText.get(_S9, months) : MText.get(_S10);
    }
    long weeks = ChronoUnit.WEEKS.between(timeStart, timeEnd);
    if (weeks > 0) {
        return weeks > 1 ? MText.get(_S11, weeks) : MText.get(_S12);
    }
    long days = ChronoUnit.DAYS.between(timeStart, timeEnd);
    if (days > 0) {
        return days > 1 ? MText.get(_S13, days) : MText.get(_S14);
    }
    long hours = ChronoUnit.HOURS.between(timeStart, timeEnd);
    if (hours > 0) {
        return hours > 1 ? MText.get(_S15, hours) : MText.get(_S16);
    }
    long minutes = ChronoUnit.MINUTES.between(timeStart, timeEnd);
    if (minutes > 0) {
        return minutes > 1 ? MText.get(_S17, minutes) : MText.get(_S18);
    }
    return _S19;
}
Example 74
Project: nextprot-api-master  File: TermController.java View source code
// TODO: Not sure about the representation to provide
/*@ApiMethod(path = "/ontology/{terminology}", verb = ApiVerb.GET, description = "Gets a terminology", produces = MediaType.APPLICATION_JSON_VALUE)
	@RequestMapping(value = "/ontology/{terminology}", method = { RequestMethod.GET }, produces = MediaType.APPLICATION_JSON_VALUE)
	public OntologyDAG getTerminologyGraph(
			@ApiPathParam(name = "terminology", description = "The name of the terminology. To get a list of possible terminologies, look at terminology-names method",  allowedvalues = { "nextprot-anatomy-cv"})
			@PathVariable("terminology") String terminology) {

		return terminolgyService.findOntologyGraph(TerminologyCv.getTerminologyOf(terminology));
	}*/
@PreAuthorize("hasRole('ROLE_ADMIN')")
@ResponseBody
@RequestMapping(value = "/ontology/build-all", produces = MediaType.APPLICATION_JSON_VALUE)
@ApiMethod(path = "/ontology/build-all", verb = ApiVerb.GET, description = "Build the ontology cache", produces = MediaType.APPLICATION_JSON_VALUE)
@ApiAuthBasic(roles = { "ROLE_ADMIN" })
public Map<String, String> buildOntologyCache() {
    Map<String, String> map = new HashMap<>();
    Instant totalTime = Instant.now();
    for (TerminologyCv terminologyCv : TerminologyCv.values()) {
        Instant t = Instant.now();
        terminolgyService.findOntologyGraph(terminologyCv);
        long ms = ChronoUnit.MILLIS.between(t, Instant.now());
        map.put(terminologyCv.name(), String.valueOf(ms) + " ms");
    }
    map.put("TOTAL BUILD", String.valueOf(ChronoUnit.SECONDS.between(totalTime, Instant.now())) + " s");
    return map;
}
Example 75
Project: nifi-master  File: GetAzureEventHubTest.java View source code
@Override
protected Iterable<EventData> receiveEvents(final ProcessContext context, final String partitionId) throws ProcessException {
    if (nullReceive) {
        return null;
    }
    if (getReceiverThrow) {
        throw new ProcessException("Could not create receiver");
    }
    final LinkedList<EventData> receivedEvents = new LinkedList<>();
    for (int i = 0; i < 10; i++) {
        final EventData eventData = new EventData(String.format("test event number: %d", i).getBytes());
        Whitebox.setInternalState(eventData, "isReceivedEvent", true);
        Whitebox.setInternalState(eventData, "partitionKey", "0");
        Whitebox.setInternalState(eventData, "offset", "100");
        Whitebox.setInternalState(eventData, "sequenceNumber", 13L);
        Whitebox.setInternalState(eventData, "enqueuedTime", Instant.now().minus(100L, ChronoUnit.SECONDS));
        receivedEvents.add(eventData);
    }
    return receivedEvents;
}
Example 76
Project: nuxeo-master  File: TestPermissionForTransientUsers.java View source code
@Test
public void shouldRemoveTokenWhenArchivingACEForTransientUser() throws InterruptedException {
    Date now = new Date();
    Calendar end = new GregorianCalendar();
    end.setTimeInMillis(now.toInstant().plus(5, ChronoUnit.SECONDS).toEpochMilli());
    String transientUsername = NuxeoPrincipal.computeTransientUsername("leela@nuxeo.com");
    ACE leelaACE = ACE.builder(transientUsername, WRITE).end(end).build();
    ACP acp = doc.getACP();
    acp.addACE(ACL.LOCAL_ACL, leelaACE);
    doc.setACP(acp, true);
    TransactionHelper.commitOrRollbackTransaction();
    eventService.waitForAsyncCompletion();
    TransactionHelper.startTransaction();
    String token = tokenAuthenticationService.getToken(transientUsername, doc.getRepositoryName(), doc.getId());
    assertNotNull(token);
    Thread.sleep(10000);
    TransactionHelper.commitOrRollbackTransaction();
    eventService.fireEvent(UpdateACEStatusListener.UPDATE_ACE_STATUS_EVENT, new EventContextImpl());
    eventService.waitForAsyncCompletion();
    TransactionHelper.startTransaction();
    token = tokenAuthenticationService.getToken(transientUsername, doc.getRepositoryName(), doc.getId());
    assertNull(token);
}
Example 77
Project: objectlabkit-master  File: LocalDatePeriodCountCalculator.java View source code
@Override
public int dayDiff(final LocalDate start, final LocalDate end, final PeriodCountBasis basis) {
    int diff;
    switch(basis) {
        case CONV_30_360:
            diff = diffConv30v360(start, end);
            break;
        case CONV_360E_ISDA:
            diff = diff360EIsda(start, end);
            break;
        case CONV_360E_ISMA:
            diff = diff360EIsma(start, end);
            break;
        default:
            diff = (int) ChronoUnit.DAYS.between(start, end);
    }
    return diff;
}
Example 78
Project: onos-master  File: LatencyConstraintTest.java View source code
/**
     * Tests equality of the instances.
     */
@Test
public void testEquality() {
    LatencyConstraint c1 = new LatencyConstraint(Duration.of(1, ChronoUnit.SECONDS));
    LatencyConstraint c2 = new LatencyConstraint(Duration.of(1000, ChronoUnit.MILLIS));
    LatencyConstraint c3 = new LatencyConstraint(Duration.of(2, ChronoUnit.SECONDS));
    LatencyConstraint c4 = new LatencyConstraint(Duration.of(2000, ChronoUnit.MILLIS));
    new EqualsTester().addEqualityGroup(c1, c2).addEqualityGroup(c3, c4).testEquals();
}
Example 79
Project: owner-master  File: DurationConverterTest.java View source code
@Test
public void testSuffixEquality() {
    DurationTypesConfig cfg = ConfigFactory.create(DurationTypesConfig.class);
    allEqual(Duration.of(10, ChronoUnit.NANOS), Arrays.asList(cfg.nsSuffix(), cfg.nanoSuffix(), cfg.nanosSuffix(), cfg.nanosecondSuffix(), cfg.nanosecondsSuffix()));
    allEqual(Duration.of(10, ChronoUnit.MICROS), Arrays.asList(cfg.usSuffix(), cfg.µsSuffix(), cfg.microSuffix(), cfg.microsSuffix(), cfg.microsecondSuffix(), cfg.microsecondsSuffix()));
    allEqual(Duration.of(10, ChronoUnit.MILLIS), Arrays.asList(cfg.msSuffix(), cfg.milliSuffix(), cfg.millisSuffix(), cfg.millisecondSuffix(), cfg.millisecondsSuffix()));
    allEqual(Duration.of(10, ChronoUnit.SECONDS), Arrays.asList(cfg.sSuffix(), cfg.secondSuffix(), cfg.secondsSuffix()));
    allEqual(Duration.of(10, ChronoUnit.MINUTES), Arrays.asList(cfg.mSuffix(), cfg.minuteSuffix(), cfg.minutesSuffix()));
    allEqual(Duration.of(10, ChronoUnit.HOURS), Arrays.asList(cfg.hSuffix(), cfg.hourSuffix(), cfg.hoursSuffix()));
    allEqual(Duration.of(10, ChronoUnit.DAYS), Arrays.asList(cfg.dSuffix(), cfg.daySuffix(), cfg.daysSuffix()));
}
Example 80
Project: ratpack-master  File: ResponseTimer.java View source code
/**
   * Adds the number of milliseconds of elapsed time between {@link Request#getTimestamp()} and when the response is ready to be sent.
   * <p>
   * The timer is stopped, and the header added, by {@link Response#beforeSend(ratpack.func.Action)}.
   * This means that the time value is the elapsed time, commonly referred to as wall clock time, and not CPU time.
   * Similarly, it does not include the time to actually start sending data out over the socket.
   * It effectively times the application processing.
   * <p>
   * The value is in milliseconds, accurate to 5 decimal places.
   *
   * @param ctx the handling context.
   */
@Override
public void handle(Context ctx) {
    Response response = ctx.getResponse();
    response.beforeSend( m -> {
        Clock clock = ctx.get(Clock.class);
        Instant start = ctx.getRequest().getTimestamp();
        long nanos = start.until(Instant.now(clock), ChronoUnit.NANOS);
        BigDecimal diffNanos = new BigDecimal(nanos);
        BigDecimal diffMillis = diffNanos.divide(NANOS_IN_MILLIS, 5, RoundingMode.UP);
        m.getHeaders().set(HEADER_NAME, diffMillis.toString());
    });
    ctx.next();
}
Example 81
Project: sandbox-master  File: LoggingContext.java View source code
@Override
public FileVisitResult preVisitDirectory(Path path, BasicFileAttributes attrs) {
    if (path.equals(rootPath)) {
        return FileVisitResult.CONTINUE;
    }
    // compare only the first subfolder
    String relPath = rootPath.relativize(path).getName(0).toString();
    try {
        Date folderDate = TIMESTAMP_FORMAT.parse(relPath);
        long ageInSecs = folderDate.toInstant().until(Instant.now(), ChronoUnit.SECONDS);
        return ageInSecs > maxAgeInSecs ? FileVisitResult.CONTINUE : FileVisitResult.SKIP_SUBTREE;
    } catch (ParseException e) {
        return FileVisitResult.SKIP_SUBTREE;
    }
}
Example 82
Project: Terasology-master  File: LoggingContext.java View source code
@Override
public FileVisitResult preVisitDirectory(Path path, BasicFileAttributes attrs) {
    if (path.equals(rootPath)) {
        return FileVisitResult.CONTINUE;
    }
    // compare only the first subfolder
    String relPath = rootPath.relativize(path).getName(0).toString();
    try {
        Date folderDate = TIMESTAMP_FORMAT.parse(relPath);
        long ageInSecs = folderDate.toInstant().until(Instant.now(), ChronoUnit.SECONDS);
        return ageInSecs > maxAgeInSecs ? FileVisitResult.CONTINUE : FileVisitResult.SKIP_SUBTREE;
    } catch (ParseException e) {
        return FileVisitResult.SKIP_SUBTREE;
    }
}
Example 83
Project: termd-master  File: Client.java View source code
public static Client connectCommandExecutingClient(String webSocketUrl, Optional<Consumer<String>> responseDataConsumer) throws InterruptedException, TimeoutException {
    ObjectWrapper<Boolean> connected = new ObjectWrapper<>(false);
    Client client = Client.initializeDefault();
    Consumer<byte[]> responseConsumer = ( bytes) -> {
        String responseData = new String(bytes);
        if ("% ".equals(responseData)) {
            //TODO use events
            connected.set(true);
        } else {
            responseDataConsumer.ifPresent(( rdc) -> rdc.accept(responseData));
            ;
        }
    };
    client.onBinaryMessage(responseConsumer);
    client.onClose( closeReason -> {
    });
    try {
        client.connect(webSocketUrl + "/");
    } catch (Exception e) {
        throw new AssertionError("Failed to connect to remote client.", e);
    }
    Wait.forCondition(() -> connected.get(), 5, ChronoUnit.SECONDS, "Client was not connected within given timeout.");
    return client;
}
Example 84
Project: vaadin-master  File: AbstractLocalDateTimeField.java View source code
private LocalDateTime getDate(LocalDateTime date, DateTimeResolution forResolution) {
    if (date == null) {
        return null;
    }
    switch(forResolution) {
        case YEAR:
            return date.withDayOfYear(1).toLocalDate().atStartOfDay();
        case MONTH:
            return date.withDayOfMonth(1).toLocalDate().atStartOfDay();
        case DAY:
            return date.toLocalDate().atStartOfDay();
        case HOUR:
            return date.truncatedTo(ChronoUnit.HOURS);
        case MINUTE:
            return date.truncatedTo(ChronoUnit.MINUTES);
        case SECOND:
            return date.truncatedTo(ChronoUnit.SECONDS);
        default:
            assert false : "Unexpected resolution argument " + forResolution;
            return null;
    }
}
Example 85
Project: webofneeds-master  File: AbstractSolrMatcherActor.java View source code
protected void processNeedEvent(NeedEvent needEvent) throws IOException, SolrServerException, JsonLdError {
    log.info("Start processing need event {}", needEvent);
    // check if the need has doNotMatch flag, then do not use it for querying or indexing
    Dataset dataset = deserializeNeed(needEvent);
    NeedModelWrapper needModelWrapper = new NeedModelWrapper(dataset);
    if (needModelWrapper.hasFlag(WON.NO_HINT_FOR_ME) && needModelWrapper.hasFlag(WON.NO_HINT_FOR_COUNTERPART)) {
        log.info("Discarding received need due to flags won:NoHintForMe and won:NoHintForCounterpart: {}", needEvent);
        return;
    }
    // check if need is usedForTesting only
    boolean usedForTesting = needModelWrapper.hasFlag(WON.USED_FOR_TESTING);
    SolrMatcherQueryExecutor queryExecutor = (usedForTesting ? testQueryExecuter : defaultQueryExecuter);
    // default query matches content terms (of fields title, description and tags) with different weights
    // and gives an additional multiplicative boost for geographically closer needs
    DefaultNeedQueryFactory needQueryFactory = new DefaultNeedQueryFactory(dataset);
    String queryString = needQueryFactory.createQuery();
    // add filters to the query: need status active and creation date overlap 1 month
    String[] filterQueries = new String[2];
    filterQueries[0] = new NeedStateQueryFactory(dataset).createQuery();
    filterQueries[1] = new CreationDateQueryFactory(dataset, 1, ChronoUnit.MONTHS).createQuery();
    log.info("query Solr endpoint {} for need {}", config.getSolrEndpointUri(usedForTesting), needEvent.getUri());
    SolrDocumentList docs = executeQuery(queryExecutor, queryString, null, filterQueries);
    if (docs != null) {
        BulkHintEvent events = produceHints(docs, needEvent, needModelWrapper);
        publishHints(events, needEvent);
    } else {
        log.warning("No results found for query of need ", needEvent);
    }
    indexNeedEvent(needEvent, dataset);
}
Example 86
Project: zava-master  File: DateTimeExamples.java View source code
private static void useLocalDate() {
    LocalDate date = LocalDate.of(2014, 3, 18);
    // 2014
    int year = date.getYear();
    // MARCH
    Month month = date.getMonth();
    // 18
    int day = date.getDayOfMonth();
    // TUESDAY
    DayOfWeek dow = date.getDayOfWeek();
    // 31 (days in March)
    int len = date.lengthOfMonth();
    // false (not a leap year)
    boolean leap = date.isLeapYear();
    System.out.println(date);
    int y = date.get(ChronoField.YEAR);
    int m = date.get(ChronoField.MONTH_OF_YEAR);
    int d = date.get(ChronoField.DAY_OF_MONTH);
    // 13:45:20
    LocalTime time = LocalTime.of(13, 45, 20);
    // 13
    int hour = time.getHour();
    // 45
    int minute = time.getMinute();
    // 20
    int second = time.getSecond();
    System.out.println(time);
    // 2014-03-18T13:45
    LocalDateTime dt1 = LocalDateTime.of(2014, Month.MARCH, 18, 13, 45, 20);
    LocalDateTime dt2 = LocalDateTime.of(date, time);
    LocalDateTime dt3 = date.atTime(13, 45, 20);
    LocalDateTime dt4 = date.atTime(time);
    LocalDateTime dt5 = time.atDate(date);
    System.out.println(dt1);
    LocalDate date1 = dt1.toLocalDate();
    System.out.println(date1);
    LocalTime time1 = dt1.toLocalTime();
    System.out.println(time1);
    Instant instant = Instant.ofEpochSecond(44 * 365 * 86400);
    Instant now = Instant.now();
    Duration d1 = Duration.between(LocalTime.of(13, 45, 10), time);
    Duration d2 = Duration.between(instant, now);
    System.out.println(d1.getSeconds());
    System.out.println(d2.getSeconds());
    Duration threeMinutes = Duration.of(3, ChronoUnit.MINUTES);
    System.out.println(threeMinutes);
    JapaneseDate japaneseDate = JapaneseDate.from(date);
    System.out.println(japaneseDate);
}
Example 87
Project: JFoenix-master  File: JFXDatePickerContent.java View source code
protected void forward(int offset, ChronoUnit unit, boolean focusDayCell, boolean withAnimation) {
    if (withAnimation) {
        if (tempImageTransition == null || tempImageTransition.getStatus() == Status.STOPPED) {
            Pane monthContent = (Pane) calendarPlaceHolder.getChildren().get(0);
            this.getParent().setManaged(false);
            SnapshotParameters snapShotparams = new SnapshotParameters();
            snapShotparams.setFill(Color.TRANSPARENT);
            WritableImage temp = monthContent.snapshot(snapShotparams, new WritableImage((int) monthContent.getWidth(), (int) monthContent.getHeight()));
            ImageView tempImage = new ImageView(temp);
            calendarPlaceHolder.getChildren().add(calendarPlaceHolder.getChildren().size() - 2, tempImage);
            TranslateTransition imageTransition = new TranslateTransition(Duration.millis(160), tempImage);
            imageTransition.setToX(-offset * calendarPlaceHolder.getWidth());
            imageTransition.setOnFinished(( finish) -> calendarPlaceHolder.getChildren().remove(tempImage));
            monthContent.setTranslateX(offset * calendarPlaceHolder.getWidth());
            TranslateTransition contentTransition = new TranslateTransition(Duration.millis(160), monthContent);
            contentTransition.setToX(0);
            tempImageTransition = new ParallelTransition(imageTransition, contentTransition);
            tempImageTransition.setOnFinished(( finish) -> {
                calendarPlaceHolder.getChildren().remove(tempImage);
                this.getParent().setManaged(true);
            });
            tempImageTransition.play();
        }
    }
    YearMonth yearMonth = selectedYearMonth.get();
    DateCell dateCell = currentFocusedDayCell;
    if (dateCell == null || !(dayCellDate(dateCell).getMonth() == yearMonth.getMonth())) {
        dateCell = findDayCellOfDate(yearMonth.atDay(1));
    }
    goToDayCell(dateCell, offset, unit, focusDayCell);
}
Example 88
Project: jidefx-oss-master  File: AbstractDatePopupContent.java View source code
protected void forward(int offset, ChronoUnit unit) {
    YearMonth yearMonth = displayedYearMonth.get();
    DateCell dateCell = lastFocusedDayCell;
    if (dateCell == null || !dayCellDate(dateCell).getMonth().equals(yearMonth.getMonth())) {
        dateCell = findDayCellForDate(yearMonth.atDay(1));
    }
    goToDayCell(dateCell, offset, unit);
}
Example 89
Project: rakam-master  File: PrestoRetentionQueryExecutor.java View source code
@Override
public QueryExecution query(String project, Optional<RetentionAction> firstAction, Optional<RetentionAction> returningAction, DateUnit dateUnit, Optional<String> dimension, Optional<Integer> period, LocalDate startDate, LocalDate endDate, ZoneId zoneId, boolean approximateVal) {
    boolean approximate = true;
    period.ifPresent( e -> checkArgument(e >= 0, "Period must be 0 or a positive value"));
    String timeColumn = getTimeExpression(dateUnit);
    LocalDate start;
    LocalDate end;
    if (dateUnit == MONTH) {
        start = startDate.withDayOfMonth(1);
        end = endDate.withDayOfMonth(1).plus(1, ChronoUnit.MONTHS);
    } else if (dateUnit == WEEK) {
        TemporalField fieldUS = WeekFields.of(Locale.US).dayOfWeek();
        start = startDate.with(fieldUS, 1);
        end = endDate.with(fieldUS, 1).plus(1, ChronoUnit.MONTHS);
    } else if (dateUnit == DAY) {
        start = startDate;
        end = endDate;
    } else {
        throw new IllegalStateException();
    }
    Optional<Integer> range = period.map( v -> Math.min(v, Ints.checkedCast(DAYS.between(start, end))));
    if (range.isPresent() && range.get() < 0) {
        throw new IllegalArgumentException("startDate must be before endDate.");
    }
    if (range.isPresent() && range.get() == 0) {
        return QueryExecution.completedQueryExecution(null, QueryResult.empty());
    }
    Set<CalculatedUserSet> missingPreComputedTables = new HashSet<>();
    String firstActionQuery = generateQuery(project, firstAction, CONNECTOR_FIELD, timeColumn, dimension, startDate, endDate, missingPreComputedTables, zoneId, approximate);
    String returningActionQuery = generateQuery(project, returningAction, CONNECTOR_FIELD, timeColumn, dimension, startDate, endDate, missingPreComputedTables, zoneId, approximate);
    if (firstActionQuery == null || returningActionQuery == null) {
        return QueryExecution.completedQueryExecution("", QueryResult.empty());
    }
    String timeSubtraction = diffTimestamps(dateUnit, "data.date", "returning_action.date");
    String dimensionColumn = dimension.isPresent() ? "data.dimension" : "data.date";
    String mergeSetAggregation = dimension.map( v -> approximate ? "merge" : "merge_sets").orElse("");
    String query = format("with first_action as (\n" + "  %s\n" + "), \n" + "returning_action as (\n" + "  %s\n" + ") \n" + "select %s, cast(null as bigint) as lead, cardinality(%s(%s_set)) count from first_action data %s union all\n" + "SELECT * FROM (select %s, %s - 1, greatest(0, cardinality_intersection(%s(data.%s_set), %s(returning_action.%s_set))) count \n" + "from first_action data join returning_action on (data.date < returning_action.date %s) \n" + "%s) ORDER BY 1, 2 NULLS FIRST", firstActionQuery, returningActionQuery, dimensionColumn, mergeSetAggregation, CONNECTOR_FIELD, dimension.map( v -> "GROUP BY 1").orElse(""), dimensionColumn, timeSubtraction, mergeSetAggregation, CONNECTOR_FIELD, mergeSetAggregation, CONNECTOR_FIELD, range.map( v -> String.format("AND data.date + interval '%d' day >= returning_action.date", v)).orElse(""), dimension.map( v -> "GROUP BY 1, 2").orElse(""));
    return new DelegateQueryExecution(executor.executeQuery(project, query),  result -> {
        result.setProperty("calculatedUserSets", missingPreComputedTables);
        if (!result.isFailed()) {
            List<List<Object>> results = result.getResult().stream().filter( rows -> rows.get(2) != null && !rows.get(2).equals(0L)).collect(Collectors.toList());
            return new QueryResult(result.getMetadata(), results, result.getProperties());
        }
        return result;
    });
}
Example 90
Project: chvote-1-0-master  File: KeyGenerator.java View source code
private X509v3CertificateBuilder createCertificateBuilder(KeyPair keyPair) throws PropertyConfigurationException, CertIOException {
    X500NameBuilder nameBuilder = new X500NameBuilder(BCStyle.INSTANCE);
    nameBuilder.addRDN(BCStyle.CN, propertyConfigurationService.getConfigValue(CERT_COMMON_NAME_PROPERTY));
    nameBuilder.addRDN(BCStyle.O, propertyConfigurationService.getConfigValue(CERT_ORGANISATION_PROPERTY));
    nameBuilder.addRDN(BCStyle.OU, propertyConfigurationService.getConfigValue(CERT_ORGANISATIONAL_UNIT_PROPERTY));
    nameBuilder.addRDN(BCStyle.C, propertyConfigurationService.getConfigValue(CERT_COUNTRY_PROPERTY));
    X500Name x500Name = nameBuilder.build();
    BigInteger serial = new BigInteger(CERT_SERIAL_NUMBER_BIT_SIZE, SecureRandomFactory.createPRNG());
    SubjectPublicKeyInfo publicKeyInfo = SubjectPublicKeyInfo.getInstance(keyPair.getPublic().getEncoded());
    Date startDate = new Date();
    Date endDate = Date.from(startDate.toInstant().plus(propertyConfigurationService.getConfigValueAsInt(CERT_VALIDITY_DAYS_PROPERTY), ChronoUnit.DAYS));
    X509v3CertificateBuilder certificateBuilder = new X509v3CertificateBuilder(x500Name, serial, startDate, endDate, x500Name, publicKeyInfo);
    String certFriendlyName = propertyConfigurationService.getConfigValue(CERT_PRIVATE_FRIENDLY_NAME_PROPERTY);
    certificateBuilder.addExtension(PKCSObjectIdentifiers.pkcs_9_at_friendlyName, false, new DERBMPString(certFriendlyName));
    return certificateBuilder;
}
Example 91
Project: ddf-master  File: CachedResourceMetacardComparatorTest.java View source code
@Before
public void setup() throws Exception {
    Instant createdDate = Instant.now();
    Instant effectiveDate = createdDate.plus(1, ChronoUnit.HOURS);
    Instant modificationDate = createdDate.plus(2, ChronoUnit.DAYS);
    Instant expirationDate = createdDate.plus(60, ChronoUnit.DAYS);
    String metacardId = UUID.randomUUID().toString();
    cachedMetacard = createMetacard(metacardId, createdDate, effectiveDate, expirationDate, modificationDate);
    updatedMetacard = createMetacard(metacardId, createdDate, effectiveDate, expirationDate, modificationDate);
}
Example 92
Project: esper-master  File: CalendarOpPlusMinus.java View source code
protected static LocalDateTime action(LocalDateTime ldt, int factor, Long duration) {
    if (duration == null) {
        return ldt;
    }
    if (duration < Integer.MAX_VALUE) {
        return ldt.plus(factor * duration, ChronoUnit.MILLIS);
    }
    int days = (int) (duration / (1000L * 60 * 60 * 24));
    int msec = (int) (duration - days * (1000L * 60 * 60 * 24));
    ldt = ldt.plus(factor * msec, ChronoUnit.MILLIS);
    return ldt.plus(factor * days, ChronoUnit.DAYS);
}
Example 93
Project: haikudepotserver-master  File: PasswordResetServiceImpl.java View source code
@Override
public void complete(String tokenCode, String passwordClear) {
    Preconditions.checkArgument(!Strings.isNullOrEmpty(tokenCode), "the token code must be provided");
    Preconditions.checkArgument(!Strings.isNullOrEmpty(passwordClear), "the pssword clear must be provided");
    Instant now = Instant.now();
    try {
        if (!Strings.isNullOrEmpty(tokenCode)) {
            ObjectContext context = serverRuntime.getContext();
            Optional<UserPasswordResetToken> tokenOptional = UserPasswordResetToken.getByCode(context, tokenCode);
            if (tokenOptional.isPresent()) {
                try {
                    UserPasswordResetToken token = tokenOptional.get();
                    if (token.getCreateTimestamp().getTime() > now.minus(timeToLiveHours, ChronoUnit.HOURS).toEpochMilli()) {
                        User user = token.getUser();
                        if (user.getActive()) {
                            if (!Strings.isNullOrEmpty(passwordClear) && authenticationService.validatePassword(passwordClear)) {
                                user.setPasswordSalt();
                                user.setPasswordHash(authenticationService.hashPassword(user, passwordClear));
                                context.deleteObjects(token);
                                context.commitChanges();
                                LOGGER.info("did reset the password for; {}", user.toString());
                            } else {
                                LOGGER.warn("the password has been supplied as invalid; will ignore");
                            }
                        } else {
                            LOGGER.warn("the user having their password reset is inactive; will ignore");
                        }
                    } else {
                        LOGGER.warn("the token used to reset the password is expired; will ignore");
                    }
                } finally {
                    // open a new context so that just in case something goes wrong / invalid in the other context,
                    // that the deletion of the token can still proceed.
                    ObjectContext deleteContext = serverRuntime.getContext();
                    Optional<UserPasswordResetToken> deleteTokenOptional = UserPasswordResetToken.getByCode(deleteContext, tokenCode);
                    if (deleteTokenOptional.isPresent()) {
                        deleteContext.deleteObjects(deleteTokenOptional.get());
                        deleteContext.commitChanges();
                        LOGGER.info("did delete user password reset token {} after having processed it", tokenCode);
                    }
                }
            } else {
                LOGGER.warn("unable to find the user password reset token {}; will ignore", tokenCode);
            }
        } else {
            LOGGER.warn("the code has been supplied as null when attempting to reset a password; will ignore");
        }
    } catch (Throwable th) {
        LOGGER.error("unable to reset the password from a token", th);
    }
}
Example 94
Project: ipp-master  File: TestSnapshot.java View source code
@Test
public void testSerializeToJson_ComplexerObject() throws Exception {
    Snapshot snapshot = Snapshot.builder(Instant.EPOCH, null).withStartTime(Instant.EPOCH).withEndTime(Instant.EPOCH).withTeamStates(new TeamStates().setStateForTeam(0, new TeamState().addTagSeenEvent(new Snapshot(Instant.EPOCH), new TagSeenEvent(Instant.EPOCH, new TagId("ABCD"), 0, 0L)).addTagSeenEvent(// TODO: It's not really clean that we're passing null here,
    null, //       but it should work fine nonetheless
    new TagSeenEvent(Instant.EPOCH.plus(1000, ChronoUnit.SECONDS), new TagId("ABCD"), 0, 1L)))).withTeamTagMap(new TeamTagMap().addTagToTeam("ABCD", 0)).withStatusMessage("foo").build();
    MatcherAssert.assertThat(objectMapper.writeValueAsString(snapshot), SameJSONAs.sameJSONAs("{\"snapshotTime\":0,statusMessage:foo,\"startTime\":0,\"endTime\":0,\"teamTagMap\":{\"0\":[\"ABCD\"]}," + "\"teamStates\":{\"0\":{\"lastTagSeenEvent\":{\"type\":\"TagSeen\",\"time\":1000," + "\"tag\":\"ABCD\",\"readerId\":0}, \"tagFragmentCount\":3}}}").allowingExtraUnexpectedFields());
}
Example 95
Project: jsr354-ri-master  File: MonetaryRoundingsTest.java View source code
/**
     * Test method for
     * {@link javax.money.Monetary#getRounding(javax.money.RoundingQuery)} with timestamps.
     * .
     */
@Test
public void testGetRoundingCurrencyUnitLong() {
    MonetaryOperator r = Monetary.getRounding(RoundingQueryBuilder.of().setCurrency(Monetary.getCurrency("XXX")).set(LocalDate.now().plus(1, ChronoUnit.DAYS)).build());
    assertNotNull(r);
    assertEquals(Monetary.getDefaultAmountFactory().setCurrency("XXX").setNumber(-1).create(), Monetary.getDefaultAmountFactory().setCurrency("XXX").setNumber(2.0234343).create().with(r));
}
Example 96
Project: kinesis-vcr-master  File: KinesisRecorderTest.java View source code
@Test
public void testRecordAndReplay() throws Exception {
    VcrConfiguration configuration = new VcrConfiguration(kinesisStreamName, kinesisStreamName, bucketName, 1024 * 10, TimeUnit.SECONDS.toMillis(60));
    KinesisRecorder recorder = new KinesisRecorder(configuration, s3, awsCredentialsProvider);
    executorService.submit(recorder);
    kinesis.putRecord(kinesisStreamName, ByteBuffer.wrap(new byte[40_000]), UUID.randomUUID().toString());
    kinesis.putRecord(kinesisStreamName, ByteBuffer.wrap(new byte[40_000]), UUID.randomUUID().toString());
    kinesis.putRecord(kinesisStreamName, ByteBuffer.wrap(new byte[40_000]), UUID.randomUUID().toString());
    kinesis.putRecord(kinesisStreamName, ByteBuffer.wrap(new byte[40_000]), UUID.randomUUID().toString());
    kinesis.putRecord(kinesisStreamName, ByteBuffer.wrap(new byte[40_000]), UUID.randomUUID().toString());
    kinesis.putRecord(kinesisStreamName, ByteBuffer.wrap(new byte[40_000]), UUID.randomUUID().toString());
    kinesis.putRecord(kinesisStreamName, ByteBuffer.wrap(new byte[40_000]), UUID.randomUUID().toString());
    kinesis.putRecord(kinesisStreamName, ByteBuffer.wrap(new byte[40_000]), UUID.randomUUID().toString());
    kinesis.putRecord(kinesisStreamName, ByteBuffer.wrap(new byte[40_000]), UUID.randomUUID().toString());
    kinesis.putRecord(kinesisStreamName, ByteBuffer.wrap(new byte[40_000]), UUID.randomUUID().toString());
    Thread.sleep(TimeUnit.SECONDS.toMillis(45));
    KinesisPlayer player = new KinesisPlayer(configuration, s3, kinesis);
    Observable<byte[]> bytesObservable = player.playableObjects(LocalDateTime.now().truncatedTo(ChronoUnit.DAYS), LocalDateTime.now().plusDays(1)).flatMap(player::objectToPayloads);
    TestSubscriber<byte[]> testSubscriber = new TestSubscriber<>();
    bytesObservable.subscribe(testSubscriber);
    testSubscriber.awaitTerminalEvent();
    testSubscriber.assertNoErrors();
    List<byte[]> result = testSubscriber.getOnNextEvents();
    assertThat(result).isNotEmpty();
    assertThat(result).are(new Condition<byte[]>() {

        @Override
        public boolean matches(byte[] value) {
            return Arrays.equals(value, new byte[40_000]);
        }
    });
    recorder.stop();
}
Example 97
Project: ProjectAres-master  File: TimeUtils.java View source code
public static long toUnit(TemporalUnit unit, Duration duration) {
    switch((ChronoUnit) unit) {
        case NANOS:
            return duration.toNanos();
        case MICROS:
            return toMicros(duration);
        case MILLIS:
            return duration.toMillis();
        case SECONDS:
            return duration.getSeconds();
    }
    if (unit.getDuration().getNano() == 0) {
        return duration.getSeconds() / unit.getDuration().getSeconds();
    }
    throw new IllegalArgumentException("Unsupported sub-second unit " + unit);
}
Example 98
Project: spring-framework-master  File: DefaultServerWebExchange.java View source code
private boolean validateIfUnmodifiedSince(Instant lastModified) {
    if (lastModified.isBefore(Instant.EPOCH)) {
        return false;
    }
    long ifUnmodifiedSince = getRequestHeaders().getIfUnmodifiedSince();
    if (ifUnmodifiedSince == -1) {
        return false;
    }
    // We will perform this validation...
    Instant sinceInstant = Instant.ofEpochMilli(ifUnmodifiedSince);
    this.notModified = sinceInstant.isBefore(lastModified.truncatedTo(ChronoUnit.SECONDS));
    return true;
}
Example 99
Project: Strata-master  File: SabrSwaptionCalibratorCubeNormalTest.java View source code
@Test
public void normal_cube() {
    double beta = 0.50;
    Surface betaSurface = ConstantSurface.of("Beta", beta).withMetadata(DefaultSurfaceMetadata.builder().xValueType(ValueType.YEAR_FRACTION).yValueType(ValueType.YEAR_FRACTION).zValueType(ValueType.SABR_BETA).surfaceName("Beta").build());
    double shift = 0.0300;
    Surface shiftSurface = ConstantSurface.of("Shift", shift).withMetadata(DefaultSurfaceMetadata.builder().xValueType(ValueType.YEAR_FRACTION).yValueType(ValueType.YEAR_FRACTION).surfaceName("Shift").build());
    SabrParametersSwaptionVolatilities calibrated = SABR_CALIBRATION.calibrateWithFixedBetaAndShift(DEFINITION, CALIBRATION_TIME, DATA_SPARSE, MULTICURVE, betaSurface, shiftSurface);
    for (int looptenor = 0; looptenor < TENORS.size(); looptenor++) {
        double tenor = TENORS.get(looptenor).get(ChronoUnit.YEARS);
        for (int loopexpiry = 0; loopexpiry < EXPIRIES.size(); loopexpiry++) {
            LocalDate expiry = EUR_FIXED_1Y_EURIBOR_6M.getFloatingLeg().getStartDateBusinessDayAdjustment().adjust(CALIBRATION_DATE.plus(EXPIRIES.get(loopexpiry)), REF_DATA);
            LocalDate effectiveDate = EUR_FIXED_1Y_EURIBOR_6M.calculateSpotDateFromTradeDate(expiry, REF_DATA);
            LocalDate endDate = effectiveDate.plus(TENORS.get(looptenor));
            SwapTrade swap = EUR_FIXED_1Y_EURIBOR_6M.toTrade(CALIBRATION_DATE, effectiveDate, endDate, BuySell.BUY, 1.0, 0.0);
            double parRate = SWAP_PRICER.parRate(swap.resolve(REF_DATA).getProduct(), MULTICURVE);
            ZonedDateTime expiryDateTime = expiry.atTime(11, 0).atZone(ZoneId.of("Europe/Berlin"));
            double time = calibrated.relativeTime(expiryDateTime);
            for (int loopmoney = 0; loopmoney < MONEYNESS.size(); loopmoney++) {
                if (!Double.isNaN(DATA_ARRAY_SPARSE[looptenor][loopexpiry][loopmoney])) {
                    double strike = parRate + MONEYNESS.get(loopmoney);
                    double volBlack = calibrated.volatility(expiryDateTime, tenor, strike, parRate);
                    double priceComputed = BlackFormulaRepository.price(parRate + shift, parRate + MONEYNESS.get(loopmoney) + shift, time, volBlack, true);
                    double priceNormal = NormalFormulaRepository.price(parRate, parRate + MONEYNESS.get(loopmoney), time, DATA_ARRAY_SPARSE[looptenor][loopexpiry][loopmoney], PutCall.CALL);
                    assertEquals(priceComputed, priceNormal, TOLERANCE_PRICE_CALIBRATION_LS);
                }
            }
        }
    }
}
Example 100
Project: Time4J-master  File: JSR310DurationAdapter.java View source code
//~ Methoden ----------------------------------------------------------
@Override
public long get(TemporalUnit unit) {
    for (Map.Entry<IsoUnit, TemporalUnit> entry : MAP.entrySet()) {
        if (entry.getValue().equals(unit)) {
            long amount = this.duration.getPartialAmount(entry.getKey());
            if (this.duration.isNegative()) {
                amount = Math.negateExact(amount);
            }
            return amount;
        }
    }
    if (unit.equals(ChronoUnit.HALF_DAYS)) {
        long hd = Math.floorDiv(this.duration.getPartialAmount(ClockUnit.HOURS), 12);
        if (this.duration.isNegative()) {
            hd = Math.negateExact(hd);
        }
        return hd;
    }
    // throws NPE if unit is null
    throw new UnsupportedTemporalTypeException(unit.toString());
}
Example 101
Project: Weasis-master  File: TagDTest.java View source code
@Test
public void testGetDicomPeriod() throws Exception {
    String period = TagD.getDicomPeriod(null);
    //$NON-NLS-1$
    assertEquals("", period);
    //$NON-NLS-1$
    period = TagD.getDicomPeriod("0");
    //$NON-NLS-1$
    assertEquals("", period);
    //$NON-NLS-1$
    period = TagD.getDicomPeriod("0Z");
    //$NON-NLS-1$
    assertEquals("", period);
    //$NON-NLS-1$
    period = TagD.getDicomPeriod("031Y");
    //$NON-NLS-1$
    assertEquals("31 " + ChronoUnit.YEARS.toString(), period);
    //$NON-NLS-1$
    period = TagD.getDicomPeriod("001Y");
    //$NON-NLS-1$
    assertEquals("1 " + ChronoUnit.YEARS.toString(), period);
    //$NON-NLS-1$
    period = TagD.getDicomPeriod("1Y");
    //$NON-NLS-1$
    assertEquals("1 " + ChronoUnit.YEARS.toString(), period);
    //$NON-NLS-1$
    period = TagD.getDicomPeriod("000Y");
    //$NON-NLS-1$
    assertEquals("0 " + ChronoUnit.YEARS.toString(), period);
    //$NON-NLS-1$
    period = TagD.getDicomPeriod("001M");
    //$NON-NLS-1$
    assertEquals("1 " + ChronoUnit.MONTHS.toString(), period);
    //$NON-NLS-1$
    period = TagD.getDicomPeriod("011W");
    //$NON-NLS-1$
    assertEquals("11 " + ChronoUnit.WEEKS.toString(), period);
    //$NON-NLS-1$
    period = TagD.getDicomPeriod("111D");
    //$NON-NLS-1$
    assertEquals("111 " + ChronoUnit.DAYS.toString(), period);
}