Example usage for java.util Calendar before

List of usage examples for java.util Calendar before

Introduction

In this page you can find the example usage for java.util Calendar before.

Prototype

public boolean before(Object when) 

Source Link

Document

Returns whether this Calendar represents a time before the time represented by the specified Object.

Usage

From source file:com.aurel.track.report.dashboard.AverageTimeToCloseItem.java

private SortedMap<Integer, SortedMap<Integer, ArrayList<ReportBeanWithHistory>>> createYearToIntervalToReportBeanListMap(
        int timeInterval, Set<Integer> finalStates) {
    SortedMap<Integer, SortedMap<Integer, ArrayList<ReportBeanWithHistory>>> yearToIntervalToReportBeanList = new TreeMap<Integer, SortedMap<Integer, ArrayList<ReportBeanWithHistory>>>();
    if (reportBeanWithHistoryList != null) {
        Calendar calendar = Calendar.getInstance();
        Calendar calendarEndDate = Calendar.getInstance();
        int calendarInterval = getCalendarInterval(timeInterval);

        for (ReportBeanWithHistory reportBean : reportBeanWithHistoryList) {
            TWorkItemBean workItemBean = reportBean.getWorkItemBean();
            calendar.setTime(dateFrom);/*from  ww w  . j a  va2  s .  c  om*/
            calendarEndDate.setTime(dateTo);
            int yearValue = calendar.get(Calendar.YEAR);
            int intervalValue = calendar.get(calendarInterval);
            boolean isFirst = true;
            while (calendar.before(calendarEndDate) || isFirst) {
                if (isFirst) {
                    isFirst = false;
                } else {
                    calendar.add(calendarInterval, 1);
                }
                yearValue = calendar.get(Calendar.YEAR);
                intervalValue = calendar.get(calendarInterval);
                SortedMap<Integer, ArrayList<ReportBeanWithHistory>> intervalToReportBeans = yearToIntervalToReportBeanList
                        .get(Integer.valueOf(yearValue));
                if (intervalToReportBeans == null) {
                    yearToIntervalToReportBeanList.put(new Integer(yearValue),
                            new TreeMap<Integer, ArrayList<ReportBeanWithHistory>>());
                    intervalToReportBeans = yearToIntervalToReportBeanList.get(Integer.valueOf(yearValue));
                }
                ArrayList<ReportBeanWithHistory> reportBeanList = intervalToReportBeans
                        .get(Integer.valueOf(intervalValue));
                if (reportBeanList == null) {
                    reportBeanList = new ArrayList<ReportBeanWithHistory>();
                    intervalToReportBeans.put(Integer.valueOf(intervalValue), reportBeanList);
                }
                Integer stateID = getReportBeanStateID(reportBean);
                Date lastStateChangeDate = getReportBeanLastStateChange(reportBean);
                if (stateID == null || lastStateChangeDate == null) {
                    continue;
                }
                if (finalStates.contains(stateID)) {
                    if (timeInterval == TIME_INTERVAL.DAY) {
                        if (DateTimeUtils.compareTwoDatesWithoutTimeValue(workItemBean.getCreated(),
                                calendar.getTime()) == 0
                                && DateTimeUtils.compareTwoDatesWithoutTimeValue(lastStateChangeDate,
                                        calendar.getTime()) == 0) {
                            reportBeanList.add(reportBean);
                        }
                    } else {
                        Calendar actualReportinIntervalEndCalendar = Calendar.getInstance();
                        actualReportinIntervalEndCalendar.setTime(calendar.getTime());
                        actualReportinIntervalEndCalendar.add(calendarInterval, 1);
                        if (DateTimeUtils.greaterOrEqual(workItemBean.getCreated(), calendar.getTime())
                                && DateTimeUtils.greater(lastStateChangeDate, calendar.getTime())
                                && DateTimeUtils.lessOrEqual(lastStateChangeDate,
                                        actualReportinIntervalEndCalendar.getTime())) {
                            reportBeanList.add(reportBean);
                        }
                    }
                }
            }
        }
    }
    return yearToIntervalToReportBeanList;
}

From source file:org.openmrs.module.sync.api.impl.SyncServiceImpl.java

