Example usage for org.joda.time DateTime getYear

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

Introduction

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

Prototype

public int getYear() 

Source Link

Document

Get the year field value.

Usage

From source file:org.jtotus.database.LocalJDBC.java

License:Open Source License

public HashMap<String, Double> fetchPeriodAsMap(String tableName, DateTime startDate, DateTime endDate) {

    HashMap<String, Double> retMap = new HashMap<String, Double>();
    BigDecimal retValue = null;//from   w w  w .j  av a  2s. c o  m
    PreparedStatement pstm = null;
    java.sql.Date retDate = null;
    ResultSet results = null;
    Connection connection = null;

    try {
        String query = "SELECT CLOSE, DATE FROM " + this.normTableName(tableName)
                + " WHERE DATE>=? AND DATE<=? ORDER BY DATE ASC";
        // this.createTable(connection, this.normTableName(tableName));

        connection = this.getConnection();
        pstm = connection.prepareStatement(query);

        java.sql.Date startSqlDate = new java.sql.Date(startDate.getMillis());
        pstm.setDate(1, startSqlDate);

        java.sql.Date endSqlDate = new java.sql.Date(endDate.getMillis());
        pstm.setDate(2, endSqlDate);

        System.out.printf("fetchPeriod : %s : %s\n", startSqlDate, endSqlDate);
        DateIterator iter = new DateIterator(startDate, endDate);
        results = pstm.executeQuery();
        DateTime dateCheck;

        while (results.next()) {
            retValue = results.getBigDecimal(1);
            retDate = results.getDate(2);

            if (retValue == null || retDate == null) {
                System.err.println("Database is corrupted!");
                System.exit(-1);
            }

            if (iter.hasNext()) {
                dateCheck = iter.nextInCalendar();

                DateTime compCal = new DateTime(retDate.getTime());

                if (debug) {
                    if (retValue != null) {
                        System.out.printf("Fetched:\'%s\' from \'%s\' : value:%f date:%s\n", "Closing Price",
                                tableName, retValue.doubleValue(), retDate.toString());
                    } else {
                        System.out.printf("Fetched:\'%s\' from \'%s\' : value:%s date:%s\n", "Closing Price",
                                tableName, "is null", retDate.toString());
                    }
                }

                if (compCal.getDayOfMonth() == dateCheck.getDayOfMonth()
                        && compCal.getMonthOfYear() == dateCheck.getMonthOfYear()
                        && compCal.getYear() == dateCheck.getYear()) {
                    retMap.put(formatter.print(compCal), retValue.doubleValue());
                    continue;
                }

                while (((compCal.getDayOfMonth() != dateCheck.getDayOfMonth())
                        || (compCal.getMonthOfYear() != dateCheck.getMonthOfYear())
                        || (compCal.getYear() != dateCheck.getYear())) && dateCheck.isBefore(compCal)) {
                    if (fetcher != null) {
                        BigDecimal failOverValue = getFetcher().fetchData(tableName, dateCheck, "CLOSE");
                        if (failOverValue != null) {
                            retMap.put(formatter.print(dateCheck), retValue.doubleValue());
                        }

                        if (iter.hasNext()) {
                            System.err.printf("Warning : Miss matching dates for: %s - %s\n",
                                    retDate.toString(), dateCheck.toString());
                            dateCheck = iter.nextInCalendar();
                            continue;
                        }
                    } else {
                        System.err.printf("Fatal missing fetcher : Miss matching dates: %s - %s\n",
                                retDate.toString(), dateCheck.toString());
                        return null;
                    }
                }
            }
        }

        while (iter.hasNext()) {
            retValue = getFetcher().fetchData(tableName, iter.nextInCalendar(), "CLOSE");
            if (retValue != null) {
                retMap.put(formatter.print(iter.getCurrentAsCalendar()), retValue.doubleValue());
            }
        }

    } catch (SQLException ex) {
        System.err.printf("LocalJDBC Unable to find date for:'%s' from'%s' Time" + startDate.toDate() + "\n",
                "Cosing Price", tableName);
        //            ex.printStackTrace();
        //            SQLException xp = null;
        //            while((xp = ex.getNextException()) != null) {
        //                xp.printStackTrace();
        //            }

    } finally {
        try {
            if (results != null)
                results.close();
            if (pstm != null)
                pstm.close();
            if (connection != null)
                connection.close();
            //                System.out.printf("Max connect:%d in use:%d\n",mainPool.getMaxConnections(), mainPool.getActiveConnections());
            //                mainPool.dispose();

        } catch (SQLException ex) {
            Logger.getLogger(LocalJDBC.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    return retMap;
}

From source file:org.kemri.wellcome.dhisreport.api.utils.QuarterlyPeriod.java

License:Open Source License

@Override
public String getAsIsoString() {
    DateTime dt = new DateTime(getStart());
    return dt.getYear() + "Q" + ((dt.getMonthOfYear() / 3) + 1);
}

From source file:org.kitesdk.apps.examples.report.ScheduledReportJob.java

License:Apache License

public void run() {

    // TODO: Switch to parameterized views.
    View<ExampleEvent> view = Datasets.load(ScheduledReportApp.EXAMPLE_DS_URI, ExampleEvent.class);

    RefinableView<GenericRecord> target = Datasets.load(ScheduledReportApp.REPORT_DS_URI, GenericRecord.class);

    // Get the view into which this report will be written.
    DateTime dateTime = getNominalTime().toDateTime(DateTimeZone.UTC);

    View<GenericRecord> output = target.with("year", dateTime.getYear())
            .with("month", dateTime.getMonthOfYear()).with("day", dateTime.getDayOfMonth())
            .with("hour", dateTime.getHourOfDay()).with("minute", dateTime.getMinuteOfHour());

    Pipeline pipeline = getPipeline();//w  ww.j  av  a  2 s . com

    PCollection<ExampleEvent> events = pipeline.read(CrunchDatasets.asSource(view));

    PTable<Long, ExampleEvent> eventsByUser = events.by(new GetEventId(), Avros.longs());

    // Count of events by user ID.
    PTable<Long, Long> userEventCounts = eventsByUser.keys().count();

    PCollection<GenericData.Record> report = userEventCounts.parallelDo(new ToUserReport(),
            Avros.generics(SCHEMA));

    pipeline.write(report, CrunchDatasets.asTarget(output));

    pipeline.run();
}

From source file:org.logstash.filters.parser.JodaParser.java

License:Apache License

private Instant parseAndGuessYear(DateTimeFormatter parser, String value) {
    // if we get here, we need to do some special handling at the time each event is handled
    // because things like the current year could be different, etc.
    DateTime dateTime;//from ww  w .j  av  a2s .c o  m
    if (hasZone) {
        dateTime = parser.parseDateTime(value);
    } else {
        dateTime = parser.withZoneUTC().parseLocalDateTime(value).toDateTime(parser.getZone());
    }

    // The time format we have has no year listed, so we'll have to guess the year.
    int month = dateTime.getMonthOfYear();
    DateTime now = clock.read();
    int eventYear;

    if (month == 12 && now.getMonthOfYear() == 1) {
        // Now is January, event is December. Assume it's from last year.
        eventYear = now.getYear() - 1;
    } else if (month == 1 && now.getMonthOfYear() == 12) {
        // Now is December, event is January. Assume it's from next year.
        eventYear = now.getYear() + 1;
    } else {
        // Otherwise, assume it's from this year.
        eventYear = now.getYear();
    }

    return dateTime.withYear(eventYear).toInstant();
}

From source file:org.mayocat.shop.front.context.DateContext.java

License:Mozilla Public License

public DateContext(Date date, Locale locale) {
    DateTime dt = new DateTime(date);

    shortDate = DateTimeFormat.shortDate().withLocale(locale).print(dt);
    longDate = DateTimeFormat.longDate().withLocale(locale).print(dt);

    dayOfMonth = dt.getDayOfMonth();/*from  w  ww. ja  va  2 s .  c om*/
    monthOfYear = dt.getMonthOfYear();
    year = dt.getYear();
    time = dt.toDate().getTime();
    dateTime = dt.toString();
}

From source file:org.medici.bia.controller.admin.EditUserController.java

License:Open Source License

/**
 * /*from ww  w .j  a va2  s .c om*/
 * @param command
 * @param result
 * @return
 */
@RequestMapping(method = RequestMethod.GET)
public ModelAndView setupForm(@ModelAttribute("command") EditUserCommand command) {
    Map<String, Object> model = new HashMap<String, Object>(0);
    List<Month> months = null;
    User user = new User();

    try {
        months = getAdminService().getMonths();
        model.put("months", months);

        List<UserAuthority> authorities = getAdminService().getAuthorities();
        model.put("authorities", authorities);
    } catch (ApplicationThrowable ath) {
        return new ModelAndView("error/ShowDocument", model);
    }

    try {
        if (StringUtils.isNotBlank(command.getAccount())) {
            user = getAdminService().findUser(command.getAccount());

            if (user != null) {
                command.setAccount(user.getAccount());
                command.setOriginalAccount(user.getAccount());
                command.setFirstName(user.getFirstName());
                command.setMiddleName(user.getMiddleName());
                command.setLastName(user.getLastName());
                command.setPassword(user.getPassword());
                Iterator<UserRole> iterator = user.getUserRoles().iterator();
                List<String> userRoles = new ArrayList<String>(0);
                while (iterator.hasNext()) {
                    UserRole userRole = iterator.next();
                    userRoles.add(userRole.getUserAuthority().getAuthority().toString());
                }
                command.setUserRoles(userRoles);
                DateTime expirationUserDate = new DateTime(user.getExpirationDate());
                command.setYearExpirationUser(expirationUserDate.getYear());
                command.setMonthExpirationUser(new Month(expirationUserDate.getMonthOfYear()).getMonthNum());
                command.setDayExpirationUser(expirationUserDate.getDayOfMonth());
                DateTime expirationPasswordDate = new DateTime(user.getExpirationPasswordDate());
                command.setYearExpirationPassword(expirationPasswordDate.getYear());
                command.setMonthExpirationPassword(
                        new Month(expirationPasswordDate.getMonthOfYear()).getMonthNum());
                command.setDayExpirationPassword(expirationPasswordDate.getDayOfMonth());

                command.setActive(user.getActive());
                command.setApproved(user.getApproved());
                command.setLocked(user.getLocked());
            }
        } else {
            // If account is blank, flow manage create new account
            command.setAccount("");
            command.setFirstName("");
            command.setLastName("");
            command.setPassword("");

            // Default user role is GUEST
            List<String> userRoles = new ArrayList<String>(0);
            userRoles.add(UserAuthority.Authority.COMMUNITY_USERS.toString());
            command.setUserRoles(userRoles);

            Integer expirationUserMonth = NumberUtils
                    .toInt(ApplicationPropertyManager.getApplicationProperty("user.expiration.user.months"));
            DateTime expirationUserDate = (new DateTime()).plusMonths(expirationUserMonth);
            command.setYearExpirationUser(expirationUserDate.getYear());
            command.setMonthExpirationUser(new Month(expirationUserDate.getMonthOfYear()).getMonthNum());
            command.setDayExpirationUser(expirationUserDate.getDayOfMonth());

            Integer expirationPasswordMonth = NumberUtils.toInt(
                    ApplicationPropertyManager.getApplicationProperty("user.expiration.password.months"));
            DateTime expirationPasswordDate = (new DateTime()).plusMonths(expirationPasswordMonth);
            command.setYearExpirationPassword(expirationPasswordDate.getYear());
            command.setMonthExpirationPassword(
                    new Month(expirationPasswordDate.getMonthOfYear()).getMonthNum());
            command.setDayExpirationPassword(expirationPasswordDate.getDayOfMonth());

            command.setActive(Boolean.TRUE);
            command.setApproved(Boolean.TRUE);
            command.setLocked(Boolean.FALSE);
        }
    } catch (ApplicationThrowable applicationThrowable) {
        model.put("applicationThrowable", applicationThrowable);
        return new ModelAndView("error/EditUser", model);
    }

    return new ModelAndView("admin/EditUser", model);
}

From source file:org.mifos.application.servicefacade.LoanAccountServiceFacadeWebTier.java

License:Open Source License

private BigDecimal cumulativeTotalForMonth(DateTime dateOfCashFlow, LoanScheduleDto loanScheduleDto) {
    BigDecimal value = new BigDecimal(0).setScale(2, BigDecimal.ROUND_HALF_UP);
    for (LoanCreationInstallmentDto repaymentScheduleInstallment : loanScheduleDto.getInstallments()) {

        DateTime dueDate = new DateTime(repaymentScheduleInstallment.getDueDate());

        if (dueDate.getMonthOfYear() == dateOfCashFlow.getMonthOfYear()
                && (dueDate.getYear() == dateOfCashFlow.getYear())) {
            value = value.add(BigDecimal.valueOf(repaymentScheduleInstallment.getTotal()));
        }//from www .jav  a 2s . co  m
    }
    return value;
}

From source file:org.mifos.calendar.CalendarUtils.java

License:Open Source License

public static DateTime nearestDayOfWeekTo(final int dayOfWeek, final DateTime date) {

    DateTime withDayOfWeek = date.withDayOfWeek(dayOfWeek);

    if (date.getYear() == withDayOfWeek.getYear()) {

        if (date.getDayOfYear() > withDayOfWeek.getDayOfYear()) {
            return withDayOfWeek.plusWeeks(1);
        }/*from  w w w  .  j  a v  a 2  s  .co m*/

        return withDayOfWeek;
    }

    // back a year
    if (date.getYear() > withDayOfWeek.getYear()) {
        return withDayOfWeek.plusWeeks(1);
    }

    return withDayOfWeek;
}

From source file:org.mifos.customers.center.struts.action.CenterCustAction.java

License:Open Source License

@TransactionDemarcate(saveToken = true)
public ActionForward load(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        @SuppressWarnings("unused") HttpServletResponse response) throws Exception {

    CenterCustActionForm actionForm = (CenterCustActionForm) form;
    actionForm.clearActionFormFields();/*from w w  w.  j  a  v  a  2s.  c  o  m*/
    SessionUtils.removeAttribute(CustomerConstants.CUSTOMER_MEETING, request);

    UserContext userContext = getUserContext(request);
    CenterCreation centerCreationDto = new CenterCreation(actionForm.getOfficeIdValue(), userContext.getId(),
            userContext.getLevelId(), userContext.getPreferredLocale());

    CenterFormCreationDto centerFormCreation = this.centerServiceFacade
            .retrieveCenterFormCreationData(centerCreationDto);

    //        SessionUtils.setCollectionAttribute(CustomerConstants.CUSTOM_FIELDS_LIST, new ArrayList<Serializable>(), request);
    SessionUtils.setCollectionAttribute(CustomerConstants.LOAN_OFFICER_LIST,
            centerFormCreation.getActiveLoanOfficersForBranch(), request);
    SessionUtils.setCollectionAttribute(CustomerConstants.ADDITIONAL_FEES_LIST,
            centerFormCreation.getAdditionalFees(), request);
    //        actionForm.setCustomFields(centerFormCreation.getCustomFieldViews());
    actionForm.setDefaultFees(centerFormCreation.getDefaultFees());

    DateTime today = new DateTime().toDateMidnight().toDateTime();
    actionForm.setMfiJoiningDate(today.getDayOfMonth(), today.getMonthOfYear(), today.getYear());

    return mapping.findForward(ActionForwards.load_success.toString());
}

From source file:org.mifos.platform.cashflow.service.CashFlowServiceImpl.java

License:Open Source License

@Override
public CashFlowBoundary getCashFlowBoundary(DateTime firstInstallmentDueDate, DateTime lastInstallmentDueDate) {
    DateTime monthAfterLastInstallment = lastInstallmentDueDate
            .plusMonths(EXTRA_DURATION_FOR_CASH_FLOW_SCHEDULE).withDayOfMonth(FIRST_DAY);
    DateTime monthBeforeFirstInstallment = firstInstallmentDueDate
            .minusMonths(EXTRA_DURATION_FOR_CASH_FLOW_SCHEDULE).withDayOfMonth(FIRST_DAY);
    int numberOfMonths = Months.monthsBetween(monthBeforeFirstInstallment, monthAfterLastInstallment)
            .getMonths() + 1;/*w  ww  .  ja  va2 s.  co m*/
    return new CashFlowBoundary(monthBeforeFirstInstallment.getMonthOfYear(),
            monthBeforeFirstInstallment.getYear(), numberOfMonths);
}