List of usage examples for java.sql Timestamp before
public boolean before(Timestamp ts)
From source file:token.ValidateToken.java
@Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { JSONObject arrayObj = new JSONObject(); String str_token = request.getParameter("access_token"); String user_agent = request.getHeader("user-agent"); String ip_address = request.getRemoteAddr(); String access_token = str_token + "#" + user_agent + "#" + ip_address; String query = "SELECT * FROM tokendata WHERE token='" + access_token + "'"; System.out.println("Client USER_AGENT: " + user_agent); System.out.println("Client IP_ADDRESS: " + ip_address); try {//w ww . j a v a2 s. c o m Connection currentCon = ConnectionManager.getConnection(); Statement stmt = currentCon.createStatement(); ResultSet rs = stmt.executeQuery(query); boolean valid = rs.next(); System.out.println("ADA TOKEN TAU GAK = " + valid); if (valid) { Timestamp create_time = getTimeStamp(access_token); Calendar cal = Calendar.getInstance(); cal.setTimeInMillis(create_time.getTime()); cal.add(Calendar.MINUTE, 30); Timestamp expired_time = new Timestamp(cal.getTimeInMillis()); Timestamp current_time = new Timestamp(System.currentTimeMillis()); if (expired_time.before(current_time)) { arrayObj.put("status", "expired"); } else { arrayObj = getJsonObj(access_token); setCreateTime(getUserID(access_token), access_token, current_time); } } else { arrayObj.put("status", "non-valid"); } } catch (SQLException se) { System.out.println(se); } response.setContentType("application/json:charset=UTF-8"); response.getWriter().write(arrayObj.toString()); }
From source file:org.kuali.kfs.module.ar.document.service.impl.InvoiceRecurrenceDocumentServiceImpl.java
/** * @see org.kuali.kfs.module.ar.document.service.InvoiceRecurrenceService#isValidRecurrenceEndDate(Date) *//*from w w w .ja v a 2 s.c o m*/ @Override public boolean isValidRecurrenceEndDate(Date beginDate, Date endDate) { boolean isSuccess = true; if (ObjectUtils.isNull(beginDate) || ObjectUtils.isNull(endDate)) { return isSuccess; } Timestamp beginDateTimestamp = new Timestamp(beginDate.getTime()); Timestamp endDateTimestamp = new Timestamp(endDate.getTime()); if ((ObjectUtils.isNotNull(endDateTimestamp)) && (endDateTimestamp.before(beginDateTimestamp) || endDateTimestamp.equals(beginDateTimestamp))) { return false; } return isSuccess; }
From source file:org.kuali.rice.kew.notes.web.NoteAction.java
private List<Note> sortNotes(List<Note> allNotes, String sortOrder) { final int returnCode = KewApiConstants.Sorting.SORT_SEQUENCE_DSC.equalsIgnoreCase(sortOrder) ? -1 : 1; try {//ww w . j ava2 s.co m Collections.sort(allNotes, new Comparator<Note>() { @Override public int compare(Note o1, Note o2) { Timestamp date1 = o1.getNoteCreateDate(); Timestamp date2 = o2.getNoteCreateDate(); if (date1.before(date2)) { return returnCode * -1; } else if (date1.after(date2)) { return returnCode; } else { return 0; } } }); } catch (Throwable e) { LOG.error(e.getMessage(), e); } return allNotes; }
From source file:org.ohmage.query.impl.UserSurveyResponseQueries.java
/** * Retrieves the percentage of non-null location values from surveys over * the past 'hours'.//from w w w . j a va 2 s . co m * * @param requestersUsername The username of the user that is requesting * this information. * * @param usersUsername The username of the user to which the data belongs. * * @param hours Defines the timespan for which the information should be * retrieved. The timespan is from now working backwards until * 'hours' hours ago. * * @return Returns the percentage of non-null location values from surveys * over the last 'hours' or null if there were no surveys. */ public Double getPercentageOfNonNullSurveyLocations(String requestersUsername, String usersUsername, int hours) throws DataAccessException { long nonNullLocationsCount = 0; long totalLocationsCount = 0; try { // Get a time stamp from 24 hours ago. Calendar dayAgo = Calendar.getInstance(); dayAgo.add(Calendar.HOUR_OF_DAY, -hours); final Timestamp dayAgoTimestamp = new Timestamp(dayAgo.getTimeInMillis()); final List<String> nonNullLocations = new LinkedList<String>(); final List<String> allLocations = new LinkedList<String>(); getJdbcTemplate().query(SQL_GET_SURVEY_RESPONSES_FOR_USER_FOR_REQUESTER, new Object[] { usersUsername, requestersUsername }, new RowMapper<String>() { @Override public String mapRow(ResultSet rs, int rowNum) throws SQLException { // Get the time the Mobility point was uploaded. Timestamp generatedTimestamp = rs.getTimestamp("upload_timestamp"); // If it was uploaded within the last 'hours' it is // valid. if (!generatedTimestamp.before(dayAgoTimestamp)) { String location = rs.getString("location"); if (location != null) { nonNullLocations.add(location); } allLocations.add(location); } return null; } }); nonNullLocationsCount += nonNullLocations.size(); totalLocationsCount += allLocations.size(); } catch (org.springframework.dao.DataAccessException e) { throw new DataAccessException( "Error while executing '" + SQL_GET_SURVEY_RESPONSES_FOR_USER_FOR_REQUESTER + "' with parameters: " + usersUsername + ", " + requestersUsername, e); } if (totalLocationsCount == 0) { return null; } else { return new Double(nonNullLocationsCount) / new Double(totalLocationsCount); } }
From source file:org.siyapath.gossip.GossipImpl.java
/** * Merge a given set of discoveredResourceNodes with existing nodeResource Map up * to a given limit and by comparing timestamps * * @param initialMap/*from www . jav a 2 s. c om*/ * @param discoveredResourceNodes * @return new merged Set of node resource */ private Map<Integer, NodeResource> mergeNewNodeResource(Map initialMap, Map<Integer, NodeResource> discoveredResourceNodes) { Map<Integer, NodeResource> newMap = initialMap; //Iterate through the discoveredResourceNodes for (Map.Entry<Integer, NodeResource> entry : discoveredResourceNodes.entrySet()) { int key = entry.getKey(); NodeResource value = entry.getValue(); if (key != nodeContext.getNodeInfo().getNodeId()) { //Check for MemberResource Map limit if (newMap.size() < SiyapathConstants.RESOURCE_MEMBER_SET_LIMIT) { if (initialMap.containsKey(key)) { //Compare timestamps NodeResource initialResource = (NodeResource) initialMap.get(key); Timestamp initialStamp = new Timestamp(initialResource.getTimeStamp()); Timestamp newStamp = new Timestamp(value.getTimeStamp()); if (initialStamp.before(newStamp)) { newMap.put(key, value); } } else { newMap.put(key, value); } } else { //select a random node to remove int newKey = newMap.entrySet().iterator().next().getKey(); if (initialMap.containsKey(key)) { //Compare timestamps NodeResource initialResource = (NodeResource) initialMap.get(key); Timestamp initialStamp = new Timestamp(initialResource.getTimeStamp()); Timestamp newStamp = new Timestamp(value.getTimeStamp()); if (initialStamp.before(newStamp)) { newMap.put(key, value); } } else { newMap.remove(newKey); newMap.put(key, value); } } } } return newMap; }
From source file:org.kuali.kfs.module.tem.businessobject.lookup.TemProfileAddressLookupableHelperServiceImpl.java
/** * @see org.kuali.rice.kns.lookup.KualiLookupableHelperServiceImpl#getSearchResults(java.util.Map) *//*from ww w .j a va2 s .co m*/ @Override public List<? extends BusinessObject> getSearchResults(Map<String, String> fieldValues) { List<TemProfileAddress> searchResults = new ArrayList<TemProfileAddress>(); if (fieldValues.containsKey(TemPropertyConstants.TemProfileProperties.PRINCIPAL_ID) && !StringUtils.isEmpty(fieldValues.get(TemPropertyConstants.TemProfileProperties.PRINCIPAL_ID))) { final Map<String, String> kimFieldsForLookup = this.getPersonFieldValues(fieldValues); kimFieldsForLookup.put(KFSPropertyConstants.KUALI_USER_PERSON_ACTIVE_INDICATOR, KFSConstants.ACTIVE_INDICATOR); List<EntityAddressBo> addresses = (List<EntityAddressBo>) getLookupService() .findCollectionBySearchHelper(EntityAddressBo.class, kimFieldsForLookup, false); for (EntityAddressBo address : addresses) { TemProfileAddress temAddress = getTravelerService() .convertToTemProfileAddressFromKimAddress(address); temAddress.setPrincipalId(fieldValues.get(TemPropertyConstants.TemProfileProperties.PRINCIPAL_ID)); searchResults.add(temAddress); } } if (searchResults.isEmpty() && fieldValues.containsKey(TemPropertyConstants.TemProfileProperties.CUSTOMER_NUMBER) && !StringUtils .isEmpty(fieldValues.get(TemPropertyConstants.TemProfileProperties.CUSTOMER_NUMBER))) { final Map<String, String> customerFieldsForLookup = this.getCustomerFieldValues(fieldValues); LOG.debug("Using fieldsForLookup " + customerFieldsForLookup); Collection<AccountsReceivableCustomerAddress> customerAddresses = getAccountsReceivableModuleService() .searchForCustomerAddresses(customerFieldsForLookup); boolean active; for (AccountsReceivableCustomerAddress customerAddress : customerAddresses) { active = true; if (ObjectUtils.isNotNull(customerAddress)) { if (ObjectUtils.isNotNull(customerAddress.getCustomerAddressEndDate())) { Timestamp currentDateTimestamp = new Timestamp( SpringContext.getBean(DateTimeService.class).getCurrentDate().getTime()); Timestamp addressEndDateTimestamp = new Timestamp( customerAddress.getCustomerAddressEndDate().getTime()); if (addressEndDateTimestamp.before(currentDateTimestamp)) { active = false; } } } if (active) { searchResults.add(getTravelerService().convertToTemProfileAddressFromCustomer(customerAddress)); } } } CollectionIncomplete results = new CollectionIncomplete(searchResults, Long.valueOf(searchResults.size())); // sort list if default sort column given List<String> defaultSortColumns = getDefaultSortColumns(); if (defaultSortColumns.size() > 0) { Collections.sort(results, new BeanPropertyComparator(defaultSortColumns, true)); } return results; }
From source file:org.openmicroscopy.shoola.agents.dataBrowser.DataFilter.java
/** * Filters the image by date. Returns <code>true</code> if the image is * in the interval, <code>false</code> otherwise. * //from w w w . jav a2s.co m * @param image The image to handle. * @return See above. */ private boolean filterByDate(ImageData image) { Timestamp start = context.getFromDate(); Timestamp end = context.getToDate(); if (start == null && end == null) return true; Timestamp date; if (context.getTimeType() == SearchParameters.DATE_ACQUISITION) { date = image.getAcquisitionDate(); } else { date = image.getCreated(); } if (date == null) return false; if (start != null && end != null) { return date.after(start) && date.before(end); } if (start == null) { return date.before(end); } return date.after(start); }
From source file:crossbear.convergence.ConvergenceConnector.java
/** * Try to retrieve a ConvergenceCertObservation from the local cache i.e. the ConvergenceCertObservations-table * //w ww.j a va 2s.co m * @param hostPort The Hostname and port of the server from which a questionable certificate has been received * @param certSHA1 The SHA1-hash of the questionable certificate * @return If known (and not archaic): The ConvergenceCertObservation for the "hostPort"/"certSHA1"-combination, else null * @throws SQLException */ private ConvergenceCertObservation getCCOFromCache(String hostPort, String certSHA1) throws SQLException { Object[] params = { hostPort, certSHA1 }; ResultSet rs = db.executeQuery( "SELECT * FROM ConvergenceCertObservations WHERE ServerHostPort = ? AND SHA1Hash = ? LIMIT 1", params); // If the result is empty then there is no cache entry to return if (!rs.next()) { return null; } // If the cache entry is not valid anymore (and should be refreshed) then there is nothing to return Timestamp lastUpdate = rs.getTimestamp("LastUpdate"); if (lastUpdate.before(new Timestamp(System.currentTimeMillis() - this.refreshInterval))) return null; // If there is a cache entry that is currently valid: return it as ConvergenceCertObservation return new ConvergenceCertObservation(rs.getString("ServerHostPort"), rs.getString("SHA1Hash"), rs.getTimestamp("FirstObservation"), rs.getTimestamp("LastObservation"), lastUpdate); }
From source file:fr.paris.lutece.plugins.calendar.service.AgendaSubscriberService.java
/** * Validate subscription// ww w .j a va 2 s. c o m * @param request HttpServletRequest * @throws SiteMessageException site message exception */ public void doValidationSubscription(HttpServletRequest request) throws SiteMessageException { String strKey = request.getParameter(Constants.MARK_KEY); String strPluginName = request.getParameter(Constants.PARAMETER_PLUGIN_NAME); strPluginName = !(strPluginName == null) ? strPluginName : Constants.PLUGIN_NAME; Plugin plugin = PluginService.getPlugin(strPluginName); CalendarNotification calendarNotification = CalendarNotificationHome.findByPrimaryKey(strKey, plugin); if (calendarNotification != null) { Calendar calendar = GregorianCalendar.getInstance(); Timestamp todaydate = new Timestamp(calendar.getTimeInMillis()); if (todaydate.before(calendarNotification.getDateExpiry())) { String strEmail = calendarNotification.getEmail(); int nIdAgenda = calendarNotification.getIdAgenda(); //Checks if a subscriber with the same email address doesn't exist yet CalendarSubscriber subscriber = CalendarSubscriberHome.findByEmail(strEmail, plugin); if (subscriber == null) { // The email doesn't exist, so create a new subcriber subscriber = new CalendarSubscriber(); subscriber.setEmail(strEmail); CalendarSubscriberHome.create(subscriber, plugin); } CalendarSubscriberHome.addSubscriber(nIdAgenda, subscriber.getId(), new Timestamp(new Date().getTime()), plugin); CalendarNotificationHome.remove(strKey, plugin); SiteMessageService.setMessage(request, PROPERTY_SUBSCRIPTION_OK_ALERT_MESSAGE, SiteMessage.TYPE_INFO, AppPathService.getBaseUrl(request) + URL_JSP_PAGE_PORTAL, PROPERTY_SUBSCRIPTION_OK_TITLE_MESSAGE, null); } else { SiteMessageService.setMessage(request, PROPERTY_EXPIRATION_SUBSCRIPTION_ALERT_MESSAGE, SiteMessage.TYPE_ERROR, AppPathService.getBaseUrl(request) + URL_JSP_PAGE_PORTAL, PROPERTY_EXPIRATION_SUBSCRIPTION_TITLE_MESSAGE, null); } } else { SiteMessageService.setMessage(request, PROPERTY_INVALID_KEY_SUBSCRIPTION_ALERT_MESSAGE, SiteMessage.TYPE_ERROR, AppPathService.getBaseUrl(request) + URL_JSP_PAGE_PORTAL, PROPERTY_INVALID_KEY_SUBSCRIPTION_TITLE_MESSAGE, null); } }
From source file:org.kuali.kra.coi.service.impl.CoiMessagesServiceImpl.java
/** * @ Check COI to see if annual disclosure is coming due *///from www . ja v a 2s . c om public List<String> getMessages() { List<String> results = new ArrayList<String>(); UserSession session = GlobalVariables.getUserSession(); if (session != null && StringUtils.isNotEmpty(GlobalVariables.getUserSession().getPrincipalId())) { String personId = GlobalVariables.getUserSession().getPrincipalId(); String renewalDateString = getParameterService().getParameterValueAsString( Constants.MODULE_NAMESPACE_COIDISCLOSURE, ParameterConstants.DOCUMENT_COMPONENT, "ANNUAL_DISCLOSURE_RENEWAL_DATE"); LOG.debug("renewalDateString=" + renewalDateString); if (StringUtils.isNotEmpty(renewalDateString)) { Date renewalDue = null; try { renewalDue = new Date(new SimpleDateFormat("MM/dd/yyyy").parse(renewalDateString).getTime()); } catch (Exception e) { LOG.error( "***** no valid Annual Disclosure Certification renewal date found. Defaulting to anniversary of last Annual"); } String advanceNoticeString = getParameterService().getParameterValueAsString( Constants.MODULE_NAMESPACE_COIDISCLOSURE, ParameterConstants.DOCUMENT_COMPONENT, "ANNUAL_DISCLOSURE_ADVANCE_NOTICE"); int advanceDays = -1; try { advanceDays = Integer.parseInt(advanceNoticeString); } catch (Exception e) { LOG.error( "***** no valid Annual Disclosure Certification advance notice parameter found. Defaulting to 30 days."); advanceDays = 30; } LOG.debug("advanceDays=" + advanceDays); // find latest existing annual review Map<String, Object> fieldValues = new HashMap<String, Object>(); fieldValues.put("personId", personId); fieldValues.put("eventTypeCode", CoiDisclosureEventType.ANNUAL); List<CoiDisclosure> annualDisclosures = (List<CoiDisclosure>) businessObjectService .findMatching(CoiDisclosure.class, fieldValues); Timestamp lastAnnualDate = null; for (CoiDisclosure disclosure : annualDisclosures) { final Timestamp disclosureCertificationTimestamp = disclosure.getCertificationTimestamp(); if (disclosureCertificationTimestamp != null) { if (lastAnnualDate == null || lastAnnualDate.before(disclosureCertificationTimestamp)) { lastAnnualDate = disclosureCertificationTimestamp; } } } Calendar lastAnnualCalendar = null; if (lastAnnualDate != null) { lastAnnualCalendar = Calendar.getInstance(); lastAnnualCalendar.setTimeInMillis(lastAnnualDate.getTime()); } final Calendar currentTime = Calendar.getInstance(); boolean sendErrorWithDate = false; boolean sendError = false; LOG.debug("renewalDue=" + renewalDue); if (renewalDue != null) { final Calendar reminderDate = Calendar.getInstance(); reminderDate.setTimeInMillis(renewalDue.getTime()); reminderDate.add(Calendar.DATE, -advanceDays); if (currentTime.after(reminderDate) && ((lastAnnualCalendar == null) || currentTime.after(lastAnnualCalendar))) { sendErrorWithDate = true; } } else { final Calendar dueCalendarDate = Calendar.getInstance(); if (lastAnnualDate == null) { sendError = true; } else { dueCalendarDate.setTimeInMillis(lastAnnualDate.getTime()); dueCalendarDate.add(Calendar.YEAR, 1); dueCalendarDate.add(Calendar.DATE, -1); renewalDue = new Date(dueCalendarDate.getTimeInMillis()); final Calendar reminderDate = Calendar.getInstance(); reminderDate.setTimeInMillis(renewalDue.getTime()); reminderDate.add(Calendar.DATE, -advanceDays); if (currentTime.after(reminderDate)) { sendErrorWithDate = true; } } } if (sendError) { String msg = getConfigurationService() .getPropertyValueAsString("annual.disclosure.due.message"); if (!StringUtils.isEmpty(msg)) { results.add(msg); } } if (sendErrorWithDate) { String msg = getConfigurationService() .getPropertyValueAsString("annual.disclosure.due.message.with.date"); if (!StringUtils.isEmpty(msg)) { results.add(msg.replace("{0}", new SimpleDateFormat("MM/dd/yyyy").format(renewalDue))); } } } } return results; }