/**
 * Gets stats for the server: 1. Sync Records count by server by state 2. If any sync records
 * are in 'pending'/failed state and it has been > 24hrs, add statistic for it 3. count of
 * 'pending' sync records (i.e. the ones that are not in complete or error state
 * //from ww  w .  j a  v a  2s .c o  m
 * @param fromDate start date
 * @param toDate end date
 * @return
 * @throws DAOException
 */
public Map<RemoteServer, LinkedHashSet<SyncStatistic>> getSyncStatistics(Date fromDate, Date toDate)
        throws DAOException {

    Map<RemoteServer, LinkedHashSet<SyncStatistic>> stats = getSynchronizationDAO().getSyncStatistics(fromDate,
            toDate);

    //check out the info for the servers: if any records are pending and are older than 1 day, add flag to stats
    for (Map.Entry<RemoteServer, LinkedHashSet<SyncStatistic>> entry1 : stats.entrySet()) {
        Long pendingCount = 0L;
        for (SyncStatistic syncStat : entry1.getValue()) {
            if (syncStat.getType() == SyncStatistic.Type.SYNC_RECORD_COUNT_BY_STATE) {
                if (syncStat.getName() != SyncRecordState.ALREADY_COMMITTED.toString()
                        && syncStat.getName() != SyncRecordState.COMMITTED.toString()
                        && syncStat.getName() != SyncRecordState.NOT_SUPPOSED_TO_SYNC.toString()) {
                    pendingCount = pendingCount + ((syncStat.getValue() == null) ? 0L
                            : Long.parseLong(syncStat.getValue().toString()));
                }
            }
        }

        //add pending count
        entry1.getValue().add(new SyncStatistic(SyncStatistic.Type.SYNC_RECORDS_PENDING_COUNT,
                SyncStatistic.Type.SYNC_RECORDS_PENDING_COUNT.toString(), pendingCount)); //careful, manipulating live collection

        //if some 'stale' records found see if it has been 24hrs since last sync
        RemoteServer server = entry1.getKey();

        if (server.getLastSync() != null) {
            Calendar lastSync = Calendar.getInstance();
            lastSync.setTime(server.getLastSync());
            Calendar threeDayThreshold = Calendar.getInstance();
            threeDayThreshold.add(Calendar.HOUR, -72); // check if last sync is more than 3 days ago
            Calendar oneDayThreshold = Calendar.getInstance();
            oneDayThreshold.add(Calendar.HOUR, -24); // check if last sync is more than 3 days ago

            if (lastSync.before(threeDayThreshold)) {
                entry1.getValue().add(new SyncStatistic(SyncStatistic.Type.LAST_SYNC_REALLY_LONG_TIME_AGO,
                        SyncStatistic.Type.LAST_SYNC_REALLY_LONG_TIME_AGO.toString(), pendingCount)); //careful, manipulating live collection
            } else if (lastSync.before(oneDayThreshold)) {
                entry1.getValue().add(new SyncStatistic(SyncStatistic.Type.LAST_SYNC_TIME_SOMEWHAT_TROUBLESOME,
                        SyncStatistic.Type.LAST_SYNC_TIME_SOMEWHAT_TROUBLESOME.toString(), pendingCount)); //careful, manipulating live collection
            }
        }
    }

    return stats;
}

From source file:de.jost_net.JVerein.server.MitgliedImpl.java

@SuppressWarnings("unused")
private void plausi() throws RemoteException, ApplicationException {
    checkExterneMitgliedsnummer();/*w ww . j  ava 2  s . c  o m*/

    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:com.ecofactor.qa.automation.newapp.service.MockDataServiceImpl.java

/**
 * List events./*from ww  w.  j a  v a 2  s. co m*/
 * 
 * @param thermostatId
 *            the thermostat id
 * @param algoId
 *            the algo id
 * @param startTime
 *            the start time
 * @param endTime
 *            the end time
 * @return the list
 * @see com.ecofactor.qa.automation.algorithm.service.DataService#listEvents(java.lang.Integer,
 *      int, java.util.Calendar, java.util.Calendar)
 */
