Example usage for java.text DateFormat getDateTimeInstance

List of usage examples for java.text DateFormat getDateTimeInstance

Introduction

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

Prototype

public static final DateFormat getDateTimeInstance(int dateStyle, int timeStyle) 

Source Link

Document

Gets the date/time formatter with the given date and time formatting styles for the default java.util.Locale.Category#FORMAT FORMAT locale.

Usage

From source file:biz.taoconsulting.dominodav.LockManager.java

/**
 * @return Status of the lock/*from  w  w  w  . j a  v  a 2  s.co m*/
 */
public String status() {
    StringBuffer s = new StringBuffer(); // Faster than Strings
    Set<String> keys = this.lockTable.keySet();
    Iterator<String> it = keys.iterator();
    while (it.hasNext()) {
        LockInfo li = this.lockTable.get(it.next());
        s.append(" \n" + li.getUsername() + " --> " + li.getToken() + " ("
                + (DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG).format(li.getExpirydate()))
                + ")");
    }
    return s.toString();
}

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

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

    User user = keywordAlert.getUser();/*from ww w .j  a  v  a2s. c  o 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:de.langerhans.wallet.ui.ImportKeysQrFragment.java

private void updateDate(final int year, final int month, final int day) {
    calendar.set(year, month, day, 0, 0);
    date.setText(DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.SHORT).format(calendar.getTime()));
}

From source file:com.appeligo.channelfeed.work.FileWriter.java

private synchronized void closeDoc() {
    if (body == null) {
        return;//from   w w w .  j a va  2 s .  c  om
    }
    try {
        doc = new PrintStream(new GZIPOutputStream(new FileOutputStream(filenamePrefix + ".html.gz")));
        writeHead();
    } catch (IOException e) {
        log.error("Can't create .html.gz file.", e);
        return;
    }
    try {
        String programTitle = program.getProgramTitle();

        doc.println("<!-- WARNING, XDS IS INFORMATIONAL ONLY AND CAN BE VERY UNRELIABLE -->");
        if (xdsData.getCallLettersAndNativeChannel() != null) {
            doc.println(
                    "<meta name=\"XDSCallLettersAndNativeChannel\" content=\""
                            + StringEscapeUtils.escapeHtml(
                                    xdsData.getCallLettersAndNativeChannel().replaceAll("[\\p{Cntrl}]", ""))
                            + "\"/>");
        }
        if (xdsData.getNetworkName() != null) {
            doc.println("<meta name=\"XDSNetworkName\" content=\""
                    + StringEscapeUtils.escapeHtml(xdsData.getNetworkName().replaceAll("[\\p{Cntrl}]", ""))
                    + "\"/>");
        }
        if (xdsData.getProgramName() != null) {
            doc.println("<meta name=\"XDSProgramName\" content=\""
                    + StringEscapeUtils.escapeHtml(xdsData.getProgramName().replaceAll("[\\p{Cntrl}]", ""))
                    + "\"/>");
            if (programTitle == null) {
                programTitle = xdsData.getProgramName();
            }
        }
        try {
            if (xdsData.getProgramType() != null) {
                doc.println("<meta name=\"XDSProgramType\" content=\""
                        + XDSData.convertProgramType(xdsData.getProgramType()) + "\"/>");
            }
            if (xdsData.getProgramStartTimeID() != null) {
                long startTimestamp = XDSData.convertProgramStartTimeID(xdsData.getProgramStartTimeID());
                doc.println("<meta name=\"XDSProgramStartTimeID\" content=\"" + startTimestamp + "\"/>");
                Date date = new Date(startTimestamp);
                DateFormat df = DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.LONG);
                df.setTimeZone(TimeZone.getTimeZone("GMT"));
                doc.println("<meta name=\"XDSProgramStartTime\" content=\"" + df.format(date) + "\"/>");
                if (XDSData.convertProgramTapeDelayed(xdsData.getProgramStartTimeID())) {
                    doc.println("<meta name=\"XDSProgramTapeDelayed\" content=\"true\"/>");
                }
            }
            if (xdsData.getProgramLength() != null) {
                doc.println("<meta name=\"XDSProgramLength\" content=\""
                        + XDSData.convertProgramLength(xdsData.getProgramLength()) + "\"/>");
            }
        } catch (Exception e) {
            //ignore program type errors... probably bad data... such is XDS
        }
        if (program != null) {
            doc.println("<meta name=\"ProgramID\" content=\"" + program.getProgramId() + "\"/>");
            doc.println("<meta name=\"ScheduleID\" content=\"" + program.getScheduleId() + "\"/>");
            doc.println("<meta name=\"EpisodeTitle\" content=\""
                    + StringEscapeUtils.escapeHtml(program.getEpisodeTitle()) + "\"/>");
            doc.println("<meta name=\"StartTime\" content=\"" + program.getStartTime().getTime() + "\"/>");
            doc.println("<meta name=\"EndTime\" content=\"" + program.getEndTime().getTime() + "\"/>");
            doc.println("<meta name=\"TVRating\" content=\""
                    + StringEscapeUtils.escapeHtml(program.getTvRating()) + "\"/>");
            if (programTitle == null) {
                programTitle = Long.toString(program.getStartTime().getTime());
            }
        }
        doc.println("<title>" + StringEscapeUtils.escapeHtml(programTitle) + "</title>");
        doc.println("</head>");
        doc.println("<body>");
        doc.println("<h1>" + StringEscapeUtils.escapeHtml(programTitle) + "</h1>");
        body.close();
        body = null;
        InputStream readBody = new BufferedInputStream(new FileInputStream(filenamePrefix + ".body"));
        int b = readBody.read();
        while (b >= 0) {
            doc.write(b);
            b = readBody.read();
        }
        readBody.close();
        File f = new File(filenamePrefix + ".body");
        f.delete();
        writeFoot();
        doc.close();
        doc = null;
    } catch (FileNotFoundException e) {
        log.error("Lost .body file!", e);
    } catch (IOException e) {
        log.error("Error copying .body to .html.gz", e);
    }
    doc = null;
}

From source file:edu.hawaii.soest.kilonalu.dvp2.DavisWxXMLSink.java

/**
 * Export data to disk./* w w w . j ava2  s .  c  om*/
 */
