List of usage examples for java.util Date before
public boolean before(Date when)
From source file:com.rogchen.common.xml.UtilDateTime.java
public static Boolean currentDateDeviationIsThisRange(Date date, int senconds) { Calendar cuurnetCalendar1 = Calendar.getInstance(); cuurnetCalendar1.setTime(date);/*w ww . ja va 2s .c om*/ cuurnetCalendar1.add(Calendar.SECOND, senconds); Calendar cuurnetCalendar2 = Calendar.getInstance(); cuurnetCalendar2.setTime(date); cuurnetCalendar2.add(Calendar.SECOND, -senconds); Date currentDate = new Date(); return currentDate.after(cuurnetCalendar2.getTime()) && currentDate.before(cuurnetCalendar1.getTime()); }
From source file:gov.nih.nci.firebird.service.annual.registration.AnnualRegistrationServiceBean.java
private boolean isCurrentDateAfterDueDateAndWithinRenewalRange(Date dueDate) { Date now = new Date(); Date boundaryDate = DateUtils.addDays(dueDate, daysAfterDueDateToUseAsBasisForRenewalDate); return now.before(boundaryDate) && now.after(dueDate); }
From source file:com.github.amsacode.predict4java.PassPredictor.java
/** * Calculates positions of satellite for a given point in time, time range * and step increment.//w ww. jav a 2s .co m * * @param referenceDate * @param incrementSeconds * @param minutesBefore * @param minutesAfter * @return list of SatPos * @throws SatNotFoundException * @throws InvalidTleException */ public List<SatPos> getPositions(final Date referenceDate, final int incrementSeconds, final int minutesBefore, final int minutesAfter) throws SatNotFoundException { Date trackDate = new Date(referenceDate.getTime() - (minutesBefore * 60L * 1000L)); final Date endDateDate = new Date(referenceDate.getTime() + (minutesAfter * 60L * 1000L)); final List<SatPos> positions = new ArrayList<SatPos>(); while (trackDate.before(endDateDate)) { positions.add(getSatPos(trackDate)); trackDate = new Date(trackDate.getTime() + (incrementSeconds * 1000)); } return positions; }
From source file:Fetcher.Fetcher.java
@Deprecated @Override/* w w w .j a v a 2 s . c o m*/ /** * run() is deprecated. Use startFetching() instead. */ public void run() { WebDocument link = null; HttpURLConnection connection; Proxy p; //PreConnfiguration //Configure proxy //TODO Anonymizer is deprecated. Use in following for warning generation. switch (Variables.anonymizerProxyType) { case DIRECT: p = new Proxy(Proxy.Type.DIRECT, new InetSocketAddress(Variables.anonymizerIP, Variables.anonymizerPort)); break; case HTTP: p = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(Variables.anonymizerIP, Variables.anonymizerPort)); break; case SOCKS: p = new Proxy(Proxy.Type.SOCKS, new InetSocketAddress(Variables.anonymizerIP, Variables.anonymizerPort)); break; case NONE: default: p = null; break; } link = Methods.getNextProfileLink(); while (link != null && isWorking) { //Start fetching ... //Check if it should work or not Date currentTime = Methods.getCurrentTime(); if (!currentTime.after(Variables.startTime) || !currentTime.before(Variables.endTime)) { try { synchronized (t) { getThread().wait(60000); //sleep 60 seconds } } catch (InterruptedException ex) { if (Variables.debug) { Variables.logger.Log(Fetcher.class, Variables.LogType.Error, "Time is not between start and end time and thread is in exception!"); } } finally { continue; } } String URL = link.getNextUrl(); String UA = Methods.getRandomUserAgent(); //Use this UA for refererd or single links. //loop for referer for (int i = 0; i <= link.getRefererCount(); URL = link.getNextUrl(), i++) { if (Variables.debug && Variables.vv) { Variables.logger.Log(Fetcher.class, Variables.LogType.Trace, "Fetcher (" + Methods.Colorize(name, Methods.Color.Green) + ") start getting " + URL); } try { //Anonymizer if (Variables.anonymizerProxyType == Variables.AnonymizerProxy.NONE) { connection = (HttpURLConnection) new URL(URL).openConnection(); } else { connection = (HttpURLConnection) new URL(URL).openConnection(p); } connection.setDoOutput(true); connection.setDoInput(true); connection.setRequestProperty("User-Agent", UA); connection.setRequestProperty("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"); connection.setRequestProperty("Accept-Language", "en-US,en;q=0.5"); connection.setRequestProperty("Accept-Encoding", "gzip, deflated"); String referer = link.getNextReferrer(); if (referer != null) { connection.setRequestProperty("Referer", referer); referer = null; System.gc(); } //Send Cookie using user input if (!(Variables.Cookie == null || Variables.Cookie.equalsIgnoreCase(""))) { connection.setRequestProperty("Cookie", Variables.Cookie); } else if (cookies.getCookieStore().getCookies().size() > 0) { //From referer, there are some cookies connection.setRequestProperty("Cookie", Join(",", cookies.getCookieStore().getCookies())); } connection.setRequestMethod("GET"); connection.connect(); //Get Cookie from response getCookies(connection); if (connection.getResponseCode() == 200) { //Write to file String outputName = Variables.outputDirectory + link.getOutputName().substring(0, link.getOutputName().lastIndexOf(".")) + i + link.getOutputName().substring(link.getOutputName().lastIndexOf(".")); //Check extension if (!(outputName.endsWith("html") || outputName.endsWith("htm"))) { outputName += "html"; } //get content String html = ""; if (connection.getContentEncoding().equalsIgnoreCase("gzip")) { html = IOUtils.toString(new GZIPInputStream(connection.getInputStream())); } else if (connection.getContentEncoding().equalsIgnoreCase("deflate")) { html = IOUtils.toString(new InflaterInputStream(connection.getInputStream())); } FileWriter fw = new FileWriter(outputName); fw.write(html); fw.flush(); fw.close(); } else { //The returned code is not 200. if (Variables.debug) { Variables.logger.Log(Fetcher.class, Variables.LogType.Error, "Fetcher could not download (" + Methods.Colorize(URL, Methods.Color.Red) + ") in " + name); if (Variables.vv) { Variables.logger.Log(Fetcher.class, Variables.LogType.Error, "Server responded (" + Methods.Colorize(connection.getResponseCode() + " - " + connection.getResponseMessage(), Methods.Color.Red) + ") for " + URL); } } } //Close the connection connection.disconnect(); //Report progress Variables.logger.logResult(connection, link); Methods.oneFinished(); if (Variables.debug && Variables.vv) { Variables.logger.Log(Fetcher.class, Variables.LogType.Info, "[+] Done fetching (" + Methods.Colorize(URL, Methods.Color.Red) + "]"); } try { synchronized (t) { t.wait(Methods.getNextRandom() * 1000); } } catch (InterruptedException ex) { if (Variables.debug) { Variables.logger.Log(Fetcher.class, Variables.LogType.Error, "Cannot interrupt thread [" + Methods.Colorize(name, Methods.Color.Red) + "]. Interrupted before!"); } } catch (IllegalArgumentException ex) { if (Variables.debug) { Variables.logger.Log(Fetcher.class, Variables.LogType.Error, "-1 is returned as random number for thread [" + Methods.Colorize(name, Methods.Color.Red) + "]."); } } } catch (IOException ex) { if (Variables.debug) { if (Variables.vv) { Variables.logger.Log(Fetcher.class, Variables.LogType.Error, "Error in fetching [" + Methods.Colorize(URL, Methods.Color.Red) + "] in fetcher (" + Methods.Colorize(name, Methods.Color.Yellow) + ") for writing in (" + Methods.Colorize(link.getOutputName(), Methods.Color.White) + "). Detail:\r\n" + ex.getMessage()); } else { Variables.logger.Log(Fetcher.class, Variables.LogType.Error, "Error in fetching [" + Methods.Colorize(URL, Methods.Color.Red) + "]"); } } } catch (NullPointerException ex) { //Thrown sometimes and make the thread as Dead! if (Variables.debug) { if (Variables.vv) { Variables.logger.Log(Fetcher.class, Variables.LogType.Error, "Null pointer occured. Error in fetching [" + Methods.Colorize(URL, Methods.Color.Red) + "] in fetcher (" + Methods.Colorize(name, Methods.Color.Yellow) + ") for writing in (" + Methods.Colorize(link.getOutputName(), Methods.Color.White) + ")."); } else { Variables.logger.Log(Fetcher.class, Variables.LogType.Error, "Null pointer occured. Error in fetching [" + Methods.Colorize(URL, Methods.Color.Red) + "]"); } } } } //Check size limit and compress ... long size = Methods.getFolderSize(Variables.outputDirectory); if (size >= Variables.outputSizeLimit) { //Deactivate itself by waiting ... Variables.state = Variables.microbotState.Compressing; Variables.threadController.changeActiveThreads(false, t, Variables.microbotState.Compressing); } //Check if user terminated program or not if (isWorking) { link = Methods.getNextProfileLink(); } } //Thread finished. (Normally or by force) Variables.state = Variables.microbotState.Stopping; Variables.threadController.changeActiveThreads(false, t, Variables.microbotState.Stopping); //URLs done. This thread finishes its work. if (Variables.debug) { Variables.logger.Log(Fetcher.class, Variables.LogType.Info, "Fetcher (" + Methods.Colorize(name, Methods.Color.Green) + ") finished its work."); } }
From source file:fragment.web.SystemHealthControllerTest.java
@SuppressWarnings("unchecked") @Test/*from ww w. j a v a 2s . c o m*/ public void testHealth() throws Exception { calendar.add(Calendar.HOUR_OF_DAY, -1); Date start = calendar.getTime(); calendar.add(Calendar.HOUR_OF_DAY, 5); Date end = calendar.getTime(); ServiceNotification notification = new ServiceNotification(getRootUser(), start, end, "planned", "planned down time", defaultServiceInstance); serviceNotificationDAO.save(notification); for (int i = 0; i < 3; i++) { calendar.add(Calendar.DAY_OF_MONTH, random.nextInt(5) + 2); start = calendar.getTime(); calendar.add(Calendar.HOUR_OF_DAY, random.nextInt(5) + 1); end = calendar.getTime(); notification = new ServiceNotification(getRootUser(), start, end, "planned", "planned down time", defaultServiceInstance); serviceNotificationDAO.save(notification); } serviceNotificationDAO.flush(); ServiceInstance instance = serviceInstanceDao.find(1L); String view = controller.health(instance.getUuid(), 0, map); Assert.assertEquals("system.health", view); Object o = map.get("dateStatus"); Assert.assertTrue(o instanceof Map); Map<Date, Health> dates = (Map<Date, Health>) o; Assert.assertEquals(AbstractBaseController.getDefaultPageSize().intValue(), dates.keySet().size()); for (Date date : dates.keySet()) { System.out.println(date); Assert.assertTrue(DateUtils.isSameDay(new Date(), date) || date.before(new Date())); } o = map.get("dateStatusHistory"); Assert.assertTrue(o instanceof Map); Map<Date, List<ServiceNotification>> datesStatusHistory = (Map<Date, List<ServiceNotification>>) o; Assert.assertEquals(AbstractBaseController.getDefaultPageSize().intValue(), datesStatusHistory.keySet().size()); for (Date date : datesStatusHistory.keySet()) { System.out.println(date); Assert.assertTrue(DateUtils.isSameDay(new Date(), date) || date.before(new Date())); } }
From source file:com.abiquo.abiserver.business.authentication.AuthenticationManagerApi.java
/** * @see com.abiquo.abiserver.business.authentication.IAuthenticationManager#checkSession(com.abiquo.abiserver.pojo.authentication.UserSession) *//*from w w w . jav a 2 s . co m*/ @Override public BasicResult checkSession(final UserSession userSession) { BasicResult checkSessionResult = new BasicResult(); getFactory().beginConnection(); UserSession sessionToCheck = null; try { sessionToCheck = getUserSessionDAO().getCurrentUserSession(userSession.getUser(), userSession.getKey()); if (sessionToCheck == null) { // The session does not exist, so is not valid checkSessionResult.setResultCode(BasicResult.SESSION_INVALID); // logger.debug("The session is invalid. Please log in again. "); // log into the // authentication.log // errorManager // .reportError(resourceManger, checkSessionResult, "checkSession.invalid"); logger.trace("Invalid session. Please login again"); } else { // Checking if the session has expired Date currentDate = new Date(); if (currentDate.before(sessionToCheck.getExpireDate())) { extendSession(sessionToCheck); checkSessionResult.setSuccess(true); checkSessionResult .setMessage(AuthenticationManagerApi.resourceManger.getMessage("checkSession.success")); } else { // The session has time out. Deleting the session from Data Base getUserSessionDAO().makeTransient(sessionToCheck); checkSessionResult.setResultCode(BasicResult.SESSION_TIMEOUT); // logger.debug("The session is expired. Please log in again. "); // log into // the // authentication.log // errorManager.reportError(resourceManger, checkSessionResult, // "checkSession.expired"); logger.trace("Session expired. Please login again"); } } } catch (Exception e) { if (getFactory().isTransactionActive()) { getFactory().rollbackConnection(); } logger.trace("Unexpected error while checking the user session", e); } finally { getFactory().endConnection(); } return checkSessionResult; }
From source file:com.px100systems.data.core.InMemoryDatabase.java
protected boolean persistenceStalled() { if (persistence == PersistenceMode.WriteBehind) { Date threshold = SpringELCtx.dateArithmetic(new Date(), "-" + maxPersistenceDelayHours + "h"); Date lastSaveTime = new Date(getRuntimeStorage().getProvider().getAtomicLong("lastPersist", null)); if (lastSaveTime.before(threshold) && !getRuntimeStorage().getProvider().search(PersistenceLogEntry.UNIT_NAME, PersistenceLogEntry.class, Criteria.gt("time", lastSaveTime.getTime()), null, 10) .isEmpty()) {/*w w w. ja va 2 s . co m*/ log.info("Persistence has stalled"); emergencyShutdown(); return true; } } return false; }
From source file:dk.dma.ais.utils.filter.AisFilter.java
@Override public void accept(AisPacket packet) { if (out == null) { // Open new output stream out = getNextOutputStram();// ww w .ja va2 s. c o m } end = System.currentTimeMillis(); if (start == 0) { start = end; } for (IPacketFilter filter : filters) { if (filter.rejectedByFilter(packet)) { return; } } Integer baseMMSI = -1; String country = ""; String region = ""; Vdm vdm = packet.getVdm(); if (vdm == null) { return; } // Get source tag properties IProprietarySourceTag sourceTag = vdm.getSourceTag(); if (sourceTag != null) { baseMMSI = sourceTag.getBaseMmsi(); if (sourceTag.getCountry() != null) { country = sourceTag.getCountry().getTwoLetter(); } if (sourceTag.getRegion() != null) { region = sourceTag.getRegion(); } } if (region.equals("")) { region = "0"; } // Maybe check for start date Date timestamp = vdm.getTimestamp(); if (filter.getStartDate() != null && timestamp != null) { if (timestamp.before(filter.getStartDate())) { return; } } // Maybe check for end date if (filter.getEndDate() != null && timestamp != null) { if (timestamp.after(filter.getEndDate())) { System.exit(0); } } // Maybe check for base station MMSI if (filter.getBaseStations().size() > 0) { if (!filter.getBaseStations().contains(baseMMSI)) { return; } } // Maybe check for country if (filter.getCountries().size() > 0) { if (!filter.getCountries().contains(country)) { return; } } // Maybe check for region if (filter.getRegions().size() > 0) { if (!filter.getRegions().contains(region)) { return; } } if (stop) { return; } // Count message msgCount++; // Print tag line packet out.print(packet.getStringMessage() + "\r\n"); // Count bytes bytes += packet.getStringMessage().length() + 2; currentFileBytes += packet.getStringMessage().length() + 2; // Maybe print parsed if (dumpParsed) { if (timestamp != null) { out.println("+ timetamp " + timestampFormat.format(timestamp)); } if (vdm.getTags() != null) { for (IProprietaryTag tag : vdm.getTags()) { out.println("+ " + tag.toString()); } } AisMessage aisMessage = packet.tryGetAisMessage(); if (aisMessage != null) { out.println("+ " + aisMessage.toString()); } else { out.println("+ AIS message could not be parsed"); } // Check for binary message if (aisMessage instanceof AisBinaryMessage) { AisBinaryMessage binaryMessage = (AisBinaryMessage) aisMessage; try { AisApplicationMessage appMessage = binaryMessage.getApplicationMessage(); out.println(appMessage); } catch (SixbitException e) { } } out.println("---------------------------"); } // Maybe time for new outfile if (splitSize != null && currentFileBytes >= splitSize) { out.close(); out = null; currentFileBytes = 0; } }
From source file:com.redhat.rhn.frontend.xmlrpc.errata.test.ErrataHandlerTest.java
public void testListByDate() throws Exception { Calendar cal = Calendar.getInstance(); Date earlyDate = cal.getTime(); cal.add(Calendar.YEAR, 5);// ww w . j a v a2s . c om Date laterDate = cal.getTime(); assertTrue(earlyDate.before(laterDate)); Errata earlyErrata = ErrataFactoryTest.createTestPublishedErrata(admin.getOrg().getId()); Errata laterErrata = ErrataFactoryTest.createTestPublishedErrata(admin.getOrg().getId()); Channel testChannel = ChannelFactoryTest.createTestChannel(admin); earlyErrata.addChannel(testChannel); earlyErrata.setIssueDate(earlyDate); laterErrata.addChannel(testChannel); laterErrata.setIssueDate(laterDate); List test = handler.listByDate(admin, testChannel.getLabel()); assertEquals(2, test.size()); Object[] array = test.toArray(); assertEquals(array[0], earlyErrata); assertEquals(array[1], laterErrata); }