Example usage for java.time.temporal ChronoUnit HOURS

List of usage examples for java.time.temporal ChronoUnit HOURS

Introduction

In this page you can find the example usage for java.time.temporal ChronoUnit HOURS.

Prototype

ChronoUnit HOURS

To view the source code for java.time.temporal ChronoUnit HOURS.

Click Source Link

Document

Unit that represents the concept of an hour.

Usage

From source file:org.apache.openmeetings.web.user.calendar.CalendarPanel.java

@Override
protected void onInitialize() {
    final Form<Date> form = new Form<>("form");
    add(form);/* w  w  w .  j a va 2s .  c  o m*/

    dialog = new AppointmentDialog("appointment", this, new CompoundPropertyModel<>(getDefault()));
    add(dialog);

    boolean isRtl = isRtl();
    Options options = new Options();
    options.set("isRTL", isRtl);
    options.set("height", Options.asString("parent"));
    options.set("header", isRtl
            ? "{left: 'agendaDay,agendaWeek,month', center: 'title', right: 'today nextYear,next,prev,prevYear'}"
            : "{left: 'prevYear,prev,next,nextYear today', center: 'title', right: 'month,agendaWeek,agendaDay'}");
    options.set("allDaySlot", false);
    options.set("axisFormat", Options.asString("H(:mm)"));
    options.set("defaultEventMinutes", 60);
    options.set("timeFormat", Options.asString("H(:mm)"));

    options.set("buttonText", new JSONObject().put("month", getString("801")).put("week", getString("800"))
            .put("day", getString("799")).put("today", getString("1555")).toString());

    options.set("locale", Options.asString(WebSession.get().getLocale().toLanguageTag()));

    calendar = new Calendar("calendar", new AppointmentModel(), options) {
        private static final long serialVersionUID = 1L;

        @Override
        protected void onInitialize() {
            super.onInitialize();
            add(new CalendarFunctionsBehavior(getMarkupId()));
        }

        @Override
        public boolean isSelectable() {
            return true;
        }

        @Override
        public boolean isDayClickEnabled() {
            return true;
        }

        @Override
        public boolean isEventClickEnabled() {
            return true;
        }

        @Override
        public boolean isEventDropEnabled() {
            return true;
        }

        @Override
        public boolean isEventResizeEnabled() {
            return true;
        }

        //no need to override onDayClick
        @Override
        public void onSelect(AjaxRequestTarget target, CalendarView view, LocalDateTime start,
                LocalDateTime end, boolean allDay) {
            Appointment a = getDefault();
            LocalDateTime s = start, e = end;
            if (CalendarView.month == view) {
                LocalDateTime now = ZonedDateTime.now(getZoneId()).toLocalDateTime();
                s = start.withHour(now.getHour()).withMinute(now.getMinute());
                e = s.plus(1, ChronoUnit.HOURS);
            }
            a.setStart(getDate(s));
            a.setEnd(getDate(e));
            dialog.setModelObjectWithAjaxTarget(a, target);

            dialog.open(target);
        }

        @Override
        public void onEventClick(AjaxRequestTarget target, CalendarView view, String eventId) {
            if (!StringUtils.isNumeric(eventId)) {
                return;
            }
            Appointment a = apptDao.get(Long.valueOf(eventId));
            dialog.setModelObjectWithAjaxTarget(a, target);

            dialog.open(target);
        }

        @Override
        public void onEventDrop(AjaxRequestTarget target, String eventId, long delta, boolean allDay) {
            if (!StringUtils.isNumeric(eventId)) {
                refresh(target);
                return;
            }
            Appointment a = apptDao.get(Long.valueOf(eventId));
            if (!AppointmentDialog.isOwner(a)) {
                return;
            }
            java.util.Calendar cal = WebSession.getCalendar();
            cal.setTime(a.getStart());
            cal.add(java.util.Calendar.MILLISECOND, (int) delta);
            a.setStart(cal.getTime());

            cal.setTime(a.getEnd());
            cal.add(java.util.Calendar.MILLISECOND, (int) delta);
            a.setEnd(cal.getTime());

            apptDao.update(a, getUserId());

            if (a.getCalendar() != null) {
                updatedeleteAppointment(target, CalendarDialog.DIALOG_TYPE.UPDATE_APPOINTMENT, a);
            }
        }

        @Override
        public void onEventResize(AjaxRequestTarget target, String eventId, long delta) {
            if (!StringUtils.isNumeric(eventId)) {
                refresh(target);
                return;
            }
            Appointment a = apptDao.get(Long.valueOf(eventId));
            if (!AppointmentDialog.isOwner(a)) {
                return;
            }
            java.util.Calendar cal = WebSession.getCalendar();
            cal.setTime(a.getEnd());
            cal.add(java.util.Calendar.MILLISECOND, (int) delta);
            a.setEnd(cal.getTime());

            apptDao.update(a, getUserId());

            if (a.getCalendar() != null) {
                updatedeleteAppointment(target, CalendarDialog.DIALOG_TYPE.UPDATE_APPOINTMENT, a);
            }
        }
    };

    form.add(calendar);

    populateGoogleCalendars();

    add(refreshTimer);
    add(syncTimer);

    calendarDialog = new CalendarDialog("calendarDialog", this,
            new CompoundPropertyModel<>(getDefaultCalendar()));

    add(calendarDialog);

    calendarListContainer.setOutputMarkupId(true);
    calendarListContainer
            .add(new ListView<OmCalendar>("items", new LoadableDetachableModel<List<OmCalendar>>() {
                private static final long serialVersionUID = 1L;

                @Override
                protected List<OmCalendar> load() {
                    List<OmCalendar> cals = new ArrayList<>(apptManager.getCalendars(getUserId()));
                    cals.addAll(apptManager.getGoogleCalendars(getUserId()));
                    return cals;
                }
            }) {
                private static final long serialVersionUID = 1L;

                @Override
                protected void populateItem(final ListItem<OmCalendar> item) {
                    item.setOutputMarkupId(true);
                    final OmCalendar cal = item.getModelObject();
                    item.add(new WebMarkupContainer("item").add(new Label("name", cal.getTitle())));
                    item.add(new AjaxEventBehavior(EVT_CLICK) {
                        private static final long serialVersionUID = 1L;

                        @Override
                        protected void onEvent(AjaxRequestTarget target) {
                            calendarDialog.open(target, CalendarDialog.DIALOG_TYPE.UPDATE_CALENDAR, cal);
                            target.add(calendarDialog);
                        }
                    });
                }
            });

    add(new Button("syncCalendarButton").add(new AjaxEventBehavior(EVT_CLICK) {
        private static final long serialVersionUID = 1L;

        @Override
        protected void onEvent(AjaxRequestTarget target) {
            syncCalendar(target);
        }
    }));

    add(new Button("submitCalendar").add(new AjaxEventBehavior(EVT_CLICK) {
        private static final long serialVersionUID = 1L;

        @Override
        protected void onEvent(AjaxRequestTarget target) {
            calendarDialog.open(target, CalendarDialog.DIALOG_TYPE.UPDATE_CALENDAR, getDefaultCalendar());
            target.add(calendarDialog);
        }
    }));

    add(calendarListContainer);

    super.onInitialize();
}

