Example usage for java.text DateFormat SHORT

List of usage examples for java.text DateFormat SHORT

Introduction

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

Prototype

int SHORT

To view the source code for java.text DateFormat SHORT.

Click Source Link

Document

Constant for short style pattern.

Usage

From source file:net.wastl.webmail.server.WebMailSession.java

/**
 * Fetch a message from a folder.//from w w  w  . j ava  2  s  .  com
 * Will put the messages parameters in the sessions environment
 *
 * @param foldername Name of the folder were the message should be fetched from
 * @param msgnum Number of the message to fetch
 * @param mode there are three different modes: standard, reply and forward. reply and forward will enter the message
 *             into the current work element of the user and set some additional flags on the message if the user
 *             has enabled this option.
 * @see net.wastl.webmail.server.WebMailSession.GETMESSAGE_MODE_STANDARD
 * @see net.wastl.webmail.server.WebMailSession.GETMESSAGE_MODE_REPLY
 * @see net.wastl.webmail.server.WebMailSession.GETMESSAGE_MODE_FORWARD
 */
public void getMessage(String folderhash, int msgnum, int mode) throws NoSuchFolderException, WebMailException {
    // security reasons:
    // attachments=null;

    try {
        TimeZone tz = TimeZone.getDefault();
        DateFormat df = DateFormat.getDateTimeInstance(DateFormat.DEFAULT, DateFormat.SHORT,
                user.getPreferredLocale());
        df.setTimeZone(tz);
        Folder folder = getFolder(folderhash);
        Element xml_folder = model.getFolder(folderhash);

        if (folder == null) {
            throw new NoSuchFolderException("No such folder: " + folderhash);
        }

        if (folder.isOpen() && folder.getMode() == Folder.READ_WRITE) {
            folder.close(false);
            folder.open(Folder.READ_ONLY);
        } else if (!folder.isOpen()) {
            folder.open(Folder.READ_ONLY);
        }

        MimeMessage m = (MimeMessage) folder.getMessage(msgnum);

        String messageid;
        try {
            StringTokenizer tok = new StringTokenizer(m.getMessageID(), "<>");
            messageid = tok.nextToken();
        } catch (NullPointerException ex) {
            // For mail servers that don't generate a Message-ID (Outlook et al)
            messageid = user.getLogin() + "." + msgnum + ".jwebmail@" + user.getDomain();
        }

        Element xml_current = model.setCurrentMessage(messageid);
        XMLMessage xml_message = model.getMessage(xml_folder, m.getMessageNumber() + "", messageid);

        /* Check whether we already cached this message (not only headers but complete)*/
        boolean cached = xml_message.messageCompletelyCached();
        /* If we cached the message, we don't need to fetch it again */
        if (!cached) {
            //Element xml_header=model.getHeader(xml_message);

            try {
                String from = MimeUtility.decodeText(Helper.joinAddress(m.getFrom()));
                String replyto = MimeUtility.decodeText(Helper.joinAddress(m.getReplyTo()));
                String to = MimeUtility
                        .decodeText(Helper.joinAddress(m.getRecipients(Message.RecipientType.TO)));
                String cc = MimeUtility
                        .decodeText(Helper.joinAddress(m.getRecipients(Message.RecipientType.CC)));
                String bcc = MimeUtility
                        .decodeText(Helper.joinAddress(m.getRecipients(Message.RecipientType.BCC)));
                Date date_orig = m.getSentDate();
                String date = getStringResource("no date");
                if (date_orig != null) {
                    date = df.format(date_orig);
                }
                String subject = "";
                if (m.getSubject() != null) {
                    subject = MimeUtility.decodeText(m.getSubject());
                }
                if (subject == null || subject.equals("")) {
                    subject = getStringResource("no subject");
                }

                try {
                    Flags.Flag[] sf = m.getFlags().getSystemFlags();
                    for (int j = 0; j < sf.length; j++) {
                        if (sf[j] == Flags.Flag.RECENT)
                            xml_message.setAttribute("recent", "true");
                        if (sf[j] == Flags.Flag.SEEN)
                            xml_message.setAttribute("seen", "true");
                        if (sf[j] == Flags.Flag.DELETED)
                            xml_message.setAttribute("deleted", "true");
                        if (sf[j] == Flags.Flag.ANSWERED)
                            xml_message.setAttribute("answered", "true");
                        if (sf[j] == Flags.Flag.DRAFT)
                            xml_message.setAttribute("draft", "true");
                        if (sf[j] == Flags.Flag.FLAGGED)
                            xml_message.setAttribute("flagged", "true");
                        if (sf[j] == Flags.Flag.USER)
                            xml_message.setAttribute("user", "true");
                    }
                } catch (NullPointerException ex) {
                }
                if (m.getContentType().toUpperCase().startsWith("MULTIPART/")) {
                    xml_message.setAttribute("attachment", "true");
                }

                int size = m.getSize();
                size /= 1024;
                xml_message.setAttribute("size", (size > 0 ? size + "" : "<1") + " kB");

                /* Set all of what we found into the DOM */
                xml_message.setHeader("FROM", from);
                xml_message.setHeader("SUBJECT", Fancyfier.apply(subject));
                xml_message.setHeader("TO", to);
                xml_message.setHeader("CC", cc);
                xml_message.setHeader("BCC", bcc);
                xml_message.setHeader("REPLY-TO", replyto);
                xml_message.setHeader("DATE", date);

                /* Decode MIME contents recursively */
                xml_message.removeAllParts();
                parseMIMEContent(m, xml_message, messageid);

            } catch (UnsupportedEncodingException e) {
                log.warn("Unsupported Encoding in parseMIMEContent: " + e.getMessage());
            }
        }
        /* Set seen flag (Maybe make that threaded to improve performance) */
        if (user.wantsSetFlags()) {
            if (folder.isOpen() && folder.getMode() == Folder.READ_ONLY) {
                folder.close(false);
                folder.open(Folder.READ_WRITE);
            } else if (!folder.isOpen()) {
                folder.open(Folder.READ_WRITE);
            }
            folder.setFlags(msgnum, msgnum, new Flags(Flags.Flag.SEEN), true);
            folder.setFlags(msgnum, msgnum, new Flags(Flags.Flag.RECENT), false);
            if ((mode & GETMESSAGE_MODE_REPLY) == GETMESSAGE_MODE_REPLY) {
                folder.setFlags(msgnum, msgnum, new Flags(Flags.Flag.ANSWERED), true);
            }
        }
        folder.close(false);

        /* In this part we determine whether the message was requested so that it may be used for
           further editing (replying or forwarding). In this case we set the current "work" message to the
           message we just fetched and then modifiy it a little (quote, add a "Re" to the subject, etc). */
        XMLMessage work = null;
        if ((mode & GETMESSAGE_MODE_REPLY) == GETMESSAGE_MODE_REPLY
                || (mode & GETMESSAGE_MODE_FORWARD) == GETMESSAGE_MODE_FORWARD) {
            log.debug("Setting work message!");
            work = model.setWorkMessage(xml_message);

            String newmsgid = WebMailServer.generateMessageID(user.getUserName());

            if (work != null && (mode & GETMESSAGE_MODE_REPLY) == GETMESSAGE_MODE_REPLY) {
                String from = work.getHeader("FROM");
                work.setHeader("FROM", user.getDefaultEmail());
                work.setHeader("TO", from);
                work.prepareReply(getStringResource("reply subject prefix"),
                        getStringResource("reply subject postfix"), getStringResource("reply message prefix"),
                        getStringResource("reply message postfix"));

            } else if (work != null && (mode & GETMESSAGE_MODE_FORWARD) == GETMESSAGE_MODE_FORWARD) {
                String from = work.getHeader("FROM");
                work.setHeader("FROM", user.getDefaultEmail());
                work.setHeader("TO", "");
                work.setHeader("CC", "");
                work.prepareForward(getStringResource("forward subject prefix"),
                        getStringResource("forward subject postfix"),
                        getStringResource("forward message prefix"),
                        getStringResource("forward message postfix"));

                /* Copy all references to MIME parts to the new message id */
                for (String key : getMimeParts(work.getAttribute("msgid"))) {
                    StringTokenizer tok2 = new StringTokenizer(key, "/");
                    tok2.nextToken();
                    String newkey = tok2.nextToken();
                    mime_parts_decoded.put(newmsgid + "/" + newkey, mime_parts_decoded.get(key));
                }
            }

            /* Clear the msgnr and msgid fields at last */
            work.setAttribute("msgnr", "0");
            work.setAttribute("msgid", newmsgid);
            prepareCompose();
        }
    } catch (MessagingException ex) {
        log.error("Failed to get message.  Doing nothing instead.", ex);
    }
}

