001    /*
002     * Licensed to the Apache Software Foundation (ASF) under one
003     * or more contributor license agreements.  See the NOTICE file
004     * distributed with this work for additional information
005     * regarding copyright ownership.  The ASF licenses this file
006     * to you under the Apache License, Version 2.0 (the
007     * "License"); you may not use this file except in compliance
008     * with the License.  You may obtain a copy of the License at
009     *
010     *  http://www.apache.org/licenses/LICENSE-2.0
011     *
012     * Unless required by applicable law or agreed to in writing,
013     * software distributed under the License is distributed on an
014     * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
015     * KIND, either express or implied.  See the License for the
016     * specific language governing permissions and limitations
017     * under the License.
018     */
019    
020    package javax.mail.internet;
021    
022    import java.util.Collections;
023    import java.util.Enumeration;
024    import java.util.HashMap;
025    import java.util.Iterator;
026    import java.util.Map;
027    import java.util.StringTokenizer;
028    import java.util.List;
029    import java.util.ArrayList;// Represents lists in things like
030    
031    import org.apache.geronimo.mail.util.ASCIIUtil;
032    import org.apache.geronimo.mail.util.RFC2231Encoder;
033    import org.apache.geronimo.mail.util.SessionUtil;
034    
035    // Content-Type: text/plain;charset=klingon
036    //
037    // The ;charset=klingon is the parameter list, may have more of them with ';'
038    
039    /**
040     * @version $Rev: 467553 $ $Date: 2006-10-25 06:01:51 +0200 (Mi, 25. Okt 2006) $
041     */
042    public class ParameterList {
043        private static final String MIME_ENCODEPARAMETERS = "mail.mime.encodeparameters";
044        private static final String MIME_DECODEPARAMETERS = "mail.mime.decodeparameters";
045        private static final String MIME_DECODEPARAMETERS_STRICT = "mail.mime.decodeparameters.strict";
046    
047        private static final int HEADER_SIZE_LIMIT = 76;
048    
049        private Map _parameters = new HashMap();
050    
051        private boolean encodeParameters = false;
052        private boolean decodeParameters = false;
053        private boolean decodeParametersStrict = false;
054    
055        public ParameterList() {
056            // figure out how parameter handling is to be performed.
057            getInitialProperties();
058        }
059    
060        public ParameterList(String list) throws ParseException {
061            // figure out how parameter handling is to be performed.
062            getInitialProperties();
063            // get a token parser for the type information
064            HeaderTokenizer tokenizer = new HeaderTokenizer(list, HeaderTokenizer.MIME);
065            while (true) {
066                HeaderTokenizer.Token token = tokenizer.next();
067    
068                switch (token.getType()) {
069                    // the EOF token terminates parsing.
070                    case HeaderTokenizer.Token.EOF:
071                        return;
072    
073                    // each new parameter is separated by a semicolon, including the first, which separates
074                    // the parameters from the main part of the header.
075                    case ';':
076                        // the next token needs to be a parameter name
077                        token = tokenizer.next();
078                        // allow a trailing semicolon on the parameters.
079                        if (token.getType() == HeaderTokenizer.Token.EOF) {
080                            return;
081                        }
082    
083                        if (token.getType() != HeaderTokenizer.Token.ATOM) {
084                            throw new ParseException("Invalid parameter name: " + token.getValue());
085                        }
086    
087                        // get the parameter name as a lower case version for better mapping.
088                        String name = token.getValue().toLowerCase();
089    
090                        token = tokenizer.next();
091    
092                        // parameters are name=value, so we must have the "=" here.
093                        if (token.getType() != '=') {
094                            throw new ParseException("Missing '='");
095                        }
096    
097                        // now the value, which may be an atom or a literal
098                        token = tokenizer.next();
099    
100                        if (token.getType() != HeaderTokenizer.Token.ATOM && token.getType() != HeaderTokenizer.Token.QUOTEDSTRING) {
101                            throw new ParseException("Invalid parameter value: " + token.getValue());
102                        }
103    
104                        String value = token.getValue();
105                        String encodedValue = null;
106    
107                        // we might have to do some additional decoding.  A name that ends with "*"
108                        // is marked as being encoded, so if requested, we decode the value.
109                        if (decodeParameters && name.endsWith("*")) {
110                            // the name needs to be pruned of the marker, and we need to decode the value.
111                            name = name.substring(0, name.length() - 1);
112                            // get a new decoder
113                            RFC2231Encoder decoder = new RFC2231Encoder(HeaderTokenizer.MIME);
114    
115                            try {
116                                // decode the value
117                                encodedValue = decoder.decode(value);
118                            } catch (Exception e) {
119                                // if we're doing things strictly, then raise a parsing exception for errors.
120                                // otherwise, leave the value in its current state.
121                                if (decodeParametersStrict) {
122                                    throw new ParseException("Invalid RFC2231 encoded parameter");
123                                }
124                            }
125                        }
126                        _parameters.put(name, new ParameterValue(name, value, encodedValue));
127    
128                        break;
129    
130                    default:
131                        throw new ParseException("Missing ';'");
132    
133                }
134            }
135        }
136    
137        /**
138         * Get the initial parameters that control parsing and values.
139         * These parameters are controlled by System properties.
140         */
141        private void getInitialProperties() {
142            decodeParameters = SessionUtil.getBooleanProperty(MIME_DECODEPARAMETERS, false);
143            decodeParametersStrict = SessionUtil.getBooleanProperty(MIME_DECODEPARAMETERS_STRICT, false);
144            encodeParameters = SessionUtil.getBooleanProperty(MIME_ENCODEPARAMETERS, false);
145        }
146    
147        public int size() {
148            return _parameters.size();
149        }
150    
151        public String get(String name) {
152            ParameterValue value = (ParameterValue)_parameters.get(name.toLowerCase());
153            if (value != null) {
154                return value.value;
155            }
156            return null;
157        }
158    
159        public void set(String name, String value) {
160            name = name.toLowerCase();
161            _parameters.put(name, new ParameterValue(name, value));
162        }
163    
164        public void remove(String name) {
165            _parameters.remove(name);
166        }
167    
168        public Enumeration getNames() {
169            return Collections.enumeration(_parameters.keySet());
170        }
171    
172        public String toString() {
173            // we need to perform folding, but out starting point is 0.
174            return toString(0);
175        }
176    
177        public String toString(int used) {
178            StringBuffer stringValue = new StringBuffer();
179    
180            Iterator values = _parameters.values().iterator();
181    
182            while (values.hasNext()) {
183                ParameterValue parm = (ParameterValue)values.next();
184                // get the values we're going to encode in here.
185                String name = parm.getEncodedName();
186                String value = parm.toString();
187    
188                // add the semicolon separator.  We also add a blank so that folding/unfolding rules can be used.
189                stringValue.append("; ");
190                used += 2;
191    
192                // too big for the current header line?
193                if ((used + name.length() + value.length() + 1) > HEADER_SIZE_LIMIT) {
194                    // and a CRLF-whitespace combo.
195                    stringValue.append("\r\n ");
196                    // reset the counter for a fresh line
197                    used = 3;
198                }
199                // now add the keyword/value pair.
200                stringValue.append(name);
201                stringValue.append("=");
202    
203                used += name.length() + 1;
204    
205                // we're not out of the woods yet.  It is possible that the keyword/value pair by itself might
206                // be too long for a single line.  If that's the case, the we need to fold the value, if possible
207                if (used + value.length() > HEADER_SIZE_LIMIT) {
208                    String foldedValue = ASCIIUtil.fold(used, value);
209    
210                    stringValue.append(foldedValue);
211    
212                    // now we need to sort out how much of the current line is in use.
213                    int lastLineBreak = foldedValue.lastIndexOf('\n');
214    
215                    if (lastLineBreak != -1) {
216                        used = foldedValue.length() - lastLineBreak + 1;
217                    }
218                    else {
219                        used += foldedValue.length();
220                    }
221                }
222                else {
223                    // no folding required, just append.
224                    stringValue.append(value);
225                    used += value.length();
226                }
227            }
228    
229            return stringValue.toString();
230        }
231    
232    
233        /**
234         * Utility class for representing parameter values in the list.
235         */
236        class ParameterValue {
237            public String name;              // the name of the parameter
238            public String value;             // the original set value
239            public String encodedValue;      // an encoded value, if encoding is requested.
240    
241            public ParameterValue(String name, String value) {
242                this.name = name;
243                this.value = value;
244                this.encodedValue = null;
245            }
246    
247            public ParameterValue(String name, String value, String encodedValue) {
248                this.name = name;
249                this.value = value;
250                this.encodedValue = encodedValue;
251            }
252    
253            public String toString() {
254                if (encodedValue != null) {
255                    return MimeUtility.quote(encodedValue, HeaderTokenizer.MIME);
256                }
257                return MimeUtility.quote(value, HeaderTokenizer.MIME);
258            }
259    
260            public String getEncodedName() {
261                if (encodedValue != null) {
262                    return name + "*";
263                }
264                return name;
265            }
266        }
267    }