Example usage for java.util GregorianCalendar getTimeInMillis

List of usage examples for java.util GregorianCalendar getTimeInMillis

Introduction

In this page you can find the example usage for java.util GregorianCalendar getTimeInMillis.

Prototype

public long getTimeInMillis() 

Source Link

Document

Returns this Calendar's time value in milliseconds.

Usage

From source file:org.tolven.gen.model.RepeatScenario.java

/**
 * To apply this scenario, we will modify the start time of the scenario to repeat to
 * be the selected event time. For example, if the repeat interval is one year (in milliseconds), 
 * and apply is called with a start time around 1992, then the child scenario is called
 * with a start time of 1977, 1978, to the end-time (present day or death being most common
 * for chronic diseases or the duration of the disease for acute diseases).
 * Since most repeat scenarios represent followup activity, the start date is often offset 
 * by some interval. Thus, with a startOffset of 12 (months), and the 
 * startDate were to be 1976, then the first "repeat" will be around 1977. 
 *//* ww w  .j ava  2  s .co  m*/
public boolean apply(GenMedical patient, Date startTime, Date endTime, RandomData rng) {
    GregorianCalendar clock = new GregorianCalendar();
    clock.setTime(startTime);
    boolean rslt = false;
    int count = -startOffset;
    //      TolvenLogger.info( getTitle() + " of " + getScenarioToRepeat().getTitle() + " Ranging from " + clock.getTime() + " to " + endTime, RepeatScenario.class); 
    while (true) {
        if (count++ >= MAX_REPEAT)
            throw new IllegalArgumentException("Maximum repeat for scenario " + getTitle());
        if (count > maxCount)
            break;
        // Now pick a random time around that clock setting unless this is the first instance or there is no deviation
        Date instanceTime;
        if (getDeviation() == 0.0 || count <= 0) {
            instanceTime = new Date(clock.getTimeInMillis());
        } else {
            instanceTime = new Date(((long) rng.nextGaussian(clock.getTimeInMillis(), getDeviationMs())));
        }
        // Needs to be before the end time, otherwise, we're done.
        if (instanceTime.after(endTime))
            break;
        // Now apply the instance (if we're past the startOffset)
        if (count > 0) {
            getScenarioToRepeat().apply(patient, instanceTime, endTime, rng);
        }
        // Reset the clock if requested
        if (resetClock)
            clock.setTime(instanceTime);
        // Advance the clock with no randomness
        clock.add(intervalType, intervalValue);
        rslt = true;
    }
    // If there's a future count, then we keep going by calling the futureScenario
    // Note: Logic is similar but not identical to above.
    for (int x = 0; x < getFutureCount(); x++) {
        Date instanceTime;
        if (getDeviation() == 0.0) {
            instanceTime = new Date(clock.getTimeInMillis());
        } else {
            instanceTime = new Date(((long) rng.nextGaussian(clock.getTimeInMillis(), getDeviationMs())));
        }
        // 
        // In the future, start and end time are the same.
        getFutureScenario().apply(patient, instanceTime, instanceTime, rng);
        // Reset the clock if requested
        if (resetClock)
            clock.setTime(instanceTime);
        // Advance the clock with no randomness
        clock.add(intervalType, intervalValue);
    }
    return rslt;
}

From source file:io.n7.calendar.caldav.CalDAVService.java

private long parseDateTimeToMillis(String date, String tzid) {
    GregorianCalendar cal = new GregorianCalendar(Integer.parseInt(date.substring(0, 4)),
            Integer.parseInt(date.substring(4, 6)) - 1, Integer.parseInt(date.substring(6, 8)),
            Integer.parseInt(date.substring(9, 11)), Integer.parseInt(date.substring(11, 13)),
            Integer.parseInt(date.substring(13, 15)));
    TimeZone tz = TimeZone.getTimeZone(tzid);
    cal.setTimeZone(tz);/*w  w w .  j  av a  2 s. c o m*/
    return cal.getTimeInMillis();
}

From source file:com.forrestguice.suntimeswidget.SuntimesUtils.java