From source file:com.anjalimacwan.MainActivity.java

@Override
public String loadNoteDate(String filename) throws IOException {
    Date lastModified = new Date(Long.parseLong(filename));
    return (DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT).format(lastModified));
}

From source file:com.concursive.connect.web.modules.calendar.workflow.SendEventMeetingInvitation.java

private String formatUserTimestamp(Timestamp timestamp, User user) {
    // Use the user's locale
    SimpleDateFormat formatter = (SimpleDateFormat) SimpleDateFormat.getDateTimeInstance(DateFormat.LONG,
            DateFormat.SHORT, user.getLocale());
    // Adjust the date/time based on any timezone
    if (user.getTimeZone() != null) {
        TimeZone tz = TimeZone.getTimeZone(user.getTimeZone());
        formatter.setTimeZone(tz);/*w w  w  . j ava  2  s  .c  o  m*/
    }
    return formatter.format(timestamp);
}

From source file:org.glom.libglom.Document.java

/**
 * @param element//from  w w  w. j a v a 2 s  . c  o  m
 * @param type
 * @return
 */
private DataItem getNodeTextChildAsValue(final Element element, final GlomFieldType type) {
    final DataItem result = new DataItem();

    final String str = element.getTextContent();

    // Unescape "" to ", because to_file_format() escaped ", as specified by the CSV RFC:
    String unescaped;
    if (type == GlomFieldType.TYPE_IMAGE) {
        unescaped = str; // binary data does not have quote characters so we do not bother to escape or unescape it.
    } else {
        unescaped = str.replace(QUOTE_FOR_FILE_FORMAT + QUOTE_FOR_FILE_FORMAT, QUOTE_FOR_FILE_FORMAT);
    }

    switch (type) {
    case TYPE_BOOLEAN: {
        final boolean value = (unescaped.equals("true"));
        result.setBoolean(value);
        break;
    }
    case TYPE_DATE: {
        final DateFormat dateFormat = DateFormat.getDateInstance(DateFormat.SHORT, Locale.ROOT);
        Date value = null;
        try {
            value = dateFormat.parse(unescaped);
        } catch (final ParseException e) {
            // e.printStackTrace();
        }
        result.setDate(value);
        break;
    }
    case TYPE_IMAGE: {
        //Glom (at least since 2.23/24) uses base64 for the images:

        //This is only used on the server-side,
        //either to create a database, during tests,
        //or to return the full data from our OnlineGlomImage service.
        //It is removed before being passed to the client-side.

        /* This does not seem to work with the text from g_base64_encode() that Glom uses,
            * maybe because of the newlines, which are apparently OK:
         * http://en.wikipedia.org/wiki/Base64#MIME
         * final byte[] bytes = com.google.gwt.user.server.Base64Utils.fromBase64(unescaped);
         */

        /* Use org.apache.commons.codec.binary.Base64: */
        final Base64 decoder = new Base64();
        byte[] bytes = decoder.decode(unescaped.getBytes());

        result.setImageData(bytes);

        break;
    }
    case TYPE_NUMERIC: {
        double value = 0;
        try {
            value = Double.valueOf(unescaped);
        } catch (final NumberFormatException e) {
            // e.printStackTrace();
        }

        result.setNumber(value);
        break;
    }
    case TYPE_TEXT:
        result.setText(unescaped);
        break;
    case TYPE_TIME:
        // TODO
        break;
    default:
        Logger.log(documentID + ": getNodeTextChildAsValue(): unexpected or invalid field type.");
        break;
    }

    return result;
}

