Example usage for org.joda.time Period getHours

List of usage examples for org.joda.time Period getHours

Introduction

In this page you can find the example usage for org.joda.time Period getHours.

Prototype

public int getHours() 

Source Link

Document

Gets the hours field part of the period.

Usage

From source file:org.kalypso.commons.time.PeriodUtils.java

License:Open Source License

/**
 * @return {@link Integer#MAX_VALUE} if the amount could not be determined.
 *//*from www. jav a 2s . c om*/
public static int findCalendarAmount(final Period period) {
    final int fieldCount = countNonZeroFields(period);
    if (fieldCount > 1)
        throw new IllegalArgumentException(
                "Unable to find calendar amount for periods with more than one field: " + period); //$NON-NLS-1$

    if (period.getDays() != 0)
        return period.getDays();

    if (period.getHours() != 0)
        return period.getHours();

    if (period.getMillis() != 0)
        return period.getMillis();

    if (period.getMinutes() != 0)
        return period.getMinutes();

    if (period.getMonths() != 0)
        return period.getMonths();

    if (period.getSeconds() != 0)
        return period.getSeconds();

    if (period.getWeeks() != 0)
        return period.getWeeks();

    if (period.getYears() != 0)
        return period.getYears();

    return Integer.MAX_VALUE;
}

From source file:org.kalypso.commons.time.PeriodUtils.java

License:Open Source License

public static FIELD findCalendarField(final Period period) {
    final int fieldCount = countNonZeroFields(period);

    if (fieldCount > 1)
        throw new IllegalArgumentException(
                "Unable to find calendar field for periods with more than one field: " + period); //$NON-NLS-1$

    if (period.getDays() != 0)
        return FIELD.DAY_OF_MONTH;

    if (period.getHours() != 0)
        return FIELD.HOUR_OF_DAY;

    if (period.getMillis() != 0)
        return FIELD.MILLISECOND;

    if (period.getMinutes() != 0)
        return FIELD.MINUTE;

    if (period.getMonths() != 0)
        return FIELD.MONTH;

    if (period.getSeconds() != 0)
        return FIELD.SECOND;

    if (period.getWeeks() != 0)
        return FIELD.WEEK_OF_YEAR;

    if (period.getYears() != 0)
        return FIELD.YEAR;

    return null;/*  www.j av a 2s. c o m*/
}

From source file:org.kalypso.ogc.sensor.metadata.MetadataHelper.java

License:Open Source License

public static void setTimestep(final MetadataList mdl, final Period timestep) {
    final int[] values = timestep.getValues();
    int fieldCount = 0;
    for (final int value : values) {
        if (value != 0)
            fieldCount++;//from  w  w  w . j av  a2s .  c  o m
    }

    if (fieldCount > 1)
        throw new IllegalArgumentException(Messages.getString("MetadataHelper_2") + timestep); //$NON-NLS-1$

    int amount = -1;
    int calendarField = -1;

    if (timestep.getDays() != 0) {
        amount = timestep.getDays();
        calendarField = Calendar.DAY_OF_MONTH;
    } else if (timestep.getHours() != 0) {
        amount = timestep.getHours();
        calendarField = Calendar.HOUR_OF_DAY;
    } else if (timestep.getMillis() != 0) {
        amount = timestep.getMillis();
        calendarField = Calendar.MILLISECOND;
    } else if (timestep.getMinutes() != 0) {
        amount = timestep.getMinutes();
        calendarField = Calendar.MINUTE;
    } else if (timestep.getMonths() != 0) {
        amount = timestep.getMonths();
        calendarField = Calendar.MONTH;
    } else if (timestep.getSeconds() != 0) {
        amount = timestep.getSeconds();
        calendarField = Calendar.SECOND;
    } else if (timestep.getWeeks() != 0) {
        amount = timestep.getWeeks();
        calendarField = Calendar.WEEK_OF_YEAR;
    } else if (timestep.getYears() != 0) {
        amount = timestep.getYears();
        calendarField = Calendar.YEAR;
    }

    if (amount == -1)
        throw new IllegalArgumentException(Messages.getString("MetadataHelper_3")); //$NON-NLS-1$

    setTimestep(mdl, calendarField, amount);

    return;
}

