List of usage examples for java.util Calendar after
public boolean after(Object when)
Calendar
represents a time after the time represented by the specified Object
. From source file:com.android.deskclock.alarms.AlarmStateManager.java
/** * This registers the AlarmInstance to the state manager. This will look at the instance * and choose the most appropriate state to put it in. This is primarily used by new * alarms, but it can also be called when the system time changes. * * Most state changes are handled by the states themselves, but during major time changes we * have to correct the alarm instance state. This means we have to handle special cases as * describe below:/*from w w w . j a v a2 s. c om*/ * * <ul> * <li>Make sure all dismissed alarms are never re-activated</li> * <li>Make sure pre-dismissed alarms stay predismissed</li> * <li>Make sure firing alarms stayed fired unless they should be auto-silenced</li> * <li>Missed instance that have parents should be re-enabled if we went back in time</li> * <li>If alarm was SNOOZED, then show the notification but don't update time</li> * <li>If low priority notification was hidden, then make sure it stays hidden</li> * </ul> * * If none of these special case are found, then we just check the time and see what is the * proper state for the instance. * * @param context application context * @param instance to register */ public static void registerInstance(Context context, AlarmInstance instance, boolean updateNextAlarm) { final ContentResolver cr = context.getContentResolver(); final Alarm alarm = Alarm.getAlarm(cr, instance.mAlarmId); final Calendar currentTime = getCurrentTime(); final Calendar alarmTime = instance.getAlarmTime(); final Calendar timeoutTime = instance.getTimeout(context); final Calendar lowNotificationTime = instance.getLowNotificationTime(); final Calendar highNotificationTime = instance.getHighNotificationTime(); final Calendar missedTTL = instance.getMissedTimeToLive(); // Handle special use cases here if (instance.mAlarmState == AlarmInstance.DISMISSED_STATE) { // This should never happen, but add a quick check here LogUtils.e("Alarm Instance is dismissed, but never deleted"); deleteInstanceAndUpdateParent(context, instance); return; } else if (instance.mAlarmState == AlarmInstance.FIRED_STATE) { // Keep alarm firing, unless it should be timed out boolean hasTimeout = timeoutTime != null && currentTime.after(timeoutTime); if (!hasTimeout) { setFiredState(context, instance); return; } } else if (instance.mAlarmState == AlarmInstance.MISSED_STATE) { if (currentTime.before(alarmTime)) { if (instance.mAlarmId == null) { LogUtils.i("Cannot restore missed instance for one-time alarm"); // This instance parent got deleted (ie. deleteAfterUse), so // we should not re-activate it.- deleteInstanceAndUpdateParent(context, instance); return; } // TODO: This will re-activate missed snoozed alarms, but will // use our normal notifications. This is not ideal, but very rare use-case. // We should look into fixing this in the future. // Make sure we re-enable the parent alarm of the instance // because it will get activated by by the below code alarm.enabled = true; Alarm.updateAlarm(cr, alarm); } } else if (instance.mAlarmState == AlarmInstance.PREDISMISSED_STATE) { if (currentTime.before(alarmTime)) { setPreDismissState(context, instance); } else { deleteInstanceAndUpdateParent(context, instance); } return; } // Fix states that are time sensitive if (currentTime.after(missedTTL)) { // Alarm is so old, just dismiss it deleteInstanceAndUpdateParent(context, instance); } else if (currentTime.after(alarmTime)) { // There is a chance that the TIME_SET occurred right when the alarm should go off, so // we need to add a check to see if we should fire the alarm instead of marking it // missed. Calendar alarmBuffer = Calendar.getInstance(); alarmBuffer.setTime(alarmTime.getTime()); alarmBuffer.add(Calendar.SECOND, ALARM_FIRE_BUFFER); if (currentTime.before(alarmBuffer)) { setFiredState(context, instance); } else { setMissedState(context, instance); } } else if (instance.mAlarmState == AlarmInstance.SNOOZE_STATE) { // We only want to display snooze notification and not update the time, // so handle showing the notification directly AlarmNotifications.showSnoozeNotification(context, instance); scheduleInstanceStateChange(context, instance.getAlarmTime(), instance, AlarmInstance.FIRED_STATE); } else if (currentTime.after(highNotificationTime)) { setHighNotificationState(context, instance); } else if (currentTime.after(lowNotificationTime)) { // Only show low notification if it wasn't hidden in the past if (instance.mAlarmState == AlarmInstance.HIDE_NOTIFICATION_STATE) { setHideNotificationState(context, instance); } else { setLowNotificationState(context, instance); } } else { // Alarm is still active, so initialize as a silent alarm setSilentState(context, instance); } // The caller prefers to handle updateNextAlarm for optimization if (updateNextAlarm) { updateNextAlarm(context); } }
From source file:be.integrationarchitects.web.dragdrop.servlet.impl.DragDropServlet.java
protected synchronized void cleanUpOldFiles() { if (cfg.getOldFilesCleanupAgeDays() <= 0) return;//from w ww . ja va 2 s.c om String[] files = cfg.getFolder().list(); if (files == null) return; Calendar now = Calendar.getInstance(); now.add(Calendar.DATE, cfg.getOldFilesCleanupAgeDays() * -1); for (String fileName : files) { File f = new File(cfg.getFolder(), fileName); if (!f.isFile()) { continue; } if (f.getName().endsWith(".dat") || f.getName().endsWith(".inf") || f.getName().endsWith(".mime")) { Date d = new Date(f.lastModified()); Calendar fcal = Calendar.getInstance(); fcal.setTime(d); if (now.after(fcal)) { logger.logDebug("Delete old file:" + f.getName()); f.delete(); } } } }
From source file:com.androidinspain.deskclock.alarms.AlarmStateManager.java
/** * This registers the AlarmInstance to the state manager. This will look at the instance * and choose the most appropriate state to put it in. This is primarily used by new * alarms, but it can also be called when the system time changes. * * Most state changes are handled by the states themselves, but during major time changes we * have to correct the alarm instance state. This means we have to handle special cases as * describe below:// w w w .j a v a 2 s . co m * * <ul> * <li>Make sure all dismissed alarms are never re-activated</li> * <li>Make sure pre-dismissed alarms stay predismissed</li> * <li>Make sure firing alarms stayed fired unless they should be auto-silenced</li> * <li>Missed instance that have parents should be re-enabled if we went back in time</li> * <li>If alarm was SNOOZED, then show the notification but don't update time</li> * <li>If low priority notification was hidden, then make sure it stays hidden</li> * </ul> * * If none of these special case are found, then we just check the time and see what is the * proper state for the instance. * * @param context application context * @param instance to register */ public static void registerInstance(Context context, AlarmInstance instance, boolean updateNextAlarm) { LogUtils.i("Registering instance: " + instance.mId); final ContentResolver cr = context.getContentResolver(); final Alarm alarm = Alarm.getAlarm(cr, instance.mAlarmId); final Calendar currentTime = getCurrentTime(); final Calendar alarmTime = instance.getAlarmTime(); final Calendar timeoutTime = instance.getTimeout(); final Calendar lowNotificationTime = instance.getLowNotificationTime(); final Calendar highNotificationTime = instance.getHighNotificationTime(); final Calendar missedTTL = instance.getMissedTimeToLive(); // Handle special use cases here if (instance.mAlarmState == AlarmInstance.DISMISSED_STATE) { // This should never happen, but add a quick check here LogUtils.e("Alarm Instance is dismissed, but never deleted"); deleteInstanceAndUpdateParent(context, instance); return; } else if (instance.mAlarmState == AlarmInstance.FIRED_STATE) { // Keep alarm firing, unless it should be timed out boolean hasTimeout = timeoutTime != null && currentTime.after(timeoutTime); if (!hasTimeout) { setFiredState(context, instance); return; } } else if (instance.mAlarmState == AlarmInstance.MISSED_STATE) { if (currentTime.before(alarmTime)) { if (instance.mAlarmId == null) { LogUtils.i("Cannot restore missed instance for one-time alarm"); // This instance parent got deleted (ie. deleteAfterUse), so // we should not re-activate it.- deleteInstanceAndUpdateParent(context, instance); return; } // TODO: This will re-activate missed snoozed alarms, but will // use our normal notifications. This is not ideal, but very rare use-case. // We should look into fixing this in the future. // Make sure we re-enable the parent alarm of the instance // because it will get activated by by the below code alarm.enabled = true; Alarm.updateAlarm(cr, alarm); } } else if (instance.mAlarmState == AlarmInstance.PREDISMISSED_STATE) { if (currentTime.before(alarmTime)) { setPreDismissState(context, instance); } else { deleteInstanceAndUpdateParent(context, instance); } return; } // Fix states that are time sensitive if (currentTime.after(missedTTL)) { // Alarm is so old, just dismiss it deleteInstanceAndUpdateParent(context, instance); } else if (currentTime.after(alarmTime)) { // There is a chance that the TIME_SET occurred right when the alarm should go off, so // we need to add a check to see if we should fire the alarm instead of marking it // missed. Calendar alarmBuffer = Calendar.getInstance(); alarmBuffer.setTime(alarmTime.getTime()); alarmBuffer.add(Calendar.SECOND, ALARM_FIRE_BUFFER); if (currentTime.before(alarmBuffer)) { setFiredState(context, instance); } else { setMissedState(context, instance); } } else if (instance.mAlarmState == AlarmInstance.SNOOZE_STATE) { // We only want to display snooze notification and not update the time, // so handle showing the notification directly AlarmNotifications.showSnoozeNotification(context, instance); scheduleInstanceStateChange(context, instance.getAlarmTime(), instance, AlarmInstance.FIRED_STATE); } else if (currentTime.after(highNotificationTime)) { setHighNotificationState(context, instance); } else if (currentTime.after(lowNotificationTime)) { // Only show low notification if it wasn't hidden in the past if (instance.mAlarmState == AlarmInstance.HIDE_NOTIFICATION_STATE) { setHideNotificationState(context, instance); } else { setLowNotificationState(context, instance); } } else { // Alarm is still active, so initialize as a silent alarm setSilentState(context, instance); } // The caller prefers to handle updateNextAlarm for optimization if (updateNextAlarm) { updateNextAlarm(context); } }
From source file:nl.strohalm.cyclos.services.accountfees.AccountFeeServiceImpl.java
@Override public int chargeScheduledFees(final Calendar time) { final AccountFeeQuery query = new AccountFeeQuery(); query.setReturnDisabled(false);//from w w w .ja v a 2s . com query.setResultType(ResultType.LIST); query.setHour((byte) time.get(Calendar.HOUR_OF_DAY)); query.setType(RunMode.SCHEDULED); query.fetch(AccountFee.Relationships.LOGS); query.setEnabledBefore(time); final List<AccountFee> list = new ArrayList<AccountFee>(); // Get the daily fees query.setRecurrence(TimePeriod.Field.DAYS); list.addAll(search(query)); // Get the weekly fees query.setRecurrence(TimePeriod.Field.WEEKS); query.setDay((byte) time.get(Calendar.DAY_OF_WEEK)); list.addAll(search(query)); // Get the monthly fees query.setRecurrence(TimePeriod.Field.MONTHS); query.setDay((byte) time.get(Calendar.DAY_OF_MONTH)); list.addAll(search(query)); int count = 0; for (final AccountFee fee : list) { final AccountFeeLog lastExecution = fee.getLastExecution(); boolean charge; if (lastExecution == null) { // Was never executed. Charge now charge = true; } else { final TimePeriod recurrence = fee.getRecurrence(); if (recurrence.getNumber() == 1) { // When recurrence is every day or week or month, charge now charge = true; } else { // Check the recurrence final Calendar lastExecutionDate = lastExecution.getDate(); if (lastExecutionDate.after(time)) { // Consistency check: don't charge if last execution was after the current time charge = false; } // Find the number of elapsed periods int number = 0; final Calendar cal = DateHelper.truncate(lastExecutionDate); final int calendarField = recurrence.getField().getCalendarValue(); final Calendar date = DateHelper.truncate(time); while (cal.before(date)) { number++; cal.add(calendarField, 1); } // Charge each 'x' periods charge = number % recurrence.getNumber() == 0; } } // Charge the fee if (charge) { insertNextExecution(fee); count++; } } return count; }
From source file:org.apache.synapse.mediators.deprecation.DeprecationMediator.java
private boolean isDeprecated(SynapseObject service) { try {//from ww w . j ava 2s . c om if (service.getBoolean("enabled").booleanValue()) { Calendar current = Calendar.getInstance(); TimeZone tz = current.getTimeZone(); int offset = tz.getRawOffset(); Calendar calendar = new GregorianCalendar(tz); DateFormat df = new SimpleDateFormat("d/M/y:H:m"); df.setTimeZone(tz); Date d1 = service.getDate(DeprecationConstants.CFG_DEPRECATION_FROM_DATE); Calendar fromCalendar = new GregorianCalendar(tz); d1.setTime(d1.getTime() + offset); fromCalendar.setTime(d1); String toDate = service.getDate(DeprecationConstants.CFG_DEPRECATION_TO_DATE).toString(); if (toDate == null || (toDate.length() == 0)) { return calendar.before(fromCalendar); } Date d2 = service.getDate("toDate"); Calendar toCalendar = new GregorianCalendar(tz); d2.setTime(d2.getTime() + offset); toCalendar.setTime(d2); return (calendar.after(fromCalendar) && calendar.before(toCalendar)); } } catch (Exception e) { e.printStackTrace(); return false; } return false; }
From source file:org.alfresco.module.org_alfresco_module_wcmquickstart.jobs.DynamicCollectionProcessor.java
private void runInternal() { AuthenticationUtil.runAs(new RunAsWork<Object>() { @Override//from w ww.j a va2s . co m public Object doWork() throws Exception { transactionService.getRetryingTransactionHelper() .doInTransaction(new RetryingTransactionCallback<Object>() { @Override public Object execute() throws Throwable { ResultSet rs = null; try { //Find all web root nodes rs = searchService.query(StoreRef.STORE_REF_WORKSPACE_SPACESSTORE, SearchService.LANGUAGE_LUCENE, QUERY); if (log.isDebugEnabled()) { log.debug("Running dynamic collection refresh processor across " + rs.length() + " dynamic collection nodes"); } // Get the current date Calendar now = Calendar.getInstance(); // Interate over the dynamic queries for (NodeRef collection : rs.getNodeRefs()) { Date refreshAtDate = (Date) nodeService.getProperty(collection, PROP_REFRESH_AT); Calendar refreshAt = Calendar.getInstance(); if (refreshAtDate != null) { // Convert the date to calendar refreshAt.setTime(refreshAtDate); } if ((refreshAtDate == null) || now.after(refreshAt)) { if (log.isDebugEnabled() == true) { String collectionName = (String) nodeService.getProperty(collection, ContentModel.PROP_NAME); if (collectionName != null) { log.debug("Refreshing dynamic collection " + collectionName); } } // Refresh the collection collectionHelper.refreshCollection(collection); } } } finally { if (rs != null) { rs.close(); } } return null; } }); return null; } }, AuthenticationUtil.SYSTEM_USER_NAME); }
From source file:nl.strohalm.cyclos.services.transactions.InvoiceServiceImpl.java
private Validator getValidator(final Invoice invoice) { final Validator validator = new Validator("invoice"); validator.property("from").required(); validator.property("to").add(new PropertyValidation() { private static final long serialVersionUID = -5222363482447066104L; @Override//from w w w .j a v a2s . c om public ValidationError validate(final Object object, final Object name, final Object value) { final Invoice invoice = (Invoice) object; // Can't be the same from / to if (invoice.getFrom() != null && invoice.getTo() != null && invoice.getFrom().equals(invoice.getTo())) { return new InvalidError(); } return null; } }); validator.property("description").required().maxLength(1000); validator.property("amount").required().positiveNonZero(); if (LoggedUser.hasUser()) { final boolean asMember = !LoggedUser.accountOwner().equals(invoice.getFrom()); if (asMember || LoggedUser.isMember() || LoggedUser.isOperator()) { validator.property("destinationAccountType").required(); } else { validator.property("transferType").required(); } } validator.general(new GeneralValidation() { private static final long serialVersionUID = 4085922259108191939L; @Override public ValidationError validate(final Object object) { // Validate the scheduled payments final Invoice invoice = (Invoice) object; final List<InvoicePayment> payments = invoice.getPayments(); if (CollectionUtils.isEmpty(payments)) { return null; } // Validate the from member Member fromMember = invoice.getFromMember(); if (fromMember == null && LoggedUser.isMember()) { fromMember = LoggedUser.element(); } Calendar maxPaymentDate = null; if (fromMember != null) { fromMember = fetchService.fetch(fromMember, RelationshipHelper.nested(Element.Relationships.GROUP)); final MemberGroup group = fromMember.getMemberGroup(); // Validate the max payments final int maxSchedulingPayments = group.getMemberSettings().getMaxSchedulingPayments(); if (payments.size() > maxSchedulingPayments) { return new ValidationError("errors.greaterEquals", messageResolver.message("transfer.paymentCount"), maxSchedulingPayments); } // Get the maximum payment date final TimePeriod maxSchedulingPeriod = group.getMemberSettings().getMaxSchedulingPeriod(); if (maxSchedulingPeriod != null) { maxPaymentDate = maxSchedulingPeriod.add(DateHelper.truncate(Calendar.getInstance())); } } final BigDecimal invoiceAmount = invoice.getAmount(); final BigDecimal minimumPayment = paymentService.getMinimumPayment(); BigDecimal totalAmount = BigDecimal.ZERO; Calendar lastDate = DateHelper.truncate(Calendar.getInstance()); for (final InvoicePayment payment : payments) { final Calendar date = payment.getDate(); // Validate the max payment date if (maxPaymentDate != null && date.after(maxPaymentDate)) { final LocalSettings localSettings = settingsService.getLocalSettings(); final CalendarConverter dateConverter = localSettings.getRawDateConverter(); return new ValidationError("payment.invalid.schedulingDate", dateConverter.toString(maxPaymentDate)); } final BigDecimal amount = payment.getAmount(); if (amount == null || amount.compareTo(minimumPayment) < 0) { return new RequiredError(messageResolver.message("transfer.amount")); } if (date == null) { return new RequiredError(messageResolver.message("transfer.date")); } else if (date.before(lastDate)) { return new ValidationError("invoice.invalid.paymentDates"); } totalAmount = totalAmount.add(amount); lastDate = date; } if (invoiceAmount != null && totalAmount.compareTo(invoiceAmount) != 0) { return new ValidationError("invoice.invalid.paymentAmount"); } return null; } }); // Custom fields final List<TransferType> possibleTransferTypes = getPossibleTransferTypes(invoice); if (possibleTransferTypes.size() == 1) { validator.chained(new DelegatingValidator(new DelegatingValidator.DelegateSource() { @Override public Validator getValidator() { final TransferType transferType = possibleTransferTypes.iterator().next(); return paymentCustomFieldService.getValueValidator(transferType); } })); } return validator; }
From source file:bkampfbot.Instance.java
/** * Fhrt die aktuelle Instans aus//from ww w .jav a2s. c o m * * @throws ClientProtocolException * @throws IOException * @throws FatalError * @throws JSONException * @throws RestartLater * @throws NoSuchAlgorithmException */ public final void run() throws FatalError, RestartLater { // initialization HTTP client this.httpclient = new DefaultHttpClient(); final HttpParams params = new BasicHttpParams(); HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1); HttpProtocolParams.setUseExpectContinue(params, false); HttpProtocolParams.setUserAgent(params, Config.getUserAgent()); this.httpclient.setParams(params); if (Config.getProxyHost() != null && Config.getProxyPort() != 0) { if (Config.getProxyUsername() != null && Config.getProxyPassword() != null) { httpclient.getCredentialsProvider().setCredentials( new AuthScope(Config.getProxyHost(), Config.getProxyPort()), new UsernamePasswordCredentials(Config.getProxyUsername(), Config.getProxyPassword())); } HttpHost proxy = new HttpHost(Config.getProxyHost(), Config.getProxyPort()); httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy); } this.httpclient.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BROWSER_COMPATIBILITY); switch (this.modus) { // default: do nothing default: break; // call help case help: Output.help(); System.exit(0); break; // call proxy test case testproxy: new TestProxy(); System.exit(0); break; } // login this.login(); this.switchToSpeedHost(); switch (this.modus) { // for things without login case help: case testproxy: break; case daily: for (Daily d : this.daily) { if (d == null) break; switch (d) { // call "Rubbellos" case scratchTicket: ScratchTicket.getInstance().run(); break; // call "Tagesquiz" case quiz: Quiz.getInstance().run(); break; // call "Lotto" case glueck: Gluecksrad.getInstance().run(); break; // call "Weinfsser" case wein: Wein.getInstance().run(); break; // call "Tagesspiel" case spiel: Tagesspiel.getInstance().run(); break; // call "Tagesspiel" case spielZwerg: Tagesspiel.getInstance(true).run(); break; // call "Wrterjagd" case jagd: Jagd.getInstance().run(); break; } } Control.safeExit(); break; // call "Lotto" case lottery: Lottery.getInstance().run(); Control.safeExit(); break; // call "Pins" case pins: Pins.getInstance().run(); Control.safeExit(); break; // call "Plan" default: case normal: if (Config.getPlan0() == null && Config.getPlan1() == null) { Output.printTabLn("Beide Plne sind leer. " + "Bitte berprfen Sie die Konfiguration.", 0); System.exit(1); } Calendar lastCall = null; while (true) { Calendar now = new GregorianCalendar(); now.setTime(Config.getDate()); now.add(Calendar.MINUTE, -2); if (lastCall != null && lastCall.after(now)) { Output.println("Der Bot war bei der Abarbeitung der Plne zu schnell. " + "Vermutlich trat ein Fehler auf. Damit wir nicht auffallen, " + "warten wir 5 Minuten.", 1); Control.sleep(3000); } lastCall = new GregorianCalendar(); this.runPlans(); Control.sleep(5); this.getCharacter(); Control.sleep(5); } } }
From source file:it.geosolutions.geobatch.flow.file.FileBasedFlowManager.java
/** * returns an unmodifiable descending ordered by creation time list of all the consumers * //from ww w. jav a2s . c o m * @return */ public final Set<BaseEventConsumer> getEventConsumers() { TreeSet tree = new TreeSet<BaseEventConsumer<EventObject, EventConsumerConfiguration>>( new Comparator<BaseEventConsumer<EventObject, EventConsumerConfiguration>>() { @Override public int compare(BaseEventConsumer<EventObject, EventConsumerConfiguration> o1, BaseEventConsumer<EventObject, EventConsumerConfiguration> o2) { Calendar cal = o1.getCreationTimestamp(); Calendar currentcal = o2.getCreationTimestamp(); if (cal.before(currentcal)) return 1; else if (cal.after(currentcal)) return -1; else return 0; } }); tree.addAll(eventConsumers.values()); return tree; }