Example usage for org.joda.time LocalDate withDayOfMonth

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

Introduction

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

Prototype

public LocalDate withDayOfMonth(int dayOfMonth) 

Source Link

Document

Returns a copy of this date with the day of month field updated.

Usage

From source file:de.jollyday.parser.impl.FixedWeekdayInMonthParser.java

License:Apache License

/**
 * Parses the {@link FixedWeekdayInMonth}.
 * /*from ww w  .  jav a  2  s .  c  o m*/
 * @param year
 *            the year
 * @param fwm
 *            the fwm
 * @return the local date
 */
protected LocalDate parse(int year, FixedWeekdayInMonth fwm) {
    LocalDate date = calendarUtil.create(year, xmlUtil.getMonth(fwm.getMonth()), 1);
    int direction = 1;
    if (fwm.getWhich() == Which.LAST) {
        date = date.withDayOfMonth(date.dayOfMonth().getMaximumValue());
        direction = -1;
    }
    date = moveToNextRequestedWeekdayByDirection(fwm, date, direction);
    date = moveNumberOfRequestedWeeks(fwm, date);
    return date;
}

From source file:energy.usef.agr.workflow.settlement.receive.AgrReceiveSettlementMessageCoordinator.java

License:Apache License

/**
 * Handle CheckSettlement Event./*from  ww  w.  jav a 2s .c  o  m*/
 *
 * @param event
 */
@Asynchronous
public void handleCheckSettlementEvent(
        @Observes(during = TransactionPhase.AFTER_COMPLETION) CheckSettlementEvent event) {
    LOGGER.debug(USEFConstants.LOG_COORDINATOR_START_HANDLING_EVENT, event);

    LocalDate eventDate = event.getPeriodInMonth();
    if (eventDate == null) {
        eventDate = DateTimeUtil.getCurrentDate().minusMonths(1);
    }
    LocalDate startDate = eventDate.withDayOfMonth(1);
    LocalDate endDate = startDate.plusMonths(1).minusDays(1);

    List<PlanboardMessage> flexOrderSettlementMessages = corePlanboardBusinessService.findPlanboardMessages(
            DocumentType.FLEX_ORDER_SETTLEMENT, startDate, endDate, DocumentStatus.RECEIVED);
    LOGGER.debug(
            "Fetched [{}] FLEX_ORDER_SETTLEMENTS from PlanboardMessage with status RECEIVED between [{}] and [{}]",
            flexOrderSettlementMessages.size(), startDate, endDate);
    Map<String, List<PlanboardMessage>> flexOrderSettlementsPerParticipant = flexOrderSettlementMessages
            .stream()
            .collect(Collectors.groupingBy(PlanboardMessage::getParticipantDomain, Collectors.toList()));
    flexOrderSettlementsPerParticipant
            .forEach((participant, flexOrderSettlements) -> checkSettlementPerParticipant(participant,
                    flexOrderSettlements, startDate, endDate));

    LOGGER.debug(USEFConstants.LOG_COORDINATOR_FINISHED_HANDLING_EVENT, event);
}

From source file:energy.usef.brp.workflow.settlement.initiate.BrpInitiateSettlementCoordinator.java

License:Apache License

/**
 * Preparation of the Initiate Settlement process for the first day of the previous month until the last day of the previous
 * month. The initiating of settlements will stop if there are no flex orders in the selected period.
 *
 * @param event The {@link CollectSmartMeterDataEvent} triggering the process.
 *///  w ww.ja v  a2s  .  c  om