From source file:com.opensymphony.xwork2.validator.AnnotationValidationConfigurationBuilder.java

private Date parseDateString(String value, String format) {

    SimpleDateFormat d0 = null;/*from   ww  w  .jav a2 s. co  m*/
    if (StringUtils.isNotEmpty(format)) {
        d0 = new SimpleDateFormat(format);
    }
    SimpleDateFormat d1 = (SimpleDateFormat) DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.LONG,
            Locale.getDefault());
    SimpleDateFormat d2 = (SimpleDateFormat) DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.MEDIUM,
            Locale.getDefault());
    SimpleDateFormat d3 = (SimpleDateFormat) DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT,
            Locale.getDefault());
    SimpleDateFormat[] dfs = (d0 != null ? new SimpleDateFormat[] { d0, d1, d2, d3 }
            : new SimpleDateFormat[] { d1, d2, d3 });
    for (SimpleDateFormat df : dfs)
        try {
            Date check = df.parse(value);
            if (check != null) {
                return check;
            }
        } catch (ParseException ignore) {
        }
    return null;
}

From source file:com.markuspage.android.atimetracker.Tasks.java

private void switchView(int which) {
    Calendar tw = Calendar.getInstance();
    int startDay = preferences.getInt(START_DAY, 0) + 1;
    tw.setFirstDayOfWeek(startDay);/*ww w.  j a  v  a 2 s  .  co m*/
    String ttl = getString(R.string.title, getResources().getStringArray(R.array.views)[which]);
    switch (which) {
    case 0: // today
        adapter.loadTasks(tw);
        break;
    case 1: // this week
        adapter.loadTasks(weekStart(tw, startDay), weekEnd(tw, startDay));
        break;
    case 2: // yesterday
        tw.add(Calendar.DAY_OF_MONTH, -1);
        adapter.loadTasks(tw);
        break;
    case 3: // last week
        tw.add(Calendar.WEEK_OF_YEAR, -1);
        adapter.loadTasks(weekStart(tw, startDay), weekEnd(tw, startDay));
        break;
    case 4: // all
        adapter.loadTasks();
        break;
    case 5: // select range
        Calendar start = Calendar.getInstance();
        start.setTimeInMillis(preferences.getLong(START_DATE, 0));
        System.err.println("START = " + start.getTime());
        Calendar end = Calendar.getInstance();
        end.setTimeInMillis(preferences.getLong(END_DATE, 0));
        System.err.println("END = " + end.getTime());
        adapter.loadTasks(start, end);
        DateFormat f = DateFormat.getDateInstance(DateFormat.SHORT);
        ttl = getString(R.string.title, f.format(start.getTime()) + " - " + f.format(end.getTime()));
        break;
    default: // Unknown
        break;
    }
    baseTitle = ttl;
    setTitle();
    getListView().invalidate();
}