From source file:org.kuali.kpme.core.util.TKUtils.java

License:Educational Community License

/**
 * Method to obtain the timezone offset string for the specified date time.
 *
 * Examples:/*from www  . j a  v  a 2  s  .c o  m*/
 *
 * -0500
 * -0800
 *
 * @param date
 * @return
 */
public static String getTimezoneOffset(DateTime date) {
    StringBuilder o = new StringBuilder();

    int offsetms = date.getZone().getOffset(date);
    boolean negative = offsetms < 0;
    if (negative)
        offsetms = offsetms * -1;

    Period period = new Period(offsetms);
    if (negative)
        o.append('-');
    o.append(StringUtils.leftPad(period.getHours() + "", 2, '0'));
    o.append(StringUtils.leftPad(period.getMinutes() + "", 2, '0'));

    return o.toString();
}

From source file:org.kuali.kpme.tklm.time.batch.ClockedInEmployeeJob.java

License:Educational Community License

public void execute(JobExecutionContext context) throws JobExecutionException {
    //Get Configuration Settings
    BigDecimal hourLimit = getHourLimit();
    String jobAction = getJobAction();
    String batchJobPrincipalId = BatchJobUtil.getBatchUserPrincipalId();

    // code to send one email per approver
    // Map<String, Map<String, String>> notificationMap = new HashMap<String, Map<String, String>>();

    DateTime asOfDate = new LocalDate().toDateTimeAtStartOfDay();
    List<CalendarEntry> calendarEntries = HrServiceLocator.getCalendarEntryService()
            .getCurrentCalendarEntriesNeedsScheduled(30, asOfDate);

    for (CalendarEntry calendarEntry : calendarEntries) {
        Calendar calendar = HrServiceLocator.getCalendarService().getCalendar(calendarEntry.getHrCalendarId());
        if (StringUtils.equals(calendar.getCalendarTypes(), "Pay")) {
            DateTime beginDate = calendarEntry.getBeginPeriodFullDateTime();
            DateTime endDate = calendarEntry.getEndPeriodFullDateTime();

            List<TimesheetDocumentHeader> timesheetDocumentHeaders = TkServiceLocator
                    .getTimesheetDocumentHeaderService().getDocumentHeaders(beginDate, endDate);

            for (TimesheetDocumentHeader timesheetDocumentHeader : timesheetDocumentHeaders) {
                String principalId = timesheetDocumentHeader.getPrincipalId();
                List<Assignment> assignments = HrServiceLocator.getAssignmentService()
                        .getAllAssignmentsByCalEntryForTimeCalendar(principalId, calendarEntry);
                for (Assignment assignment : assignments) {
                    String groupKeyCode = assignment.getGroupKeyCode();
                    String jobNumber = String.valueOf(assignment.getJobNumber());
                    String workArea = String.valueOf(assignment.getWorkArea());
                    String task = String.valueOf(assignment.getTask());
                    ClockLog lastClockLog = TkServiceLocator.getClockLogService().getLastClockLog(groupKeyCode,
                            principalId, jobNumber, workArea, task, calendarEntry);
                    if (lastClockLog != null
                            && TkConstants.ON_THE_CLOCK_CODES.contains(lastClockLog.getClockAction())) {
                        DateTime lastClockLogDateTime = lastClockLog.getClockDateTime();
                        DateTime currentDate = new DateTime();

                        Period p = new Period(lastClockLogDateTime, currentDate);
                        BigDecimal hoursBetween = new BigDecimal(p.getHours());
                        BigDecimal dayHours = new BigDecimal(p.getDays() * 24);
                        hoursBetween = hoursBetween.add(dayHours);

                        if (hoursBetween.compareTo(hourLimit) > 0) {
                            if (jobAction.equals("NOTIFY")) {

                                //code to send one notification per employee to all approvers of employee
                                for (Person approver : getApprovers(assignment.getWorkArea())) {
                                    EntityNamePrincipalName employee = KimApiServiceLocator.getIdentityService()
                                            .getDefaultNamesForPrincipalId(principalId);
                                    String approverSubject = "Employee Clocked In Over " + hourLimit.toString()
                                            + " Hours Notification";
                                    StringBuilder approverNotification = new StringBuilder();
                                    approverNotification.append(employee.getPrincipalName() + " (" + principalId
                                            + ") has been clocked in since ");
                                    SimpleDateFormat sdf = new SimpleDateFormat("EEEE, MMMM d yyyy HH:mm a");
                                    String dateTime = sdf.format(
                                            new java.sql.Date(lastClockLog.getClockDateTime().getMillis()));
                                    approverNotification.append(dateTime);
                                    approverNotification.append(
                                            " for work area " + assignment.getWorkAreaObj().getDescription());
                                    HrServiceLocator.getKPMENotificationService().sendNotification(
                                            approverSubject, approverNotification.toString(),
                                            approver.getPrincipalId());
                                }//from  w w w . j av  a2 s .c o m

                                /* Code to send one email per approver - Create notification
                                Map<String, String> hourInfo = new HashMap<String, String>();
                                hourInfo.put(principalId, hoursBetween.toString());
                                for (Person person : getApprovers(lastClockLog.getWorkArea())) {
                                    if (notificationMap.containsKey(person.getPrincipalId())) {
                                notificationMap.get(person.getPrincipalId()).put(principalId, hoursBetween.toString());
                                    } else {
                                notificationMap.put(person.getPrincipalId(), hourInfo);
                                    }
                                } */
                            } else if (jobAction.equals("CLOCK_OUT")) {
                                //Clock User Out
                                ClockLog clockOut = TkServiceLocator.getClockLogService().processClockLog(
                                        principalId, timesheetDocumentHeader.getDocumentId(), currentDate,
                                        assignment, calendarEntry, TKUtils.getIPNumber(),
                                        currentDate.toLocalDate(), "CO", true, batchJobPrincipalId);

                                TkServiceLocator.getClockLogService().saveClockLog(clockOut);

                                // Notify User
                                String employeeSubject = "You have been clocked out of "
                                        + assignment.getAssignmentDescription();
                                StringBuilder employeeNotification = new StringBuilder();
                                employeeNotification.append(
                                        "You have been Clocked out of " + assignment.getAssignmentDescription()
                                                + " on " + clockOut.getClockDateTime());
                                HrServiceLocator.getKPMENotificationService().sendNotification(employeeSubject,
                                        employeeNotification.toString(), principalId);

                                //add Note to time sheet
                                Note.Builder builder = Note.Builder
                                        .create(timesheetDocumentHeader.getDocumentId(), batchJobPrincipalId);
                                builder.setCreateDate(new DateTime());
                                builder.setText("Clock out from " + assignment.getAssignmentDescription()
                                        + " on " + clockOut.getClockDateTime()
                                        + " was initiated by the Clocked In Employee Batch Job");
                                KewApiServiceLocator.getNoteService().createNote(builder.build());
                            }

                        }
                    }
                }
            }
        }
    }

    /* code to send one email per approver
    for (Map.Entry<String, Map<String, String>> approverEntry : notificationMap.entrySet()) {
    String subject = "Users clocked in over " + hourLimit.toString() + " hours";
    StringBuilder notification = new StringBuilder();
    notification.append("The following users have been clocked in for over " + hourLimit.toString() + " hours:");
    notification.append(SystemUtils.LINE_SEPARATOR);
    for (Map.Entry<String, String> employeeEntry : approverEntry.getValue().entrySet()) {
        notification.append(KimApiServiceLocator.getPersonService().getPerson(employeeEntry.getKey()).getPrincipalName());
        notification.append(" (" + employeeEntry.getKey() + ") : " + employeeEntry.getValue() + " hours");
        notification.append(SystemUtils.LINE_SEPARATOR);
    }
    HrServiceLocator.getKPMENotificationService().sendNotification(subject, notification.toString(), approverEntry.getKey());
    }
    */

}