From source file:org.apache.solr.cloud.CreateRoutedAliasTest.java

@Test
public void testV1() throws Exception {
    final String aliasName = getTestName();
    final String baseUrl = cluster.getRandomJetty(random()).getBaseUrl().toString();
    Instant start = Instant.now().truncatedTo(ChronoUnit.HOURS); // mostly make sure no millis
    HttpGet get = new HttpGet(baseUrl + "/admin/collections?action=CREATEALIAS" + "&wt=xml" + "&name="
            + aliasName + "&router.field=evt_dt" + "&router.name=time" + "&router.start=" + start
            + "&router.interval=%2B30MINUTE" + "&create-collection.collection.configName=_default"
            + "&create-collection.router.field=foo_s" + "&create-collection.numShards=1"
            + "&create-collection.replicationFactor=2");
    assertSuccess(get);/*ww  w  .j  ava2 s . com*/

    String initialCollectionName = TimeRoutedAlias.formatCollectionNameFromInstant(aliasName, start);
    assertCollectionExists(initialCollectionName);

    // Test created collection:
    final DocCollection coll = solrClient.getClusterStateProvider().getState(initialCollectionName).get();
    //TODO how do we assert the configSet ?
    assertEquals(CompositeIdRouter.class, coll.getRouter().getClass());
    assertEquals("foo_s", ((Map) coll.get("router")).get("field"));
    assertEquals(1, coll.getSlices().size()); // numShards
    assertEquals(2, coll.getReplicationFactor().intValue()); // num replicas
    //TODO SOLR-11877 assertEquals(2, coll.getStateFormat());

    // Test Alias metadata
    Aliases aliases = cluster.getSolrClient().getZkStateReader().getAliases();
    Map<String, String> collectionAliasMap = aliases.getCollectionAliasMap();
    String alias = collectionAliasMap.get(aliasName);
    assertNotNull(alias);
    Map<String, String> meta = aliases.getCollectionAliasProperties(aliasName);
    assertNotNull(meta);
    assertEquals("evt_dt", meta.get("router.field"));
    assertEquals("_default", meta.get("create-collection.collection.configName"));
    assertEquals(null, meta.get("start"));
}

