Example usage for org.joda.time LocalDate fromDateFields

List of usage examples for org.joda.time LocalDate fromDateFields

Introduction

In this page you can find the example usage for org.joda.time LocalDate fromDateFields.

Prototype

@SuppressWarnings("deprecation")
public static LocalDate fromDateFields(Date date) 

Source Link

Document

Constructs a LocalDate from a java.util.Date using exactly the same field values.

Usage

From source file:odin.domain.Sprint.java

License:Apache License

public static int getRemainingAvailability(String sprintString, String username) {
    EntityManager em = DBUtil.getEntityManager();

    TypedQuery<Sprint> q = em/* www .java  2s  . com*/
            .createQuery("select s from Sprint s WHERE s.sprintName = :sprintString", Sprint.class)
            .setParameter("sprintString", sprintString);
    Sprint sprint = q.getSingleResult();
    // em.detach(sprint);
    LocalDate today = new LocalDate();
    int availability = 0;
    SimpleDateFormat sdf = new SimpleDateFormat("M/d/yy");

    for (Week week : sprint.getWeeks()) {
        LocalDate weekEndDate = LocalDate.fromDateFields(week.getEndDate());
        int days = Days.daysBetween(today, weekEndDate).getDays();
        System.out.println(days);
        if (days >= 0) {
            if (days < 6) {
                // Calculate hours left on a part week.
                int remainingHours = Availability.getAvailability(sdf.format(weekEndDate.toDate()), username)
                        / 5 * days;
                availability = availability + remainingHours;
                System.out.println("Part week. Calculated availability for week ending "
                        + sdf.format(week.getEndDate()) + " is " + remainingHours);
            } else
                availability = availability
                        + Availability.getAvailability(sdf.format(weekEndDate.toDate()), username);
        }
    }

    em.close();
    return availability;
}

From source file:org.alexlg.bankit.services.SyncService.java

License:Open Source License

/**
 * Sync a list of operation with current ones.
 * @param operations Operations to sync.
 *//*from w w w  . j  a  va 2  s . c  o m*/
public void syncOpList(List<Operation> operations) {
    if (operations == null)
        return;
    Date start = optionsService.getDate(OP_SYNC_OPT);
    LocalDate startSync = start == null ? null : LocalDate.fromDateFields(start);
    LocalDate maxDate = null; //older operation date

    for (Operation op : operations) {
        LocalDate opDate = LocalDate.fromDateFields(op.getOperationDate());

        if (startSync == null || opDate.isAfter(startSync)) {
            operationDao.insert(op);

            //checking if operation if after maxDate
            if (maxDate == null || opDate.isAfter(maxDate))
                maxDate = opDate;
        }
    }

    //setting last execution
    if (maxDate != null)
        optionsService.set(OP_SYNC_OPT, maxDate.toDate());
}

From source file:org.apache.fineract.accounting.closure.bookoffincomeandexpense.service.CalculateIncomeAndExpenseBookingImpl.java

License:Apache License

