Example usage for java.time LocalDateTime plus

List of usage examples for java.time LocalDateTime plus

Introduction

In this page you can find the example usage for java.time LocalDateTime plus.

Prototype

@Override
public LocalDateTime plus(long amountToAdd, TemporalUnit unit) 

Source Link

Document

Returns a copy of this date-time with the specified amount added.

Usage

From source file:Main.java

public static void main(String[] args) {

    LocalDateTime timePoint = LocalDateTime.now();
    LocalDateTime newDateTime = timePoint.plus(3, ChronoUnit.WEEKS).plus(3, ChronoUnit.YEARS);

    System.out.println(newDateTime);
}

From source file:Main.java

public static void main(String[] args) {
    LocalDateTime a = LocalDateTime.of(2014, 6, 30, 12, 00);

    LocalDateTime t = a.plus(10, ChronoUnit.DAYS);

    System.out.println(t);/*from w  w w  . ja va  2 s  .  com*/
}

From source file:Main.java

public static void main(String[] argv) {
    LocalDate today = LocalDate.now();
    LocalDate tomorrow = today.plusDays(1);
    LocalDateTime time = LocalDateTime.now();
    LocalDateTime nextHour = time.plusHours(1);

    System.out.println("today = " + today);
    System.out.println("1) tomorrow = " + tomorrow + " \n2) tomorrow = " + today.plus(1, DAYS));
    System.out.println("local time now = " + time);
    System.out.println("1) nextHour = " + nextHour + " \n2) nextHour = " + time.plus(1, HOURS));

    LocalDate nextWeek = today.plus(1, WEEKS);
    System.out.println("Date after 1 week : " + nextWeek);

    LocalDate previousYear = today.minus(1, YEARS);
    System.out.println("Date before 1 year : " + previousYear);

    LocalDate nextYear = today.plus(1, YEARS);
    System.out.println("Date after 1 year : " + nextYear);

    LocalDate firstDayOfMonth = LocalDate.now().with(TemporalAdjusters.firstDayOfMonth());
    System.out.println("firstDayOfMonth = " + firstDayOfMonth);
}

From source file:com.ikanow.aleph2.data_model.utils.TimeUtils.java

/** Attempts to parse a (typically recurring) time  
 * @param human_readable_duration - Uses some simple regexes (1h,d, 1month etc), and Natty (try examples http://natty.joestelmach.com/try.jsp#)
 * @param base_date - for relative date, locks the date to this origin (mainly for testing in this case?)
 * @return the machine readable duration, or an error
 *//* w w w. j  ava 2s.  com*/
public static Validation<String, Duration> getDuration(final String human_readable_duration,
        Optional<Date> base_date) {
    // There's a few different cases:
    // - the validation from getTimePeriod
    // - a slightly more complicated version <N><p> where <p> == period from the above
    // - use Natty for more complex expressions

    final Validation<String, ChronoUnit> first_attempt = getTimePeriod(human_readable_duration);
    if (first_attempt.isSuccess()) {
        return Validation
                .success(Duration.of(first_attempt.success().getDuration().getSeconds(), ChronoUnit.SECONDS));
    } else { // Slightly more complex version
        final Matcher m = date_parser.matcher(human_readable_duration);
        if (m.matches()) {
            final Validation<String, Duration> candidate_ret = getTimePeriod(m.group(2)).map(cu -> {
                final LocalDateTime now = LocalDateTime.now();
                return Duration.between(now, now.plus(Integer.parseInt(m.group(1)), cu));
            });

            if (candidate_ret.isSuccess())
                return candidate_ret;
        }
    }
    // If we're here then try Natty
    final Date now = base_date.orElse(new Date());
    return getSchedule(human_readable_duration, Optional.of(now)).map(d -> {
        final long duration = d.getTime() - now.getTime();
        return Duration.of(duration, ChronoUnit.MILLIS);
    });
}

From source file:net.havox.times.model.times.impl.WorkUnitImpl.java

@Override
public void setWorkUnitDuration(LocalDateTime start, Duration duration) {
    if ((start == null) || (duration == null)) {
        String message = "Neigther the parameter 'start'=" + start + " nor the parameter 'duration'=" + duration
                + "is allowed to be NULL.";
        throw new GuruMeditationWarning(ILLEGAL_ARGUMENT, message);
    }/*from  w w  w.java 2s.  co  m*/

    this.workUnitStart = start;
    this.workUnitEnd = start.plus(duration.toNanos(), ChronoUnit.NANOS);
}

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  av  a 2s.c om

    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.hadoop.yarn.server.resourcemanager.security.JWTSecurityHandler.java

@InterfaceAudience.Private
@VisibleForTesting//from   www  . j  a  va  2s.  c om
protected void prepareJWTGenerationParameters(JWTMaterialParameter parameter) {
    parameter.setAudiences(jwtAudience);
    LocalDateTime now = getNow();
    LocalDateTime expirationTime = now.plus(validityPeriod.getFirst(), validityPeriod.getSecond());
    parameter.setExpirationDate(expirationTime);
    parameter.setValidNotBefore(now);
    // JWT for applications will not be automatically renewed.
    // JWTSecurityHandler will renew them
    parameter.setRenewable(false);
    parameter.setExpLeeway(leeway.intValue());
}

From source file:org.apache.hadoop.yarn.server.resourcemanager.security.TestHopsworksRMAppSecurityActions.java