From source file:com.simiacryptus.util.Util.java

/**
 * Cvt temporal unit.//ww w.j  a  va2  s .c o  m
 *
 * @param units the units
 * @return the temporal unit
 */
@javax.annotation.Nonnull
public static TemporalUnit cvt(@javax.annotation.Nonnull final TimeUnit units) {
    switch (units) {
    case DAYS:
        return ChronoUnit.DAYS;
    case HOURS:
        return ChronoUnit.HOURS;
    case MINUTES:
        return ChronoUnit.MINUTES;
    case SECONDS:
        return ChronoUnit.SECONDS;
    case NANOSECONDS:
        return ChronoUnit.NANOS;
    case MICROSECONDS:
        return ChronoUnit.MICROS;
    case MILLISECONDS:
        return ChronoUnit.MILLIS;
    default:
        throw new IllegalArgumentException(units.toString());
    }
}

From source file:com.example.app.profile.model.company.CompanyModelExtension.java

/**
 * Add image./*ww  w.j  a v  a  2 s.co  m*/
 *
 * @param imageParams the image params.
 */
public static void addImage(ImageParams imageParams) {
    EntityRetriever er = EntityRetriever.getInstance();
    imageParams.getDmb().addChild(imageParams.getDomainModelName(), String.class)
            .setUsageInstructions(IMAGE_USAGE_INSTRUCTIONS())
            .addDataResolver(String.class, (domainModelContext, domainModel, arguments) -> {
                final FileEntity image = er.reattachIfNecessary((FileEntity) imageParams.getImageResolver()
                        .resolve(domainModelContext, domainModel, arguments));
                FactoryResourceConfiguration config = null;
                if (image != null && !image.isEntityTrashed()) {
                    try {
                        if (imageParams.getDimension() != null) {
                            int width = imageParams.getDimension().getWidthMetric().intValue();
                            int height = imageParams.getDimension().getHeightMetric().intValue();
                            final Dimension scaledDimension = getScaledDimension(getDimension(image), width,
                                    height);
                            final String resourceId = imageParams.getImageResourceFactory()
                                    .getPersistentResourceId(image, scaledDimension.getWidthMetric().intValue(),
                                            scaledDimension.getHeightMetric().intValue());
                            config = new FactoryResourceConfiguration(
                                    imageParams.getImageResourceFactory().getFactoryId(), resourceId);
                        }
                    } catch (IOException ioe) {
                        _logger.debug("Unable to get scaled image.", ioe);
                    }
                    if (config == null) {
                        config = new FactoryResourceConfiguration(
                                imageParams.getFileResourceFactory().getFactoryId(),
                                imageParams.getFileResourceFactory().getPersistentResourceId(image));
                    }
                    config.setExpireInterval(4, ChronoUnit.HOURS);
                } else {
                    config = new FactoryResourceConfiguration(imageParams.getAppUtil().getDefaultUserImage());
                    config.setExpireInterval(30, ChronoUnit.DAYS);
                }
                imageParams.getUrlGenerator().setHostname(domainModelContext.getSite().getDefaultHostname());
                return imageParams.getUrlGenerator().createURL(config).getLink().getURIAsString();
            });
}

