messagemanager.java

来自「moblie syncml mail javame」· Java 代码 · 共 1,265 行 · 第 1/4 页

JAVA
1,265
字号
        
        for(int i=0; i<count; i++) {
            Message msg = msgs[i];
            msg.setKey(makeLuid(msg));
        }

        // Dump memory stats
        Log.stats("End of MessageManager.getMessagesInFolder");
        
        return msgs;
    }

    
    
    
    
    
    /**
     * Return a single message fetched from its folder.
     *
     * @param key the message key
     * @return the Message
     */
    public Message getMessage(String key) {
        String folderName = folderFromKey(key);
        Folder folder     = msgStore.getFolder(folderName);
        return getMessage(folder, key);
    }

    /**
     * Return a single message fetched from its folder.
     *
     * @param folder the folder containing the message
     * @param key the message key
     * @return the Message
 
     */
    public Message getMessage(Folder folder, String key) {
        String recordId = msgIdFromKey(key);
        // Get the message
        Message msg = folder.getMessage(recordId);
        // Set Message key
        if (msg!=null) {
            //if the message has been previously deleted this generates NPE
            msg.setKey(makeLuid(msg));
        }
        return msg;
    }
    
    /**
     * Returns the first message in the given folder.
     *
     * @return the first message if it exists, null otherwise
     * @throws MailException if an existing message cannot be read, or if the
     * folder is not in the store
     */
    public Message getFirstMessage(Folder folder) throws MailException {
        Message msg = folder.getFirstMessage();
        // Set Message key
        if (msg != null) {
            msg.setKey(makeLuid(msg));
        }
        return msg;
    }

    /**
     * Returns the next message in the given folder.
     *
     * @return the next message if it exists, null otherwise
     * @throws MailException if an existing message cannot be read, or if the
     * folder is not in the store
     */
    public Message getNextMessage(Folder folder) throws MailException {
        Message msg = folder.getNextMessage();
        // Set Message key
        if (msg != null) {
            msg.setKey(makeLuid(msg));
        }
        return msg;
    }

    /**
     * Returns the Folder corresponding to the given folder id.
     * If the folder id does not correspond to any real folder, the method may
     * throw an OutOfBoundArrayException.
     *
     * (@see MessageManager.INBOX, @see MessageManager.OUTBOX,
     *  @see MessageManager.DRAFT, @see MessageManager.SENT)
     *
     *  @param folder the folder id
     */
    public Folder getFolder(int folder) {
        Folder tmpRootFolders[] = getRootFolders();
        return tmpRootFolders[folder];
    }
    

    /**
     * Get the message Id from the key.
     *
     * @param key is the message key
     * @return is the record id
     */
    public String msgIdFromKey(String key) {
        int pos = key.indexOf('/');
        
        if(pos != -1) {
            return key.substring(pos+1);
        }
        return key;
    }

    /**
     * Get the folder name from the key.
     *
     * @param key is the message key
     * @return the folder name
     */
    public String folderFromKey(String key) {
        if(key == null) {
            return null;
        }
        int pos = key.indexOf('/');
        
        if(pos != -1) {
            return key.substring(0, pos);
        }
        return null;
    }

    /**
     * Dumps an email flags into SyncML format.
     *
     * @param msg is the email message
     * @return the SyncML format
     */
    public byte[] formatFlags(MessageFlags flags) {
        StringBuffer out = new StringBuffer();
        out.append("<Email>\n");
        formatFlags(flags, out);
        out.append("</Email>\n");
        return out.toString().getBytes();
    }

    /**
     * Dumps an email into SyncML format.
     *
     * @param msg is the email message
     * @return the SyncML format
     */
    public byte[] format(Message msg) {
        MessageFlags flags = msg.getFlags();
        StringBuffer out = new StringBuffer();
        out.append("<Email>\n");

        formatFlags(flags, out);

        String utcdate = null;
        Date received = msg.getReceivedDate();
        Date created  = msg.getSentDate();
        Date modified = msg.getSentDate();
        
        if(received != null){
            utcdate = MailDateFormatter.dateToUTC(received);
            XmlUtil.addElement(out, TREC_TAG, utcdate);
        }
        if(created != null){
            utcdate = MailDateFormatter.dateToUTC(created);
            XmlUtil.addElement(out, TCRE_TAG, utcdate);
        }
        if(modified != null) {
            utcdate = MailDateFormatter.dateToUTC(modified);
            XmlUtil.addElement(out, TMOD_TAG, utcdate);
        }
        
        MIMEFormatter mimef = new MIMEFormatter();
        out.append("<emailitem>\n<![CDATA[");
        // Append MIME representation of emailItem to out.
        mimef.format(msg, out);
        out.append("]]&gt;\n</emailitem>\n");
        out.append("</Email>\n");

        return out.toString().getBytes();
    }

    /**
     * Creates a new Folder. At the moment we do not really create any local
     * folder. We have a set of predefined folders (Inbox, Outbox, Draft and
     * Sent). Any folder propagated by the server is just ignored.
     *
     * @param syncmlStream syncml byte stream
     * @return the Folder
     * @throws XmlException if the byte stream cannot be parsed
     */
    public Folder createFolder(byte syncmlStream[]) throws XmlException {
        return parseFolder(syncmlStream);
    }

 
    //--------------------------------------------------------- Private Fields
    // These fields are SyncML tags for email description

    private static final String EMAIL_TAG = "Email";
    private static final String READ_TAG = "read";
    private static final String FORW_TAG = "forwarded" ;
    private static final String REPL_TAG = "replied" ;
    private static final String TREC_TAG = "received" ;
    private static final String TCRE_TAG = "created" ;
    private static final String TMOD_TAG = "modified" ;
    private static final String DELE_TAG = "deleted" ;
    private static final String FLAG_TAG = "flagged" ;
    private static final String ITEM_TAG = "emailitem" ;
    private static final String EXT_TAG  = "Ext" ;

    // These fields are SyncML tags for folder description
    private static final String FOLDER_TAG = "Folder";
    private static final String NAME_TAG = "name";
    private static final String CREATED_TAG = "created";
    private static final String ROLE_TAG = "role";

   

    //--------------------------------------------------------- Private Methods

    /**
     * Utility function to parse an email message flags (the email is a SyncML
     * byte stream)
     *
     * @param syncmlData is the SyncML byte stream
     * @return the MessageFlags
     */
    private MessageFlags parseFlags(byte[] syncmlData)
    throws XmlException, MailException {
        ChunkedString data = new ChunkedString(new String(syncmlData));
        ChunkedString xml = XmlUtil.getTagValue(data, EMAIL_TAG);
        return parseFlags(xml);
    }

     /**
     * Utility function to parse an email message flags (the email is a SyncML
     * chunked string)
     *
     * @param xml is the SyncML byte stream tokenized
     * @return the MessageFlags
     */
    private MessageFlags parseFlags(ChunkedString xml)
    throws XmlException, MailException {

        MessageFlags flags = new MessageFlags();

        flags.setFlag(MessageFlags.OPENED,    getXmlFlag(xml, READ_TAG));
        flags.setFlag(MessageFlags.FORWARDED, getXmlFlag(xml, FORW_TAG));
        flags.setFlag(MessageFlags.ANSWERED,  getXmlFlag(xml, REPL_TAG));
        flags.setFlag(MessageFlags.DELETED,   getXmlFlag(xml, DELE_TAG));
        flags.setFlag(MessageFlags.FLAGGED,   getXmlFlag(xml, FLAG_TAG));

        return flags;
    }

    /**
     * This method parses a SyncML byte stream describing an email and builds
     * the corresponding Message object.
     *
     * @param syncmlData email in SyncML byte stream format
     * @return the Message
     * @throws XmlException if the byte stream cannot be parsed
     */
    private Message parseMessage(byte[] syncmlData)
    throws XmlException {

        // Dump memory stats
        Log.stats("Beginning of MessageManager.parseMessage");

        ChunkedString data = null;
        try {
            // The encoding must be set to UTF-8 
            // in order to read the symbols like "euro" 
            data = new ChunkedString(new String(syncmlData, "UTF-8"));
        } catch (UnsupportedEncodingException uee) {
            uee.printStackTrace();
            Log.error("[MessageManager] Cannot convert email data");
        }
        
        ChunkedString xml = XmlUtil.getTagValue(data, EMAIL_TAG);
        data = null;

        MessageFlags flags = parseFlags(xml);
       
        Date received = getXmlDate(xml, TREC_TAG);
        Date created =  getXmlDate(xml, TCRE_TAG);
        Date modified = getXmlDate(xml, TMOD_TAG);

        int itemPos = XmlUtil.getTag(xml, ITEM_TAG);
        if(itemPos > -1) {
            int begin = xml.indexOf(">", itemPos);
            if(xml.charAt(begin-1) == '/') {
                Log.debug("EmailData.parse: empty emailitem.");
                return null;
            }
            int end = xml.indexOf("</"+ITEM_TAG+">", begin);
            if(begin == -1 || end == -1) {
                Log.error("[EmailData] error parsing EmailItem");
                throw new XmlException("Can't parse email item");
            }
            // FIXME: implement the CDATA handling in the Xml parser or use
            //        kxml
            int pos = xml.indexOf("<![CDATA[", begin);
            if (pos != -1) {
                begin = pos + 8;
                end = xml.indexOf("]]>", begin);
                
                if (end == -1) {
                    Log.error("[EmailData] can't find CDATA end.");
                    throw new XmlException("Can't find CDATA end.");
                }
            }
            ChunkedString item = xml.substring(begin+1, end);

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?