Example usage for java.text DateFormat getTimeInstance

List of usage examples for java.text DateFormat getTimeInstance

Introduction

In this page you can find the example usage for java.text DateFormat getTimeInstance.

Prototype

public static final DateFormat getTimeInstance(int style) 

Source Link

Document

Gets the time formatter with the given formatting style for the default java.util.Locale.Category#FORMAT FORMAT locale.

Usage

From source file:org.telscenter.sail.webapp.presentation.web.controllers.student.brainstorm.XMLBrainstorm.java

public static String getXMLRevision(Revision revision) {
    Date timestamp = revision.getTimestamp();
    String formattedTime = DateFormat.getTimeInstance(DateFormat.SHORT).format(timestamp);

    String formattedDate = DateFormat.getDateInstance(DateFormat.MEDIUM).format(timestamp);

    String xmlDisplayname = "";
    if (revision.getDisplayname() != null && !revision.getDisplayname().equals("")) {
        xmlDisplayname = "<displayname>" + revision.getDisplayname() + "</displayname>";
    }/*w  ww . j  ava 2 s.c o m*/
    String XMLRevision = "<revision><id>" + revision.getId() + "</id><timestamp>" + formattedTime + " "
            + formattedDate + "</timestamp>" + xmlDisplayname + "<body>"
            + StringEscapeUtils.escapeHtml(revision.getBody()) + "</body></revision>";
    return XMLRevision;
}

From source file:org.jactr.tools.async.iterative.tracker.IterativeRunTracker.java

protected void update(StatusMessage message) {
    _totalIterations = message.getTotalIterations();
    _currentIteration = message.getIteration();
    if (_startTime == 0)
        _startTime = message.getWhen(); // when it actually started

    if (message.isStop()) {

        long currentDuration = message.getWhen() - _startTime;
        /*/*ww  w. ja  v a  2s  .  c  om*/
         * we set the next start time to this so that we can accurately measure
         * the cost of any analyses being run outside of the simulation
         */
        _startTime = message.getWhen();

        _summedDurations += currentDuration;

        /*
         * weighted average of everyone up to now and last
         */
        _estimatedIterationDuration = _summedDurations / _currentIteration;

        long remainingTime = (_totalIterations - _currentIteration + 1) * _estimatedIterationDuration;

        _estimatedCompletionTime = remainingTime + message.getWhen();

        if (LOGGER.isDebugEnabled())
            LOGGER.debug("estimated duration : " + _estimatedIterationDuration + " r:"
                    + (_totalIterations - _currentIteration) + " remainingTime : " + remainingTime + "ms eta "
                    + DateFormat.getTimeInstance(DateFormat.LONG).format(_estimatedCompletionTime));
    }
}

From source file:com.google.samples.apps.iosched.util.UIUtils.java

/**
 * Format and return the given session time and {@link Rooms} values using {@link
 * Config#CONFERENCE_TIMEZONE}.//w  ww . j  av a2s . com
 */
public static String formatSessionSubtitle(long intervalStart, long intervalEnd, String roomName,
        StringBuilder recycle, Context context, boolean shortFormat) {

    // Determine if the session is in the past
    long currentTimeMillis = TimeUtils.getCurrentTime(context);
    boolean conferenceEnded = currentTimeMillis > Config.CONFERENCE_END_MILLIS;
    boolean sessionEnded = currentTimeMillis > intervalEnd;
    if (sessionEnded && !conferenceEnded) {
        return context.getString(R.string.session_finished);
    }

    if (roomName == null) {
        roomName = context.getString(R.string.unknown_room);
    }

    if (shortFormat) {
        TimeZone timeZone = SettingsUtils.getDisplayTimeZone(context);
        Date intervalStartDate = new Date(intervalStart);
        SimpleDateFormat shortDateFormat = new SimpleDateFormat("MMM dd");
        DateFormat shortTimeFormat = DateFormat.getTimeInstance(DateFormat.SHORT);
        shortDateFormat.setTimeZone(timeZone);
        shortTimeFormat.setTimeZone(timeZone);
        return shortDateFormat.format(intervalStartDate) + " " + shortTimeFormat.format(intervalStartDate);
    } else {
        String timeInterval = formatIntervalTimeString(intervalStart, intervalEnd, recycle, context);
        return context.getString(R.string.session_subtitle, timeInterval, roomName);
    }
}

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

/**
 * Final initialization, once all dependencies are set.
 *///from  ww w  .  ja v  a 2 s.c  om
