geronimo-scm mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From rickmcgu...@apache.org
Subject svn commit: r421852 [6/15] - in /geronimo/specs/trunk: ./ geronimo-spec-j2ee/ geronimo-spec-javamail-1.3.1/ geronimo-spec-javamail-1.3.1/src/ geronimo-spec-javamail-1.4/ geronimo-spec-javamail-1.4/src/ geronimo-spec-javamail-1.4/src/main/ geronimo-spec...
Date Fri, 14 Jul 2006 10:02:29 GMT
Added: geronimo/specs/trunk/geronimo-spec-javamail-1.4/src/main/java/javax/mail/internet/HeaderTokenizer.java
URL: http://svn.apache.org/viewvc/geronimo/specs/trunk/geronimo-spec-javamail-1.4/src/main/java/javax/mail/internet/HeaderTokenizer.java?rev=421852&view=auto
==============================================================================
--- geronimo/specs/trunk/geronimo-spec-javamail-1.4/src/main/java/javax/mail/internet/HeaderTokenizer.java (added)
+++ geronimo/specs/trunk/geronimo-spec-javamail-1.4/src/main/java/javax/mail/internet/HeaderTokenizer.java Fri Jul 14 03:02:19 2006
@@ -0,0 +1,282 @@
+/**
+ *
+ * Copyright 2003-2006 The Apache Software Foundation
+ *
+ *  Licensed under the Apache License, Version 2.0 (the "License");
+ *  you may not use this file except in compliance with the License.
+ *  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing, software
+ *  distributed under the License is distributed on an "AS IS" BASIS,
+ *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *  See the License for the specific language governing permissions and
+ *  limitations under the License.
+ */
+
+package javax.mail.internet;
+
+/**
+ * @version $Rev$ $Date$
+ */
+public class HeaderTokenizer {
+    public static class Token {
+        // Constant values from J2SE 1.4 API Docs (Constant values)
+        public static final int ATOM = -1;
+        public static final int COMMENT = -3;
+        public static final int EOF = -4;
+        public static final int QUOTEDSTRING = -2;
+        private int _type;
+        private String _value;
+
+        public Token(int type, String value) {
+            _type = type;
+            _value = value;
+        }
+
+        public int getType() {
+            return _type;
+        }
+
+        public String getValue() {
+            return _value;
+        }
+    }
+
+    private static final Token EOF = new Token(Token.EOF, null);
+    // characters not allowed in MIME
+    public static final String MIME = "()<>@,;:\\\"\t []/?=";
+    // charaters not allowed in RFC822
+    public static final String RFC822 = "()<>@,;:\\\"\t .[]";
+    private static final String WHITE = " \t\n\r";
+    private String _delimiters;
+    private String _header;
+    private boolean _skip;
+    private int pos;
+
+    public HeaderTokenizer(String header) {
+        this(header, RFC822);
+    }
+
+    public HeaderTokenizer(String header, String delimiters) {
+        this(header, delimiters, true);
+    }
+
+    public HeaderTokenizer(String header,
+                           String delimiters,
+                           boolean skipComments) {
+        _skip = skipComments;
+        _header = header;
+        _delimiters = delimiters;
+    }
+
+    public String getRemainder() {
+        return _header.substring(pos);
+    }
+
+    public Token next() throws ParseException {
+        return readToken();
+    }
+
+    public Token peek() throws ParseException {
+        int start = pos;
+        try {
+            return readToken();
+        } finally {
+            pos = start;
+        }
+    }
+
+    /**
+     * Read an ATOM token from the parsed header.
+     *
+     * @return A token containing the value of the atom token.
+     */
+    private Token readAtomicToken() {
+        // skip to next delimiter
+        int start = pos;
+        while (++pos < _header.length()) {
+            // break on the first non-atom character.
+            char ch = _header.charAt(pos);
+            if (_delimiters.indexOf(_header.charAt(pos)) != -1 || ch < 32 || ch >= 127) {
+                break;
+            }
+        }
+
+        return new Token(Token.ATOM, _header.substring(start, pos));
+    }
+
+    /**
+     * Read the next token from the header.
+     *
+     * @return The next token from the header.  White space is skipped, and comment
+     *         tokens are also skipped if indicated.
+     * @exception ParseException
+     */
+    private Token readToken() throws ParseException {
+        if (pos >= _header.length()) {
+            return EOF;
+        } else {
+            char c = _header.charAt(pos);
+            // comment token...read and skip over this
+            if (c == '(') {
+                Token comment = readComment();
+                if (_skip) {
+                    return readToken();
+                } else {
+                    return comment;
+                }
+                // quoted literal
+            } else if (c == '\"') {
+                return readQuotedString();
+            // white space, eat this and find a real token.
+            } else if (WHITE.indexOf(c) != -1) {
+                eatWhiteSpace();
+                return readToken();
+            // either a CTL or special.  These characters have a self-defining token type.
+            } else if (c < 32 || c >= 127 || _delimiters.indexOf(c) != -1) {
+                pos++;
+                return new Token((int)c, String.valueOf(c));
+            } else {
+                // start of an atom, parse it off.
+                return readAtomicToken();
+            }
+        }
+    }
+
+    /**
+     * Extract a substring from the header string and apply any
+     * escaping/folding rules to the string.
+     *
+     * @param start  The starting offset in the header.
+     * @param end    The header end offset + 1.
+     *
+     * @return The processed string value.
+     * @exception ParseException
+     */
+    private String getEscapedValue(int start, int end) throws ParseException {
+        StringBuffer value = new StringBuffer();
+
+        for (int i = start; i < end; i++) {
+            char ch = _header.charAt(i);
+            // is this an escape character?
+            if (ch == '\\') {
+                i++;
+                if (i == end) {
+                    throw new ParseException("Invalid escape character");
+                }
+                value.append(_header.charAt(i));
+            }
+            // line breaks are ignored, except for naked '\n' characters, which are consider
+            // parts of linear whitespace.
+            else if (ch == '\r') {
+                // see if this is a CRLF sequence, and skip the second if it is.
+                if (i < end - 1 && _header.charAt(i + 1) == '\n') {
+                    i++;
+                }
+            }
+            else {
+                // just append the ch value.
+                value.append(ch);
+            }
+        }
+        return value.toString();
+    }
+
+    /**
+     * Read a comment from the header, applying nesting and escape
+     * rules to the content.
+     *
+     * @return A comment token with the token value.
+     * @exception ParseException
+     */
+    private Token readComment() throws ParseException {
+        int start = pos + 1;
+        int nesting = 1;
+
+        boolean requiresEscaping = false;
+
+        // skip to end of comment/string
+        while (++pos < _header.length()) {
+            char ch = _header.charAt(pos);
+            if (ch == ')') {
+                nesting--;
+                if (nesting == 0) {
+                    break;
+                }
+            }
+            else if (ch == '(') {
+                nesting++;
+            }
+            else if (ch == '\\') {
+                pos++;
+                requiresEscaping = true;
+            }
+            // we need to process line breaks also
+            else if (ch == '\r') {
+                requiresEscaping = true;
+            }
+        }
+
+        if (nesting != 0) {
+            throw new ParseException("Unbalanced comments");
+        }
+
+        String value;
+        if (requiresEscaping) {
+            value = getEscapedValue(start, pos);
+        }
+        else {
+            value = _header.substring(start, pos++);
+        }
+        return new Token(Token.COMMENT, value);
+    }
+
+    /**
+     * Parse out a quoted string from the header, applying escaping
+     * rules to the value.
+     *
+     * @return The QUOTEDSTRING token with the value.
+     * @exception ParseException
+     */
+    private Token readQuotedString() throws ParseException {
+        int start = pos+1;
+        boolean requiresEscaping = false;
+
+        // skip to end of comment/string
+        while (++pos < _header.length()) {
+            char ch = _header.charAt(pos);
+            if (ch == '"') {
+                String value;
+                if (requiresEscaping) {
+                    value = getEscapedValue(start, pos);
+                }
+                else {
+                    value = _header.substring(start, pos++);
+                }
+                return new Token(Token.QUOTEDSTRING, value);
+            }
+            else if (ch == '\\') {
+                pos++;
+                requiresEscaping = true;
+            }
+            // we need to process line breaks also
+            else if (ch == '\r') {
+                requiresEscaping = true;
+            }
+        }
+
+        throw new ParseException("Missing '\"'");
+    }
+
+    /**
+     * Skip white space in the token string.
+     */
+    private void eatWhiteSpace() {
+        // skip to end of whitespace
+        while (++pos < _header.length()
+                && WHITE.indexOf(_header.charAt(pos)) != -1)
+            ;
+    }
+}

Propchange: geronimo/specs/trunk/geronimo-spec-javamail-1.4/src/main/java/javax/mail/internet/HeaderTokenizer.java
------------------------------------------------------------------------------
    svn:eol-style = native

Propchange: geronimo/specs/trunk/geronimo-spec-javamail-1.4/src/main/java/javax/mail/internet/HeaderTokenizer.java
------------------------------------------------------------------------------
    svn:keywords = Date Revision

Propchange: geronimo/specs/trunk/geronimo-spec-javamail-1.4/src/main/java/javax/mail/internet/HeaderTokenizer.java
------------------------------------------------------------------------------
    svn:mime-type = text/plain