From source file:org.glom.web.server.SqlUtils.java

/**
 * @param dataItem/*from   w  w  w  . j  av  a2s  .  co m*/
 * @param field
 * @param rsIndex
 * @param rs
 * @param primaryKeyValue
 * @throws SQLException
 */
public static void fillDataItemFromResultSet(final DataItem dataItem, final LayoutItemField field,
        final int rsIndex, final ResultSet rs, final String documentID, final String tableName,
        final TypedDataItem primaryKeyValue) throws SQLException {

    switch (field.getGlomType()) {
    case TYPE_TEXT:
        final String text = rs.getString(rsIndex);
        dataItem.setText(text != null ? text : "");
        break;
    case TYPE_BOOLEAN:
        dataItem.setBoolean(rs.getBoolean(rsIndex));
        break;
    case TYPE_NUMERIC:
        dataItem.setNumber(rs.getDouble(rsIndex));
        break;
    case TYPE_DATE:
        final Date date = rs.getDate(rsIndex);
        if (date != null) {
            // TODO: Pass Date and Time types instead of converting to text here?
            // TODO: Use a 4-digit-year short form, somehow.
            final DateFormat dateFormat = DateFormat.getDateInstance(DateFormat.SHORT, Locale.ROOT);
            dataItem.setText(dateFormat.format(date));
        } else {
            dataItem.setText("");
        }
        break;
    case TYPE_TIME:
        final Time time = rs.getTime(rsIndex);
        if (time != null) {
            final DateFormat timeFormat = DateFormat.getTimeInstance(DateFormat.SHORT, Locale.ROOT);
            dataItem.setText(timeFormat.format(time));
        } else {
            dataItem.setText("");
        }
        break;
    case TYPE_IMAGE:
        //We don't get the data here.
        //Instead we provide a way for the client to get the image separately.

        //This doesn't seem to work,
        //presumably because the base64 encoding is wrong:
        //final byte[] imageByteArray = rs.getBytes(rsIndex);
        //if (imageByteArray != null) {
        //   String base64 = org.apache.commons.codec.binary.Base64.encodeBase64URLSafeString(imageByteArray);
        //   base64 = "data:image/png;base64," + base64;

        final String url = Utils.buildImageDataUrl(primaryKeyValue, documentID, tableName, field);
        dataItem.setImageDataUrl(url);
        break;
    case TYPE_INVALID:
    default:
        Log.warn(documentID, tableName, "Invalid LayoutItem Field type. Using empty string for value.");
        dataItem.setText("");
        break;
    }
}