public void init() {
    /** The time zone for our GMT times. */
    M_tz = TimeZone.getTimeZone("GMT");

    M_log.info("init()");

    /**
     * a calendar to clone for GMT time construction
     */
    M_GCal = getCalendar(M_tz, 0, 0, 0, 0, 0, 0, 0);

    // Note: formatting for GMT time representations
    M_fmtA = (DateFormat) (new SimpleDateFormat("yyyyMMddHHmmssSSS"));
    M_fmtB = DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.SHORT);
    M_fmtC = DateFormat.getTimeInstance(DateFormat.SHORT);
    M_fmtD = DateFormat.getDateInstance(DateFormat.MEDIUM);
    M_fmtE = (DateFormat) (new SimpleDateFormat("yyyyMMddHHmmss"));
    M_fmtG = (DateFormat) (new SimpleDateFormat("yyyy/DDD/HH/")); // that's year, day of year, hour

    M_fmtA.setTimeZone(M_tz);
    M_fmtB.setTimeZone(M_tz);
    M_fmtC.setTimeZone(M_tz);
    M_fmtD.setTimeZone(M_tz);
    M_fmtE.setTimeZone(M_tz);
    M_fmtG.setTimeZone(M_tz);

    //register the Cache
    M_userTzCache = memoryService.newCache("org.sakaiproject.time.impl.BasicTimeService.userTimezoneCache");
}

From source file:no.firestorm.weathernotificatonservice.WeatherNotificationService.java

/**
 * Shows a notification with information about the error, either NoLocation
 * or DownloadError (default)//  w  ww  . j a v a 2 s.  c om
 * 
 * @param e
 *            Exception
 */
private void makeNotification(Exception e) {
    int tickerIcon, contentIcon;
    CharSequence tickerText, contentTitle, contentText, contentTime;
    final DateFormat df = DateFormat.getTimeInstance(DateFormat.SHORT);
    contentIcon = android.R.drawable.stat_notify_error;
    final Context context = WeatherNotificationService.this;
    contentTime = df.format(new Date());
    long when = (new Date()).getTime();

    if (e instanceof NoLocationException) {
        setShortAlarm();
        tickerText = WeatherNotificationService.this.getString(R.string.location_error);
        contentTitle = WeatherNotificationService.this.getString(R.string.location_error);
    } else {
        if (e instanceof NetworkErrorException)
            updateAlarm();
        else
            setShortAlarm();

        // Network error has occurred
        // Set title
        tickerText = WeatherNotificationService.this.getString(R.string.download_error);
        contentTitle = WeatherNotificationService.this.getString(R.string.download_error);
    }

    final Date lastTime = WeatherNotificationSettings.getLastUpdateTime(WeatherNotificationService.this);
    Float temperatureF = null;
    if (lastTime != null) {
        temperatureF = Float.parseFloat(WeatherNotificationSettings.getSavedLastTemperature(context));
        contentText = String.format("%s %.1f C %s %s", context.getString(R.string.last_temperature),
                temperatureF, context.getString(R.string._tid_), df.format(lastTime));
        tickerIcon = TempToDrawable.getDrawableFromTemp(temperatureF);

    } else {
        contentText = WeatherNotificationService.this.getString(R.string.press_for_update);
        tickerIcon = android.R.drawable.stat_notify_error;
    }

    makeNotification(tickerIcon, contentIcon, tickerText, contentTitle, contentText, contentTime, when,
            temperatureF);

}

From source file:com.ehret.mixit.fragment.SessionDetailFragment.java

