List of usage examples for java.util Date before
public boolean before(Date when)
From source file:gov.nih.nci.ncicb.tcga.dcc.dam.dao.usage.UsageLoggerFileImpl.java
/** * If start date and end date are null, returns all sessions. If start date is null, returns all sessions from * first recorded until end date. If end date is null, returns all sessions since start date. * * @return a List of all UsageSessions that have been recorded between start and end date * @throws UsageLoggerException if there is an error * @param startDate the start date, or null * @param endDate the end date, or null//from www .j av a2 s . c o m */ public List<UsageSession> getAllSessionsForDates(Date startDate, Date endDate) throws UsageLoggerException { List<UsageSession> sessions = new ArrayList<UsageSession>(); BufferedReader logFile = null; try { //noinspection IOResourceOpenedButNotSafelyClosed logFile = new BufferedReader(new FileReader(getFile())); String line = logFile.readLine(); Pattern actionPattern = Pattern.compile("^\\[(.+)\\](.+)=(.*)@(.+)$"); UsageSession currentSession = null; while (line != null) { Matcher m = actionPattern.matcher(line); if (m.matches()) { String sessionId = m.group(1); String actionName = m.group(2); String value = m.group(3); String dateString = m.group(4); Date date = getDateFormat().parse(dateString); boolean include = true; if (startDate != null && date.before(startDate)) { include = false; } if (endDate != null && date.after(startDate)) { include = false; } if (include) { if (currentSession == null || !sessionId.equals(currentSession.sessionKey)) { currentSession = new UsageSession(); sessions.add(currentSession); } UsageSessionAction action = new UsageSessionAction(); action.name = actionName; action.value = value; action.actionTime = date; currentSession.actions.add(action); } } line = logFile.readLine(); } } catch (FileNotFoundException e) { throw new UsageLoggerException("Could not open usage log", e); } catch (IOException e) { throw new UsageLoggerException("Error reading log", e); } catch (ParseException e) { throw new UsageLoggerException("Error parsing date in log", e); } finally { IOUtils.closeQuietly(logFile); } return sessions; }
From source file:com.autentia.tnt.manager.holiday.UserHolidaysStateManager.java
/** * @return Devuelve el nmero de das laborables que hay entre dos fechas *//* www .j a v a2 s . c o m*/ public int getWorkingDays(Date fromDate, Date toDate) { int total = 0; // Evitamos un bucle infinito en el bucle que viene a continuacin if (fromDate.before(toDate) || DateUtils.isSameDay(fromDate, toDate)) { HolidaySearch fiestaSearch = new HolidaySearch(); Date current = (Date) fromDate.clone(); fiestaSearch.setStartDate(fromDate); fiestaSearch.setEndDate(toDate); List<Holiday> fiestas = HolidayManager.getDefault().getAllEntities(fiestaSearch, null); while (current.before(toDate) || DateUtils.isSameDay(current, toDate)) { if (!this.isHoliday(fiestas, current)) { total++; } current = DateUtils.addDays(current, 1); } } return total; }
From source file:com.jiwhiz.domain.account.UserAccountRepositoryTest.java
@Test public void testAuditing() { // create account UserAccount account = new UserAccount(); account.setUserId(userId1);// w w w . ja v a2 s.com account.setRoles(new UserRoleType[] { UserRoleType.ROLE_ADMIN, UserRoleType.ROLE_AUTHOR }); account.setDisplayName("John"); accountRepository.save(account); String id = account.getId(); assertTrue(accountRepository.exists(id)); // read UserAccount accountInDb = accountRepository.findOne(id); assertEquals(JiwhizBlogRepositoryTestApplication.TEST_AUDITOR, accountInDb.getCreatedBy()); assertNotNull(accountInDb.getCreatedTime()); assertEquals(JiwhizBlogRepositoryTestApplication.TEST_AUDITOR, accountInDb.getLastModifiedBy()); assertNotNull(accountInDb.getLastModifiedTime()); // update Date updatedTimeBefore = accountInDb.getLastModifiedTime(); String newWebSite = "www.hello.com"; account.setWebSite(newWebSite); accountRepository.save(account); accountInDb = accountRepository.findOne(id); assertTrue(updatedTimeBefore.before(accountInDb.getLastModifiedTime())); }
From source file:com.cemeterylistingsweb.services.impl.ViewListingBySubscriberServiceImpl.java
@Override public List<PublishedDeceasedListing> findListingBySubscriber(Long subID) { List<PublishedDeceasedListing> publists = publishRepo.findAll(); //find listing by dob Subscriber sub = SubscrRepo.findOne(subID); List<PublishedDeceasedListing> list = new ArrayList(); for (PublishedDeceasedListing pubListing : publists) { SimpleDateFormat format = new SimpleDateFormat("dd/MM/yyyy"); Date parsed = null;/*from ww w. j a va 2s. c om*/ try { parsed = format.parse(pubListing.getDateOfDeath()); } catch (ParseException ex) { Logger.getLogger(ViewListingBySubscriberServiceImpl.class.getName()).log(Level.SEVERE, null, ex); } java.sql.Date dod = new java.sql.Date(parsed.getTime()); //Date dod = new SimpleDateFormat("MMMM d, yyyy", Locale.ENGLISH).parse(pubListing.getDateOfDeath()); System.out.println(dod); if (dod.after(sub.getSubscriptionDate()) && dod.before(sub.getValidUntil())) System.out.println(dod); System.out.println("added" + ""); list.add(pubListing); } return list; }
From source file:com.salesmanager.core.module.impl.application.files.LocalFileImpl.java
public InputStream getFileInputStream(HttpServletRequest request) throws Exception { // parse token String fileid = request.getParameter("fileId"); Map fileInfo = FileUtil.getFileDownloadFileTokens(fileid); String fileId = (String) fileInfo.get("ID"); String date = (String) fileInfo.get("DATE"); String merchantId = (String) fileInfo.get("MERCHANTID"); // Compare the date Date today = new Date(); DateFormat d = new SimpleDateFormat("yyyy-MM-dd"); Date dt = null; dt = d.parse(date);// w w w .jav a2s . c om if (dt.before(new Date(today.getTime()))) { // expired CoreException excpt = new CoreException(ErrorConstants.DELAY_EXPIRED); throw excpt; // String lbl = // LabelUtil.getInstance().getText("message.error.download.delayexpired1"); } OrderService oservice = (OrderService) ServiceFactory.getService(ServiceFactory.OrderService); OrderProductDownload download = oservice.getOrderProductDownload(new Long(fileId)); this.setFileName(download.getOrderProductFilename()); int maxcount = conf.getInt("core.product.file.downloadmaxcount", 5); // String filename = ""; FileHistory fh = oservice.getFileHistory(Integer.parseInt(merchantId), download.getFileId()); if (fh == null) { log.warn("Trying to update non existing file history [attrid " + download.getFileId() + "][merchantid " + merchantId + "]"); } else { int downloadcount = fh.getDownloadCount(); int newcount = downloadcount + 1; fh.setDownloadCount(newcount); oservice.saveOrUpdateFileHistory(fh); } int downloadcount = download.getDownloadCount(); if (downloadcount == maxcount) { OrderException oe = new OrderException("Maximum download reached", ErrorConstants.MAXIMUM_ORDER_PRODUCT_DOWNLOAD_REACHED); throw oe; } int newcount = downloadcount + 1; download.setDownloadCount(newcount); oservice.saveOrUpdateOrderProductDownload(download); //String downloadPath = conf.getString("core.product.file.filefolder"); String downloadPath = FileUtil.getDownloadFilePath(); File file = new File(downloadPath + "/" + merchantId + "/" + download.getOrderProductFilename()); BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file)); return bis; }
From source file:se.inera.axel.shs.broker.agreement.mongo.MongoAgreementService.java
private void isValidNow(ShsAgreement agreement) { General general = agreement.getGeneral(); if (general == null) return;// ww w . j a va2 s .co m Valid valid = general.getValid(); if (valid == null) return; ValidFrom validFrom = valid.getValidFrom(); Date fromDate = validFrom == null ? null : validFrom.getDate(); ValidTo validTo = agreement.getGeneral().getValid().getValidTo(); Date toDate = validTo == null ? null : validTo.getDate(); Date today = new Date(); if ((fromDate != null && today.before(fromDate)) || (toDate != null && today.after(toDate))) { throw new IllegalAgreementException("the current time is outside validity period of agreement"); } }
From source file:be.fedict.eid.pkira.common.util.FilterHelperBean.java
@Override public boolean filterByDate(Date actualDate, Date dateFrom, Date dateTo) { if (dateFrom != null) { dateFrom = changeTime(dateFrom, 0, 0, 0); if (dateFrom.after(actualDate)) { return false; }// www . j ava 2 s . c o m } if (dateTo != null) { dateTo = changeTime(dateTo, 23, 59, 59); if (dateTo.before(actualDate)) { return false; } } return true; }
From source file:com.netcracker.tss.web.servlet.customer.CustomerMMGServiceServlet.java
/** * Handles the HTTP <code>POST</code> method. * * @param request servlet request//w w w .j a v a2s . com * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("UTF-8"); try { if (request.getParameter("addFrom") != null) { addAddressFrom(request); response.sendRedirect("/customer/orderpage"); } else if (request.getParameter("addTo") != null) { addAddressTo(request); response.sendRedirect("/customer/orderpage"); } else if (request.getParameter("deleteTo") != null || request.getParameter("deleteFrom") != null) { deleteAddress(request); response.sendRedirect("/customer/orderpage"); } else { Date bookingTime = new Date(); Date orderTime = DateParser.parseDate(request); if (orderTime.before(bookingTime)) { request.setAttribute("errorMessage", "It is impossible to order taxi at the past! Please input the correct order time."); redirectToTaxiOrder(request, response); // req.getRequestDispatcher("/customer/orderpage").forward(req, resp); // resp.sendRedirect("/customer/orderpage?err=It is impossible to order taxi at the past! Please input the correct order time."); } else { User user = findCurrentUser(); MeetMyGuestBeanLocal myGuestBeanLocal = getMeetMyGuestBean(request); TaxiOrderBeanLocal taxiOrderBeanLocal = getTaxiOrderBean(request); PriceBeanLocal priceBean = getPriceBean(request); float distance = 0; double price = 0; Route route = new Route(findCurrentUser().getUsername() + " Route"); route.setDistance(distance); Address addFrom = toAddress(request.getParameter("fromAddr"), request); Address addTo = toAddress(request.getParameter("toAddr"), request); TaxiOrder taxiOrder = new TaxiOrder(AdditionalParameters.taxiOrderAddParameters(request)); MapBeanLocal mapBean = getMapBean(request); distance = mapBean.calculateDistance(request.getParameter("fromAddr"), request.getParameter("toAddr")); price = priceBean.calculatePrice(distance, DateParser.parseDate(request), taxiOrder, UserUtils.findCurrentUser()); taxiOrder.setBookingTime(bookingTime); taxiOrder.setOrderTime(orderTime); taxiOrder.setPrice(price); String guestName = request.getParameter("guestName"); myGuestBeanLocal.addMeetMyGuestService(user, route, addFrom, addTo, taxiOrder, guestName); int latestTOId = taxiOrderBeanLocal.getTaxiOrderHistory(1, 1, user).get(0).getId(); request.setAttribute("taxiOrderId", latestTOId); request.setAttribute("pageContent", "content/confirmation.jsp"); request.getRequestDispatcher("/WEB-INF/views/customer/customer-template.jsp").forward(request, response); } } } catch (Exception e) { Logger.getLogger(CustomerSoberServiceServlet.class.getName()).log(Level.SEVERE, e.getMessage(), e); request.setAttribute("errorMessage", "Sorry, we can not make this order! Please, check all input parameters ad try again."); redirectToTaxiOrder(request, response); // response.sendRedirect( // "/customer/mmgServicePage?err=Sorry, we can not make this order! Please, check all input parameters ad try again."); } }
From source file:com.vmware.identity.util.TimePeriod.java
/** * * @param pointOfTime//from ww w . ja v a 2 s. c o m * cannot be null * @return if given pointOfTime is in this time period. If this period has * start and end times this point of time can match with start time * but not with end time, meaning if start and end times are not null * the point of time is compared to this interval inclusive the start * time, exclusive the end time. */ public boolean contains(Date pointOfTime) { Validate.notNull(pointOfTime); boolean result = true; if (startTime != null) { result &= (pointOfTime.compareTo(startTime) >= 0); } if (endTime != null) { result &= pointOfTime.before(endTime); } return result; }
From source file:net.audumla.climate.bom.BOMHistoricalClimateObserver.java
synchronized public ClimateData getClimateData(Date date) { if (!invalidMonths.contains(Time.getMonthAndYear(date))) { if (!date.before(Time.getToday())) { throw new UnsupportedOperationException("JulianDate requested is in the future"); }/*from w ww . jav a 2 s . com*/ try { if (date.after(source.getLastRecord())) { throw new UnsupportedOperationException("JulianDate requested is after the last record"); } } catch (Exception ignored) { } ClimateData data = null; try { Date dayDate = yearMonthDay.parse(yearMonthDay.format(date)); data = historicalData.get(dayDate); if (data == null) { if (loadStationData(source.getId(), date)) { data = historicalData.get(dayDate); } } } catch (ParseException ignored) { } if (data != null) { return data; } } invalidMonths.add(Time.getMonthAndYear(date)); throw new UnsupportedOperationException("Cannot locate historical data " + yearMonthDay.format(date) + " for for station - " + source.getId()); }