From source file:org.libreplan.importers.MPXJProjectFileConversor.java

License:Open Source License

/**
 * Private Method/*from ww  w .  ja  v a2  s .  c  o m*/
 *
 * Get the number of hours of a ProjectCalendarHours
 *
 * @param projectCalendarDateRanges
 *            ProjectCalendarDateRanges to extract data from.
 * @return Integer  with the total number of hours or null if the projectCalendarHours is null.
 */
private static List<Integer> toHours(ProjectCalendarDateRanges projectCalendarDateRanges) {

    if (projectCalendarDateRanges != null) {

        List<Integer> duration = new ArrayList<Integer>();

        int hours = 0;

        int minutes = 0;

        for (DateRange dateRange : projectCalendarDateRanges) {

            DateTime start = new DateTime(dateRange.getStart());

            DateTime end = new DateTime(dateRange.getEnd());

            Period period = new Period(start, end);

            int days = period.getDays();
            if (period.getDays() != 0) {

                hours += 24 * days;

            }
            hours += period.getHours();

            minutes += period.getMinutes();
        }

        duration.add(hours);

        duration.add(minutes);

        return duration;

    } else {
        return null;
    }
}

From source file:org.libreplan.importers.MPXJProjectFileConverter.java

License:Open Source License

/**
 * Get the number of hours of a ProjectCalendarHours.
 *
 * @param projectCalendarDateRanges/*from   w  w w  .  j  av a 2 s  .  com*/
 *            ProjectCalendarDateRanges to extract data from.
 * @return Integer  with the total number of hours or null if the projectCalendarHours is null.
 */
