Example usage for org.joda.time LocalDate toDateTimeAtStartOfDay

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

Introduction

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

Prototype

public DateTime toDateTimeAtStartOfDay() 

Source Link

Document

Converts this LocalDate to a full datetime at the earliest valid time for the date using the default time zone.

Usage

From source file:com.receipts.backingbeans.StoreView.java

public void importStores(FileUploadEvent event) {
    int userId = (int) event.getComponent().getAttributes().get("userId");
    UploadedFile zipFile = event.getFile();

    String insertStoresSql = "insert into stores (store_id, store_date, user_id) values (?, ?, ?)";
    String selectStoresSql = "select id from stores where store_id = ? and store_date = ?";
    String insertReceiptsSql = "insert into receipts (store_fk, user_id, img_name) values (?, ?, ?)";
    try (Connection conn = DbUtils.getDbConnection()) {
        try (ZipInputStream zin = new ZipInputStream(new BufferedInputStream(zipFile.getInputstream()));
                PreparedStatement insertStoresPs = conn.prepareStatement(insertStoresSql);
                PreparedStatement selectStoresPs = conn.prepareStatement(selectStoresSql);
                PreparedStatement insertReceiptsPs = conn.prepareStatement(insertReceiptsSql)) {
            ZipEntry entry;//from   w w w. j  a  v a  2  s . co  m

            conn.setAutoCommit(false);

            while ((entry = zin.getNextEntry()) != null) {
                String entryName = entry.getName();
                boolean isDirectory = entry.isDirectory();

                if (isDirectory) {
                    String storeId = entryName.split("_")[0];
                    String storeDay = entryName.split("_")[1];
                    String storeMonth = entryName.split("_")[2];
                    String storeYear = entryName.split("_")[3].substring(0,
                            entryName.split("_")[3].length() - 1);

                    LocalDate storeDate = new LocalDate(Integer.parseInt(storeYear),
                            Integer.parseInt(storeMonth), Integer.parseInt(storeDay));

                    insertStoresPs.setString(1, storeId);
                    insertStoresPs.setDate(2,
                            new java.sql.Date(storeDate.toDateTimeAtStartOfDay().getMillis()));
                    insertStoresPs.setInt(3, userId);

                    insertStoresPs.executeUpdate();
                } else {
                    String storeData = entryName.split("/")[0];
                    String fileName = entryName.split("/")[1];

                    if (fileName.toLowerCase().endsWith(".jpg") || fileName.toLowerCase().endsWith(".jpeg")
                            || fileName.toLowerCase().endsWith(".png")
                            || fileName.toLowerCase().endsWith(".gif") || fileName.endsWith(".tiff")) {
                        String storeId = storeData.split("_")[0];
                        String storeDay = storeData.split("_")[1];
                        String storeMonth = storeData.split("_")[2];
                        String storeYear = storeData.split("_")[3];

                        LocalDate storeDate = new LocalDate(Integer.parseInt(storeYear),
                                Integer.parseInt(storeMonth), Integer.parseInt(storeDay));

                        selectStoresPs.setInt(1, Integer.parseInt(storeId));
                        selectStoresPs.setDate(2,
                                new java.sql.Date(storeDate.toDateTimeAtStartOfDay().getMillis()));

                        int storePK = -1;
                        try (ResultSet rs = selectStoresPs.executeQuery()) {
                            while (rs.next()) {
                                storePK = rs.getInt("id");
                            }
                        }

                        //                            insertReceiptsPs.setBlob(1, zin, entry.getSize());
                        insertReceiptsPs.setInt(1, storePK);
                        insertReceiptsPs.setInt(2, userId);
                        insertReceiptsPs.setString(3, fileName);

                        insertReceiptsPs.executeUpdate();
                    }
                }
            }

            conn.commit();

            allStores = storesService.loadAllStores();
            conn.setAutoCommit(true);
        } catch (Exception ex) {
            conn.rollback();
            conn.setAutoCommit(true);

            ex.printStackTrace();
        }
    } catch (SQLException e) {
        e.printStackTrace();
    }
}