private void addGeneralInfo(Talk conference) {
    SimpleDateFormat sdf = new SimpleDateFormat("EEE");
    if (conference.getStart() != null && conference.getEnd() != null) {
        horaire.setText(//from w  ww  .j  a  v a 2 s .c  o m
                String.format(getResources().getString(R.string.periode), sdf.format(conference.getStart()),
                        DateFormat.getTimeInstance(DateFormat.SHORT).format(conference.getStart()),
                        DateFormat.getTimeInstance(DateFormat.SHORT).format(conference.getEnd())));
    } else {
        horaire.setText(getResources().getString(R.string.pasdate));

    }
    name.setText(conference.getTitle());
    if (conference.getSummary() != null) {
        summary.setText(Html.fromHtml(Processor.process(conference.getSummary()).trim()));
    }
    if (conference.getDescription() != null) {
        descriptif
                .setText(Html.fromHtml(
                        Processor.process(conference.getDescription(),
                                Configuration.builder().forceExtentedProfile().build()).trim(),
                        null, htmlTagHandler), TextView.BufferType.SPANNABLE);
    }
    final Salle room = Salle.getSalle(conference.getRoom());

    if (conference.getTrack() != null) {
        switch (conference.getTrack()) {
        case "aliens":
            imageTrack.setImageDrawable(getResources().getDrawable(R.drawable.mxt_icon__aliens));
            track.setText("Track Alien");
            break;
        case "design":
            imageTrack.setImageDrawable(getResources().getDrawable(R.drawable.mxt_icon__design));
            track.setText("Track Design");
            break;
        case "hacktivism":
            imageTrack.setImageDrawable(getResources().getDrawable(R.drawable.mxt_icon__hack));
            track.setText("Track Hacktivism");
            break;
        case "tech":
            imageTrack.setImageDrawable(getResources().getDrawable(R.drawable.mxt_icon__tech));
            track.setText("Track Tech");
            break;
        case "learn":
            imageTrack.setImageDrawable(getResources().getDrawable(R.drawable.mxt_icon__learn));
            track.setText("Track Learn");
            break;
        case "makers":
            imageTrack.setImageDrawable(getResources().getDrawable(R.drawable.mxt_icon__makers));
            track.setText("Track Makers");
            break;
        default:
            imageTrack.setImageDrawable(null);
            track.setText("");
        }

    }

    if (conference.getLang() != null && "ENGLISH".equals(conference.getLang())) {
        langImage.setImageDrawable(getResources().getDrawable(R.drawable.en));
    } else {
        langImage.setImageDrawable(getResources().getDrawable(R.drawable.fr));
    }
    if (Salle.INCONNU != room) {
        salle.setText(String.format(getString(R.string.Salle), room.getNom()));
        if (room.getDrawable() != 0) {
            salle.setBackgroundResource(room.getDrawable());
        } else {
            salle.setBackgroundColor(getActivity().getBaseContext().getResources().getColor(room.getColor()));
        }
        salle.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Map<String, Object> parametres = new HashMap<>();
                parametres.put(UIUtils.ARG_KEY_ROOM, room.getEtage());
                UIUtils.startActivity(SalleActivity.class, getActivity(), parametres);
            }
        });
    }
}

From source file:DateTimeEditor.java

protected void setupFormat() {
    switch (m_timeOrDateType) {
    case TIME:/*from   w  w  w  . j  av  a 2s. c o  m*/
        m_format = DateFormat.getTimeInstance(m_lengthStyle);
        break;
    case DATE:
        m_format = DateFormat.getDateInstance(m_lengthStyle);
        break;
    case DATETIME:
        m_format = DateFormat.getDateTimeInstance(m_lengthStyle, m_lengthStyle);
        break;
    }
}

From source file:qtiscoringengine.QTIUtility.java

public static String getUniqueFileName(String fileNamePrefix, String fileExtension) {
    Date d = Calendar.getInstance().getTime();
    long now = System.currentTimeMillis();
    return "QTIScoringEngine_" + fileNamePrefix + "_"
            + DateFormat.getDateInstance(DateFormat.SHORT).format(d).replace("/", "-") + "_"
            + DateFormat.getTimeInstance(DateFormat.LONG).format(d).replace(" ", "").replace(":", "_")
            + fileExtension;//from www  .  j  a  va  2 s  . com
}

From source file:com.appeligo.alerts.KeywordAlertChecker.java