@SuppressWarnings("ConstantConditions")
public TimeDisplayText timeDeltaLongDisplayString(long timeSpan1, long timeSpan2, boolean showSeconds) {
    String value = strSpace;/*  w  w  w .ja  v  a 2  s .  com*/
    String units = strEmpty;
    String suffix = strEmpty;

    long timeSpan = timeSpan2 - timeSpan1;
    GregorianCalendar d = new GregorianCalendar();
    d.setTimeInMillis(timeSpan);
    long timeInMillis = d.getTimeInMillis();

    long numberOfSeconds = timeInMillis / 1000;
    suffix += ((numberOfSeconds > 0) ? strTimeLonger : strTimeShorter);
    numberOfSeconds = Math.abs(numberOfSeconds);

    long numberOfMinutes = numberOfSeconds / 60;
    long numberOfHours = numberOfMinutes / 60;
    long numberOfDays = numberOfHours / 24;
    long numberOfWeeks = numberOfDays / 7;
    long numberOfYears = numberOfDays / 365;

    long remainingWeeks = (long) (numberOfWeeks % 52.1429);
    long remainingDays = numberOfDays % 7;
    //long remainingDays = numberOfDays % 365;
    long remainingHours = numberOfHours % 24;
    long remainingMinutes = numberOfMinutes % 60;
    long remainingSeconds = numberOfSeconds % 60;

    boolean showingYears = (numberOfYears > 0);
    if (showingYears)
        value += String.format(strTimeDeltaFormat, numberOfYears, strYears);

    boolean showingWeeks = (numberOfWeeks > 0);
    if (showingWeeks)
        value += (showingYears ? strSpace : strEmpty)
                + String.format(strTimeDeltaFormat, remainingWeeks, strWeeks);

    boolean showingDays = (remainingDays > 0);
    if (showingDays)
        value += (showingYears || showingWeeks ? strSpace : strEmpty)
                + String.format(strTimeDeltaFormat, remainingDays, strDays);

    boolean showingHours = (!showingYears && !showingWeeks && remainingHours > 0);
    if (showingHours)
        value += (showingYears || showingWeeks || showingDays ? strSpace : strEmpty)
                + String.format(strTimeDeltaFormat, remainingHours, strHours);

    boolean showingMinutes = (!showingDays && !showingWeeks && !showingYears && remainingMinutes > 0);
    if (showingMinutes)
        value += (showingYears || showingWeeks || showingDays || showingHours ? strSpace : strEmpty)
                + String.format(strTimeDeltaFormat, remainingMinutes, strMinutes);

    boolean showingSeconds = (showSeconds && !showingDays && !showingWeeks && !showingYears
            && (remainingSeconds > 0));
    if (showingSeconds)
        value += (showingHours || showingMinutes ? strSpace : strEmpty)
                + String.format(strTimeDeltaFormat, remainingSeconds, strSeconds);

    if (!showingSeconds && !showingMinutes && !showingHours && !showingDays && !showingWeeks && !showingYears) {
        if (showSeconds)
            value += String.format(strTimeDeltaFormat, "0", strSeconds);
        else
            value += String.format(strTimeDeltaFormat, "1", strMinutes);
    }

    TimeDisplayText text = new TimeDisplayText(value.trim(), units, suffix);
    text.setRawValue(timeSpan);
    return text;
}

From source file:eu.tango.energymodeller.datasourceclient.SlurmDataSourceAdaptor.java

/**
 * Parses a line from slurm and adds the data into the data source adaptor.
 *
 * @param line//from   w  w w . j  a  va 2 s.c o m
 */