@Asynchronous
@Lock(LockType.WRITE)
public void handleCollectSmartMeterDataEvent(
        @Observes(during = TransactionPhase.AFTER_COMPLETION) CollectSmartMeterDataEvent event) {
    LOGGER.debug(USEFConstants.LOG_COORDINATOR_START_HANDLING_EVENT, event);
    LocalDate dayOneMonthBefore = event.getPeriodInMonth();
    if (dayOneMonthBefore == null) {
        dayOneMonthBefore = DateTimeUtil.getCurrentDate().minusMonths(1);
    }
    LocalDate startDate = dayOneMonthBefore.withDayOfMonth(1);
    LocalDate endDate = dayOneMonthBefore.dayOfMonth().withMaximumValue();

    // retrieve a distinct list of all connections valid in given time frame and map them to a string list.
    Map<LocalDate, Map<ConnectionGroup, List<Connection>>> connectionGroupsWithConnections = corePlanboardBusinessService
            .findConnectionGroupWithConnectionsWithOverlappingValidity(startDate, endDate);
    List<LocalDate> daysWithOrders = corePlanboardBusinessService
            .findPlanboardMessages(DocumentType.FLEX_ORDER, startDate, endDate, DocumentStatus.ACCEPTED)
            .stream().map(PlanboardMessage::getPeriod).distinct().collect(Collectors.toList());
    if (daysWithOrders.isEmpty()) {
        checkInitiateSettlementDoneEvent
                .fire(new CheckInitiateSettlementDoneEvent(startDate.getYear(), startDate.getMonthOfYear()));
        LOGGER.debug(USEFConstants.LOG_COORDINATOR_FINISHED_HANDLING_EVENT, event);
        return;
    }
    // loop through all the MDCs
    for (MeterDataCompany meterDataCompany : brpBusinessService.findAllMDCs()) {
        // query meter data company (MDC) for all connections
        LOGGER.info("Preparing sending MeterDataQuery to Meter Data Company {}", meterDataCompany.getDomain());
        for (LocalDate period : connectionGroupsWithConnections.keySet()) {
            if (!daysWithOrders.contains(period)) {
                continue;
            }
            LocalDateTime expirationDateTime = DateTimeUtil.getCurrentDateTime().plusHours(
                    configBrp.getIntegerProperty(ConfigBrpParam.BRP_METER_DATA_QUERY_EXPIRATION_IN_HOURS));
            MessageMetadata messageMetadata = MessageMetadataBuilder
                    .build(meterDataCompany.getDomain(), USEFRole.MDC,
                            config.getProperty(ConfigParam.HOST_DOMAIN), USEFRole.BRP, TRANSACTIONAL)
                    .validUntil(expirationDateTime).build();

            // fill the MeterDataQuery message
            MeterDataQuery meterDataQuery = new MeterDataQuery();
            meterDataQuery.setMessageMetadata(messageMetadata);
            meterDataQuery.setDateRangeStart(period);
            meterDataQuery.setDateRangeEnd(period);
            meterDataQuery.getConnections()
                    .addAll(buildConnectionGroups(connectionGroupsWithConnections.get(period)));
            MeterDataQueryMessageUtil.populateConnectionsInConnectionGroups(meterDataQuery,
                    connectionGroupsWithConnections.get(period));

            // Store in PlanboardMessage, no connectionGroup available because query is for the whole grid.
            // the period should be the startDate of the month.
            PlanboardMessage meterDataQueryPlanboardMessage = new PlanboardMessage(
                    DocumentType.METER_DATA_QUERY_USAGE, sequenceGeneratorService.next(), DocumentStatus.SENT,
                    meterDataCompany.getDomain(), period, null, null, expirationDateTime);
            corePlanboardBusinessService.updatePlanboardMessage(meterDataQueryPlanboardMessage);

            // send the message
            jmsHelperService.sendMessageToOutQueue(XMLUtil.messageObjectToXml(meterDataQuery));
        }
    }
    LOGGER.debug(USEFConstants.LOG_COORDINATOR_FINISHED_HANDLING_EVENT, event);
}

From source file:energy.usef.core.repository.PtuFlexOrderRepository.java

License:Apache License

/**
 * Find the Accepted {@link PtuFlexOrder}'s for the requested month and year.
 *
 * @param workingDate - The date with requested month and year
 * @return//from ww w.  j  av a2s  .c  om
 */
