Example usage for org.joda.time Days getDays

List of usage examples for org.joda.time Days getDays

Introduction

In this page you can find the example usage for org.joda.time Days getDays.

Prototype

public int getDays() 

Source Link

Document

Gets the number of days that this period represents.

Usage

From source file:org.extensiblecatalog.ncip.v2.koha.KohaLookupUserService.java

License:Open Source License

private void updateResponseData(ILSDIvOneOneLookupUserInitiationData initData,
        ILSDIvOneOneLookupUserResponseData responseData, JSONObject kohaUser, KohaRemoteServiceManager svcMgr)
        throws ParseException, KohaException {

    ResponseHeader responseHeader = KohaUtil.reverseInitiationHeader(initData);

    if (responseHeader != null)
        responseData.setResponseHeader(responseHeader);

    UserId userId = KohaUtil.createUserId(initData.getUserId().getUserIdentifierValue(),
            LocalConfig.getDefaultAgency());
    responseData.setUserId(userId);/*from   w  w w .  ja va 2  s .c o m*/

    UserOptionalFields userOptionalFields = new UserOptionalFields();

    if (LocalConfig.useRestApiInsteadOfSvc()) {

        if (initData.getNameInformationDesired()) {
            String firstname = (String) kohaUser.get("firstname");
            String surname = (String) kohaUser.get("surname");
            String title = (String) kohaUser.get("title");
            String othernames = (String) kohaUser.get("othernames");

            StructuredPersonalUserName structuredPersonalUserName = new StructuredPersonalUserName();
            structuredPersonalUserName.setGivenName(firstname);
            structuredPersonalUserName.setPrefix(title);
            structuredPersonalUserName.setSurname(surname);
            structuredPersonalUserName.setSuffix(othernames);

            PersonalNameInformation personalNameInformation = new PersonalNameInformation();
            personalNameInformation.setStructuredPersonalUserName(structuredPersonalUserName);

            NameInformation nameInformation = new NameInformation();
            nameInformation.setPersonalNameInformation(personalNameInformation);
            userOptionalFields.setNameInformation(nameInformation);
        }

        if (initData.getUserAddressInformationDesired())
            userOptionalFields.setUserAddressInformations(KohaUtil.parseUserAddressInformations(kohaUser));

        if (initData.getUserPrivilegeDesired()) {

            String branchcode = (String) kohaUser.get("branchcode");
            String agencyUserPrivilegeType = (String) kohaUser.get("categorycode");

            if (branchcode != null && agencyUserPrivilegeType != null) {

                List<UserPrivilege> userPrivileges = new ArrayList<UserPrivilege>();
                UserPrivilege userPrivilege = new UserPrivilege();

                userPrivilege.setAgencyId(new AgencyId(branchcode));

                userPrivilege.setAgencyUserPrivilegeType(new AgencyUserPrivilegeType(
                        "http://www.niso.org/ncip/v1_0/imp1/schemes/agencyuserprivilegetype/agencyuserprivilegetype.scm",
                        agencyUserPrivilegeType));

                userPrivilege.setValidFromDate(
                        KohaUtil.parseGregorianCalendarFromKohaDate((String) kohaUser.get("dateenrolled")));
                userPrivilege.setValidToDate(
                        KohaUtil.parseGregorianCalendarFromKohaDate((String) kohaUser.get("dateexpiry")));

                userPrivileges.add(userPrivilege);
                userOptionalFields.setUserPrivileges(userPrivileges);
            }
        }

        if (initData.getDateOfBirthDesired()) {
            String dateOfBirth = (String) kohaUser.get("dateofbirth");
            userOptionalFields.setDateOfBirth(KohaUtil.parseGregorianCalendarFromKohaDate(dateOfBirth));
        }

        if (initData.getLoanedItemsDesired()) {
            JSONArray checkouts = (JSONArray) kohaUser.get("checkouts");

            if (checkouts != null && checkouts.size() != 0) {
                List<LoanedItem> loanedItems = new ArrayList<LoanedItem>();
                for (int i = 0; i < checkouts.size(); ++i) {
                    JSONObject checkout = (JSONObject) checkouts.get(i);
                    loanedItems.add(KohaUtil.parseLoanedItem(checkout));
                }
                responseData.setLoanedItems(loanedItems);
            }

        }

        if (initData.getRequestedItemsDesired()) {
            JSONArray holds = (JSONArray) kohaUser.get("holds");

            if (holds != null && holds.size() != 0) {
                List<RequestedItem> requestedItems = new ArrayList<RequestedItem>();
                for (int i = 0; i < holds.size(); ++i) {
                    JSONObject hold = (JSONObject) holds.get(i);
                    RequestedItem requestedItem = KohaUtil.parseRequestedItem(hold);
                    if (requestedItem != null)
                        requestedItems.add(requestedItem);
                }
                responseData.setRequestedItems(requestedItems);
            }
        }

        if (initData.getBlockOrTrapDesired()) {

            List<BlockOrTrap> blocks = new ArrayList<BlockOrTrap>(4);

            // Parse expiration
            GregorianCalendar expiryDate = KohaUtil
                    .parseGregorianCalendarFromKohaDate((String) kohaUser.get("dateexpiry"));

            GregorianCalendar warningForExpiryDateGregCal = ((GregorianCalendar) expiryDate.clone());
            warningForExpiryDateGregCal.add(GregorianCalendar.DAY_OF_YEAR, -14);

            Date now = new Date();
            if (now.after(expiryDate.getTime())) {

                BlockOrTrap expired = KohaUtil.createBlockOrTrap("Expired");

                blocks.add(expired);

            } else if (now.after(warningForExpiryDateGregCal.getTime())) {

                Days days = Days.daysBetween(new DateTime(now), new DateTime(expiryDate));

                BlockOrTrap expiresSoon = KohaUtil
                        .createBlockOrTrap("Expires in " + (days.getDays() + 1) + " days");

                blocks.add(expiresSoon);
            }

            // Parse debarred status
            String debarredStatus = (String) kohaUser.get("debarred");

            if (debarredStatus != null && !debarredStatus.isEmpty()) {

                String debarredComment = (String) kohaUser.get("debarredcomment");

                BlockOrTrap debarred = KohaUtil.createBlockOrTrap(
                        "Debarred" + (debarredComment != null ? ": " + debarredComment : ""));

                blocks.add(debarred);
            }

            if (blocks.size() > 0)
                userOptionalFields.setBlockOrTraps(blocks);

        }

        if (initData.getUserFiscalAccountDesired()) {

            JSONArray accountLines = (JSONArray) kohaUser.get("accountLines");

            if (accountLines != null && accountLines.size() != 0) {
                List<UserFiscalAccount> userFiscalAccounts = new ArrayList<UserFiscalAccount>(1);
                UserFiscalAccount userFiscalAccount = new UserFiscalAccount();
                List<AccountDetails> accountDetails = new ArrayList<AccountDetails>();

                for (int i = 0; i < accountLines.size(); ++i) {
                    JSONObject accountLine = (JSONObject) accountLines.get(i);
                    accountDetails.add(KohaUtil.parseAccountDetails(accountLine));
                }

                BigDecimal amount = null; // Sum all transactions ..
                for (AccountDetails details : accountDetails) {
                    if (amount == null)
                        amount = details.getFiscalTransactionInformation().getAmount().getMonetaryValue();
                    else
                        amount = amount
                                .add(details.getFiscalTransactionInformation().getAmount().getMonetaryValue());
                }
                userFiscalAccount.setAccountBalance(KohaUtil.createAccountBalance(amount));

                userFiscalAccount.setAccountDetails(accountDetails);
                userFiscalAccounts.add(userFiscalAccount); // Suppose user has
                // only one account
                // ..
                responseData.setUserFiscalAccounts(userFiscalAccounts);
            }
        }

        if (initData.getHistoryDesired() != null) {
            LoanedItemsHistory loanedItemsHistory = KohaUtil.parseLoanedItemsHistory(kohaUser, initData);
            responseData.setLoanedItemsHistory(loanedItemsHistory);
        }

    } else {
        JSONObject userInfo = (JSONObject) kohaUser.get("userInfo");
        if (userInfo != null) {
            if (initData.getNameInformationDesired()) {
                String firstname = (String) userInfo.get("firstname");
                String surname = (String) userInfo.get("surname");
                String title = (String) userInfo.get("title");
                String othernames = (String) userInfo.get("othernames");

                StructuredPersonalUserName structuredPersonalUserName = new StructuredPersonalUserName();
                structuredPersonalUserName.setGivenName(firstname);
                structuredPersonalUserName.setPrefix(title);
                structuredPersonalUserName.setSurname(surname);
                structuredPersonalUserName.setSuffix(othernames);

                PersonalNameInformation personalNameInformation = new PersonalNameInformation();
                personalNameInformation.setStructuredPersonalUserName(structuredPersonalUserName);

                NameInformation nameInformation = new NameInformation();
                nameInformation.setPersonalNameInformation(personalNameInformation);
                userOptionalFields.setNameInformation(nameInformation);
            }

            if (initData.getUserAddressInformationDesired())
                userOptionalFields.setUserAddressInformations(KohaUtil.parseUserAddressInformations(userInfo));

            if (initData.getUserPrivilegeDesired()) {

                String branchcode = (String) userInfo.get("branchcode");
                String agencyUserPrivilegeType = (String) userInfo.get("categorycode");

                if (branchcode != null && agencyUserPrivilegeType != null) {

                    List<UserPrivilege> userPrivileges = new ArrayList<UserPrivilege>();
                    UserPrivilege userPrivilege = new UserPrivilege();

                    userPrivilege.setAgencyId(new AgencyId(branchcode));

                    userPrivilege.setAgencyUserPrivilegeType(new AgencyUserPrivilegeType(
                            "http://www.niso.org/ncip/v1_0/imp1/schemes/agencyuserprivilegetype/agencyuserprivilegetype.scm",
                            agencyUserPrivilegeType));

                    userPrivilege.setValidFromDate(
                            KohaUtil.parseGregorianCalendarFromKohaDate((String) userInfo.get("dateenrolled")));
                    userPrivilege.setValidToDate(
                            KohaUtil.parseGregorianCalendarFromKohaDate((String) userInfo.get("dateexpiry")));

                    userPrivileges.add(userPrivilege);
                    userOptionalFields.setUserPrivileges(userPrivileges);
                }
            }

            if (initData.getBlockOrTrapDesired()) {
                List<BlockOrTrap> blockOrTraps = KohaUtil.parseBlockOrTraps((JSONArray) userInfo.get("blocks"));
                userOptionalFields.setBlockOrTraps(blockOrTraps);
            }

            if (initData.getDateOfBirthDesired()) {
                String dateOfBirth = (String) userInfo.get("dateofbirth");
                userOptionalFields.setDateOfBirth(KohaUtil.parseGregorianCalendarFromKohaDate(dateOfBirth));
            }
        }

        JSONArray requestedItemsParsed = (JSONArray) kohaUser.get("requestedItems");
        if (requestedItemsParsed != null && requestedItemsParsed.size() != 0) {
            List<RequestedItem> requestedItems = new ArrayList<RequestedItem>();
            for (int i = 0; i < requestedItemsParsed.size(); ++i) {
                JSONObject requestedItemParsed = (JSONObject) requestedItemsParsed.get(i);
                RequestedItem requestedItem = KohaUtil.parseRequestedItem(requestedItemParsed);
                if (requestedItem != null)
                    requestedItems.add(requestedItem);
            }
            responseData.setRequestedItems(requestedItems);
        }

        JSONArray loanedItemsParsed = (JSONArray) kohaUser.get("loanedItems");
        if (loanedItemsParsed != null && loanedItemsParsed.size() != 0) {
            List<LoanedItem> loanedItems = new ArrayList<LoanedItem>();
            for (int i = 0; i < loanedItemsParsed.size(); ++i) {
                JSONObject loanedItem = (JSONObject) loanedItemsParsed.get(i);
                loanedItems.add(KohaUtil.parseLoanedItem(loanedItem));
            }
            responseData.setLoanedItems(loanedItems);
        }

        JSONArray userFiscalAccountParsed = (JSONArray) kohaUser.get("userFiscalAccount");
        if (userFiscalAccountParsed != null && userFiscalAccountParsed.size() != 0) {
            List<UserFiscalAccount> userFiscalAccounts = new ArrayList<UserFiscalAccount>();
            UserFiscalAccount userFiscalAccount = new UserFiscalAccount();
            List<AccountDetails> accountDetails = new ArrayList<AccountDetails>();

            for (int i = 0; i < userFiscalAccountParsed.size(); ++i) {
                JSONObject accountDetail = (JSONObject) userFiscalAccountParsed.get(i);
                accountDetails.add(KohaUtil.parseAccountDetails(accountDetail));
            }

            BigDecimal amount = null; // Sum all transactions ..
            for (AccountDetails details : accountDetails) {
                if (amount == null)
                    amount = details.getFiscalTransactionInformation().getAmount().getMonetaryValue();
                else
                    amount.add(details.getFiscalTransactionInformation().getAmount().getMonetaryValue());
            }
            userFiscalAccount.setAccountBalance(KohaUtil.createAccountBalance(amount));

            userFiscalAccount.setAccountDetails(accountDetails);
            userFiscalAccounts.add(userFiscalAccount); // Suppose user has
            // only one account
            // ..
            responseData.setUserFiscalAccounts(userFiscalAccounts);
        }

    }
    responseData.setUserOptionalFields(userOptionalFields);

}

