List of usage examples for java.util Calendar before
public boolean before(Object when)
Calendar
represents a time before the time represented by the specified Object
. From source file:cz.cvut.fel.webrtc.handlers.WebHandler.java
public WebHandler() { super();/*from w w w .j a v a2s. c om*/ TimerTask task = new TimerTask() { @Override public void run() { Calendar currentDate = Calendar.getInstance(); for (WebUser user : registry.getAll()) { Calendar ping = user.getLastPing(); ping.add(Calendar.SECOND, 40); if (ping.before(currentDate)) { try { log.info("{} is unreachable.", user.getName()); leaveRoom(user); } catch (Exception e) { } } } } }; Timer timer = new Timer(); timer.scheduleAtFixedRate(task, 30000, 30000); }
From source file:com.tdclighthouse.prototype.utils.Configuration.java
public Date getTime(String key, Date defaultValue) { Date result = defaultValue;//ww w . ja va2 s .c o m String stringDate = properties.getProperty(key); try { if (StringUtils.isNotBlank(stringDate)) { Calendar calendar = new GregorianCalendar(); calendar.setTime(new SimpleDateFormat(TIME_FORMAT_STRING).parse(stringDate)); Calendar now = new GregorianCalendar(); calendar.set(now.get(Calendar.YEAR), now.get(Calendar.MONTH), now.get(Calendar.DAY_OF_MONTH)); if (calendar.before(now)) { calendar.add(Calendar.DAY_OF_MONTH, 1); } result = calendar.getTime(); } } catch (ParseException e) { LOG.error( "the given value \"{}\" of the key \"{}\" is not of the format \"{}\" so we default back to the default value", stringDate, key, TIME_FORMAT_STRING); } return result; }
From source file:net.ontopia.topicmaps.db2tm.SynchronizationServlet.java
@Override public void init(ServletConfig config) throws ServletException { super.init(config); log.info("Initializing synchronization servlet."); try {/*from ww w.j a v a2 s . co m*/ // no default starttime Date time = null; long delay = 180 * 1000; String timeval = config.getInitParameter("start-time"); if (timeval != null) { Date d = df.parse(timeval); Calendar c0 = Calendar.getInstance(); Calendar c = Calendar.getInstance(); c.set(Calendar.HOUR_OF_DAY, 1); c.set(Calendar.MINUTE, 0); c.add(Calendar.MILLISECOND, (int) d.getTime()); if (c.before(c0)) c.add(Calendar.HOUR_OF_DAY, 24); time = c.getTime(); log.info("Setting synchronization start time to {} ms.", time); } else { // default delay is 180 sec. delay = getLongProperty(config, "delay", delay); log.info("Setting synchronization delay to {} ms.", delay); } // default interval is 24 hours. long interval = getLongProperty(config, "interval", 1000 * 60 * 60 * 24); log.info("Setting synchronization interval to {} ms.", interval); // load relation mapping file String mapping = config.getInitParameter("mapping"); if (mapping == null) throw new OntopiaRuntimeException("Servlet init-param 'mapping' must be specified."); // get relation names (comma separated) Collection<String> relnames = null; String relations = config.getInitParameter("relations"); if (relations != null) relnames = Arrays.asList(StringUtils.split(relations, ",")); // get hold of the topic map String tmid = config.getInitParameter("topicmap"); if (tmid == null) throw new OntopiaRuntimeException("Servlet init-param 'topicmap' must be specified."); TopicMapRepositoryIF rep = NavigatorUtils.getTopicMapRepository(config.getServletContext()); TopicMapReferenceIF ref = rep.getReferenceByKey(tmid); // make sure delay is at least 10 seconds to make sure that it doesn't // start too early if (time == null) task = new SynchronizationTask(config.getServletName(), (delay < 10000 ? 10000 : delay), interval); else task = new SynchronizationTask(config.getServletName(), time, interval); task.setRelationMappingFile(mapping); task.setRelationNames(relnames); task.setTopicMapReference(ref); task.setBaseLocator(null); } catch (Exception e) { throw new ServletException(e); } }
From source file:org.linagora.linshare.core.service.impl.UploadRequestUrlServiceImpl.java
private void accessBusinessCheck(UploadRequestUrl requestUrl, String password) throws BusinessException { UploadRequest request = requestUrl.getUploadRequest(); if (!isValidPassword(requestUrl, password)) { throw new BusinessException(BusinessErrorCode.UPLOAD_REQUEST_URL_FORBIDDEN, "You do not have the right to get this upload request url : " + requestUrl.getUuid()); }/* w w w .ja va 2 s . com*/ if (!(request.getStatus().equals(UploadRequestStatus.STATUS_ENABLED) || request.getStatus().equals(UploadRequestStatus.STATUS_CLOSED))) { throw new BusinessException(BusinessErrorCode.UPLOAD_REQUEST_READONLY_MODE, "The current upload request url is not available : " + requestUrl.getUuid()); } Calendar now = GregorianCalendar.getInstance(); Calendar compare = GregorianCalendar.getInstance(); compare.setTime(request.getActivationDate()); if (now.before(compare)) { throw new BusinessException(BusinessErrorCode.UPLOAD_REQUEST_NOT_ENABLE_YET, "The current upload request url is not enable yet : " + requestUrl.getUuid()); } if (request.getExpiryDate() != null) { compare.setTime(request.getExpiryDate()); if (now.after(compare)) { throw new BusinessException(BusinessErrorCode.UPLOAD_REQUEST_NOT_ENABLE_YET, "The current upload request url is no more available now. : " + requestUrl.getUuid()); } } }
From source file:com.l2jfree.loginserver.network.L2Client.java
public void setAge(int year, int month, int day) { Calendar dateOfBirth = new GregorianCalendar(year, month - 1, day); Calendar today = Calendar.getInstance(); int age = today.get(Calendar.YEAR) - dateOfBirth.get(Calendar.YEAR); dateOfBirth.add(Calendar.YEAR, age); if (today.before(dateOfBirth)) age--;/*from w w w. j a v a2 s. c o m*/ _age = age; }
From source file:br.com.autonomiccs.autonomic.administration.plugin.services.AutonomicClusterManagementService.java
/** * Checks if the cluster has been processed recently (according to the * administration algorithm management interval). If the host has no last administration value * ('last_administration' column is null), then we consider that the cluster * has never been processed; therefore, we will put it into the management queue. * @return true if the cluster can be processed *//*from www . j a v a2s . c om*/ public boolean canProcessCluster(long clusterId, ClusterAdministrationHeuristicAlgorithm algorithm) { Date lastAdministration = clusterDaoJdbc.getClusterLastAdminstration(clusterId); if (lastAdministration == null) { return true; } Calendar lastAdministrationCalendar = Calendar.getInstance(); lastAdministrationCalendar.setTime(lastAdministration); lastAdministrationCalendar.add(Calendar.SECOND, algorithm.getClusterIntervalBetweenConsolidation()); Calendar calendarNow = Calendar.getInstance(); return lastAdministrationCalendar.before(calendarNow); }
From source file:cz.incad.kramerius.security.impl.criteria.MovingWall.java
public EvaluatingResult evaluateDoc(int wallFromConf, Document xmlDoc, String xPathExpression) throws XPathExpressionException { XPath xpath = xpfactory.newXPath(); xpath.setNamespaceContext(new FedoraNamespaceContext()); XPathExpression expr = xpath.compile(xPathExpression); Object date = expr.evaluate(xmlDoc, XPathConstants.NODE); if (date != null) { String patt = ((Text) date).getData(); try {//from w w w . j a v a2s. co m DatesParser dateParse = new DatesParser(new DateLexer(new StringReader(patt))); Date parsed = dateParse.dates(); Calendar calFromMetadata = Calendar.getInstance(); calFromMetadata.setTime(parsed); Calendar calFromConf = Calendar.getInstance(); calFromConf.add(Calendar.YEAR, -1 * wallFromConf); return calFromMetadata.before(calFromConf) ? EvaluatingResult.TRUE : EvaluatingResult.FALSE; } catch (RecognitionException e) { LOGGER.log(Level.SEVERE, e.getMessage(), e); LOGGER.log(Level.SEVERE, "Returning NOT_APPLICABLE"); return EvaluatingResult.NOT_APPLICABLE; } catch (TokenStreamException e) { LOGGER.log(Level.SEVERE, e.getMessage(), e); LOGGER.log(Level.SEVERE, "Returning NOT_APPLICABLE"); return EvaluatingResult.NOT_APPLICABLE; } } return null; }
From source file:com.sean.takeastand.storage.ScheduleEditor.java
private boolean setRepeatingAlarmNow(String startTime, String endTime) { //Set repeating alarm if in between start and end time Calendar rightNow = Calendar.getInstance(); Calendar startTimeDate = Utils.convertToCalendarTime(startTime, mContext); Calendar endTimeDate = Utils.convertToCalendarTime(endTime, mContext); if (startTimeDate.before(rightNow) && endTimeDate.after(rightNow)) { Log.i(TAG, "New alarm is within current day's timeframe. Starting RepeatingAlarm."); return true; } else {/* ww w . j av a2s . c o m*/ Log.i(TAG, "New alarm's repeating timeframe has either not begun or has already passed."); return false; } }
From source file:no.dusken.aranea.web.control.PageController.java
public ModelAndView handleArticle(HttpServletRequest request, HttpServletResponse response) throws Exception { Map<String, Object> map = new HashMap<String, Object>(); if (showUnpublished) { //assuming that when this is true, we do not want caching. response.setHeader("Cache-Control", "no-cache"); } else {//from w w w . j av a2 s.c o m response.setHeader("Cache-Control", "max-age=3600"); } Long ID; Page p; if (request.getParameter("externalID") != null) { ID = ServletRequestUtils.getRequiredLongParameter(request, "externalID"); p = pageService.getEntityByExternalID(ID); } else { ID = ServletRequestUtils.getLongParameter(request, "ID", 0); p = pageService.getEntity(ID); } Calendar now = new GregorianCalendar(); if (p == null || (p != null && !((p.getPublished() || showUnpublished) && p.getVisibleFrom().before(now) && now.before(p.getVisibleTo())))) { throw new PageNotFoundException("Page with ID: " + ID); } if (p instanceof Article) { Article article = (Article) p; List<String> paragraphs = getParagraphs(article); map.put("paragraphs", paragraphs); map.put("photographers", pageService.getPhotographers(article)); map.put("drawers", pageService.getDrawers(article)); int pages = 1; if (paragraphs.size() > MAX_PARAGRAPHS) { pages = paragraphs.size() / MAX_PARAGRAPHS; if (paragraphs.size() % MAX_PARAGRAPHS >= (MAX_PARAGRAPHS / 2)) { pages++; } } int articlePage = ServletRequestUtils.getIntParameter(request, "articlepage", 1); if (articlePage < 1 || articlePage > pages) { articlePage = 1; } int startIndex, endIndex; if (pages == 1) { startIndex = 1; endIndex = paragraphs.size(); } else { int paragraphs_per_page = paragraphs.size() / pages; startIndex = paragraphs_per_page * (articlePage - 1) + 1; endIndex = startIndex + paragraphs_per_page + 1; if (endIndex >= paragraphs.size()) { endIndex = paragraphs.size(); } } map.put("articleStartIndex", startIndex); map.put("articleEndIndex", endIndex); map.put("articlePage", articlePage); map.put("articlePageCount", pages); } map.put("article", p); HashMap<String, List<Page>> relationMap = new HashMap<String, List<Page>>(); HashMap<Integer, List<PageRelation>> paragraphRelationMap = new HashMap<Integer, List<PageRelation>>(); for (PageRelation pr : p.getPageRelations()) { Integer paragraph = pr.getParagraph(p); Page relatedPage = pr.getPageRelatedTo(p); if (paragraph == 0) { String description = pr.getDescription(p); if (relationMap.containsKey(description)) { relationMap.get(description).add(relatedPage); } else { List<Page> list = new LinkedList<Page>(); list.add(relatedPage); relationMap.put(description, list); } } else { if (paragraphRelationMap.containsKey(paragraph)) { paragraphRelationMap.get(paragraph).add(pr); } else { List<PageRelation> list = new LinkedList<PageRelation>(); list.add(pr); paragraphRelationMap.put(paragraph, list); } } } map.put("paragraphPagerelations", paragraphRelationMap); map.put("pageRelations", relationMap); map.put("captchaString", UUID.randomUUID().toString()); return new ModelAndView(ARTICLEVIEW, map); }
From source file:com.linuxbox.enkive.imap.mongo.MongoImapAccountCreator.java
@Override public void addImapMessages(String username, Date fromDate, Date toDate) throws MessageSearchException { Calendar startTime = Calendar.getInstance(); startTime.setTime(fromDate);//from w ww .j a v a 2 s . co m Calendar endTime = Calendar.getInstance(); endTime.setTime(toDate); while (startTime.before(endTime)) { Calendar endOfMonth = (Calendar) startTime.clone(); endOfMonth.set(Calendar.DAY_OF_MONTH, endOfMonth.getActualMaximum(Calendar.DAY_OF_MONTH)); if (endOfMonth.after(endTime)) endOfMonth = (Calendar) endTime.clone(); // Need to get all messages to add Set<String> messageIdsToAdd = getMailboxMessageIds(username, startTime.getTime(), endOfMonth.getTime()); // Need to add messages // Get top UID, add from there if (!messageIdsToAdd.isEmpty()) { // Need to check if folder exists, if not create it and add to // user // mailbox list DBObject mailboxObject = getMessagesFolder(username, startTime.getTime()); @SuppressWarnings("unchecked") HashMap<String, String> mailboxMsgIds = (HashMap<String, String>) mailboxObject .get(MongoEnkiveImapConstants.MESSAGEIDS); TreeMap<String, String> sortedMsgIds = new TreeMap<String, String>(); sortedMsgIds.putAll(mailboxMsgIds); long i = 0; if (!sortedMsgIds.isEmpty()) i = Long.valueOf(sortedMsgIds.lastKey()); for (String msgId : messageIdsToAdd) { i++; mailboxMsgIds.put(((Long.toString(i))), msgId); } mailboxObject.put(MongoEnkiveImapConstants.MESSAGEIDS, mailboxMsgIds); imapCollection.findAndModify(new BasicDBObject("_id", mailboxObject.get("_id")), mailboxObject); } startTime.set(Calendar.DAY_OF_MONTH, 1); startTime.add(Calendar.MONTH, 1); } }