public List<PtuFlexOrder> findAcknowledgedFlexOrdersForMonthInYear(LocalDate workingDate) {
    StringBuilder sql = new StringBuilder();
    sql.append("SELECT fo ");
    sql.append("FROM PtuFlexOrder fo ");
    sql.append("WHERE fo.acknowledgementStatus = :acknowledgementStatus ");
    sql.append("  AND fo.ptuContainer.ptuDate >= :firstDay ");
    sql.append("  AND fo.ptuContainer.ptuDate <= :lastDay ");
    Query query = entityManager.createQuery(sql.toString(), PtuFlexOrder.class);

    query.setParameter("acknowledgementStatus", AcknowledgementStatus.ACCEPTED);
    query.setParameter("firstDay", workingDate.withDayOfMonth(1).toDateMidnight().toDate(), DATE);
    query.setParameter("lastDay",
            workingDate.plusMonths(1).withDayOfMonth(1).minusDays(1).toDateMidnight().toDate(), DATE);

    return query.getResultList();
}

From source file:energy.usef.dso.workflow.settlement.collect.DsoCollectOrangeRegimeDataCoordinator.java

License:Apache License

/**
 * Initiates collect orange regime data process.
 *
 * @param event the {@link InitiateCollectOrangeRegimeDataEvent} event that triggers the process.
 *//*from   w  w  w .  j a  va  2 s.c o  m*/
@Asynchronous
@Lock(LockType.WRITE)
public void initiateCollectOrangeRegimeData(@Observes InitiateCollectOrangeRegimeDataEvent event) {
    LOGGER.info(LOG_COORDINATOR_START_HANDLING_EVENT, event);

    LocalDate dayOneMonthBefore = DateTimeUtil.getCurrentDate().minusMonths(1);
    LocalDate startDay = dayOneMonthBefore.withDayOfMonth(1);
    LocalDate endDay = dayOneMonthBefore.dayOfMonth().withMaximumValue();

    List<MeterDataCompany> mdcList = dsoPlanboardBusinessService.findAllMDCs();

    for (LocalDate day = startDay; !day.isAfter(endDay); day = day.plusDays(1)) {
        // Retrieving a list of all connections involved in the orange regime processing.
        Map<ConnectionGroup, List<Connection>> connectionsMap = corePlanboardBusinessService
                .findConnections(day, day, RegimeType.ORANGE);
        if (!connectionsMap.isEmpty()) {
            // Looping through all the MDCs
            for (MeterDataCompany meterDataCompany : mdcList) {
                sendMeterDataQuery(connectionsMap, meterDataCompany.getDomain(), day,
                        sequenceGeneratorService.next());
            }
        }
    }
    LOGGER.info(LOG_COORDINATOR_FINISHED_HANDLING_EVENT, event);
}

From source file:energy.usef.dso.workflow.settlement.initiate.DsoInitiateSettlementCoordinator.java

License:Apache License

/**
 * Preparation of the Initiate Settlement process.
 *
 * @param event the {@link CollectSmartMeterDataEvent} that triggers the process.
 *//*from ww  w. ja  v  a 2  s.  c om*/
