Java Code Examples for java.time.temporal.ChronoUnit

The following are top voted examples for showing how to use java.time.temporal.ChronoUnit. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: GiveawayBot   File: Giveaway.java   Source Code and License 8 votes vote down vote up
public Message render(Color color, Instant now)
{
    MessageBuilder mb = new MessageBuilder();
    boolean close = now.plusSeconds(6).isAfter(end);
    mb.append(Constants.YAY).append(close ? " **G I V E A W A Y** " : "   **GIVEAWAY**   ").append(Constants.YAY);
    EmbedBuilder eb = new EmbedBuilder();
    if(close)
        eb.setColor(Color.RED);
    else if(color==null)
        eb.setColor(Constants.BLURPLE);
    else
        eb.setColor(color);
    eb.setFooter((winners==1 ? "" : winners+" Winners | ")+"Ends at",null);
    eb.setTimestamp(end);
    eb.setDescription("React with "+Constants.TADA+" to enter!\nTime remaining: "+FormatUtil.secondsToTime(now.until(end, ChronoUnit.SECONDS)));
    if(prize!=null)
        eb.setAuthor(prize, null, null);
    if(close)
        eb.setTitle("Last chance to enter!!!", null);
    mb.setEmbed(eb.build());
    return mb.build();
}
 
Example 2
Project: jdk8u-jdk   File: TCKMinguoChronology.java   Source Code and License 7 votes vote down vote up
@SuppressWarnings("unused")
@Test(dataProvider="samples")
public void test_MinguoDate(MinguoDate minguoDate, LocalDate iso) {
    MinguoDate hd = minguoDate;
    ChronoLocalDateTime<MinguoDate> hdt = hd.atTime(LocalTime.NOON);
    ZoneOffset zo = ZoneOffset.ofHours(1);
    ChronoZonedDateTime<MinguoDate> hzdt = hdt.atZone(zo);
    hdt = hdt.plus(1, ChronoUnit.YEARS);
    hdt = hdt.plus(1, ChronoUnit.MONTHS);
    hdt = hdt.plus(1, ChronoUnit.DAYS);
    hdt = hdt.plus(1, ChronoUnit.HOURS);
    hdt = hdt.plus(1, ChronoUnit.MINUTES);
    hdt = hdt.plus(1, ChronoUnit.SECONDS);
    hdt = hdt.plus(1, ChronoUnit.NANOS);
    ChronoLocalDateTime<MinguoDate> a2 = hzdt.toLocalDateTime();
    MinguoDate a3 = a2.toLocalDate();
    MinguoDate a5 = hzdt.toLocalDate();
    //System.out.printf(" d: %s, dt: %s; odt: %s; zodt: %s; a4: %s%n", date, hdt, hodt, hzdt, a5);
}
 
Example 3
Project: IPPR2016   File: TimeoutScheduleActor.java   Source Code and License 7 votes vote down vote up
private void handleTimeoutScheduleStartMessage(final Object obj) {
  final TimeoutScheduleStartMessage msg = (TimeoutScheduleStartMessage) obj;
  final SubjectState subjectState = subjectStateRepository.findOne(msg.getSsId());
  final long timeout =
      subjectState.getCurrentState().getTimeoutTransition().get().getTimeout().longValue();

  final LocalDateTime now = LocalDateTime.now();
  final LocalDateTime lastChanged = subjectState.getLastChanged();
  final long alreadyPassed = ChronoUnit.MINUTES.between(lastChanged, now);

  long actualTimeout = timeout - alreadyPassed;
  if (actualTimeout < 0) {
    actualTimeout = 0;
  }

  LOG.info("Start [{}] min. timeout for [{}]", actualTimeout, subjectState);
  scheduler = actorSystem.scheduler()
      .scheduleOnce(Duration.create(actualTimeout, TimeUnit.MINUTES), () -> {
        getContext().parent().tell(new TimeoutExecuteMessage(subjectState.getSsId()), getSelf());
        getContext().stop(getSelf());
      }, actorSystem.dispatcher());
}
 
Example 4
Project: quilt   File: QuoteBySourceAmountResponseOerCodec.java   Source Code and License 6 votes vote down vote up
@Override
public QuoteBySourceAmountResponse read(CodecContext context, InputStream inputStream)
    throws IOException {

  Objects.requireNonNull(context);
  Objects.requireNonNull(inputStream);

  /* read the destination amount, which is a uint64 */
  final BigInteger destinationAmount = context.read(OerUint64.class, inputStream).getValue();

  /* read the source hold duration which is a unit32 */
  long sourceHoldDuration = context.read(OerUint32.class, inputStream).getValue();

  return QuoteBySourceAmountResponse.Builder.builder()
      .destinationAmount(destinationAmount)
      .sourceHoldDuration(Duration.of(sourceHoldDuration, ChronoUnit.MILLIS)).build();
}
 
