Example usage for java.text DateFormat DEFAULT

List of usage examples for java.text DateFormat DEFAULT

Introduction

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

Prototype

int DEFAULT

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

Click Source Link

Document

Constant for default style pattern.

Usage

From source file:io.bitsquare.gui.util.BSFormatter.java

public String formatDate(Date date) {
    if (date != null) {
        DateFormat dateFormatter = DateFormat.getDateInstance(DateFormat.DEFAULT, locale);
        return dateFormatter.format(date);
    } else {/*from  w w w . j  a v  a2 s  .  c  om*/
        return "";
    }
}

From source file:net.wastl.webmail.xml.XMLUserData.java

private String formatDate(long date) {
    TimeZone tz = TimeZone.getDefault();
    DateFormat df = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.DEFAULT, getPreferredLocale());
    df.setTimeZone(tz);/*from  ww  w  . j  ava2s  .  c om*/
    String now = df.format(new Date(date));
    return now;
}

From source file:net.wastl.webmail.storage.FileStorage.java

protected String formatDate(long date) {
    if (df == null) {
        TimeZone tz = TimeZone.getDefault();
        df = DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.DEFAULT, Locale.getDefault());
        df.setTimeZone(tz);/*from   w  w w . j  a  v a2 s. c  o m*/
    }
    String now = df.format(new Date(date));
    return now;
}

From source file:org.jajuk.util.UtilString.java

/**
 * Gets the locale date formatter./*from  www.  j  a v a 2s.c o  m*/
 *
 * @return locale date FORMATTER instance
 */
public static DateFormat getLocaleDateFormatter() {
    // store the dateFormat as ThreadLocal to avoid performance impact via the costly construction
    if (dateFormat.get() == null) {
        dateFormat.set(DateFormat.getDateInstance(DateFormat.DEFAULT, Locale.getDefault()));
    }
    return dateFormat.get();
}

From source file:de.betterform.xml.xforms.ui.state.UIElementStateUtil.java

/**
 * localize a string value depending on datatype and locale
 *
 * @param owner the BindingElement which is localized
 * @param type  the datatype of the bound Node
 * @param value the string value to convert
 * @return returns a localized representation of the input string
 *///from   w  w  w. j a v  a 2 s .c om
public static String localiseValue(BindingElement owner, Element state, String type, String value)
        throws XFormsException {
    if (value == null || value.equals("")) {
        return value;
    }
    String tmpType = type;
    if (tmpType != null && tmpType.contains(":")) {
        tmpType = tmpType.substring(tmpType.indexOf(":") + 1, tmpType.length());
    }
    if (Config.getInstance().getProperty(XFormsProcessorImpl.BETTERFORM_ENABLE_L10N, "true").equals("true")) {

        Locale locale = (Locale) owner.getModel().getContainer().getProcessor().getContext()
                .get(XFormsProcessorImpl.BETTERFORM_LOCALE);
        if (tmpType == null) {
            tmpType = owner.getModelItem().getDeclarationView().getDatatype();
        }
        if (tmpType == null) {
            LOGGER.debug(DOMUtil.getCanonicalPath(owner.getInstanceNode()) + " has no type, assuming 'string'");
            return value;
        }
        if (tmpType.equalsIgnoreCase("float") || tmpType.equalsIgnoreCase("decimal")
                || tmpType.equalsIgnoreCase("double")) {
            if (value.equals(""))
                return value;
            if (value.equals("NaN"))
                return value; //do not localize 'NaN' as it returns strange characters
            try {
                NumberFormat formatter = NumberFormat.getNumberInstance(locale);
                if (formatter instanceof DecimalFormat) {
                    //get original number format
                    int separatorPos = value.indexOf(".");
                    if (separatorPos == -1) {
                        formatter.setMaximumFractionDigits(0);
                    } else {
                        int fractionDigitCount = value.length() - separatorPos - 1;
                        formatter.setMinimumFractionDigits(fractionDigitCount);
                    }

                    Double num = Double.parseDouble(value);
                    return formatter.format(num.doubleValue());
                }
            } catch (NumberFormatException e) {
                LOGGER.warn("Value '" + value + "' is no valid " + tmpType);
                return value;
            }

        } else if (tmpType.equalsIgnoreCase("date")) {
            SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
            try {
                Date d = sf.parse(value);
                return DateFormat.getDateInstance(DateFormat.DEFAULT, locale).format(d);
            } catch (ParseException e) {
                LOGGER.warn("Value '" + value + "' is no valid " + tmpType);
                return value;
            }

        } else if (tmpType.equalsIgnoreCase("dateTime")) {

            //hackery due to lacking pattern for ISO 8601 Timezone representation in SimpleDateFormat
            String timezone = "";
            String dateTime = null;
            if (value.contains("GMT")) {
                timezone = " GMT" + value.substring(value.lastIndexOf(":") - 3, value.length());
                int devider = value.lastIndexOf(":");
                dateTime = value.substring(0, devider) + value.substring(devider + 1, value.length());
            } else if (value.contains("Z")) {
                timezone = "";
                dateTime = value.substring(0, value.indexOf("Z"));

            } else if (value.contains("+")) {
                timezone = value.substring(value.indexOf("+"), value.length());
                dateTime = value.substring(0, value.indexOf("+"));

            } else {
                dateTime = value;
            }
            SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");

            try {
                Date d = sf.parse(dateTime);
                return DateFormat.getDateTimeInstance(DateFormat.DEFAULT, DateFormat.DEFAULT, locale).format(d)
                        + timezone;
            } catch (ParseException e) {
                LOGGER.warn("Value '" + value + "' is no valid " + tmpType);
                return value;
            }

        } else {
            //not logging for type 'string'
            if (LOGGER.isTraceEnabled() && !(tmpType.equals("string"))) {
                LOGGER.trace("Type " + tmpType + " cannot be localized");
            }
        }
    }
    return value;
}

