Example usage for org.joda.time DateTime withHourOfDay

List of usage examples for org.joda.time DateTime withHourOfDay

Introduction

In this page you can find the example usage for org.joda.time DateTime withHourOfDay.

Prototype

public DateTime withHourOfDay(int hour) 

Source Link

Document

Returns a copy of this datetime with the hour of day field updated.

Usage

From source file:azkaban.app.jmx.JobScheduler.java

License:Apache License

public String scheduleWorkflow(String jobName, boolean ignoreDeps, int hour, int minutes, int seconds,
        String scheduledDate, boolean isRecurring, int period, String periodUnits) {
    String errorMsg = null;//from  w w  w.j a  va2s.c  om
    if (jobName == null || jobName.trim().length() == 0) {
        errorMsg = "You must select at least one job to run.";
        logger.error(errorMsg);
        return errorMsg;
    }
    JobDescriptor descriptor = jobManager.getJobDescriptor(jobName);
    if (descriptor == null) {
        errorMsg = "Job: '" + jobName + "' doesn't exist.";
        logger.error(errorMsg);
        return errorMsg;
    }

    DateTime day = null;
    DateTime time = null;
    try {
        if (scheduledDate == null || scheduledDate.trim().length() == 0) {
            day = new LocalDateTime().toDateTime();
            time = day.withHourOfDay(hour).withMinuteOfHour(minutes).withSecondOfMinute(seconds);
            if (day.isAfter(time)) {
                time = time.plusDays(1);
            }
        } else {
            try {
                day = DateTimeFormat.forPattern("MM-dd-yyyy").parseDateTime(scheduledDate);
            } catch (IllegalArgumentException e) {
                logger.error(e);
                return "Invalid date: '" + scheduledDate + "', \"MM-dd-yyyy\" format is expected.";
            }
            time = day.withHourOfDay(hour).withMinuteOfHour(minutes).withSecondOfMinute(seconds);
        }
    } catch (IllegalFieldValueException e) {
        logger.error(e);
        return "Invalid schedule time (see logs): " + e.getMessage();

    }
    ReadablePeriod thePeriod = null;
    if (isRecurring) {
        if ("d".equals(periodUnits)) {
            thePeriod = Days.days(period);
        } else if ("h".equals(periodUnits)) {
            thePeriod = Hours.hours(period);
        } else if ("m".equals(periodUnits)) {
            thePeriod = Minutes.minutes(period);
        } else if ("s".equals(periodUnits)) {
            thePeriod = Seconds.seconds(period);
        } else {
            errorMsg = "Unknown period unit: " + periodUnits;
            logger.error(errorMsg);
            return errorMsg;
        }
    }
    try {
        if (thePeriod == null) {
            scheduler.schedule(jobName, time, ignoreDeps);
        } else {
            scheduler.schedule(jobName, time, thePeriod, ignoreDeps);
        }
        return "Schedule Successful!";
    } catch (Exception e) {
        logger.error(e);
        return "Schedule Failed (see logs): " + e.getMessage();
    }
}

From source file:azkaban.reportal.util.Reportal.java

License:Apache License