@Override
public Collection<IncomeAndExpenseBookingData> CalculateIncomeAndExpenseBookings(JsonQuery query) {
    final GLClosureCommand closureCommand = this.fromApiJsonDeserializer.commandFromApiJson(query.json());
    closureCommand.validateForCreate();//from  ww w  .j a  va  2 s . c  om
    final Long officeId = closureCommand.getOfficeId();
    final Office office = this.officeRepository.findOne(officeId);
    if (office == null) {
        throw new OfficeNotFoundException(officeId);
    }

    final Date todaysDate = new Date();
    final Date closureDate = closureCommand.getClosingDate().toDate();
    if (closureDate.after(todaysDate)) {
        throw new GLClosureInvalidException(GLClosureInvalidException.GL_CLOSURE_INVALID_REASON.FUTURE_DATE,
                closureDate);
    }
    // shouldn't be before an existing accounting closure
    final GLClosure latestGLClosure = this.glClosureRepository.getLatestGLClosureByBranch(officeId);
    if (latestGLClosure != null) {
        if (latestGLClosure.getClosingDate().after(closureDate)) {
            throw new GLClosureInvalidException(
                    GLClosureInvalidException.GL_CLOSURE_INVALID_REASON.ACCOUNTING_CLOSED,
                    latestGLClosure.getClosingDate());
        }
    }
    final LocalDate incomeAndExpenseBookOffDate = LocalDate.fromDateFields(closureDate);

    /*get all offices underneath it valid closure date for all, get Jl for all and make bookings*/
    // final List<Office> childOffices = office.getChildren();
    final Collection<Long> childOfficesByHierarchy = this.officeReadPlatformService.officeByHierarchy(officeId);
    if (closureCommand.getSubBranches() && childOfficesByHierarchy.size() > 0) {
        for (final Long childOffice : childOfficesByHierarchy) {
            final GLClosure latestChildGlClosure = this.glClosureRepository
                    .getLatestGLClosureByBranch(childOffice);
            if (latestChildGlClosure != null) {
                if (latestChildGlClosure.getClosingDate().after(closureDate)) {
                    throw new GLClosureInvalidException(
                            GLClosureInvalidException.GL_CLOSURE_INVALID_REASON.ACCOUNTING_CLOSED,
                            latestChildGlClosure.getClosingDate());
                }
            }
        }
    }

    Collection<IncomeAndExpenseBookingData> incomeAndExpenseBookingCollection = new ArrayList<>();
    final Long equityGlAccountId = closureCommand.getEquityGlAccountId();

    final GLAccount glAccount = this.glAccountRepository.findOne(equityGlAccountId);

    if (glAccount == null) {
        throw new GLAccountNotFoundException(equityGlAccountId);
    }

    if (closureCommand.getSubBranches() && childOfficesByHierarchy.size() > 0) {
        for (final Long childOffice : childOfficesByHierarchy) {
            final List<IncomeAndExpenseJournalEntryData> incomeAndExpenseJournalEntryDataList = this.incomeAndExpenseReadPlatformService
                    .retrieveAllIncomeAndExpenseJournalEntryData(childOffice, incomeAndExpenseBookOffDate,
                            closureCommand.getCurrencyCode());
            final IncomeAndExpenseBookingData incomeAndExpBookingData = this.bookOffIncomeAndExpense(
                    incomeAndExpenseJournalEntryDataList, closureCommand, true, glAccount,
                    this.officeRepository.findOne(childOffice));
            if (incomeAndExpBookingData.getJournalEntries().size() > 0) {
                incomeAndExpenseBookingCollection.add(incomeAndExpBookingData);
            }
        }
    } else {
        final List<IncomeAndExpenseJournalEntryData> incomeAndExpenseJournalEntryDataList = this.incomeAndExpenseReadPlatformService
                .retrieveAllIncomeAndExpenseJournalEntryData(officeId, incomeAndExpenseBookOffDate,
                        closureCommand.getCurrencyCode());
        final IncomeAndExpenseBookingData incomeAndExpBookingData = this.bookOffIncomeAndExpense(
                incomeAndExpenseJournalEntryDataList, closureCommand, true, glAccount, office);
        if (incomeAndExpBookingData.getJournalEntries().size() > 0) {
            incomeAndExpenseBookingCollection.add(incomeAndExpBookingData);
        }
    }
    return incomeAndExpenseBookingCollection;
}

From source file:org.apache.fineract.accounting.closure.storeglaccountbalance.service.GLClosureJournalEntryBalanceWritePlatformServiceImp.java

License:Apache License