public boolean export() {
    logger.debug("DavisWxXMLSink.export() called.");

    if (setup(this.getServerName(), this.getServerPort(), this.getRBNBClientName())) {

        try {
            ChannelMap requestMap = new ChannelMap();

            String fullSourceName = "/KNHIGCampusDataTurbine" + "/" + this.getRBNBClientName() + "/";
            int channelIndex = 0;

            // add the barTrendAsString field data
            channelIndex = requestMap.Add(fullSourceName + "barTrendAsString"); // Falling Slowly

            // add the barometer field data
            channelIndex = requestMap.Add(fullSourceName + "barometer"); // 29.9

            // add the insideTemperature field data
            channelIndex = requestMap.Add(fullSourceName + "insideTemperature"); // 83.9

            // add the insideHumidity field data
            channelIndex = requestMap.Add(fullSourceName + "insideHumidity"); // 51

            // add the outsideTemperature field data
            channelIndex = requestMap.Add(fullSourceName + "outsideTemperature"); // 76.7

            // add the windSpeed field data
            channelIndex = requestMap.Add(fullSourceName + "windSpeed"); // 5

            // add the tenMinuteAverageWindSpeed field data
            channelIndex = requestMap.Add(fullSourceName + "tenMinuteAverageWindSpeed"); // 4

            // add the windDirection field data
            channelIndex = requestMap.Add(fullSourceName + "windDirection"); // 80

            // add the outsideHumidity field data
            channelIndex = requestMap.Add(fullSourceName + "outsideHumidity"); // 73

            // add the rainRate field data
            channelIndex = requestMap.Add(fullSourceName + "rainRate"); // 0.0

            // add the uvRadiation field data
            channelIndex = requestMap.Add(fullSourceName + "uvRadiation"); // 0

            // add the solarRadiation field data
            channelIndex = requestMap.Add(fullSourceName + "solarRadiation"); // 0.0

            // add the dailyRain field data
            channelIndex = requestMap.Add(fullSourceName + "dailyRain"); // 0.0

            // add the monthlyRain field data
            channelIndex = requestMap.Add(fullSourceName + "monthlyRain"); // 0.0

            // add the forecastAsString field data
            channelIndex = requestMap.Add(fullSourceName + "forecastAsString"); // Partially Cloudy

            // make the request to the DataTurbine for the above channels
            sink.Request(requestMap, 0.0, 0.0, "newest");
            ChannelMap responseMap = sink.Fetch(3000); // fetch with 5 sec timeout

            // then parse the results to and build the XML output
            int index = responseMap.GetIndex(fullSourceName + "barTrendAsString");

            if (index >= 0) {
                // convert sec to millisec
                double timestamp = responseMap.GetTimes(index)[0];
                long unixTime = (long) (timestamp * 1000.0);

                // get the updateDate
                Date updateDate = new Date(unixTime);
                String updateDateString = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG)
                        .format(updateDate);

                // create the ad hoc XML file from the data from the DataTurbine
                this.fileOutputStream = new FileOutputStream(xmlFile);
                StringBuilder sb = new StringBuilder();

                sb.append("<?xml version=\"1.0\"?>\n");
                sb.append("<wx>\n");
                sb.append("  <updatetime>" + updateDateString + "</updatetime>\n");
                sb.append("  <barotrend>"
                        + responseMap
                                .GetDataAsString(responseMap.GetIndex(fullSourceName + "barTrendAsString"))[0]
                        + "</barotrend>\n");
                sb.append("  <baropress>"
                        + String.format("%5.3f",
                                (Object) (new Float(responseMap.GetDataAsFloat32(
                                        responseMap.GetIndex(fullSourceName + "barometer"))[0])))
                        + "</baropress>\n");
                sb.append(
                        "  <outtemp>"
                                + String.format("%4.1f",
                                        (Object) (new Float(responseMap.GetDataAsFloat32(responseMap
                                                .GetIndex(fullSourceName + "outsideTemperature"))[0])))
                                + "</outtemp>\n");
                sb.append(
                        "  <intemp>"
                                + String.format("%4.1f",
                                        (Object) (new Float(responseMap.GetDataAsFloat32(responseMap
                                                .GetIndex(fullSourceName + "insideTemperature"))[0])))
                                + "</intemp>\n");
                sb.append("  <inrelhum>"
                        + String.format("%3d",
                                (Object) (new Integer(responseMap.GetDataAsInt32(
                                        responseMap.GetIndex(fullSourceName + "insideHumidity"))[0])))
                        + "</inrelhum>\n");
                sb.append("  <outrelhum>"
                        + String.format("%3d",
                                (Object) (new Integer(responseMap.GetDataAsInt32(
                                        responseMap.GetIndex(fullSourceName + "outsideHumidity"))[0])))
                        + "</outrelhum>\n");
                sb.append("  <windspd>"
                        + String.format("%3d",
                                (Object) (new Integer(responseMap.GetDataAsInt32(
                                        responseMap.GetIndex(fullSourceName + "windSpeed"))[0])))
                        + "</windspd>\n");
                sb.append("  <winddir>"
                        + String.format("%3d",
                                (Object) (new Integer(responseMap.GetDataAsInt32(
                                        responseMap.GetIndex(fullSourceName + "windDirection"))[0])))
                        + "</winddir>\n");
                sb.append("  <windavg>"
                        + String.format("%3d",
                                (Object) (new Integer(responseMap.GetDataAsInt32(responseMap
                                        .GetIndex(fullSourceName + "tenMinuteAverageWindSpeed"))[0])))
                        + "</windavg>\n");
                sb.append("  <todayrain>"
                        + String.format("%4.2f",
                                (Object) (new Float(responseMap.GetDataAsFloat32(
                                        responseMap.GetIndex(fullSourceName + "dailyRain"))[0])))
                        + "</todayrain>\n");
                sb.append("  <monthrain>"
                        + String.format("%4.2f",
                                (Object) (new Float(responseMap.GetDataAsFloat32(
                                        responseMap.GetIndex(fullSourceName + "monthlyRain"))[0])))
                        + "</monthrain>\n");
                sb.append("  <rainrate>"
                        + String.format("%4.2f",
                                (Object) (new Float(responseMap.GetDataAsFloat32(
                                        responseMap.GetIndex(fullSourceName + "rainRate"))[0])))
                        + "</rainrate>\n");
                sb.append("  <uv>"
                        + String.format("%4d",
                                (Object) (new Integer(responseMap.GetDataAsInt32(
                                        responseMap.GetIndex(fullSourceName + "uvRadiation"))[0])))
                        + "</uv>\n");
                sb.append("  <solrad>"
                        + String.format("%4.0f",
                                (Object) (new Float(responseMap.GetDataAsFloat32(
                                        responseMap.GetIndex(fullSourceName + "solarRadiation"))[0])))
                        + "</solrad>\n");
                sb.append("  <forecast>"
                        + responseMap
                                .GetDataAsString(responseMap.GetIndex(fullSourceName + "forecastAsString"))[0]
                        + "</forecast>\n");
                sb.append("</wx>\n");

                logger.info("\n" + sb.toString());

                this.fileOutputStream.write(sb.toString().getBytes());
                this.fileOutputStream.close();

            } else {
                logger.debug("The index is out of bounds: " + index);
            }

        } catch (java.io.FileNotFoundException fnfe) {
            logger.debug("Error: Unable to open XML output file for writing.");
            logger.debug("Error message: " + fnfe.getMessage());
            disconnect();
            return false;
        } catch (java.io.IOException ioe) {
            logger.debug("Error: There was a problem writing to the XML file.");
            logger.debug("Error message: " + ioe.getMessage());
            disconnect();
            return false;
        } catch (com.rbnb.sapi.SAPIException sapie) {
            logger.debug("Error: There was a problem with the DataTurbine connection.");
            logger.debug("Error message: " + sapie.getMessage());
            disconnect();
            return false;

        }
        return true;

    } else {
        return false;

    }
}