Added: geronimo/specs/trunk/geronimo-spec-javamail-1.4/src/main/java/javax/mail/internet/InternetAddress.java
URL: http://svn.apache.org/viewvc/geronimo/specs/trunk/geronimo-spec-javamail-1.4/src/main/java/javax/mail/internet/InternetAddress.java?rev=421852&view=auto
==============================================================================
--- geronimo/specs/trunk/geronimo-spec-javamail-1.4/src/main/java/javax/mail/internet/InternetAddress.java (added)
+++ geronimo/specs/trunk/geronimo-spec-javamail-1.4/src/main/java/javax/mail/internet/InternetAddress.java Fri Jul 14 03:02:19 2006
@@ -0,0 +1,567 @@
+/**
+ *
+ * Copyright 2003-2006 The Apache Software Foundation
+ *
+ *  Licensed under the Apache License, Version 2.0 (the "License");
+ *  you may not use this file except in compliance with the License.
+ *  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing, software
+ *  distributed under the License is distributed on an "AS IS" BASIS,
+ *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *  See the License for the specific language governing permissions and
+ *  limitations under the License.
+ */
+package javax.mail.internet;
+
+import java.io.UnsupportedEncodingException;
+import java.lang.reflect.Array;
+import java.net.InetAddress;
+import java.net.UnknownHostException;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.StringTokenizer;
+
+import javax.mail.Address;
+import javax.mail.Session;
+
+import org.apache.geronimo.mail.util.SessionUtil;
+
+/**
+ * A representation of an Internet email address as specified by RFC822 in
+ * conjunction with a human-readable personal name that can be encoded as
+ * specified by RFC2047.
+ * A typical address is "user@host.domain" and personal name "Joe User"
+ *
+ * @version $Rev$ $Date$
+ */
+public class InternetAddress extends Address implements Cloneable {
+    /**
+     * The address in RFC822 format.
+     */
+    protected String address;
+
+    /**
+     * The personal name in RFC2047 format.
+     * Subclasses must ensure that this field is updated if the personal field
+     * is updated; alternatively, it can be invalidated by setting to null
+     * which will cause it to be recomputed.
+     */
+    protected String encodedPersonal;
+
+    /**
+     * The personal name as a Java String.
+     * Subclasses must ensure that this field is updated if the encodedPersonal field
+     * is updated; alternatively, it can be invalidated by setting to null
+     * which will cause it to be recomputed.
+     */
+    protected String personal;
+
+    public InternetAddress() {
+    }
+
+    public InternetAddress(String address) throws AddressException {
+        this(address, true);
+    }
+
+    public InternetAddress(String address, boolean strict) throws AddressException {
+        // use the parse method to process the address.  This has the wierd side effect of creating a new
+        // InternetAddress instance to create an InternetAddress, but these are lightweight objects and
+        // we need access to multiple pieces of data from the parsing process.
+        AddressParser parser = new AddressParser(address, strict ? AddressParser.STRICT : AddressParser.NONSTRICT);
+
+        InternetAddress parsedAddress = parser.parseAddress();
+        // copy the important information, which right now is just the address and
+        // personal info.
+        this.address = parsedAddress.address;
+        this.personal = parsedAddress.personal;
+        this.encodedPersonal = parsedAddress.encodedPersonal;
+    }
+
+    public InternetAddress(String address, String personal) throws UnsupportedEncodingException {
+        this(address, personal, null);
+    }
+
+    public InternetAddress(String address, String personal, String charset) throws UnsupportedEncodingException {
+        this.address = address;
+        setPersonal(personal, charset);
+    }
+
+    /**
+     * Clone this object.
+     *
+     * @return a copy of this object as created by Object.clone()
+     */
+    public Object clone() {
+        try {
+            return super.clone();
+        } catch (CloneNotSupportedException e) {
+            throw new Error();
+        }
+    }
+
+    /**
+     * Return the type of this address.
+     *
+     * @return the type of this address; always "rfc822"
+     */
+    public String getType() {
+        return "rfc822";
+    }
+
+    /**
+     * Set the address.
+     * No validation is performed; validate() can be used to check if it is valid.
+     *
+     * @param address the address to set
+     */
+    public void setAddress(String address) {
+        this.address = address;
+    }
+
+    /**
+     * Set the personal name.
+     * The name is first checked to see if it can be encoded; if this fails then an
+     * UnsupportedEncodingException is thrown and no fields are modified.
+     *
+     * @param name    the new personal name
+     * @param charset the charset to use; see {@link MimeUtility#encodeWord(String, String, String) MimeUtilityencodeWord}
+     * @throws UnsupportedEncodingException if the name cannot be encoded
+     */
+    public void setPersonal(String name, String charset) throws UnsupportedEncodingException {
+        personal = name;
+        if (name != null) {
+            encodedPersonal = MimeUtility.encodeWord(name, charset, null);
+        }
+        else {
+            encodedPersonal = null;
+        }
+    }
+
+    /**
+     * Set the personal name.
+     * The name is first checked to see if it can be encoded using {@link MimeUtility#encodeWord(String)}; if this fails then an
+     * UnsupportedEncodingException is thrown and no fields are modified.
+     *
+     * @param name the new personal name
+     * @throws UnsupportedEncodingException if the name cannot be encoded
+     */
+    public void setPersonal(String name) throws UnsupportedEncodingException {
+        personal = name;
+        if (name != null) {
+            encodedPersonal = MimeUtility.encodeWord(name);
+        }
+        else {
+            encodedPersonal = null;
+        }
+    }
+
+    /**
+     * Return the address.
+     *
+     * @return the address
+     */
+    public String getAddress() {
+        return address;
+    }
+
+    /**
+     * Return the personal name.
+     * If the personal field is null, then an attempt is made to decode the encodedPersonal
+     * field using {@link MimeUtility#decodeWord(String)}; if this is sucessful, then
+     * the personal field is updated with that value and returned; if there is a problem
+     * decoding the text then the raw value from encodedPersonal is returned.
+     *
+     * @return the personal name
+     */
+    public String getPersonal() {
+        if (personal == null && encodedPersonal != null) {
+            try {
+                personal = MimeUtility.decodeWord(encodedPersonal);
+            } catch (ParseException e) {
+                return encodedPersonal;
+            } catch (UnsupportedEncodingException e) {
+                return encodedPersonal;
+            }
+        }
+        return personal;
+    }
+
+    /**
+     * Return the encoded form of the personal name.
+     * If the encodedPersonal field is null, then an attempt is made to encode the
+     * personal field using {@link MimeUtility#encodeWord(String)}; if this is
+     * successful then the encodedPersonal field is updated with that value and returned;
+     * if there is a problem encoding the text then null is returned.
+     *
+     * @return the encoded form of the personal name
+     */
+    private String getEncodedPersonal() {
+        if (encodedPersonal == null && personal != null) {
+            try {
+                encodedPersonal = MimeUtility.encodeWord(personal);
+            } catch (UnsupportedEncodingException e) {
+                // as we could not encode this, return null
+                return null;
+            }
+        }
+        return encodedPersonal;
+    }
+
+
+    /**
+     * Return a string representation of this address using only US-ASCII characters.
+     *
+     * @return a string representation of this address
+     */
+    public String toString() {
+        // group addresses are always returned without modification.
+        if (isGroup()) {
+            return address;
+        }
+
+        // if we have personal information, then we need to return this in the route-addr form:
+        // "personal <address>".  If there is no personal information, then we typically return
+        // the address without the angle brackets.  However, if the address contains anything other
+        // than atoms, '@', and '.' (e.g., uses domain literals, has specified routes, or uses
+        // quoted strings in the local-part), we bracket the address.
+        String p = getEncodedPersonal();
+        if (p == null) {
+            return formatAddress(address);
+        }
+        else {
+            StringBuffer buf = new StringBuffer(p.length() + 8 + address.length() + 3);
+            buf.append(AddressParser.quoteString(p));
+            buf.append(" <").append(address).append(">");
+            return buf.toString();
+        }
+    }
+
+    /**
+     * Check the form of an address, and enclose it within brackets
+     * if they are required for this address form.
+     *
+     * @param a      The source address.
+     *
+     * @return A formatted address, which can be the original address string.
+     */
+    private String formatAddress(String a)
+    {
+        // this could be a group address....we don't muck with those.
+        if (address.endsWith(";") && address.indexOf(":") > 0) {
+            return address;
+        }
+
+        if (AddressParser.containsCharacters(a, "()<>,;:\"[]")) {
+            StringBuffer buf = new StringBuffer(address.length() + 3);
+            buf.append("<").append(address).append(">");
+            return buf.toString();
+        }
+        return address;
+    }
+
+    /**
+     * Return a string representation of this address using Unicode characters.
+     *
+     * @return a string representation of this address
+     */
+    public String toUnicodeString() {
+        // group addresses are always returned without modification.
+        if (isGroup()) {
+            return address;
+        }
+
+        // if we have personal information, then we need to return this in the route-addr form:
+        // "personal <address>".  If there is no personal information, then we typically return
+        // the address without the angle brackets.  However, if the address contains anything other
+        // than atoms, '@', and '.' (e.g., uses domain literals, has specified routes, or uses
+        // quoted strings in the local-part), we bracket the address.
+
+        // NB:  The difference between toString() and toUnicodeString() is the use of getPersonal()
+        // vs. getEncodedPersonal() for the personal portion.  If the personal information contains only
+        // ASCII-7 characters, these are the same.
+        String p = getPersonal();
+        if (p == null) {
+            return formatAddress(address);
+        }
+        else {
+            StringBuffer buf = new StringBuffer(p.length() + 8 + address.length() + 3);
+            buf.append(AddressParser.quoteString(p));
+            buf.append(" <").append(address).append(">");
+            return buf.toString();
+        }
+    }
+
+    /**
+     * Compares two addresses for equality.
+     * We define this as true if the other object is an InternetAddress
+     * and the two values returned by getAddress() are equal in a
+     * case-insensitive comparison.
+     *
+     * @param o the other object
+     * @return true if the addresses are the same
+     */
+    public boolean equals(Object o) {
+        if (this == o) return true;
+        if (!(o instanceof InternetAddress)) return false;
+
+        InternetAddress other = (InternetAddress) o;
+        String myAddress = getAddress();
+        return myAddress == null ? (other.getAddress() == null) : myAddress.equalsIgnoreCase(other.getAddress());
+    }
+
+    /**
+     * Return the hashCode for this address.
+     * We define this to be the hashCode of the address after conversion to lowercase.
+     *
+     * @return a hashCode for this address
+     */
+    public int hashCode() {
+        return (address == null) ? 0 : address.toLowerCase().hashCode();
+    }
+
+    /**
+     * Return true is this address is an RFC822 group address in the format
+     * <code>phrase ":" [#mailbox] ";"</code>.
+     * We check this by using the presense of a ':' character in the address, and a
+     * ';' as the very last character.
+     *
+     * @return true is this address represents a group
+     */
+    public boolean isGroup() {
+        if (address == null) {
+            return false;
+        }
+
+        return address.endsWith(";") && address.indexOf(":") > 0;
+    }
+
+    /**
+     * Return the members of a group address.
+     *
+     * If strict is true and the address does not contain an initial phrase then an AddressException is thrown.
+     * Otherwise the phrase is skipped and the remainder of the address is checked to see if it is a group.
+     * If it is, the content and strict flag are passed to parseHeader to extract the list of addresses;
+     * if it is not a group then null is returned.
+     *
+     * @param strict whether strict RFC822 checking should be performed
+     * @return an array of InternetAddress objects for the group members, or null if this address is not a group
+     * @throws AddressException if there was a problem parsing the header
+     */
+    public InternetAddress[] getGroup(boolean strict) throws AddressException {
+        if (address == null) {
+            return null;
+        }
+
+        // create an address parser and use it to extract the group information.
+        AddressParser parser = new AddressParser(address, strict ? AddressParser.STRICT : AddressParser.NONSTRICT);
+        return parser.extractGroupList();
+    }
+
+    /**
+     * Return an InternetAddress representing the current user.
+     * <P/>
+     * If session is not null, we first look for an address specified in its
+     * "mail.from" property; if this is not set, we look at its "mail.user"
+     * and "mail.host" properties and if both are not null then an address of
+     * the form "${mail.user}@${mail.host}" is created.
+     * If this fails to give an address, then an attempt is made to create
+     * an address by combining the value of the "user.name" System property
+     * with the value returned from InetAddress.getLocalHost().getHostName().
+     * Any SecurityException raised accessing the system property or any
+     * UnknownHostException raised getting the hostname are ignored.
+     * <P/>
+     * Finally, an attempt is made to convert the value obtained above to
+     * an InternetAddress. If this fails, then null is returned.
+     *
+     * @param session used to obtain mail properties
+     * @return an InternetAddress for the current user, or null if it cannot be determined
+     */
+    public static InternetAddress getLocalAddress(Session session) {
+        String host = null;
+        String user = null;
+
+        // ok, we have several steps for resolving this.  To start with, we could have a from address
+        // configured already, which will be a full InternetAddress string.  If we don't have that, then
+        // we need to resolve a user and host to compose an address from.
+        if (session != null) {
+            String address = session.getProperty("mail.from");
+            // if we got this, we can skip out now
+            if (address != null) {
+                try {
+                    return new InternetAddress(address);
+                } catch (AddressException e) {
+                    // invalid address on the from...treat this as an error and return null.
+                    return null;
+                }
+            }
+
+            // now try for user and host information.  We have both session and system properties to check here.
+            // we'll just handle the session ones here, and check the system ones below if we're missing information.
+            user = session.getProperty("mail.user");
+            host = session.getProperty("mail.host");
+        }
+
+        try {
+
+            // if either user or host is null, then we check non-session sources for the information.
+            if (user == null) {
+                user = System.getProperty("user.name");
+            }
+
+            if (host == null) {
+                host = InetAddress.getLocalHost().getHostName();
+            }
+
+            if (user != null && host != null) {
+                // if we have both a user and host, we can create a local address
+                return new InternetAddress(user + '@' + host);
+            }
+        } catch (AddressException e) {
+            // ignore
+        } catch (UnknownHostException e) {
+            // ignore
+        } catch (SecurityException e) {
+            // ignore
+        }
+        return null;
+    }
+
+    /**
+     * Convert the supplied addresses into a single String of comma-separated text as
+     * produced by {@link InternetAddress#toString() toString()}.
+     * No line-break detection is performed.
+     *
+     * @param addresses the array of addresses to convert
+     * @return a one-line String of comma-separated addresses
+     */
+    public static String toString(Address[] addresses) {
+        if (addresses == null || addresses.length == 0) {
+            return null;
+        }
+        if (addresses.length == 1) {
+            return addresses[0].toString();
+        } else {
+            StringBuffer buf = new StringBuffer(addresses.length * 32);
+            buf.append(addresses[0].toString());
+            for (int i = 1; i < addresses.length; i++) {
+                buf.append(", ");
+                buf.append(addresses[i].toString());
+            }
+            return buf.toString();
+        }
+    }
+
+    /**
+     * Convert the supplies addresses into a String of comma-separated text,
+     * inserting line-breaks between addresses as needed to restrict the line
+     * length to 72 characters. Splits will only be introduced between addresses
+     * so an address longer than 71 characters will still be placed on a single
+     * line.
+     *
+     * @param addresses the array of addresses to convert
+     * @param used      the starting column
+     * @return a String of comma-separated addresses with optional line breaks
+     */
+    public static String toString(Address[] addresses, int used) {
+        if (addresses == null || addresses.length == 0) {
+            return null;
+        }
+        if (addresses.length == 1) {
+            String s = addresses[0].toString();
+            if (used + s.length() > 72) {
+                s = "\r\n  " + s;
+            }
+            return s;
+        } else {
+            StringBuffer buf = new StringBuffer(addresses.length * 32);
+            for (int i = 0; i < addresses.length; i++) {
+                String s = addresses[1].toString();
+                if (i == 0) {
+                    if (used + s.length() + 1 > 72) {
+                        buf.append("\r\n  ");
+                        used = 2;
+                    }
+                } else {
+                    if (used + s.length() + 1 > 72) {
+                        buf.append(",\r\n  ");
+                        used = 2;
+                    } else {
+                        buf.append(", ");
+                        used += 2;
+                    }
+                }
+                buf.append(s);
+                used += s.length();
+            }
+            return buf.toString();
+        }
+    }
+
+    /**
+     * Parse addresses out of the string with basic checking.
+     *
+     * @param addresses the addresses to parse
+     * @return an array of InternetAddresses parsed from the string
+     * @throws AddressException if addresses checking fails
+     */
+    public static InternetAddress[] parse(String addresses) throws AddressException {
+        return parse(addresses, true);
+    }
+
+    /**
+     * Parse addresses out of the string.
+     *
+     * @param addresses the addresses to parse
+     * @param strict if true perform detailed checking, if false just perform basic checking
+     * @return an array of InternetAddresses parsed from the string
+     * @throws AddressException if address checking fails
+     */
+    public static InternetAddress[] parse(String addresses, boolean strict) throws AddressException {
+        return parse(addresses, strict ? AddressParser.STRICT : AddressParser.NONSTRICT);
+    }
+
+    /**
+     * Parse addresses out of the string.
+     *
+     * @param addresses the addresses to parse
+     * @param strict if true perform detailed checking, if false perform little checking
+     * @return an array of InternetAddresses parsed from the string
+     * @throws AddressException if address checking fails
+     */
+    public static InternetAddress[] parseHeader(String addresses, boolean strict) throws AddressException {
+        return parse(addresses, strict ? AddressParser.STRICT : AddressParser.PARSE_HEADER);
+    }
+
+    /**
+     * Parse addresses with increasing degrees of RFC822 compliance checking.
+     *
+     * @param addresses the string to parse
+     * @param level     The required strictness level.
+     *
+     * @return an array of InternetAddresses parsed from the string
+     * @throws AddressException
+     *                if address checking fails
+     */
+    private static InternetAddress[] parse(String addresses, int level) throws AddressException {
+        // create a parser and have it extract the list using the requested strictness leve.
+        AddressParser parser = new AddressParser(addresses, level);
+        return parser.parseAddressList();
+    }
+
+    /**
+     * Validate the address portion of an internet address to ensure
+     * validity.   Throws an AddressException if any validity
+     * problems are encountered.
+     *
+     * @exception AddressException
+     */
+    public void validate() throws AddressException {
+
+        // create a parser using the strictest validation level.
+        AddressParser parser = new AddressParser(formatAddress(address), AddressParser.STRICT);
+        parser.validateAddress();
+    }
+}