@Override
@Transactional/*from  w  w  w. j  a v a  2s .  c o m*/
public void storeJournalEntryRunningBalance(final GLClosure glClosure,
        final IncomeAndExpenseBooking incomeAndExpenseBooking) {
    if (glClosure != null && glClosure.getOffice() != null && glClosure.getClosingDate() != null
            && this.configurationDomainService.storeJournalEntryBalanceAtPeriodClosure()) {
        final Long officeId = glClosure.getOffice().getId();
        final Date closureClosingDate = glClosure.getClosingDate();
        final LocalDate maxEntryDate = LocalDate.fromDateFields(closureClosingDate);
        final Collection<GLClosureJournalEntryData> journalEntriesData = this.glClosureJournalEntryReadPlatformService
                .retrieveAllJournalEntries(officeId, maxEntryDate);
        final Map<Long, GLAccount> glAccountMap = this.retrieveAllActiveGlAccounts();

        if (journalEntriesData != null) {
            // will hold array of GL account ids that have already been processed 
            // (GLClosureJournalEntryBalance entity already created and stored in the database)
            Long[] processedGLAccountIds = new Long[journalEntriesData.size()];
            int longArrayIndex = 0;

            final Map<Long, JournalEntryData> journalEntryDataMap = this
                    .getIncomeAndExpenseBookingJournalEntryDataMap(incomeAndExpenseBooking);

            for (GLClosureJournalEntryData journalEntryData : journalEntriesData) {
                Long glAccountId = journalEntryData.getAccountId();
                GLAccount glAccount = glAccountMap.get(glAccountId);

                // calculate the running balance for the GL account
                BigDecimal runningBalance = this.calculateAccountRunningBalance(glAccount,
                        journalEntryData.getOfficeRunningBalance(), journalEntryDataMap);

                // create new GLClosureJournalEntryBalance entity
                GLClosureJournalEntryBalance journalEntryBalance = GLClosureJournalEntryBalance
                        .newGLClosureBalance(glClosure, glAccount, runningBalance);

                // add the id of the GL account to the array of ids of already processed GL accounts
                processedGLAccountIds[longArrayIndex] = glAccountId;

                // increment the array index
                longArrayIndex++;

                // save entity and flush changes instantly
                this.glClosureJournalEntryBalanceRepository.saveAndFlush(journalEntryBalance);
            }

            Iterator<Map.Entry<Long, GLAccount>> glAccounts = glAccountMap.entrySet().iterator();

            while (glAccounts.hasNext()) {
                Map.Entry<Long, GLAccount> glAccountEntry = glAccounts.next();

                // if GL account has not been processed, go ahead and create a new GLClosureJournalEntryBalance
                // with a zero amount (the GL account has no journal entry)
                if (!Arrays.asList(processedGLAccountIds).contains(glAccountEntry.getKey())) {
                    GLAccount glAccount = glAccountEntry.getValue();

                    // calculate the running balance for the GL account
                    BigDecimal runningBalance = this.calculateAccountRunningBalance(glAccount, BigDecimal.ZERO,
                            journalEntryDataMap);

                    // create new GLClosureJournalEntryBalance entity
                    GLClosureJournalEntryBalance journalEntryBalance = GLClosureJournalEntryBalance
                            .newGLClosureBalance(glClosure, glAccount, runningBalance);

                    // save entity and flush changes instantly
                    this.glClosureJournalEntryBalanceRepository.saveAndFlush(journalEntryBalance);
                }
            }
        }
    }
}

From source file:org.apache.fineract.portfolio.floatingrates.domain.FloatingRate.java

License:Apache License

private void updateRatePeriods(final Set<FloatingRatePeriod> newRatePeriods, final AppUser appUser) {
    final LocalDate today = DateUtils.getLocalDateOfTenant();
    if (this.floatingRatePeriods != null) {
        for (FloatingRatePeriod ratePeriod : this.floatingRatePeriods) {
            LocalDate fromDate = LocalDate.fromDateFields(ratePeriod.getFromDate());
            if (fromDate.isAfter(today)) {
                ratePeriod.setActive(false);
                ratePeriod.setModifiedBy(appUser);
                ratePeriod.setModifiedOn(today.toDate());
            }//from w  ww .j  a v a  2s.  c  o m
        }
    }
    for (FloatingRatePeriod newRatePeriod : newRatePeriods) {
        newRatePeriod.updateFloatingRate(this);
        this.floatingRatePeriods.add(newRatePeriod);
    }
}