From source file:it.jugpadova.blo.EventBo.java

@RemoteMethod
public void updateBadgePanel(String continent, String country, String jugName, String pastEvents,
        String orderByDate, String jebShowJUGName, String jebShowCountry, String jebShowDescription,
        String jebShowParticipants, String badgeStyle, String locale, String maxResults) {
    WebContext wctx = WebContextFactory.get();
    HttpServletRequest req = wctx.getHttpServletRequest();
    ScriptSession session = wctx.getScriptSession();
    Util util = new Util(session);
    java.text.DateFormat dateFormat = java.text.DateFormat.getDateInstance(java.text.DateFormat.DEFAULT,
            new Locale(locale));
    java.lang.String baseUrl = "http://" + req.getServerName() + ":" + req.getServerPort()
            + req.getContextPath();/* w  w w  .  j av a2  s.  co m*/
    it.jugpadova.bean.EventSearch eventSearch = new it.jugpadova.bean.EventSearch();
    eventSearch.setContinent(continent);
    eventSearch.setCountry(country);
    eventSearch.setJugName(jugName);
    eventSearch.setPastEvents(java.lang.Boolean.parseBoolean(pastEvents));
    eventSearch.setOrderByDate(orderByDate);
    if (StringUtils.isNotBlank(maxResults)) {
        try {
            eventSearch.setMaxResults(new Integer(maxResults));
        } catch (NumberFormatException numberFormatException) {
            /* ignore it */
        }
    }
    java.util.List<it.jugpadova.po.Event> events = this.search(eventSearch);
    boolean showJUGName = java.lang.Boolean.parseBoolean(jebShowJUGName);
    boolean showCountry = java.lang.Boolean.parseBoolean(jebShowCountry);
    boolean showDescription = java.lang.Boolean.parseBoolean(jebShowDescription);
    boolean showParticipants = java.lang.Boolean.parseBoolean(jebShowParticipants);
    util.setValue("badgeCode",
            this.getBadgePageCode(baseUrl, continent, country, jugName, pastEvents, orderByDate, jebShowJUGName,
                    jebShowCountry, jebShowDescription, jebShowParticipants, badgeStyle, locale, maxResults));
    util.setValue("badgePreview", this.getBadgeHtmlCode(events, dateFormat, baseUrl, showJUGName, showCountry,
            showDescription, showParticipants, badgeStyle, locale));
}

From source file:op.care.values.PnlValues.java