private void parse(String line) {
    try {
        boolean valid = true;
        GregorianCalendar calander = new GregorianCalendar();
        long clock = TimeUnit.MILLISECONDS.toSeconds(calander.getTimeInMillis());
        String[] values = line.split(";");
        String watts = getValue("CurrentWatts", values);
        String wattskwh = getValue("ConsumedJoules", values);
        String hostname = getValue("NodeName", values);
        String state = getValue("State", values);
        if (hostname.isEmpty()) {
            return;
        }
        String hostId = hostname.replaceAll("[^0-9]", "");
        CircularFifoQueue<SlurmDataSourceAdaptor.CPUUtilisation> lastCpuMeasurements = cpuMeasure.get(hostname);
        if (lastCpuMeasurements == null) {
            //Needs enough information to cover any recent queries of cpu utilisation, thus gather last 10mins of data
            lastCpuMeasurements = new CircularFifoQueue(
                    (int) TimeUnit.MINUTES.toSeconds(10) / poller.getPollRate());
            cpuMeasure.put(hostname, lastCpuMeasurements);
        }
        Host host = getHostByName(hostname);

        //Check for need to disover host
        if (host == null) {
            host = new Host(Integer.parseInt(hostId), hostname);
            hosts.put(hostname, host);
        }
        host.setAvailable(!state.isEmpty() && !state.equals("DOWN*"));
        /**
         * The further metrics from this host are not relevant and may cause
         * parse errors
         */
        if (!host.isAvailable()) {
            return;
        }

        //Note CPU Load = N/A when the node is down, but perhas might occur in some other case. The previous guard should prevent this error.
        String cpuLoad = getValue("CPULoad", values);
        if (!cpuLoad.equals("N/A") && cpuLoad.matches("-?\\d+(\\.\\d+)?")) {
            lastCpuMeasurements.add(new SlurmDataSourceAdaptor.CPUUtilisation(clock, hostname,
                    (Double.valueOf(cpuLoad)) * 100));
        }
        HostMeasurement measurement = new HostMeasurement(host, clock);
        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));
        readGresString(values, measurement, clock);
        readGresUsedString(values, measurement, clock);
        readGenericMetrics(values, measurement, clock);
        double cpuUtil = Double.valueOf(cpuLoad) / Double.valueOf(getValue("CPUTot", values));
        valid = valid && validatedAddMetric(measurement, new MetricValue(KpiList.CPU_SPOT_USAGE_KPI_NAME,
                KpiList.CPU_SPOT_USAGE_KPI_NAME, cpuUtil * 100 + "", clock));
        valid = valid && validatedAddMetric(measurement, new MetricValue(KpiList.CPU_IDLE_KPI_NAME,
                KpiList.CPU_IDLE_KPI_NAME, ((1 - cpuUtil)) * 100 + "", clock));
        if (!valid) {
            System.out.println("The measurement taken was invalid");
            return;
        }

        valid = valid && validatedAddMetric(measurement,
                new MetricValue(KpiList.MEMORY_AVAILABLE_KPI_NAME, KpiList.MEMORY_AVAILABLE_KPI_NAME,
                        (int) (Double.valueOf(getValue("FreeMem", values)) / 1048576) + "", clock));
        valid = valid && validatedAddMetric(measurement,
                new MetricValue(KpiList.MEMORY_TOTAL_KPI_NAME, KpiList.MEMORY_TOTAL_KPI_NAME,
                        (int) (Double.valueOf(getValue("RealMemory", values)) / 1048576) + "", clock));

        if (!valid) {
            return;
        }
        current.put(hostname, measurement);
        if (lowest.get(hostname) == null || measurement.getPower() < lowest.get(hostname).getPower()) {
            lowest.put(hostname, measurement);
        }
        if (highest.get(hostname) == null || measurement.getPower() > highest.get(hostname).getPower()) {
            highest.put(hostname, measurement);
        }
    } catch (NumberFormatException ex) {
        //Ignore these errors and carry on. It may just be the header line.
        Logger.getLogger(SlurmDataSourceAdaptor.class.getName()).log(Level.SEVERE, "Unexpected number format",
                ex);
    }
}

From source file:org.apache.juddi.api.impl.UDDISubscriptionImpl.java

/**
 * Will add the expiration date to the provided subscription request.  Date is earlier of user provided date and the system default
 * /*from ww  w . java 2s .  com*/
 * @param apiSubscription
 * @throws DispositionReportFaultMessage
 */
private void doSubscriptionExpirationDate(org.uddi.sub_v3.Subscription apiSubscription)
        throws DispositionReportFaultMessage {

    int subscriptionExpirationDays = DEFAULT_SUBSCRIPTIONEXPIRATION_DAYS;
    try {
        subscriptionExpirationDays = AppConfig.getConfiguration()
                .getInt(Property.JUDDI_SUBSCRIPTION_EXPIRATION_DAYS);
    } catch (ConfigurationException ce) {
        throw new FatalErrorException(new ErrorMessage("errors.configuration.Retrieval"));
    }

    GregorianCalendar expirationDate = new GregorianCalendar();
    expirationDate.add(GregorianCalendar.DAY_OF_MONTH, subscriptionExpirationDays);

    // The expiration date is the earlier of the provided date and that specified by the parameter.
    if (apiSubscription.getExpiresAfter() != null) {
        GregorianCalendar userExpiration = apiSubscription.getExpiresAfter().toGregorianCalendar();
        if (userExpiration.getTimeInMillis() < expirationDate.getTimeInMillis())
            expirationDate.setTimeInMillis(userExpiration.getTimeInMillis());
    }

    try {
        DatatypeFactory df = DatatypeFactory.newInstance();
        apiSubscription.setExpiresAfter(df.newXMLGregorianCalendar(expirationDate));
    } catch (DatatypeConfigurationException ce) {
        throw new FatalErrorException(new ErrorMessage("errors.Unspecified"));
    }

}

From source file:org.dmfs.tasks.notification.NotificationUpdaterService.java