From source file:org.apache.fineract.portfolio.loanaccount.api.LoanTransactionsApiResource.java

License:Apache License

@GET
@Path("template")
@Consumes({ MediaType.APPLICATION_JSON })
@Produces({ MediaType.APPLICATION_JSON })
public String retrieveTransactionTemplate(@PathParam("loanId") final Long loanId,
        @QueryParam("command") final String commandParam, @Context final UriInfo uriInfo,
        @QueryParam("dateFormat") final String dateFormat,
        @QueryParam("transactionDate") final DateParam transactionDateParam,
        @QueryParam("locale") final String locale) {

    this.context.authenticatedUser().validateHasReadPermission(this.resourceNameForPermissions);

    LoanTransactionData transactionData = null;
    if (is(commandParam, "repayment")) {
        transactionData = this.loanReadPlatformService.retrieveLoanTransactionTemplate(loanId);
    } else if (is(commandParam, "waiveinterest")) {
        transactionData = this.loanReadPlatformService.retrieveWaiveInterestDetails(loanId);
    } else if (is(commandParam, "writeoff")) {
        transactionData = this.loanReadPlatformService.retrieveLoanWriteoffTemplate(loanId);
    } else if (is(commandParam, "close-rescheduled")) {
        transactionData = this.loanReadPlatformService.retrieveNewClosureDetails();
    } else if (is(commandParam, "close")) {
        transactionData = this.loanReadPlatformService.retrieveNewClosureDetails();
    } else if (is(commandParam, "disburse")) {
        transactionData = this.loanReadPlatformService.retrieveDisbursalTemplate(loanId, true);
    } else if (is(commandParam, "disburseToSavings")) {
        transactionData = this.loanReadPlatformService.retrieveDisbursalTemplate(loanId, false);
    } else if (is(commandParam, "recoverypayment")) {
        transactionData = this.loanReadPlatformService.retrieveRecoveryPaymentTemplate(loanId);
    } else if (is(commandParam, "prepayLoan")) {
        LocalDate transactionDate = null;
        if (transactionDateParam == null) {
            transactionDate = DateUtils.getLocalDateOfTenant();
        } else {/* w  w w  .j  a v  a 2 s .  c  om*/
            transactionDate = LocalDate
                    .fromDateFields(transactionDateParam.getDate("transactionDate", dateFormat, locale));
        }
        transactionData = this.loanReadPlatformService.retrieveLoanPrePaymentTemplate(loanId, transactionDate);
    } else if (is(commandParam, "refundbycash")) {
        transactionData = this.loanReadPlatformService.retrieveRefundByCashTemplate(loanId);
    } else if (is(commandParam, "refundbytransfer")) {
        transactionData = this.loanReadPlatformService.retrieveDisbursalTemplate(loanId, true);
    } else {
        throw new UnrecognizedQueryParamException("command", commandParam);
    }

    final ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper
            .process(uriInfo.getQueryParameters());
    return this.toApiJsonSerializer.serialize(settings, transactionData, this.RESPONSE_DATA_PARAMETERS);
}

From source file:org.apache.fineract.portfolio.meeting.domain.Meeting.java

License:Apache License

private static boolean isValidMeetingDate(final CalendarInstance calendarInstance, final Date meetingDate) {
    final Calendar calendar = calendarInstance.getCalendar();
    LocalDate meetingDateLocalDate = null;
    if (meetingDate != null) {
        meetingDateLocalDate = LocalDate.fromDateFields(meetingDate);
    }//from  w  w w. j  a va  2s . co m

    if (meetingDateLocalDate == null || !calendar.isValidRecurringDate(meetingDateLocalDate)) {
        return false;
    }
    return true;
}