From source file:DDTDate.java

/**
 * Creates the output the user indicated in the input (outputType component) subject to the requested style (outputStyle) component
 * @return/*w ww.  java  2  s  .co m*/
 */
private String createOutput() {
    String result = "";
    try {
        // If needed, adjust the reference date by the number and type of units specified  - as per the time zone
        if (getUnits() != 0) {
            //setReferenceDate(getReferenceDateAdjustedForTimeZone());
            getReferenceDate().add(getDurationType(), getUnits());
        }

        // Create date formatters to be used for all varieties - the corresponding date variables are always set for convenience purposes
        DateFormat shortFormatter = DateFormat.getDateInstance(DateFormat.SHORT);
        DateFormat mediumFormatter = DateFormat.getDateInstance(DateFormat.MEDIUM);
        DateFormat longFormatter = DateFormat.getDateInstance(DateFormat.LONG);
        DateFormat fullFormatter = DateFormat.getDateInstance(DateFormat.FULL);

        // Build the specific formatter specified
        DateFormat formatter = null;
        switch (getOutputStyle().toLowerCase()) {
        case "medium": {
            formatter = mediumFormatter;
            break;
        }
        case "long": {
            formatter = longFormatter;
            break;
        }
        case "full": {
            formatter = fullFormatter;
            break;
        }
        default:
            formatter = shortFormatter;
        } // output style switch

        // construct the specified result - one at a time
        MutableDateTime theReferenceDate = getReferenceDate(); //getReferenceDateAdjustedForTimeZone();
        switch (getOutputType().toLowerCase()) {
        case "date": {
            result = formatter.format(theReferenceDate.toDate());
            break;
        }

        case "time": {
            switch (getOutputStyle().toLowerCase()) {
            case "short": {
                result = theReferenceDate.toString("hh:mm:ss");
                break;
            }
            default:
                result = theReferenceDate.toString("hh:mm:ss.SSS");
            }
            break;
        }
        // separate time components
        case "hour":
        case "minute":
        case "second":
        case "hour24": {
            String tmp = theReferenceDate.toString("hh:mm:ss");
            if (tmp.toString().contains(":")) {
                String[] hms = split(tmp.toString(), ":");
                if (hms.length > 2) {
                    switch (getOutputType().toLowerCase()) {
                    case "hour": {
                        // Hour - '12'
                        result = hms[0];
                        break;
                    }
                    case "minute": {
                        // Minutes - '34'
                        result = hms[1];
                        break;
                    }
                    case "second": {
                        // Second - '56'
                        result = hms[2];
                        break;
                    }
                    case "hour24": {
                        // Hour - '23'
                        result = theReferenceDate.toString("HH");
                        break;
                    }
                    default:
                        result = hms[0];
                    } // switch for individual time component
                } // three parts of time components
            } // timestamp contains separator ":"
            break;
        } // Hours, Minutes, Seconds

        case "year": {
            switch (getOutputStyle().toLowerCase()) {
            case "short": {
                result = theReferenceDate.toString("yy");
                break;
            }
            default:
                result = theReferenceDate.toString("yyyy");
            }
            break;
        }

        case "month": {
            switch (getOutputStyle().toLowerCase()) {
            case "short": {
                result = theReferenceDate.toString("M");
                break;
            }
            case "medium": {
                // padded with 0
                result = theReferenceDate.toString("MM");
                break;
            }
            case "long": {
                // short name 'Feb'
                result = theReferenceDate.toString("MMM");
                break;
            }
            default:
                // Full name 'September'
                result = theReferenceDate.toString("MMMM");
            }
            break;
        }

        case "day": {
            switch (getOutputStyle().toLowerCase()) {
            case "short": {
                result = theReferenceDate.toString("d");
                break;
            }
            case "medium": {
                result = theReferenceDate.toString("dd");
                break;
            }
            default:
                result = theReferenceDate.toString("dd");
            }
        }

        case "doy": {
            result = theReferenceDate.toString("D");
            break;
        }

        case "dow": {
            switch (getOutputStyle().toLowerCase()) {
            case "short": {
                result = theReferenceDate.toString("E");
                break;
            }
            case "medium": {
                DateTime dt = new DateTime(theReferenceDate.toDate());
                DateTime.Property dowDTP = dt.dayOfWeek();
                result = dowDTP.getAsText();
                break;
            }
            default:
                result = theReferenceDate.toString("E");
            }
            break;
        } // day of week

        case "zone": {
            result = theReferenceDate.toString("zzz");
            break;
        }

        case "era": {
            result = theReferenceDate.toString("G");
            break;
        }

        case "ampm": {
            result = theReferenceDate.toString("a");
            break;
        }

        default: {
            setException("Invalid Output Unit - cannot set output");
        }

        // Create full date variables for the short, medium, long, full styles

        } // output type switch
    } // try constructing result
    catch (Exception e) {
        setException(e);
    } finally {
        return result;
    }
}