From source file:org.wallride.service.PageService.java

@CacheEvict(value = WallRideCacheConfiguration.PAGE_CACHE, allEntries = true)
public Page savePage(PageUpdateRequest request, AuthorizedUser authorizedUser) {
    postRepository.lock(request.getId());
    Page page = pageRepository.findOneByIdAndLanguage(request.getId(), request.getLanguage());
    LocalDateTime now = LocalDateTime.now();

    String code = request.getCode();
    if (code == null) {
        try {//ww  w . j a  v  a2 s. c o m
            code = new CodeFormatter().parse(request.getTitle(), LocaleContextHolder.getLocale());
        } catch (ParseException e) {
            throw new ServiceException(e);
        }
    }
    if (!StringUtils.hasText(code)) {
        if (!page.getStatus().equals(Post.Status.DRAFT)) {
            throw new EmptyCodeException();
        }
    }
    if (!page.getStatus().equals(Post.Status.DRAFT)) {
        Post duplicate = postRepository.findOneByCodeAndLanguage(code, request.getLanguage());
        if (duplicate != null && !duplicate.equals(page)) {
            throw new DuplicateCodeException(code);
        }
    }

    if (!page.getStatus().equals(Post.Status.DRAFT)) {
        page.setCode(code);
        page.setDraftedCode(null);
    } else {
        page.setCode(null);
        page.setDraftedCode(code);
    }

    Page parent = (request.getParentId() != null)
            ? entityManager.getReference(Page.class, request.getParentId())
            : null;
    if (!(page.getParent() == null && parent == null)
            && !ObjectUtils.nullSafeEquals(page.getParent(), parent)) {
        pageRepository.shiftLftRgt(page.getLft(), page.getRgt());
        pageRepository.shiftRgt(page.getRgt());
        pageRepository.shiftLft(page.getRgt());

        int rgt = 0;
        if (parent == null) {
            rgt = pageRepository.findMaxRgt();
            rgt++;
        } else {
            rgt = parent.getRgt();
            pageRepository.unshiftRgt(rgt);
            pageRepository.unshiftLft(rgt);
        }
        page.setLft(rgt);
        page.setRgt(rgt + 1);
    }

    page.setParent(parent);

    Media cover = null;
    if (request.getCoverId() != null) {
        cover = entityManager.getReference(Media.class, request.getCoverId());
    }
    page.setCover(cover);
    page.setTitle(request.getTitle());
    page.setBody(request.getBody());

    //      User author = null;
    //      if (request.getAuthorId() != null) {
    //         author = entityManager.getReference(User.class, request.getAuthorId());
    //      }
    //      page.setAuthor(author);

    LocalDateTime date = request.getDate();
    if (Post.Status.PUBLISHED.equals(page.getStatus())) {
        if (date == null) {
            date = now.truncatedTo(ChronoUnit.HOURS);
        } else if (date.isAfter(now)) {
            page.setStatus(Post.Status.SCHEDULED);
        }
    }
    page.setDate(date);
    page.setLanguage(request.getLanguage());

    page.getCategories().clear();
    SortedSet<Category> categories = new TreeSet<>();
    for (long categoryId : request.getCategoryIds()) {
        categories.add(entityManager.getReference(Category.class, categoryId));
    }
    page.setCategories(categories);

    page.getTags().clear();
    Set<String> tagNames = StringUtils.commaDelimitedListToSet(request.getTags());
    if (!CollectionUtils.isEmpty(tagNames)) {
        for (String tagName : tagNames) {
            Tag tag = tagRepository.findOneForUpdateByNameAndLanguage(tagName, request.getLanguage());
            if (tag == null) {
                tag = new Tag();
                tag.setName(tagName);
                tag.setLanguage(request.getLanguage());
                page.setCreatedAt(now);
                page.setCreatedBy(authorizedUser.toString());
                page.setUpdatedAt(now);
                page.setUpdatedBy(authorizedUser.toString());
                tag = tagRepository.saveAndFlush(tag);
            }
            page.getTags().add(tag);
        }
    }

    page.getRelatedPosts().clear();
    Set<Post> relatedPosts = new HashSet<>();
    for (long relatedId : request.getRelatedPostIds()) {
        relatedPosts.add(entityManager.getReference(Post.class, relatedId));
    }
    page.setRelatedToPosts(relatedPosts);

    Seo seo = new Seo();
    seo.setTitle(request.getSeoTitle());
    seo.setDescription(request.getSeoDescription());
    seo.setKeywords(request.getSeoKeywords());
    page.setSeo(seo);

    List<Media> medias = new ArrayList<>();
    if (StringUtils.hasText(request.getBody())) {
        //         Blog blog = blogService.getBlogById(Blog.DEFAULT_ID);
        String mediaUrlPrefix = wallRideProperties.getMediaUrlPrefix();
        Pattern mediaUrlPattern = Pattern.compile(String.format("%s([0-9a-zA-Z\\-]+)", mediaUrlPrefix));
        Matcher mediaUrlMatcher = mediaUrlPattern.matcher(request.getBody());
        while (mediaUrlMatcher.find()) {
            Media media = mediaRepository.findOneById(mediaUrlMatcher.group(1));
            medias.add(media);
        }
    }
    page.setMedias(medias);

    page.setUpdatedAt(now);
    page.setUpdatedBy(authorizedUser.toString());

    SortedSet<CustomFieldValue> fieldValues = new TreeSet<>();
    Map<CustomField, CustomFieldValue> valueMap = new LinkedHashMap<>();
    for (CustomFieldValue value : page.getCustomFieldValues()) {
        valueMap.put(value.getCustomField(), value);
    }

    page.getCustomFieldValues().clear();
    if (!CollectionUtils.isEmpty(request.getCustomFieldValues())) {
        for (CustomFieldValueEditForm valueForm : request.getCustomFieldValues()) {
            CustomField customField = entityManager.getReference(CustomField.class,
                    valueForm.getCustomFieldId());
            CustomFieldValue value = valueMap.get(customField);
            if (value == null) {
                value = new CustomFieldValue();
            }
            value.setCustomField(customField);
            value.setPost(page);
            if (valueForm.getFieldType().equals(CustomField.FieldType.CHECKBOX)) {
                if (!ArrayUtils.isEmpty(valueForm.getTextValues())) {
                    value.setTextValue(String.join(",", valueForm.getTextValues()));
                } else {
                    value.setTextValue(null);
                }
            } else {
                value.setTextValue(valueForm.getTextValue());
            }
            value.setStringValue(valueForm.getStringValue());
            value.setNumberValue(valueForm.getNumberValue());
            value.setDateValue(valueForm.getDateValue());
            value.setDatetimeValue(valueForm.getDatetimeValue());
            if (!value.isEmpty()) {
                fieldValues.add(value);
            }
        }
    }
    page.setCustomFieldValues(fieldValues);

    return pageRepository.save(page);
}