From source file:org.jasig.cas.adaptors.ldap.LdapPasswordPolicyEnforcer.java

License:Apache License

/**
 * Calculates the number of days left to the expiration date based on the
 * {@code expireDate} parameter./*from  ww  w  .  j  a v a  2  s.  c om*/
 * @param expireDate
 * @param userId
 * @return number of days left to the expiration date, or {@value #PASSWORD_STATUS_PASS}
 */
private long getDaysToExpirationDate(final String userId, final DateTime expireDate)
        throws LdapPasswordPolicyEnforcementException {

    log.debug("Calculating number of days left to the expiration date for user {}", userId);

    final DateTime currentTime = new DateTime(DEFAULT_TIME_ZONE);

    log.info("Current date is {}, expiration date is {}", currentTime.toString(), expireDate.toString());

    final Days d = Days.daysBetween(currentTime, expireDate);
    int daysToExpirationDate = d.getDays();

    if (expireDate.equals(currentTime) || expireDate.isBefore(currentTime)) {
        String msgToLog = "Authentication failed because account password has expired with "
                + daysToExpirationDate + " to expiration date. ";
        msgToLog += "Verify the value of the " + this.dateAttribute
                + " attribute and make sure it's not before the current date, which is "
                + currentTime.toString();

        final LdapPasswordPolicyEnforcementException exc = new LdapPasswordPolicyEnforcementException(msgToLog);

        log.error(msgToLog, exc);

        throw exc;
    }

    /*
     * Warning period begins from X number of ways before the expiration date
     */
    DateTime warnPeriod = new DateTime(DateTime.parse(expireDate.toString()), DEFAULT_TIME_ZONE);

    warnPeriod = warnPeriod.minusDays(this.warningDays);
    log.info("Warning period begins on {}", warnPeriod.toString());

    if (this.warnAll) {
        log.info("Warning all. The password for {} will expire in {} days.", userId, daysToExpirationDate);
    } else if (currentTime.equals(warnPeriod) || currentTime.isAfter(warnPeriod)) {
        log.info("Password will expire in {} days.", daysToExpirationDate);
    } else {
        log.info("Password is not expiring. {} days left to the warning", daysToExpirationDate);
        daysToExpirationDate = PASSWORD_STATUS_PASS;
    }

    return daysToExpirationDate;
}

From source file:org.jasig.cas.adaptors.ldap.lppe.LPPEAuthenticationHandler.java

License:Apache License

/**
 * Calculates the number of days left to the expiration date.
 * @return Number of days left to the expiration date or -1 if the no expiration warning is
 * calculated based on the defined policy.
 *///from w w w .  ja  va  2s  .  c  om
protected int getDaysToExpirationDate(final DateTime expireDate, final PasswordPolicyResult result)
        throws LoginException {
    final DateTimeZone timezone = configuration.getDateConverter().getTimeZone();
    final DateTime currentTime = new DateTime(timezone);
    logger.debug("Current date is {}. Expiration date is {}", currentTime, expireDate);

    final Days d = Days.daysBetween(currentTime, expireDate);
    int daysToExpirationDate = d.getDays();

    logger.debug("[{}] days left to the expiration date.", daysToExpirationDate);
    if (expireDate.equals(currentTime) || expireDate.isBefore(currentTime)) {
        final String msgToLog = String.format("Password expiration date %s is on/before the current time %s.",
                daysToExpirationDate, currentTime);
        logger.debug(msgToLog);
        throw new CredentialExpiredException(msgToLog);
    }

    // Warning period begins from X number of days before the expiration date
    final DateTime warnPeriod = new DateTime(DateTime.parse(expireDate.toString()), timezone)
            .minusDays(result.getPasswordWarningNumberOfDays());
    logger.debug("Warning period begins on [{}]", warnPeriod);

    if (configuration.isAlwaysDisplayPasswordExpirationWarning()) {
        logger.debug("Warning all. The password for [{}] will expire in [{}] day(s).", result.getDn(),
                daysToExpirationDate);
    } else if (currentTime.equals(warnPeriod) || currentTime.isAfter(warnPeriod)) {
        logger.debug("Password will expire in [{}] day(s)", daysToExpirationDate);
    } else {
        logger.debug("Password is not expiring. [{}] day(s) left to the warning.", daysToExpirationDate);
        daysToExpirationDate = -1;
    }

    return daysToExpirationDate;
}

From source file:org.jasig.cas.authentication.support.DefaultAccountStateHandler.java

License:Apache License

/**
 * Handle an account state warning produced by ldaptive account state machinery.
 * <p>//from   www.  j  av a  2 s. c  om
 * Override this method to provide custom warning message handling.
 *
 * @param warning the account state warning messages.
 * @param response Ldaptive authentication response.
 * @param configuration Password policy configuration.
 * @param messages Container for messages produced by account state warning handling.
 */
protected void handleWarning(final AccountState.Warning warning, final AuthenticationResponse response,
        final LdapPasswordPolicyConfiguration configuration, final List<MessageDescriptor> messages) {

    logger.debug("Handling warning {}", warning);
    if (warning == null) {
        logger.debug("Account state warning not defined");
        return;
    }

    final Calendar expDate = warning.getExpiration();
    final Days ttl = Days.daysBetween(Instant.now(), new Instant(expDate));
    logger.debug("Password expires in {} days. Expiration warning threshold is {} days.", ttl.getDays(),
            configuration.getPasswordWarningNumberOfDays());
    if (configuration.isAlwaysDisplayPasswordExpirationWarning()
            || ttl.getDays() < configuration.getPasswordWarningNumberOfDays()) {
        messages.add(new PasswordExpiringWarningMessageDescriptor(
                "Password expires in {0} days. Please change your password at <href=\"{1}\">{1}</a>",
                ttl.getDays(), configuration.getPasswordPolicyUrl()));
    }
    if (warning.getLoginsRemaining() > 0) {
        messages.add(new DefaultMessageDescriptor("password.expiration.loginsRemaining",
                "You have {0} logins remaining before you MUST change your password.",
                warning.getLoginsRemaining()));

    }
}

From source file:org.jbpm.console.ng.ht.backend.server.TaskCalendarServiceImpl.java

License:Apache License

private int getNumberOfDaysWithinDateRange(LocalDate dayFrom, LocalDate dayTo) {
    Days daysBetween = Days.daysBetween(dayFrom, dayTo);
    return daysBetween.getDays() + 1;
}

From source file:org.jhub1.agent.statistics.SmartDateDisplay.java

License:Open Source License

public static String showHowLong(DateTime rDate) {
    StringBuilder sb = new StringBuilder();
    DateTime dt = new DateTime();
    Weeks w = Weeks.weeksBetween(rDate, dt);
    Days d = Days.daysBetween(rDate, dt);
    Hours h = Hours.hoursBetween(rDate, dt);
    Minutes m = Minutes.minutesBetween(rDate, dt);
    Seconds s = Seconds.secondsBetween(rDate, dt);
    if (s.getSeconds() != 0) {
        sb.append(s.getSeconds() % 60).append("s");
    }//from  w  ww.j  a v a2s.  co m
    if (m.getMinutes() != 0) {
        sb.insert(0, (m.getMinutes() % 60) + "m ");
    }
    if (h.getHours() != 0) {
        sb.insert(0, (h.getHours() % 24) + "h ");
    }
    if (d.getDays() != 0) {
        sb.insert(0, (d.getDays() % 7) + "d ");
    }
    if (w.getWeeks() != 0) {
        sb.insert(0, w.getWeeks() + "w ");
    }
    return sb.toString();
}

From source file:org.jobscheduler.dashboard.web.rest.SchedulerHistoryResource.java

License:Apache License

/**
 * Build one serie with number of jobs between startDate and endDate (job in
 * error or not)/*from w  w w. ja  v  a  2s  .c  o m*/
 * 
 * @param startTime
 * @param endTime
 * @param model
 * @return
 */
@RequestMapping("/nbJobsBetween2Date")
@ApiOperation(value = "Build one serie with number of jobs between startDate and endDate")
public @ResponseBody List<SerieDTO> nbJobsBetween2Date(
        @RequestParam(value = "startDate", required = false) @DateTimeFormat(pattern = "yyyy/MM/dd") DateTime startChartDT,
        @RequestParam(value = "endDate", required = false) @DateTimeFormat(pattern = "yyyy/MM/dd") DateTime endChartDT,
        @RequestParam(value = "jobInError", required = false) Boolean jobInError, Model model) {

    if ((startChartDT == null) || (endChartDT == null))
        return null;

    Days days = Days.daysBetween(startChartDT, endChartDT);
    if (days.getDays() < 0)
        return new ArrayList<SerieDTO>(0);
    // Create 1 serie with point per day
    List<SerieDTO> series = new ArrayList<SerieDTO>(1);
    SerieDTO serie = new SerieDTO();
    List<PointDTO> points = new ArrayList<PointDTO>(days.getDays() + 1);
    for (int i = 0; i < days.getDays() + 1; i++) {
        PointDTO point = new PointDTO();
        point.setX(startChartDT.plusDays(i).getMillis());
        Long nbJobs;
        if (jobInError) {
            nbJobs = schedulerHistoryRepository.countByStartTimeBetweenAndError(
                    new Timestamp(startChartDT.plusDays(i).getMillis()),
                    new Timestamp(startChartDT.plusDays(i + 1).getMillis()), new BigDecimal(1));
        } else {
            nbJobs = schedulerHistoryRepository.countByStartTimeBetween(
                    new Timestamp(startChartDT.plusDays(i).getMillis()),
                    new Timestamp(startChartDT.plusDays(i + 1).getMillis()));
        }

        point.setY(nbJobs);
        points.add(point);
    }
    String inError = "";
    if (jobInError)
        inError = "in Error";
    serie.setKey("Number of jobs " + inError + " between " + startChartDT.toString(fmt) + " and "
            + endChartDT.toString(fmt));

    serie.setValues(points);
    series.add(serie);
    return series;

}

From source file:org.jobscheduler.dashboard.web.rest.SchedulerHistoryResource.java

License:Apache License

/**
 * Build series with long running jobs// w w  w.j  ava2  s  .c  o  m
 * 
 * @param startTime
 * @param endTime
 * @param model
 * @return
 */
@RequestMapping("/longRunningJobsBetween2Date")
@ApiOperation(value = "Build series with the most long running jobs between startDate and endDate")
public @ResponseBody List<SerieDTO> longRunningJobsBetween2Date(
        @RequestParam(value = "startDate", required = false) @DateTimeFormat(pattern = "yyyy/MM/dd") DateTime startChartDT,
        @RequestParam(value = "endDate", required = false) @DateTimeFormat(pattern = "yyyy/MM/dd") DateTime endChartDT,
        Model model) {

    if ((startChartDT == null) || (endChartDT == null))
        return null;

    Days days = Days.daysBetween(startChartDT, endChartDT);
    if (days.getDays() < 0)
        return new ArrayList<SerieDTO>(0);
    // 1 serie by day
    List<SerieDTO> series = new ArrayList<SerieDTO>(days.getDays());

    for (int i = 0; i < days.getDays() + 1; i++) {
        // 1 serie contains the most long running jobs
        SerieDTO serie = new SerieDTO();
        serie.setKey("Serie " + i + " in seconds");
        List<PointDTO> points = new ArrayList<PointDTO>();
        serie.setValues(points);
        series.add(serie);
    }

    for (int i = 0; i < days.getDays() + 1; i++) {
        List<SchedulerHistory> schedulerHistories = schedulerHistoryRepository
                .findByStartTimeBetweenAndDuringTime(new Timestamp(startChartDT.getMillis()),
                        new Timestamp(startChartDT.plusDays(i).getMillis()),
                        new PageRequest(0, days.getDays() + 1));
        SerieDTO serie = series.get(days.getDays() - i);
        for (int j = 0; j < schedulerHistories.size(); j++) {
            List<PointDTO> points = (List<PointDTO>) serie.getValues();
            PointDTO point = new PointDTO();
            point.setX(startChartDT.plusDays(j).getMillis());
            if (schedulerHistories.get(j).getEndTime() != null
                    && schedulerHistories.get(j).getStartTime() != null) {
                long elapsedTime = schedulerHistories.get(j).getEndTime().getTime()
                        - schedulerHistories.get(j).getStartTime().getTime();

                point.setY(elapsedTime);
            } else
                point.setY(0L);
            points.add(point);
        }
    }
    return series;

}

From source file:org.kuali.kpme.tklm.utils.TkTestUtils.java

License:Educational Community License

public static Map<DateTime, BigDecimal> getDateToHoursMap(TimeBlock timeBlock, TimeHourDetail timeHourDetail) {
    Map<DateTime, BigDecimal> dateToHoursMap = new HashMap<DateTime, BigDecimal>();
    DateTime beginTime = timeBlock.getBeginDateTime();
    DateTime endTime = timeBlock.getEndDateTime();

    Days d = Days.daysBetween(beginTime, endTime);
    int numberOfDays = d.getDays();
    if (numberOfDays < 1) {
        dateToHoursMap.put(timeBlock.getBeginDateTime(), timeHourDetail.getHours());
        return dateToHoursMap;
    }/*from   www . j ava2s.  c o m*/
    DateTime currentTime = beginTime;
    for (int i = 0; i < numberOfDays; i++) {
        DateTime nextDayAtMidnight = currentTime.plusDays(1);
        nextDayAtMidnight = nextDayAtMidnight.hourOfDay().setCopy(12);
        nextDayAtMidnight = nextDayAtMidnight.minuteOfDay().setCopy(0);
        nextDayAtMidnight = nextDayAtMidnight.secondOfDay().setCopy(0);
        nextDayAtMidnight = nextDayAtMidnight.millisOfSecond().setCopy(0);
        Duration dur = new Duration(currentTime, nextDayAtMidnight);
        long duration = dur.getStandardSeconds();
        BigDecimal hrs = new BigDecimal(duration / 3600, HrConstants.MATH_CONTEXT);
        dateToHoursMap.put(currentTime, hrs);
        currentTime = nextDayAtMidnight;
    }
    Duration dur = new Duration(currentTime, endTime);
    long duration = dur.getStandardSeconds();
    BigDecimal hrs = new BigDecimal(duration / 3600, HrConstants.MATH_CONTEXT);
    dateToHoursMap.put(currentTime, hrs);

    return dateToHoursMap;
}

From source file:org.libreplan.business.planner.chart.ContiguousDaysLine.java

License:Open Source License

public static <T> ContiguousDaysLine<T> create(LocalDate fromInclusive, LocalDate endExclusive) {
    if (fromInclusive.isAfter(endExclusive)) {
        throw new IllegalArgumentException(
                "fromInclusive (" + fromInclusive + ") is after endExclusive (" + endExclusive + ")");
    }//from w w  w.j a  va 2s  . c  om
    Days daysBetween = Days.daysBetween(fromInclusive, endExclusive);
    return new ContiguousDaysLine<T>(fromInclusive, daysBetween.getDays());
}