private static List<Integer> toHours(ProjectCalendarDateRanges projectCalendarDateRanges) {

    if (projectCalendarDateRanges != null) {

        List<Integer> duration = new ArrayList<>();

        int hours = 0;

        int minutes = 0;

        for (DateRange dateRange : projectCalendarDateRanges) {

            DateTime start = new DateTime(dateRange.getStart());

            DateTime end = new DateTime(dateRange.getEnd());

            Period period = new Period(start, end);

            int days = period.getDays();

            if (period.getDays() != 0) {
                hours += 24 * days;
            }

            hours += period.getHours();

            minutes += period.getMinutes();
        }

        duration.add(hours);

        duration.add(minutes);

        return duration;

    } else {
        return null;
    }
}

From source file:org.openmrs.module.chaiui.ChaiUiUtils.java

License:Open Source License

/**
 * Formats a duration//ww w  .  ja va 2  s .  c  om
 * @param time the time in milliseconds
 * @return the formatted duration
 */
public String formatDuration(long time) {
    Period period = new Period(time);
    return String.format(DURATION_FORMAT, period.getHours(), period.getMinutes(), period.getSeconds());
}

From source file:org.projectforge.plugins.teamcal.event.TeamCalEventProvider.java

License:Open Source License

/**
 * @see org.projectforge.web.calendar.MyFullCalendarEventsProvider#buildEvents(org.joda.time.DateTime, org.joda.time.DateTime)
 */// w w w  . j  a  v a 2  s.  c o m