From source file:com.example.app.support.service.AppUtil.java

/**
 * Get a ZonedDateTime for comparison on membership dates
 *
 * @param zone the TimeZone//from  w  ww .j a v  a  2  s.com
 *
 * @return the ZonedDateTime
 */
public static ZonedDateTime getZonedDateTimeForComparison(TimeZone zone) {
    ZonedDateTime dt = ZonedDateTime.now(zone.toZoneId());
    dt = dt.plus(1L, ChronoUnit.HOURS);
    dt = dt.truncatedTo(ChronoUnit.HOURS);
    return dt;
}

From source file:alfio.manager.TicketReservationManager.java

void sendReminderForOfflinePaymentsToEventManagers() {
    eventRepository.findAllActives(ZonedDateTime.now(Clock.systemUTC())).stream().filter(event -> {
        ZonedDateTime dateTimeForEvent = ZonedDateTime.now(event.getZoneId());
        return dateTimeForEvent.truncatedTo(ChronoUnit.HOURS).getHour() == 5; //only for the events at 5:00 local time
    }).forEachOrdered(event -> {/*from w ww  . ja v a  2 s. c o  m*/
        ZonedDateTime dateTimeForEvent = ZonedDateTime.now(event.getZoneId()).truncatedTo(ChronoUnit.DAYS)
                .plusDays(1);
        List<TicketReservationInfo> reservations = ticketReservationRepository
                .findAllOfflinePaymentReservationWithExpirationBefore(dateTimeForEvent, event.getId());
        log.info("for event {} there are {} pending offline payments to handle", event.getId(),
                reservations.size());
        if (!reservations.isEmpty()) {
            Organization organization = organizationRepository.getById(event.getOrganizationId());
            List<String> cc = notificationManager.getCCForEventOrganizer(event);
            String subject = String.format(
                    "There are %d pending offline payments that will expire in event: %s", reservations.size(),
                    event.getDisplayName());
            String baseUrl = configurationManager
                    .getRequiredValue(Configuration.from(event.getOrganizationId(), event.getId(), BASE_URL));
            Map<String, Object> model = TemplateResource
                    .prepareModelForOfflineReservationExpiringEmailForOrganizer(event, reservations, baseUrl);
            notificationManager.sendSimpleEmail(event, organization.getEmail(), cc, subject,
                    () -> templateManager.renderTemplate(event,
                            TemplateResource.OFFLINE_RESERVATION_EXPIRING_EMAIL_FOR_ORGANIZER, model,
                            Locale.ENGLISH));
            extensionManager.handleOfflineReservationsWillExpire(event, reservations);
        }
    });
}