private JPanel createContentPanel4Year(final ResValueTypes vtype, final int year) {
    final String keyYears = vtype.getID() + ".xtypes." + Integer.toString(year) + ".year";

    java.util.List<ResValue> myValues;
    synchronized (mapType2Values) {
        if (!mapType2Values.containsKey(keyYears)) {
            mapType2Values.put(keyYears, ResValueTools.getResValues(resident, vtype, year));
        }/*from   www .  j  a va  2  s .c  o  m*/
        if (mapType2Values.get(keyYears).isEmpty()) {
            JLabel lbl = new JLabel(SYSTools.xx("misc.msg.novalue"));
            JPanel pnl = new JPanel();
            pnl.add(lbl);
            return pnl;
        }
        myValues = mapType2Values.get(keyYears);
    }

    JPanel pnlYear = new JPanel(new VerticalLayout());

    pnlYear.setOpaque(false);

    for (final ResValue resValue : myValues) {
        String title = "<html><table border=\"0\">" + "<tr>" + "<td width=\"200\" align=\"left\">"
                + DateFormat.getDateTimeInstance(DateFormat.DEFAULT, DateFormat.SHORT).format(resValue.getPit())
                + " [" + resValue.getID() + "]</td>" + "<td width=\"340\" align=\"left\">"
                + ResValueTools.getValueAsHTML(resValue) + "</td>" + "<td width=\"200\" align=\"left\">"
                + resValue.getUser().getFullname() + "</td>" + "</tr>" + "</table>" + "</html>";

        final DefaultCPTitle pnlTitle = new DefaultCPTitle(title, null);

        pnlTitle.getMain().setBackground(GUITools.blend(vtype.getColor(), Color.WHITE, 0.1f));
        pnlTitle.getMain().setOpaque(true);

        if (resValue.isObsolete()) {
            pnlTitle.getAdditionalIconPanel().add(new JLabel(SYSConst.icon22eraser));
        }
        if (resValue.isReplacement()) {
            pnlTitle.getAdditionalIconPanel().add(new JLabel(SYSConst.icon22edited));
        }
        if (!resValue.getText().trim().isEmpty()) {
            pnlTitle.getAdditionalIconPanel().add(new JLabel(SYSConst.icon22info));
        }
        if (pnlTitle.getAdditionalIconPanel().getComponentCount() > 0) {
            pnlTitle.getButton().addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    GUITools.showPopup(
                            GUITools.getHTMLPopup(pnlTitle.getButton(), ResValueTools.getInfoAsHTML(resValue)),
                            SwingConstants.NORTH);
                }
            });
        }

        if (!resValue.getAttachedFilesConnections().isEmpty()) {
            /***
             *      _     _         _____ _ _
             *     | |__ | |_ _ __ |  ___(_) | ___  ___
             *     | '_ \| __| '_ \| |_  | | |/ _ \/ __|
             *     | |_) | |_| | | |  _| | | |  __/\__ \
             *     |_.__/ \__|_| |_|_|   |_|_|\___||___/
             *
             */
            final JButton btnFiles = new JButton(
                    Integer.toString(resValue.getAttachedFilesConnections().size()), SYSConst.icon22greenStar);
            btnFiles.setToolTipText(SYSTools.xx("misc.btnfiles.tooltip"));
            btnFiles.setForeground(Color.BLUE);
            btnFiles.setHorizontalTextPosition(SwingUtilities.CENTER);
            btnFiles.setFont(SYSConst.ARIAL18BOLD);
            btnFiles.setPressedIcon(SYSConst.icon22Pressed);
            btnFiles.setAlignmentX(Component.RIGHT_ALIGNMENT);
            btnFiles.setAlignmentY(Component.TOP_ALIGNMENT);
            btnFiles.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
            btnFiles.setContentAreaFilled(false);
            btnFiles.setBorder(null);

            btnFiles.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent actionEvent) {
                    new DlgFiles(resValue, new Closure() {
                        @Override
                        public void execute(Object o) {
                            EntityManager em = OPDE.createEM();
                            final ResValue myValue = em.find(ResValue.class, resValue.getID());
                            em.close();

                            synchronized (mapType2Values) {
                                mapType2Values.get(keyYears).remove(resValue);
                                mapType2Values.get(keyYears).add(myValue);
                                Collections.sort(mapType2Values.get(keyYears));
                            }

                            createCP4Year(vtype, year);
                            buildPanel();
                        }
                    });
                }
            });
            btnFiles.setEnabled(OPDE.isFTPworking());
            pnlTitle.getRight().add(btnFiles);
        }

        if (!resValue.getAttachedProcessConnections().isEmpty()) {
            /***
             *      _     _         ____
             *     | |__ | |_ _ __ |  _ \ _ __ ___   ___ ___  ___ ___
             *     | '_ \| __| '_ \| |_) | '__/ _ \ / __/ _ \/ __/ __|
             *     | |_) | |_| | | |  __/| | | (_) | (_|  __/\__ \__ \
             *     |_.__/ \__|_| |_|_|   |_|  \___/ \___\___||___/___/
             *
             */
            final JButton btnProcess = new JButton(
                    Integer.toString(resValue.getAttachedProcessConnections().size()), SYSConst.icon22redStar);
            btnProcess.setToolTipText(SYSTools.xx("misc.btnprocess.tooltip"));
            btnProcess.setForeground(Color.YELLOW);
            btnProcess.setHorizontalTextPosition(SwingUtilities.CENTER);
            btnProcess.setFont(SYSConst.ARIAL18BOLD);
            btnProcess.setPressedIcon(SYSConst.icon22Pressed);
            btnProcess.setAlignmentX(Component.RIGHT_ALIGNMENT);
            btnProcess.setAlignmentY(Component.TOP_ALIGNMENT);
            btnProcess.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
            btnProcess.setContentAreaFilled(false);
            btnProcess.setBorder(null);
            btnProcess.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent actionEvent) {
                    new DlgProcessAssign(resValue, new Closure() {
                        @Override
                        public void execute(Object o) {
                            if (o == null) {
                                return;
                            }
                            Pair<ArrayList<QProcess>, ArrayList<QProcess>> result = (Pair<ArrayList<QProcess>, ArrayList<QProcess>>) o;

                            ArrayList<QProcess> assigned = result.getFirst();
                            ArrayList<QProcess> unassigned = result.getSecond();

                            EntityManager em = OPDE.createEM();

                            try {
                                em.getTransaction().begin();

                                em.lock(em.merge(resident), LockModeType.OPTIMISTIC);
                                ResValue myValue = em.merge(resValue);
                                em.lock(myValue, LockModeType.OPTIMISTIC_FORCE_INCREMENT);

                                ArrayList<SYSVAL2PROCESS> attached = new ArrayList<SYSVAL2PROCESS>(
                                        resValue.getAttachedProcessConnections());
                                for (SYSVAL2PROCESS linkObject : attached) {
                                    if (unassigned.contains(linkObject.getQProcess())) {
                                        linkObject.getQProcess().getAttachedNReportConnections()
                                                .remove(linkObject);
                                        linkObject.getResValue().getAttachedProcessConnections()
                                                .remove(linkObject);
                                        em.merge(new PReport(
                                                SYSTools.xx(PReportTools.PREPORT_TEXT_REMOVE_ELEMENT) + ": "
                                                        + myValue.getTitle() + " ID: " + myValue.getID(),
                                                PReportTools.PREPORT_TYPE_REMOVE_ELEMENT,
                                                linkObject.getQProcess()));
                                        em.remove(linkObject);
                                    }
                                }
                                attached.clear();

                                for (QProcess qProcess : assigned) {
                                    java.util.List<QProcessElement> listElements = qProcess.getElements();
                                    if (!listElements.contains(myValue)) {
                                        QProcess myQProcess = em.merge(qProcess);
                                        SYSVAL2PROCESS myLinkObject = em
                                                .merge(new SYSVAL2PROCESS(myQProcess, myValue));
                                        em.merge(new PReport(
                                                SYSTools.xx(PReportTools.PREPORT_TEXT_ASSIGN_ELEMENT) + ": "
                                                        + myValue.getTitle() + " ID: " + myValue.getID(),
                                                PReportTools.PREPORT_TYPE_ASSIGN_ELEMENT, myQProcess));
                                        qProcess.getAttachedResValueConnections().add(myLinkObject);
                                        myValue.getAttachedProcessConnections().add(myLinkObject);
                                    }
                                }

                                em.getTransaction().commit();

                                synchronized (mapType2Values) {
                                    mapType2Values.get(keyYears).remove(resValue);
                                    mapType2Values.get(keyYears).add(myValue);
                                    Collections.sort(mapType2Values.get(keyYears));
                                }
                                createCP4Year(vtype, year);

                                buildPanel();

                            } catch (OptimisticLockException ole) {
                                OPDE.warn(ole);
                                if (em.getTransaction().isActive()) {
                                    em.getTransaction().rollback();
                                }
                                if (ole.getMessage().indexOf("Class> entity.info.Resident") > -1) {
                                    OPDE.getMainframe().emptyFrame();
                                    OPDE.getMainframe().afterLogin();
                                }
                                OPDE.getDisplayManager().addSubMessage(DisplayManager.getLockMessage());
                            } catch (RollbackException ole) {
                                if (em.getTransaction().isActive()) {
                                    em.getTransaction().rollback();
                                }
                                if (ole.getMessage().indexOf("Class> entity.info.Resident") > -1) {
                                    OPDE.getMainframe().emptyFrame();
                                    OPDE.getMainframe().afterLogin();
                                }
                                OPDE.getDisplayManager().addSubMessage(DisplayManager.getLockMessage());
                            } catch (Exception e) {
                                if (em.getTransaction().isActive()) {
                                    em.getTransaction().rollback();
                                }
                                OPDE.fatal(e);
                            } finally {
                                em.close();
                            }
                        }
                    });
                }
            });
            btnProcess.setEnabled(OPDE.getAppInfo().isAllowedTo(InternalClassACL.UPDATE, internalClassID));
            pnlTitle.getRight().add(btnProcess);
        }
        /***
         *      __  __
         *     |  \/  | ___ _ __  _   _
         *     | |\/| |/ _ \ '_ \| | | |
         *     | |  | |  __/ | | | |_| |
         *     |_|  |_|\___|_| |_|\__,_|
         *
         */
        final JButton btnMenu = new JButton(SYSConst.icon22menu);
        btnMenu.setPressedIcon(SYSConst.icon22Pressed);
        btnMenu.setAlignmentX(Component.RIGHT_ALIGNMENT);
        btnMenu.setAlignmentY(Component.TOP_ALIGNMENT);
        btnMenu.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
        btnMenu.setContentAreaFilled(false);
        btnMenu.setBorder(null);
        btnMenu.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                JidePopup popup = new JidePopup();
                popup.setMovable(false);
                popup.getContentPane().setLayout(new BoxLayout(popup.getContentPane(), BoxLayout.LINE_AXIS));
                popup.setOwner(btnMenu);
                popup.removeExcludedComponent(btnMenu);
                JPanel pnl = getMenu(resValue);
                popup.getContentPane().add(pnl);
                popup.setDefaultFocusComponent(pnl);

                GUITools.showPopup(popup, SwingConstants.WEST);
            }
        });
        btnMenu.setEnabled(!resValue.isObsolete());
        pnlTitle.getRight().add(btnMenu);

        pnlYear.add(pnlTitle.getMain());
        synchronized (linemap) {
            linemap.put(resValue, pnlTitle.getMain());
        }
    }
    return pnlYear;
}

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