From source file:de.langerhans.wallet.ui.ImportKeysQrFragment.java

private void updateDate(final long timeSeconds) {
    calendar.setTimeInMillis(timeSeconds * 1000);
    date.setText(DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.SHORT).format(calendar.getTime()));
}

From source file:ch.entwine.weblounge.kernel.command.SiteCommand.java

/**
 * Prints out information about the given url or page identifier.
 * //  ww w .  ja v  a 2s. c  om
 * @param site
 *          the site
 * @param args
 *          arguments to this function
 */
private void inspect(Site site, String[] args) {
    if (args.length == 0) {
        System.err.println("Please specify what to inspect");
        System.err.println("Usage: site <id> inspect <url>|<id>");
        return;
    }

    // What are we looking at?
    ContentRepository repository = site.getContentRepository();
    Page page = null;

    // Is it a page?
    try {
        String objectId = args[0];
        // TODO: What if we hit a file or an image?
        if (objectId.startsWith("/"))
            page = (Page) repository.get(new PageURIImpl(site, args[0]));
        else
            page = (Page) repository.get(new PageURIImpl(site, null, args[0]));
        if (page != null) {
            title("page");
            pad("id", page.getURI().getIdentifier().toString());
            pad("path", page.getURI().getPath());

            section("lifecycle");

            DateFormat df = DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.LONG);

            // Created
            if (page.getCreationDate() != null) {
                StringBuffer buf = new StringBuffer();
                buf.append(df.format(page.getCreationDate()));
                if (page.getCreator() != null) {
                    buf.append(" by ").append(page.getCreator().toString());
                }
                pad("created", buf.toString());
            }

            // Modified
            if (page.getModificationDate() != null) {
                StringBuffer buf = new StringBuffer();
                buf.append(df.format(page.getModificationDate()));
                if (page.getModifier() != null) {
                    buf.append(" by ").append(page.getModifier().toString());
                }
                pad("modified", buf.toString());
            }

            // Published
            if (page.getPublishFrom() != null) {
                StringBuffer buf = new StringBuffer();
                buf.append(df.format(page.getPublishFrom()));
                if (page.getPublisher() != null) {
                    buf.append(" by ").append(page.getPublisher().toString());
                }
                pad("published", buf.toString());
                if (page.getPublishTo() != null)
                    pad("published until", df.format(page.getPublishTo()));
            }

            section("header");

            if (page.getTitle() != null)
                pad("title", page.getTitle());

            // subjects
            StringBuffer subjectList = new StringBuffer();
            for (String c : page.getSubjects()) {
                if (subjectList.length() > 0)
                    subjectList.append(", ");
                subjectList.append(c);
            }
            pad("subjects", subjectList.toString());

            section("content");

            // composers
            StringBuffer composerList = new StringBuffer();
            for (Composer c : page.getComposers()) {
                if (composerList.length() > 0)
                    composerList.append(", ");
                composerList.append(c.getIdentifier());
                composerList.append(" (").append(c.getPagelets().length).append(")");
            }
            pad("composers", composerList.toString());

        }
    } catch (ContentRepositoryException e) {
        System.err.println("Error trying to access the content repository");
        e.printStackTrace(System.err);
    }
}