@Asynchronous
@Lock(LockType.WRITE)
public void handleCollectSmartMeterDataEvent(
        @Observes(during = TransactionPhase.AFTER_COMPLETION) CollectSmartMeterDataEvent event) {
    LOGGER.debug(USEFConstants.LOG_COORDINATOR_START_HANDLING_EVENT, event);
    LocalDate dayOneMonthBefore = event.getPeriodInMonth();
    if (dayOneMonthBefore == null) {
        dayOneMonthBefore = DateTimeUtil.getCurrentDate().minusMonths(1);
    }
    LocalDate startDate = dayOneMonthBefore.withDayOfMonth(1);
    LocalDate endDate = dayOneMonthBefore.dayOfMonth().withMaximumValue();

    LOGGER.info("Preparing Initiate Settlement workflow for the start day {} and end day {}.", startDate,
            endDate);

    // retrieve a distinct list of all connections valid in given time frame and map them to a string list.
    Map<LocalDate, Map<ConnectionGroup, List<Connection>>> connectionGroupsWithConnections = corePlanboardBusinessService
            .findConnectionGroupWithConnectionsWithOverlappingValidity(startDate, endDate);
    List<LocalDate> daysWithOrders = corePlanboardBusinessService
            .findPlanboardMessages(DocumentType.FLEX_ORDER, startDate, endDate, DocumentStatus.ACCEPTED)
            .stream().map(PlanboardMessage::getPeriod).distinct().collect(toList());
    if (daysWithOrders.isEmpty()) {
        checkInitiateSettlementDoneEvent
                .fire(new CheckInitiateSettlementDoneEvent(startDate.getYear(), startDate.getMonthOfYear()));
        LOGGER.debug(USEFConstants.LOG_COORDINATOR_FINISHED_HANDLING_EVENT, event);
        return;
    }
    // loop through all the MDCs
    for (MeterDataCompany meterDataCompany : dsoPlanboardBusinessService.findAllMDCs()) {
        // query meter data company (MDC) for all connections
        LOGGER.info("Preparing sending MeterDataQuery to Meter Data Company {}", meterDataCompany.getDomain());
        for (LocalDate period : connectionGroupsWithConnections.keySet()) {
            if (!daysWithOrders.contains(period)) {
                continue;
            }
            LocalDateTime expirationDateTime = DateTimeUtil.getCurrentDateTime().plusHours(
                    configDso.getIntegerProperty(ConfigDsoParam.DSO_METER_DATA_QUERY_EXPIRATION_IN_HOURS));
            MessageMetadata messageMetadata = MessageMetadataBuilder
                    .build(meterDataCompany.getDomain(), USEFRole.MDC,
                            config.getProperty(ConfigParam.HOST_DOMAIN), USEFRole.DSO, TRANSACTIONAL)
                    .validUntil(expirationDateTime).build();
            // fill the MeterDataQuery message
            MeterDataQuery meterDataQuery = new MeterDataQuery();
            meterDataQuery.setMessageMetadata(messageMetadata);
            meterDataQuery.setDateRangeStart(period);
            meterDataQuery.setDateRangeEnd(period);
            meterDataQuery.getConnections()
                    .addAll(buildConnectionGroups(connectionGroupsWithConnections.get(period)));
            MeterDataQueryMessageUtil.populateConnectionsInConnectionGroups(meterDataQuery,
                    connectionGroupsWithConnections.get(period));

            // Store in PlanboardMessage, no connectionGroup available because query is for the whole grid.
            // the period should be the startDate of the month.
            PlanboardMessage meterDataQueryPlanboardMessage = new PlanboardMessage(
                    DocumentType.METER_DATA_QUERY_USAGE, sequenceGeneratorService.next(), DocumentStatus.SENT,
                    meterDataCompany.getDomain(), period, null, null, null);
            meterDataQueryPlanboardMessage.setExpirationDate(expirationDateTime);
            corePlanboardBusinessService.updatePlanboardMessage(meterDataQueryPlanboardMessage);

            // send the message
            jmsHelperService.sendMessageToOutQueue(XMLUtil.messageObjectToXml(meterDataQuery));
        }
    }
    LOGGER.debug(USEFConstants.LOG_COORDINATOR_FINISHED_HANDLING_EVENT, event);
}

From source file:net.jrkatz.minero.data.MonthlyPeriodDefinition.java

License:Open Source License

private LocalDate startForMonth(final int year, final int month) {
    LocalDate firstOfMonth = new LocalDate(year, month, 1);
    return firstOfMonth.withDayOfMonth(Math.min(firstOfMonth.dayOfMonth().getMaximumValue(), mDayStart));
}

From source file:net.objectlab.kit.datecalc.joda.LocalDateIMMDateCalculator.java

License:Apache License

/**
 * Assumes that the month is correct, get the day for the 2rd wednesday.
 *
 * @param original/*w  w w  .j a va2 s. co m*/
 *            the start date
 * @return the 3rd Wednesday of the month
 */
private LocalDate calculate3rdWednesday(final LocalDate original) {
    final LocalDate firstOfMonth = original.withDayOfMonth(1);
    LocalDate firstWed = firstOfMonth.withDayOfWeek(MONTHS_IN_QUARTER);
    if (firstWed.isBefore(firstOfMonth)) {
        firstWed = firstWed.plusWeeks(1);
    }
    return firstWed.plusWeeks(2);
}