@Test
public void testGenerateJWT() throws Exception {
    ApplicationId appId = ApplicationId.newInstance(System.currentTimeMillis(), 1);
    JWTSecurityHandler.JWTMaterialParameter jwtParam = createJWTParameter(appId);

    RMAppSecurityActions actor = RMAppSecurityActionsFactory.getInstance().getActor(conf);
    String jwt = actor.generateJWT(jwtParam);
    Assert.assertNotNull(jwt);//from   ww w  .  ja v a2s  .c  o  m
    String[] tokenizedSubject = JWT_SUBJECT.split("__");
    JWT decoded = JWTParser.parse(jwt);
    String subject = decoded.getJWTClaimsSet().getSubject();
    Assert.assertEquals(tokenizedSubject[1], subject);

    // Test generate and fall-back to application submitter
    appId = ApplicationId.newInstance(System.currentTimeMillis(), 2);
    jwtParam = new JWTSecurityHandler.JWTMaterialParameter(appId, "dorothy");
    jwtParam.setRenewable(false);
    LocalDateTime now = DateUtils.getNow();
    LocalDateTime expiresAt = now.plus(10L, ChronoUnit.MINUTES);
    jwtParam.setExpirationDate(expiresAt);
    jwtParam.setValidNotBefore(now);
    jwtParam.setAudiences(new String[] { "job" });
    jwt = actor.generateJWT(jwtParam);
    decoded = JWTParser.parse(jwt);
    subject = decoded.getJWTClaimsSet().getSubject();
    Assert.assertEquals("dorothy", subject);

    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss");
    LocalDateTime nbfFromToken = DateUtils.date2LocalDateTime(decoded.getJWTClaimsSet().getNotBeforeTime());
    Assert.assertEquals(now.format(formatter), nbfFromToken.format(formatter));
    LocalDateTime expirationFromToken = DateUtils
            .date2LocalDateTime(decoded.getJWTClaimsSet().getExpirationTime());
    Assert.assertEquals(expiresAt.format(formatter), expirationFromToken.format(formatter));
}

From source file:org.apache.hadoop.yarn.server.resourcemanager.security.TestHopsworksRMAppSecurityActions.java

private JWTSecurityHandler.JWTMaterialParameter createJWTParameter(ApplicationId appId, long amountToAdd,
        TemporalUnit unit) {//from   w  ww  .  j a  va  2 s .  com
    JWTSecurityHandler.JWTMaterialParameter jwtParam = new JWTSecurityHandler.JWTMaterialParameter(appId,
            JWT_SUBJECT);
    jwtParam.setRenewable(false);
    LocalDateTime now = DateUtils.getNow();
    LocalDateTime expiresAt = now.plus(amountToAdd, unit);
    jwtParam.setExpirationDate(expiresAt);
    jwtParam.setValidNotBefore(now);
    jwtParam.setAudiences(new String[] { "job" });
    return jwtParam;
}

From source file:org.apache.hadoop.yarn.server.resourcemanager.security.TestHopsworksRMAppSecurityActions.java

@Test
public void testConfUpdate() throws Exception {
    LocalDateTime now = LocalDateTime.now();
    Date nbf = DateUtils.localDateTime2Date(now);
    LocalDateTime expiration = now.plus(10, ChronoUnit.MINUTES);
    Date expirationDate = DateUtils.localDateTime2Date(expiration);
    JWTClaimsSet masterClaims = new JWTClaimsSet();
    masterClaims.setSubject("master_token");
    masterClaims.setExpirationTime(expirationDate);
    masterClaims.setNotBeforeTime(nbf);//  w w  w.j ava  2 s  .  co  m
    String newMasterToken = jwtIssuer.generate(masterClaims);
    Assert.assertNotNull(newMasterToken);

    String[] newRenewalTokens = new String[5];
    JWTClaimsSet renewClaims = new JWTClaimsSet();
    renewClaims.setSubject("renew_token");
    renewClaims.setExpirationTime(expirationDate);
    renewClaims.setNotBeforeTime(nbf);
    for (int i = 0; i < newRenewalTokens.length; i++) {
        String renewToken = jwtIssuer.generate(renewClaims);
        Assert.assertNotNull(renewToken);
        newRenewalTokens[i] = renewToken;
    }
    RMAppSecurityActions actor = new TestingHopsworksActions(newMasterToken, expirationDate, newRenewalTokens);
    ((Configurable) actor).setConf(conf);
    actor.init();
    TimeUnit.MILLISECONDS.sleep(500);

    // Renewal must have happened, check new values in ssl-server
    Configuration sslConf = new Configuration();
    sslConf.addResource(conf.get(SSLFactory.SSL_SERVER_CONF_KEY));
    String newMasterTokenConf = sslConf.get(YarnConfiguration.RM_JWT_MASTER_TOKEN, "");
    Assert.assertEquals(newMasterToken, newMasterTokenConf);
    for (int i = 0; i < newRenewalTokens.length; i++) {
        String confKey = String.format(YarnConfiguration.RM_JWT_RENEW_TOKEN_PATTERN, i);
        String newRenewalToken = sslConf.get(confKey, "");
        Assert.assertEquals(newRenewalTokens[i], newRenewalToken);
    }

    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss");
    Assert.assertEquals(expiration.format(formatter),
            ((HopsworksRMAppSecurityActions) actor).getMasterTokenExpiration().format(formatter));
    actor.destroy();
}