public void updateSchedules(Reportal report, ScheduleManager scheduleManager, User user, Flow flow)
        throws ScheduleManagerException {
    // Clear previous schedules
    removeSchedules(scheduleManager);/*  w  ww. j  a v  a 2  s .c om*/
    // Add new schedule
    if (schedule) {
        int hour = (Integer.parseInt(scheduleHour) % 12) + (scheduleAmPm.equalsIgnoreCase("pm") ? 12 : 0);
        int minute = Integer.parseInt(scheduleMinute) % 60;
        DateTimeZone timeZone = scheduleTimeZone.equalsIgnoreCase("UTC") ? DateTimeZone.UTC
                : DateTimeZone.getDefault();
        DateTime firstSchedTime = DateTimeFormat.forPattern("MM/dd/yyyy").withZone(timeZone)
                .parseDateTime(scheduleDate);
        firstSchedTime = firstSchedTime.withHourOfDay(hour).withMinuteOfHour(minute).withSecondOfMinute(0)
                .withMillisOfSecond(0);

        ReadablePeriod period = null;
        if (scheduleRepeat) {
            int intervalQuantity = Integer.parseInt(scheduleIntervalQuantity);

            if (scheduleInterval.equals("y")) {
                period = Years.years(intervalQuantity);
            } else if (scheduleInterval.equals("m")) {
                period = Months.months(intervalQuantity);
            } else if (scheduleInterval.equals("w")) {
                period = Weeks.weeks(intervalQuantity);
            } else if (scheduleInterval.equals("d")) {
                period = Days.days(intervalQuantity);
            } else if (scheduleInterval.equals("h")) {
                period = Hours.hours(intervalQuantity);
            } else if (scheduleInterval.equals("M")) {
                period = Minutes.minutes(intervalQuantity);
            }
        }

        ExecutionOptions options = new ExecutionOptions();
        options.getFlowParameters().put("reportal.execution.user", user.getUserId());
        options.getFlowParameters().put("reportal.title", report.title);
        options.getFlowParameters().put("reportal.render.results.as.html",
                report.renderResultsAsHtml ? "true" : "false");
        options.setMailCreator(ReportalMailCreator.REPORTAL_MAIL_CREATOR);

        scheduleManager.scheduleFlow(-1, project.getId(), project.getName(), flow.getId(), "ready",
                firstSchedTime.getMillis(), firstSchedTime.getZone(), period, DateTime.now().getMillis(),
                firstSchedTime.getMillis(), firstSchedTime.getMillis(), user.getUserId(), options, null);
    }
}

From source file:azkaban.web.pages.IndexServlet.java

License:Apache License

private String scheduleJobs(AzkabanApplication app, HttpServletRequest req, HttpServletResponse resp)
        throws IOException, ServletException {
    String[] jobNames = req.getParameterValues("jobs");
    if (!hasParam(req, "jobs")) {
        addError(req, "You must select at least one job to run.");
        return "";
    }/*from w ww  .j av a2s. c  o  m*/

    if (hasParam(req, "flow_now")) {
        if (jobNames.length > 1) {
            addError(req, "Can only run flow instance on one job.");
            return "";
        }

        String jobName = jobNames[0];
        JobManager jobManager = app.getJobManager();
        JobDescriptor descriptor = jobManager.getJobDescriptor(jobName);
        if (descriptor == null) {
            addError(req, "Can only run flow instance on one job.");
            return "";
        } else {
            return req.getContextPath() + "/flow?job_id=" + jobName;
        }
    } else {
        for (String job : jobNames) {
            if (hasParam(req, "schedule")) {
                int hour = getIntParam(req, "hour");
                int minutes = getIntParam(req, "minutes");
                boolean isPm = getParam(req, "am_pm").equalsIgnoreCase("pm");
                String scheduledDate = req.getParameter("date");
                DateTime day = null;
                if (scheduledDate == null || scheduledDate.trim().length() == 0) {
                    day = new LocalDateTime().toDateTime();
                } else {
                    try {
                        day = DateTimeFormat.forPattern("MM-dd-yyyy").parseDateTime(scheduledDate);
                    } catch (IllegalArgumentException e) {
                        addError(req, "Invalid date: '" + scheduledDate + "'");
                        return "";
                    }
                }

                ReadablePeriod thePeriod = null;
                if (hasParam(req, "is_recurring"))
                    thePeriod = parsePeriod(req);

                if (isPm && hour < 12)
                    hour += 12;
                hour %= 24;

                app.getScheduleManager().schedule(job,
                        day.withHourOfDay(hour).withMinuteOfHour(minutes).withSecondOfMinute(0), thePeriod,
                        false);

                addMessage(req, job + " scheduled.");
            } else if (hasParam(req, "run_now")) {
                boolean ignoreDeps = !hasParam(req, "include_deps");
                try {
                    app.getJobExecutorManager().execute(job, ignoreDeps);
                } catch (JobExecutionException e) {
                    addError(req, e.getMessage());
                    return "";
                }
                addMessage(req, "Running " + job);
            } else {
                addError(req, "Neither run_now nor schedule param is set.");
            }
        }
        return "";
    }

}