From source file:org.alexlg.bankit.controllers.AccountController.java

License:Open Source License

/**
 * Calculate the first day of the history. If the current day is after the 7th day of the month,
 * the return date will be the 1st of the current month. Otherwise, the return date
 * will be the 1st of the previous month.
 * @return First history day//from  w w w  .  j a v  a 2 s  .  com
 */
protected LocalDate calculateFirstHistoDay() {
    LocalDate date = new LocalDate();
    if (date.getDayOfMonth() > 7) {
        return date.withDayOfMonth(1);
    } else {
        return date.minusMonths(1).withDayOfMonth(1);
    }
}

From source file:org.alexlg.bankit.dao.CategoryDao.java

License:Open Source License

/**
 * Calculate the amount of operations for all categories on a specific month
 * @param yearMonth Year and month of the summary to calculate
 * @return Map containing the Category and the amount for the month
 *//*from www. ja  va  2s .co  m*/
public Map<Category, BigDecimal> getMonthSummary(YearMonth yearMonth) {
    CriteriaBuilder b = getBuilder();

    //SELECT PASSED OPERATION
    //create criteria and join
    CriteriaQuery<Tuple> q = b.createTupleQuery();
    Root<Operation> operation = q.from(Operation.class);
    //we left join to get operation with no categories
    Join<Operation, Category> category = operation.join(Operation_.category, JoinType.LEFT);

    //select
    //sum all amount operation for operation imported from the bank
    Expression<BigDecimal> sum = b.sum(operation.get(Operation_.amount));

    //sum only planned amount if the amount is not set (as we have a planned operation)
    //we use a sum(case when xx end) for that
    //in sql, it will be translated into : sum(case when o.amount is null then o.planned otherwise 0 end)
    Expression<BigDecimal> sumPlanned = b.sum(b.<BigDecimal>selectCase()
            .when(b.isNull(operation.get(Operation_.amount)), operation.get(Operation_.planned))
            .otherwise(BigDecimal.ZERO));

    //select the 3 fields into a tuple
    q.select(b.tuple(category, sum, sumPlanned));

    //where clause : between the start/end date, and for operation with no category, only < 0
    LocalDate startDate = yearMonth.toLocalDate(1);
    LocalDate endDate = startDate.withDayOfMonth(startDate.dayOfMonth().getMaximumValue());
    q.where(b.between(operation.get(Operation_.operationDate), startDate.toDate(), endDate.toDate()),
            b.or(b.isNotNull(operation.get(Operation_.category)), b.lt(operation.get(Operation_.amount), 0),
                    b.lt(operation.get(Operation_.planned), 0)));

    //group by
    q.groupBy(category.get(Category_.categoryId));

    //order by
    q.orderBy(b.asc(category.get(Category_.name)));

    //execute query
    List<Tuple> results = getEm().createQuery(q).getResultList();

    //put in map
    Map<Category, BigDecimal> resMap = new LinkedHashMap<Category, BigDecimal>(results.size());
    //saving null category for adding at the end
    BigDecimal noCatAmount = null;
    for (Tuple res : results) {
        Category resCat = res.get(category);

        BigDecimal sumVal = res.get(sum);
        BigDecimal sumPlannedVal = res.get(sumPlanned);
        if (sumVal == null)
            sumVal = BigDecimal.ZERO;
        if (sumPlannedVal == null)
            sumPlannedVal = BigDecimal.ZERO;
        BigDecimal sumTotal = sumVal.add(sumPlannedVal);

        if (!sumTotal.equals(BigDecimal.ZERO)) {
            if (resCat != null) {
                resMap.put(resCat, sumTotal);
            } else {
                noCatAmount = sumTotal;
            }
        }
    }

    //adding operation with no categories at the end of the list
    if (noCatAmount != null) {
        Category noCat = new Category();
        noCat.setCategoryId(-1);
        noCat.setName("");
        resMap.put(noCat, noCatAmount);
    }

    return resMap;
}