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:org.kuali.kfs.module.tem.service.impl.PerDiemServiceImpl.java
/** * Determines if the given date happens on or after the given season begin month/day for the year of the given date * @param seasonBegin the season begin month/day to check * @param d the date to check if on or after season begin * @return true if the given date is on or after the season begin date, false otherwise *///from w ww.j a va 2 s. c o m protected boolean isOnOrAfterSeasonBegin(String seasonBegin, java.sql.Timestamp d) { if (StringUtils.isBlank(seasonBegin)) { return true; // no season begin/end? Well...then we're after that, I should think } Calendar dCal = Calendar.getInstance(); dCal.setTime(d); final int year = dCal.get(Calendar.YEAR); Calendar seasonBeginCal = getSeasonBeginMonthDayCalendar(seasonBegin, year); if (KfsDateUtils.isSameDay(dCal, seasonBeginCal)) { // let's see if they're on the same day, regardless of time return true; } if (dCal.after(seasonBeginCal)) { // now that we know they're not on the same day, time isn't such a big deal return true; } return false; }
From source file:com.jgui.ttscrape.htmlunit.GridParser.java
/** * Parse a row in the table into a sequence of shows. * /*from w w w. j av a 2s . co m*/ * @param gridStartTime * the start time of the first show in the column. * @param row * row to be parsed. * @return collection of shows generated for this row. */ private List<Show> parseListingRow(Date gridStartTime, HtmlTableRow row) { ArrayList<Show> rv = new ArrayList<Show>(); try { String currentChannel = null; String currentChannelName = null; // String currentNetwork = null; Calendar timeAcrossGrid = Calendar.getInstance(); timeAcrossGrid.setTime(gridStartTime); for (HtmlTableCell cell : row.getCells()) { String cellClass = cell.getAttribute("class"); Show show = null; // gLSC class cell is the small cell before the shows start // (continuation cell) if ("gLSC".equals(cellClass)) { continue; } // gRSC is the blank cell at the end of a row. if ("gRSC".equals(cellClass)) { continue; } if ("gridCallSignCell".equals(cellClass)) { // extract grid call sign text span cell. for (HtmlElement el : cell.getChildElements()) { if ("gridCallSignText".equals(el.getAttribute("class"))) { currentChannelName = el.asText(); break; } // else if ("gridNetworkText".equals(el.getAttribute("class"))) { // currentNetwork = el.asText(); // } } } else if ("gridChannelCell".equals(cellClass)) { currentChannel = cell.asText(); } // gELC class cell is a continuation of a previous listing. // gEBC class cell is a continuation that fills the entire timespan. // cannot compute end time yet else if ((cellClass.startsWith("gELC ")) || (cellClass.startsWith("gEBC "))) { show = new Show(); show.setStartTime(timeAcrossGrid.getTime()); show.setChannelName(currentChannelName); show.setChannelNumber(currentChannel); // colspan is +1 from the show's remaining time for gELC int dur = Integer.parseInt(cell.getAttribute("colspan")); timeAcrossGrid.add(Calendar.MINUTE, (dur - 1)); show.setDuration(dur - 1); try { // show should have a "Continued from hh:mm a NodeList spanList = cell.getElementsByTagName("span"); for (int j = 0; j < spanList.getLength(); j++) { HtmlSpan span = (HtmlSpan) spanList.item(j); String title = span.getAttribute("title"); if ((title != null) && (title.startsWith("Continued from "))) { String[] splits = title.split(" "); String tm = splits[2]; String ampm = splits[3]; Calendar gridStartCal = Calendar.getInstance(); gridStartCal.setTime(gridStartTime); SimpleDateFormat sdf = new SimpleDateFormat("hh:mm a"); Date dt = sdf.parse(tm + " " + ampm); Calendar cal2 = Calendar.getInstance(); cal2.setTime(dt); Calendar cal4 = Calendar.getInstance(); cal4.setTimeInMillis(gridStartCal.getTimeInMillis()); cal4.set(Calendar.HOUR_OF_DAY, cal2.get(Calendar.HOUR_OF_DAY)); cal4.set(Calendar.MINUTE, cal2.get(Calendar.MINUTE)); // cal4 represents the time from the continued from except it // might be in the future // since it doesn't take into account the day boundary. Deal // with that. long diff; if (cal4.after(gridStartCal)) { // must have cross the day - show continues from previous day. diff = cal4.getTimeInMillis() - gridStartCal.getTimeInMillis(); } else { diff = gridStartCal.getTimeInMillis() - cal4.getTimeInMillis(); } Calendar cal3 = Calendar.getInstance(); cal3.setTime(show.getStartTime()); cal3.add(Calendar.MILLISECOND, (int) (diff * -1)); show.setStartTime(cal3.getTime()); show.setDuration(show.getDuration() + (int) (diff / (1000 * 60))); } } } catch (Exception ex) { logger.error("failed to parse continuation", ex); } } // a gERC cell continues into the next time period so it's // colspan is one larger than the duration we're aware of. else if ((cellClass.startsWith("gC ")) || (cellClass.startsWith("gERC "))) { show = new Show(); show.setStartTime(timeAcrossGrid.getTime()); show.setChannelName(currentChannelName); show.setChannelNumber(currentChannel); int dur = Integer.parseInt(cell.getAttribute("colspan")); if (cellClass.startsWith("gC ")) { timeAcrossGrid.add(Calendar.MINUTE, (dur)); show.setDuration(dur); } else { // must be gERC so subtract from the duration timeAcrossGrid.add(Calendar.MINUTE, (dur - 1)); show.setDuration(dur - 1); } } // at this point, the show variable should be assigned // a value if we have a show to process. If null, // we can continue to the next cell. if (show == null) { continue; } parseShowContent(show, cell); try { String[] classItems = cellClass.split(" "); String cat = categoryMap.get(classItems[1]); if (cat == null) { cat = "Other"; } show.setCategory(cat); } catch (Exception ex) { logger.error("could not get category from class", ex); } String data = cell.getAttribute("data"); if (data != null) { int idx1 = data.indexOf("EID:"); if (idx1 > 0) { String eid; int idx2 = data.indexOf(",", idx1); if (idx2 < 0) { eid = data.substring(idx1 + 4); } else { eid = data.substring(idx1 + 4, idx2); } show.setDetailKey(Integer.parseInt(eid)); show.setId(Integer.parseInt(eid)); } } if (isValid(show)) { rv.add(show); } } } catch (Exception ex) { logger.error("failed to process row {}", row, ex); } return rv; }
From source file:de.jost_net.JVerein.server.MitgliedImpl.java
@SuppressWarnings("unused") private void plausi() throws RemoteException, ApplicationException { checkExterneMitgliedsnummer();//from ww w . j av a 2 s . com if (getPersonenart() == null || (!getPersonenart().equals("n") && !getPersonenart().equals("j"))) { throw new ApplicationException("Personenstatus ist nicht 'n' oder 'j'"); } if (getName() == null || getName().length() == 0) { throw new ApplicationException("Bitte Namen eingeben"); } if (getPersonenart().equals("n") && (getVorname() == null || getVorname().length() == 0)) { throw new ApplicationException("Bitte Vornamen eingeben"); } if (getAdresstyp().getJVereinid() == 1 && getPersonenart().equals("n") && getGeburtsdatum().getTime() == Einstellungen.NODATE.getTime() && Einstellungen.getEinstellung().getGeburtsdatumPflicht()) { throw new ApplicationException("Bitte Geburtsdatum eingeben"); } if (getAdresstyp().getJVereinid() == 1 && getPersonenart().equals("n") && Einstellungen.getEinstellung().getGeburtsdatumPflicht()) { Calendar cal1 = Calendar.getInstance(); cal1.setTime(getGeburtsdatum()); Calendar cal2 = Calendar.getInstance(); if (cal1.after(cal2)) { throw new ApplicationException("Geburtsdatum liegt in der Zukunft"); } if (getSterbetag() != null) { cal2.setTime(getSterbetag()); } cal2.add(Calendar.YEAR, -150); if (cal1.before(cal2)) { throw new ApplicationException("Ist das Mitglied wirklich lter als 150 Jahre?"); } } if (getPersonenart().equals("n") && getGeschlecht() == null) { throw new ApplicationException("Bitte Geschlecht auswhlen"); } if (getEmail() != null && getEmail().length() > 0) { if (!EmailValidator.getInstance().isValid(getEmail())) { throw new ApplicationException("Ungltige Email-Adresse."); } } if (getAdresstyp().getJVereinid() == 1 && getEintritt().getTime() == Einstellungen.NODATE.getTime() && Einstellungen.getEinstellung().getEintrittsdatumPflicht()) { throw new ApplicationException("Bitte Eintrittsdatum eingeben"); } if (getAdresstyp().getJVereinid() == 1 && getZahlungsweg() == Zahlungsweg.BASISLASTSCHRIFT && BeitragsUtil.getBeitrag(Einstellungen.getEinstellung().getBeitragsmodel(), this.getZahlungstermin(), this.getZahlungsrhythmus().getKey(), this.getBeitragsgruppe(), new Date(), getEintritt(), getAustritt()) > 0) { if (getBic() == null || getBic().length() == 0 || getIban() == null || getIban().length() == 0) { throw new ApplicationException("Bitte BIC und IBAN eingeben"); } } if (getIban() != null && getIban().length() != 0) { try { new IBAN(getIban()); } catch (SEPAException e) { if (e.getFehler() != Fehler.UNGUELTIGES_LAND) { throw new ApplicationException(e.getMessage()); } } } if (getBic() != null && getBic().length() != 0) { try { new BIC(getBic()); } catch (SEPAException e) { if (!e.getMessage().startsWith("Ungltiges Land")) { throw new ApplicationException(e.getMessage()); } } } if (getZahlungsrhythmus() == null) { throw new ApplicationException("Ungltiger Zahlungsrhytmus: " + getZahlungsrhythmus()); } if (getSterbetag() != null && getAustritt() == null) { throw new ApplicationException("Bei verstorbenem Mitglied muss das Austrittsdatum gefllt sein!"); } if (getAustritt() != null || getKuendigung() != null) { // Person ist ausgetreten // Hat das Mitglied fr andere gezahlt? if (getBeitragsgruppe().getBeitragsArt() == ArtBeitragsart.FAMILIE_ZAHLER) { // ja DBIterator<Mitglied> famang = Einstellungen.getDBService().createList(Mitglied.class); famang.addFilter("zahlerid = " + getID()); famang.addFilter("austritt is null"); if (famang.hasNext()) { throw new ApplicationException( "Dieses Mitglied zahlt noch fr andere Mitglieder. Zunchst Beitragsart der Angehrigen ndern!"); } } } if (getBeitragsgruppe() != null && getBeitragsgruppe().getBeitragsArt() == ArtBeitragsart.FAMILIE_ANGEHOERIGER && getZahlerID() == null) { throw new ApplicationException("Bitte Zahler auswhlen!"); } }
From source file:nl.strohalm.cyclos.services.elements.MemberImportServiceImpl.java
private void importMember(final MemberImport memberImport, final MemberGroupAccountSettings accountSettings, final int lineNumber, final Map<String, CustomField> customFieldMap, final Map<String, MemberRecordType> recordTypeMap, final Map<MemberRecordType, Map<String, CustomField>> recordTypeFieldsMap, final LocalSettings localSettings, final AccessSettings accessSettings, final List<String> headers, final List<String> values, final Set<String> importedUsernames) { final Map<MemberRecordType, ImportedMemberRecord> records = new HashMap<MemberRecordType, ImportedMemberRecord>(); final Map<String, String> customFieldValues = new HashMap<String, String>(); final Map<MemberRecordType, Map<String, String>> recordFieldValues = new HashMap<MemberRecordType, Map<String, String>>(); // Insert the member ImportedMember member = new ImportedMember(); member.setSalt(hashHandler.newSalt()); member.setLineNumber(lineNumber);/*from w ww.j a v a 2 s . c om*/ member.setImport(memberImport); member.setStatus(ImportedMember.Status.SUCCESS); member = importedMemberDao.insert(member); final Calendar today = DateHelper.truncate(Calendar.getInstance()); try { member.setCustomValues(new ArrayList<MemberCustomFieldValue>()); final CalendarConverter dateConverter = localSettings.getRawDateConverter(); // Process each field. Field names are lowercased to ignore case for (int i = 0; i < headers.size() && i < values.size(); i++) { final String field = StringUtils.trimToEmpty(headers.get(i)).toLowerCase(); final String value = StringUtils.trimToNull(values.get(i)); if ("name".equals(field)) { member.setName(value); } else if ("username".equals(field)) { member.setUsername(value); } else if ("password".equals(field)) { member.setPassword(hashHandler.hash(member.getSalt(), value)); } else if ("email".equals(field)) { member.setEmail(value); } else if ("creationdate".equals(field)) { try { final Calendar creationDate = dateConverter.valueOf(value); if (creationDate != null) { if (creationDate.after(today) || creationDate.get(Calendar.YEAR) < 1950) { throw new Exception(); } member.setCreationDate(creationDate); } } catch (final Exception e) { member.setStatus(ImportedMember.Status.INVALID_CREATION_DATE); member.setErrorArgument1(value); break; } } else if ("balance".equals(field)) { try { member.setInitialBalance(localSettings.getNumberConverter().valueOf(value)); } catch (final Exception e) { member.setStatus(ImportedMember.Status.INVALID_BALANCE); member.setErrorArgument1(value); break; } } else if ("creditlimit".equals(field)) { try { BigDecimal limit = localSettings.getNumberConverter().valueOf(value); // Ensure the limit is positive if (limit != null) { limit = limit.abs(); } member.setCreditLimit(limit); } catch (final Exception e) { member.setStatus(ImportedMember.Status.INVALID_CREDIT_LIMIT); member.setErrorArgument1(value); break; } } else if ("uppercreditlimit".equals(field)) { try { member.setUpperCreditLimit(localSettings.getNumberConverter().valueOf(value)); } catch (final Exception e) { member.setStatus(ImportedMember.Status.INVALID_UPPER_CREDIT_LIMIT); member.setErrorArgument1(value); break; } } else if (customFieldMap.containsKey(field)) { // Create a custom field value CustomField customField = customFieldMap.get(field); final MemberCustomFieldValue fieldValue = new MemberCustomFieldValue(); fieldValue.setField(customField); fieldValue.setValue(preprocessCustomFieldValue(customField, value)); member.getCustomValues().add(fieldValue); customFieldValues.put(field, value); } else if (field.contains(".")) { // A record type value final String[] parts = field.split("\\."); // Find the record type final String recordTypeName = parts[0]; final MemberRecordType recordType = recordTypeMap.get(recordTypeName); if (recordType == null) { member.setStatus(ImportedMember.Status.INVALID_RECORD_TYPE); member.setErrorArgument1(recordTypeName); break; } // Find the custom field final String recordTypeField = parts[1]; final Map<String, CustomField> fieldsMap = recordTypeFieldsMap.get(recordType); final CustomField customField = fieldsMap.get(recordTypeField); if (customField == null) { member.setStatus(ImportedMember.Status.INVALID_RECORD_TYPE_FIELD); member.setErrorArgument1(recordTypeName); member.setErrorArgument2(recordTypeField); break; } // Find the imported member record ImportedMemberRecord record = records.get(recordType); if (record == null) { // None yet - create a new one record = new ImportedMemberRecord(); record.setMember(member); record.setType(recordType); record = importedMemberRecordDao.insert(record); record.setCustomValues(new ArrayList<ImportedMemberRecordCustomFieldValue>()); records.put(recordType, record); } // Set the custom field final ImportedMemberRecordCustomFieldValue fieldValue = new ImportedMemberRecordCustomFieldValue(); fieldValue.setField(customField); fieldValue.setValue(preprocessCustomFieldValue(customField, value)); record.getCustomValues().add(fieldValue); // Store the field value in a map Map<String, String> fieldValues = recordFieldValues.get(recordType); if (fieldValues == null) { fieldValues = new HashMap<String, String>(); recordFieldValues.put(recordType, fieldValues); } fieldValues.put(recordTypeField, value); } else { throw new UnknownColumnException(field); } } // When there was an error, stop processing if (member.getStatus() != ImportedMember.Status.SUCCESS) { return; } // Validate some data if (member.getName() == null) { // Name is always required member.setStatus(ImportedMember.Status.MISSING_NAME); return; } final String username = member.getUsername(); if (accessSettings.getUsernameGeneration() == UsernameGeneration.NONE && username == null) { // Username is required when it's not generated member.setStatus(ImportedMember.Status.MISSING_USERNAME); return; } // Validate the username if (username != null) { // Check the username format ValidationError error = new RegexValidation(accessSettings.getUsernameRegex()).validate(null, null, username); if (error == null) { // Check the username length error = new LengthValidation(accessSettings.getUsernameLength()).validate(null, null, username); } if (error != null) { member.setStatus(ImportedMember.Status.INVALID_USERNAME); member.setErrorArgument1(username); return; } // Check if username is duplicated in this import if (!importedUsernames.add(username)) { member.setStatus(ImportedMember.Status.USERNAME_ALREADY_IN_USE); member.setErrorArgument1(username); return; } // Check if username is already used by another member in cyclos try { elementService.loadUser(username); // If an user could be loaded, it means that the username is already in use member.setStatus(ImportedMember.Status.USERNAME_ALREADY_IN_USE); member.setErrorArgument1(username); return; } catch (final EntityNotFoundException e) { // Ok - not used yet } } if (member.getEmail() == null && localSettings.isEmailRequired()) { // Mail is required member.setStatus(ImportedMember.Status.MISSING_EMAIL); return; } if (EmailValidation.instance().validate(null, null, member.getEmail()) != null) { // Mail format is invalid member.setStatus(ImportedMember.Status.INVALID_EMAIL); member.setErrorArgument1(member.getEmail()); return; } if (memberImport.getAccountType() == null) { // Nothing related to accounts will be imported member.setInitialBalance(null); member.setCreditLimit(null); member.setUpperCreditLimit(null); } else { if (member.getCreditLimit() == null) { // Get the default group credit limit member.setCreditLimit(accountSettings.getDefaultCreditLimit()); } if (member.getUpperCreditLimit() == null) { // Get the default group upper credit limit member.setUpperCreditLimit(accountSettings.getDefaultUpperCreditLimit()); } final BigDecimal balance = member.getInitialBalance(); if (balance != null) { double balanceValue = balance.doubleValue(); if (balanceValue > 0 && memberImport.getInitialCreditTransferType() == null) { // There was an initial credit, but no TT for it: ignore member.setInitialBalance(null); balanceValue = 0; } else if (balanceValue < 0 && memberImport.getInitialDebitTransferType() == null) { // There was an initial debit, but no TT for it: ignore member.setInitialBalance(null); balanceValue = 0; } final BigDecimal creditLimit = member.getCreditLimit(); if (creditLimit != null && balanceValue < 0 && balance.compareTo(creditLimit.negate()) < 0) { // When the initial balance is negative, ensure the credit limit accommodates it member.setStatus(ImportedMember.Status.BALANCE_LOWER_THAN_CREDIT_LIMIT); return; } final BigDecimal upperCreditLimit = member.getUpperCreditLimit(); if (upperCreditLimit != null && balanceValue > 0 && balance.compareTo(upperCreditLimit) > 0) { // When the initial balance is positive, ensure the credit limit accommodates it member.setStatus(ImportedMember.Status.BALANCE_UPPER_THAN_CREDIT_LIMIT); return; } } } // Save the custom field values try { memberCustomFieldService.saveValues(member); } catch (final Exception e) { member.setStatus(ImportedMember.Status.INVALID_CUSTOM_FIELD); if (e instanceof ValidationException) { final ValidationException vex = (ValidationException) e; final Map<String, Collection<ValidationError>> errorsByProperty = vex.getErrorsByProperty(); if (MapUtils.isNotEmpty(errorsByProperty)) { final String fieldName = errorsByProperty.keySet().iterator().next(); final String displayName = vex.getDisplayNameByProperty().get(fieldName); member.setErrorArgument1(StringUtils.isEmpty(displayName) ? fieldName : displayName); final String fieldValue = StringUtils .trimToNull(customFieldValues.get(fieldName.toLowerCase())); if (CollectionUtils.isNotEmpty(errorsByProperty.get(fieldName))) { ValidationError ve = errorsByProperty.get(fieldName).iterator().next(); if (ve instanceof UniqueError) { member.setStatus(ImportedMember.Status.INVALID_CUSTOM_FIELD_VALUE_UNIQUE); member.setErrorArgument2(ve.getArguments().iterator().next().toString()); } else if (ve instanceof RequiredError) { member.setStatus(ImportedMember.Status.MISSING_CUSTOM_FIELD); } else if (ve instanceof MaxLengthError) { member.setStatus(ImportedMember.Status.INVALID_CUSTOM_FIELD_VALUE_MAX_LENGTH); member.setErrorArgument2(ve.getArguments().iterator().next().toString()); } else if (ve instanceof MinLengthError) { member.setStatus(ImportedMember.Status.INVALID_CUSTOM_FIELD_VALUE_MIN_LENGTH); member.setErrorArgument2(ve.getArguments().iterator().next().toString()); } } if (StringUtils.isEmpty(member.getErrorArgument2()) && fieldValue != null) { member.setErrorArgument2(fieldValue); } } } return; } // Save each record field values for (final ImportedMemberRecord record : records.values()) { final MemberRecordType recordType = record.getType(); final Map<String, String> fieldValues = recordFieldValues.get(recordType); // Check if the record is not empty boolean empty = true; for (final String value : fieldValues.values()) { if (StringUtils.isNotEmpty(value)) { empty = false; break; } } if (empty) { // There are no fields for this record: remove the record itself importedMemberRecordDao.delete(record.getId()); continue; } try { memberRecordCustomFieldService.saveValues(record); } catch (final Exception e) { member.setStatus(ImportedMember.Status.INVALID_RECORD_FIELD); if (e instanceof ValidationException) { final ValidationException vex = (ValidationException) e; final Map<String, Collection<ValidationError>> errorsByProperty = vex.getErrorsByProperty(); if (MapUtils.isNotEmpty(errorsByProperty)) { final String fieldName = errorsByProperty.keySet().iterator().next(); member.setErrorArgument1(recordType.getName() + "." + fieldName); final String fieldValue = StringUtils.trimToNull(fieldValues.get(fieldName)); if (fieldValue == null) { // When validation failed and the field is null, it's actually missing member.setStatus(ImportedMember.Status.MISSING_RECORD_FIELD); } else { member.setErrorArgument2(fieldValue); } } } return; } } } catch (final UnknownColumnException e) { throw e; } catch (final Exception e) { member.setStatus(ImportedMember.Status.UNKNOWN_ERROR); member.setErrorArgument1(e.toString()); } finally { importedMemberDao.update(member); } }
From source file:se.tillvaxtverket.tsltrust.weblogic.utils.TslCache.java
private boolean isWithinValidityPeriod(AaaCertificate cert) { Calendar present = Calendar.getInstance(); Calendar certNotBefore = Calendar.getInstance(); certNotBefore.setTime(cert.getNotBefore()); Calendar certNotAfter = Calendar.getInstance(); certNotAfter.setTime(cert.getNotAfter()); if (present.before(certNotBefore)) { return false; }/*from ww w .ja v a2s . com*/ if (present.after(certNotAfter)) { return false; } return true; }
From source file:com.yangtsaosoftware.pebblemessenger.services.MessageProcessingService.java
@Override public void onCreate() { super.onCreate(); phone_is_ontalking = false;//from w w w. j a v a2 s . co m loadPrefs(); Thread proceedthread = new ProcessThread(); proceedthread.start(); messageHandler = new MessageHandler(Looper.getMainLooper()); mMessenger = new Messenger(messageHandler); MessageProcessingService._context = getApplicationContext(); fdb = new FontDbHandler(_context); fdb.open(); mdb = new MessageDbHandler(_context); mdb.open(); bindService(new Intent(this, PebbleCenter.class), connToPebbleCenter, Context.BIND_AUTO_CREATE); BroadcastReceiver br = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { int command = intent.getIntExtra(Constants.BROADCAST_COMMAND, Constants.BROADCAST_PREFER_CHANGED); switch (command) { case Constants.BROADCAST_PREFER_CHANGED: loadPrefs(); break; case Constants.BROADCAST_CALL_INCOMING: String number = intent.getStringExtra(Constants.BROADCAST_PHONE_NUM); String name = intent.getStringExtra(Constants.BROADCAST_NAME); if (callQuietEnable) { Calendar c = Calendar.getInstance(); Calendar now = new GregorianCalendar(0, 0, 0, c.get(Calendar.HOUR_OF_DAY), c.get(Calendar.MINUTE)); Constants.log(TAG_NAME, "Checking quiet hours. Now: " + now.toString() + " vs " + quiet_hours_before.toString() + " and " + quiet_hours_after.toString()); if (now.before(quiet_hours_before) || now.after(quiet_hours_after)) { Constants.log(TAG_NAME, "Time is before or after the quiet hours time. Returning."); addNewCall(number, name, MessageDbHandler.NEW_ICON); } else { Bundle b = new Bundle(); b.putLong(MessageDbHandler.COL_CALL_ID, addNewCall(number, name, MessageDbHandler.OLD_ICON)); b.putString(MessageDbHandler.COL_CALL_NUMBER, number); b.putString(MessageDbHandler.COL_CALL_NAME, name); Message innerMsg = processHandler.obtainMessage(INNER_CALL_PROCEED); innerMsg.setData(b); processHandler.sendMessage(innerMsg); } } else { Bundle b = new Bundle(); if (phone_is_ontalking) { b.putString(MessageDbHandler.COL_MESSAGE_APP, "Call"); b.putString(MessageDbHandler.COL_MESSAGE_CONTENT, name + "\n" + number); addNewCall(number, name, MessageDbHandler.NEW_ICON); b.putLong(MessageDbHandler.COL_MESSAGE_ID, addNewMessage(b, MessageDbHandler.OLD_ICON)); Message innerMsg = processHandler.obtainMessage(INNER_MESSAGE_PROCEED); innerMsg.setData(b); processHandler.sendMessage(innerMsg); } else { b.putLong(MessageDbHandler.COL_CALL_ID, addNewCall(number, name, MessageDbHandler.OLD_ICON)); b.putString(MessageDbHandler.COL_CALL_NUMBER, number); b.putString(MessageDbHandler.COL_CALL_NAME, name); Message innerMsg = processHandler.obtainMessage(INNER_CALL_PROCEED); innerMsg.setData(b); processHandler.sendMessage(innerMsg); } } break; case Constants.BROADCAST_CALL_HOOK: phone_is_ontalking = true; break; case Constants.BROADCAST_CALL_IDLE: phone_is_ontalking = false; break; case Constants.BROADCAST_SMS_INCOMING: { Message msg = Message.obtain(); msg.what = MSG_NEW_MESSAGE; Bundle b = new Bundle(); b.putString(MessageDbHandler.COL_MESSAGE_APP, "SMS"); b.putString(MessageDbHandler.COL_MESSAGE_CONTENT, intent.getStringExtra(Constants.BROADCAST_SMS_BODY)); msg.setData(b); messageHandler.sendMessage(msg); } } } }; IntentFilter intentFilter = new IntentFilter(MessageProcessingService.class.getName()); LocalBroadcastManager.getInstance(getApplicationContext()).registerReceiver(br, intentFilter); }
From source file:org.simbasecurity.core.saml.SAMLResponseHandlerImpl.java
/** * Verifies that the document is still valid according Conditions Element. * * @return true if still valid/* w w w.j av a2s. co m*/ */ private boolean validateTimestamps() { NodeList timestampNodes = document.getElementsByTagNameNS("*", "Conditions"); if (timestampNodes.getLength() != 0) { for (int i = 0; i < timestampNodes.getLength(); i++) { NamedNodeMap attrName = timestampNodes.item(i).getAttributes(); Node nbAttribute = attrName.getNamedItem("NotBefore"); Node naAttribute = attrName.getNamedItem("NotOnOrAfter"); Calendar now = Calendar.getInstance(TimeZone.getTimeZone("UTC")); log.debug("now :" + now.get(Calendar.HOUR_OF_DAY) + ":" + now.get(Calendar.MINUTE) + ":" + now.get(Calendar.SECOND)); // validate NotOnOrAfter using UTC if (naAttribute != null) { final Calendar notOnOrAfterDate = javax.xml.bind.DatatypeConverter .parseDateTime(naAttribute.getNodeValue()); log.debug("notOnOrAfterDate :" + notOnOrAfterDate.get(Calendar.HOUR_OF_DAY) + ":" + notOnOrAfterDate.get(Calendar.MINUTE) + ":" + notOnOrAfterDate.get(Calendar.SECOND)); if (now.equals(notOnOrAfterDate) || now.after(notOnOrAfterDate)) { return false; } } // validate NotBefore using UTC if (nbAttribute != null) { final Calendar notBeforeDate = javax.xml.bind.DatatypeConverter .parseDateTime(nbAttribute.getNodeValue()); log.debug("notBeforeDate :" + notBeforeDate.get(Calendar.HOUR_OF_DAY) + ":" + notBeforeDate.get(Calendar.MINUTE) + ":" + notBeforeDate.get(Calendar.SECOND)); if (now.before(notBeforeDate)) { return false; } } } } return true; }
From source file:nl.strohalm.cyclos.services.accountfees.AccountFeeServiceImpl.java
private AccountFeeLog insertNextExecution(AccountFee fee) { fee = fetchService.fetch(fee);//from ww w . j a v a2 s. co m if (!fee.isEnabled()) { return null; } // Resolve the period Period period = null; Calendar executionDate = null; if (fee.getRunMode() == RunMode.MANUAL) { // Manual fee executionDate = Calendar.getInstance(); } else { // Scheduled fee executionDate = fee.getNextExecutionDate(); // Do not insert future account fees. if (executionDate.after(Calendar.getInstance())) { return null; } period = fee.getRecurrence().previousPeriod(executionDate); } // Create the log AccountFeeLog nextExecution = new AccountFeeLog(); nextExecution.setAccountFee(fee); nextExecution.setDate(executionDate); nextExecution.setPeriod(period); nextExecution.setAmount(fee.getAmount()); nextExecution.setFreeBase(fee.getFreeBase()); return accountFeeLogDao.insert(nextExecution); }
From source file:nl.strohalm.cyclos.services.elements.MemberServiceImpl.java
private MemberSmsStatus performGetSmsStatus(Member member) { // First, acquire a pessimistic lock LockHandler lockHandler = lockHandlerFactory.getLockHandler(); lockHandler.lockSmsStatus(member);/*from w w w . j a v a2 s .c o m*/ // Try to load the sms status. If none found, a new one will be returned member = fetchService.fetch(member, Element.Relationships.GROUP); final Calendar today = Calendar.getInstance(); final Period currentMonth = TimePeriod.ONE_MONTH.currentPeriod(today); MemberSmsStatus status; try { // Try loading the member status status = memberSmsStatusDao.load(member); // If got to this line, the status exists boolean changed = false; if (today.after(status.getFreeSmsExpiration())) { // The free sms period has expired. Reset. status.setFreeSmsSent(0); status.setFreeSmsExpiration(currentMonth.getEnd()); changed = true; } final Calendar paidSmsExpiration = status.getPaidSmsExpiration(); if (paidSmsExpiration != null && today.after(paidSmsExpiration)) { // The paid sms messages have expired. Reset. status.setPaidSmsLeft(0); status.setPaidSmsExpiration(null); changed = true; } if (changed) { // Update the record if it has changed status = memberSmsStatusDao.update(status); } } catch (final EntityNotFoundException e) { // The status does not exist. Create a new one. MemberGroup group = member.getMemberGroup(); status = new MemberSmsStatus(); status.setMember(member); status.setFreeSmsExpiration(currentMonth.getEnd()); status.setAllowChargingSms(group.isDefaultAllowChargingSms()); status.setAcceptFreeMailing(group.isDefaultAcceptFreeMailing()); status.setAcceptPaidMailing(group.isDefaultAcceptPaidMailing()); ensureAllowChargingSms(status, hasNotificationsBySms(member)); status = memberSmsStatusDao.insert(status); } finally { lockHandler.release(); } return status; }
From source file:org.kuali.kfs.pdp.service.impl.PaymentFileValidationServiceImpl.java
/** * Checks the payment date is not more than 30 days past or 30 days coming * * @param paymentGroup <code>PaymentGroup</code> being checked * @param warnings <code>List</code> list of accumulated warning messages */// w w w .jav a 2 s . c o m protected void checkGroupPaymentDate(PaymentGroup paymentGroup, List<String> warnings) { Timestamp now = dateTimeService.getCurrentTimestamp(); Calendar nowPlus30 = Calendar.getInstance(); nowPlus30.setTime(now); nowPlus30.add(Calendar.DATE, 30); Calendar nowMinus30 = Calendar.getInstance(); nowMinus30.setTime(now); nowMinus30.add(Calendar.DATE, -30); if (paymentGroup.getPaymentDate() != null) { Calendar payDate = Calendar.getInstance(); payDate.setTime(paymentGroup.getPaymentDate()); if (payDate.before(nowMinus30)) { addWarningMessage(warnings, PdpKeyConstants.MESSAGE_PAYMENT_LOAD_PAYDATE_OVER_30_DAYS_PAST, dateTimeService.toDateString(paymentGroup.getPaymentDate())); } if (payDate.after(nowPlus30)) { addWarningMessage(warnings, PdpKeyConstants.MESSAGE_PAYMENT_LOAD_PAYDATE_OVER_30_DAYS_OUT, dateTimeService.toDateString(paymentGroup.getPaymentDate())); } } else { // KFSMI-9997 // Calculate tomorrow's date to set as payment date rather than null Calendar tomorrow = Calendar.getInstance(); tomorrow.setTime(now); tomorrow.add(Calendar.DATE, 1); tomorrow.getTime(); Date paymentDate = new Date(tomorrow.getTime().getTime()); paymentGroup.setPaymentDate(paymentDate); } }