Example 5
Project: xm-uaa   File: UserServiceIntTest.java   Source Code and License 6 votes vote down vote up
@Test
public void assertThatResetKeyMustNotBeOlderThan24Hours() {
    UserLogin userLogin = new UserLogin();
    userLogin.setTypeKey(UserLoginType.EMAIL.getValue());
    userLogin.setLogin("[email protected]");

    User user = new User();
    user.setUserKey("test");
    user.setPassword(RandomStringUtils.random(60));
    user.getLogins().add(userLogin);
    userLogin.setUser(user);

    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 6
Project: Spring-5.0-Cookbook   File: TestEmployeeNativeStreamService.java   Source Code and License 6 votes vote down vote up
@Test
public void test(){
	Flux.just("Ben", "Michael", "Mark")
       .doOnNext(v -> {
           if (new Random().nextInt(10) + 1 == 5) {
               throw new RuntimeException("Boo!");
           }
       })
       .doOnSubscribe(subscription ->
       {
           System.out.println(subscription);
       })
       .retryWhen(throwableFlux -> Flux.range(1, 5)
               .flatMap(i -> {
                   System.out.println(i);
                   return Flux.just(i)
                           .delay(Duration.of(i, ChronoUnit.SECONDS));
               }))
       .subscribe(System.out::println);
}
 
Example 7
Project: jdk8u-jdk   File: ChronoLocalDateImpl.java   Source Code and License 6 votes vote down vote up
@Override
@SuppressWarnings("unchecked")
public D plus(long amountToAdd, TemporalUnit unit) {
    if (unit instanceof ChronoUnit) {
        ChronoUnit f = (ChronoUnit) unit;
        switch (f) {
            case DAYS: return plusDays(amountToAdd);
            case WEEKS: return plusDays(Math.multiplyExact(amountToAdd, 7));
            case MONTHS: return plusMonths(amountToAdd);
            case YEARS: return plusYears(amountToAdd);
            case DECADES: return plusYears(Math.multiplyExact(amountToAdd, 10));
            case CENTURIES: return plusYears(Math.multiplyExact(amountToAdd, 100));
            case MILLENNIA: return plusYears(Math.multiplyExact(amountToAdd, 1000));
            case ERAS: return with(ERA, Math.addExact(getLong(ERA), amountToAdd));
        }
        throw new UnsupportedTemporalTypeException("Unsupported unit: " + unit);
    }
    return (D) ChronoLocalDate.super.plus(amountToAdd, unit);
}
 
Example 8
Project: RFTBackend   File: TransportServiceImpl.java   Source Code and License 6 votes vote down vote up
@Override
public Page<TransportListViewDTO> listTransports(Pageable pageable) {
    return transportRepository.findAll(pageable).map(transport -> {
        TransportListViewDTO listViewDTO = new TransportListViewDTO();

        //Map transport to dto
        listViewDTO.setId(transport.getId());
        listViewDTO.setCargoName(transport.getCargo().getName());
        listViewDTO.setCityFrom(transport.getPlaceOfLoad().getCity());
        listViewDTO.setCityTo(transport.getPlaceOfUnload().getCity());
        listViewDTO.setDescription(transport.getCargo().getDescription());
        listViewDTO.setOwner(transport.getOwner().getUserName());
        if (transport.getBids().size() > 0) {
            listViewDTO.setCurrentPrice(transport.getBids().stream().mapToInt(b -> b.getAmount()).min().getAsInt());
            listViewDTO.setLowestBidder(transport.getBids().stream().min(Comparator.comparing(Bid::getAmount)).get().getBidder().getUserName());
        } else {
            listViewDTO.setCurrentPrice(transport.getStartingPrice());
            listViewDTO.setLowestBidder("");
        }
        listViewDTO.setDaysRemaining(ChronoUnit.DAYS.between(LocalDate.now(), transport.getTimeOfLoad()));

        return listViewDTO;
    });
}
 
Example 9
Project: displaydirect   File: Kv78ProcessTask.java   Source Code and License 6 votes vote down vote up
@Override
public void run() {
    LOGGER.info("Started ZMQ pusher");

    pull.connect("tcp://127.0.0.1:"+ port);

    while (!Thread.interrupted() || stopped.get()) {
        String m = null;
        try {
            m = pull.recvStr();
            InputHandler.handleMessage(m);
        } catch (ZMQException ex) {
            LOGGER.error("ZMQ error in KV7/8 processing", ex);
        } catch (Exception e) {
            LOGGER.error("Error in KV7/8 processing", e);
            metrics.increaseBucketValue("kv78turbo.messages.errors", ChronoUnit.HOURS);
            if (m != null) {
                LOGGER.debug("Got message {}", m);
            }
        }
    }

    LOGGER.debug("Processing task is interrupted");
    disconnect();
}
 
Example 10
Project: jdk8u-jdk   File: TCKOffsetDateTime.java   Source Code and License 6 votes vote down vote up
@Test
public void test_isSupported_TemporalUnit() {
    assertEquals(TEST_2008_6_30_11_30_59_000000500.isSupported((TemporalUnit) null), false);
    assertEquals(TEST_2008_6_30_11_30_59_000000500.isSupported(ChronoUnit.NANOS), true);
    assertEquals(TEST_2008_6_30_11_30_59_000000500.isSupported(ChronoUnit.MICROS), true);
    assertEquals(TEST_2008_6_30_11_30_59_000000500.isSupported(ChronoUnit.MILLIS), true);
    assertEquals(TEST_2008_6_30_11_30_59_000000500.isSupported(ChronoUnit.SECONDS), true);
    assertEquals(TEST_2008_6_30_11_30_59_000000500.isSupported(ChronoUnit.MINUTES), true);
    assertEquals(TEST_2008_6_30_11_30_59_000000500.isSupported(ChronoUnit.HOURS), true);
    assertEquals(TEST_2008_6_30_11_30_59_000000500.isSupported(ChronoUnit.HALF_DAYS), true);
    assertEquals(TEST_2008_6_30_11_30_59_000000500.isSupported(ChronoUnit.DAYS), true);
    assertEquals(TEST_2008_6_30_11_30_59_000000500.isSupported(ChronoUnit.WEEKS), true);
    assertEquals(TEST_2008_6_30_11_30_59_000000500.isSupported(ChronoUnit.MONTHS), true);
    assertEquals(TEST_2008_6_30_11_30_59_000000500.isSupported(ChronoUnit.YEARS), true);
    assertEquals(TEST_2008_6_30_11_30_59_000000500.isSupported(ChronoUnit.DECADES), true);
    assertEquals(TEST_2008_6_30_11_30_59_000000500.isSupported(ChronoUnit.CENTURIES), true);
    assertEquals(TEST_2008_6_30_11_30_59_000000500.isSupported(ChronoUnit.MILLENNIA), true);
    assertEquals(TEST_2008_6_30_11_30_59_000000500.isSupported(ChronoUnit.ERAS), true);
    assertEquals(TEST_2008_6_30_11_30_59_000000500.isSupported(ChronoUnit.FOREVER), false);
}
 
Example 11
Project: IP1   File: SearchDetailsController.java   Source Code and License 6 votes vote down vote up
@FXML
private void borrowBook(ActionEvent event) {
    if(!borrowed.isBookBorrowedAlready(Main.getId(), this.bookId)) {
        LocalDate today = LocalDate.now();
        LocalDate next2Week = today.plus(2, ChronoUnit.WEEKS);

        borrowed.addNewBorrowedBook(Main.getId(), this.bookId, today.toString(), next2Week.toString());
        book.updateBookQuantity(this.bookId, -1);

        quantity.setText(Integer.toString(bookDetails.getQuantity() - 1));
        warning.setTextFill(Color.web("#00FF00"));
        warning.setText("Book successfully borrowed!");

        this.isBorrowOrRequestAllowed();
    } else {
        warning.setTextFill(Color.web("#FF0000"));
        warning.setText("Book borrowed already!");
    }
}
 
Example 12
Project: openjdk-jdk10   File: TCKMinguoChronology.java   Source Code and License 6 votes vote down vote up
@SuppressWarnings("unused")
@Test(dataProvider="samples")
public void test_MinguoDate(MinguoDate minguoDate, LocalDate iso) {
    MinguoDate hd = minguoDate;
    ChronoLocalDateTime<MinguoDate> hdt = hd.atTime(LocalTime.NOON);
    ZoneOffset zo = ZoneOffset.ofHours(1);
    ChronoZonedDateTime<MinguoDate> hzdt = hdt.atZone(zo);
    hdt = hdt.plus(1, ChronoUnit.YEARS);
    hdt = hdt.plus(1, ChronoUnit.MONTHS);
    hdt = hdt.plus(1, ChronoUnit.DAYS);
    hdt = hdt.plus(1, ChronoUnit.HOURS);
    hdt = hdt.plus(1, ChronoUnit.MINUTES);
    hdt = hdt.plus(1, ChronoUnit.SECONDS);
    hdt = hdt.plus(1, ChronoUnit.NANOS);
    ChronoLocalDateTime<MinguoDate> a2 = hzdt.toLocalDateTime();
    MinguoDate a3 = a2.toLocalDate();
    MinguoDate a5 = hzdt.toLocalDate();
    //System.out.printf(" d: %s, dt: %s; odt: %s; zodt: %s; a4: %s%n", date, hdt, hodt, hzdt, a5);
}
 
Example 13
Project: cas-5.1.0   File: TicketGrantingTicketExpirationPolicy.java   Source Code and License 6 votes vote down vote up
@Override
public boolean isExpired(final TicketState ticketState) {
    final ZonedDateTime currentSystemTime = ZonedDateTime.now(ZoneOffset.UTC);
    final ZonedDateTime creationTime = ticketState.getCreationTime();
    final ZonedDateTime lastTimeUsed = ticketState.getLastTimeUsed();

    // Ticket has been used, check maxTimeToLive (hard window)
    ZonedDateTime expirationTime = creationTime.plus(this.maxTimeToLiveInSeconds, ChronoUnit.SECONDS);
    if (currentSystemTime.isAfter(expirationTime)) {
        LOGGER.debug("Ticket is expired because the time since creation is greater than maxTimeToLiveInSeconds");
        return true;
    }

    expirationTime = lastTimeUsed.plus(this.timeToKillInSeconds, ChronoUnit.SECONDS);
    if (currentSystemTime.isAfter(expirationTime)) {
        LOGGER.debug("Ticket is expired because the time since last use is greater than timeToKillInSeconds");
        return true;
    }

    return false;
}
 
Example 14
Project: morpheus-core   File: RangeBasicTests.java   Source Code and License 6 votes vote down vote up
@Test(dataProvider = "localDateRanges")
public void testRangeOfLocalDates(LocalDate start, LocalDate end, Period step, boolean parallel) {
    final Range<LocalDate> range = Range.of(start, end, step);
    final Array<LocalDate> array = range.toArray(parallel);
    final boolean ascend = start.isBefore(end);
    final int expectedLength = (int)Math.ceil(Math.abs((double)ChronoUnit.DAYS.between(start, end)) / (double)step.getDays());
    Assert.assertEquals(array.length(), expectedLength);
    Assert.assertEquals(array.typeCode(), ArrayType.LOCAL_DATE);
    Assert.assertTrue(!array.style().isSparse());
    Assert.assertEquals(range.start(), start, "The range start");
    Assert.assertEquals(range.end(), end, "The range end");
    LocalDate expected = null;
    for (int i=0; i<array.length(); ++i) {
        final LocalDate actual = array.getValue(i);
        expected = expected == null ? start : ascend ? expected.plus(step) : expected.minus(step);
        Assert.assertEquals(actual, expected, "Value matches at " + i);
        Assert.assertTrue(ascend ? actual.compareTo(start) >=0 && actual.isBefore(end) : actual.compareTo(start) <= 0 && actual.isAfter(end), "Value in bounds at " + i);
    }
}
 
Example 15
Project: Chronetic   File: ChronoRangeTest.java   Source Code and License 6 votes vote down vote up
@Test
public void chronoRangeTest3() {
    ChronoSeries chronoSeries = ChronoSeries.fromFrequency(1, ChronoUnit.SECONDS,
            Instant.parse("2017-07-30T14:08:20Z"), Instant.parse("2017-07-30T14:18:24Z"));
    ISeq<ChronoGene> genes = ISeq.of(
            new ChronoGene(new ChronoPattern(ChronoScaleUnit.asFactual(chronoSeries, ChronoUnit.MINUTES), 0, 14)),
            new ChronoGene(new ChronoPattern(ChronoScaleUnit.asFactual(chronoSeries, ChronoUnit.MINUTES), 0, 18))
    );
    ChronoRange chronoRange = ChronoRange.getChronoRange(chronoSeries, genes);

    assertTrue(chronoRange.getTimestampRanges().size() == 2);
    assertArrayEquals("Invalid ChronoRange", new Instant[]{
            Instant.parse("2017-07-30T14:14:00Z"),
            Instant.parse("2017-07-30T14:15:00Z"),
    }, chronoRange.getTimestampRanges().get(0));
    assertArrayEquals("Invalid ChronoRange", new Instant[]{
            Instant.parse("2017-07-30T14:18:00Z"),
            Instant.parse("2017-07-30T14:18:24Z"),
    }, chronoRange.getTimestampRanges().get(1));
    assertTrue(chronoRange.getRangeDuration().getSeconds() == (60 + 24));
}
 
Example 16
Project: spring-io   File: UserServiceIntTest.java   Source Code and License 6 votes vote down vote up
@Test
public void assertThatResetKeyMustNotBeOlderThan24Hours() {
    User user = userService.createUser("johndoe", "johndoe", "John", "Doe", "[email protected]", "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 17
Project: cas-5.1.0   File: MultiTimeUseOrTimeoutExpirationPolicy.java   Source Code and License 6 votes vote down vote up
@Override
public boolean isExpired(final TicketState ticketState) {
    if (ticketState == null) {
        LOGGER.debug("Ticket state is null for [{}]", this.getClass().getSimpleName());
        return true;
    }
    final long countUses = ticketState.getCountOfUses();
    if (countUses >= this.numberOfUses) {
        LOGGER.debug("Ticket usage count [{}] is greater than or equal to [{}]", countUses, this.numberOfUses);
        return true;
    }

    final ZonedDateTime systemTime = ZonedDateTime.now(ZoneOffset.UTC);
    final ZonedDateTime lastTimeUsed = ticketState.getLastTimeUsed();
    final ZonedDateTime expirationTime = lastTimeUsed.plus(this.timeToKillInSeconds, ChronoUnit.SECONDS);

    if (systemTime.isAfter(expirationTime)) {
        LOGGER.debug("Ticket has expired because the difference between current time [{}] "
                        + "and ticket time [{}] is greater than or equal to [{}]", systemTime, lastTimeUsed,
                this.timeToKillInSeconds);
        return true;
    }
    return false;
}
 
Example 18
Project: InfoSys-1D   File: WeekCalendarServiceImpl.java   Source Code and License 6 votes vote down vote up
private List<List<String>> createProfCalMatrix(String profAlias, LocalDate startDateOfSchoolWeek) {
    List<BookingSlot> slotList = slotService.getSlotsByProfAndSWeek(profAlias, startDateOfSchoolWeek);
    List<List<String>> output = new ArrayList<>();
    List<String> temp;

    for (int i = 0; i < WEEK_CAL_ROW; i++) {
        LocalTime timePart = ROW_TO_TIME.get(i);
        String timeRange = timeRangeFormat(timePart);

        temp = new ArrayList<>();
        temp.add(timeRange);

        for (int j = 0; j < WEEK_CAL_COL; j++) {
            LocalDate datePart = startDateOfSchoolWeek.plus(j, ChronoUnit.DAYS);
            LocalDateTime dateTime = LocalDateTime.of(datePart, timePart);

            temp.add(createProfCalString(dateTime, slotList));
        }

        output.add(temp);
    }

    return output;
}
 
Example 19
Project: Chronetic   File: ChronoRangeTest.java   Source Code and License 6 votes vote down vote up
@Test
public void chronoRangeCompareTest3() {
    ChronoSeries chronoSeries = ChronoSeries.of(
            Instant.parse("2011-11-04T08:48:11Z"),
            Instant.parse("2012-11-02T09:23:16Z"),
            Instant.parse("2013-11-01T09:51:49Z"),
            Instant.parse("2014-11-07T08:43:00Z"),
            Instant.parse("2015-11-06T08:22:25Z")
    );
    ISeq<ChronoGene> genes = ISeq.of(
            new ChronoGene(new ChronoPattern(ChronoScaleUnit.asFactual(chronoSeries, ChronoUnit.HOURS), 0, 0))
    );
    ChronoRange chronoRange = ChronoRange.getChronoRange(chronoSeries, genes);

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

    assertTrue(chronoRange.isSameChronoRange(chronoRange2));
}
 
Example 20
Project: Chronetic   File: ChronoRangeTest.java   Source Code and License 6 votes vote down vote up
@Test
public void chronoRangeCompareTest9() {
    ChronoSeries chronoSeries = ChronoSeries.of(
            Instant.parse("2011-11-04T08:48:11Z"),
            Instant.parse("2012-11-02T09:23:16Z"),
            Instant.parse("2013-11-01T09:51:49Z"),
            Instant.parse("2014-11-07T08:43:00Z"),
            Instant.parse("2015-11-06T08:22:25Z")
    );
    ISeq<ChronoGene> genes = ISeq.of(
            new ChronoGene(new ChronoPattern(ChronoScaleUnit.asFactual(chronoSeries, ChronoUnit.WEEKS), 0, 1))
    );
    ChronoRange chronoRange = ChronoRange.getChronoRange(chronoSeries, genes);

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

    assertTrue(chronoRange.isSameChronoRange(chronoRange2));
}
 
Example 21
Project: pugtsdb   File: Temporals.java   Source Code and License 6 votes vote down vote up
public static ZonedDateTime truncate(ZonedDateTime time, ChronoUnit unit) {
    switch (unit) {
        case NANOS:
        case MICROS:
        case MILLIS:
        case SECONDS:
        case MINUTES:
        case HOURS:
        case HALF_DAYS:
        case DAYS:
            return time.truncatedTo(unit);
        case MONTHS:
            return time.truncatedTo(DAYS).withDayOfMonth(1);
        case YEARS:
            return time.truncatedTo(DAYS).withDayOfYear(1);
        default:
            throw new UnsupportedTemporalTypeException("Invalid unit for truncation: " + unit);
    }
}
 
Example 22
Project: grittier_ext   File: Tags.java   Source Code and License 6 votes vote down vote up
public static void createTags(Node post, HashMap<String, Object>  input, LocalDateTime dateTime, GraphDatabaseService db) {
    Matcher mat = hashtagPattern.matcher(((String)input.get("status")).toLowerCase());
    for (Relationship r1 : post.getRelationships(Direction.OUTGOING, RelationshipType.withName("TAGGED_ON_" +
            dateTime.format(dateFormatter)))) {
        r1.delete();
    }
    Set<Node> tagged = new HashSet<>();
    while (mat.find()) {
        String tag = mat.group(1);
        Node hashtag = db.findNode(Labels.Tag, NAME, tag);
        if (hashtag == null) {
            hashtag = db.createNode(Labels.Tag);
            hashtag.setProperty(NAME, tag);
            hashtag.setProperty(TIME, dateTime.truncatedTo(ChronoUnit.DAYS).toEpochSecond(ZoneOffset.UTC));
        }
        if (!tagged.contains(hashtag)) {
            post.createRelationshipTo(hashtag, RelationshipType.withName("TAGGED_ON_" +
                    dateTime.format(dateFormatter)));
            tagged.add(hashtag);
        }
    }
}
 
Example 23
Project: calendar-component   File: Calendar.java   Source Code and License 5 votes vote down vote up
@Override
public void rangeSelect(SelectionRange selectionRange) {

    if (!isClientChangeAllowed()) {
        return;
    }

    // MounthSelection
    if (selectionRange.s != null && selectionRange.e != null) {

        fireRangeSelect(
                ZonedDateTime.of(
                        selectionRange.s.y,
                        selectionRange.s.m,
                        selectionRange.s.d,
                        0,0,0,0, getZoneId()),
                ZonedDateTime.of(
                        selectionRange.e.y,
                        selectionRange.e.m,
                        selectionRange.e.d,
                        23, 59, 59, 999999, getZoneId()));

    } else if (selectionRange.s != null) {

        ZonedDateTime dateTime = ZonedDateTime.of(
                selectionRange.s.y,
                selectionRange.s.m,
                selectionRange.s.d,
                0,0,0,0, getZoneId());

        ZonedDateTime start = ZonedDateTime.from(dateTime.plus(selectionRange.sMin, ChronoUnit.MINUTES));
        ZonedDateTime end   = ZonedDateTime.from(dateTime.plus(selectionRange.eMin, ChronoUnit.MINUTES));

        fireRangeSelect(start, end);

    }
}
 
Example 24
Project: jdk8u-jdk   File: TCKLocalDateTime.java   Source Code and License 5 votes vote down vote up
@DataProvider(name="query")
Object[][] data_query() {
    return new Object[][] {
            {TEST_2007_07_15_12_30_40_987654321, TemporalQueries.chronology(), IsoChronology.INSTANCE},
            {TEST_2007_07_15_12_30_40_987654321, TemporalQueries.zoneId(), null},
            {TEST_2007_07_15_12_30_40_987654321, TemporalQueries.precision(), ChronoUnit.NANOS},
            {TEST_2007_07_15_12_30_40_987654321, TemporalQueries.zone(), null},
            {TEST_2007_07_15_12_30_40_987654321, TemporalQueries.offset(), null},
            {TEST_2007_07_15_12_30_40_987654321, TemporalQueries.localDate(), LocalDate.of(2007, 7, 15)},
            {TEST_2007_07_15_12_30_40_987654321, TemporalQueries.localTime(), LocalTime.of(12, 30, 40, 987654321)},
    };
}
 
Example 25
Project: Saber-Bot   File: Logging.java   Source Code and License 5 votes vote down vote up
/**
 * used logging minor (possibly expected) errors (level 2)
 * @param caller the java class from which the command is called
 * @param msg the message to log
 */
public static void warn(Class caller, String msg)
{
    if(Main.getBotSettingsManager().getLogLevel() < 2) return;

    String now = LocalTime.now().truncatedTo(ChronoUnit.SECONDS).format(DateTimeFormatter.ISO_LOCAL_TIME);
    String content = "[" + now + "] " +
            ANSI_RED + "[Warn]" + ANSI_RESET + " " +
            ANSI_YELLOW_BACKGROUND + ANSI_BLACK +
            "[" + caller.getSimpleName() + "]" +
            ANSI_RESET + " " + ANSI_RED + msg +
            ANSI_RESET;

    System.out.println(content);
}
 
Example 26
Project: learn-java8   File: DateTests.java   Source Code and License 5 votes vote down vote up
@Test
public void testSpecificDate() {
      LocalDate Christmas = LocalDate.of(2014, Month.DECEMBER, 25);
      System.out.println("Christmas Date: " + Christmas);
      
      LocalDate newYearsDay = Christmas.plus(1, ChronoUnit.WEEKS);
      System.out.println("New Years Eve: " + newYearsDay);
      
      assertEquals(DayOfWeek.THURSDAY, newYearsDay.getDayOfWeek());
      assertEquals(1, newYearsDay.getDayOfMonth());
      assertEquals(1, newYearsDay.getMonthValue());
      assertEquals(2015, newYearsDay.getYear());
}
 
Example 27
Project: openjdk-jdk10   File: TestIsoWeekFields.java   Source Code and License 5 votes vote down vote up
@Test(dataProvider = "fields")
public void test_WBY_basics(TemporalField weekField, TemporalField yearField) {
    assertEquals(yearField.isDateBased(), true);
    assertEquals(yearField.isTimeBased(), false);
    assertEquals(yearField.getBaseUnit(), IsoFields.WEEK_BASED_YEARS);
    assertEquals(yearField.getRangeUnit(), ChronoUnit.FOREVER);
}
 
Example 28
Project: Shadbot   File: HangmanManager.java   Source Code and License 5 votes vote down vote up
public HangmanManager(AbstractCommand cmd, String prefix, IChannel channel, IUser author, Difficulty difficulty) {
	super(cmd, prefix, channel, author);
	this.rateLimiter = new RateLimiter(2, 2, ChronoUnit.SECONDS);
	this.message = new UpdateableMessage(channel);
	this.word = HangmanCmd.getWord(difficulty);
	this.charsTested = new ArrayList<>();
	this.failsCount = 0;
}
 
Example 29
Project: jdk8u-jdk   File: TCKLocalDate.java   Source Code and License 5 votes vote down vote up
@DataProvider(name="query")
Object[][] data_query() {
    return new Object[][] {
            {TEST_2007_07_15, TemporalQueries.chronology(), IsoChronology.INSTANCE},
            {TEST_2007_07_15, TemporalQueries.zoneId(), null},
            {TEST_2007_07_15, TemporalQueries.precision(), ChronoUnit.DAYS},
            {TEST_2007_07_15, TemporalQueries.zone(), null},
            {TEST_2007_07_15, TemporalQueries.offset(), null},
            {TEST_2007_07_15, TemporalQueries.localDate(), TEST_2007_07_15},
            {TEST_2007_07_15, TemporalQueries.localTime(), null},
    };
}
 
Example 30
Project: Saber-Bot   File: ScheduleEntry.java   Source Code and License 5 votes vote down vote up
/**
 * handles when an event ends
 */
public void end()
{
    Message msg = this.getMessageObject();
    if(msg == null) return;

    if(!this.quietEnd)
    {
        // dont send end announcement if 15 minutes late
        if(this.entryEnd.isAfter(ZonedDateTime.now().minusMinutes(15)))
        {
            // send the end announcement
            String endMsg = ParsingUtilities.parseMessageFormat(Main.getScheduleManager().getEndAnnounceFormat(this.chanId), this, true);
            String identifier = Main.getScheduleManager().getEndAnnounceChan(this.chanId);
            if(identifier != null)
            {
                announcementHelper(msg, endMsg, identifier);
                Logging.event(this.getClass(), "Ended event \"" + this.getTitle() + "\" [" + this.entryId + "] scheduled for " +
                        this.getEnd().withZoneSameInstant(ZoneId.systemDefault())
                                .truncatedTo(ChronoUnit.MINUTES).toLocalTime().toString());
            }
        }
    }
    else
    {
        Logging.warn(this.getClass(), "Late event end: "+this.entryTitle+" ["+this.entryId+"] "+this.entryEnd);
    }

    this.repeat();
}
 
Example 31
Project: jdk8u-jdk   File: TCKYearMonth.java   Source Code and License 5 votes vote down vote up
@DataProvider(name="plus_long_TemporalUnit")
Object[][] data_plus_long_TemporalUnit() {
    return new Object[][] {
        {YearMonth.of(1, 10), 1, ChronoUnit.YEARS, YearMonth.of(2, 10), null},
        {YearMonth.of(1, 10), -12, ChronoUnit.YEARS, YearMonth.of(-11, 10), null},
        {YearMonth.of(1, 10), 0, ChronoUnit.YEARS, YearMonth.of(1, 10), null},
        {YearMonth.of(999999999, 12), 0, ChronoUnit.YEARS, YearMonth.of(999999999, 12), null},
        {YearMonth.of(-999999999, 1), 0, ChronoUnit.YEARS, YearMonth.of(-999999999, 1), null},
        {YearMonth.of(0, 1), -999999999, ChronoUnit.YEARS, YearMonth.of(-999999999, 1), null},
        {YearMonth.of(0, 12), 999999999, ChronoUnit.YEARS, YearMonth.of(999999999, 12), null},

        {YearMonth.of(1, 10), 1, ChronoUnit.MONTHS, YearMonth.of(1, 11), null},
        {YearMonth.of(1, 10), -12, ChronoUnit.MONTHS, YearMonth.of(0, 10), null},
        {YearMonth.of(1, 10), 0, ChronoUnit.MONTHS, YearMonth.of(1, 10), null},
        {YearMonth.of(999999999, 12), 0, ChronoUnit.MONTHS, YearMonth.of(999999999, 12), null},
        {YearMonth.of(-999999999, 1), 0, ChronoUnit.MONTHS, YearMonth.of(-999999999, 1), null},
        {YearMonth.of(-999999999, 2), -1, ChronoUnit.MONTHS, YearMonth.of(-999999999, 1), null},
        {YearMonth.of(999999999, 3), 9, ChronoUnit.MONTHS, YearMonth.of(999999999, 12), null},

        {YearMonth.of(-1, 10), 1, ChronoUnit.ERAS, YearMonth.of(2, 10), null},
        {YearMonth.of(5, 10), 1, ChronoUnit.CENTURIES, YearMonth.of(105, 10), null},
        {YearMonth.of(5, 10), 1, ChronoUnit.DECADES, YearMonth.of(15, 10), null},

        {YearMonth.of(999999999, 12), 1, ChronoUnit.MONTHS, null, DateTimeException.class},
        {YearMonth.of(-999999999, 1), -1, ChronoUnit.MONTHS, null, DateTimeException.class},

        {YearMonth.of(1, 1), 0, ChronoUnit.DAYS, null, DateTimeException.class},
        {YearMonth.of(1, 1), 0, ChronoUnit.WEEKS, null, DateTimeException.class},
    };
}
 
Example 32
Project: Hydrograph   File: DateFunctions.java   Source Code and License 5 votes vote down vote up
/**
 * Returns an integer which hold difference of years between two dates
 *
 * @param fromDate the date from which the difference is to be calculated
 * @param toDate   the date to which the difference is to be calculated
 * @return difference of years between {@code fromDate} and {@code toDate}
 * if either of {@code fromDate} or {@code toDate} are null return null
 */
public static Integer getYearDifference(Date fromDate, Date toDate) {

    if (fromDate == null || toDate == null)
        return null;
    Date localFromDate = new Date(fromDate.getTime());
    Date localToDate = new Date(toDate.getTime());

    LocalDateTime firstDate = LocalDateTime.ofInstant(localFromDate.toInstant(), ZoneId.systemDefault());
    LocalDateTime secondDate = LocalDateTime.ofInstant(localToDate.toInstant(), ZoneId.systemDefault());
    long years = Math.abs(ChronoUnit.YEARS.between(firstDate, secondDate));
    return (int) (long) years;
}
 
Example 33
Project: vind   File: FullTextEntry.java   Source Code and License 5 votes vote down vote up
public FullTextEntry(Application application, String source, FulltextSearch search, SearchResult result, ZonedDateTime start, ZonedDateTime end, Session session) {
    this.application = application;
    this.session = session;
    this.timeStamp = start;
    this.request = new FullTextRequest(search,source);
    this.response = new Response(result.getNumOfResults(), start.until(end, ChronoUnit.MILLIS));
    this.sorting = search.getSorting().toString();
    this.paging = new Paging(search.getResultSet());
}
 
Example 34
Project: openjdk-jdk10   File: TestUmmAlQuraChronology.java   Source Code and License 5 votes vote down vote up
@Test (dataProvider="monthDays")
public void test_valueRange_monthDays(int year, int month, int maxlength) {
    ChronoLocalDate date = HijrahChronology.INSTANCE.date(year, month, 1);
    ValueRange range = null;
    for (int i=1; i<=12; i++) {
        range = date.range(ChronoField.DAY_OF_MONTH);
        date = date.plus(1, ChronoUnit.MONTHS);
        assertEquals(range.getMaximum(), month, maxlength);
    }
}
 
Example 35
Project: Chronetic   File: ChronoScale.java   Source Code and License 5 votes vote down vote up
/**
 * Returns the parent ChronoUnit for the given ChronoUnit.
 *
 * @param chronoUnit desired ChronoUnit
 * @return parent ChronoUnit of the given ChronoUnit
 */
@NotNull
public static ChronoUnit getParentChronoUnit(@NotNull ChronoUnit chronoUnit) {
    switch (requireNonNull(chronoUnit)) {
        case NANOS:
            return ChronoUnit.SECONDS;
        case MICROS:
            return ChronoUnit.SECONDS;
        case MILLIS:
            return ChronoUnit.SECONDS;
        case SECONDS:
            return ChronoUnit.MINUTES;
        case MINUTES:
            return ChronoUnit.HOURS;
        case HOURS:
            return ChronoUnit.DAYS;
        case DAYS:
            return ChronoUnit.WEEKS;
        case WEEKS:
            return ChronoUnit.MONTHS;
        case MONTHS:
            return ChronoUnit.YEARS;
        case YEARS:
            return ChronoUnit.DECADES;
        case DECADES:
            return ChronoUnit.CENTURIES;
        case CENTURIES:
            return ChronoUnit.ERAS;
        default:
            throw new UnsupportedOperationException("Unsupported chrono unit: " + chronoUnit);
    }
}
 
Example 36
Project: TorgCRM-Server   File: UserServiceIntTest.java   Source Code and License 5 votes vote down vote up
@Test
@Transactional
public void assertThatResetKeyMustBeValid() {
    Instant daysAgo = Instant.now().minus(25, ChronoUnit.HOURS);
    user.setActivated(true);
    user.setResetDate(daysAgo);
    user.setResetKey("1234");
    userRepository.saveAndFlush(user);

    Optional<User> maybeUser = userService.completePasswordReset("johndoe2", user.getResetKey());
    assertThat(maybeUser).isNotPresent();
    userRepository.delete(user);
}
 
Example 37
Project: patient-portal   File: UserServiceIntTest.java   Source Code and License 5 votes vote down vote up
@Test
public void testRemoveNotActivatedUsers() {
    User user = userService.createUser("johndoe", "johndoe", "John", "Doe", "[email protected]", "http://placehold.it/50x50", "en-US");
    user.setActivated(false);
    user.setCreatedDate(Instant.now().minus(30, ChronoUnit.DAYS));
    userRepository.save(user);
    assertThat(userRepository.findOneByLogin("johndoe")).isPresent();
    userService.removeNotActivatedUsers();
    assertThat(userRepository.findOneByLogin("johndoe")).isNotPresent();
}
 
Example 38
Project: spring-io   File: UserServiceIntTest.java   Source Code and License 5 votes vote down vote up
@Test
public void testFindNotActivatedUsersByCreationDateBefore() {
    userService.removeNotActivatedUsers();
    Instant now = Instant.now();
    List<User> users = userRepository.findAllByActivatedIsFalseAndCreatedDateBefore(now.minus(3, ChronoUnit.DAYS));
    assertThat(users).isEmpty();
}
 
Example 39
Project: codemotion-2017-taller-de-jhipster   File: UserServiceIntTest.java   Source Code and License 5 votes vote down vote up
@Test
@Transactional
public void testFindNotActivatedUsersByCreationDateBefore() {
    Instant now = Instant.now();
    user.setActivated(false);
    User dbUser = userRepository.saveAndFlush(user);
    dbUser.setCreatedDate(now.minus(4, ChronoUnit.DAYS));
    userRepository.saveAndFlush(user);
    List<User> users = userRepository.findAllByActivatedIsFalseAndCreatedDateBefore(now.minus(3, ChronoUnit.DAYS));
    assertThat(users).isNotEmpty();
    userService.removeNotActivatedUsers();
    users = userRepository.findAllByActivatedIsFalseAndCreatedDateBefore(now.minus(3, ChronoUnit.DAYS));
    assertThat(users).isEmpty();
}
 
Example 40
Project: Chronetic   File: ChronoDescriptor.java   Source Code and License 5 votes vote down vote up
@NotNull
private String everyChronoUnit(@NotNull ChronoUnit chronoUnit) {
    String singular = singularChronoUnit(requireNonNull(chronoUnit));
    switch (singular) {
        case "nanosecond":
            return "every nanosecond";
        case "microsecond":
            return "every microsecond";
        case "millisecond":
            return "every millisecond";
        case "second":
            return "every second";
        case "minute":
            return "every minute";
        case "hour":
            return "every hour";
        case "day":
            return "every day";
        case "week":
            return "every week";
        case "month":
            return "every month";
        case "year":
            return "every year";
        default:
            throw new RuntimeException("bad");
    }
}