@Override
protected void buildEvents(final DateTime start, final DateTime end) {
    final TemplateEntry activeTemplateEntry = filter.getActiveTemplateEntry();
    if (activeTemplateEntry == null) {
        // Nothing to build.
        return;
    }
    final Set<Integer> visibleCalendars = activeTemplateEntry.getVisibleCalendarIds();
    if (CollectionUtils.isEmpty(visibleCalendars) == true) {
        // Nothing to build.
        return;
    }
    final TeamEventFilter eventFilter = new TeamEventFilter();
    eventFilter.setTeamCals(visibleCalendars);
    eventFilter.setStartDate(start.toDate());
    eventFilter.setEndDate(end.toDate());
    eventFilter.setUser(PFUserContext.getUser());
    final List<TeamEvent> teamEvents = teamEventDao.getEventList(eventFilter);

    boolean longFormat = false;
    days = Days.daysBetween(start, end).getDays();
    if (days < 10) {
        // Week or day view:
        longFormat = true;
    }

    final TeamCalRight right = new TeamCalRight();
    final PFUserDO user = PFUserContext.getUser();
    final TimeZone timeZone = PFUserContext.getTimeZone();
    if (CollectionUtils.isNotEmpty(teamEvents) == true) {
        for (final TeamEvent teamEvent : teamEvents) {
            final DateTime startDate = new DateTime(teamEvent.getStartDate(), PFUserContext.getDateTimeZone());
            final DateTime endDate = new DateTime(teamEvent.getEndDate(), PFUserContext.getDateTimeZone());
            final TeamEventDO eventDO;
            final TeamCalEventId id = new TeamCalEventId(teamEvent, timeZone);
            if (teamEvent instanceof TeamEventDO) {
                eventDO = (TeamEventDO) teamEvent;
            } else {
                eventDO = ((TeamRecurrenceEvent) teamEvent).getMaster();
            }
            teamEventMap.put(id.toString(), teamEvent);
            final MyEvent event = new MyEvent();
            event.setClassName(
                    EVENT_CLASS_NAME + " " + EventDroppedCallbackScriptGenerator.NO_CONTEXTMENU_INDICATOR);
            event.setId("" + id);
            event.setColor(activeTemplateEntry.getColorCode(eventDO.getCalendarId()));

            if (eventRight.hasUpdateAccess(PFUserContext.getUser(), eventDO, null)) {
                event.setEditable(true);
            } else {
                event.setEditable(false);
            }

            if (teamEvent.isAllDay() == true) {
                event.setAllDay(true);
            }

            event.setStart(startDate);
            event.setEnd(endDate);

            event.setTooltip(eventDO.getCalendar().getTitle(),
                    new String[][] { { eventDO.getSubject() },
                            { eventDO.getLocation(), getString("timesheet.location") },
                            { eventDO.getNote(), getString("plugins.teamcal.event.note") } });
            final String title;
            String durationString = "";
            if (longFormat == true) {
                // String day = duration.getDays() + "";
                final Period period = new Period(startDate, endDate);
                int hourInt = period.getHours();
                if (period.getDays() > 0) {
                    hourInt += period.getDays() * 24;
                }
                final String hour = hourInt < 10 ? "0" + hourInt : "" + hourInt;

                final int minuteInt = period.getMinutes();
                final String minute = minuteInt < 10 ? "0" + minuteInt : "" + minuteInt;

                if (event.isAllDay() == false) {
                    durationString = "\n" + getString("plugins.teamcal.event.duration") + ": " + hour + ":"
                            + minute;
                }
                final StringBuffer buf = new StringBuffer();
                buf.append(teamEvent.getSubject());
                if (StringUtils.isNotBlank(teamEvent.getNote()) == true) {
                    buf.append("\n").append(getString("plugins.teamcal.event.note")).append(": ")
                            .append(teamEvent.getNote());
                }
                buf.append(durationString);
                title = buf.toString();
            } else {
                title = teamEvent.getSubject();
            }
            if (right.hasMinimalAccess(eventDO.getCalendar(), user.getId()) == true) {
                // for minimal access
                event.setTitle("");
                event.setEditable(false);
            } else {
                event.setTitle(title);
            }
            events.put(id + "", event);
        }
    }
}

From source file:org.projectforge.web.calendar.MyEvent.java

License:Open Source License

public String getDuration() {
    if (duration != null) {
        return duration;
    }//from   w ww.j  a  v a  2  s .c  o  m
    final Period period = new Period(this.getStart(), this.getEnd());
    int days = period.getDays();
    if (isAllDay() == true) {
        ++days;
    }
    final int hours = period.getHours();
    final int minutes = period.getMinutes();
    final StringBuffer buf = new StringBuffer();
    if (days > 0) { // days
        buf.append(days).append(PFUserContext.getLocalizedString("calendar.unit.day")).append(" ");
    }
    if (isAllDay() == false) {
        buf.append(hours).append(":"); // hours
        if (minutes < 10) {
            buf.append("0");
        }
        buf.append(minutes);
    }
    duration = buf.toString();
    return duration;
}