From source file:azkaban.webapp.servlet.ScheduleServlet.java

License:Apache License

private DateTime parseDateTime(String scheduleDate, String scheduleTime) {
    // scheduleTime: 12,00,pm,PDT
    String[] parts = scheduleTime.split(",", -1);
    int hour = Integer.parseInt(parts[0]);
    int minutes = Integer.parseInt(parts[1]);
    boolean isPm = parts[2].equalsIgnoreCase("pm");

    DateTimeZone timezone = parts[3].equals("UTC") ? DateTimeZone.UTC : DateTimeZone.getDefault();

    // scheduleDate: 02/10/2013
    DateTime day = null;
    if (scheduleDate == null || scheduleDate.trim().length() == 0) {
        day = new LocalDateTime().toDateTime();
    } else {/*from   w  w w.ja v a 2s  . co m*/
        day = DateTimeFormat.forPattern("MM/dd/yyyy").withZone(timezone).parseDateTime(scheduleDate);
    }

    hour %= 12;

    if (isPm)
        hour += 12;

    DateTime firstSchedTime = day.withHourOfDay(hour).withMinuteOfHour(minutes).withSecondOfMinute(0);

    return firstSchedTime;
}

From source file:com.arpnetworking.kairosdb.aggregators.MovingWindowAggregator.java

License:Apache License

/**
 * For YEARS, MONTHS, WEEKS, DAYS: Computes the timestamp of the first
 * millisecond of the day of the timestamp. For HOURS, Computes the timestamp of
 * the first millisecond of the hour of the timestamp. For MINUTES, Computes the
 * timestamp of the first millisecond of the minute of the timestamp. For
 * SECONDS, Computes the timestamp of the first millisecond of the second of the
 * timestamp. For MILLISECONDS, returns the timestamp
 *
 * @param timestamp Timestamp in milliseconds to use as a basis for range alignment
 * @return timestamp aligned to the configured sampling unit
 *///from  w w  w .j  av a 2  s. c  om
@SuppressWarnings("fallthrough")
@SuppressFBWarnings("SF_SWITCH_FALLTHROUGH")
private long alignRangeBoundary(final long timestamp) {
    DateTime dt = new DateTime(timestamp, _timeZone);
    final TimeUnit tu = m_sampling.getUnit();
    switch (tu) {
    case YEARS:
        dt = dt.withDayOfYear(1).withMillisOfDay(0);
        break;
    case MONTHS:
        dt = dt.withDayOfMonth(1).withMillisOfDay(0);
        break;
    case WEEKS:
        dt = dt.withDayOfWeek(1).withMillisOfDay(0);
        break;
    case DAYS:
        dt = dt.withHourOfDay(0);
    case HOURS:
        dt = dt.withMinuteOfHour(0);
    case MINUTES:
        dt = dt.withSecondOfMinute(0);
    case SECONDS:
    default:
        dt = dt.withMillisOfSecond(0);
        break;
    }
    return dt.getMillis();
}

From source file:com.boha.monitor.utilx.ListUtil.java

public static ResponseDTO getProjectStatusData(EntityManager em, Integer projectID, int days)
        throws DataException {
    long s = System.currentTimeMillis();
    if (days == 0) {
        days = 30;//from  w w  w .  j  av a  2s.  c  om
    }
    ResponseDTO resp = new ResponseDTO();
    try {
        Project p = em.find(Project.class, projectID);
        ProjectDTO project = new ProjectDTO(p);

        DateTime now = new DateTime();
        DateTime then = now.minusDays(days);
        then = then.withHourOfDay(0);
        then = then.withMinuteOfHour(0);
        then = then.withSecondOfMinute(0);

        project.setProjectTaskList(
                ListUtil.getProjectStatus(em, projectID, then.toDate(), now.toDate()).getProjectTaskList());
        project.setPhotoUploadList(
                getPhotosByProject(em, projectID, then.toDate(), now.toDate()).getPhotoUploadList());

        resp.setProjectList(new ArrayList<>());
        resp.getProjectList().add(project);

        long e = System.currentTimeMillis();
        log.log(Level.INFO, "############---------- project data retrieved: {0} seconds",
                Elapsed.getElapsed(s, e));
    } catch (OutOfMemoryError e) {
        log.log(Level.SEVERE, "Failed", e);
        throw new DataException("Failed to get project data: OUT OF MEMORY!\n");
    }

    return resp;
}

