Example usage for org.joda.time LocalDate plusDays

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

Introduction

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

Prototype

public LocalDate plusDays(int days) 

Source Link

Document

Returns a copy of this date plus the specified number of days.

Usage

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

License:Apache License

/**
 * Delete all {@link MessageError}s for a certain date.
 *
 * @param period/* w  w  w. j ava 2s  .c o m*/
 * @return the number of {@link MessageError}s deleted.
 */
public int cleanup(LocalDate period) {
    LocalDate endDate = period.plusDays(1);

    Date start = new Date(period.toDateMidnight().getMillis());
    Date end = new Date(endDate.toDateMidnight().getMillis());

    StringBuilder sql = new StringBuilder();
    sql.append("DELETE FROM MessageError me ");
    sql.append(
            "WHERE me.message IN (SELECT m FROM Message m WHERE m.creationTime >= :start AND m.creationTime < :end)");

    return entityManager.createQuery(sql.toString()).setParameter("start", start).setParameter("end", end)
            .executeUpdate();
}

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

License:Apache License

/**
 * Delete all {@link Message}s created on a certain date.
 *
 * @param period/*ww  w. jav  a  2s  .co  m*/
 * @return the number of {@link Message}s deleted.
 */
public int cleanup(LocalDate period) {
    LocalDate endDate = period.plusDays(1);

    Date start = new Date(period.toDateMidnight().getMillis());
    Date end = new Date(endDate.toDateMidnight().getMillis());
    StringBuilder sql = new StringBuilder();
    sql.append("DELETE FROM Message m WHERE m.creationTime >= :start AND m.creationTime < :end");

    return entityManager.createQuery(sql.toString()).setParameter("start", start, TIMESTAMP)
            .setParameter("end", end, TIMESTAMP).executeUpdate();
}

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

License:Apache License

/**
 * Delete all {@link SignedMessageHash}s for a certain date.
 *
 * @param period//from w w  w  .j av a 2s .  co m
 * @return the number of {@link SignedMessageHash}s deleted.
 */
public int cleanup(LocalDate period) {
    LocalDate endDate = period.plusDays(1);

    Date start = new Date(period.toDateMidnight().getMillis());
    Date end = new Date(endDate.toDateMidnight().getMillis());

    String sql = "DELETE FROM SignedMessageHash o WHERE o.creationTime >= :start AND o.creationTime < :end";
    return entityManager.createQuery(sql).setParameter("start", start).setParameter("end", end).executeUpdate();
}

From source file:energy.usef.core.service.business.CorePlanboardBusinessService.java

License:Apache License

private void createConnectionGroupState(String connection, String congestionPoint,
        Map<String, CongestionPoint> congestionPointToCongestionPoint, LocalDate initializationDate,
        Integer validityDuration) {
    LOGGER.debug("Creating new ConnectionGroupState for [{}/{}] from [{}] until [{}].", congestionPoint,
            connection, initializationDate, initializationDate.plusDays(validityDuration));
    createGroupState(//from ww w. j ava 2s  .  c  o m
            congestionPointConnectionGroupRepository.findOrCreate(congestionPoint,
                    congestionPointToCongestionPoint.get(congestionPoint).getDSODomain()),
            connection, initializationDate, validityDuration);
}

From source file:energy.usef.core.service.business.CorePlanboardBusinessService.java

License:Apache License