@Override
public List<PartitionedThermostatEvent> listEvents(Integer thermostatId, int algoId, Calendar startTime,
        Calendar endTime) {

    loadEvents(thermostatId);
    List<PartitionedThermostatEvent> events = new ArrayList<PartitionedThermostatEvent>();
    Set<Calendar> timeSet = timeEventMap.keySet();
    for (Calendar time : timeSet) {
        PartitionedThermostatEvent event = timeEventMap.get(time);
        if (time.after(startTime) && time.before(endTime) && event.getAlgorithmId() == algoId) {
            events.add(event);
        }
    }

    return events;
}

From source file:com.ecofactor.qa.automation.newapp.service.BaseDataServiceImpl.java

/**
 * Wait and verify temperature change./*w w  w  .  j ava 2 s. co m*/
 * @param thermostatId the thermostat id
 * @param algoId the algo id
 * @param targetTemperature the target temperature
 */
public void waitAndVerifyTemperatureChange(Integer thermostatId, int algoId, double targetTemperature) {

    DriverConfig.setLogString("Wait for event Thermostat : " + thermostatId + ", Algo Id : " + algoId
            + ", Desired Target : " + targetTemperature, true);
    boolean eventProcessed = false;
    largeWait();

    Algorithm algorithm = findByAlgorithmId(algoId);
    Integer phaseDuration = (int) ((3) * (int) (algorithm.getPhaseDuration()));
    String startTimeString = DateUtil.getUTCCurrentTimeStamp();
    Calendar startTime = DateUtil.parseToCalendar(startTimeString, DateUtil.DATE_FMT_FULL);

    String endTimeString = DateUtil.getUTCCurrentTimeStamp();
    Calendar endTime = DateUtil.parseToCalendar(endTimeString, DateUtil.DATE_FMT_FULL);

    if (algoId == 190 || algoId == 191) {
        endTime.add(Calendar.MINUTE, 15);
    } else {
        endTime.add(Calendar.SECOND, phaseDuration);
    }

    DriverConfig.setLogString(
            "Wait for Maximum time till : " + DateUtil.format(endTime, DateUtil.DATE_FMT_FULL), true);

    String currentTimeString = DateUtil.getUTCCurrentTimeStamp();
    Calendar currentTime = DateUtil.parseToCalendar(currentTimeString, DateUtil.DATE_FMT_FULL);
    do {
        smallWait();
        List<PartitionedThermostatEvent> events = listEvents(thermostatId, startTime, endTime);
        if (events != null) {
            for (PartitionedThermostatEvent event : events) {
                if (event.getAlgorithmId().intValue() == algoId) {
                    if ((algoId == -20 || event.getStatus() == 1)
                            && event.getNewSetting() == targetTemperature) {
                        DataUtil.printEventTableGrid(events);
                        eventProcessed = true;
                        break;
                    }
                }
            }
        }

        if (eventProcessed) {
            break;
        }

        currentTimeString = DateUtil.getUTCCurrentTimeStamp();
        currentTime = DateUtil.parseToCalendar(currentTimeString, DateUtil.DATE_FMT_FULL);

    } while (currentTime.before(endTime));

    Assert.assertTrue(eventProcessed, "Processed Event not found for algo " + algoId);
}

From source file:cs.umass.edu.prepare.view.activities.CalendarActivity.java

/**
 * Allows the user to set time for adherence data where the time is unknown.
 * @param medication the medication for which the adherence is being modified.
 * @param index the index of the adherence being modified, i.e. AM or PM.
 *//* www. ja  va 2s .co  m*/