From source file:onl.area51.gfs.grib2.job.GribRetriever.java

/**
 * Convert a {@link LocalDateTime} to a GFS run time. Specifically this is the date and hour of the day restricted to 0, 7, 12 or 18 hours.
 * <p>/*  w ww .  j  a v a  2s.co m*/
 * @param date date
 * <p>
 * @return date modified to the nearest GFS run (earlier than date) or null if date was null
 */
public static LocalDateTime toGFSRunTime(LocalDateTime date) {
    if (date == null) {
        return null;
    }

    LocalDateTime dateTime = date.truncatedTo(ChronoUnit.HOURS);

    // Only allow hours 0, 6, 12 & 18
    int h = dateTime.get(ChronoField.HOUR_OF_DAY);
    if (h % 6 == 0) {
        return dateTime;
    }

    return dateTime.withHour((h / 6) * 6);
}

From source file:org.ambraproject.rhino.rest.controller.ArticleCrudController.java

/**
 * Calculate the date range using the specified rule. For example:
 *
 * <ul>//from  w  w w . j  a v  a2  s .  com
 * <li>sinceRule=2y  - 2 years</li>
 * <li>sinceRule=5m  - 5 months</li>
 * <li>sinceRule=10d - 10 days</li>
 * <li>sinceRule=5h  - 5 hours</li>
 * <li>sinceRule=33  - 33 minutes</li>
 * </ul>
 *
 * The method will result in a {@link java.util.Map Map} containing the following keys:
 *
 * <ul>
 * <li><b>fromDate</b> - the starting date
 * <li><b>toDate</b> - the ending date, which will be the current system date (i.e. now())
 * </ul>
 *
 * @param sinceRule The rule to calculate the date range
 *
 * @return A {@link java.util.Map Map}
 */