From source file:com.rhythm.louie.pb.PBUtils.java

License:Apache License

static public DataTypeProtos.DatePB createDatePB(LocalDate date) {
    DataTypeProtos.DatePB.Builder builder = DataTypeProtos.DatePB.newBuilder();
    if (date != null) {
        builder.setTime(date.toDateTimeAtStartOfDay().getMillis());
    }// www .j  a v  a 2  s.  c  o m
    return builder.build();
}

From source file:com.stagecents.common.EffectiveDateInterval.java

License:Open Source License

/**
 * Creates a new EffectiveDateInterval from the given <code>LocalDate</code>
 * start and end dates. The <code>startDate</code> is converted to a
 * <code>DateTime</code> object by setting it to midnight (00:00) at the
 * start of the given day. The <code>endDate</code> is converted to a
 * <code>DateTime</code> object by setting it to midnight (00:00) of the day
 * following the given day.// w  w  w  . j  ava  2  s. c o m
 * <p>
 * If <code>startDate</code> is null, the start date of the
 * EffectiveDateInterval will be set to the beginning of time. If
 * <code>endDate</code> is null, the end date of the EffectiveDateInterval
 * will be set to the end of time.
 * 
 * @param startDate The date on which the EffectiveDateInterval becomes
 *            effective.
 * @param endDate The date after which the EffectiveDateInterval is no
 *            longer effective or the end of time if null.
 * @see http://www.joda.org/joda-time/key_partial.html
 */
public EffectiveDateInterval(LocalDate startDate, LocalDate endDate) {
    if (startDate != null) {
        // Convert start day to midnight
        this.startDate = startDate.toDateTimeAtStartOfDay();
    } else {
        this.startDate = new DateTime(0);
    }
    if (endDate != null) {
        this.endDate = endDate.plusDays(1).toDateTimeAtStartOfDay();
    } else {
        this.endDate = new DateTime(Long.MAX_VALUE);
    }
}

From source file:de.appsolve.padelcampus.admin.controller.reports.AdminReportsUtilizationController.java

private ModelAndView getIndexView(DateRange dateRange) throws JsonProcessingException {
    ModelAndView mav = new ModelAndView("admin/reports/utilization/index");
    List<Booking> bookings = bookingDAO.findBlockedBookingsBetween(dateRange.getStartDate(),
            dateRange.getEndDate());/*from   w  w w. j  av a 2  s.  co  m*/

    Map<Long, Integer> map = new TreeMap<>();
    for (Booking booking : bookings) {
        LocalDate date = booking.getBookingDate();
        Long millis = date.toDateTimeAtStartOfDay().getMillis();
        Integer count = map.get(millis);
        if (count == null) {
            count = 1;
        } else {
            count++;
        }
        map.put(millis, count);
    }

    mav.addObject("chartData", objectMapper.writeValueAsString(map));
    mav.addObject("DateRange", dateRange);

    return mav;
}

From source file:de.appsolve.padelcampus.controller.ranking.RankingController.java

@RequestMapping("{participantUUID}/history")
public ModelAndView getRankingHistory(@PathVariable() String participantUUID) throws JsonProcessingException {
    Participant participant = participantDAO.findByUUID(participantUUID);
    if (participant == null) {
        throw new ResourceNotFoundException();
    }//  ww w  .j  a va 2 s.  co m

    LocalDate endDate = LocalDate.now();
    LocalDate startDate = endDate.minusDays(365);
    Map<Gender, Map<Long, BigDecimal>> genderDateRankingMap = new TreeMap<>();
    for (Gender gender : EnumSet.of(Gender.male, Gender.female, Gender.unisex)) {
        List<Ranking> rankings = rankingUtil.getPlayerRanking(gender, participant, startDate, endDate);
        if (rankings != null && !rankings.isEmpty()) {
            Map<Long, BigDecimal> dateRankingMap = new TreeMap<>();
            for (Ranking ranking : rankings) {
                LocalDate date = ranking.getDate();
                Long millis = date.toDateTimeAtStartOfDay().getMillis();
                dateRankingMap.put(millis, ranking.getValue().setScale(0, RoundingMode.HALF_UP));
            }
            genderDateRankingMap.put(gender, dateRankingMap);
        }
    }
    ModelAndView mav = new ModelAndView(getPath() + "ranking/history");
    mav.addObject("Participant", participant);
    mav.addObject("GenderDateRankingMap", genderDateRankingMap);
    mav.addObject("ChartMap", objectMapper.writeValueAsString(genderDateRankingMap));
    return mav;
}