public void sendMessages(KeywordAlert keywordAlert, String fragments, Document doc, String messagePrefix) {

    User user = keywordAlert.getUser();/*  w w  w .  ja  v a  2  s . co  m*/
    if (user == null) {
        return;
    }
    String programId = doc.get("programID");
    String programTitle = doc.get("programTitle");

    if (log.isDebugEnabled())
        log.debug("keywordAlert: " + keywordAlert.getUserQuery() + ", sending message to "
                + (user == null ? null : user.getUsername()));

    try {
        // Use the user's lineup to determine the start time of this program which might air at different times for diff timezones
        String startTimeString = doc.get("lineup-" + user.getLineupId() + "-startTime");
        if (startTimeString == null) {
            // This user doesn't have the channel or program that our local feed has
            if (log.isDebugEnabled()) {
                String station = doc.get("lineup-" + liveLineup + "-stationName");
                log.debug("No startTime for station " + station + ", program " + programTitle + ", lineup="
                        + user.getLineupId() + ", start time from live lineup="
                        + doc.get("lineup-" + liveLineup + "-startTime"));
            }
            return;
        }
        Date startTime = DateTools.stringToDate(startTimeString);
        Date endTime = DateTools.stringToDate(doc.get("lineup-" + user.getLineupId() + "-endTime"));
        long durationMinutes = (endTime.getTime() - startTime.getTime()) / (60 * 1000);

        Date now = new Date();
        boolean future = endTime.after(now);
        boolean onAirNow = startTime.before(now) && future;
        boolean past = !(future || onAirNow);

        ProgramType programType = ProgramType.fromProgramID(programId);

        boolean uniqueProgram = false;
        if (programType == ProgramType.EPISODE || programType == ProgramType.SPORTS
                || programType == ProgramType.MOVIE) {
            uniqueProgram = true;
        }

        Map<String, String> context = new HashMap<String, String>();

        boolean includeDate;
        DateFormat format;
        if (Math.abs(startTime.getTime() - System.currentTimeMillis()) < 12 * 60 * 60 * 1000) {
            format = DateFormat.getTimeInstance(DateFormat.SHORT);
            includeDate = false;
        } else {
            format = new SimpleDateFormat("EEEE, MMMM d 'at' h:mm a");
            includeDate = true;
        }
        format.setTimeZone(user.getTimeZone());
        context.put("startTime", format.format(startTime));
        if (includeDate) {
            format = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT);
            format.setTimeZone(user.getTimeZone());
        }
        context.put("shortStartTime", format.format(startTime));

        context.put("durationMinutes", Long.toString(durationMinutes));
        // Use the SDTW-C lineup because this is how we know the right channel (station callsign) where we caught the
        // keyword.
        String stationName = doc.get("lineup-" + liveLineup + "-stationName");
        context.put("stationName", stationName);
        boolean sameStation = false;
        if (stationName.equals(doc.get("lineup-" + user.getLineupId() + "-stationName"))) {
            sameStation = true;
        }
        context.put("stationCallSign", doc.get("lineup-" + liveLineup + "-stationCallSign"));

        if (sameStation) {
            if (onAirNow) {
                context.put("timeChannelIntro", "We have been monitoring <b>" + stationName
                        + "</b>, and your topic was recently mentioned on the following program:");
            } else if (future) {
                if (uniqueProgram) {
                    context.put("timeChannelIntro", "We are monitoring <b>" + stationName
                            + "</b>, and your topic will be mentioned on the following program:");
                } else {
                    context.put("timeChannelIntro",
                            "We are monitoring <b>" + stationName + "</b>, and your topic was mentioned on <b>"
                                    + programTitle + "</b>. It may be mentioned when this program airs again:");
                }
            } else {
                context.put("timeChannelIntro", "We have been monitoring <b>" + stationName
                        + "</b>, and your topic was mentioned on a program that aired in your area in the past. "
                        + "You may have an opportunity to see this program in the future:");
            }
        } else {
            if (onAirNow) {
                context.put("timeChannelIntro", "We have been monitoring <b>" + programTitle
                        + "</b>, and your topic was recently mentioned:");
            } else if (future) {
                if (uniqueProgram) {
                    context.put("timeChannelIntro", "We have been monitoring <b>" + programTitle
                            + "</b>, and your topic was mentioned.  You may have an opportunity to catch this program when it airs again according to the following schedule:");
                } else {
                    context.put("timeChannelIntro", "We have been monitoring <b>" + programTitle
                            + "</b>, and your topic was mentioned.  This program will air again as follows, but the topics may or may not be the same:");
                }
            } else {
                context.put("timeChannelIntro", "We have been monitoring <b>" + programTitle
                        + "</b>, and your topic was mentioned.  However, this program aired in your area in the past. "
                        + "You may have an opportunity to see this program in the future:");
            }
        }
        if (onAirNow) {
            context.put("startsAt", "Started at");
        } else if (future) {
            if (includeDate) {
                context.put("startsAt", "Starts on");
            } else {
                context.put("startsAt", "Starts at");
            }
        } else {
            if (includeDate) {
                context.put("startsAt", "Last aired on");
            } else {
                context.put("startsAt", "Previously aired at");
            }
        }
        context.put("lcStartsAt", context.get("startsAt").toLowerCase());

        String webPath = doc.get("webPath");
        if (webPath == null) {
            webPath = DefaultEpg.getInstance().getProgram(programId).getWebPath();
        }
        if (webPath.charAt(0) == '/') {
            webPath = webPath.substring(1);
        }
        String reducedTitle40 = doc.get("reducedTitle40");
        if (reducedTitle40 == null) {
            reducedTitle40 = DefaultEpg.getInstance().getProgram(programId).getReducedTitle40();
        }
        String programLabel = doc.get("programLabel");
        if (programLabel == null) {
            programLabel = DefaultEpg.getInstance().getProgram(programId).getLabel();
        }
        context.put("programId", programId);
        context.put("webPath", webPath);
        context.put("programLabel", programLabel);
        context.put("reducedTitle40", reducedTitle40);
        if (doc.get("description").trim().length() > 0) {
            context.put("description", "Description: " + doc.get("description") + "<br/>");
        } else {
            context.put("description", "");
        }
        if (fragments == null || fragments.trim().length() == 0) {
            context.put("fragments", "");
        } else {
            context.put("fragments", "Relevant Dialogue: <i>" + fragments + "</i><br/>");
        }
        context.put("query", keywordAlert.getUserQuery());
        context.put("keywordAlertId", Long.toString(keywordAlert.getId()));
        String greeting = user.getUsername();
        context.put("username", greeting);
        String firstName = user.getFirstName();
        if (firstName != null && firstName.trim().length() > 0) {
            greeting = firstName;
        }
        context.put("greeting", greeting);

        format = DateFormat.getTimeInstance(DateFormat.SHORT);
        format.setTimeZone(user.getTimeZone());
        context.put("now", format.format(new Date()));

        ScheduledProgram futureProgram = DefaultEpg.getInstance().getNextShowing(user.getLineupId(), programId,
                false, false);
        if (uniqueProgram) {
            String typeString = null;
            if (programType == ProgramType.EPISODE) {
                typeString = "episode";
            } else if (programType == ProgramType.SPORTS) {
                typeString = "game";
            } else {
                typeString = "movie";
            }
            if (futureProgram != null) {
                String timePreposition = null;
                if ((futureProgram.getStartTime().getTime() - System.currentTimeMillis()) < 12 * 60 * 60
                        * 1000) {
                    timePreposition = "at ";
                    format = DateFormat.getTimeInstance(DateFormat.SHORT);
                } else {
                    timePreposition = "on ";
                    format = new SimpleDateFormat("EEEE, MMMM d 'at' h:mm a");
                }
                format.setTimeZone(user.getTimeZone());
                context.put("rerunInfo", "You can still catch this " + typeString
                        + " in its entirety!  It's scheduled to replay " + timePreposition
                        + format.format(futureProgram.getStartTime()) + " on "
                        + futureProgram.getNetwork().getStationName() + ". Do you want to <a href=\"" + url
                        + webPath + "#addreminder\">set a reminder</a> to be notified the next time this "
                        + typeString + " airs?");
            } else {
                if (programType == ProgramType.SPORTS) {
                    context.put("rerunInfo", "");
                } else {
                    if (onAirNow) {
                        context.put("rerunInfo",
                                "If it's too late to flip on the program now, you can <a href=\"" + url
                                        + webPath
                                        + "#addreminder\">set a reminder</a> to be notified the next time this "
                                        + typeString + " airs.");
                    } else {
                        context.put("rerunInfo",
                                "You can <a href=\"" + url + webPath
                                        + "#addreminder\">set a reminder</a> to be notified the next time this "
                                        + typeString + " airs.");
                    }
                }
            }
        } else {
            if ((futureProgram != null) && futureProgram.isNewEpisode()) {
                context.put("rerunInfo",
                        "The next airing of this show will be new content, and is <i>not a rerun</i>,"
                                + " so these same topics may or may not be discussed."
                                + "  You may still be interested in catching future airings, and you can"
                                + " <a href=\"" + url + webPath
                                + "#addreminder\">set a Flip.TV reminder for this show</a>.");
            } else {
                context.put("rerunInfo",
                        "The broadcaster did not provide enough information to know which future airings,"
                                + " if any, are identical reruns with the same topics mentioned."
                                + "  You may still be interested in catching future airings, and you can"
                                + " <a href=\"" + url + webPath
                                + "#addreminder\">set a Flip.TV reminder for this show</a>.");
            }
        }

        if (keywordAlert.getTodaysAlertCount() == keywordAlert.getMaxAlertsPerDay()) {
            context.put("maxAlertsExceededSentence",
                    "You asked to stop receiving alerts for this topic after receiving "
                            + keywordAlert.getMaxAlertsPerDay()
                            + " alerts in a single day. That limit has been reached. You can change this setting"
                            + " at any time.  Otherwise, we will resume sending alerts"
                            + " for this topic tomorrow.");
        } else {
            context.put("maxAlertsExceededSentence", "");
        }

        if (keywordAlert.isUsingPrimaryEmailRealtime()) {
            Message message = new Message(messagePrefix + "_email", context);
            message.setUser(user);
            message.setTo(user.getPrimaryEmail());
            if (log.isDebugEnabled())
                log.debug("Sending email message to: " + user.getPrimaryEmail());
            message.insert();
        }
        if (keywordAlert.isUsingSMSRealtime() && user.getSmsEmail().trim().length() > 0) {
            Message message = new Message(messagePrefix + "_sms", context);
            message.setTo(user.getSmsEmail());
            message.setUser(user);
            message.setSms(true);
            if (log.isDebugEnabled())
                log.debug("Sending sms message to: " + user.getSmsEmail());
            message.insert();
        }
    } catch (NumberFormatException e) {
        log.error("Couldn't process lucene document for program " + programId, e);
    } catch (MessageContextException e) {
        log.error("Software bug resulted in exception with email message context or configuration", e);
    } catch (ParseException e) {
        log.error(
                "Software bug resulted in exception with document 'startTime' or 'endTime' format in lucene document for program id "
                        + programId,
                e);
    }
}