@TargetApi(Build.VERSION_CODES.KITKAT)
private void updateNextDayAlarm() {
    Intent intent = new Intent(this, NotificationUpdaterService.class);
    intent.setAction(ACTION_NEXT_DAY);//  w w w  .  j  a v  a 2 s  .  c  om
    mDateChangePendingIntent = PendingIntent.getService(this, 0, intent, 0);

    // set alarm to update the next day
    GregorianCalendar tomorrow = new GregorianCalendar();
    tomorrow.add(Calendar.DAY_OF_YEAR, 1);
    tomorrow.set(Calendar.HOUR_OF_DAY, 0);
    tomorrow.set(Calendar.MINUTE, 0);
    tomorrow.set(Calendar.SECOND, 0);
    tomorrow.set(Calendar.MILLISECOND, 0);

    AlarmManager alarmManager = (AlarmManager) this.getSystemService(Context.ALARM_SERVICE);
    if (VERSION.SDK_INT >= VERSION_CODES.KITKAT) {
        alarmManager.setWindow(AlarmManager.RTC, tomorrow.getTimeInMillis(), 1000, mDateChangePendingIntent);
    } else {
        alarmManager.set(AlarmManager.RTC, tomorrow.getTimeInMillis(), mDateChangePendingIntent);
    }
}

From source file:com.zimbra.qa.unittest.TestCalDav.java

public static ParsedDateTime parsedDateTime(int year, int month, int day, int hour, int min,
        ICalTimeZone icalTimeZone) {/*from w ww  .  jav a2  s .  com*/
    GregorianCalendar date = new GregorianCalendar();
    date.set(java.util.Calendar.YEAR, year);
    date.set(java.util.Calendar.MONTH, month);
    date.set(java.util.Calendar.DAY_OF_MONTH, month);
    date.set(java.util.Calendar.HOUR_OF_DAY, hour);
    date.set(java.util.Calendar.MINUTE, min);
    date.set(java.util.Calendar.SECOND, 0);
    return ParsedDateTime.fromUTCTime(date.getTimeInMillis(), icalTimeZone);
}

From source file:org.sakaiproject.time.impl.BasicTimeService.java

/**
 * {@inheritDoc}/*w w  w  .j a  v a 2  s  . c om*/
 */
public Time newTime(GregorianCalendar cal) {
    return new MyTime(this, cal.getTimeInMillis());
}

From source file:com.opendesign.utils.Day.java

public long getTimeInMillis() {
    GregorianCalendar cal = new GregorianCalendar(this.timeZone);
    cal.set(Calendar.YEAR, year);
    cal.set(Calendar.MONTH, month - 1);
    cal.set(Calendar.DAY_OF_MONTH, day);
    cal.set(Calendar.HOUR_OF_DAY, hour);
    cal.set(Calendar.MINUTE, minute);
    cal.set(Calendar.SECOND, second);
    return cal.getTimeInMillis();
}

From source file:org.accada.epcis.repository.query.QuerySubscription.java

/**
 * Updates the subscription in the database. This is required in order to
 * correctly re-initialize the subscriptions, especially the
 * lastTimeExecuted field, after a context restart.
 * <p>//from w w  w.  j av a  2s.  co  m
 * TODO: This is a back-end method: move this method to the
 * QueryOperationsBackend and delegate to it (thus we would need a reference
 * to the QueryOperationsBackend in this class).
 * 
 * @param lastTimeExecuted
 *            The new lastTimeExecuted.
 */
private void updateSubscription(final GregorianCalendar lastTimeExecuted) {
    String jndiName = getProperties().getProperty("jndi.datasource.name", "java:comp/env/jdbc/EPCISDB");
    try {
        // open a database connection
        Context ctx = new InitialContext();
        DataSource db = (DataSource) ctx.lookup(jndiName);
        Connection dbconnection = db.getConnection();

        // update the subscription in the database
        String update = "UPDATE subscription SET lastexecuted=(?), params=(?)" + " WHERE subscriptionid=(?);";
        PreparedStatement stmt = dbconnection.prepareStatement(update);
        LOG.debug("SQL: " + update);
        Timestamp ts = new Timestamp(lastTimeExecuted.getTimeInMillis());
        String time = ts.toString();
        stmt.setString(1, time);
        LOG.debug("       query param 1: " + time);
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        ObjectOutput out = new ObjectOutputStream(outStream);
        out.writeObject(queryParams);
        ByteArrayInputStream inStream = new ByteArrayInputStream(outStream.toByteArray());
        stmt.setBinaryStream(2, inStream, inStream.available());
        LOG.debug("       query param 2: [" + inStream.available() + " bytes]");
        stmt.setString(3, subscriptionID);
        LOG.debug("       query param 3: " + subscriptionID);
        stmt.executeUpdate();

        // close the database connection
        dbconnection.close();
    } catch (SQLException e) {
        String msg = "An SQL error occurred while updating the subscriptions in the database.";
        LOG.error(msg, e);
    } catch (IOException e) {
        String msg = "Unable to update the subscription in the database: " + e.getMessage();
        LOG.error(msg, e);
    } catch (NamingException e) {
        String msg = "Unable to find JNDI data source with name " + jndiName;
        LOG.error(msg, e);
    }
}