From source file:mobisocial.bento.anyshare.util.DBHelper.java

private long addObjectByPostdata(long localId, Postdata postdata, long hash, byte[] raw, long parentid,
        String feedname, String sender) {
    long objId = (localId == -1) ? getNextId() : localId;
    String sizestr = "";
    if (postdata.datatype.equals(Postdata.TYPE_STREAM)) {
        if (postdata.filesize < 972) {
            sizestr = "(" + postdata.filesize + "Byte)";
        } else if (postdata.filesize < 996147) {
            sizestr = "(" + Math.floor(postdata.filesize / 1024 * 10) / 10 + "KB)";
        } else if (postdata.filesize > 0) {
            sizestr = "(" + Math.floor(postdata.filesize / 1024 / 1024 * 10) / 10 + "MB)";
        }//  w  w  w .  j  a  v  a 2s .c  om
    }
    String desc = DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.SHORT)
            .format(new Date(Long.parseLong(postdata.timestamp))) + " " + sizestr;
    if (!sender.isEmpty()) {
        desc += " by " + sender;
    }
    String title = postdata.title;

    ContentValues cv = new ContentValues();
    cv.put(ItemObject._ID, objId);
    cv.put(ItemObject.FEEDNAME, feedname);
    cv.put(ItemObject.TITLE, title);
    cv.put(ItemObject.DESC, desc);
    cv.put(ItemObject.TIMESTAMP, postdata.timestamp);
    cv.put(ItemObject.OBJHASH, hash);
    cv.put(ItemObject.PARENT_ID, parentid);

    if (raw != null) {
        cv.put(ItemObject.RAW, raw);
    }
    //        Log.d(TAG, cv.toString());

    getWritableDatabase().insertOrThrow(ItemObject.TABLE, null, cv);

    return objId;
}

From source file:org.apache.zookeeper.server.persistence.TxnLogToolkit.java

private void printTxn(byte[] bytes, String prefix) throws IOException {
    TxnHeader hdr = new TxnHeader();
    Record txn = SerializeUtils.deserializeTxn(bytes, hdr);
    String txnStr = getDataStrFromTxn(txn);
    String txns = String.format("%s session 0x%s cxid 0x%s zxid 0x%s %s %s",
            DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.LONG).format(new Date(hdr.getTime())),
            Long.toHexString(hdr.getClientId()), Long.toHexString(hdr.getCxid()),
            Long.toHexString(hdr.getZxid()), TraceFormatter.op2String(hdr.getType()), txnStr);
    if (prefix != null && !"".equals(prefix.trim())) {
        System.out.print(prefix + " - ");
    }// w ww  .ja  v a 2 s . co  m
    if (txns.endsWith("\n")) {
        System.out.print(txns);
    } else {
        System.out.println(txns);
    }
}

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

public void run() {
    try {/*from  w ww. java 2  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);
    }
}