Propchange: geronimo/specs/trunk/geronimo-spec-javamail-1.4/src/main/java/javax/mail/internet/InternetAddress.java
------------------------------------------------------------------------------
    svn:eol-style = native

Propchange: geronimo/specs/trunk/geronimo-spec-javamail-1.4/src/main/java/javax/mail/internet/InternetAddress.java
------------------------------------------------------------------------------
    svn:keywords = Date Revision

Propchange: geronimo/specs/trunk/geronimo-spec-javamail-1.4/src/main/java/javax/mail/internet/InternetAddress.java
------------------------------------------------------------------------------
    svn:mime-type = text/plain

Added: geronimo/specs/trunk/geronimo-spec-javamail-1.4/src/main/java/javax/mail/internet/InternetHeaders.java
URL: http://svn.apache.org/viewvc/geronimo/specs/trunk/geronimo-spec-javamail-1.4/src/main/java/javax/mail/internet/InternetHeaders.java?rev=421852&view=auto
==============================================================================
--- geronimo/specs/trunk/geronimo-spec-javamail-1.4/src/main/java/javax/mail/internet/InternetHeaders.java (added)
+++ geronimo/specs/trunk/geronimo-spec-javamail-1.4/src/main/java/javax/mail/internet/InternetHeaders.java Fri Jul 14 03:02:19 2006
@@ -0,0 +1,670 @@
+/**
+ *
+ * Copyright 2003-2006 The Apache Software Foundation
+ *
+ *  Licensed under the Apache License, Version 2.0 (the "License");
+ *  you may not use this file except in compliance with the License.
+ *  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing, software
+ *  distributed under the License is distributed on an "AS IS" BASIS,
+ *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *  See the License for the specific language governing permissions and
+ *  limitations under the License.
+ */
+
+package javax.mail.internet;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.Enumeration;
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+import javax.mail.Address;
+import javax.mail.Header;
+import javax.mail.MessagingException;
+
+/**
+ * Class that represents the RFC822 headers associated with a message.
+ *
+ * @version $Rev$ $Date$
+ */
+public class InternetHeaders {
+    // the list of headers (to preserve order);
+    protected List headers = new ArrayList();
+
+    private transient String lastHeaderName;
+
+    /**
+     * Create an empty InternetHeaders
+     */
+    public InternetHeaders() {
+        // these are created in the preferred order of the headers.
+        addHeader("Return-path", null);
+        addHeader("Received", null);
+        addHeader("Message-ID", null);
+        addHeader("Resent-Date", null);
+        addHeader("Date", null);
+        addHeader("Resent-From", null);
+        addHeader("From", null);
+        addHeader("Reply-To", null);
+        addHeader("Sender", null);
+        addHeader("To", null);
+        addHeader("Subject", null);
+        addHeader("Cc", null);
+        addHeader("In-Reply-To", null);
+        addHeader("Resent-Message-Id", null);
+        addHeader("Errors-To", null);
+        addHeader("MIME-Version", null);
+        addHeader("Content-Type", null);
+        addHeader("Content-Transfer-Encoding", null);
+        addHeader("Content-MD5", null);
+        // the following is a special marker used to identify new header insertion points.
+        addHeader(":", null);
+        addHeader("Content-Length", null);
+        addHeader("Status", null);
+    }
+
+    /**
+     * Create a new InternetHeaders initialized by reading headers from the
+     * stream.
+     *
+     * @param in
+     *            the RFC822 input stream to load from
+     * @throws MessagingException
+     *             if there is a problem pasring the stream
+     */
+    public InternetHeaders(InputStream in) throws MessagingException {
+        load(in);
+    }
+
+    /**
+     * Read and parse the supplied stream and add all headers to the current
+     * set.
+     *
+     * @param in
+     *            the RFC822 input stream to load from
+     * @throws MessagingException
+     *             if there is a problem pasring the stream
+     */
+    public void load(InputStream in) throws MessagingException {
+        try {
+            StringBuffer name = new StringBuffer(32);
+            StringBuffer value = new StringBuffer(128);
+            done: while (true) {
+                int c = in.read();
+                char ch = (char) c;
+                if (c == -1) {
+                    break;
+                } else if (c == 13) {
+                    // empty line terminates header
+                    in.read(); // skip LF
+                    break;
+                } else if (Character.isWhitespace(ch)) {
+                    // handle continuation
+                    do {
+                        c = in.read();
+                        if (c == -1) {
+                            break done;
+                        }
+                        ch = (char) c;
+                    } while (Character.isWhitespace(ch));
+                } else {
+                    // new header
+                    if (name.length() > 0) {
+                        addHeader(name.toString().trim(), value.toString().trim());
+                    }
+                    name.setLength(0);
+                    value.setLength(0);
+                    while (true) {
+                        name.append((char) c);
+                        c = in.read();
+                        if (c == -1) {
+                            break done;
+                        } else if (c == ':') {
+                            break;
+                        }
+                    }
+                    c = in.read();
+                    if (c == -1) {
+                        break done;
+                    }
+                }
+
+                while (c != 13) {
+                    ch = (char) c;
+                    value.append(ch);
+                    c = in.read();
+                    if (c == -1) {
+                        break done;
+                    }
+                }
+                // skip LF
+                c = in.read();
+                if (c == -1) {
+                    break;
+                }
+            }
+            if (name.length() > 0) {
+                addHeader(name.toString().trim(), value.toString().trim());
+            }
+        } catch (IOException e) {
+            throw new MessagingException("Error loading headers", e);
+        }
+    }
+
+
+    /**
+     * Return all the values for the specified header.
+     *
+     * @param name
+     *            the header to return
+     * @return the values for that header, or null if the header is not present
+     */
+    public String[] getHeader(String name) {
+        List accumulator = new ArrayList();
+
+        for (int i = 0; i < headers.size(); i++) {
+            InternetHeader header = (InternetHeader)headers.get(i);
+            if (header.getName().equalsIgnoreCase(name) && header.getValue() != null) {
+                accumulator.add(header.getValue());
+            }
+        }
+
+        // this is defined as returning null of nothing is found.
+        if (accumulator.isEmpty()) {
+            return null;
+        }
+
+        // convert this to an array.
+        return (String[])accumulator.toArray(new String[accumulator.size()]);
+    }
+
+    /**
+     * Return the values for the specified header as a single String. If the
+     * header has more than one value then all values are concatenated together
+     * separated by the supplied delimiter.
+     *
+     * @param name
+     *            the header to return
+     * @param delimiter
+     *            the delimiter used in concatenation
+     * @return the header as a single String
+     */
+    public String getHeader(String name, String delimiter) {
+        // get all of the headers with this name
+        String[] matches = getHeader(name);
+
+        // no match?  return a null.
+        if (matches == null) {
+            return null;
+        }
+
+        // a null delimiter means just return the first one.  If there's only one item, this is easy too.
+        if (matches.length == 1 || delimiter == null) {
+            return matches[0];
+        }
+
+        // perform the concatenation
+        StringBuffer result = new StringBuffer(matches[0]);
+
+        for (int i = 1; i < matches.length; i++) {
+            result.append(delimiter);
+            result.append(matches[i]);
+        }
+
+        return result.toString();
+    }
+
+
+    /**
+     * Set the value of the header to the supplied value; any existing headers
+     * are removed.
+     *
+     * @param name
+     *            the name of the header
+     * @param value
+     *            the new value
+     */
+    public void setHeader(String name, String value) {
+        // look for a header match
+        for (int i = 0; i < headers.size(); i++) {
+            InternetHeader header = (InternetHeader)headers.get(i);
+            // found a matching header
+            if (name.equalsIgnoreCase(header.getName())) {
+                // just update the header value
+                header.setValue(value);
+                // remove all of the headers from this point
+                removeHeaders(name, i + 1);
+                return;
+            }
+        }
+
+        // doesn't exist, so process as an add.
+        addHeader(name, value);
+    }
+
+
+    /**
+     * Remove all headers with the given name, starting with the
+     * specified start position.
+     *
+     * @param name   The target header name.
+     * @param pos    The position of the first header to examine.
+     */
+    private void removeHeaders(String name, int pos) {
+        // now go remove all other instances of this header
+        for (int i = pos; i < headers.size(); i++) {
+            InternetHeader header = (InternetHeader)headers.get(i);
+            // found a matching header
+            if (name.equalsIgnoreCase(header.getName())) {
+                // remove this item, and back up
+                headers.remove(i);
+                i--;
+            }
+        }
+    }
+
+
+    /**
+     * Find a header in the current list by name, returning the index.
+     *
+     * @param name   The target name.
+     *
+     * @return The index of the header in the list.  Returns -1 for a not found
+     *         condition.
+     */
+    private int findHeader(String name) {
+        return findHeader(name, 0);
+    }
+
+
+    /**
+     * Find a header in the current list, beginning with the specified
+     * start index.
+     *
+     * @param name   The target header name.
+     * @param start  The search start index.
+     *
+     * @return The index of the first matching header.  Returns -1 if the
+     *         header is not located.
+     */
+    private int findHeader(String name, int start) {
+        for (int i = start; i < headers.size(); i++) {
+            InternetHeader header = (InternetHeader)headers.get(i);
+            // found a matching header
+            if (name.equalsIgnoreCase(header.getName())) {
+                return i;
+            }
+        }
+        return -1;
+    }
+
+    /**
+     * Add a new value to the header with the supplied name.
+     *
+     * @param name
+     *            the name of the header to add a new value for
+     * @param value
+     *            another value
+     */
+    public void addHeader(String name, String value) {
+        InternetHeader newHeader = new InternetHeader(name, value);
+
+        // The javamail spec states that "Recieved" headers need to be added in reverse order.
+        // Return-Path is permitted before Received, so handle it the same way.
+        if (name.equalsIgnoreCase("Received") || name.equalsIgnoreCase("Return-Path")) {
+            // see if we have one of these already
+            int pos = findHeader(name);
+
+            // either insert before an existing header, or insert at the very beginning
+            if (pos != -1) {
+                // this could be a placeholder header with a null value.  If it is, just update
+                // the value.  Otherwise, insert in front of the existing header.
+                InternetHeader oldHeader = (InternetHeader)headers.get(pos);
+                if (oldHeader.getValue() == null) {
+                    oldHeader.setValue(value);
+                }
+                else {
+                    headers.add(pos, newHeader);
+                }
+            }
+            else {
+                // doesn't exist, so insert at the beginning
+                headers.add(0, newHeader);
+            }
+        }
+        // normal insertion
+        else {
+            // see if we have one of these already
+            int pos = findHeader(name);
+
+            // either insert before an existing header, or insert at the very beginning
+            if (pos != -1) {
+                InternetHeader oldHeader = (InternetHeader)headers.get(pos);
+                // if the existing header is a place holder, we can just update the value
+                if (oldHeader.getValue() == null) {
+                    oldHeader.setValue(value);
+                }
+                else {
+                    // we have at least one existing header with this name.  We need to find the last occurrance,
+                    // and insert after that spot.
+
+                    int lastPos = findHeader(name, pos + 1);
+
+                    while (lastPos != -1) {
+                        pos = lastPos;
+                        lastPos = findHeader(name, pos + 1);
+                    }
+
+                    // ok, we have the insertion position
+                    headers.add(pos + 1, newHeader);
+                }
+            }
+            else {
+                // find the insertion marker.  If that is missing somehow, insert at the end.
+                pos = findHeader(":");
+                if (pos == -1) {
+                    pos = headers.size();
+                }
+                headers.add(pos, newHeader);
+            }
+        }
+    }
+
+
+    /**
+     * Remove all header entries with the supplied name
+     *
+     * @param name
+     *            the header to remove
+     */
+    public void removeHeader(String name) {
+        // the first occurrance of a header is just zeroed out.
+        int pos = findHeader(name);
+
+        if (pos != -1) {
+            InternetHeader oldHeader = (InternetHeader)headers.get(pos);
+            // keep the header in the list, but with a null value
+            oldHeader.setValue(null);
+            // now remove all other headers with this name
+            removeHeaders(name, pos + 1);
+        }
+    }
+
+
+    /**
+     * Return all headers.
+     *
+     * @return an Enumeration<Header> containing all headers
+     */
+    public Enumeration getAllHeaders() {
+        List result = new ArrayList();
+
+        for (int i = 0; i < headers.size(); i++) {
+            InternetHeader header = (InternetHeader)headers.get(i);
+            // we only include headers with real values, no placeholders
+            if (header.getValue() != null) {
+                result.add(header);
+            }
+        }
+        // just return a list enumerator for the header list.
+        return Collections.enumeration(result);
+    }
+
+
+    /**
+     * Test if a given header name is a match for any header in the
+     * given list.
+     *
+     * @param name   The name of the current tested header.
+     * @param names  The list of names to match against.
+     *
+     * @return True if this is a match for any name in the list, false
+     *         for a complete mismatch.
+     */
+    private boolean matchHeader(String name, String[] names) {
+        for (int i = 0; i < names.length; i++) {
+            if (name.equalsIgnoreCase(names[i])) {
+                return true;
+            }
+        }
+        return false;
+    }
+
+
+    /**
+     * Return all matching Header objects.
+     */
+    public Enumeration getMatchingHeaders(String[] names) {
+        List result = new ArrayList();
+
+        for (int i = 0; i < headers.size(); i++) {
+            InternetHeader header = (InternetHeader)headers.get(i);
+            // we only include headers with real values, no placeholders
+            if (header.getValue() != null) {
+                // only add the matching ones
+                if (matchHeader(header.getName(), names)) {
+                    result.add(header);
+                }
+            }
+        }
+        return Collections.enumeration(result);
+    }
+
+
+    /**
+     * Return all non matching Header objects.
+     */
+    public Enumeration getNonMatchingHeaders(String[] names) {
+        List result = new ArrayList();
+
+        for (int i = 0; i < headers.size(); i++) {
+            InternetHeader header = (InternetHeader)headers.get(i);
+            // we only include headers with real values, no placeholders
+            if (header.getValue() != null) {
+                // only add the non-matching ones
+                if (!matchHeader(header.getName(), names)) {
+                    result.add(header);
+                }
+            }
+        }
+        return Collections.enumeration(result);
+    }
+
+
+    /**
+     * Add an RFC822 header line to the header store. If the line starts with a
+     * space or tab (a continuation line), add it to the last header line in the
+     * list. Otherwise, append the new header line to the list.
+     *
+     * Note that RFC822 headers can only contain US-ASCII characters
+     *
+     * @param line
+     *            raw RFC822 header line
+     */
+    public void addHeaderLine(String line) {
+        // null lines are a nop
+        if (line.length() == 0) {
+            return;
+        }
+
+        // we need to test the first character to see if this is a continuation whitespace
+        char ch = line.charAt(0);
+
+        // tabs and spaces are special.  This is a continuation of the last header in the list.
+        if (ch == ' ' || ch == '\t') {
+            InternetHeader header = (InternetHeader)headers.get(headers.size() - 1);
+            header.appendValue(line);
+        }
+        else {
+            // this just gets appended to the end, preserving the addition order.
+            headers.add(new InternetHeader(line));
+        }
+    }
+
+
+    /**
+     * Return all the header lines as an Enumeration of Strings.
+     */
+    public Enumeration getAllHeaderLines() {
+        return new HeaderLineEnumeration(getAllHeaders());
+    }
+
+    /**
+     * Return all matching header lines as an Enumeration of Strings.
+     */
+    public Enumeration getMatchingHeaderLines(String[] names) {
+        return new HeaderLineEnumeration(getMatchingHeaders(names));
+    }
+
+    /**
+     * Return all non-matching header lines.
+     */
+    public Enumeration getNonMatchingHeaderLines(String[] names) {
+        return new HeaderLineEnumeration(getNonMatchingHeaders(names));
+    }
+
+
+    /**
+     * Set an internet header from a list of addresses.  The
+     * first address item is set, followed by a series of addHeaders().
+     *
+     * @param name      The name to set.
+     * @param addresses The list of addresses to set.
+     */
+    void setHeader(String name, Address[] addresses) {
+        // if this is empty, then ew need to replace this
+        if (addresses.length == 0) {
+            removeHeader(name);
+        }
+
+        // replace the first header
+        setHeader(name, addresses[0].toString());
+
+        // now add the rest as extra headers.
+        for (int i = 1; i < addresses.length; i++) {
+            Address address = addresses[i];
+            addHeader(name, address.toString());
+        }
+    }
+
+
+    void writeTo(OutputStream out, String[] ignore) throws IOException {
+        if (ignore == null) {
+            // write out all header lines with non-null values
+            for (int i = 0; i < headers.size(); i++) {
+                InternetHeader header = (InternetHeader)headers.get(i);
+                // we only include headers with real values, no placeholders
+                if (header.getValue() != null) {
+                    header.writeTo(out);
+                }
+            }
+        }
+        else {
+            // write out all matching header lines with non-null values
+            for (int i = 0; i < headers.size(); i++) {
+                InternetHeader header = (InternetHeader)headers.get(i);
+                // we only include headers with real values, no placeholders
+                if (header.getValue() != null) {
+                    if (matchHeader(header.getName(), ignore)) {
+                        header.writeTo(out);
+                    }
+                }
+            }
+        }
+    }
+
+    protected static final class InternetHeader extends Header {
+
+        public InternetHeader(String h) {
+            // initialize with null values, which we'll update once we parse the string
+            super("", "");
+            int separator = h.indexOf(':');
+            // no separator, then we take this as a name with a null string value.
+            if (separator == -1) {
+                name = h.trim();
+            }
+            else {
+                name = h.substring(0, separator);
+                // step past the separator.  Now we need to remove any leading white space characters.
+                separator++;
+
+                while (separator < h.length()) {
+                    char ch = h.charAt(separator);
+                    if (ch != ' ' && ch != '\t' && ch != '\r' && ch != '\n') {
+                        break;
+                    }
+                    separator++;
+                }
+
+                value = h.substring(separator);
+            }
+        }
+
+        public InternetHeader(String name, String value) {
+            super(name, value);
+        }
+
+
+        /**
+         * Package scope method for setting the header value.
+         *
+         * @param value  The new header value.
+         */
+        void setValue(String value) {
+            this.value = value;
+        }
+
+        /**
+         * Package scope method for extending a header value.
+         *
+         * @param value  The appended header value.
+         */
+        void appendValue(String value) {
+            if (this.value == null) {
+                this.value = value;
+            }
+            else {
+                this.value = this.value + "\r\n" + value;
+            }
+        }
+
+        void writeTo(OutputStream out) throws IOException {
+            out.write(name.getBytes());
+            out.write(':');
+            out.write(' ');
+            out.write(value.getBytes());
+            out.write('\r');
+            out.write('\n');
+        }
+    }
+
+    private static class HeaderLineEnumeration implements Enumeration {
+        private Enumeration headers;
+
+        public HeaderLineEnumeration(Enumeration headers) {
+            this.headers = headers;
+        }
+
+        public boolean hasMoreElements() {
+            return headers.hasMoreElements();
+        }
+
+        public Object nextElement() {
+            Header h = (Header) headers.nextElement();
+            return h.getName() + ": " + h.getValue();
+        }
+    }
+}