From source file:com.github.dbourdette.otto.source.TimeFrame.java

License:Apache License

private DateTime twelveHours(DateTime dateTime) {
    dateTime = dateTime.withMillisOfSecond(0);
    dateTime = dateTime.withSecondOfMinute(0);
    dateTime = dateTime.withMinuteOfHour(0);

    if (dateTime.getHourOfDay() < 12) {
        return dateTime.withHourOfDay(0);
    } else {/*  w  ww .  jav a2s .c om*/
        return dateTime.withHourOfDay(12);
    }
}

From source file:com.github.dbourdette.otto.source.TimeFrame.java

License:Apache License

private DateTime oneDay(DateTime dateTime) {
    dateTime = dateTime.withMillisOfSecond(0);
    dateTime = dateTime.withSecondOfMinute(0);
    dateTime = dateTime.withMinuteOfHour(0);
    return dateTime.withHourOfDay(0);
}

From source file:com.jay.pea.mhealthapp2.model.MedicationManager.java

License:Open Source License

/**
 * Method to build the first dose map which holds the dose due time and the dose taken time.
 * If not taken the dose taken time is recorded as epoch 01-01-70.
 *
 * @param med//from  w w  w  .j  a v  a2s.co m
 * @param context
 * @return
 */
public HashMap<DateTime, DateTime> buildDoseMap1(Medication med, Context context) {
    //get a db object
    dbOpenHelper = new MedDBOpenHelper(context);

    //get final med
    final Medication medication = med;

    //hash map to map doses to taken bool
    HashMap<DateTime, DateTime> doseMap1 = new HashMap();

    //get existing hashMap details if exist
    doseMap1 = dbOpenHelper.getDoseMaps(medication)[0];

    //erase all future dose data, retain past data

    //get inclusive start and end date
    DateTime startDate = new DateTime(med.getMedStart() * 1000l);
    DateTime endDate = new DateTime(med.getMedEnd() * 1000l);

    //set hashStart date as today
    DateTime hashStart = today;

    //if medication is in future set hashStart to future date, if med start is in the past, set hashStart to today (for update to HashMap)
    if (hashStart.isBefore(startDate))
        hashStart = startDate;

    //get alarm times
    DateTime alert1 = new DateTime(med.getAlert1() * 1000l);
    DateTime alert2 = new DateTime(med.getAlert2() * 1000l);
    DateTime alert3 = new DateTime(med.getAlert3() * 1000l);
    DateTime alert4 = new DateTime(med.getAlert4() * 1000l);
    DateTime alert5 = new DateTime(med.getAlert5() * 1000l);
    DateTime alert6 = new DateTime(med.getAlert6() * 1000l);

    DateTime[] dtArray = new DateTime[] { alert1, alert2, alert3, alert4, alert5, alert6 };

    //get the number of days of med prescription
    int days = Days.daysBetween(hashStart.toLocalDate(), endDate.toLocalDate()).getDays() + 1;

    //get Frequency for alerts to ignore non required alerts.
    int freq = med.getFreq();

    //build the hashmap for daily dose due dates and bool for taken, if in the past exclude the reminder
    for (int i = 0; i < days; i++) {
        DateTime thisDay = hashStart.plusDays(i);
        //for the freq setup all alerts
        for (int j = 0; j < freq; j++) {
            DateTime alertTime = thisDay.withHourOfDay(dtArray[j].getHourOfDay())
                    .withMinuteOfHour(dtArray[j].getMinuteOfHour()).withSecondOfMinute(0);
            final DateTime zeroDate = new DateTime(0);
            doseMap1.put(alertTime, zeroDate);
            Log.d(TAG, alertTime + " Time" + dtArray[j].getHourOfDay() + " zero date  " + zeroDate);
        }

    }
    //get existing hashMap details if exist
    HashMap<DateTime, DateTime> tempDoseMap1 = dbOpenHelper.getDoseMaps(medication)[0];

    //add all past dose data,
    if (!tempDoseMap1.isEmpty()) {
        for (DateTime dateTime : tempDoseMap1.keySet()) {

            if (dateTime.isBefore(today)) {
                doseMap1.put(dateTime, tempDoseMap1.get(dateTime));
            }
        }
    }
    Log.d(TAG, doseMap1.size() + " doseMap1 size");
    return doseMap1;
}