public static final Map<String, LocalDateTime> calculateDateRange(String sinceRule) {
    if (StringUtils.isBlank(sinceRule)) {
        return ImmutableMap.of();
    }

    final String timeDesignation = StringUtils.right(sinceRule, 1);
    long timeDelta = 0;
    try {
        // Assume last character is NOT a letter (i.e. all characters are digits).
        timeDelta = Long.parseLong(sinceRule);
    } catch (NumberFormatException exception) {
        // If an exception, then last character MUST have been a letter,
        // so we now exclude the last character and re-try conversion.
        try {
            timeDelta = Long.parseLong(sinceRule.substring(0, sinceRule.length() - 1));
        } catch (NumberFormatException error) {
            log.warn("Failed to convert {} to a timeDelta/timeDesignation!", sinceRule);
            timeDelta = 0;
        }
    }

    if (timeDelta < 1) {
        return ImmutableMap.of();
    }

    final LocalDateTime toDate = LocalDateTime.now();
    final LocalDateTime fromDate;
    if (timeDesignation.equalsIgnoreCase("y")) {
        fromDate = toDate.minusYears(timeDelta);
    } else if (timeDesignation.equalsIgnoreCase("m")) {
        fromDate = toDate.minusMonths(timeDelta);
    } else if (timeDesignation.equalsIgnoreCase("d")) {
        fromDate = toDate.minusDays(timeDelta);
    } else if (timeDesignation.equalsIgnoreCase("h")) {
        fromDate = toDate.minus(timeDelta, ChronoUnit.HOURS);
    } else {
        fromDate = toDate.minus(timeDelta, ChronoUnit.MINUTES);
    }

    final ImmutableMap<String, LocalDateTime> dateRange = ImmutableMap.of(FROM_DATE, fromDate, TO_DATE, toDate);
    return dateRange;
}

From source file:org.janusgraph.diskstorage.configuration.CommonConfigTest.java

@Test
public void testDateParsing() {
    BaseConfiguration base = new BaseConfiguration();
    CommonsConfiguration config = new CommonsConfiguration(base);

    for (ChronoUnit unit : Arrays.asList(ChronoUnit.NANOS, ChronoUnit.MICROS, ChronoUnit.MILLIS,
            ChronoUnit.SECONDS, ChronoUnit.MINUTES, ChronoUnit.HOURS, ChronoUnit.DAYS)) {
        base.setProperty("test", "100 " + unit.toString());
        Duration d = config.get("test", Duration.class);
        assertEquals(TimeUnit.NANOSECONDS.convert(100, Temporals.timeUnit(unit)), d.toNanos());
    }//  w  w  w  .  j  a v a  2s.c om

    Map<ChronoUnit, String> mapping = ImmutableMap.of(ChronoUnit.MICROS, "us", ChronoUnit.DAYS, "d");
    for (Map.Entry<ChronoUnit, String> entry : mapping.entrySet()) {
        base.setProperty("test", "100 " + entry.getValue());
        Duration d = config.get("test", Duration.class);
        assertEquals(TimeUnit.NANOSECONDS.convert(100, Temporals.timeUnit(entry.getKey())), d.toNanos());
    }

}