From source file:de.iteratec.iteraplan.presentation.dialog.History.HistoryController.java

License:Open Source License

/**
 * URL Handler method that returns an HTML view of the history of one building block, narrowed down by provided criteria
 * @param bbId Building Block ID/*from  www.  ja  va  2s .co m*/
 * @param bbType Building Block type code, which can be decoded by {@link TypeOfBuildingBlock#fromInitialCapString(String)}
 * @param page The number of the page to return, depending on {@code pageSize}. Zero-based. May be {@code null}, in which case the default value 0 is used.
 * @param pageSize The number of history events on the returned page. -1 is interpreted as "everything". May be {@code null}, in which case the default value -1 is used.
 * @param dateFromStr The start date of the time range to filter history events for. This is expected to be in ISO date format (pattern yyyy-MM-dd)!
 * @param dateToStr The end date (inclusive) of the time range to filter history events for. This is expected to be in ISO date format (pattern yyyy-MM-dd)!
 */
@SuppressWarnings("boxing")
@RequestMapping
public ModelAndView localHistory(@RequestParam(value = "id", required = true) String bbId,
        @RequestParam(value = "buildingBlockType", required = true) String bbType,
        @RequestParam(value = "page", required = false) String page,
        @RequestParam(value = "pageSize", required = false) String pageSize,
        @RequestParam(value = "dateFrom", required = false) String dateFromStr,
        @RequestParam(value = "dateTo", required = false) String dateToStr) {

    ModelAndView modelAndView = new ModelAndView("history/local");

    // Check if user may see history, and note so JSP can show a nice error. If not, return
    Boolean hasPermission = Boolean.valueOf(UserContext.getCurrentPerms().getUserHasFuncPermViewHistory());
    modelAndView.addObject("isHasViewHistoryPermission", hasPermission);
    if (!hasPermission.booleanValue()) {
        return modelAndView;
    }

    int id = parseInt(bbId, -1);

    // Default to showing page 0 (first page), if unspecified
    int curPage = parseInt(page, 0);
    // current page must not be negative
    curPage = Math.max(curPage, 0);

    // Default -1 means infinite results Per Page
    int pageSizeInt = parseInt(pageSize, -1);
    // make sure it's not 0, /0 error later; and make all values < -1 turn into -1
    if (pageSizeInt <= 0) {
        pageSizeInt = -1;
    }

    DateTimeFormatter isoDateFormatter = ISODateTimeFormat.date();
    DateTime dateFrom = null;
    DateTime dateTo = null;
    if (StringUtils.isNotEmpty(dateFromStr)) {
        try {
            LocalDate date = LocalDate.parse(dateFromStr, isoDateFormatter);
            dateFrom = date.toDateTimeAtStartOfDay();
        } catch (IllegalArgumentException ex) {
            // invalid date format, ignore
        }
    }

    if (StringUtils.isNotEmpty(dateToStr)) {
        try {
            // assumption: we parsed from a date with no time which gave us the beginning of that day, but
            // we want to include the whole day, so add 1 day
            LocalDate date = LocalDate.parse(dateToStr, isoDateFormatter).plusDays(1);
            dateTo = date.toDateTimeAtStartOfDay();
        } catch (IllegalArgumentException ex) {
            // invalid date format, ignore
        }
    }

    HistoryResultsPage resultsPage;
    try {
        resultsPage = historyService.getLocalHistoryPage(getClassFromTypeString(bbType), id, curPage,
                pageSizeInt, dateFrom, dateTo);
    } catch (Exception e) {
        throw new IteraplanTechnicalException(IteraplanErrorMessages.HISTORY_RETRIEVAL_GENERAL_ERROR, e);
    }
    assert resultsPage != null;

    modelAndView.addObject("resultsPage", resultsPage);
    modelAndView.addObject("isHistoryEnabled", Boolean.valueOf(historyService.isHistoryEnabled()));

    return modelAndView;
}

From source file:de.sub.goobi.persistence.managers.ProcessMysqlHelper.java

License:Open Source License

public static void saveBatch(Batch batch) throws SQLException {
    Connection connection = null;
    Timestamp start = null;//  ww w. j a v  a2  s. c  o m
    Timestamp end = null;

    if (batch.getStartDate() != null) {
        LocalDate localDate = new LocalDate(batch.getStartDate());
        start = new Timestamp(localDate.toDateTimeAtStartOfDay().getMillis());

    }

    if (batch.getEndDate() != null) {
        LocalDate localDate = new LocalDate(batch.getEndDate());
        end = new Timestamp(localDate.toDateTimeAtStartOfDay().getMillis());
    }

    if (batch.getBatchId() == null) {
        StringBuilder sql = new StringBuilder();
        sql.append("INSERT INTO batches (batchName, startDate, endDate) VALUES (?,?,?)");
        try {
            connection = MySQLHelper.getInstance().getConnection();
            QueryRunner run = new QueryRunner();
            Integer id = run.insert(connection, sql.toString(), MySQLHelper.resultSetToIntegerHandler,
                    batch.getBatchName(), start, end);
            if (id != null) {
                batch.setBatchId(id);
            }
        } finally {
            if (connection != null) {
                MySQLHelper.closeConnection(connection);
            }
        }

    } else {
        StringBuilder sql = new StringBuilder();
        sql.append("UPDATE batches set batchName = ?, startDate = ?, endDate= ? where id = ?");
        try {
            connection = MySQLHelper.getInstance().getConnection();
            QueryRunner run = new QueryRunner();
            run.update(connection, sql.toString(), batch.getBatchName(), start, end, batch.getBatchId());
        } finally {
            if (connection != null) {
                MySQLHelper.closeConnection(connection);
            }
        }

    }

}

From source file:dom.regulation.Regulations.java

License:Apache License

@Programmatic
boolean isInPast(final LocalDate someDate) {
    return someDate.toDateTimeAtStartOfDay().getMillis() < clockService.nowAsMillis();
}

From source file:dom.todo.ToDoItems.java

License:Apache License

@Programmatic
boolean isMoreThanOneWeekInPast(final LocalDate dueBy) {
    return dueBy.toDateTimeAtStartOfDay().getMillis() < clockService.nowAsMillis() - ONE_WEEK_IN_MILLIS;
}

From source file:energy.usef.agr.workflow.nonudi.service.PowerMatcher.java

License:Apache License

/**
 * Returns a interval ({@link String}) based on the date, ptuIndex, ptuDuration and number of ptus. For example:
 * "2015-05-01T13:00:00Z/2015-05-01T14:00:00Z". This time format is compatible with the PowerMatcher.
 *
 * @param date//from   ww w .ja  v a  2s.  c  o m
 * @param ptuIndex
 * @param ptuDuration
 * @param numberOfPtus
 * @return
 */
public static String getInterval(LocalDate date, int ptuIndex, int ptuDuration, int numberOfPtus) {
    LocalDateTime start = date.toDateTimeAtStartOfDay().toLocalDateTime()
            .plusMinutes((ptuIndex - 1) * ptuDuration);
    LocalDateTime end = start.plusMinutes(numberOfPtus * ptuDuration).minusSeconds(1);

    DateTime startDateTime = start.toDateTime().toDateTime(DateTimeZone.UTC);
    DateTime endDateTime = end.toDateTime().toDateTime(DateTimeZone.UTC);
    return startDateTime.toString(POWER_MATCHER_TIME_FORMAT) + "/"
            + endDateTime.toString(POWER_MATCHER_TIME_FORMAT);
}