From source file:org.apache.sqoop.connector.hbase.HbaseExtractor.java

License:Apache License

@Override
public void extract(ExtractorContext context, LinkConfiguration linkConfig, FromJobConfiguration fromJobConfig,
        GenericJdbcPartition partition) {
    HbaseExecutor executor = new HbaseExecutor(linkConfig.linkConfig);

    String query = context.getString(HbaseConnectorConstants.CONNECTOR_JDBC_FROM_DATA_SQL);
    String conditions = partition.getConditions();
    query = query.replace(HbaseConnectorConstants.SQL_CONDITIONS_TOKEN, conditions);
    LOG.info("Using query: " + query);

    rowsRead = 0;/*from   ww w . j a  v a 2 s . c o m*/
    ResultSet resultSet = executor.executeQuery(query);

    Schema schema = context.getSchema();
    Column[] schemaColumns = schema.getColumnsArray();
    try {
        ResultSetMetaData metaData = resultSet.getMetaData();
        int columnCount = metaData.getColumnCount();
        if (schemaColumns.length != columnCount) {
            throw new SqoopException(GenericJdbcConnectorError.GENERIC_JDBC_CONNECTOR_0021,
                    schemaColumns.length + ":" + columnCount);
        }
        while (resultSet.next()) {
            Object[] array = new Object[columnCount];
            for (int i = 0; i < columnCount; i++) {
                if (resultSet.getObject(i + 1) == null) {
                    array[i] = null;
                    continue;
                }
                // check type of the column
                Column schemaColumn = schemaColumns[i];
                switch (schemaColumn.getType()) {
                case DATE:
                    // convert the sql date to JODA time as prescribed the Sqoop IDF spec
                    array[i] = LocalDate.fromDateFields((java.sql.Date) resultSet.getObject(i + 1));
                    break;
                case DATE_TIME:
                    // convert the sql date time to JODA time as prescribed the Sqoop IDF spec
                    array[i] = LocalDateTime.fromDateFields((java.sql.Timestamp) resultSet.getObject(i + 1));
                    break;
                case TIME:
                    // convert the sql time to JODA time as prescribed the Sqoop IDF spec
                    array[i] = LocalTime.fromDateFields((java.sql.Time) resultSet.getObject(i + 1));
                    break;
                default:
                    //for anything else
                    array[i] = resultSet.getObject(i + 1);

                }
            }
            context.getDataWriter().writeArrayRecord(array);
            rowsRead++;
        }
    } catch (SQLException e) {
        throw new SqoopException(GenericJdbcConnectorError.GENERIC_JDBC_CONNECTOR_0004, e);

    } finally {
        executor.close();
    }
}

From source file:org.apache.sqoop.connector.jdbc.GenericJdbcExtractor.java

License:Apache License