private void setTimeTaken(final Medication medication, final Calendar dateKey, final int index) {
    final Dialog dialog = new Dialog(this);
    dialog.setContentView(R.layout.dialog_set_time);

    final TimePicker timePicker = (TimePicker) dialog.findViewById(R.id.time_picker);

    Button cancelButton = (Button) dialog.findViewById(R.id.btn_time_cancel);
    cancelButton.setOnClickListener(v -> dialog.dismiss());

    Button saveButton = (Button) dialog.findViewById(R.id.btn_time_save);
    saveButton.setOnClickListener(v -> {
        Calendar time = Utils.getTimeNoInterval(timePicker); // TODO: Store times taken
        Map<Medication, Adherence[]> dailyAdherence = adherenceData.get(dateKey);
        Adherence[] adherence = dailyAdherence.get(medication);
        adherence[index].setTimeTaken(time);

        Calendar[] schedule = dailySchedule.get(medication);
        Calendar timeToTake = (Calendar) time.clone();
        timeToTake.set(Calendar.HOUR_OF_DAY, schedule[index].get(Calendar.HOUR_OF_DAY));
        timeToTake.set(Calendar.MINUTE, schedule[index].get(Calendar.MINUTE));
        Calendar upperBound = (Calendar) timeToTake.clone();
        upperBound.add(Calendar.HOUR_OF_DAY, 1);
        Calendar lowerBound = (Calendar) timeToTake.clone();
        lowerBound.add(Calendar.HOUR_OF_DAY, -1);

        if (time.after(upperBound) || time.before(lowerBound)) {
            adherence[index].setAdherenceType(Adherence.AdherenceType.TAKEN_EARLY_OR_LATE);
        } else {
            adherence[index].setAdherenceType(Adherence.AdherenceType.TAKEN);
        }

        dialog.dismiss();
        refresh();

        DataIO preferences = DataIO.getInstance(CalendarActivity.this);
        preferences.setAdherenceData(this, adherenceData);
    });

    dialog.show();
}

From source file:com.tibco.tgdb.test.lib.TGServer.java

/**
 * Start the TG server synchronously.// w  w w  . j av a  2  s  . c o  m
 * 
 * @param timeout
 *            Number of milliseconds allowed to start the server
 * @throws TGStartException Start operation fails
 */
public void start(long timeout) throws TGStartException {

    if (this.configFile == null)
        throw new TGStartException("TGServer - Config file not set");

    if (this.logFile == null)
        this.setLogFile("tgdb_" + this.dbName);

    //this.outStream = new ByteArrayOutputStream(); // reset
    //this.errStream = new ByteArrayOutputStream(); // reset
    PumpStreamHandler psh = new PumpStreamHandler(new ByteArrayOutputStream());
    DefaultExecuteResultHandler resultHandler = new DefaultExecuteResultHandler();

    Executor tgExec = new DefaultExecutor();
    tgExec.setWorkingDirectory(new File(this.home + "/bin"));
    tgExec.setStreamHandler(psh);
    CommandLine tgCL = new CommandLine((new File(this.home + "/bin/" + process)).getAbsolutePath());
    tgCL.addArguments(new String[] { "-s", "-c", this.configFile.getAbsolutePath(), "-l", this.logFileBase });

    System.out.println("TGServer - Starting " + StringUtils.toString(tgCL.toStrings(), " "));
    try {
        tgExec.execute(tgCL, resultHandler);
    } catch (IOException ioe) {
        try {
            Thread.sleep(1000); // Make sure output/error fill up
        } catch (InterruptedException ie) {
            ;
        }
        throw new TGStartException(ioe.getMessage());
    }

    if (timeout > 0) {
        Calendar future = Calendar.getInstance();
        future.add(Calendar.MILLISECOND, (int) timeout);
        boolean started = false;
        boolean error = false;
        List<String> acceptedClients = new ArrayList<String>();
        String acceptedClient;
        while (!future.before(Calendar.getInstance())) {
            try {
                Thread.sleep(1000);
                BufferedReader reader = new BufferedReader(new StringReader(this.getOutput()));
                String line = reader.readLine();
                while (line != null) {
                    if (line.contains("Process pid:"))
                        this.setPid(Integer.parseInt(line.substring(line.lastIndexOf("Process pid:") + 12,
                                line.indexOf(",", line.lastIndexOf("Process pid:") + 12))));
                    if (line.contains("[Error]")) {
                        error = true;
                    }
                    if (line.contains("Accepting clients on")) {
                        started = true;
                        acceptedClient = line.substring(line.indexOf("- Accepting clients on") + 2);
                        if (!acceptedClients.contains(acceptedClient))
                            acceptedClients.add(acceptedClient);
                    }
                    line = reader.readLine();
                }
                reader.close();
                if (started)
                    break;
            } catch (Exception e) {
                throw new TGStartException("TGServer - " + e.getMessage());
            }
        }
        if (!started)
            throw new TGStartException(
                    "TGServer - Did not start on time (after " + timeout + " msec) - See log " + this.logFile);
        else {
            this.running = true;
            System.out.println("TGServer - Started successfully with pid " + this.pid + " :");
            System.out.println("\t\t- Log file: " + this.logFile);
            if (error)
                System.out.println("\t\t- With some error(s) - See log");
            for (String client : acceptedClients)
                System.out.println("\t\t- " + client);
            try {
                this.setBanner(this.getOutput());
            } catch (TGGeneralException tge) {
                throw new TGStartException(tge.getMessage());
            }
        }
    }
}

