List of usage examples for java.util Calendar getTimeInMillis
public long getTimeInMillis()
From source file:com.cws.esolutions.security.quartz.PasswordExpirationNotifier.java
/** * @see org.quartz.Job#execute(org.quartz.JobExecutionContext) *//*from ww w . j a v a 2 s . c om*/ public void execute(final JobExecutionContext context) { final String methodName = PasswordExpirationNotifier.CNAME + "#execute(final JobExecutionContext jobContext)"; if (DEBUG) { DEBUGGER.debug(methodName); DEBUGGER.debug("JobExecutionContext: {}", context); } final Map<String, Object> jobData = context.getJobDetail().getJobDataMap(); if (DEBUG) { DEBUGGER.debug("jobData: {}", jobData); } try { UserManager manager = UserManagerFactory .getUserManager(bean.getConfigData().getSecurityConfig().getUserManager()); if (DEBUG) { DEBUGGER.debug("UserManager: {}", manager); } List<String[]> accounts = manager.listUserAccounts(); if (DEBUG) { DEBUGGER.debug("accounts: {}", accounts); } if ((accounts == null) || (accounts.size() == 0)) { return; } Calendar cal = Calendar.getInstance(); cal.add(Calendar.DATE, 30); Long expiryTime = cal.getTimeInMillis(); if (DEBUG) { DEBUGGER.debug("Calendar: {}", cal); DEBUGGER.debug("expiryTime: {}", expiryTime); } for (String[] account : accounts) { if (DEBUG) { DEBUGGER.debug("Account: {}", (Object) account); } List<Object> accountDetail = manager.loadUserAccount(account[0]); if (DEBUG) { DEBUGGER.debug("List<Object>: {}", accountDetail); } try { Email email = new SimpleEmail(); email.setHostName((String) jobData.get("mailHost")); email.setSmtpPort(Integer.parseInt((String) jobData.get("portNumber"))); if ((Boolean) jobData.get("isSecure")) { email.setSSLOnConnect(true); } if ((Boolean) jobData.get("isAuthenticated")) { email.setAuthenticator(new DefaultAuthenticator((String) jobData.get("username"), PasswordUtils.decryptText((String) (String) jobData.get("password"), (String) jobData.get("salt"), secConfig.getSecretAlgorithm(), secConfig.getIterations(), secConfig.getKeyBits(), secConfig.getEncryptionAlgorithm(), secConfig.getEncryptionInstance(), systemConfig.getEncoding()))); } email.setFrom((String) jobData.get("emailAddr")); email.addTo((String) accountDetail.get(6)); email.setSubject((String) jobData.get("messageSubject")); email.setMsg(String.format((String) jobData.get("messageBody"), (String) accountDetail.get(4))); if (DEBUG) { DEBUGGER.debug("SimpleEmail: {}", email); } email.send(); } catch (EmailException ex) { ERROR_RECORDER.error(ex.getMessage(), ex); } catch (SecurityException sx) { ERROR_RECORDER.error(sx.getMessage(), sx); } } } catch (UserManagementException umx) { ERROR_RECORDER.error(umx.getMessage(), umx); } }
From source file:com.fivesticks.time.activity.ActivityResolver.java
public Date resolve() { Calendar c = new GregorianCalendar(); c.setTime(date);//from ww w.j a va 2 s . c om int year = c.get(Calendar.YEAR); int month = c.get(Calendar.MONTH); int day = c.get(Calendar.DAY_OF_MONTH); parseActivityString(); Calendar c2 = new GregorianCalendar(year, month, day, this.getResolvedHours(), this.getResolvedMinutes()); Date ret = new Date(); ret.setTime(c2.getTimeInMillis()); return ret; }
From source file:com.hihframework.core.utils.DateUtils.java
/** * ??// w ww . ja va 2s .c o m * * @return ? */ public static java.sql.Timestamp getNowTimestamp() { Calendar cal1 = Calendar.getInstance(); return new java.sql.Timestamp(cal1.getTimeInMillis()); }
From source file:com.sonyericsson.jenkins.plugins.bfa.graphs.TimeSeriesChart.java
@Override protected JFreeChart createGraph() { TimeTableXYDataset dataset = createDataset(); ValueAxis xAxis = new DateAxis(); xAxis.setLowerMargin(0.0);/*from ww w . j a va 2 s . c o m*/ xAxis.setUpperMargin(0.0); Calendar lowerBound = getLowerGraphBound(); xAxis.setRange(lowerBound.getTimeInMillis(), Calendar.getInstance().getTimeInMillis()); NumberAxis yAxis = new NumberAxis(Y_AXIS_LABEL); yAxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits()); StackedXYBarRenderer renderer = new StackedXYBarRenderer(); renderer.setBaseToolTipGenerator(new XYToolTipGenerator() { @Override public String generateToolTip(XYDataset dataset, int series, int item) { String seriesKey = dataset.getSeriesKey(series).toString(); StringBuilder sb = new StringBuilder(); if (seriesKey.equals(GRAPH_OTHERS)) { long timeInMillis = dataset.getX(series, item).longValue(); Date time = new Date(timeInMillis); TimePeriod period = null; if (intervalSize == Calendar.DATE) { period = new Day(time); } else if (intervalSize == Calendar.HOUR_OF_DAY) { period = new Hour(time); } else if (intervalSize == Calendar.MONTH) { period = new Month(time); } List<FailureCauseTimeInterval> excludedDataList = excludedDataForPeriod.get(period); if (excludedDataList != null) { Collections.sort(excludedDataList, new Comparator<FailureCauseTimeInterval>() { @Override public int compare(FailureCauseTimeInterval o1, FailureCauseTimeInterval o2) { return o2.getNumber() - o1.getNumber(); } }); for (FailureCauseTimeInterval excludedData : excludedDataList) { sb.append(excludedData).append(" \n"); } } } else { int number = dataset.getY(series, item).intValue(); sb.append(seriesKey).append(": ").append(number); } return sb.toString(); } }); XYPlot plot = new XYPlot(dataset, xAxis, yAxis, renderer); plot.setOrientation(PlotOrientation.VERTICAL); plot.setRangeAxis(yAxis); JFreeChart chart = new JFreeChart(graphTitle, JFreeChart.DEFAULT_TITLE_FONT, plot, true); return chart; }
From source file:org.onebusaway.webapp.actions.rss.StopProblemReportsAction.java
@Override public String execute() { AgencyBean agency = _transitDataService.getAgency(_agencyId); if (agency == null) return INPUT; Calendar c = Calendar.getInstance(); long timeTo = c.getTimeInMillis(); c.add(Calendar.DAY_OF_WEEK, -_days); long timeFrom = c.getTimeInMillis(); StopProblemReportQueryBean query = new StopProblemReportQueryBean(); query.setAgencyId(_agencyId);//w w w .ja v a2s. com query.setTimeFrom(timeFrom); query.setTimeTo(timeTo); if (_status != null) query.setStatus(EProblemReportStatus.valueOf(_status)); ListBean<StopProblemReportBean> result = _transitDataService.getStopProblemReports(query); List<StopProblemReportBean> reports = result.getList(); _feed = new SyndFeedImpl(); StringBuilder title = new StringBuilder(); title.append(getText("rss.OneBusAwayStopProblemReports")); title.append(" - "); title.append(agency.getName()); title.append(" - "); title.append(getText("rss.LastXDays", Arrays.asList((Object) _days))); HttpServletRequest request = ServletActionContext.getRequest(); StringBuilder b = new StringBuilder(); b.append("http://"); b.append(request.getServerName()); if (request.getServerPort() != 80) b.append(":").append(request.getServerPort()); if (request.getContextPath() != null) b.append(request.getContextPath()); String baseUrl = b.toString(); _feed.setTitle(title.toString()); _feed.setLink(baseUrl); _feed.setDescription( getText("rss.UserSubmittedStopProblemReports", Arrays.asList((Object) agency.getName(), _days))); List<SyndEntry> entries = new ArrayList<SyndEntry>(); _feed.setEntries(entries); for (StopProblemReportBean report : reports) { StopBean stop = report.getStop(); SyndEntry entry = new SyndEntryImpl(); StringBuilder entryTitle = new StringBuilder(); if (stop == null) { entryTitle.append("stopId="); entryTitle.append(report.getStopId()); entryTitle.append(" (?)"); } else { entryTitle.append(getText("StopNum", Arrays.asList(stop.getCode()))); entryTitle.append(" - "); entryTitle.append(stop.getName()); if (stop.getDirection() != null) entryTitle.append(" - ").append(getText("bound", Arrays.asList(stop.getDirection()))); } StringBuilder entryUrl = new StringBuilder(); entryUrl.append(baseUrl); entryUrl.append("/admin/problems/stop-problem-reports!edit.action?stopId="); entryUrl.append(report.getStopId()); entryUrl.append("&id="); entryUrl.append(report.getId()); StringBuilder entryDesc = new StringBuilder(); entryDesc.append(getText("Data")); entryDesc.append(": "); entryDesc.append(report.getData()); entryDesc.append("<br/>"); if (report.getUserComment() != null) { entryDesc.append(getText("Comment")); entryDesc.append(": "); entryDesc.append(report.getUserComment()); entryDesc.append("<br/>"); } if (report.getStatus() != null) { entryDesc.append(getText("Status")); entryDesc.append(": "); entryDesc.append(report.getStatus()); entryDesc.append("<br/>"); } entry = new SyndEntryImpl(); entry.setTitle(entryTitle.toString()); entry.setLink(entryUrl.toString()); entry.setPublishedDate(new Date(report.getTime())); SyndContent description = new SyndContentImpl(); description.setType("text/html"); description.setValue(entryDesc.toString()); entry.setDescription(description); entries.add(entry); } return SUCCESS; }
From source file:org.starfishrespect.myconsumption.server.business.sensors.SensorsDataRetriever.java
/** * Retrieves and stores the data for one user * * @param onlyThisSensorId retrieve only data for one sensor with this id * @return false if something goes wrong; true otherwise */// www .ja v a2 s. c o m public boolean retrieve(List<Sensor> sensors, String onlyThisSensorId) { boolean allSuccessful = true; for (Sensor sensor : sensors) { System.out.println("Retrieve data for sensor " + sensor.getId()); try { valuesRepository.setSensor(sensor.getId()); valuesRepository.init(); if (onlyThisSensorId != null) { if (!sensor.getId().equals(onlyThisSensorId)) { continue; } } HashMap<Integer, HashMap<Integer, Integer>> sortedValues = new HashMap<Integer, HashMap<Integer, Integer>>(); Date lastValue = sensor.getLastValue(); SensorRetriever retriever = null; if (sensor instanceof FluksoSensor) { retriever = new FluksoRetriever((FluksoSensor) sensor); } if (retriever == null) { System.out.println("This sensor type has not been found!"); continue; } TreeMap<Integer, Integer> data = retriever.getDataSince(lastValue).getData(); if (data.size() != 0) { for (int key : data.keySet()) { int hour = key - key % 3600; HashMap<Integer, Integer> hourData = sortedValues.get(hour); if (hourData == null) { hourData = new HashMap<Integer, Integer>(); sortedValues.put(hour, hourData); } hourData.put(key % 3600, data.get(key)); } for (int key : sortedValues.keySet()) { Date dateKey = new Date(key * 1000L); SensorDataset newValue = new SensorDataset(dateKey); newValue.addAllValues(sortedValues.get(key)); valuesRepository.insertOrUpdate(newValue); } if (sensor.getLastValue().before(new Date(data.lastKey() * 1000L))) { sensor.setLastValue(new Date(data.lastKey() * 1000L)); } if (sensor.getFirstValue().after(new Date(data.firstKey() * 1000L)) || sensor.getFirstValue().getTime() == 0) { sensor.setFirstValue(new Date(data.firstKey() * 1000L)); } // sync operation, this avoid to insert a sensor who would have been deleted // while retrieving its data int currentUsageCount = sensorRepository.getUsageCount(sensor.getId()); if (currentUsageCount > -1) { // update, the field may have been incremented during retrieving sensor.setUsageCount(currentUsageCount); sensor.setDead(false); sensorRepository.updateSensor(sensor); } System.out.println("Retrieve successful"); } else { System.out.println("No values retrieved for this sensor"); if (!sensor.isDead()) { // test if sensor is dead ? Calendar cal = new GregorianCalendar(); cal.add(Calendar.HOUR, -6); if (sensor.getLastValue().before(new Date(cal.getTimeInMillis()))) { System.out.println( "Sensor has not sent anything in the last 6 hours! Set its status as dead."); sensor.setDead(true); sensorRepository.updateSensor(sensor); } } else { System.out.println("Sensor is still dead"); } } } catch (RetrieveException | DaoException e) { System.err.println(e.getMessage()); allSuccessful = false; } } return allSuccessful; }
From source file:com.frostwire.search.tbp.TPBSearchResult.java
private long parseCreationTime(String group) { //Today or for whatever minutes ago if (group.contains("Today") || group.contains("<b>")) { return System.currentTimeMillis(); } else if (group.contains("Y-day")) { return System.currentTimeMillis() - (24 * 60 * 60 * 1000); }/*from w ww .j av a 2 s. c om*/ Matcher OLDER_DATE_PATTERN_MATCHER = OLDER_DATE_PATTERN.matcher(group); Matcher COMMON_DATE_PATTERN_MATCHER = COMMON_DATE_PATTERN.matcher(group); Matcher DATE_TIME_PATTERN_MATCHER = DATE_TIME_PATTERN.matcher(group); Matcher RIGHT_MATCHER = (OLDER_DATE_PATTERN_MATCHER.matches()) ? OLDER_DATE_PATTERN_MATCHER : COMMON_DATE_PATTERN_MATCHER; if (!RIGHT_MATCHER.matches() && DATE_TIME_PATTERN_MATCHER.matches()) { RIGHT_MATCHER = DATE_TIME_PATTERN_MATCHER; } int month = Integer.parseInt(RIGHT_MATCHER.group(1)); int date = Integer.parseInt(RIGHT_MATCHER.group(2)); int year = 0; if (OLDER_DATE_PATTERN_MATCHER.matches() && OLDER_DATE_PATTERN_MATCHER.groupCount() == 3) { year = Integer.parseInt(RIGHT_MATCHER.group(3)); } else if (COMMON_DATE_PATTERN_MATCHER.matches() || DATE_TIME_PATTERN_MATCHER.matches()) { year = Calendar.getInstance().get(Calendar.YEAR); } Calendar instance = Calendar.getInstance(); instance.clear(); instance.set(year, month, date); return instance.getTimeInMillis(); }
From source file:ch.algotrader.adapter.dc.DCFixMarketDataMessageHandler.java
public void onMessage(MarketDataSnapshotFullRefresh marketData, SessionID sessionID) throws FieldNotFound { Symbol symbol = marketData.getSymbol(); int count = marketData.getGroupCount(NoMDEntries.FIELD); for (int i = 1; i <= count; i++) { Group group = marketData.getGroup(i, NoMDEntries.FIELD); char entryType = group.getChar(MDEntryType.FIELD); if (entryType == MDEntryType.BID || entryType == MDEntryType.OFFER) { double price = group.getDouble(MDEntryPx.FIELD); double size = group.getDouble(MDEntrySize.FIELD); Date time = group.getUtcTimeOnly(MDEntryTime.FIELD); Calendar calendar = Calendar.getInstance(); calendar.setTimeZone(TimeZone.getTimeZone("UTC")); calendar = DateUtils.truncate(calendar, Calendar.DATE); Date date = new Date(calendar.getTimeInMillis() + time.getTime()); String tickerId = symbol.getValue(); switch (entryType) { case MDEntryType.BID: if (LOGGER.isTraceEnabled()) { LOGGER.trace("{} BID {}@{}", symbol.getValue(), size, price); }/* w w w . j a v a2 s . co m*/ BidVO bidVO = new BidVO(tickerId, FeedType.DC.name(), date, price, (int) size); this.serverEngine.sendEvent(bidVO); break; case MDEntryType.OFFER: if (LOGGER.isTraceEnabled()) { LOGGER.trace("{} ASK {}@{}", symbol.getValue(), size, price); } AskVO askVO = new AskVO(tickerId, FeedType.DC.name(), date, price, (int) size); this.serverEngine.sendEvent(askVO); break; } } } }
From source file:org.psystems.dicom.browser.server.stat.StatClientRequestsChartServlet.java
/** * Returns a sample dataset.//from ww w . j a v a 2s . c o m * * @return The dataset. */ private CategoryDataset createDataset() { DefaultCategoryDataset dataset = new DefaultCategoryDataset(); Calendar calendarEnd = Calendar.getInstance(); int tzoffset = calendarEnd.getTimeZone().getOffset(calendarEnd.getTimeInMillis()); long time = calendarEnd.getTimeInMillis(); time = time - (time % (60 * 60 * 24 * 1000)) - tzoffset; calendarEnd.setTimeInMillis(time); try { Connection connection = Util.getConnection("main", getServletContext()); Calendar calendarBegin = (Calendar) calendarEnd.clone(); calendarBegin.add(Calendar.DAY_OF_MONTH, -7); getMetrics(connection, " ?", "CLIENT_CONNECTIONS", calendarBegin.getTimeInMillis(), calendarEnd.getTimeInMillis(), dataset); } catch (SQLException e) { logger.error(e); e.printStackTrace(); } return dataset; }
From source file:com.datasnap.android.cache.SettingsCache.java
/** * Returns the cached value, or calls load to get the value. * Will automatically refresh every cacheForMs, and will save the new value in the cache * afterwards./*from ww w . jav a 2 s . c o m*/ */ @Override public String get() { String json = super.get(); EasyJSONObject container = parseContainer(json); if (container != null) { // if we have it cached, let's check its time // to make sure its recent Calendar rightNow = Calendar.getInstance(); Calendar lastUpdated = container.getCalendar(LAST_UPDATED_KEY); if (lastUpdated != null) { long timeCached = rightNow.getTimeInMillis() - lastUpdated.getTimeInMillis(); if (timeCached > cacheForMs) { Logger.d("Segment.io settings cache expired, loading new settings ..."); // it's been cached too long, we need to refresh load(); } return container.toString(); } else { Logger.w("Container exists, but without last updated key. JSON: %s", container); } } return null; }