List of usage examples for java.util GregorianCalendar getTimeInMillis
public long getTimeInMillis()
From source file:org.opencms.notification.CmsNotificationCandidates.java
/** * Collects all resources that will expire in short time, or will become valid, or are not modified since a long time.<p> * /* w w w. j a v a2 s . c o m*/ * @param cms the CmsObject * * @throws CmsException if something goes wrong */ public CmsNotificationCandidates(CmsObject cms) throws CmsException { m_resources = new ArrayList(); m_cms = cms; m_cms.getRequestContext() .setCurrentProject(m_cms.readProject(OpenCms.getSystemInfo().getNotificationProject())); String folder = "/"; GregorianCalendar now = new GregorianCalendar(TimeZone.getDefault(), CmsLocaleManager.getDefaultLocale()); now.setTimeInMillis(System.currentTimeMillis()); GregorianCalendar inOneWeek = (GregorianCalendar) now.clone(); inOneWeek.add(Calendar.WEEK_OF_YEAR, 1); Iterator resources; CmsResource resource; // read all files with the 'notification-interval' property set try { resources = m_cms .readResourcesWithProperty(folder, CmsPropertyDefinition.PROPERTY_NOTIFICATION_INTERVAL) .iterator(); while (resources.hasNext()) { resource = (CmsResource) resources.next(); int notification_interval = Integer.parseInt(m_cms .readPropertyObject(resource, CmsPropertyDefinition.PROPERTY_NOTIFICATION_INTERVAL, true) .getValue()); GregorianCalendar intervalBefore = new GregorianCalendar(TimeZone.getDefault(), CmsLocaleManager.getDefaultLocale()); intervalBefore.setTimeInMillis(resource.getDateLastModified()); intervalBefore.add(Calendar.DAY_OF_YEAR, notification_interval); GregorianCalendar intervalAfter = (GregorianCalendar) intervalBefore.clone(); intervalAfter.add(Calendar.WEEK_OF_YEAR, -1); for (int i = 0; (i < 100) && intervalAfter.getTime().before(now.getTime()); i++) { if (intervalBefore.getTime().after(now.getTime())) { m_resources.add(new CmsExtendedNotificationCause(resource, CmsExtendedNotificationCause.RESOURCE_UPDATE_REQUIRED, intervalBefore.getTime())); } intervalBefore.add(Calendar.DAY_OF_YEAR, notification_interval); intervalAfter.add(Calendar.DAY_OF_YEAR, notification_interval); } } } catch (CmsDbEntryNotFoundException e) { // no resources with property 'notification-interval', ignore } // read all files that were not modified longer than the max notification-time GregorianCalendar oneYearAgo = (GregorianCalendar) now.clone(); oneYearAgo.add(Calendar.DAY_OF_YEAR, -OpenCms.getSystemInfo().getNotificationTime()); // create a resource filter to get the resources with CmsResourceFilter filter = CmsResourceFilter.IGNORE_EXPIRATION .addRequireLastModifiedBefore(oneYearAgo.getTimeInMillis()); resources = m_cms.readResources(folder, filter).iterator(); while (resources.hasNext()) { resource = (CmsResource) resources.next(); m_resources.add(new CmsExtendedNotificationCause(resource, CmsExtendedNotificationCause.RESOURCE_OUTDATED, new Date(resource.getDateLastModified()))); } // get all resources that will expire within the next week CmsResourceFilter resourceFilter = CmsResourceFilter.IGNORE_EXPIRATION .addRequireExpireBefore(inOneWeek.getTimeInMillis()); resourceFilter = resourceFilter.addRequireExpireAfter(now.getTimeInMillis()); resources = m_cms.readResources(folder, resourceFilter).iterator(); while (resources.hasNext()) { resource = (CmsResource) resources.next(); m_resources.add(new CmsExtendedNotificationCause(resource, CmsExtendedNotificationCause.RESOURCE_EXPIRES, new Date(resource.getDateExpired()))); } // get all resources that will release within the next week resourceFilter = CmsResourceFilter.IGNORE_EXPIRATION.addRequireReleaseBefore(inOneWeek.getTimeInMillis()); resourceFilter = resourceFilter.addRequireReleaseAfter(now.getTimeInMillis()); resources = m_cms.readResources(folder, resourceFilter).iterator(); while (resources.hasNext()) { resource = (CmsResource) resources.next(); m_resources.add(new CmsExtendedNotificationCause(resource, CmsExtendedNotificationCause.RESOURCE_RELEASE, new Date(resource.getDateReleased()))); } }
From source file:com.projity.options.CalendarOption.java
public long makeValidEnd(long end, boolean force) { end = DateTime.minuteFloor(end);/*from w w w . ja va 2 s. c om*/ GregorianCalendar cal = DateTime.calendarInstance(); cal.setTimeInMillis(end); if (force || cal.get(GregorianCalendar.HOUR_OF_DAY) == 0 && cal.get(GregorianCalendar.MINUTE) == 0) { cal.set(GregorianCalendar.HOUR_OF_DAY, getDefaultEndTime().get(GregorianCalendar.HOUR_OF_DAY)); cal.set(GregorianCalendar.MINUTE, getDefaultEndTime().get(GregorianCalendar.MINUTE)); } return cal.getTimeInMillis(); }
From source file:com.workplacesystems.queuj.process.ProcessScheduler.java
@Override protected void doRun() { synchronized (this) { FilterableArrayList list = null; do_notify = false; try {/* w w w . ja v a 2s .c om*/ // Check whether we were interrupted while outside of the sync if (!interrupted()) { // If process_times is empty just continue // Use Iterator for performance Iterator i = process_times.keySet().iterator(); if (i.hasNext()) { // Get the first scheduled time GregorianCalendar gc_key = (GregorianCalendar) i.next(); i = null; // Calculate how long we need to wait if at all and wait long when = gc_key.getTimeInMillis(); long now; while ((now = (new GregorianCalendar()).getTimeInMillis()) < when) { long wait_time = when - now; if (log.isDebugEnabled()) log.debug("Waiting for " + wait_time); wait(wait_time); } // Remove the current scheduled time and all processes // but keep a local copy (list). list = (FilterableArrayList) process_times.remove(gc_key); if (list != null) { do_notify = true; (new IterativeCallback() { @Override protected void nextObject(Object obj) { processes.put(obj, null); } }).iterate(list); } } } } catch (InterruptedException ie) { log.debug("process_scheduler thread InterruptedException: " + hashCode()); } if (do_notify) unParkProcesses(list, null); } log.debug("process_scheduler thread stopped: " + hashCode()); }
From source file:com.blanyal.remindme.MainActivity.java
private void generateFakeCall(int x, String attackmsg, boolean isExp) { //Log.v("vbharill","fake call started"); GregorianCalendar cal = new GregorianCalendar(); long curr_time = cal.getTimeInMillis(); Intent i = new Intent(); i.setAction("smsschedulerAlarmReceiverINTENT_FILTER"); i.putExtra("datetimeCreated", -1 * curr_time); i.putExtra("callno", x); i.putExtra("datetimeScheduled", curr_time); i.putExtra("recipientNumber", "9495015557"); i.putExtra("recipientName", "varun"); i.putExtra("message", "hi from fake service implicit."); i.putExtra("attackmsg", attackmsg); if (!isExp) { startService(i);/*from www.j a v a2 s. co m*/ } else { Intent ei = convertImplicitIntentToExplicitIntent(i, getApplicationContext()); if (ei != null) { getApplicationContext().startService(ei); } else { Log.v("vbharill", "going to start the service."); System.out.print("ei was null"); } } //startService(i); // Intent ei = convertImplicitIntentToExplicitIntent(i,getApplicationContext()); // if(ei != null) { // getApplicationContext().startService(ei); // } else { // Log.v("vbharill","going to start the service."); // System.out.print("ei was null"); // } // Log.v("vbharill","going to start the service."); // Log.v("vbharill","line after starting service."); // Log.v("vbharill","fake call ended"); /*public static final String COLUMN_TIMESTAMP_CREATED = "datetimeCreated"; public static final String COLUMN_TIMESTAMP_SCHEDULED = "datetimeScheduled"; public static final String COLUMN_RECIPIENT_NUMBER = "recipientNumber"; public static final String COLUMN_RECIPIENT_NAME = "recipientName"; public static final String COLUMN_MESSAGE = "message"; public static final String COLUMN_STATUS = "status"; public static final String COLUMN_RESULT = "result";*/ }
From source file:eu.tango.energymodeller.datasourceclient.WattsUpMeterDataSourceAdaptor.java
@Override public synchronized double getCpuUtilisation(Host host, int lastNSeconds) { double count = 0.0; double sumOfUtil = 0.0; GregorianCalendar cal = new GregorianCalendar(); long now = TimeUnit.MILLISECONDS.toSeconds(cal.getTimeInMillis()); long nowMinustime = now - lastNSeconds; CopyOnWriteArrayList<CPUUtilisation> list = new CopyOnWriteArrayList<>(); list.addAll(cpuMeasure);/*from ww w. j av a 2 s . c o m*/ for (Iterator<CPUUtilisation> it = list.iterator(); it.hasNext();) { CPUUtilisation util = it.next(); if (util.isOlderThan(nowMinustime)) { list.remove(util); cpuMeasure.remove(util); } else { sumOfUtil = sumOfUtil + util.getCpuBusy(); count = count + 1; } } if (count == 0) { return 0.0; } return sumOfUtil / count; }
From source file:nodomain.freeyourgadget.gadgetbridge.externalevents.AlarmReceiver.java
@Override public void onReceive(Context context, Intent intent) { if (!GBApplication.getPrefs().getBoolean("send_sunrise_sunset", false)) { LOG.info("won't send sunrise and sunset events (disabled in preferences)"); return;//from w w w. j av a 2s. c om } LOG.info("will resend sunrise and sunset events"); final GregorianCalendar dateTimeTomorrow = new GregorianCalendar(TimeZone.getTimeZone("UTC")); dateTimeTomorrow.set(Calendar.HOUR, 0); dateTimeTomorrow.set(Calendar.MINUTE, 0); dateTimeTomorrow.set(Calendar.SECOND, 0); dateTimeTomorrow.set(Calendar.MILLISECOND, 0); dateTimeTomorrow.add(GregorianCalendar.DAY_OF_MONTH, 1); /* * rotate ids ud reuse the id from two days ago for tomorrow, this way we will have * sunrise /sunset for 3 days while sending only sunrise/sunset per day */ byte id_tomorrow = (byte) ((dateTimeTomorrow.getTimeInMillis() / (1000L * 60L * 60L * 24L)) % 3); GBApplication.deviceService().onDeleteCalendarEvent(CalendarEventSpec.TYPE_SUNRISE, id_tomorrow); GBApplication.deviceService().onDeleteCalendarEvent(CalendarEventSpec.TYPE_SUNSET, id_tomorrow); Prefs prefs = GBApplication.getPrefs(); float latitude = prefs.getFloat("location_latitude", 0); float longitude = prefs.getFloat("location_longitude", 0); LOG.info("got longitude/latitude from preferences: " + latitude + "/" + longitude); if (ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED && prefs.getBoolean("use_updated_location_if_available", false)) { LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE); Criteria criteria = new Criteria(); String provider = locationManager.getBestProvider(criteria, false); if (provider != null) { Location lastKnownLocation = locationManager.getLastKnownLocation(provider); if (lastKnownLocation != null) { latitude = (float) lastKnownLocation.getLatitude(); longitude = (float) lastKnownLocation.getLongitude(); LOG.info("got longitude/latitude from last known location: " + latitude + "/" + longitude); } } } GregorianCalendar[] sunriseTransitSetTomorrow = SPA.calculateSunriseTransitSet(dateTimeTomorrow, latitude, longitude, DeltaT.estimate(dateTimeTomorrow)); CalendarEventSpec calendarEventSpec = new CalendarEventSpec(); calendarEventSpec.durationInSeconds = 0; calendarEventSpec.description = null; calendarEventSpec.type = CalendarEventSpec.TYPE_SUNRISE; calendarEventSpec.title = "Sunrise"; if (sunriseTransitSetTomorrow[0] != null) { calendarEventSpec.id = id_tomorrow; calendarEventSpec.timestamp = (int) (sunriseTransitSetTomorrow[0].getTimeInMillis() / 1000); GBApplication.deviceService().onAddCalendarEvent(calendarEventSpec); } calendarEventSpec.type = CalendarEventSpec.TYPE_SUNSET; calendarEventSpec.title = "Sunset"; if (sunriseTransitSetTomorrow[2] != null) { calendarEventSpec.id = id_tomorrow; calendarEventSpec.timestamp = (int) (sunriseTransitSetTomorrow[2].getTimeInMillis() / 1000); GBApplication.deviceService().onAddCalendarEvent(calendarEventSpec); } }
From source file:eu.tango.energymodeller.datasourceclient.WattsUpMeterDataSourceAdaptor.java
/** * This registers the required meters for the energy modeller. * * @param meter The meter to register the event listeners for */// ww w .jav a 2s. c om private void registerEventListeners(WattsUp meter) { meter.registerListener(new WattsUpDataAvailableListener() { @Override public void processDataAvailable(final WattsUpDataAvailableEvent event) { GregorianCalendar calander = new GregorianCalendar(); long clock = TimeUnit.MILLISECONDS.toSeconds(calander.getTimeInMillis()); HostMeasurement measurement = new HostMeasurement(host, clock); WattsUpPacket[] values = event.getValue(); String watts = values[0].get("watts").getValue(); String volts = values[0].get("volts").getValue(); String amps = values[0].get("amps").getValue(); String wattskwh = values[0].get("wattskwh").getValue(); watts = "" + changeOrderOfMagnitude(watts, 1); volts = "" + changeOrderOfMagnitude(volts, 1); amps = "" + changeOrderOfMagnitude(amps, 3); measurement .addMetric(new MetricValue(KpiList.POWER_KPI_NAME, KpiList.POWER_KPI_NAME, watts, clock)); measurement.addMetric( new MetricValue(KpiList.ENERGY_KPI_NAME, KpiList.ENERGY_KPI_NAME, wattskwh, clock)); measurement.addMetric(new MetricValue(VOLTAGE_KPI_NAME, VOLTAGE_KPI_NAME, volts, clock)); measurement.addMetric(new MetricValue(CURRENT_KPI_NAME, CURRENT_KPI_NAME, amps, clock)); try { CpuPerc cpu = sigar.getCpuPerc(); cpuMeasure.add(new CPUUtilisation(clock, cpu)); Mem mem = sigar.getMem(); measurement.addMetric(new MetricValue(KpiList.CPU_IDLE_KPI_NAME, KpiList.CPU_IDLE_KPI_NAME, cpu.getIdle() * 100 + "", clock)); measurement.addMetric(new MetricValue(KpiList.CPU_INTERUPT_KPI_NAME, KpiList.CPU_INTERUPT_KPI_NAME, cpu.getIrq() * 100 + "", clock)); measurement.addMetric(new MetricValue(KpiList.CPU_IO_WAIT_KPI_NAME, KpiList.CPU_IO_WAIT_KPI_NAME, cpu.getWait() * 100 + "", clock)); measurement.addMetric(new MetricValue(KpiList.CPU_NICE_KPI_NAME, KpiList.CPU_NICE_KPI_NAME, cpu.getNice() * 100 + "", clock)); measurement.addMetric(new MetricValue(KpiList.CPU_SOFT_IRQ_KPI_NAME, KpiList.CPU_SOFT_IRQ_KPI_NAME, cpu.getIrq() * 100 + "", clock)); measurement.addMetric(new MetricValue(KpiList.CPU_STEAL_KPI_NAME, KpiList.CPU_STEAL_KPI_NAME, cpu.getStolen() * 100 + "", clock)); measurement.addMetric(new MetricValue(KpiList.CPU_SYSTEM_KPI_NAME, KpiList.CPU_SYSTEM_KPI_NAME, cpu.getSys() * 100 + "", clock)); measurement.addMetric(new MetricValue(KpiList.CPU_USER_KPI_NAME, KpiList.CPU_USER_KPI_NAME, cpu.getUser() * 100 + "", clock)); measurement.addMetric( new MetricValue(KpiList.MEMORY_AVAILABLE_KPI_NAME, KpiList.MEMORY_AVAILABLE_KPI_NAME, (int) (Double.valueOf(mem.getActualFree()) / 1048576) + "", clock)); measurement .addMetric(new MetricValue(KpiList.MEMORY_TOTAL_KPI_NAME, KpiList.MEMORY_TOTAL_KPI_NAME, (int) (Double.valueOf(mem.getTotal()) / 1048576) + "", clock)); } catch (SigarException ex) { Logger.getLogger(WattsUpMeterDataSourceAdaptor.class.getName()).log(Level.SEVERE, null, ex); } current = measurement; if (lowest == null || measurement.getPower() < lowest.getPower()) { lowest = measurement; } if (highest == null || measurement.getPower() > highest.getPower()) { highest = measurement; } } }); meter.registerListener(new WattsUpMemoryCleanListener() { @Override public void processWattsUpReset(WattsUpMemoryCleanEvent event) { System.out.println("WattsUp Meter Memory Just Cleaned"); } }); meter.registerListener(new WattsUpStopLoggingListener() { @Override public void processStopLogging(WattsUpStopLoggingEvent event) { System.out.println("WattsUp Meter Logging Stopped"); } }); meter.registerListener(new WattsUpDisconnectListener() { @Override public void onDisconnect(WattsUpDisconnectEvent event) { System.out.println("WattsUp Meter Client Exiting"); } }); }
From source file:com.krminc.phr.security.PHRRealm.java
private void InvalidPasswordAttempt(String username) throws NoSuchUserException { String query = "SELECT failed_password_attempts, failed_password_window_start FROM user_users WHERE username = ?"; ResultSet rs = null;/*from w ww. j ava 2s.c o m*/ PreparedStatement st = null; Timestamp windowStart = null; int failedAttemptsVal = 0; try { createDS(); conn = ds.getNonTxConnection(); st = conn.prepareStatement(query); st.setString(1, username); rs = st.executeQuery(); } catch (Exception e) { log("Error getting roles from database"); log(e.getMessage()); rs = null; } finally { try { conn.close(); } catch (Exception e) { log(e.getMessage()); } conn = null; } if (rs != null) { try { rs.beforeFirst(); while (rs.next()) { failedAttemptsVal = rs.getInt(1); windowStart = rs.getTimestamp(2); } } catch (Exception e) { log("Error getting invalid attempt values from resultset"); log(e.getMessage()); } finally { try { st.close(); rs.close(); } catch (Exception e) { log(e.getMessage()); } } } else { throw new NoSuchUserException("User not available."); } //take values and decide whether to lock account, increment failed attempts, or start new failure window if (windowStart != null) { //check if user has more than X previously existing failed logins if (Integer.valueOf(failedAttemptsVal).compareTo(failedAttempts) >= 0) { //lock out doFailedUpdate(username, null, failedAttemptsVal + 1, true); } else { //dont lock account, just increment failed attempts doFailedUpdate(username, windowStart, failedAttemptsVal + 1, false); } } else { //windowStart is null, set to now and set failed attempts to 1 GregorianCalendar tempCal = new GregorianCalendar(); windowStart = new java.sql.Timestamp(tempCal.getTimeInMillis()); failedAttemptsVal = 1; doFailedUpdate(username, windowStart, failedAttemptsVal, false); } }
From source file:com.krminc.phr.security.PHRRealm.java
private void doFailedUpdate(String username, java.sql.Timestamp windowStart, int failedAttempts, boolean setLock) { String query = "UPDATE user_users SET failed_password_attempts = ? , failed_password_window_start = ? , is_locked_out = ?, lockout_begin = ? WHERE username = ?"; PreparedStatement st = null;//from ww w .j a va 2 s . c o m java.sql.Timestamp lockoutBegin = null; if (setLock) { GregorianCalendar tempCal = new GregorianCalendar(java.util.TimeZone.getTimeZone("GMT")); lockoutBegin = new java.sql.Timestamp(tempCal.getTimeInMillis()); } try { createDS(); //TX for UPDATE conn = ds.getConnection(); st = conn.prepareStatement(query); st.setInt(1, failedAttempts); st.setTimestamp(2, windowStart); st.setBoolean(3, setLock); st.setTimestamp(4, lockoutBegin); st.setString(5, username); st.executeUpdate(); } catch (Exception e) { log("Error updating failed password values"); log(e.getMessage()); } finally { try { st.close(); conn.close(); } catch (Exception e) { log(e.getMessage()); } conn = null; } }
From source file:org.hyperic.hq.ui.action.resource.common.monitor.alerts.PortalAction.java
public ActionForward listAlerts(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { setResource(request, response);//from w w w . j a va 2 s. c o m super.setNavMapLocation(request, mapping, Constants.ALERT_LOC); // clean out the return path SessionUtils.resetReturnPath(request.getSession()); // set the return path try { setReturnPath(request, mapping); } catch (ParameterNotFoundException pne) { log.debug(pne); } GregorianCalendar cal = new GregorianCalendar(); try { Integer year = RequestUtils.getIntParameter(request, "year"); Integer month = RequestUtils.getIntParameter(request, "month"); Integer day = RequestUtils.getIntParameter(request, "day"); cal.set(Calendar.YEAR, year.intValue()); cal.set(Calendar.MONTH, month.intValue()); cal.set(Calendar.DAY_OF_MONTH, day.intValue()); request.setAttribute("date", new Long(cal.getTimeInMillis())); } catch (ParameterNotFoundException e) { request.setAttribute("date", new Long(System.currentTimeMillis())); } cal.set(Calendar.HOUR_OF_DAY, 0); cal.set(Calendar.MINUTE, 0); cal.set(Calendar.SECOND, 0); Portal portal = Portal.createPortal(); AppdefEntityID aeid = RequestUtils.getEntityId(request); boolean canTakeAction = false; try { int sessionId = RequestUtils.getSessionId(request).intValue(); AuthzSubject subject = authzBoss.getCurrentSubject(sessionId); // ...check that the user can fix/acknowledge... alertPermissionManager.canFixAcknowledgeAlerts(subject, aeid); canTakeAction = true; } catch (PermissionException e) { // ...the user can't fix/acknowledge... } request.setAttribute(Constants.CAN_TAKE_ACTION_ON_ALERT_ATTR, canTakeAction); setTitle(aeid, portal, "alerts.alert.platform.AlertList.Title"); portal.setDialog(false); if (aeid.isGroup()) { portal.addPortlet(new Portlet(".events.group.alert.list"), 1); // Set the total alerts int sessionId = RequestUtils.getSessionId(request).intValue(); request.setAttribute("listSize", new Integer(galertBoss.countAlertLogs(sessionId, aeid.getId(), cal.getTimeInMillis(), cal.getTimeInMillis() + Constants.DAYS))); } else { portal.addPortlet(new Portlet(".events.alert.list"), 1); } request.setAttribute(Constants.PORTAL_KEY, portal); return null; }