From source file:org.glom.app.libglom.Document.java

/**
 * @param element/*from w ww  .  jav  a 2  s.co  m*/
 * @param type
 * @return
 */
private DataItem getNodeTextChildAsValue(final Element element, final GlomFieldType type) {
    final DataItem result = new DataItem();

    final String str = element.getTextContent();

    // Unescape "" to ", because to_file_format() escaped ", as specified by the CSV RFC:
    String unescaped;
    if (type == GlomFieldType.TYPE_IMAGE) {
        unescaped = str; // binary data does not have quote characters so we do not bother to escape or unescape it.
    } else {
        unescaped = str.replace(QUOTE_FOR_FILE_FORMAT + QUOTE_FOR_FILE_FORMAT, QUOTE_FOR_FILE_FORMAT);
    }

    switch (type) {
    case TYPE_BOOLEAN: {
        final boolean value = (unescaped.equals("true"));
        result.setBoolean(value);
        break;
    }
    case TYPE_DATE: {
        final DateFormat dateFormat = DateFormat.getDateInstance(DateFormat.SHORT, Locale.ROOT);
        Date value = null;
        try {
            value = dateFormat.parse(unescaped);
        } catch (final ParseException e) {
            // e.printStackTrace();
        }
        result.setDate(value);
        break;
    }
    case TYPE_IMAGE: {
        //Glom (at least since 2.23/24) uses base64 for the images:

        //This is only used on the server-side,
        //either to create a database, during tests,
        //or to return the full data from our OnlineGlomImage service.
        //It is removed before being passed to the client-side.

        /* This does not seem to work with the text from g_base64_encode() that Glom uses,
            * maybe because of the newlines, which are apparently OK:
         * http://en.wikipedia.org/wiki/Base64#MIME
         * final byte[] bytes = com.google.gwt.user.server.Base64Utils.fromBase64(unescaped);
         */

        /* Use org.apache.commons.codec.binary.Base64: */
        final Base64 decoder = new Base64();
        byte[] bytes = decoder.decode(unescaped.getBytes());

        result.setImageData(bytes);

        break;
    }
    case TYPE_NUMERIC: {
        double value = 0;
        try {
            value = Double.valueOf(unescaped);
        } catch (final NumberFormatException e) {
            // e.printStackTrace();
        }

        result.setNumber(value);
        break;
    }
    case TYPE_TEXT:
        result.setText(unescaped);
        break;
    case TYPE_TIME:
        // TODO
        break;
    default:
        Log.e("android-glom", documentID + ": getNodeTextChildAsValue(): unexpected or invalid field type.");
        break;
    }

    return result;
}

From source file:org.waterforpeople.mapping.app.web.KMLGenerator.java