From source file:org.apache.oozie.coord.CoordELFunctions.java

/**
 *
 * @param n offset amount (integer)// ww  w  .  j a va  2s.com
 * @param timeUnit TimeUnit for offset n ("MINUTE", "HOUR", "DAY", "MONTH", "YEAR")
 * @return the offset time from the effective nominal time <p> return empty string ("") if the Action_Creation_time or the
 *         offset instance <p> is earlier than the Initial_Instance of dataset.
 * @throws Exception
 */
private static String coord_offset_sync(int n, String timeUnit) throws Exception {
    Calendar rawCal = resolveOffsetRawTime(n, TimeUnit.valueOf(timeUnit), null);
    if (rawCal == null) {
        // warning already logged by resolveOffsetRawTime()
        return "";
    }

    int freq = getDSFrequency();
    TimeUnit freqUnit = getDSTimeUnit();
    int freqCount = 0;
    // We're going to manually turn back/forward cal by decrements/increments of freq and then check that it gives the same
    // time as rawCal; this is to check that the offset time resolves to a frequency offset of the effective nominal time
    // In other words, that there exists an integer x, such that coord:offset(n, timeUnit) == coord:current(x) is true
    // If not, then we'll "rewind" rawCal to the latest instance earlier than rawCal and use that.
    Calendar cal = getInitialInstanceCal();
    if (rawCal.before(cal)) {
        while (cal.after(rawCal)) {
            cal.add(freqUnit.getCalendarUnit(), -freq);
            freqCount--;
        }
    } else if (rawCal.after(cal)) {
        while (cal.before(rawCal)) {
            cal.add(freqUnit.getCalendarUnit(), freq);
            freqCount++;
        }
    }
    if (cal.before(rawCal)) {
        rawCal = cal;
    } else if (cal.after(rawCal)) {
        cal.add(freqUnit.getCalendarUnit(), -freq);
        rawCal = cal;
        freqCount--;
    }
    String rawCalStr = DateUtils.formatDateOozieTZ(rawCal);

    Calendar nominalInstanceCal = getInitialInstanceCal();
    nominalInstanceCal.add(freqUnit.getCalendarUnit(), freq * freqCount);
    if (nominalInstanceCal.getTime().compareTo(getInitialInstance()) < 0) {
        XLog.getLog(CoordELFunctions.class)
                .warn("If the initial instance of the dataset is later than the offset instance"
                        + " specified, such as coord:offset({0}, {1}) in this case, an empty string is returned. This means that no"
                        + " data is available at the offset instance specified by the user and the user could try modifying his"
                        + " initial-instance to an earlier time.", n, timeUnit);
        return "";
    }
    String nominalCalStr = DateUtils.formatDateOozieTZ(nominalInstanceCal);

    if (!rawCalStr.equals(nominalCalStr)) {
        throw new RuntimeException("Shouldn't happen");
    }
    return rawCalStr;
}

From source file:com.ecofactor.qa.automation.newapp.service.MockDataServiceImpl.java

/**
 * Gets the sT events./*from w w  w  . j a  va 2  s. c  o  m*/
 * 
 * @param thermostatId
 *            the thermostat id
 * @param startTime
 *            the start time
 * @param endTime
 *            the end time
 * @return the sT events
 */