/**
 * Fetch a message from a folder./*from   ww w . ja va 2 s.  c  o  m*/
 * 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:org.apache.click.util.Format.java

/**
 * Return a formatted time string using the given date and the default
 * DateFormat./*from   w  ww .  j a va  2 s. c o m*/
 * <p/>
 * If the date is null this method will return the
 * {@link #getEmptyString()} value.
 *
 * @param date the date value to format
 * @return a formatted time string
 */
public String time(Date date) {
    if (date != null) {
        DateFormat format = DateFormat.getTimeInstance(DateFormat.DEFAULT, getLocale());

        return format.format(date);

    } else {
        return getEmptyString();
    }
}

From source file:org.yccheok.jstock.gui.PortfolioManagementJPanel.java

public boolean openAsStatements(Statements statements, File file) {
    assert (statements != null);

    if (statements.getType() == Statement.Type.PortfolioManagementBuy
            || statements.getType() == Statement.Type.PortfolioManagementSell
            || statements.getType() == Statement.Type.PortfolioManagementDeposit
            || statements.getType() == Statement.Type.PortfolioManagementDividend) {
        final GUIBundleWrapper guiBundleWrapper = statements.getGUIBundleWrapper();
        // We will use a fixed date format (Locale.English), so that it will be
        // easier for Android to process.
        ////  www  .j a  va 2s.  co m
        // "Sep 5, 2011"    -   Locale.ENGLISH
        // "2011-9-5"       -   Locale.SIMPLIFIED_CHINESE
        // "2011/9/5"       -   Locale.TRADITIONAL_CHINESE
        // 05.09.2011       -   Locale.GERMAN
        //
        // However, for backward compatible purpose (Able to read old CSV),
        // we perform a for loop to determine the best date format.
        DateFormat dateFormat = null;
        final int size = statements.size();
        switch (statements.getType()) {
        case PortfolioManagementBuy: {
            final List<Transaction> transactions = new ArrayList<Transaction>();

            for (int i = 0; i < size; i++) {
                final Statement statement = statements.get(i);
                final String _code = statement.getValueAsString(guiBundleWrapper.getString("MainFrame_Code"));
                final String _symbol = statement
                        .getValueAsString(guiBundleWrapper.getString("MainFrame_Symbol"));
                final String _date = statement
                        .getValueAsString(guiBundleWrapper.getString("PortfolioManagementJPanel_Date"));
                final Double units = statement
                        .getValueAsDouble(guiBundleWrapper.getString("PortfolioManagementJPanel_Units"));
                final Double purchasePrice = statement.getValueAsDouble(
                        guiBundleWrapper.getString("PortfolioManagementJPanel_PurchasePrice"));
                final Double broker = statement
                        .getValueAsDouble(guiBundleWrapper.getString("PortfolioManagementJPanel_Broker"));
                final Double clearingFee = statement
                        .getValueAsDouble(guiBundleWrapper.getString("PortfolioManagementJPanel_ClearingFee"));
                final Double stampDuty = statement
                        .getValueAsDouble(guiBundleWrapper.getString("PortfolioManagementJPanel_StampDuty"));
                final String _comment = statement
                        .getValueAsString(guiBundleWrapper.getString("PortfolioManagementJPanel_Comment"));

                Stock stock = null;
                if (_code.length() > 0 && _symbol.length() > 0) {
                    stock = org.yccheok.jstock.engine.Utils.getEmptyStock(Code.newInstance(_code),
                            Symbol.newInstance(_symbol));
                } else {
                    log.error("Unexpected empty stock. Ignore");
                    // stock is null.
                    continue;
                }
                Date date = null;

                if (dateFormat == null) {
                    // However, for backward compatible purpose (Able to read old CSV),
                    // we perform a for loop to determine the best date format.
                    // For the latest CSV, it should be Locale.ENGLISH.
                    Locale[] locales = { Locale.ENGLISH, Locale.SIMPLIFIED_CHINESE, Locale.GERMAN,
                            Locale.TRADITIONAL_CHINESE, Locale.ITALIAN };
                    for (Locale locale : locales) {
                        dateFormat = DateFormat.getDateInstance(DateFormat.DEFAULT, locale);
                        try {
                            date = dateFormat.parse((String) _date);
                        } catch (ParseException exp) {
                            log.error(null, exp);
                            date = null;
                            dateFormat = null;
                            continue;
                        }
                        // We had found our best dateFormat. Early break.
                        break;
                    }
                } else {
                    // We already determine our best dateFormat.
                    try {
                        date = dateFormat.parse((String) _date);
                    } catch (ParseException exp) {
                        log.error(null, exp);
                    }
                }

                if (date == null) {
                    log.error("Unexpected wrong date. Ignore");
                    continue;
                }

                // Shall we continue to ignore, or shall we just return false to
                // flag an error?
                if (units == null) {
                    log.error("Unexpected wrong units. Ignore");
                    continue;
                }
                if (purchasePrice == null || broker == null || clearingFee == null || stampDuty == null) {
                    log.error("Unexpected wrong purchasePrice/broker/clearingFee/stampDuty. Ignore");
                    continue;
                }

                final SimpleDate simpleDate = new SimpleDate(date);
                final Contract.Type type = Contract.Type.Buy;
                final Contract.ContractBuilder builder = new Contract.ContractBuilder(stock, simpleDate);
                final Contract contract = builder.type(type).quantity(units).price(purchasePrice).build();
                final Transaction t = new Transaction(contract, broker, stampDuty, clearingFee);
                t.setComment(org.yccheok.jstock.portfolio.Utils.replaceCSVLineFeedToSystemLineFeed(_comment));
                transactions.add(t);
            }

            // We allow empty portfolio.
            //if (transactions.size() <= 0) {
            //    return false;
            //}

            // Is there any exsiting displayed data?
            if (this.getBuyTransactionSize() > 0) {
                final String output = MessageFormat.format(
                        MessagesBundle.getString("question_message_load_file_for_buy_portfolio_template"),
                        file.getName());
                final int result = javax.swing.JOptionPane.showConfirmDialog(JStock.instance(), output,
                        MessagesBundle.getString("question_title_load_file_for_buy_portfolio"),
                        javax.swing.JOptionPane.YES_NO_OPTION, javax.swing.JOptionPane.QUESTION_MESSAGE);
                if (result != javax.swing.JOptionPane.YES_OPTION) {
                    // Assume success.
                    return true;
                }
            }

            this.buyTreeTable.setTreeTableModel(new BuyPortfolioTreeTableModelEx());
            final BuyPortfolioTreeTableModelEx buyPortfolioTreeTableModel = (BuyPortfolioTreeTableModelEx) buyTreeTable
                    .getTreeTableModel();
            buyPortfolioTreeTableModel.bind(this.portfolioRealTimeInfo);
            buyPortfolioTreeTableModel.bind(this);

            Map<String, String> metadatas = statements.getMetadatas();
            for (Transaction transaction : transactions) {
                final Code code = transaction.getStock().code;
                TransactionSummary transactionSummary = this.addBuyTransaction(transaction);
                if (transactionSummary != null) {
                    String comment = metadatas.get(code.toString());
                    if (comment != null) {
                        transactionSummary.setComment(
                                org.yccheok.jstock.portfolio.Utils.replaceCSVLineFeedToSystemLineFeed(comment));
                    }
                }
            }

            // Only shows necessary columns.
            initGUIOptions();

            expandTreeTable(buyTreeTable);

            updateRealTimeStockMonitorAccordingToPortfolioTreeTableModels();
            updateExchangeRateMonitorAccordingToPortfolioTreeTableModels();

            // updateWealthHeader will be called at end of switch.

            refreshStatusBarExchangeRateVisibility();
        }
            break;

        case PortfolioManagementSell: {
            final List<Transaction> transactions = new ArrayList<Transaction>();

            for (int i = 0; i < size; i++) {
                final Statement statement = statements.get(i);
                final String _code = statement.getValueAsString(guiBundleWrapper.getString("MainFrame_Code"));
                final String _symbol = statement
                        .getValueAsString(guiBundleWrapper.getString("MainFrame_Symbol"));
                final String _referenceDate = statement.getValueAsString(
                        guiBundleWrapper.getString("PortfolioManagementJPanel_ReferenceDate"));

                // Legacy file handling. PortfolioManagementJPanel_PurchaseBroker, PortfolioManagementJPanel_PurchaseClearingFee,
                // and PortfolioManagementJPanel_PurchaseStampDuty are introduced starting from 1.0.6x
                Double purchaseBroker = statement.getValueAsDouble(
                        guiBundleWrapper.getString("PortfolioManagementJPanel_PurchaseBroker"));
                if (purchaseBroker == null) {
                    // Legacy file handling. PortfolioManagementJPanel_PurchaseFee is introduced starting from 1.0.6s
                    purchaseBroker = statement.getValueAsDouble(
                            guiBundleWrapper.getString("PortfolioManagementJPanel_PurchaseFee"));
                    if (purchaseBroker == null) {
                        purchaseBroker = new Double(0.0);
                    }
                }
                Double purchaseClearingFee = statement.getValueAsDouble(
                        guiBundleWrapper.getString("PortfolioManagementJPanel_PurchaseClearingFee"));
                if (purchaseClearingFee == null) {
                    purchaseClearingFee = new Double(0.0);
                }
                Double purchaseStampDuty = statement.getValueAsDouble(
                        guiBundleWrapper.getString("PortfolioManagementJPanel_PurchaseStampDuty"));
                if (purchaseStampDuty == null) {
                    purchaseStampDuty = new Double(0.0);

                }
                final String _date = statement
                        .getValueAsString(guiBundleWrapper.getString("PortfolioManagementJPanel_Date"));
                final Double units = statement
                        .getValueAsDouble(guiBundleWrapper.getString("PortfolioManagementJPanel_Units"));
                final Double sellingPrice = statement
                        .getValueAsDouble(guiBundleWrapper.getString("PortfolioManagementJPanel_SellingPrice"));
                final Double purchasePrice = statement.getValueAsDouble(
                        guiBundleWrapper.getString("PortfolioManagementJPanel_PurchasePrice"));
                final Double broker = statement
                        .getValueAsDouble(guiBundleWrapper.getString("PortfolioManagementJPanel_Broker"));
                final Double clearingFee = statement
                        .getValueAsDouble(guiBundleWrapper.getString("PortfolioManagementJPanel_ClearingFee"));
                final Double stampDuty = statement
                        .getValueAsDouble(guiBundleWrapper.getString("PortfolioManagementJPanel_StampDuty"));
                final String _comment = statement
                        .getValueAsString(guiBundleWrapper.getString("PortfolioManagementJPanel_Comment"));

                Stock stock = null;
                if (_code.length() > 0 && _symbol.length() > 0) {
                    stock = org.yccheok.jstock.engine.Utils.getEmptyStock(Code.newInstance(_code),
                            Symbol.newInstance(_symbol));
                } else {
                    log.error("Unexpected empty stock. Ignore");
                    // stock is null.
                    continue;
                }

                Date date = null;
                Date referenceDate = null;

                if (dateFormat == null) {
                    // However, for backward compatible purpose (Able to read old CSV),
                    // we perform a for loop to determine the best date format.
                    // For the latest CSV, it should be Locale.ENGLISH.
                    Locale[] locales = { Locale.ENGLISH, Locale.SIMPLIFIED_CHINESE, Locale.GERMAN,
                            Locale.TRADITIONAL_CHINESE, Locale.ITALIAN };
                    for (Locale locale : locales) {
                        dateFormat = DateFormat.getDateInstance(DateFormat.DEFAULT, locale);
                        try {
                            date = dateFormat.parse((String) _date);
                            referenceDate = dateFormat.parse((String) _referenceDate);
                        } catch (ParseException exp) {
                            log.error(null, exp);
                            date = null;
                            referenceDate = null;
                            dateFormat = null;
                            continue;
                        }
                        // We had found our best dateFormat. Early break.
                        break;
                    }
                } else {
                    // We already determine our best dateFormat.
                    try {
                        date = dateFormat.parse((String) _date);
                        referenceDate = dateFormat.parse((String) _referenceDate);
                    } catch (ParseException exp) {
                        log.error(null, exp);
                    }
                }

                if (date == null || referenceDate == null) {
                    log.error("Unexpected wrong date/referenceDate. Ignore");
                    continue;
                }
                // Shall we continue to ignore, or shall we just return false to
                // flag an error?
                if (units == null) {
                    log.error("Unexpected wrong units. Ignore");
                    continue;
                }
                if (purchasePrice == null || broker == null || clearingFee == null || stampDuty == null
                        || sellingPrice == null) {
                    log.error(
                            "Unexpected wrong purchasePrice/broker/clearingFee/stampDuty/sellingPrice. Ignore");
                    continue;
                }

                final SimpleDate simpleDate = new SimpleDate(date);
                final SimpleDate simpleReferenceDate = new SimpleDate(referenceDate);
                final Contract.Type type = Contract.Type.Sell;
                final Contract.ContractBuilder builder = new Contract.ContractBuilder(stock, simpleDate);
                final Contract contract = builder.type(type).quantity(units).price(sellingPrice)
                        .referencePrice(purchasePrice).referenceDate(simpleReferenceDate)
                        .referenceBroker(purchaseBroker).referenceClearingFee(purchaseClearingFee)
                        .referenceStampDuty(purchaseStampDuty).build();
                final Transaction t = new Transaction(contract, broker, stampDuty, clearingFee);
                t.setComment(org.yccheok.jstock.portfolio.Utils.replaceCSVLineFeedToSystemLineFeed(_comment));
                transactions.add(t);
            } // for

            // We allow empty portfolio.
            //if (transactions.size() <= 0) {
            //    return false;
            //}

            // Is there any exsiting displayed data?
            if (this.getSellTransactionSize() > 0) {
                final String output = MessageFormat.format(
                        MessagesBundle.getString("question_message_load_file_for_sell_portfolio_template"),
                        file.getName());
                final int result = javax.swing.JOptionPane.showConfirmDialog(JStock.instance(), output,
                        MessagesBundle.getString("question_title_load_file_for_sell_portfolio"),
                        javax.swing.JOptionPane.YES_NO_OPTION, javax.swing.JOptionPane.QUESTION_MESSAGE);
                if (result != javax.swing.JOptionPane.YES_OPTION) {
                    // Assume success.
                    return true;
                }
            }

            this.sellTreeTable.setTreeTableModel(new SellPortfolioTreeTableModelEx());
            final SellPortfolioTreeTableModelEx sellPortfolioTreeTableModel = (SellPortfolioTreeTableModelEx) sellTreeTable
                    .getTreeTableModel();
            sellPortfolioTreeTableModel.bind(this.portfolioRealTimeInfo);
            sellPortfolioTreeTableModel.bind(this);

            Map<String, String> metadatas = statements.getMetadatas();

            for (Transaction transaction : transactions) {
                final Code code = transaction.getStock().code;
                TransactionSummary transactionSummary = this.addSellTransaction(transaction);
                if (transactionSummary != null) {
                    String comment = metadatas.get(code.toString());
                    if (comment != null) {
                        transactionSummary.setComment(
                                org.yccheok.jstock.portfolio.Utils.replaceCSVLineFeedToSystemLineFeed(comment));
                    }
                }
            }

            // Only shows necessary columns.
            initGUIOptions();

            expandTreeTable(this.sellTreeTable);

            updateExchangeRateMonitorAccordingToPortfolioTreeTableModels();

            // updateWealthHeader will be called at end of switch.

            refreshStatusBarExchangeRateVisibility();
        }
            break;

        case PortfolioManagementDeposit: {
            final List<Deposit> deposits = new ArrayList<Deposit>();

            for (int i = 0; i < size; i++) {
                Date date = null;
                final Statement statement = statements.get(i);
                final String object0 = statement
                        .getValueAsString(guiBundleWrapper.getString("PortfolioManagementJPanel_Date"));
                assert (object0 != null);

                if (dateFormat == null) {
                    // However, for backward compatible purpose (Able to read old CSV),
                    // we will perform a for loop to determine the best date format.
                    // For the latest CSV, it should be Locale.ENGLISH.
                    Locale[] locales = { Locale.ENGLISH, Locale.SIMPLIFIED_CHINESE, Locale.GERMAN,
                            Locale.TRADITIONAL_CHINESE, Locale.ITALIAN };
                    for (Locale locale : locales) {
                        dateFormat = DateFormat.getDateInstance(DateFormat.DEFAULT, locale);
                        try {
                            date = dateFormat.parse(object0);
                        } catch (ParseException exp) {
                            log.error(null, exp);
                            date = null;
                            dateFormat = null;
                            continue;
                        }
                        // We had found our best dateFormat. Early break.
                        break;
                    }
                } else {
                    // We already determine our best dateFormat.
                    try {
                        date = dateFormat.parse(object0);
                    } catch (ParseException exp) {
                        log.error(null, exp);
                    }
                }

                // Shall we continue to ignore, or shall we just return false to
                // flag an error?
                if (date == null) {
                    log.error("Unexpected wrong date. Ignore");
                    continue;
                }
                final Double cash = statement
                        .getValueAsDouble(guiBundleWrapper.getString("PortfolioManagementJPanel_Cash"));
                // Shall we continue to ignore, or shall we just return false to
                // flag an error?
                if (cash == null) {
                    log.error("Unexpected wrong cash. Ignore");
                    continue;
                }
                final Deposit deposit = new Deposit(cash, new SimpleDate(date));

                final String comment = statement
                        .getValueAsString(guiBundleWrapper.getString("PortfolioManagementJPanel_Comment"));
                if (comment != null) {
                    // Possible to be null. As in version <=1.0.6p, comment
                    // is not being saved to CSV.
                    deposit.setComment(
                            org.yccheok.jstock.portfolio.Utils.replaceCSVLineFeedToSystemLineFeed(comment));
                }

                deposits.add(deposit);
            }

            // We allow empty portfolio.
            //if (deposits.size() <= 0) {
            //    return false;
            //}

            // Is there any exsiting displayed data?
            if (this.depositSummary.size() > 0) {
                final String output = MessageFormat.format(
                        MessagesBundle.getString("question_message_load_file_for_cash_deposit_template"),
                        file.getName());
                final int result = javax.swing.JOptionPane.showConfirmDialog(JStock.instance(), output,
                        MessagesBundle.getString("question_title_load_file_for_cash_deposit"),
                        javax.swing.JOptionPane.YES_NO_OPTION, javax.swing.JOptionPane.QUESTION_MESSAGE);
                if (result != javax.swing.JOptionPane.YES_OPTION) {
                    // Assume success.
                    return true;
                }
            }

            this.depositSummary = new DepositSummary();

            for (Deposit deposit : deposits) {
                depositSummary.add(deposit);
            }
        }
            break;

        case PortfolioManagementDividend: {
            final List<Dividend> dividends = new ArrayList<Dividend>();

            for (int i = 0; i < size; i++) {
                Date date = null;
                StockInfo stockInfo = null;
                final Statement statement = statements.get(i);
                final String object0 = statement
                        .getValueAsString(guiBundleWrapper.getString("PortfolioManagementJPanel_Date"));
                assert (object0 != null);

                if (dateFormat == null) {
                    // However, for backward compatible purpose (Able to read old CSV),
                    // we will perform a for loop to determine the best date format.
                    // For the latest CSV, it should be Locale.ENGLISH.
                    Locale[] locales = { Locale.ENGLISH, Locale.SIMPLIFIED_CHINESE, Locale.GERMAN,
                            Locale.TRADITIONAL_CHINESE, Locale.ITALIAN };
                    for (Locale locale : locales) {
                        dateFormat = DateFormat.getDateInstance(DateFormat.DEFAULT, locale);
                        try {
                            date = dateFormat.parse(object0);
                        } catch (ParseException exp) {
                            log.error(null, exp);
                            date = null;
                            dateFormat = null;
                            continue;
                        }
                        // We had found our best dateFormat. Early break.
                        break;
                    }
                } else {
                    // We already determine our best dateFormat.
                    try {
                        date = dateFormat.parse(object0);
                    } catch (ParseException exp) {
                        log.error(null, exp);
                    }
                }

                // Shall we continue to ignore, or shall we just return false to
                // flag an error?
                if (date == null) {
                    log.error("Unexpected wrong date. Ignore");
                    continue;
                }
                final Double dividend = statement
                        .getValueAsDouble(guiBundleWrapper.getString("PortfolioManagementJPanel_Dividend"));
                // Shall we continue to ignore, or shall we just return false to
                // flag an error?
                if (dividend == null) {
                    log.error("Unexpected wrong dividend. Ignore");
                    continue;
                }
                final String codeStr = statement.getValueAsString(guiBundleWrapper.getString("MainFrame_Code"));
                final String symbolStr = statement
                        .getValueAsString(guiBundleWrapper.getString("MainFrame_Symbol"));
                if (codeStr.isEmpty() == false && symbolStr.isEmpty() == false) {
                    stockInfo = StockInfo.newInstance(Code.newInstance(codeStr), Symbol.newInstance(symbolStr));
                } else {
                    log.error("Unexpected wrong stock. Ignore");
                    // stock is null.
                    continue;
                }

                assert (stockInfo != null);
                assert (dividend != null);
                assert (date != null);

                final Dividend d = new Dividend(stockInfo, dividend, new SimpleDate(date));

                final String comment = statement
                        .getValueAsString(guiBundleWrapper.getString("PortfolioManagementJPanel_Comment"));
                if (comment != null) {
                    // Possible to be null. As in version <=1.0.6p, comment
                    // is not being saved to CSV.
                    d.setComment(
                            org.yccheok.jstock.portfolio.Utils.replaceCSVLineFeedToSystemLineFeed(comment));
                }

                dividends.add(d);
            }

            // We allow empty portfolio.
            //if (dividends.size() <= 0) {
            //    return false;
            //}                    

            if (this.dividendSummary.size() > 0) {
                final String output = MessageFormat.format(
                        MessagesBundle.getString("question_message_load_file_for_dividend_template"),
                        file.getName());
                final int result = javax.swing.JOptionPane.showConfirmDialog(JStock.instance(), output,
                        MessagesBundle.getString("question_title_load_file_for_dividend"),
                        javax.swing.JOptionPane.YES_NO_OPTION, javax.swing.JOptionPane.QUESTION_MESSAGE);
                if (result != javax.swing.JOptionPane.YES_OPTION) {
                    // Assume success.
                    return true;
                }
            }

            this.dividendSummary = new DividendSummary();

            for (Dividend dividend : dividends) {
                dividendSummary.add(dividend);
            }
        }
            break;

        default:
            assert (false);
        } // End of switch

        this.updateWealthHeader();
    } else if (statements.getType() == Statement.Type.RealtimeInfo) {
        /* Open using other tabs. */
        return JStock.instance().openAsStatements(statements, file);
    } else {
        return false;
    }
    return true;
}