Propchange: geronimo/specs/trunk/geronimo-spec-javamail-1.4/src/main/java/javax/mail/internet/InternetHeaders.java
------------------------------------------------------------------------------
    svn:eol-style = native

Propchange: geronimo/specs/trunk/geronimo-spec-javamail-1.4/src/main/java/javax/mail/internet/InternetHeaders.java
------------------------------------------------------------------------------
    svn:keywords = Date Revision

Propchange: geronimo/specs/trunk/geronimo-spec-javamail-1.4/src/main/java/javax/mail/internet/InternetHeaders.java
------------------------------------------------------------------------------
    svn:mime-type = text/plain

Added: geronimo/specs/trunk/geronimo-spec-javamail-1.4/src/main/java/javax/mail/internet/MailDateFormat.java
URL: http://svn.apache.org/viewvc/geronimo/specs/trunk/geronimo-spec-javamail-1.4/src/main/java/javax/mail/internet/MailDateFormat.java?rev=421852&view=auto
==============================================================================
--- geronimo/specs/trunk/geronimo-spec-javamail-1.4/src/main/java/javax/mail/internet/MailDateFormat.java (added)
+++ geronimo/specs/trunk/geronimo-spec-javamail-1.4/src/main/java/javax/mail/internet/MailDateFormat.java Fri Jul 14 03:02:19 2006
@@ -0,0 +1,69 @@
+/**
+ *
+ * Copyright 2003-2006 The Apache Software Foundation
+ *
+ *  Licensed under the Apache License, Version 2.0 (the "License");
+ *  you may not use this file except in compliance with the License.
+ *  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing, software
+ *  distributed under the License is distributed on an "AS IS" BASIS,
+ *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *  See the License for the specific language governing permissions and
+ *  limitations under the License.
+ */
+
+package javax.mail.internet;
+
+import java.text.FieldPosition;
+import java.text.NumberFormat;
+import java.text.ParsePosition;
+import java.text.SimpleDateFormat;
+import java.util.Calendar;
+import java.util.Date;
+import java.util.Locale;
+
+/**
+ * Formats ths date as specified by
+ * draft-ietf-drums-msg-fmt-08 dated January 26, 2000
+ * which supercedes RFC822.
+ * <p/>
+ * <p/>
+ * The format used is <code>EEE, d MMM yyyy HH:mm:ss Z</code> and
+ * locale is always US-ASCII.
+ *
+ * @version $Rev$ $Date$
+ */
+public class MailDateFormat extends SimpleDateFormat {
+    public MailDateFormat() {
+        super("EEE, d MMM yyyy HH:mm:ss Z", Locale.US);
+    }
+
+    public StringBuffer format(Date date, StringBuffer buffer, FieldPosition position) {
+        return super.format(date, buffer, position);
+    }
+
+    public Date parse(String string, ParsePosition position) {
+        return super.parse(string, position);
+    }
+
+    /**
+     * The calendar cannot be set
+     * @param calendar
+     * @throws UnsupportedOperationException
+     */
+    public void setCalendar(Calendar calendar) {
+        throw new UnsupportedOperationException();
+    }
+
+    /**
+     * The format cannot be set
+     * @param format
+     * @throws UnsupportedOperationException
+     */
+    public void setNumberFormat(NumberFormat format) {
+        throw new UnsupportedOperationException();
+    }
+}

