1/****************************************************************
2 * Licensed to the Apache Software Foundation (ASF) under one   *
3 * or more contributor license agreements.  See the NOTICE file *
4 * distributed with this work for additional information        *
5 * regarding copyright ownership.  The ASF licenses this file   *
6 * to you under the Apache License, Version 2.0 (the            *
7 * "License"); you may not use this file except in compliance   *
8 * with the License.  You may obtain a copy of the License at   *
9 *                                                              *
10 *   http://www.apache.org/licenses/LICENSE-2.0                 *
11 *                                                              *
12 * Unless required by applicable law or agreed to in writing,   *
13 * software distributed under the License is distributed on an  *
14 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY       *
15 * KIND, either express or implied.  See the License for the    *
16 * specific language governing permissions and limitations      *
17 * under the License.                                           *
18 ****************************************************************/
19
20package org.apache.james.mime4j.message;
21
22import java.io.BufferedWriter;
23import java.io.IOException;
24import java.io.InputStream;
25import java.io.OutputStream;
26import java.io.OutputStreamWriter;
27import java.util.Collections;
28import java.util.HashMap;
29import java.util.Iterator;
30import java.util.LinkedList;
31import java.util.List;
32
33import org.apache.james.mime4j.AbstractContentHandler;
34import org.apache.james.mime4j.MimeStreamParser;
35import org.apache.james.mime4j.field.ContentTypeField;
36import org.apache.james.mime4j.field.Field;
37import org.apache.james.mime4j.util.CharsetUtil;
38
39
40/**
41 * The header of an entity (see RFC 2045).
42 *
43 *
44 * @version $Id: Header.java,v 1.3 2004/10/04 15:36:44 ntherning Exp $
45 */
46public class Header {
47    private List<Field> fields = new LinkedList<Field>();
48    private HashMap<String, List<Field>> fieldMap = new HashMap<String, List<Field>>();
49
50    /**
51     * Creates a new empty <code>Header</code>.
52     */
53    public Header() {
54    }
55
56    /**
57     * Creates a new <code>Header</code> from the specified stream.
58     *
59     * @param is the stream to read the header from.
60     */
61    public Header(InputStream is) throws IOException {
62        final MimeStreamParser parser = new MimeStreamParser();
63        parser.setContentHandler(new AbstractContentHandler() {
64            @Override
65            public void endHeader() {
66                parser.stop();
67            }
68            @Override
69            public void field(String fieldData) {
70                addField(Field.parse(fieldData));
71            }
72        });
73        parser.parse(is);
74    }
75
76    /**
77     * Adds a field to the end of the list of fields.
78     *
79     * @param field the field to add.
80     */
81    public void addField(Field field) {
82        List<Field> values = fieldMap.get(field.getName().toLowerCase());
83        if (values == null) {
84            values = new LinkedList<Field>();
85            fieldMap.put(field.getName().toLowerCase(), values);
86        }
87        values.add(field);
88        fields.add(field);
89    }
90
91    /**
92     * Gets the fields of this header. The returned list will not be
93     * modifiable.
94     *
95     * @return the list of <code>Field</code> objects.
96     */
97    public List<Field> getFields() {
98        return Collections.unmodifiableList(fields);
99    }
100
101    /**
102     * Gets a <code>Field</code> given a field name. If there are multiple
103     * such fields defined in this header the first one will be returned.
104     *
105     * @param name the field name (e.g. From, Subject).
106     * @return the field or <code>null</code> if none found.
107     */
108    public Field getField(String name) {
109        List<Field> l = fieldMap.get(name.toLowerCase());
110        if (l != null && !l.isEmpty()) {
111            return l.get(0);
112        }
113        return null;
114    }
115
116    /**
117     * Gets all <code>Field</code>s having the specified field name.
118     *
119     * @param name the field name (e.g. From, Subject).
120     * @return the list of fields.
121     */
122    public List<Field> getFields(String name) {
123        List<Field> l = fieldMap.get(name.toLowerCase());
124        return Collections.unmodifiableList(l);
125    }
126
127    /**
128     * Return Header Object as String representation. Each headerline is
129     * seperated by "\r\n"
130     *
131     * @return headers
132     */
133    @Override
134    public String toString() {
135        StringBuffer str = new StringBuffer();
136        for (Iterator<Field> it = fields.iterator(); it.hasNext();) {
137            str.append(it.next().toString());
138            str.append("\r\n");
139        }
140        return str.toString();
141    }
142
143
144    /**
145     * Write the Header to the given OutputStream
146     *
147     * @param out the OutputStream to write to
148     * @throws IOException
149     */
150    public void writeTo(OutputStream out) throws IOException {
151        String charString = ((ContentTypeField) getField(Field.CONTENT_TYPE)).getCharset();
152
153        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(out, CharsetUtil.getCharset(charString)),8192);
154        writer.write(toString()+ "\r\n");
155        writer.flush();
156    }
157
158}
159