@Override
public void extract(ExtractorContext context, LinkConfiguration linkConfig, FromJobConfiguration fromJobConfig,
        GenericJdbcPartition partition) {
    GenericJdbcExecutor executor = new GenericJdbcExecutor(linkConfig.linkConfig);

    String query = context.getString(GenericJdbcConnectorConstants.CONNECTOR_JDBC_FROM_DATA_SQL);
    String conditions = partition.getConditions();
    query = query.replace(GenericJdbcConnectorConstants.SQL_CONDITIONS_TOKEN, conditions);
    LOG.info("Using query: " + query);

    rowsRead = 0;//  w  ww. j a  v a  2s.com
    ResultSet resultSet = executor.executeQuery(query);

    Schema schema = context.getSchema();
    Column[] schemaColumns = schema.getColumnsArray();
    try {
        ResultSetMetaData metaData = resultSet.getMetaData();
        int columnCount = metaData.getColumnCount();
        if (schemaColumns.length != columnCount) {
            throw new SqoopException(GenericJdbcConnectorError.GENERIC_JDBC_CONNECTOR_0021,
                    schemaColumns.length + ":" + columnCount);
        }
        while (resultSet.next()) {
            Object[] array = new Object[columnCount];
            for (int i = 0; i < columnCount; i++) {
                if (resultSet.getObject(i + 1) == null) {
                    array[i] = null;
                    continue;
                }
                // check type of the column
                Column schemaColumn = schemaColumns[i];
                switch (schemaColumn.getType()) {
                case DATE:
                    // convert the sql date to JODA time as prescribed the Sqoop IDF spec
                    array[i] = LocalDate.fromDateFields((java.sql.Date) resultSet.getObject(i + 1));
                    break;
                case DATE_TIME:
                    // convert the sql date time to JODA time as prescribed the Sqoop IDF spec
                    array[i] = LocalDateTime.fromDateFields((java.sql.Timestamp) resultSet.getObject(i + 1));
                    break;
                case TIME:
                    // convert the sql time to JODA time as prescribed the Sqoop IDF spec
                    array[i] = LocalTime.fromDateFields((java.sql.Time) resultSet.getObject(i + 1));
                    break;
                default:
                    //for anything else
                    array[i] = resultSet.getObject(i + 1);

                }
            }
            context.getDataWriter().writeArrayRecord(array);
            rowsRead++;
        }
    } catch (SQLException e) {
        throw new SqoopException(GenericJdbcConnectorError.GENERIC_JDBC_CONNECTOR_0004, e);

    } finally {
        executor.close();
    }
}

From source file:org.egov.tl.service.DemandNoticeService.java

License:Open Source License

private String getPenaltyRateDetails(List<PenaltyRates> penaltyRates, Installment currentInstallment,
        LicenseAppType licenseAppType) {
    StringBuilder penaltylist = new StringBuilder();

    Long fromRange = penaltyRatesService.getMinFromRange(licenseAppType);
    Long toRange = penaltyRatesService.getMaxToRange(licenseAppType);

    for (PenaltyRates penaltyRate : penaltyRates) {
        LocalDate currentInstallmentStartDate = LocalDate.fromDateFields(currentInstallment.getFromDate())
                .plusDays(1);//from   w w  w .jav  a 2s  .c  om
        LocalDate currentStartDate = LocalDate.fromDateFields(currentInstallment.getFromDate());
        if (penaltyRate.getRate() <= ZERO.doubleValue()) {
            penaltylist.append("Before ")
                    .append(getDefaultFormattedDate(
                            currentInstallmentStartDate.plusDays(penaltyRate.getToRange().intValue()).toDate()))
                    .append(" without penalty\n");
        }
        if (penaltyRate.getRate() > ZERO.doubleValue()) {
            if (penaltyRate.getToRange() >= toRange) {
                penaltylist.append("    After ")
                        .append(getDefaultFormattedDate(
                                currentStartDate.plusDays(penaltyRate.getFromRange().intValue()).toDate()))
                        .append(WITH).append(penaltyRate.getRate().intValue()).append("% penalty");
            } else if (penaltyRate.getFromRange() <= fromRange) {
                penaltylist.append("Before ")
                        .append(getDefaultFormattedDate(currentInstallmentStartDate
                                .plusDays(penaltyRate.getToRange().intValue()).toDate()))
                        .append(WITH).append(penaltyRate.getRate().intValue()).append("% penalty\n");
            } else {
                penaltylist.append("    From ")
                        .append(getDefaultFormattedDate(currentInstallmentStartDate
                                .plusDays(penaltyRate.getFromRange().intValue()).toDate()))
                        .append(" to ")
                        .append(getDefaultFormattedDate(
                                currentStartDate.plusDays(penaltyRate.getToRange().intValue()).toDate()))
                        .append(WITH).append(penaltyRate.getRate().intValue()).append("% penalty\n");
            }
        }
    }
    return penaltylist.toString();
}