Propchange: geronimo/specs/trunk/geronimo-spec-javamail-1.4/src/main/java/javax/mail/internet/MailDateFormat.java
------------------------------------------------------------------------------
    svn:eol-style = native

Propchange: geronimo/specs/trunk/geronimo-spec-javamail-1.4/src/main/java/javax/mail/internet/MailDateFormat.java
------------------------------------------------------------------------------
    svn:keywords = Date Revision

Propchange: geronimo/specs/trunk/geronimo-spec-javamail-1.4/src/main/java/javax/mail/internet/MailDateFormat.java
------------------------------------------------------------------------------
    svn:mime-type = text/plain

Added: geronimo/specs/trunk/geronimo-spec-javamail-1.4/src/main/java/javax/mail/internet/MimeBodyPart.java
URL: http://svn.apache.org/viewvc/geronimo/specs/trunk/geronimo-spec-javamail-1.4/src/main/java/javax/mail/internet/MimeBodyPart.java?rev=421852&view=auto
==============================================================================
--- geronimo/specs/trunk/geronimo-spec-javamail-1.4/src/main/java/javax/mail/internet/MimeBodyPart.java (added)
+++ geronimo/specs/trunk/geronimo-spec-javamail-1.4/src/main/java/javax/mail/internet/MimeBodyPart.java Fri Jul 14 03:02:19 2006
@@ -0,0 +1,676 @@
+/**
+ *
+ * Copyright 2003-2006 The Apache Software Foundation
+ *
+ *  Licensed under the Apache License, Version 2.0 (the "License");
+ *  you may not use this file except in compliance with the License.
+ *  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing, software
+ *  distributed under the License is distributed on an "AS IS" BASIS,
+ *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *  See the License for the specific language governing permissions and
+ *  limitations under the License.
+ */
+
+package javax.mail.internet;
+
+import java.io.BufferedOutputStream;
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
+import java.io.FileOutputStream;
+import java.io.File;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.io.UnsupportedEncodingException;
+import java.util.Enumeration;
+
+import javax.activation.DataHandler;
+import javax.activation.FileDataSource;
+import javax.mail.BodyPart;
+import javax.mail.MessagingException;
+import javax.mail.Multipart;
+import javax.mail.Part;
+import javax.mail.internet.HeaderTokenizer.Token;
+import javax.swing.text.AbstractDocument.Content;
+
+import org.apache.geronimo.mail.util.ASCIIUtil;
+import org.apache.geronimo.mail.util.SessionUtil;
+
+/**
+ * @version $Rev$ $Date$
+ */
+public class MimeBodyPart extends BodyPart implements MimePart {
+	 // constants for accessed properties
+    private static final String MIME_DECODEFILENAME = "mail.mime.decodefilename";
+    private static final String MIME_ENCODEFILENAME = "mail.mime.encodefilename";
+    private static final String MIME_SETDEFAULTTEXTCHARSET = "mail.mime.setdefaulttextcharset";
+    private static final String MIME_SETCONTENTTYPEFILENAME = "mail.mime.setcontenttypefilename";
+
+
+    /**
+     * The {@link DataHandler} for this Message's content.
+     */
+    protected DataHandler dh;
+    /**
+     * This message's content (unless sourced from a SharedInputStream).
+     */
+    protected byte content[];
+    /**
+     * If the data for this message was supplied by a {@link SharedInputStream}
+     * then this is another such stream representing the content of this message;
+     * if this field is non-null, then {@link #content} will be null.
+     */
+    protected InputStream contentStream;
+    /**
+     * This message's headers.
+     */
+    protected InternetHeaders headers;
+
+    public MimeBodyPart() {
+        headers = new InternetHeaders();
+    }
+
+    public MimeBodyPart(InputStream in) throws MessagingException {
+        headers = new InternetHeaders(in);
+        ByteArrayOutputStream baos = new ByteArrayOutputStream();
+        byte[] buffer = new byte[1024];
+        int count;
+        try {
+            while((count = in.read(buffer, 0, 1024)) != -1)
+                baos.write(buffer, 0, count);
+        } catch (IOException e) {
+            throw new MessagingException(e.toString(),e);
+        }
+        content = baos.toByteArray();
+    }
+
+    public MimeBodyPart(InternetHeaders headers, byte[] content) throws MessagingException {
+        this.headers = headers;
+        this.content = content;
+    }
+
+    /**
+     * Return the content size of this message.  This is obtained
+     * either from the size of the content field (if available) or
+     * from the contentStream, IFF the contentStream returns a positive
+     * size.  Returns -1 if the size is not available.
+     *
+     * @return Size of the content in bytes.
+     * @exception MessagingException
+     */
+    public int getSize() throws MessagingException {
+        if (content != null) {
+            return content.length;
+        }
+        if (contentStream != null) {
+            try {
+                int size = contentStream.available();
+                if (size > 0) {
+                    return size;
+                }
+            } catch (IOException e) {
+            }
+        }
+        return -1;
+    }
+
+    public int getLineCount() throws MessagingException {
+        return -1;
+    }
+
+    public String getContentType() throws MessagingException {
+        String value = getSingleHeader("Content-Type");
+        if (value == null) {
+            value = "text/plain";
+        }
+        return value;
+    }
+
+    /**
+     * Tests to see if this message has a mime-type match with the
+     * given type name.
+     *
+     * @param type   The tested type name.
+     *
+     * @return If this is a type match on the primary and secondare portion of the types.
+     * @exception MessagingException
+     */
+    public boolean isMimeType(String type) throws MessagingException {
+        return new ContentType(getContentType()).match(type);
+    }
+
+    /**
+     * Retrieve the message "Content-Disposition" header field.
+     * This value represents how the part should be represented to
+     * the user.
+     *
+     * @return The string value of the Content-Disposition field.
+     * @exception MessagingException
+     */
+    public String getDisposition() throws MessagingException {
+        String disp = getSingleHeader("Content-Disposition");
+        if (disp != null) {
+            return new ContentDisposition(disp).getDisposition();
+        }
+        return null;
+    }
+
+    /**
+     * Set a new dispostion value for the "Content-Disposition" field.
+     * If the new value is null, the header is removed.
+     *
+     * @param disposition
+     *               The new disposition value.
+     *
+     * @exception MessagingException
+     */
+    public void setDisposition(String disposition) throws MessagingException {
+        if (disposition == null) {
+            removeHeader("Content-Disposition");
+        }
+        else {
+            // the disposition has parameters, which we'll attempt to preserve in any existing header.
+            String currentHeader = getSingleHeader("Content-Disposition");
+            if (currentHeader != null) {
+                ContentDisposition content = new ContentDisposition(currentHeader);
+                content.setDisposition(disposition);
+                setHeader("Content-Disposition", content.toString());
+            }
+            else {
+                // set using the raw string.
+                setHeader("Content-Disposition", disposition);
+            }
+        }
+    }
+
+    /**
+     * Retrieves the current value of the "Content-Transfer-Encoding"
+     * header.  Returns null if the header does not exist.
+     *
+     * @return The current header value or null.
+     * @exception MessagingException
+     */
+    public String getEncoding() throws MessagingException {
+        // this might require some parsing to sort out.
+        String encoding = getSingleHeader("Content-Transfer-Encoding");
+        if (encoding != null) {
+            // we need to parse this into ATOMs and other constituent parts.  We want the first
+            // ATOM token on the string.
+            HeaderTokenizer tokenizer = new HeaderTokenizer(encoding, HeaderTokenizer.MIME);
+
+            Token token = tokenizer.next();
+            while (token.getType() != Token.EOF) {
+                // if this is an ATOM type, return it.
+                if (token.getType() == Token.ATOM) {
+                    return token.getValue();
+                }
+            }
+            // not ATOMs found, just return the entire header value....somebody might be able to make sense of
+            // this.
+            return encoding;
+        }
+        // no header, nothing to return.
+        return null;
+    }
+
+
+    /**
+     * Retrieve the value of the "Content-ID" header.  Returns null
+     * if the header does not exist.
+     *
+     * @return The current header value or null.
+     * @exception MessagingException
+     */
+    public String getContentID() throws MessagingException {
+        return getSingleHeader("Content-ID");
+    }
+
+    public void setContentID(String cid) throws MessagingException {
+        setOrRemoveHeader("Content-ID", cid);
+    }
+
+    public String getContentMD5() throws MessagingException {
+        return getSingleHeader("Content-MD5");
+    }
+
+    public void setContentMD5(String md5) throws MessagingException {
+        setHeader("Content-MD5", md5);
+    }
+
+    public String[] getContentLanguage() throws MessagingException {
+        return getHeader("Content-Language");
+    }
+
+    public void setContentLanguage(String[] languages) throws MessagingException {
+        if (languages == null) {
+            removeHeader("Content-Language");
+        } else if (languages.length == 1) {
+            setHeader("Content-Language", languages[0]);
+        } else {
+            StringBuffer buf = new StringBuffer(languages.length * 20);
+            buf.append(languages[0]);
+            for (int i = 1; i < languages.length; i++) {
+                buf.append(',').append(languages[i]);
+            }
+            setHeader("Content-Language", buf.toString());
+        }
+    }
+
+    public String getDescription() throws MessagingException {
+        String description = getSingleHeader("Content-Description");
+        if (description != null) {
+            try {
+                // this could be both folded and encoded.  Return this to usable form.
+                return MimeUtility.decodeText(MimeUtility.unfold(description));
+            } catch (UnsupportedEncodingException e) {
+                // ignore
+            }
+        }
+        // return the raw version for any errors.
+        return description;
+    }
+
+    public void setDescription(String description) throws MessagingException {
+        setDescription(description, null);
+    }
+
+    public void setDescription(String description, String charset) throws MessagingException {
+        if (description == null) {
+            removeHeader("Content-Description");
+        }
+        else {
+            try {
+                setHeader("Content-Description", MimeUtility.fold(21, MimeUtility.encodeText(description, charset, null)));
+            } catch (UnsupportedEncodingException e) {
+                throw new MessagingException(e.getMessage(), e);
+            }
+        }
+    }
+
+    public String getFileName() throws MessagingException {
+        // see if there is a disposition.  If there is, parse off the filename parameter.
+        String disposition = getSingleHeader("Content-Disposition");
+        String filename = null;
+
+        if (disposition != null) {
+            filename = new ContentDisposition(disposition).getParameter("filename");
+        }
+
+        // if there's no filename on the disposition, there might be a name parameter on a
+        // Content-Type header.
+        if (filename == null) {
+            String type = getSingleHeader("Content-Type");
+            if (type != null) {
+                try {
+                    filename = new ContentType(type).getParameter("name");
+                } catch (ParseException e) {
+                }
+            }
+        }
+        // if we have a name, we might need to decode this if an additional property is set.
+        if (filename != null && SessionUtil.getBooleanProperty(MIME_DECODEFILENAME, false)) {
+            try {
+                filename = MimeUtility.decodeText(filename);
+            } catch (UnsupportedEncodingException e) {
+                throw new MessagingException("Unable to decode filename", e);
+            }
+        }
+
+        return filename;
+    }
+
+
+    public void setFileName(String name) throws MessagingException {
+        System.out.println("Setting file name to " + name);
+        // there's an optional session property that requests file name encoding...we need to process this before
+        // setting the value.
+        if (name != null && SessionUtil.getBooleanProperty(MIME_ENCODEFILENAME, false)) {
+            try {
+                name = MimeUtility.encodeText(name);
+            } catch (UnsupportedEncodingException e) {
+                throw new MessagingException("Unable to encode filename", e);
+            }
+        }
+
+        // get the disposition string.
+        String disposition = getDisposition();
+        // if not there, then this is an attachment.
+        if (disposition == null) {
+            disposition = Part.ATTACHMENT;
+        }
+
+        // now create a disposition object and set the parameter.
+        ContentDisposition contentDisposition = new ContentDisposition(disposition);
+        contentDisposition.setParameter("filename", name);
+
+        // serialize this back out and reset.
+        setHeader("Content-Disposition", contentDisposition.toString());
+
+        // The Sun implementation appears to update the Content-type name parameter too, based on
+        // another system property
+        if (SessionUtil.getBooleanProperty(MIME_SETCONTENTTYPEFILENAME, true)) {
+            ContentType type = new ContentType(getContentType());
+            type.setParameter("name", name);
+            setHeader("Content-Type", type.toString());
+        }
+    }
+
+    public InputStream getInputStream() throws MessagingException, IOException {
+        return getDataHandler().getInputStream();
+    }
+
+    protected InputStream getContentStream() throws MessagingException {
+        if (contentStream != null) {
+            return contentStream;
+        }
+
+        if (content != null) {
+            return new ByteArrayInputStream(content);
+        } else {
+            throw new MessagingException("No content");
+        }
+    }
+
+    public InputStream getRawInputStream() throws MessagingException {
+        return getContentStream();
+    }
+
+    public synchronized DataHandler getDataHandler() throws MessagingException {
+        if (dh == null) {
+            dh = new DataHandler(new MimePartDataSource(this));
+        }
+        return dh;
+    }
+
+    public Object getContent() throws MessagingException, IOException {
+        return getDataHandler().getContent();
+    }
+
+    public void setDataHandler(DataHandler handler) throws MessagingException {
+        dh = handler;
+        // if we have a handler override, then we need to invalidate any content
+        // headers that define the types.  This information will be derived from the
+        // data heander unless subsequently overridden.
+        removeHeader("Content-Type");
+        removeHeader("Content-Transfer-Encoding");
+
+    }
+
+    public void setContent(Object content, String type) throws MessagingException {
+        // Multipart content needs to be handled separately.
+        if (content instanceof Multipart) {
+            setContent((Multipart)content);
+        }
+        else {
+            setDataHandler(new DataHandler(content, type));
+        }
+
+    }
+
+    public void setText(String text) throws MessagingException {
+        setText(text, null);
+    }
+
+    public void setText(String text, String charset) throws MessagingException {
+        // the default subtype is plain text.
+        setText(text, charset, "plain");
+    }
+
+
+    public void setText(String text, String charset, String subtype) throws MessagingException {
+        // we need to sort out the character set if one is not provided.
+        if (charset == null) {
+            // if we have non us-ascii characters here, we need to adjust this.
+            if (!ASCIIUtil.isAscii(text)) {
+                charset = MimeUtility.getDefaultMIMECharset();
+            }
+            else {
+                charset = "us-ascii";
+            }
+        }
+        setContent(text, "text/plain; charset=" + MimeUtility.quote(charset, HeaderTokenizer.MIME));
+    }
+
+    public void setContent(Multipart part) throws MessagingException {
+        setDataHandler(new DataHandler(part, part.getContentType()));
+        part.setParent(this);
+    }
+
+    public void writeTo(OutputStream out) throws IOException, MessagingException {
+        headers.writeTo(out, null);
+        // add the separater between the headers and the data portion.
+        out.write('\r');
+        out.write('\n');
+        // we need to process this using the transfer encoding type
+        OutputStream encodingStream = MimeUtility.encode(out, getEncoding());
+        getDataHandler().writeTo(encodingStream);
+        encodingStream.flush();
+    }
+
+    public String[] getHeader(String name) throws MessagingException {
+        return headers.getHeader(name);
+    }
+
+    public String getHeader(String name, String delimiter) throws MessagingException {
+        return headers.getHeader(name, delimiter);
+    }
+
+    public void setHeader(String name, String value) throws MessagingException {
+        headers.setHeader(name, value);
+    }
+
+    /**
+     * Conditionally set or remove a named header.  If the new value
+     * is null, the header is removed.
+     *
+     * @param name   The header name.
+     * @param value  The new header value.  A null value causes the header to be
+     *               removed.
+     *
+     * @exception MessagingException
+     */
+    private void setOrRemoveHeader(String name, String value) throws MessagingException {
+        if (value == null) {
+            headers.removeHeader(name);
+        }
+        else {
+            headers.setHeader(name, value);
+        }
+    }
+
+    public void addHeader(String name, String value) throws MessagingException {
+        headers.addHeader(name, value);
+    }
+
+    public void removeHeader(String name) throws MessagingException {
+        headers.removeHeader(name);
+    }
+
+    public Enumeration getAllHeaders() throws MessagingException {
+        return headers.getAllHeaders();
+    }
+
+    public Enumeration getMatchingHeaders(String[] name) throws MessagingException {
+        return headers.getMatchingHeaders(name);
+    }
+
+    public Enumeration getNonMatchingHeaders(String[] name) throws MessagingException {
+        return headers.getNonMatchingHeaders(name);
+    }
+
+    public void addHeaderLine(String line) throws MessagingException {
+        headers.addHeaderLine(line);
+    }
+
+    public Enumeration getAllHeaderLines() throws MessagingException {
+        return headers.getAllHeaderLines();
+    }
+
+    public Enumeration getMatchingHeaderLines(String[] names) throws MessagingException {
+        return headers.getMatchingHeaderLines(names);
+    }
+
+    public Enumeration getNonMatchingHeaderLines(String[] names) throws MessagingException {
+        return headers.getNonMatchingHeaderLines(names);
+    }
+
+    protected void updateHeaders() throws MessagingException {
+        DataHandler handler = getDataHandler();
+
+        try {
+            // figure out the content type.  If not set, we'll need to figure this out.
+            String type = dh.getContentType();
+            // parse this content type out so we can do matches/compares.
+            ContentType content = new ContentType(type);
+            // is this a multipart content?
+            if (content.match("multipart/*")) {
+                // the content is suppose to be a MimeMultipart.  Ping it to update it's headers as well.
+                try {
+                    MimeMultipart part = (MimeMultipart)handler.getContent();
+                    part.updateHeaders();
+                } catch (ClassCastException e) {
+                    throw new MessagingException("Message content is not MimeMultipart", e);
+                }
+            }
+            else if (!content.match("message/rfc822")) {
+                // simple part, we need to update the header type information
+                // if no encoding is set yet, figure this out from the data handler.
+                if (getSingleHeader("Content-Transfer-Encoding") == null) {
+                    setHeader("Content-Transfer-Encoding", MimeUtility.getEncoding(handler));
+                }
+
+                // is a content type header set?  Check the property to see if we need to set this.
+                if (getHeader("Content-Type") == null) {
+                    if (SessionUtil.getBooleanProperty(MIME_SETDEFAULTTEXTCHARSET, true)) {
+                        // is this a text type?  Figure out the encoding and make sure it is set.
+                        if (content.match("text/*")) {
+                            // the charset should be specified as a parameter on the MIME type.  If not there,
+                            // try to figure one out.
+                            if (content.getParameter("charset") == null) {
+
+                                String encoding = getEncoding();
+                                // if we're sending this as 7-bit ASCII, our character set need to be
+                                // compatible.
+                                if (encoding != null && encoding.equalsIgnoreCase("7bit")) {
+                                    content.setParameter("charset", "us-ascii");
+                                }
+                                else {
+                                    // get the global default.
+                                    content.setParameter("charset", MimeUtility.getDefaultMIMECharset());
+                                }
+                            }
+                        }
+                    }
+                }
+            }
+
+            // if we don't have a content type header, then create one.
+            if (getSingleHeader("Content-Type") == null) {
+                // get the disposition header, and if it is there, copy the filename parameter into the
+                // name parameter of the type.
+                String disp = getHeader("Content-Disposition", null);
+                if (disp != null) {
+                    // parse up the string value of the disposition
+                    ContentDisposition disposition = new ContentDisposition(disp);
+                    // now check for a filename value
+                    String filename = disposition.getParameter("filename");
+                    // copy and rename the parameter, if it exists.
+                    if (filename != null) {
+                        content.setParameter("name", filename);
+                    }
+                }
+                // set the header with the updated content type information.
+                setHeader("Content-Type", content.toString());
+            }
+
+        } catch (IOException e) {
+            throw new MessagingException("Error updating message headers", e);
+        }
+    }
+
+    private String getSingleHeader(String name) throws MessagingException {
+        String[] values = getHeader(name);
+        if (values == null || values.length == 0) {
+            return null;
+        } else {
+            return values[0];
+        }
+    }
+
+
+    /**
+     * Attach a file to this body part from a File object.
+     *
+     * @param file   The source File object.
+     *
+     * @exception IOException
+     * @exception MessagingException
+     */
+    public void attachFile(File file) throws IOException, MessagingException {
+    	FileDataSource dataSource = new FileDataSource(file);
+        setDataHandler(new DataHandler(dataSource));
+        setFileName(dataSource.getName());
+    }
+
+
+    /**
+     * Attach a file to this body part from a file name.
+     *
+     * @param file   The source file name.
+     *
+     * @exception IOException
+     * @exception MessagingException
+     */
+    public void attachFile(String file) throws IOException, MessagingException {
+        // just create a File object and attach.
+        attachFile(new File(file));
+    }
+
+
+    /**
+     * Save the body part content to a given target file.
+     *
+     * @param file   The File object used to store the information.
+     *
+     * @exception IOException
+     * @exception MessagingException
+     */
+    public void saveFile(File file) throws IOException, MessagingException {
+    	OutputStream out = new BufferedOutputStream(new FileOutputStream(file));
+        // we need to read the data in to write it out (sigh).
+        InputStream in = getInputStream();
+        try {
+            byte[] buffer = new byte[8192];
+	        int length;
+	        while ((length = in.read(buffer)) > 0) {
+         		out.write(buffer, 0, length);
+            }
+        }
+        finally {
+            // make sure all of the streams are closed before we return
+            if (in != null) {
+                in.close();
+            }
+            if (out != null) {
+                out.close();
+            }
+        }
+    }
+
+
+    /**
+     * Save the body part content to a given target file.
+     *
+     * @param file   The file name used to store the information.
+     *
+     * @exception IOException
+     * @exception MessagingException
+     */
+    public void saveFile(String file) throws IOException, MessagingException {
+        saveFile(new File(file));
+    }
+}

Propchange: geronimo/specs/trunk/geronimo-spec-javamail-1.4/src/main/java/javax/mail/internet/MimeBodyPart.java
------------------------------------------------------------------------------
    svn:eol-style = native

Propchange: geronimo/specs/trunk/geronimo-spec-javamail-1.4/src/main/java/javax/mail/internet/MimeBodyPart.java
------------------------------------------------------------------------------
    svn:keywords = Date Revision

Propchange: geronimo/specs/trunk/geronimo-spec-javamail-1.4/src/main/java/javax/mail/internet/MimeBodyPart.java
------------------------------------------------------------------------------
    svn:mime-type = text/plain



Mime
View raw message