private void storeConnections(CommonReferenceQueryResponse message, USEFRole selfRole,
        LocalDate initializationDate, Integer validityDuration) {
    // declaration of the function which uses the right ConnectionGroupRepository to find or create ConnectionGroup
    final Function<String, ConnectionGroup> connectionGroupFinder = (USEFRole.AGR == selfRole)
            ? brpConnectionGroupRepository::findOrCreate
            : agrConnectionGroupRepository::findOrCreate;

    final Function<USEFRole, Class<? extends ConnectionGroup>> connectionGroupClassFinder = usefRole -> (usefRole == USEFRole.AGR)
            ? BrpConnectionGroup.class
            : AgrConnectionGroup.class;

    // declaration of the function which uses the AGR domain or the BRP domain of the connection to determine the usef
    // identifier of the ConnectionGroup.
    final Function<energy.usef.core.data.xml.bean.message.Connection, String> usefIdentifierProvider = USEFRole.AGR == selfRole
            ? Connection::getBRPDomain
            : Connection::getAGRDomain;

    List<ConnectionGroupState> currentConnectionGroupStates = connectionGroupStateRepository
            .findActiveConnectionGroupStatesOfType(initializationDate,
                    connectionGroupClassFinder.apply(selfRole));

    Map<String, energy.usef.core.data.xml.bean.message.Connection> messageConnections = message.getConnection()
            .stream().collect(Collectors.toMap(Connection::getEntityAddress, Function.identity()));

    List<ConnectionGroupState> connectionGroupStatesToExtend = connectionGroupStateRepository
            .findEndingConnectionGroupStates(initializationDate,
                    selfRole == USEFRole.AGR ? BrpConnectionGroup.class : AgrConnectionGroup.class)
            .stream()/*w  w w  . ja  va  2  s . c  om*/
            .filter(cgs -> messageConnections.entrySet().stream()
                    .anyMatch(entry -> entry.getKey().equals(cgs.getConnection().getEntityAddress())
                            && cgs.getConnectionGroup().getUsefIdentifier()
                                    .equals(usefIdentifierProvider.apply(entry.getValue()))))
            .collect(Collectors.toList());

    // extend the connection group states to extend
    connectionGroupStatesToExtend.stream().forEach(cgs -> {
        LOGGER.debug("Extending VALID_UNTIL of [{}/{}] from [{}] to [{}].",
                cgs.getConnectionGroup().getUsefIdentifier(), cgs.getConnection().getEntityAddress(),
                cgs.getValidUntil(), cgs.getValidUntil().plusDays(validityDuration));
        cgs.setValidUntil(cgs.getValidUntil().plusDays(validityDuration));
    });

    // create new records for connections of the message that are not part of the connection groups to extend.
    messageConnections.entrySet().stream().filter(entry -> connectionGroupStatesToExtend.stream().noneMatch(
            cgs -> cgs.getConnection().getEntityAddress().equals(entry.getKey()) && cgs.getConnectionGroup()
                    .getUsefIdentifier().equals(usefIdentifierProvider.apply(entry.getValue()))))
            .filter(entry -> currentConnectionGroupStates.stream()
                    .noneMatch(cgs -> cgs.getConnection().getEntityAddress().equals(entry.getKey())))
            .forEach(entry -> {
                LOGGER.trace("Creating new ConnectionGroupState for [{}/{}] valid from [{}] until [{}].",
                        usefIdentifierProvider.apply(entry.getValue()), entry.getKey(), initializationDate,
                        initializationDate.plusDays(validityDuration));
                createGroupState(connectionGroupFinder.apply(usefIdentifierProvider.apply(entry.getValue())),
                        entry.getKey(), initializationDate, validityDuration);
            });
}

From source file:energy.usef.core.service.business.CorePlanboardBusinessService.java

License:Apache License

private void createGroupState(ConnectionGroup connectionGroup, String connectionEntityAddress,
        LocalDate modificationDate, Integer validityDuration) {
    // find or create Connection.
    energy.usef.core.model.Connection connection = connectionRepository.findOrCreate(connectionEntityAddress);

    // create new state
    ConnectionGroupState newConnectionGroupState = new ConnectionGroupState();
    newConnectionGroupState.setConnection(connection);
    newConnectionGroupState.setConnectionGroup(connectionGroup);
    newConnectionGroupState.setValidFrom(modificationDate);
    newConnectionGroupState.setValidUntil(modificationDate.plusDays(validityDuration));
    connectionGroupStateRepository.persist(newConnectionGroupState);
}

From source file:energy.usef.core.service.validation.CorePlanboardValidatorService.java

License:Apache License

/**
 * Verify whether PTU Container is within IntradayGateClosureTime.
 *
 * @param ptuContainer PTU Container//  w w w .  j  av  a 2 s  .com
 * @return true if the PTU Container is within IntradayGateClosureTime, false otherwise
 */