From source file:com.appeligo.alerts.PendingAlertThread.java

public void run() {
    try {//w w  w .  j  ava2 s  .  co  m
        Permissions.setCurrentUser(Permissions.SUPERUSER);

        while (isActive()) {

            PendingAlert next = null;

            HibernateUtil.openSession();
            try {
                next = PendingAlert.getNextAlert();
            } finally {
                HibernateUtil.closeSession();
            }

            long delay = 0;
            if (next != null) {
                delay = next.getAlertTime().getTime() - System.currentTimeMillis();
                log.debug("current time=" + System.currentTimeMillis() + ", next alert time="
                        + next.getAlertTime().getTime());
            }

            while (((delay > 0) || (next == null)) && isActive()) {
                log.debug("Waiting for next pending alert. next=" + (next == null ? null : next.getId())
                        + ", time before next alert=" + delay);
                try {
                    synchronized (this) {
                        wait(delay); // value can only be zero (as initialized) or
                                     // a positive value (as checked in while condition).
                                     // wait(0) == wait forever
                    }
                } catch (InterruptedException e) {
                }
                //need to see if there is a newer alert
                //(in which case, notifyAll was called), or the
                //alert we were waiting for was deleted
                delay = 0;
                HibernateUtil.openSession();
                try {
                    next = PendingAlert.getNextAlert();
                } finally {
                    HibernateUtil.closeSession();
                }
                if (next != null) {
                    delay = next.getAlertTime().getTime() - System.currentTimeMillis();
                    log.debug("current time=" + System.currentTimeMillis() + ", next alert time="
                            + next.getAlertTime().getTime());
                }
            }

            if (isActive())
                log.debug("Ready to fire off at least one pending alert. next=" + next.getId() + ", deleted="
                        + next.isDeleted());

            HibernateUtil.openSession();
            List<PendingAlert> pendingAlerts = PendingAlert.getExpiredAlerts();
            try {
                if (isActive())
                    log.debug("checking next");
                for (PendingAlert pendingAlert : pendingAlerts) {
                    if (!isActive()) {
                        break;
                    }
                    log.debug("next");
                    User user = null;
                    int consecutiveExceptions = 0;
                    Transaction transaction = HibernateUtil.currentSession().beginTransaction();
                    try {
                        if (pendingAlert.isDeleted()) {
                            log.debug("deleted");
                            continue;
                        }
                        ProgramAlert programAlert = pendingAlert.getProgramAlert();
                        if (programAlert == null) { // then this should be a manual pending alert
                            pendingAlert.setDeleted(true);
                            pendingAlert.save();
                            if (!pendingAlert.isManual()) {
                                log.debug("no program alert");
                                continue;
                            }
                        }
                        user = pendingAlert.getUser();
                        String programId = pendingAlert.getProgramId();
                        if (user == null || programId == null) {
                            log.debug("user (" + user + ") can't be null and programId (" + programId
                                    + ") can't be null");
                            if (programAlert != null) {
                                programAlert.setDeleted(true);
                                programAlert.save();
                            }
                            continue;
                        }
                        ScheduledProgram scheduledProgram = alertManager.getEpg()
                                .getScheduledProgramByNetworkCallSign(pendingAlert.getUser().getLineupId(),
                                        pendingAlert.getCallSign(), pendingAlert.getProgramStartTime());
                        String targetId;
                        if (programAlert == null) {
                            targetId = scheduledProgram.getProgramId();
                        } else {
                            targetId = programAlert.getProgramId();
                            // not a manual alert, so this is the id for the reminder itself
                        }
                        Program targetProgram = alertManager.getEpg().getProgram(targetId);

                        boolean invalidProgramAlert = false;

                        if (scheduledProgram == null) {
                            if (log.isDebugEnabled())
                                log.debug("no scheduled program");
                        } else {
                            if (!scheduledProgram.getProgramId().equals(programId)) {
                                invalidProgramAlert = true;
                                if (log.isDebugEnabled())
                                    log.debug("Schedule must have changed...no matching programId: "
                                            + scheduledProgram.getProgramId() + " != " + programId);
                            } else if (programAlert != null) { // Not a manual (quick) alert
                                if (programAlert.isDisabled()) {
                                    invalidProgramAlert = true;
                                    if (log.isDebugEnabled())
                                        log.debug("program alert disabled");
                                } else if (programAlert.isDeleted()) {
                                    invalidProgramAlert = true;
                                    if (log.isDebugEnabled())
                                        log.debug("program alert was deleted");
                                }
                            }
                        }

                        if ((scheduledProgram != null) && (!invalidProgramAlert)) {

                            boolean scheduledAlert = false;
                            boolean episodeAlert = false;
                            if (programAlert == null) {
                                scheduledAlert = true;
                            } else {
                                episodeAlert = true;
                            }

                            log.debug("firing pending alert=" + pendingAlert.getId());

                            Date startTime = scheduledProgram.getStartTime();
                            Date endTime = scheduledProgram.getEndTime();

                            long durationMinutes = (endTime.getTime() - startTime.getTime()) / (60 * 1000);

                            Map<String, String> context = new HashMap<String, String>();

                            DateFormat format = null;
                            DateFormat shortFormat = null;
                            if ((startTime.getTime() - System.currentTimeMillis()) < 12 * 60 * 60 * 1000) {
                                format = DateFormat.getTimeInstance(DateFormat.SHORT);
                                shortFormat = DateFormat.getTimeInstance(DateFormat.SHORT);
                                context.put("timePreposition", "at");
                            } else {
                                shortFormat = DateFormat.getDateTimeInstance(DateFormat.SHORT,
                                        DateFormat.SHORT);
                                format = new SimpleDateFormat("EEEE, MMMM d 'at' h:mm a");
                                context.put("timePreposition", "on");
                            }
                            format.setTimeZone(user.getTimeZone());
                            shortFormat.setTimeZone(user.getTimeZone());
                            context.put("startTime", format.format(startTime));
                            context.put("shortStartTime", shortFormat.format(startTime));

                            context.put("durationMinutes", Long.toString(durationMinutes));
                            context.put("programId", scheduledProgram.getProgramId()); // don't use ID from programAlert
                            // which may be a show, but this may be an episode, or may be a team, but this a game
                            String webPath = scheduledProgram.getWebPath();
                            if (webPath.charAt(0) == '/') {
                                webPath = webPath.substring(1);
                            }
                            context.put("webPath", webPath);
                            context.put("targetId", targetId);
                            context.put("programLabel", scheduledProgram.getLabel());
                            if (targetId.startsWith("TE")) {
                                context.put("whatfor", "any game featuring the " + targetProgram.getTeamName());
                                context.put("reducedTitle40", targetProgram.getReducedTitle40());
                            } else {
                                context.put("whatfor", "the following program");
                                context.put("reducedTitle40", scheduledProgram.getReducedTitle40());
                            }
                            if (scheduledProgram.getDescription().trim().length() > 0) {
                                context.put("description",
                                        "Description: " + scheduledProgram.getDescription() + "<br/>");
                            } else {
                                context.put("description", "");
                            }
                            context.put("stationName", scheduledProgram.getNetwork().getStationName());
                            String greeting = user.getUsername();
                            context.put("username", greeting);
                            String firstName = user.getFirstName();
                            if (firstName != null && firstName.trim().length() > 0) {
                                greeting = firstName;
                            }
                            context.put("greeting", greeting);
                            String targetWebPath = targetProgram.getWebPath();
                            if (targetWebPath.charAt(0) == '/') {
                                targetWebPath = targetWebPath.substring(1);
                            }
                            context.put("showDetailsLink", "<a href=\"" + url + targetWebPath + "#reminders\">"
                                    + url + targetWebPath + "#reminders</a>");
                            if (episodeAlert) {
                                context.put("deleteRemindersSentence",
                                        "Did you already see this program? If you're done with this reminder, "
                                                + "<a href=\"" + url
                                                + "reminders/deleteProgramReminders?programId=" + targetId
                                                + "\">click here to delete the reminders for this program</a>.");
                                /*
                                LATER, REPLACE THE LAST PARAGRAPH ABOVE WITH...
                                <p>
                                Did you already see this program?  <a href="${url}reminders/deleteProgramReminders?programId=@programId@">Click
                                here to delete the reminders for this program</a>\, and if you don't mind\, tell us what you think.
                                </p>
                                AND PUT A SIMILAR MESSAGE WITHOUT THE DELETE BUT WITH A LINK IN IF NOT EPISODEREMINDER, in "ELSE" BELOW
                                    */
                            } else {
                                context.put("deleteRemindersSentence", "");
                            }
                            if ((programAlert != null && programAlert.isUsingPrimaryEmail())
                                    || user.isUsingPrimaryEmailDefault()) {
                                Message message = new Message("program_reminder_email", context);
                                if ((startTime.getTime() - System.currentTimeMillis()) > 4 * 60 * 60 * 1000) {
                                    message.setPriority(2);
                                }
                                message.setUser(user);
                                message.setTo(user.getPrimaryEmail());
                                message.insert();
                            }
                            if ((programAlert != null && programAlert.isUsingSMS()
                                    && user.getSmsEmail().trim().length() > 0) || user.isUsingSMSDefault()) {
                                Message message = new Message("program_reminder_sms", context);
                                if ((startTime.getTime() - System.currentTimeMillis()) > 4 * 60 * 60 * 1000) {
                                    message.setPriority(2);
                                }
                                message.setUser(user);
                                message.setTo(user.getSmsEmail());
                                message.setSms(true);
                                message.insert();
                            }
                        }
                        consecutiveExceptions = 0;
                    } catch (MessageContextException e) {
                        log.error(
                                "Software bug resulted in exception with email message context or configuration",
                                e);
                    } catch (Throwable t) {
                        log.error("Could not complete pending alert execution", t);
                        transaction.rollback();
                        log.error("Caught throwable on pendingAlert " + pendingAlert.getId() + ", user "
                                + ((user == null) ? null : user.getUsername()), t);
                        consecutiveExceptions++;
                        if (consecutiveExceptions >= maxConsecutiveExceptions) {
                            log.fatal(
                                    "Reached max consecutive exceptions for PendingAlertThread. Exiting thread immediately.");
                            return;
                        }
                    } finally {
                        if (transaction.wasRolledBack()) {
                            transaction = HibernateUtil.currentSession().beginTransaction();
                        }
                        try {
                            log.debug("marking pending alert=" + pendingAlert.getId()
                                    + " as fired. Should see commit message next.");
                            pendingAlert.setFired(true);
                            pendingAlert.save();
                            log.debug("committing after marking pending alert");
                        } catch (Throwable t) {
                            log.error("Coult not mark pending alert", t);
                        } finally {
                            transaction.commit();
                        }
                    }
                }

                // Now that we aren't looping on PendingAlerts, I should be able to safely
                // delete all of the PendingAlerts flagged as deleted without screwing up
                // paging (if we decide to implement paging up above)
                Transaction transaction = HibernateUtil.currentSession().beginTransaction();
                try {
                    log.debug("deleting marked-deleted pending alerts");
                    PendingAlert.deleteAllMarkedDeleted();
                    log.debug("deleted marked-deleted pending alerts");
                    log.debug("deleting marked-fired pending alerts if program has started");
                    PendingAlert.deleteOldFired();
                    log.debug("deleted marked-deleted pending alerts");
                } finally {
                    transaction.commit();
                }
            } finally {
                HibernateUtil.closeSession();
            }
        }
    } catch (Throwable t) {
        log.fatal("Caught unexpected exception, causing abort of thread!", t);
    }
}