source: contrib/MailArchiver/sources/vendor/mime4j/apache-mime4j-0.7-SNAPSHOT-20110327.010440-17/dom/src/test/java/org/apache/james/mime4j/dom/MessageParserTest.java @ 6785

Revision 6785, 8.8 KB checked in by rafaelraymundo, 12 years ago (diff)

Ticket #2946 - Liberado codigo do MailArchiver?. Documentação na subpasta DOCS.

Line 
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.dom;
21
22import java.io.File;
23import java.io.FileNotFoundException;
24import java.io.FileOutputStream;
25import java.io.IOException;
26import java.io.InputStream;
27import java.net.JarURLConnection;
28import java.net.URISyntaxException;
29import java.net.URL;
30import java.util.Enumeration;
31import java.util.List;
32import java.util.jar.JarEntry;
33import java.util.jar.JarFile;
34
35import junit.framework.Test;
36import junit.framework.TestCase;
37import junit.framework.TestSuite;
38
39import org.apache.commons.io.IOUtils;
40import org.apache.james.mime4j.dom.BinaryBody;
41import org.apache.james.mime4j.dom.Body;
42import org.apache.james.mime4j.dom.Entity;
43import org.apache.james.mime4j.dom.Multipart;
44import org.apache.james.mime4j.dom.TextBody;
45import org.apache.james.mime4j.dom.field.Field;
46import org.apache.james.mime4j.field.FieldsTest;
47import org.apache.james.mime4j.message.MessageImpl;
48import org.apache.james.mime4j.message.MimeBuilder;
49import org.apache.james.mime4j.stream.MimeEntityConfig;
50import org.apache.james.mime4j.util.CharsetUtil;
51
52public class MessageParserTest extends TestCase {
53   
54    private URL url;
55
56    public MessageParserTest(String name, URL url) {
57        super(name);
58        this.url = url;
59    }
60
61    public static Test suite() throws IOException, URISyntaxException {
62        return new MessageParserTestSuite();
63    }
64   
65    static class MessageParserTestSuite extends TestSuite {
66       
67        private static final String TESTS_FOLDER = "/testmsgs";
68
69        public MessageParserTestSuite() throws IOException, URISyntaxException {
70            URL resource = MessageParserTestSuite.class.getResource(TESTS_FOLDER);
71            if (resource != null) {
72                if (resource.getProtocol().equalsIgnoreCase("file")) {
73                    File dir = new File(resource.toURI());
74                    File[] files = dir.listFiles();
75                   
76                    for (File f : files) {
77                        if (f.getName().endsWith(".msg")) {
78                            addTest(new MessageParserTest(f.getName(),
79                                    f.toURL()));
80                        }
81                    }
82                } else if (resource.getProtocol().equalsIgnoreCase("jar")) {
83                    JarURLConnection conn = (JarURLConnection) resource.openConnection();
84                    JarFile jar = conn.getJarFile();
85                    for (Enumeration<JarEntry> it = jar.entries(); it.hasMoreElements(); ) {
86                        JarEntry entry = it.nextElement();
87                        String s = "/" + entry.toString();
88                        File f = new File(s);
89                        if (s.startsWith(TESTS_FOLDER) && s.endsWith(".msg")) {
90                            addTest(new MessageParserTest(f.getName(),
91                                    new URL("jar:file:" + jar.getName() + "!" + s)));
92                        }
93                    }
94                }
95            }
96        }
97       
98    }
99   
100    @Override
101    protected void runTest() throws IOException {
102        MimeEntityConfig config = new MimeEntityConfig();
103        if (getName().startsWith("malformedHeaderStartsBody")) {
104            config.setMalformedHeaderStartsBody(true);
105        }
106        config.setMaxLineLen(-1);
107        Message m = MimeBuilder.DEFAULT.parse(url.openStream(), config);
108       
109        String s = url.toString();
110        String prefix = s.substring(0, s.lastIndexOf('.'));
111        URL xmlFileUrl = new URL(prefix + "_decoded.xml");
112       
113        String result = getStructure(m, prefix, "1");
114        try {
115                String expected = IOUtils.toString(xmlFileUrl.openStream(), "ISO8859-1");
116                assertEquals(expected, result);
117        } catch (FileNotFoundException ex) {
118                IOUtils.write(result, new FileOutputStream(xmlFileUrl.getPath()+".expected"));
119                fail("Expected file created.");
120        }
121    }
122
123    private String escape(String s) {
124        s = s.replaceAll("&", "&amp;");
125        s = s.replaceAll("<", "&lt;");
126        return s.replaceAll(">", "&gt;");
127    }
128
129    private String getStructure(Entity e, String prefix, String id)
130            throws IOException {
131       
132        StringBuilder sb = new StringBuilder();
133       
134        if (e instanceof MessageImpl) {
135            sb.append("<message>\r\n");
136        } else {
137            sb.append("<body-part>\r\n");
138        }           
139       
140        sb.append("<header>\r\n");
141        for (Field field : e.getHeader().getFields()) {
142            sb.append("<field>\r\n"
143                    + escape(FieldsTest.decode(field))
144                    + "</field>\r\n");
145        }
146        sb.append("</header>\r\n");
147       
148        if (e.getBody() instanceof Multipart) {
149            sb.append("<multipart>\r\n");
150           
151            Multipart multipart =(Multipart) e.getBody();
152            List<Entity> parts = multipart.getBodyParts();
153
154            if (multipart.getPreamble() != null) {
155                sb.append("<preamble>\r\n");
156                sb.append(escape(multipart.getPreamble()));
157                sb.append("</preamble>\r\n");
158            }
159           
160            int i = 1;
161            for (Entity bodyPart : parts) {
162                sb.append(getStructure(bodyPart, prefix, id + "_" + (i++)));
163            }
164
165            if (multipart.getEpilogue() != null) {
166                sb.append("<epilogue>\r\n");
167                sb.append(escape(multipart.getEpilogue()));
168                sb.append("</epilogue>\r\n");
169            }
170           
171            sb.append("</multipart>\r\n");
172           
173        } else if (e.getBody() instanceof MessageImpl) {
174            sb.append(getStructure((MessageImpl) e.getBody(), prefix, id + "_1"));
175        } else {
176            Body b = e.getBody();
177            String s = prefix + "_decoded_" + id
178                            + (b instanceof TextBody ? ".txt" : ".bin");
179            String tag = b instanceof TextBody ? "text-body" : "binary-body";
180            File f = new File(s);
181            sb.append("<" + tag + " name=\"" + f.getName() + "\"/>\r\n");
182            URL expectedUrl = new URL(s);
183               
184            if (b instanceof TextBody) {
185                String charset = CharsetUtil.toJavaCharset(e.getCharset());
186                if (charset == null) {
187                    charset = "ISO8859-1";
188                }
189
190                String s2 = IOUtils.toString(((TextBody) b).getReader());
191                try {
192                        String s1 = IOUtils.toString(expectedUrl.openStream(), charset);
193                        assertEquals(f.getName(), s1, s2);
194                } catch (FileNotFoundException ex) {
195                        IOUtils.write(s2, new FileOutputStream(expectedUrl.getPath()+".expected"));
196                        fail("Expected file created.");
197                }
198            } else {
199                try {
200                        assertEqualsBinary(f.getName(), expectedUrl.openStream(),
201                        ((BinaryBody) b).getInputStream());
202                } catch (FileNotFoundException ex) {
203                        IOUtils.copy(((BinaryBody) b).getInputStream(), new FileOutputStream(expectedUrl.getPath()+".expected"));
204                        fail("Expected file created.");
205                }
206            }
207        }
208       
209        if (e instanceof MessageImpl) {
210            sb.append("</message>\r\n");
211        } else {
212            sb.append("</body-part>\r\n");
213        }           
214       
215        return sb.toString();
216    }
217
218    private void assertEqualsBinary(String msg, InputStream a, InputStream b)
219            throws IOException {
220       
221        int pos = 0;
222        while (true) {
223            int b1 = a.read();
224            int b2 = b.read();
225            assertEquals(msg + " (Position " + (++pos) + ")", b1, b2);
226           
227            if (b1 == -1 || b2 == -1) {
228                break;
229            }
230        }
231    }
232}
Note: See TracBrowser for help on using the repository browser.