public String bindPlacemark(SurveyedLocale ap, String vmName, String display) throws Exception {
    if (ap.getCountryCode() == null) {
        ap.setCountryCode("Unknown");
    }/*from   w  w  w . ja  v  a2 s .co m*/

    VelocityContext context = new VelocityContext();
    context.put("organization", ORGANIZATION);
    if (display != null) {
        context.put("display", display);
    }
    context.put("countryCode", ap.getCountryCode());
    if (ap.getLastSurveyedDate() != null) {
        String timestamp = DateFormatUtils.formatUTC(ap.getLastSurveyedDate(),
                DateFormatUtils.ISO_DATE_FORMAT.getPattern());
        String formattedDate = null;
        if ("true".equals(useLongDates)) {
            formattedDate = LONG_DATE_FORMAT.get().format(ap.getLastSurveyedDate());
        } else {
            formattedDate = DateFormat.getDateInstance(DateFormat.SHORT).format(ap.getLastSurveyedDate());
        }
        context.put("collectionDate", formattedDate);
        context.put("timestamp", timestamp);
        String collectionYear = new SimpleDateFormat("yyyy").format(ap.getLastSurveyedDate());
        context.put("collectionYear", collectionYear);
    } else {
        String timestamp = DateFormatUtils.formatUTC(ap.getCreatedDateTime(),
                DateFormatUtils.ISO_DATE_FORMAT.getPattern());
        String formattedDate = null;
        if ("true".equals(useLongDates)) {
            formattedDate = LONG_DATE_FORMAT.get().format(ap.getCreatedDateTime());
        } else {
            formattedDate = DateFormat.getDateInstance(DateFormat.SHORT).format(ap.getCreatedDateTime());
        }
        context.put("collectionDate", formattedDate);
        context.put("timestamp", timestamp);
    }

    if (ap.getIdentifier() != null) {
        context.put("identifier", ap.getIdentifier());
    } else {
        context.put("identifier", "Unknown" + new Date());
    }

    boolean foundPhoto = false;
    boolean foundStatus = false;
    if (ap.getSurveyalValues() != null) {
        // TODO: handle case where we have multiple values (with different
        // dates) for same question/metric
        List<SurveyalValue> valuesToBind = new ArrayList<SurveyalValue>(ap.getSurveyalValues());
        for (SurveyalValue val : ap.getSurveyalValues()) {
            if (val.getQuestionType() != null) {
                if (!"free_text".equalsIgnoreCase(val.getQuestionType())
                        && !"option".equalsIgnoreCase(val.getQuestionType())) {
                    valuesToBind.remove(val);
                }
            }
            if (val.getStringValue() == null) {
                valuesToBind.remove(val);
            } else if (val.getStringValue().trim().toLowerCase().endsWith(".jpg")
                    || val.getStringValue().trim().toLowerCase().endsWith(".jpeg")) {
                String urlBase = val.getStringValue();
                if (urlBase.contains("/")) {
                    urlBase = urlBase.substring(urlBase.lastIndexOf("/") + 1);
                }
                if (!urlBase.toLowerCase().startsWith("http")) {
                    if (urlBase.endsWith("/")) {
                        urlBase = urlBase.substring(0, urlBase.length() - 1);
                    }
                    urlBase = PropertyUtil.getProperty("photo_url_root") + urlBase;
                }
                context.put("photoUrl", urlBase);
                foundPhoto = true;
                valuesToBind.remove(val);
            } else if (ap.getCurrentStatus() == null) {
                if (val.getMetricName() != null
                        && val.getMetricName().trim().toLowerCase().contains("status")) {
                    context.put("waterSystemStatus", val.getStringValue());
                    foundStatus = true;
                }
            }
        }

        context.put("surveyalValues", valuesToBind);
    }

    if (ap.getCurrentStatus() != null) {
        try {
            context.put("waterSystemStatus",
                    encodeStatusString(AccessPoint.Status.valueOf(ap.getCurrentStatus())));
        } catch (Exception e) {
            context.put("waterSystemStatus", "Unknown");
        }
    } else {
        if (!foundStatus) {
            context.put("waterSystemStatus", "Unknown");
        }
    }
    // TODO: parameterize the default logo
    if (!foundPhoto) {
        context.put("photoUrl", "http://waterforpeople.s3.amazonaws.com/images/wfplogo.jpg");
    }

    context.put("latitude", ap.getLatitude());
    context.put("longitude", ap.getLongitude());

    if (ap.getLocaleType() != null) {
        context.put("type", ap.getLocaleType());
    } else {
        context.put("type", "water");
    }

    String output = mergeContext(context, vmName);
    context = null;
    return output;
}