private List<PartitionedThermostatEvent> getSTEvents(Integer thermostatId, Calendar startTime,
        Calendar endTime) {

    List<PartitionedThermostatEvent> events = new ArrayList<PartitionedThermostatEvent>();
    int i = 0;
    while (startTime.before(endTime)) {

        startTime.add(Calendar.MINUTE, 4);

        Algorithm algorithm = new Algorithm();
        if (mode.equals("Cool")) {
            algorithm.setId(ST3_COOL);
        } else if (mode.equals("Heat")) {
            algorithm.setId(ST3_HEAT);
        }

        PartitionedThermostatEvent thermostatEvent = new PartitionedThermostatEvent();
        thermostatEvent.setAlgorithmId(algorithm.getId());
        thermostatEvent.setThermostatId(thermostatId);
        thermostatEvent.setPhase(i);
        thermostatEvent.getId().setEventSysTime((Calendar) startTime.clone());
        thermostatEvent.setDeltaEE((double) i);
        thermostatEvent.setOldSetting(baseTemp);
        if (mode.equals("Cool")) {
            thermostatEvent.setNewSetting(baseTemp + i);
        } else if (mode.equals("Heat")) {
            thermostatEvent.setNewSetting(baseTemp - i);
        }

        thermostatEvent.setStatus(1);
        events.add(thermostatEvent);

        i = i + 1;
        i = i % 3;
    }

    return events;
}

From source file:com.aurel.track.report.dashboard.StatusOverTimeGraph.java

/**
 * Set 0 values for the empty time intervals
 * @param dateFrom/*from   w w  w. j a va 2s .co  m*/
 * @param dateTo
 * @param selectedTimeInterval
 * @param yearToPeriodToEntityNumbersMap
 * @param entityIDs
 */
private static void addZerosForEmptyIntervals(Date dateFrom, Date dateTo, int selectedTimeInterval,
        SortedMap<Integer, SortedMap<Integer, Map<Integer, Integer>>> yearToPeriodToEntityNumbersMap,
        List entityIDs) {
    if (entityIDs == null || entityIDs.isEmpty()) {
        return;
    }
    int calendarInterval = getCalendarInterval(selectedTimeInterval);
    Calendar calendarFrom = StatusOverTimeDatasource.calculateDateFrom(dateFrom,
            (SortedMap) yearToPeriodToEntityNumbersMap, calendarInterval);
    if (calendarFrom == null) {
        return;
    }
    Calendar calendarTo = StatusOverTimeDatasource.calculateDateTo(dateTo,
            (SortedMap) yearToPeriodToEntityNumbersMap, calendarInterval);
    if (calendarTo == null) {
        return;
    }
    //previous-next issue: to avoid adding the first week of the new year as the first week of the old year,
    //because it can be that the year is the old one but the last days of the year belong to the first week of the next year
    //and that would add an entry with the first week of the old year
    int previousYearValue = calendarFrom.get(Calendar.YEAR);
    int nextYearValue = previousYearValue;
    int previousCalendarIntervalValue = calendarFrom.get(calendarInterval);
    int nextCalendarIntervalValue = previousCalendarIntervalValue;
    boolean jumpYearFirstTime = false;
    if (selectedTimeInterval == TIME_INTERVAL.WEEK && calendarFrom.get(Calendar.MONTH) == 11
            && nextCalendarIntervalValue == 1) {
        jumpYearFirstTime = true;
    }
    while (calendarFrom.before(calendarTo)) {
        if ((nextCalendarIntervalValue < previousCalendarIntervalValue && nextYearValue == previousYearValue)
                || jumpYearFirstTime) {
            nextYearValue += 1;
        }
        jumpYearFirstTime = false;
        addZerosForInterval(new Integer(nextYearValue), new Integer(nextCalendarIntervalValue),
                yearToPeriodToEntityNumbersMap, entityIDs);
        previousYearValue = nextYearValue;
        previousCalendarIntervalValue = nextCalendarIntervalValue;
        calendarFrom.add(calendarInterval, 1);
        nextYearValue = calendarFrom.get(Calendar.YEAR);
        nextCalendarIntervalValue = calendarFrom.get(calendarInterval);
    }
}