From source file:com.jay.pea.mhealthapp2.model.MedicationManager.java

License:Open Source License

/**
 * Method to build the second dose map which holds the dose due time and an int for if an alert
 * has been set./*from  www  .  ja va2 s .c o m*/
 *
 * @param med
 * @param context
 * @return
 */
public HashMap<DateTime, Integer> buildDoseMap2(Medication med, Context context) {

    //get a db object
    dbOpenHelper = new MedDBOpenHelper(context);

    //get final med
    final Medication medication = med;

    //hash map to map doses to taken bool
    HashMap<DateTime, Integer> doseMap2 = new HashMap();

    //set hashStart date as today
    DateTime hashStart = today;

    //get inclusive start and end date
    DateTime startDate = new DateTime(med.getMedStart() * 1000l);
    DateTime endDate = new DateTime(med.getMedEnd() * 1000l);

    //if medication is in future set hashStart to future date, if med start is in the past, set hashStart to today (for update to HashMap)
    if (hashStart.isBefore(startDate))
        hashStart = startDate;

    //get alarm times
    DateTime alert1 = new DateTime(med.getAlert1() * 1000l);
    DateTime alert2 = new DateTime(med.getAlert2() * 1000l);
    DateTime alert3 = new DateTime(med.getAlert3() * 1000l);
    DateTime alert4 = new DateTime(med.getAlert4() * 1000l);
    DateTime alert5 = new DateTime(med.getAlert5() * 1000l);
    DateTime alert6 = new DateTime(med.getAlert6() * 1000l);

    DateTime[] dtArray = new DateTime[] { alert1, alert2, alert3, alert4, alert5, alert6 };
    Log.d(TAG, Arrays.toString(dtArray));

    //get the number of days of med prescription
    int days = Days.daysBetween(hashStart.toLocalDate(), endDate.toLocalDate()).getDays() + 1;

    //get Frequency for alerts to ignore non required alerts.
    int freq = med.getFreq();
    Log.d(TAG, freq + " Days =" + days + " " + med.getMedName());

    //build the hashmap for daily dose due dates and alertsOn Integer, if in the past exclude the reminder
    for (int i = 0; i < days; i++) {
        DateTime thisDay = hashStart.plusDays(i);

        //for the freq setup all alertsOn
        for (int j = 0; j < freq; j++) {
            DateTime alertTime = thisDay.withHourOfDay(dtArray[j].getHourOfDay())
                    .withMinuteOfHour(dtArray[j].getMinuteOfHour()).withSecondOfMinute(0);
            if (alertTime.isAfter(today))
                doseMap2.put(alertTime, medication.getAlertsOn());

        }
        Log.d(TAG, doseMap2.size() + " doseMap2 size");

    }

    //get existing hashMap details if exist
    HashMap<DateTime, Integer> tempDoseMap2 = dbOpenHelper.getDoseMaps(medication)[1];

    //add all past dose data,
    if (!tempDoseMap2.isEmpty()) {
        for (DateTime dateTime : tempDoseMap2.keySet()) {

            if (dateTime.isBefore(today)) {
                doseMap2.put(dateTime, tempDoseMap2.get(dateTime));
            }
        }
    }
    Log.d(TAG, doseMap2.size() + " doseMap2 size");
    return doseMap2;
}