public boolean isPtuContainerWithinIntradayGateClosureTime(PtuContainer ptuContainer) {
    Integer gateClosure = config.getIntegerProperty(ConfigParam.INTRADAY_GATE_CLOSURE_PTUS);
    Integer ptuDuration = config.getIntegerProperty(ConfigParam.PTU_DURATION);
    LocalDateTime todayNow = DateTimeUtil.getCurrentDateTime();
    Integer ptusToday = PtuUtil.getNumberOfPtusPerDay(todayNow.toLocalDate(), ptuDuration);
    Integer minutesToday = DateTimeUtil.getElapsedMinutesSinceMidnight(todayNow);

    Integer ptuIndexPivot = 1 + gateClosure + minutesToday / ptuDuration;
    LocalDate ptuDatePivot = todayNow.toLocalDate();

    if (ptuIndexPivot > ptusToday) {
        ptuIndexPivot = ptuIndexPivot % ptusToday;
        ptuDatePivot = ptuDatePivot.plusDays(1);
    }

    int ptuDateComparedToDatePivot = new LocalDate(ptuContainer.getPtuDate()).compareTo(ptuDatePivot);
    if (ptuDateComparedToDatePivot == 1) {
        // PTU date is the one day after the current limit, no problem
        return false;
    } else if (ptuDateComparedToDatePivot == 0 && ptuContainer.getPtuIndex().compareTo(ptuIndexPivot) == 1) {
        // PTU date is the same day as the limit but the PTU index is after the index limit, no problem
        return false;
    }
    // PTU date is the same day (or before) and the PTU index is the same or before the index limit, problem
    return true;
}

From source file:energy.usef.core.util.DateTimeUtil.java

License:Apache License

/**
 * Calculate the number of minutes of a specific date. Only the date part (year, month and day) is used to calculate the number
 * of minutes. The number of minutes is calculated from midnight to midnight the next day. For a default day this method return
 * 24 * 60 = 1440. If on this day a summer- or wintertime switch occurs, the number of minutes are different.
 *
 * @param date the date time which includes the timezone. When setting the DateTime with the default constructor, the
 * default timezone where the application runs, is used.
 * @return the number of minutes for the day (date part) of the dateTime parameter.
 *///from  w ww  .  ja va 2s.  c o  m
public static Integer getMinutesOfDay(LocalDate date) {
    Duration duration = new Interval(date.toDateMidnight(), date.plusDays(1).toDateMidnight()).toDuration();
    return (int) duration.getStandardSeconds() / SECONDS_PER_MINUTE;
}

From source file:energy.usef.dso.controller.CommonReferenceQueryResponseController.java

License:Apache License

/**
 * Initialize the PTU containers./*  w  w  w .j  av  a2  s  .  c o m*/
 *
 * @param initializationDate
 * @param initializationDuration
 */
private void initializePtuContainers(LocalDate initializationDate, Integer initializationDuration) {
    // initialize the PTU containers
    for (int i = 0; i < initializationDuration; ++i) {
        List<PtuContainer> ptuContainers = corePlanboardBusinessService
                .findOrCreatePtuContainersForPeriod(initializationDate.plusDays(i));
        List<ConnectionGroupState> activeConnectionGroupStates = corePlanboardBusinessService
                .findActiveConnectionGroupStates(initializationDate.plusDays(i),
                        CongestionPointConnectionGroup.class);
        activeConnectionGroupStates.stream().map(ConnectionGroupState::getConnectionGroup).distinct()
                .forEach(connectionGroup -> ptuContainers.stream()
                        .forEach(ptuContainer -> createPtuState(ptuContainer, connectionGroup)));
    }
}

From source file:energy.usef.dso.repository.ConnectionMeterEventRepository.java

License:Apache License

/**
 * This method finds all ConnectionMeterEvents for a certain period that where active in that period.
 *
 * @param fromDate from date/*from   w w  w  . j a va2s .com*/
 * @param endDate end date
 * 
 * @return connection meter event list
 */
@SuppressWarnings("unchecked")
public List<ConnectionMeterEvent> findConnectionMeterEventsForPeriod(LocalDate fromDate, LocalDate endDate) {
    StringBuilder queryString = new StringBuilder();
    queryString.append("SELECT cme FROM ConnectionMeterEvent cme ");
    queryString.append(" WHERE cme.dateTime >= :fromDate ");
    // it is inclusive because i add a day to the endDate
    queryString.append("  AND cme.dateTime < :endDate ");

    Query query = getEntityManager().createQuery(queryString.toString());
    query.setParameter("fromDate", fromDate.toDateMidnight().toDateTime().toDate(), TemporalType.TIMESTAMP);
    query.setParameter("endDate", endDate.plusDays(1).toDateMidnight().toDateTime().toDate(),
            TemporalType.TIMESTAMP);

    return query.getResultList();
}