DelegatingFieldParser.java revision 4ebb916ddca5f59d4f854f104fca0de6e0dda706
1/*
2 *  Copyright 2006 the mime4j project
3 *
4 *  Licensed under the Apache License, Version 2.0 (the "License");
5 *  you may not use this file except in compliance with the License.
6 *  You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 *  Unless required by applicable law or agreed to in writing, software
11 *  distributed under the License is distributed on an "AS IS" BASIS,
12 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 *  See the License for the specific language governing permissions and
14 *  limitations under the License.
15 */
16package org.apache.james.mime4j.field;
17
18import java.util.HashMap;
19import java.util.Map;
20
21public class DelegatingFieldParser implements FieldParser {
22
23    private Map<String, FieldParser> parsers = new HashMap<String, FieldParser>();
24    private FieldParser defaultParser = new UnstructuredField.Parser();
25
26    /**
27     * Sets the parser used for the field named <code>name</code>.
28     * @param name the name of the field
29     * @param parser the parser for fields named <code>name</code>
30     */
31    public void setFieldParser(final String name, final FieldParser parser) {
32        parsers.put(name.toLowerCase(), parser);
33    }
34
35    public FieldParser getParser(final String name) {
36        final FieldParser field = parsers.get(name.toLowerCase());
37        if(field==null) {
38            return defaultParser;
39        }
40        return field;
41    }
42
43    public Field parse(final String name, final String body, final String raw) {
44        final FieldParser parser = getParser(name);
45        return parser.parse(name, body, raw);
46    }
47}
48