You are viewing a plain text version of this content. The canonical link for it is here.
Posted to server-dev@james.apache.org by ol...@apache.org on 2008/09/20 20:54:15 UTC

svn commit: r697409 [1/2] - in /james/mime4j/trunk/src: main/java/org/apache/james/mime4j/io/ main/java/org/apache/james/mime4j/message/ main/java/org/apache/james/mime4j/parser/ test/java/org/apache/james/mime4j/message/ test/java/org/apache/james/mim...

Author: olegk
Date: Sat Sep 20 11:54:15 2008
New Revision: 697409

URL: http://svn.apache.org/viewvc?rev=697409&view=rev
Log:
MIME4J-57: enforce a limit on the maximum line length

Added:
    james/mime4j/trunk/src/main/java/org/apache/james/mime4j/parser/MimeEntityConfig.java   (with props)
Modified:
    james/mime4j/trunk/src/main/java/org/apache/james/mime4j/io/BufferedLineReaderInputStream.java
    james/mime4j/trunk/src/main/java/org/apache/james/mime4j/io/LineReaderInputStreamAdaptor.java
    james/mime4j/trunk/src/main/java/org/apache/james/mime4j/message/Message.java
    james/mime4j/trunk/src/main/java/org/apache/james/mime4j/parser/AbstractEntity.java
    james/mime4j/trunk/src/main/java/org/apache/james/mime4j/parser/MimeEntity.java
    james/mime4j/trunk/src/main/java/org/apache/james/mime4j/parser/MimeStreamParser.java
    james/mime4j/trunk/src/main/java/org/apache/james/mime4j/parser/MimeTokenStream.java
    james/mime4j/trunk/src/test/java/org/apache/james/mime4j/message/ExampleMessagesRoundtripTest.java
    james/mime4j/trunk/src/test/java/org/apache/james/mime4j/message/MessageParserTest.java
    james/mime4j/trunk/src/test/java/org/apache/james/mime4j/parser/MimeStreamParserExampleMessagesTest.java
    james/mime4j/trunk/src/test/java/org/apache/james/mime4j/stream/BufferedLineReaderInputStreamTest.java
    james/mime4j/trunk/src/test/java/org/apache/james/mime4j/stream/LineReaderInputStreamAdaptorTest.java

Modified: james/mime4j/trunk/src/main/java/org/apache/james/mime4j/io/BufferedLineReaderInputStream.java
URL: http://svn.apache.org/viewvc/james/mime4j/trunk/src/main/java/org/apache/james/mime4j/io/BufferedLineReaderInputStream.java?rev=697409&r1=697408&r2=697409&view=diff
==============================================================================
--- james/mime4j/trunk/src/main/java/org/apache/james/mime4j/io/BufferedLineReaderInputStream.java (original)
+++ james/mime4j/trunk/src/main/java/org/apache/james/mime4j/io/BufferedLineReaderInputStream.java Sat Sep 20 11:54:15 2008
@@ -1,304 +1,319 @@
-/****************************************************************
- * Licensed to the Apache Software Foundation (ASF) under one   *
- * or more contributor license agreements.  See the NOTICE file *
- * distributed with this work for additional information        *
- * regarding copyright ownership.  The ASF licenses this file   *
- * to you 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 org.apache.james.mime4j.io;
-
-import org.apache.james.mime4j.util.ByteArrayBuffer;
-
-import java.io.IOException;
-import java.io.InputStream;
-
-/**
- * Input buffer that can be used to search for patterns using Quick Search 
- * algorithm in data read from an {@link InputStream}. 
- */
-public class BufferedLineReaderInputStream extends LineReaderInputStream {
-
-    private byte[] buffer;
-    
-    private int bufpos;
-    private int buflen;
-    
-    public BufferedLineReaderInputStream(final InputStream instream, int buffersize) {
-        super(instream);
-        if (instream == null) {
-            throw new IllegalArgumentException("Input stream may not be null");
-        }
-        if (buffersize <= 0) {
-            throw new IllegalArgumentException("Buffer size may not be negative or zero");
-        }
-        this.buffer = new byte[buffersize];
-        this.bufpos = 0;
-        this.buflen = 0;
-    }
-    
-    private void expand(int newlen) {
-        byte newbuffer[] = new byte[newlen];
-        int len = this.buflen - this.bufpos;
-        if (len > 0) {
-            System.arraycopy(this.buffer, this.bufpos, newbuffer, this.bufpos, len);
-        }
-        this.buffer = newbuffer;
-    }
-    
-    public void ensureCapacity(int len) {
-        if (len > this.buffer.length) {
-            expand(len);
-        }
-    }
-    
-    public int fillBuffer() throws IOException {
-        // compact the buffer if necessary
-        if (this.bufpos > 0) {
-            int len = this.buflen - this.bufpos;
-            if (len > 0) {
-                System.arraycopy(this.buffer, this.bufpos, this.buffer, 0, len);
-            }
-            this.bufpos = 0;
-            this.buflen = len;
-        }
-        int l;
-        int off = this.buflen;
-        int len = this.buffer.length - off;
-        l = in.read(this.buffer, off, len);
-        if (l == -1) {
-            return -1;
-        } else {
-            this.buflen = off + l;
-            return l;
-        }
-    }
-
-    public boolean hasBufferedData() {
-        return this.bufpos < this.buflen;
-    }
-
-    public int read() throws IOException {
-        int noRead = 0;
-        while (!hasBufferedData()) {
-            noRead = fillBuffer();
-            if (noRead == -1) {
-                return -1;
-            }
-        }
-        return this.buffer[this.bufpos++] & 0xff;
-    }
-    
-    public int read(final byte[] b, int off, int len) throws IOException {
-        if (b == null) {
-            return 0;
-        }
-        int noRead = 0;
-        while (!hasBufferedData()) {
-            noRead = fillBuffer();
-            if (noRead == -1) {
-                return -1;
-            }
-        }
-        int chunk = this.buflen - this.bufpos;
-        if (chunk > len) {
-            chunk = len;
-        }
-        System.arraycopy(this.buffer, this.bufpos, b, off, chunk);
-        this.bufpos += chunk;
-        return chunk;
-    }
-    
-    public int read(final byte[] b) throws IOException {
-        if (b == null) {
-            return 0;
-        }
-        return read(b, 0, b.length);
-    }
-    
-    public boolean markSupported() {
-        return false;
-    }
-
-    
-    public int readLine(final ByteArrayBuffer linebuf) throws IOException {
-        if (linebuf == null) {
-            throw new IllegalArgumentException("Buffer may not be null");
-        }
-        int total = 0;
-        boolean found = false;
-        int bytesRead = 0;
-        while (!found) {
-            if (!hasBufferedData()) {
-                bytesRead = fillBuffer();
-                if (bytesRead == -1) {
-                    break;
-                }
-            }
-            int i = indexOf((byte)'\n');
-            int chunk;
-            if (i != -1) {
-                found = true;
-                chunk = i + 1 - pos();
-            } else {
-                chunk = length();
-            }
-            if (chunk > 0) {
-                linebuf.append(buf(), pos(), chunk);
-                skip(chunk);
-                total += chunk;
-            }
-        }
-        if (total == 0 && bytesRead == -1) {
-            return -1;
-        } else {
-            return total;
-        }
-    }
-
-    /**
-     * Implements quick search algorithm as published by
-     * <p> 
-     * SUNDAY D.M., 1990, 
-     * A very fast substring search algorithm, 
-     * Communications of the ACM . 33(8):132-142.
-     * </p>
-     */
-    public int indexOf(final byte[] pattern, int off, int len) {
-        if (pattern == null) {
-            throw new IllegalArgumentException("Pattern may not be null");
-        }
-        if (off < this.bufpos || len < 0 || off + len > this.buflen) {
-            throw new IndexOutOfBoundsException();
-        }
-        if (len < pattern.length) {
-            return -1;
-        }
-        
-        int[] shiftTable = new int[256];
-        for (int i = 0; i < shiftTable.length; i++) {
-            shiftTable[i] = pattern.length + 1;
-        }
-        for (int i = 0; i < pattern.length; i++) {
-            int x = pattern[i] & 0xff;
-            shiftTable[x] = pattern.length - i;
-        }
-        
-        int j = 0;
-        while (j <= len - pattern.length) {
-            int cur = off + j;
-            boolean match = true;
-            for (int i = 0; i < pattern.length; i++) {
-                if (this.buffer[cur + i] != pattern[i]) {
-                    match = false;
-                    break;
-                }
-            }
-            if (match) {
-                return cur;
-            }
-            
-            int pos = cur + pattern.length; 
-            if (pos >= this.buffer.length) {
-                break;
-            }
-            int x = this.buffer[pos] & 0xff;
-            j += shiftTable[x];
-        }
-        return -1;
-    }
-    
-    /**
-     * Implements quick search algorithm as published by
-     * <p> 
-     * SUNDAY D.M., 1990, 
-     * A very fast substring search algorithm, 
-     * Communications of the ACM . 33(8):132-142.
-     * </p>
-     */
-    public int indexOf(final byte[] pattern) {
-        return indexOf(pattern, this.bufpos, this.buflen - this.bufpos);
-    }
-
-    public int indexOf(byte b, int off, int len) {
-        if (off < this.bufpos || len < 0 || off + len > this.buflen) {
-            throw new IndexOutOfBoundsException();
-        }
-        for (int i = off; i < off + len; i++) {
-            if (this.buffer[i] == b) {
-                return i;
-            }
-        }
-        return -1;
-    }
-    
-    public int indexOf(byte b) {
-        return indexOf(b, this.bufpos, this.buflen - this.bufpos);
-    }
-    
-    public byte charAt(int pos) {
-        if (pos < this.bufpos || pos > this.buflen) {
-            throw new IndexOutOfBoundsException();
-        }
-        return this.buffer[pos];
-    }
-    
-    public byte[] buf() {
-        return this.buffer;        
-    }
-    
-    public int pos() {
-        return this.bufpos;
-    }
-    
-    public int limit() {
-        return this.buflen;
-    }
-    
-    public int length() {
-        return this.buflen - this.bufpos;
-    }
-    
-    public int capacity() {
-        return this.buffer.length;
-    }
-    
-    public int skip(int n) {
-        int chunk = Math.min(n, this.buflen - this.bufpos);
-        this.bufpos += chunk; 
-        return chunk;
-    }
-
-    public void clear() {
-        this.bufpos = 0;
-        this.buflen = 0;
-    }
-    
-    public String toString() {
-        StringBuffer buffer = new StringBuffer();
-        buffer.append("[pos: ");
-        buffer.append(this.bufpos);
-        buffer.append("]");
-        buffer.append("[limit: ");
-        buffer.append(this.buflen);
-        buffer.append("]");
-        buffer.append("[");
-        for (int i = this.bufpos; i < this.buflen; i++) {
-            buffer.append((char) this.buffer[i]);
-        }
-        buffer.append("]");
-        return buffer.toString();
-    }
-
-}
+/****************************************************************
+ * Licensed to the Apache Software Foundation (ASF) under one   *
+ * or more contributor license agreements.  See the NOTICE file *
+ * distributed with this work for additional information        *
+ * regarding copyright ownership.  The ASF licenses this file   *
+ * to you 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 org.apache.james.mime4j.io;
+
+import org.apache.james.mime4j.util.ByteArrayBuffer;
+
+import java.io.IOException;
+import java.io.InputStream;
+
+/**
+ * Input buffer that can be used to search for patterns using Quick Search 
+ * algorithm in data read from an {@link InputStream}. 
+ */
+public class BufferedLineReaderInputStream extends LineReaderInputStream {
+
+    private byte[] buffer;
+    
+    private int bufpos;
+    private int buflen;
+    
+    private final int maxLineLen;
+    
+    public BufferedLineReaderInputStream(
+            final InputStream instream, 
+            int buffersize,
+            int maxLineLen) {
+        super(instream);
+        if (instream == null) {
+            throw new IllegalArgumentException("Input stream may not be null");
+        }
+        if (buffersize <= 0) {
+            throw new IllegalArgumentException("Buffer size may not be negative or zero");
+        }
+        this.buffer = new byte[buffersize];
+        this.bufpos = 0;
+        this.buflen = 0;
+        this.maxLineLen = maxLineLen;
+    }
+
+    public BufferedLineReaderInputStream(
+            final InputStream instream, 
+            int buffersize) {
+        this(instream, buffersize, -1);
+    }
+
+    private void expand(int newlen) {
+        byte newbuffer[] = new byte[newlen];
+        int len = this.buflen - this.bufpos;
+        if (len > 0) {
+            System.arraycopy(this.buffer, this.bufpos, newbuffer, this.bufpos, len);
+        }
+        this.buffer = newbuffer;
+    }
+    
+    public void ensureCapacity(int len) {
+        if (len > this.buffer.length) {
+            expand(len);
+        }
+    }
+    
+    public int fillBuffer() throws IOException {
+        // compact the buffer if necessary
+        if (this.bufpos > 0) {
+            int len = this.buflen - this.bufpos;
+            if (len > 0) {
+                System.arraycopy(this.buffer, this.bufpos, this.buffer, 0, len);
+            }
+            this.bufpos = 0;
+            this.buflen = len;
+        }
+        int l;
+        int off = this.buflen;
+        int len = this.buffer.length - off;
+        l = in.read(this.buffer, off, len);
+        if (l == -1) {
+            return -1;
+        } else {
+            this.buflen = off + l;
+            return l;
+        }
+    }
+
+    public boolean hasBufferedData() {
+        return this.bufpos < this.buflen;
+    }
+
+    public int read() throws IOException {
+        int noRead = 0;
+        while (!hasBufferedData()) {
+            noRead = fillBuffer();
+            if (noRead == -1) {
+                return -1;
+            }
+        }
+        return this.buffer[this.bufpos++] & 0xff;
+    }
+    
+    public int read(final byte[] b, int off, int len) throws IOException {
+        if (b == null) {
+            return 0;
+        }
+        int noRead = 0;
+        while (!hasBufferedData()) {
+            noRead = fillBuffer();
+            if (noRead == -1) {
+                return -1;
+            }
+        }
+        int chunk = this.buflen - this.bufpos;
+        if (chunk > len) {
+            chunk = len;
+        }
+        System.arraycopy(this.buffer, this.bufpos, b, off, chunk);
+        this.bufpos += chunk;
+        return chunk;
+    }
+    
+    public int read(final byte[] b) throws IOException {
+        if (b == null) {
+            return 0;
+        }
+        return read(b, 0, b.length);
+    }
+    
+    public boolean markSupported() {
+        return false;
+    }
+
+    
+    public int readLine(final ByteArrayBuffer dst) throws IOException {
+        if (dst == null) {
+            throw new IllegalArgumentException("Buffer may not be null");
+        }
+        int total = 0;
+        boolean found = false;
+        int bytesRead = 0;
+        while (!found) {
+            if (!hasBufferedData()) {
+                bytesRead = fillBuffer();
+                if (bytesRead == -1) {
+                    break;
+                }
+            }
+            int i = indexOf((byte)'\n');
+            int chunk;
+            if (i != -1) {
+                found = true;
+                chunk = i + 1 - pos();
+            } else {
+                chunk = length();
+            }
+            if (chunk > 0) {
+                dst.append(buf(), pos(), chunk);
+                skip(chunk);
+                total += chunk;
+            }
+            if (this.maxLineLen > 0 && dst.length() >= this.maxLineLen) {
+                throw new IOException("Maximum line length limit exceeded");
+            }
+        }
+        if (total == 0 && bytesRead == -1) {
+            return -1;
+        } else {
+            return total;
+        }
+    }
+
+    /**
+     * Implements quick search algorithm as published by
+     * <p> 
+     * SUNDAY D.M., 1990, 
+     * A very fast substring search algorithm, 
+     * Communications of the ACM . 33(8):132-142.
+     * </p>
+     */
+    public int indexOf(final byte[] pattern, int off, int len) {
+        if (pattern == null) {
+            throw new IllegalArgumentException("Pattern may not be null");
+        }
+        if (off < this.bufpos || len < 0 || off + len > this.buflen) {
+            throw new IndexOutOfBoundsException();
+        }
+        if (len < pattern.length) {
+            return -1;
+        }
+        
+        int[] shiftTable = new int[256];
+        for (int i = 0; i < shiftTable.length; i++) {
+            shiftTable[i] = pattern.length + 1;
+        }
+        for (int i = 0; i < pattern.length; i++) {
+            int x = pattern[i] & 0xff;
+            shiftTable[x] = pattern.length - i;
+        }
+        
+        int j = 0;
+        while (j <= len - pattern.length) {
+            int cur = off + j;
+            boolean match = true;
+            for (int i = 0; i < pattern.length; i++) {
+                if (this.buffer[cur + i] != pattern[i]) {
+                    match = false;
+                    break;
+                }
+            }
+            if (match) {
+                return cur;
+            }
+            
+            int pos = cur + pattern.length; 
+            if (pos >= this.buffer.length) {
+                break;
+            }
+            int x = this.buffer[pos] & 0xff;
+            j += shiftTable[x];
+        }
+        return -1;
+    }
+    
+    /**
+     * Implements quick search algorithm as published by
+     * <p> 
+     * SUNDAY D.M., 1990, 
+     * A very fast substring search algorithm, 
+     * Communications of the ACM . 33(8):132-142.
+     * </p>
+     */
+    public int indexOf(final byte[] pattern) {
+        return indexOf(pattern, this.bufpos, this.buflen - this.bufpos);
+    }
+
+    public int indexOf(byte b, int off, int len) {
+        if (off < this.bufpos || len < 0 || off + len > this.buflen) {
+            throw new IndexOutOfBoundsException();
+        }
+        for (int i = off; i < off + len; i++) {
+            if (this.buffer[i] == b) {
+                return i;
+            }
+        }
+        return -1;
+    }
+    
+    public int indexOf(byte b) {
+        return indexOf(b, this.bufpos, this.buflen - this.bufpos);
+    }
+    
+    public byte charAt(int pos) {
+        if (pos < this.bufpos || pos > this.buflen) {
+            throw new IndexOutOfBoundsException();
+        }
+        return this.buffer[pos];
+    }
+    
+    public byte[] buf() {
+        return this.buffer;        
+    }
+    
+    public int pos() {
+        return this.bufpos;
+    }
+    
+    public int limit() {
+        return this.buflen;
+    }
+    
+    public int length() {
+        return this.buflen - this.bufpos;
+    }
+    
+    public int capacity() {
+        return this.buffer.length;
+    }
+    
+    public int skip(int n) {
+        int chunk = Math.min(n, this.buflen - this.bufpos);
+        this.bufpos += chunk; 
+        return chunk;
+    }
+
+    public void clear() {
+        this.bufpos = 0;
+        this.buflen = 0;
+    }
+    
+    public String toString() {
+        StringBuffer buffer = new StringBuffer();
+        buffer.append("[pos: ");
+        buffer.append(this.bufpos);
+        buffer.append("]");
+        buffer.append("[limit: ");
+        buffer.append(this.buflen);
+        buffer.append("]");
+        buffer.append("[");
+        for (int i = this.bufpos; i < this.buflen; i++) {
+            buffer.append((char) this.buffer[i]);
+        }
+        buffer.append("]");
+        return buffer.toString();
+    }
+
+}

Modified: james/mime4j/trunk/src/main/java/org/apache/james/mime4j/io/LineReaderInputStreamAdaptor.java
URL: http://svn.apache.org/viewvc/james/mime4j/trunk/src/main/java/org/apache/james/mime4j/io/LineReaderInputStreamAdaptor.java?rev=697409&r1=697408&r2=697409&view=diff
==============================================================================
--- james/mime4j/trunk/src/main/java/org/apache/james/mime4j/io/LineReaderInputStreamAdaptor.java (original)
+++ james/mime4j/trunk/src/main/java/org/apache/james/mime4j/io/LineReaderInputStreamAdaptor.java Sat Sep 20 11:54:15 2008
@@ -1,103 +1,116 @@
-/****************************************************************
- * Licensed to the Apache Software Foundation (ASF) under one   *
- * or more contributor license agreements.  See the NOTICE file *
- * distributed with this work for additional information        *
- * regarding copyright ownership.  The ASF licenses this file   *
- * to you 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 org.apache.james.mime4j.io;
-
-import org.apache.james.mime4j.util.ByteArrayBuffer;
-
-import java.io.IOException;
-import java.io.InputStream;
-
-/**
- * <code>InputStream</code> used by the MIME parser to detect whether the
- * underlying data stream was used (read from) and whether the end of the 
- * stream was reached.
- * 
- * @version $Id$
- */
-public class LineReaderInputStreamAdaptor extends LineReaderInputStream {
-
-    private final LineReaderInputStream bis;
-    private boolean used = false;
-    private boolean eof = false;
-
-    public LineReaderInputStreamAdaptor(final InputStream is) {
-        super(is);
-        if (is instanceof LineReaderInputStream) {
-            this.bis = (LineReaderInputStream) is;
-        } else {
-            this.bis = null;
-        }
-    }
-
-    public int read() throws IOException {
-        int i = in.read();
-        this.eof = i == -1;
-        this.used = true;
-        return i;
-    }
-
-    public int read(byte[] b, int off, int len) throws IOException {
-        int i = in.read(b, off, len);
-        this.eof = i == -1;
-        this.used = true;
-        return i;
-    }
-    
-    public int readLine(final ByteArrayBuffer dst) throws IOException {
-        int i;
-        if (this.bis != null) {
-             i = this.bis.readLine(dst);
-        } else {
-             i = doReadLine(dst);
-        }
-        this.eof = i == -1;
-        this.used = true;
-        return i;
-    }
-
-    private int doReadLine(final ByteArrayBuffer dst) throws IOException {
-        int total = 0;
-        int ch;
-        while ((ch = in.read()) != -1) {
-            dst.append(ch);
-            total++;
-            if (ch == '\n') {
-                break;
-            }
-        }
-        if (total == 0 && ch == -1) {
-            return -1;
-        } else {
-            return total;
-        }
-    }
-    
-    public boolean eof() {
-        return this.eof;
-    }
-
-    public boolean isUsed() {
-        return this.used;
-    }
-    
-    public String toString() {
-        return "[LineReaderInputStreamAdaptor: " + bis + "]";
-    }
-}
+/****************************************************************
+ * Licensed to the Apache Software Foundation (ASF) under one   *
+ * or more contributor license agreements.  See the NOTICE file *
+ * distributed with this work for additional information        *
+ * regarding copyright ownership.  The ASF licenses this file   *
+ * to you 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 org.apache.james.mime4j.io;
+
+import org.apache.james.mime4j.util.ByteArrayBuffer;
+
+import java.io.IOException;
+import java.io.InputStream;
+
+/**
+ * <code>InputStream</code> used by the MIME parser to detect whether the
+ * underlying data stream was used (read from) and whether the end of the 
+ * stream was reached.
+ * 
+ * @version $Id$
+ */
+public class LineReaderInputStreamAdaptor extends LineReaderInputStream {
+
+    private final LineReaderInputStream bis;
+    private final int maxLineLen;
+    
+    private boolean used = false;
+    private boolean eof = false;
+
+    public LineReaderInputStreamAdaptor(
+            final InputStream is,
+            int maxLineLen) {
+        super(is);
+        if (is instanceof LineReaderInputStream) {
+            this.bis = (LineReaderInputStream) is;
+        } else {
+            this.bis = null;
+        }
+        this.maxLineLen = maxLineLen;
+    }
+
+    public LineReaderInputStreamAdaptor(
+            final InputStream is) {
+        this(is, -1);
+    }
+    
+    public int read() throws IOException {
+        int i = in.read();
+        this.eof = i == -1;
+        this.used = true;
+        return i;
+    }
+
+    public int read(byte[] b, int off, int len) throws IOException {
+        int i = in.read(b, off, len);
+        this.eof = i == -1;
+        this.used = true;
+        return i;
+    }
+    
+    public int readLine(final ByteArrayBuffer dst) throws IOException {
+        int i;
+        if (this.bis != null) {
+             i = this.bis.readLine(dst);
+        } else {
+             i = doReadLine(dst);
+        }
+        this.eof = i == -1;
+        this.used = true;
+        return i;
+    }
+
+    private int doReadLine(final ByteArrayBuffer dst) throws IOException {
+        int total = 0;
+        int ch;
+        while ((ch = in.read()) != -1) {
+            dst.append(ch);
+            total++;
+            if (this.maxLineLen > 0 && dst.length() >= this.maxLineLen) {
+                throw new IOException("Maximum line length limit exceeded");
+            }
+            if (ch == '\n') {
+                break;
+            }
+        }
+        if (total == 0 && ch == -1) {
+            return -1;
+        } else {
+            return total;
+        }
+    }
+    
+    public boolean eof() {
+        return this.eof;
+    }
+
+    public boolean isUsed() {
+        return this.used;
+    }
+    
+    public String toString() {
+        return "[LineReaderInputStreamAdaptor: " + bis + "]";
+    }
+}

Modified: james/mime4j/trunk/src/main/java/org/apache/james/mime4j/message/Message.java
URL: http://svn.apache.org/viewvc/james/mime4j/trunk/src/main/java/org/apache/james/mime4j/message/Message.java?rev=697409&r1=697408&r2=697409&view=diff
==============================================================================
--- james/mime4j/trunk/src/main/java/org/apache/james/mime4j/message/Message.java (original)
+++ james/mime4j/trunk/src/main/java/org/apache/james/mime4j/message/Message.java Sat Sep 20 11:54:15 2008
@@ -1,76 +1,87 @@
-/****************************************************************
- * Licensed to the Apache Software Foundation (ASF) under one   *
- * or more contributor license agreements.  See the NOTICE file *
- * distributed with this work for additional information        *
- * regarding copyright ownership.  The ASF licenses this file   *
- * to you 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 org.apache.james.mime4j.message;
-
-import org.apache.james.mime4j.MimeException;
-import org.apache.james.mime4j.field.Field;
-import org.apache.james.mime4j.field.UnstructuredField;
-import org.apache.james.mime4j.parser.MimeStreamParser;
-
-import java.io.IOException;
-import java.io.InputStream;
-
-
-/**
- * Represents a MIME message. The following code parses a stream into a 
- * <code>Message</code> object.
- * 
- * <pre>
- *      Message msg = new Message(new BufferedInputStream(
- *                                      new FileInputStream("mime.msg")));
- * </pre>
- * 
- *
- * 
- * @version $Id: Message.java,v 1.3 2004/10/02 12:41:11 ntherning Exp $
- */
-public class Message extends Entity implements Body {
-    
-    /**
-     * Creates a new empty <code>Message</code>.
-     */
-    public Message() {
-    }
-    
-    /**
-     * Parses the specified MIME message stream into a <code>Message</code>
-     * instance.
-     * 
-     * @param is the stream to parse.
-     * @throws IOException on I/O errors.
-     */
-    public Message(InputStream is) throws MimeException, IOException {
-        MimeStreamParser parser = new MimeStreamParser();
-        parser.setContentHandler(new MessageBuilder(this));
-        parser.parse(is);
-    }
-
-    
-    /**
-     * Gets the <code>Subject</code> field.
-     * 
-     * @return the <code>Subject</code> field or <code>null</code> if it
-     *         doesn't exist.
-     */
-    public UnstructuredField getSubject() {
-        return (UnstructuredField) getHeader().getField(Field.SUBJECT);
-    }
-    
-}
+/****************************************************************
+ * Licensed to the Apache Software Foundation (ASF) under one   *
+ * or more contributor license agreements.  See the NOTICE file *
+ * distributed with this work for additional information        *
+ * regarding copyright ownership.  The ASF licenses this file   *
+ * to you 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 org.apache.james.mime4j.message;
+
+import org.apache.james.mime4j.MimeException;
+import org.apache.james.mime4j.field.Field;
+import org.apache.james.mime4j.field.UnstructuredField;
+import org.apache.james.mime4j.parser.MimeEntityConfig;
+import org.apache.james.mime4j.parser.MimeStreamParser;
+
+import java.io.IOException;
+import java.io.InputStream;
+
+
+/**
+ * Represents a MIME message. The following code parses a stream into a 
+ * <code>Message</code> object.
+ * 
+ * <pre>
+ *      Message msg = new Message(new BufferedInputStream(
+ *                                      new FileInputStream("mime.msg")));
+ * </pre>
+ * 
+ *
+ * 
+ * @version $Id: Message.java,v 1.3 2004/10/02 12:41:11 ntherning Exp $
+ */
+public class Message extends Entity implements Body {
+    
+    /**
+     * Creates a new empty <code>Message</code>.
+     */
+    public Message() {
+    }
+    
+    /**
+     * Parses the specified MIME message stream into a <code>Message</code>
+     * instance using given {@link MimeEntityConfig}.
+     * 
+     * @param is the stream to parse.
+     * @throws IOException on I/O errors.
+     */
+    public Message(InputStream is, MimeEntityConfig config) throws MimeException, IOException {
+        MimeStreamParser parser = new MimeStreamParser(config);
+        parser.setContentHandler(new MessageBuilder(this));
+        parser.parse(is);
+    }
+
+    /**
+     * Parses the specified MIME message stream into a <code>Message</code>
+     * instance.
+     * 
+     * @param is the stream to parse.
+     * @throws IOException on I/O errors.
+     */
+    public Message(InputStream is) throws IOException {
+        this(is, null);
+    }
+    
+    /**
+     * Gets the <code>Subject</code> field.
+     * 
+     * @return the <code>Subject</code> field or <code>null</code> if it
+     *         doesn't exist.
+     */
+    public UnstructuredField getSubject() {
+        return (UnstructuredField) getHeader().getField(Field.SUBJECT);
+    }
+    
+}

Modified: james/mime4j/trunk/src/main/java/org/apache/james/mime4j/parser/AbstractEntity.java
URL: http://svn.apache.org/viewvc/james/mime4j/trunk/src/main/java/org/apache/james/mime4j/parser/AbstractEntity.java?rev=697409&r1=697408&r2=697409&view=diff
==============================================================================
--- james/mime4j/trunk/src/main/java/org/apache/james/mime4j/parser/AbstractEntity.java (original)
+++ james/mime4j/trunk/src/main/java/org/apache/james/mime4j/parser/AbstractEntity.java Sat Sep 20 11:54:15 2008
@@ -1,401 +1,398 @@
-/****************************************************************
- * Licensed to the Apache Software Foundation (ASF) under one   *
- * or more contributor license agreements.  See the NOTICE file *
- * distributed with this work for additional information        *
- * regarding copyright ownership.  The ASF licenses this file   *
- * to you 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 org.apache.james.mime4j.parser;
-
-import java.io.IOException;
-import java.util.BitSet;
-
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.apache.james.mime4j.MimeException;
-import org.apache.james.mime4j.descriptor.BodyDescriptor;
-import org.apache.james.mime4j.descriptor.DefaultBodyDescriptor;
-import org.apache.james.mime4j.descriptor.MaximalBodyDescriptor;
-import org.apache.james.mime4j.descriptor.MutableBodyDescriptor;
-import org.apache.james.mime4j.io.LineReaderInputStream;
-import org.apache.james.mime4j.util.ByteArrayBuffer;
-import org.apache.james.mime4j.util.CharArrayBuffer;
-import org.apache.james.mime4j.util.MessageUtils;
-
-/**
- * Abstract MIME entity.
- */
-public abstract class AbstractEntity implements EntityStateMachine {
-
-    protected final Log log;
-    
-    protected final BodyDescriptor parent;
-    protected final int startState;
-    protected final int endState;
-    protected final boolean maximalBodyDescriptor;
-    protected final boolean strictParsing;
-    protected final MutableBodyDescriptor body;
-    
-    protected int state;
-
-    private final ByteArrayBuffer linebuf;
-    private final CharArrayBuffer fieldbuf;
-
-    private int lineCount;
-    private String field, fieldName, fieldValue;
-    private boolean endOfHeader;
-
-    private static final BitSet fieldChars = new BitSet();
-
-    static {
-        for (int i = 0x21; i <= 0x39; i++) {
-            fieldChars.set(i);
-        }
-        for (int i = 0x3b; i <= 0x7e; i++) {
-            fieldChars.set(i);
-        }
-    }
-
-    /**
-     * Internal state, not exposed.
-     */
-    private static final int T_IN_BODYPART = -2;
-    /**
-     * Internal state, not exposed.
-     */
-    private static final int T_IN_MESSAGE = -3;
-
-    AbstractEntity(
-            BodyDescriptor parent,
-            int startState, 
-            int endState,
-            boolean maximalBodyDescriptor,
-            boolean strictParsing) {
-        this.log = LogFactory.getLog(getClass());        
-        this.parent = parent;
-        this.state = startState;
-        this.startState = startState; 
-        this.endState = endState;
-        this.maximalBodyDescriptor = maximalBodyDescriptor;
-        this.strictParsing = strictParsing;
-        this.body = newBodyDescriptor(parent);
-        this.linebuf = new ByteArrayBuffer(64);
-        this.fieldbuf = new CharArrayBuffer(64);
-        this.lineCount = 0;
-        this.endOfHeader = false;
-    }
-
-    public int getState() {
-        return state;
-    }
-    
-    /**
-     * Creates a new instance of {@link BodyDescriptor}. Subclasses may override
-     * this in order to create body descriptors, that provide more specific
-     * information.
-     */
-    protected MutableBodyDescriptor newBodyDescriptor(BodyDescriptor pParent) {
-        final MutableBodyDescriptor result;
-        if (maximalBodyDescriptor) {
-            result = new MaximalBodyDescriptor(pParent);
-        } else {
-            result = new DefaultBodyDescriptor(pParent);
-        }
-        return result;
-    }
-
-    protected abstract int getLineNumber();
-    
-    protected abstract LineReaderInputStream getDataStream();
-    
-    private void fillFieldBuffer() throws IOException, MimeException {
-        if (endOfHeader) {
-            return;
-        }
-        LineReaderInputStream instream = getDataStream();
-        fieldbuf.clear();
-        for (;;) {
-            // If there's still data stuck in the line buffer
-            // copy it to the field buffer
-            int len = linebuf.length();
-            if (len > 0) {
-                fieldbuf.append(linebuf, 0, len);
-            }
-            linebuf.clear();
-            if (instream.readLine(linebuf) == -1) {
-                monitor(Event.HEADERS_PREMATURE_END);
-                endOfHeader = true;
-                break;
-            }
-            len = linebuf.length();
-            if (len > 0 && linebuf.byteAt(len - 1) == '\n') {
-                len--;
-            }
-            if (len > 0 && linebuf.byteAt(len - 1) == '\r') {
-                len--;
-            }
-            if (len == 0) {
-                // empty line detected 
-                endOfHeader = true;
-                break;
-            }
-            lineCount++;
-            if (lineCount > 1) {
-                int ch = linebuf.byteAt(0);
-                if (ch != MessageUtils.SP && ch != MessageUtils.HT) {
-                    // new header detected
-                    break;
-                }
-            }
-        }
-    }
-
-    protected boolean parseField() throws IOException {
-        for (;;) {
-            if (endOfHeader) {
-                return false;
-            }
-            fillFieldBuffer();
-            
-            // Strip away line delimiter
-            int len = fieldbuf.length();
-            if (len > 0 && fieldbuf.charAt(len - 1) == '\n') {
-                len--;
-            }
-            if (len > 0 && fieldbuf.charAt(len - 1) == '\r') {
-                len--;
-            }
-            fieldbuf.setLength(len);
-            
-            boolean valid = true;
-            field = fieldbuf.toString();
-            int pos = fieldbuf.indexOf(':');
-            if (pos == -1) {
-                monitor(Event.INALID_HEADER);
-                valid = false;
-            } else {
-                fieldName = fieldbuf.substring(0, pos);
-                for (int i = 0; i < fieldName.length(); i++) {
-                    if (!fieldChars.get(fieldName.charAt(i))) {
-                        monitor(Event.INALID_HEADER);
-                        valid = false;
-                        break;
-                    }
-                }
-                fieldValue = fieldbuf.substring(pos + 1, fieldbuf.length());
-            }
-            if (valid) {
-                body.addField(fieldName, fieldValue);            
-                return true;
-            }
-        }
-    }
-
-    /**
-     * <p>Gets a descriptor for the current entity.
-     * This method is valid if {@link #getState()} returns:</p>
-     * <ul>
-     * <li>{@link #T_BODY}</li>
-     * <li>{@link #T_START_MULTIPART}</li>
-     * <li>{@link #T_EPILOGUE}</li>
-     * <li>{@link #T_PREAMBLE}</li>
-     * </ul>
-     * @return <code>BodyDescriptor</code>, not nulls
-     */
-    public BodyDescriptor getBodyDescriptor() {
-        switch (getState()) {
-        case EntityStates.T_BODY:
-        case EntityStates.T_START_MULTIPART:
-        case EntityStates.T_PREAMBLE:
-        case EntityStates.T_EPILOGUE:
-        case EntityStates.T_END_OF_STREAM:
-            return body;
-        default:
-            throw new IllegalStateException("Invalid state :" + stateToString(state));
-        }
-    }
-
-    /**
-     * This method is valid, if {@link #getState()} returns {@link #T_FIELD}.
-     * @return String with the fields raw contents.
-     * @throws IllegalStateException {@link #getState()} returns another
-     *   value than {@link #T_FIELD}.
-     */
-    public String getField() {
-        switch (getState()) {
-        case EntityStates.T_FIELD:
-            return field;
-        default:
-            throw new IllegalStateException("Invalid state :" + stateToString(state));
-        }
-    }
-
-    /**
-     * This method is valid, if {@link #getState()} returns {@link #T_FIELD}.
-     * @return String with the fields name.
-     * @throws IllegalStateException {@link #getState()} returns another
-     *   value than {@link #T_FIELD}.
-     */
-    public String getFieldName() {
-        switch (getState()) {
-        case EntityStates.T_FIELD:
-            return fieldName;
-        default:
-            throw new IllegalStateException("Invalid state :" + stateToString(state));
-        }
-    }
-
-    /**
-     * This method is valid, if {@link #getState()} returns {@link #T_FIELD}.
-     * @return String with the fields value.
-     * @throws IllegalStateException {@link #getState()} returns another
-     *   value than {@link #T_FIELD}.
-     */
-    public String getFieldValue() {
-        switch (getState()) {
-        case EntityStates.T_FIELD:
-            return fieldValue;
-        default:
-            throw new IllegalStateException("Invalid state :" + stateToString(state));
-        }
-    }
-
-    /**
-     * Monitors the given event.
-     * Subclasses may override to perform actions upon events.
-     * Base implementation logs at warn.
-     * @param event <code>Event</code>, not null
-     * @throws MimeException subclasses may elect to throw this exception upon
-     * invalid content
-     * @throws IOException subclasses may elect to throw this exception
-     */
-    protected void monitor(Event event) throws MimeException, IOException {
-        if (strictParsing) {
-            throw new MimeParseEventException(event);
-        } else {
-            warn(event);
-        }
-    }
-    
-    /**
-     * Creates an indicative message suitable for display
-     * based on the given event and the current state of the system.
-     * @param event <code>Event</code>, not null
-     * @return message suitable for use as a message in an exception
-     * or for logging
-     */
-    protected String message(Event event) {
-        String preamble = "Line " + getLineNumber() + ": ";
-        final String message;
-        if (event == null) {
-            message = "Event is unexpectedly null.";
-        } else {
-            message = event.toString();
-        }
-        final String result = preamble + message;
-        return result;
-    }
-    
-    /**
-     * Logs (at warn) an indicative message based on the given event 
-     * and the current state of the system.
-     * @param event <code>Event</code>, not null
-     */
-    protected void warn(Event event) {
-        if (log.isWarnEnabled()) {
-            log.warn(message(event));
-        }
-    }
-    
-    /**
-     * Logs (at debug) an indicative message based on the given event
-     * and the current state of the system.
-     * @param event <code>Event</code>, not null
-     */
-    protected void debug(Event event) {
-        if (log.isDebugEnabled()) {
-            log.debug(message(event));
-        }
-    }
-
-    public String toString() {
-        return getClass().getName() + " [" + stateToString(state)
-        + "][" + body.getMimeType() + "][" + body.getBoundary() + "]";
-    }
-
-    /**
-     * Renders a state as a string suitable for logging.
-     * @param state 
-     * @return rendered as string, not null
-     */
-    public static final String stateToString(int state) {
-        final String result;
-        switch (state) {
-            case EntityStates.T_END_OF_STREAM:
-                result = "End of stream";
-                break;
-            case EntityStates.T_START_MESSAGE:
-                result = "Start message";
-                break;
-            case EntityStates.T_END_MESSAGE:
-                result = "End message";
-                break;
-            case EntityStates.T_RAW_ENTITY:
-                result = "Raw entity";
-                break;
-            case EntityStates.T_START_HEADER:
-                result = "Start header";
-                break;
-            case EntityStates.T_FIELD:
-                result = "Field";
-                break;
-            case EntityStates.T_END_HEADER:
-                result = "End header";
-                break;
-            case EntityStates.T_START_MULTIPART:
-                result = "Start multipart";
-                break;
-            case EntityStates.T_END_MULTIPART:
-                result = "End multipart";
-                break;
-            case EntityStates.T_PREAMBLE:
-                result = "Preamble";
-                break;
-            case EntityStates.T_EPILOGUE:
-                result = "Epilogue";
-                break;
-            case EntityStates.T_START_BODYPART:
-                result = "Start bodypart";
-                break;
-            case EntityStates.T_END_BODYPART:
-                result = "End bodypart";
-                break;
-            case EntityStates.T_BODY:
-                result = "Body";
-                break;
-            case T_IN_BODYPART:
-                result = "Bodypart";
-                break;
-            case T_IN_MESSAGE:
-                result = "In message";
-                break;
-            default:
-                result = "Unknown";
-                break;
-        }
-        return result;
-    }
-    
-}
+/****************************************************************
+ * Licensed to the Apache Software Foundation (ASF) under one   *
+ * or more contributor license agreements.  See the NOTICE file *
+ * distributed with this work for additional information        *
+ * regarding copyright ownership.  The ASF licenses this file   *
+ * to you 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 org.apache.james.mime4j.parser;
+
+import java.io.IOException;
+import java.util.BitSet;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.james.mime4j.MimeException;
+import org.apache.james.mime4j.descriptor.BodyDescriptor;
+import org.apache.james.mime4j.descriptor.DefaultBodyDescriptor;
+import org.apache.james.mime4j.descriptor.MaximalBodyDescriptor;
+import org.apache.james.mime4j.descriptor.MutableBodyDescriptor;
+import org.apache.james.mime4j.io.LineReaderInputStream;
+import org.apache.james.mime4j.util.ByteArrayBuffer;
+import org.apache.james.mime4j.util.CharArrayBuffer;
+import org.apache.james.mime4j.util.MessageUtils;
+
+/**
+ * Abstract MIME entity.
+ */
+public abstract class AbstractEntity implements EntityStateMachine {
+
+    protected final Log log;
+    
+    protected final BodyDescriptor parent;
+    protected final int startState;
+    protected final int endState;
+    protected final MimeEntityConfig config;
+    protected final MutableBodyDescriptor body;
+    
+    protected int state;
+
+    private final ByteArrayBuffer linebuf;
+    private final CharArrayBuffer fieldbuf;
+
+    private int lineCount;
+    private String field, fieldName, fieldValue;
+    private boolean endOfHeader;
+
+    private static final BitSet fieldChars = new BitSet();
+
+    static {
+        for (int i = 0x21; i <= 0x39; i++) {
+            fieldChars.set(i);
+        }
+        for (int i = 0x3b; i <= 0x7e; i++) {
+            fieldChars.set(i);
+        }
+    }
+
+    /**
+     * Internal state, not exposed.
+     */
+    private static final int T_IN_BODYPART = -2;
+    /**
+     * Internal state, not exposed.
+     */
+    private static final int T_IN_MESSAGE = -3;
+
+    AbstractEntity(
+            BodyDescriptor parent,
+            int startState, 
+            int endState,
+            MimeEntityConfig config) {
+        this.log = LogFactory.getLog(getClass());        
+        this.parent = parent;
+        this.state = startState;
+        this.startState = startState;
+        this.endState = endState;
+        this.config = config;
+        this.body = newBodyDescriptor(parent);
+        this.linebuf = new ByteArrayBuffer(64);
+        this.fieldbuf = new CharArrayBuffer(64);
+        this.lineCount = 0;
+        this.endOfHeader = false;
+    }
+
+    public int getState() {
+        return state;
+    }
+    
+    /**
+     * Creates a new instance of {@link BodyDescriptor}. Subclasses may override
+     * this in order to create body descriptors, that provide more specific
+     * information.
+     */
+    protected MutableBodyDescriptor newBodyDescriptor(BodyDescriptor pParent) {
+        final MutableBodyDescriptor result;
+        if (config.isMaximalBodyDescriptor()) {
+            result = new MaximalBodyDescriptor(pParent);
+        } else {
+            result = new DefaultBodyDescriptor(pParent);
+        }
+        return result;
+    }
+
+    protected abstract int getLineNumber();
+    
+    protected abstract LineReaderInputStream getDataStream();
+    
+    private void fillFieldBuffer() throws IOException, MimeException {
+        if (endOfHeader) {
+            return;
+        }
+        LineReaderInputStream instream = getDataStream();
+        fieldbuf.clear();
+        for (;;) {
+            // If there's still data stuck in the line buffer
+            // copy it to the field buffer
+            int len = linebuf.length();
+            if (len > 0) {
+                fieldbuf.append(linebuf, 0, len);
+            }
+            linebuf.clear();
+            if (instream.readLine(linebuf) == -1) {
+                monitor(Event.HEADERS_PREMATURE_END);
+                endOfHeader = true;
+                break;
+            }
+            len = linebuf.length();
+            if (len > 0 && linebuf.byteAt(len - 1) == '\n') {
+                len--;
+            }
+            if (len > 0 && linebuf.byteAt(len - 1) == '\r') {
+                len--;
+            }
+            if (len == 0) {
+                // empty line detected 
+                endOfHeader = true;
+                break;
+            }
+            lineCount++;
+            if (lineCount > 1) {
+                int ch = linebuf.byteAt(0);
+                if (ch != MessageUtils.SP && ch != MessageUtils.HT) {
+                    // new header detected
+                    break;
+                }
+            }
+        }
+    }
+
+    protected boolean parseField() throws IOException {
+        for (;;) {
+            if (endOfHeader) {
+                return false;
+            }
+            fillFieldBuffer();
+            
+            // Strip away line delimiter
+            int len = fieldbuf.length();
+            if (len > 0 && fieldbuf.charAt(len - 1) == '\n') {
+                len--;
+            }
+            if (len > 0 && fieldbuf.charAt(len - 1) == '\r') {
+                len--;
+            }
+            fieldbuf.setLength(len);
+            
+            boolean valid = true;
+            field = fieldbuf.toString();
+            int pos = fieldbuf.indexOf(':');
+            if (pos == -1) {
+                monitor(Event.INALID_HEADER);
+                valid = false;
+            } else {
+                fieldName = fieldbuf.substring(0, pos);
+                for (int i = 0; i < fieldName.length(); i++) {
+                    if (!fieldChars.get(fieldName.charAt(i))) {
+                        monitor(Event.INALID_HEADER);
+                        valid = false;
+                        break;
+                    }
+                }
+                fieldValue = fieldbuf.substring(pos + 1, fieldbuf.length());
+            }
+            if (valid) {
+                body.addField(fieldName, fieldValue);            
+                return true;
+            }
+        }
+    }
+
+    /**
+     * <p>Gets a descriptor for the current entity.
+     * This method is valid if {@link #getState()} returns:</p>
+     * <ul>
+     * <li>{@link #T_BODY}</li>
+     * <li>{@link #T_START_MULTIPART}</li>
+     * <li>{@link #T_EPILOGUE}</li>
+     * <li>{@link #T_PREAMBLE}</li>
+     * </ul>
+     * @return <code>BodyDescriptor</code>, not nulls
+     */
+    public BodyDescriptor getBodyDescriptor() {
+        switch (getState()) {
+        case EntityStates.T_BODY:
+        case EntityStates.T_START_MULTIPART:
+        case EntityStates.T_PREAMBLE:
+        case EntityStates.T_EPILOGUE:
+        case EntityStates.T_END_OF_STREAM:
+            return body;
+        default:
+            throw new IllegalStateException("Invalid state :" + stateToString(state));
+        }
+    }
+
+    /**
+     * This method is valid, if {@link #getState()} returns {@link #T_FIELD}.
+     * @return String with the fields raw contents.
+     * @throws IllegalStateException {@link #getState()} returns another
+     *   value than {@link #T_FIELD}.
+     */
+    public String getField() {
+        switch (getState()) {
+        case EntityStates.T_FIELD:
+            return field;
+        default:
+            throw new IllegalStateException("Invalid state :" + stateToString(state));
+        }
+    }
+
+    /**
+     * This method is valid, if {@link #getState()} returns {@link #T_FIELD}.
+     * @return String with the fields name.
+     * @throws IllegalStateException {@link #getState()} returns another
+     *   value than {@link #T_FIELD}.
+     */
+    public String getFieldName() {
+        switch (getState()) {
+        case EntityStates.T_FIELD:
+            return fieldName;
+        default:
+            throw new IllegalStateException("Invalid state :" + stateToString(state));
+        }
+    }
+
+    /**
+     * This method is valid, if {@link #getState()} returns {@link #T_FIELD}.
+     * @return String with the fields value.
+     * @throws IllegalStateException {@link #getState()} returns another
+     *   value than {@link #T_FIELD}.
+     */
+    public String getFieldValue() {
+        switch (getState()) {
+        case EntityStates.T_FIELD:
+            return fieldValue;
+        default:
+            throw new IllegalStateException("Invalid state :" + stateToString(state));
+        }
+    }
+
+    /**
+     * Monitors the given event.
+     * Subclasses may override to perform actions upon events.
+     * Base implementation logs at warn.
+     * @param event <code>Event</code>, not null
+     * @throws MimeException subclasses may elect to throw this exception upon
+     * invalid content
+     * @throws IOException subclasses may elect to throw this exception
+     */
+    protected void monitor(Event event) throws MimeException, IOException {
+        if (config.isStrictParsing()) {
+            throw new MimeParseEventException(event);
+        } else {
+            warn(event);
+        }
+    }
+    
+    /**
+     * Creates an indicative message suitable for display
+     * based on the given event and the current state of the system.
+     * @param event <code>Event</code>, not null
+     * @return message suitable for use as a message in an exception
+     * or for logging
+     */
+    protected String message(Event event) {
+        String preamble = "Line " + getLineNumber() + ": ";
+        final String message;
+        if (event == null) {
+            message = "Event is unexpectedly null.";
+        } else {
+            message = event.toString();
+        }
+        final String result = preamble + message;
+        return result;
+    }
+    
+    /**
+     * Logs (at warn) an indicative message based on the given event 
+     * and the current state of the system.
+     * @param event <code>Event</code>, not null
+     */
+    protected void warn(Event event) {
+        if (log.isWarnEnabled()) {
+            log.warn(message(event));
+        }
+    }
+    
+    /**
+     * Logs (at debug) an indicative message based on the given event
+     * and the current state of the system.
+     * @param event <code>Event</code>, not null
+     */
+    protected void debug(Event event) {
+        if (log.isDebugEnabled()) {
+            log.debug(message(event));
+        }
+    }
+
+    public String toString() {
+        return getClass().getName() + " [" + stateToString(state)
+        + "][" + body.getMimeType() + "][" + body.getBoundary() + "]";
+    }
+
+    /**
+     * Renders a state as a string suitable for logging.
+     * @param state 
+     * @return rendered as string, not null
+     */
+    public static final String stateToString(int state) {
+        final String result;
+        switch (state) {
+            case EntityStates.T_END_OF_STREAM:
+                result = "End of stream";
+                break;
+            case EntityStates.T_START_MESSAGE:
+                result = "Start message";
+                break;
+            case EntityStates.T_END_MESSAGE:
+                result = "End message";
+                break;
+            case EntityStates.T_RAW_ENTITY:
+                result = "Raw entity";
+                break;
+            case EntityStates.T_START_HEADER:
+                result = "Start header";
+                break;
+            case EntityStates.T_FIELD:
+                result = "Field";
+                break;
+            case EntityStates.T_END_HEADER:
+                result = "End header";
+                break;
+            case EntityStates.T_START_MULTIPART:
+                result = "Start multipart";
+                break;
+            case EntityStates.T_END_MULTIPART:
+                result = "End multipart";
+                break;
+            case EntityStates.T_PREAMBLE:
+                result = "Preamble";
+                break;
+            case EntityStates.T_EPILOGUE:
+                result = "Epilogue";
+                break;
+            case EntityStates.T_START_BODYPART:
+                result = "Start bodypart";
+                break;
+            case EntityStates.T_END_BODYPART:
+                result = "End bodypart";
+                break;
+            case EntityStates.T_BODY:
+                result = "Body";
+                break;
+            case T_IN_BODYPART:
+                result = "Bodypart";
+                break;
+            case T_IN_MESSAGE:
+                result = "In message";
+                break;
+            default:
+                result = "Unknown";
+                break;
+        }
+        return result;
+    }
+    
+}

Modified: james/mime4j/trunk/src/main/java/org/apache/james/mime4j/parser/MimeEntity.java
URL: http://svn.apache.org/viewvc/james/mime4j/trunk/src/main/java/org/apache/james/mime4j/parser/MimeEntity.java?rev=697409&r1=697408&r2=697409&view=diff
==============================================================================
--- james/mime4j/trunk/src/main/java/org/apache/james/mime4j/parser/MimeEntity.java (original)
+++ james/mime4j/trunk/src/main/java/org/apache/james/mime4j/parser/MimeEntity.java Sat Sep 20 11:54:15 2008
@@ -1,287 +1,301 @@
-/****************************************************************
- * Licensed to the Apache Software Foundation (ASF) under one   *
- * or more contributor license agreements.  See the NOTICE file *
- * distributed with this work for additional information        *
- * regarding copyright ownership.  The ASF licenses this file   *
- * to you 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 org.apache.james.mime4j.parser;
-
-import java.io.IOException;
-import java.io.InputStream;
-
-import org.apache.james.mime4j.MimeException;
-import org.apache.james.mime4j.decoder.Base64InputStream;
-import org.apache.james.mime4j.decoder.QuotedPrintableInputStream;
-import org.apache.james.mime4j.descriptor.BodyDescriptor;
-import org.apache.james.mime4j.io.BufferedLineReaderInputStream;
-import org.apache.james.mime4j.io.LineReaderInputStream;
-import org.apache.james.mime4j.io.LineReaderInputStreamAdaptor;
-import org.apache.james.mime4j.io.MimeBoundaryInputStream;
-import org.apache.james.mime4j.io.RootInputStream;
-import org.apache.james.mime4j.util.MimeUtil;
-
-public class MimeEntity extends AbstractEntity {
-
-    /**
-     * Internal state, not exposed.
-     */
-    private static final int T_IN_BODYPART = -2;
-    /**
-     * Internal state, not exposed.
-     */
-    private static final int T_IN_MESSAGE = -3;
-
-    private final RootInputStream rootStream;
-    private final BufferedLineReaderInputStream inbuffer;
-    
-    private int recursionMode;
-    private MimeBoundaryInputStream mimeStream;
-    private LineReaderInputStreamAdaptor dataStream;
-    private boolean skipHeader;
-    
-    private byte[] tmpbuf;
-    
-    public MimeEntity(
-            RootInputStream rootStream,
-            BufferedLineReaderInputStream inbuffer,
-            BodyDescriptor parent, 
-            int startState, 
-            int endState,
-            boolean maximalBodyDescriptor,
-            boolean strictParsing) {
-        super(parent, startState, endState, maximalBodyDescriptor, strictParsing);
-        this.rootStream = rootStream;
-        this.inbuffer = inbuffer;
-        this.dataStream = new LineReaderInputStreamAdaptor(inbuffer);
-        this.skipHeader = false;
-    }
-
-    public MimeEntity(
-            RootInputStream rootStream,
-            BufferedLineReaderInputStream inbuffer,
-            BodyDescriptor parent, 
-            int startState, 
-            int endState) {
-        this(rootStream, inbuffer, parent, startState, endState, false, false);
-    }
-
-    public int getRecursionMode() {
-        return recursionMode;
-    }
-
-    public void setRecursionMode(int recursionMode) {
-        this.recursionMode = recursionMode;
-    }
-
-    public void skipHeader(String contentType) {
-        if (state != EntityStates.T_START_MESSAGE) {
-            throw new IllegalStateException("Invalid state: " + stateToString(state));
-        }
-        skipHeader = true;
-        body.addField("Content-Type", contentType);
-    }
-    
-    protected int getLineNumber() {
-        return rootStream.getLineNumber();
-    }
-    
-    protected LineReaderInputStream getDataStream() {
-        return dataStream;
-    }
-    
-    public EntityStateMachine advance() throws IOException, MimeException {
-        switch (state) {
-        case EntityStates.T_START_MESSAGE:
-            if (skipHeader) {
-                state = EntityStates.T_END_HEADER;
-            } else {
-                state = EntityStates.T_START_HEADER;
-            }
-            break;
-        case EntityStates.T_START_BODYPART:
-            state = EntityStates.T_START_HEADER;
-            break;
-        case EntityStates.T_START_HEADER:
-        case EntityStates.T_FIELD:
-            state = parseField() ? EntityStates.T_FIELD : EntityStates.T_END_HEADER;
-            break;
-        case EntityStates.T_END_HEADER:
-            String mimeType = body.getMimeType();
-            if (recursionMode == RecursionMode.M_FLAT) {
-                state = EntityStates.T_BODY;
-            } else if (MimeUtil.isMultipart(mimeType)) {
-                state = EntityStates.T_START_MULTIPART;
-                clearMimeStream();
-            } else if (recursionMode != RecursionMode.M_NO_RECURSE 
-                    && MimeUtil.isMessage(mimeType)) {
-                state = T_IN_MESSAGE;
-                return nextMessage();
-            } else {
-                state = EntityStates.T_BODY;
-            }
-            break;
-        case EntityStates.T_START_MULTIPART:
-            if (dataStream.isUsed()) {
-                advanceToBoundary();            
-                state = EntityStates.T_END_MULTIPART;
-            } else {
-                createMimeStream();
-                state = EntityStates.T_PREAMBLE;
-            }
-            break;
-        case EntityStates.T_PREAMBLE:
-            advanceToBoundary();            
-            if (mimeStream.isLastPart()) {
-                clearMimeStream();
-                state = EntityStates.T_END_MULTIPART;
-            } else {
-                clearMimeStream();
-                createMimeStream();
-                state = T_IN_BODYPART;
-                return nextMimeEntity();
-            }
-            break;
-        case T_IN_BODYPART:
-            advanceToBoundary();
-            if (mimeStream.eof() && !mimeStream.isLastPart()) {
-                monitor(Event.MIME_BODY_PREMATURE_END);
-            } else {
-                if (!mimeStream.isLastPart()) {
-                    clearMimeStream();
-                    createMimeStream();
-                    state = T_IN_BODYPART;
-                    return nextMimeEntity();
-                }
-            }
-            clearMimeStream();
-            state = EntityStates.T_EPILOGUE;
-            break;
-        case EntityStates.T_EPILOGUE:
-            state = EntityStates.T_END_MULTIPART;
-            break;
-        case EntityStates.T_BODY:
-        case EntityStates.T_END_MULTIPART:
-        case T_IN_MESSAGE:
-            state = endState;
-            break;
-        default:
-            if (state == endState) {
-                state = EntityStates.T_END_OF_STREAM;
-                break;
-            }
-            throw new IllegalStateException("Invalid state: " + stateToString(state));
-        }
-        return null;
-    }
-
-    private void createMimeStream() throws IOException {
-        String boundary = body.getBoundary();
-        int bufferSize = 2 * boundary.length();
-        if (bufferSize < 4096) {
-            bufferSize = 4096;
-        }
-        try {
-            if (mimeStream != null) {
-                mimeStream = new MimeBoundaryInputStream(
-                        new BufferedLineReaderInputStream(mimeStream, bufferSize), boundary);
-            } else {
-                inbuffer.ensureCapacity(bufferSize);
-                mimeStream = new MimeBoundaryInputStream(inbuffer, boundary);
-            }
-        } catch (IllegalArgumentException e) {
-            // thrown when boundary is too long
-            throw new MimeException(e.getMessage(), e);
-        }
-        dataStream = new LineReaderInputStreamAdaptor(mimeStream); 
-    }
-    
-    private void clearMimeStream() {
-        mimeStream = null;
-        dataStream = new LineReaderInputStreamAdaptor(inbuffer); 
-    }
-    
-    private void advanceToBoundary() throws IOException {
-        if (!dataStream.eof()) {
-            if (tmpbuf == null) {
-                tmpbuf = new byte[2048];
-            }
-            while (dataStream.read(tmpbuf)!= -1) {
-            }
-        }
-    }
-    
-    private EntityStateMachine nextMessage() {
-        String transferEncoding = body.getTransferEncoding();
-        InputStream instream;
-        if (MimeUtil.isBase64Encoding(transferEncoding)) {
-            log.debug("base64 encoded message/rfc822 detected");
-            instream = new Base64InputStream(dataStream);                    
-        } else if (MimeUtil.isQuotedPrintableEncoded(transferEncoding)) {
-            log.debug("quoted-printable encoded message/rfc822 detected");
-            instream = new QuotedPrintableInputStream(dataStream);                    
-        } else {
-            instream = dataStream;
-        }
-        
-        if (recursionMode == RecursionMode.M_RAW) {
-            RawEntity message = new RawEntity(instream);
-            return message;
-        } else {
-            MimeEntity message = new MimeEntity(
-                    rootStream, 
-                    new BufferedLineReaderInputStream(instream, 4 * 1024),
-                    body, 
-                    EntityStates.T_START_MESSAGE, 
-                    EntityStates.T_END_MESSAGE,
-                    maximalBodyDescriptor,
-                    strictParsing);
-            message.setRecursionMode(recursionMode);
-            return message;
-        }
-    }
-    
-    private EntityStateMachine nextMimeEntity() {
-        if (recursionMode == RecursionMode.M_RAW) {
-            RawEntity message = new RawEntity(mimeStream);
-            return message;
-        } else {
-            BufferedLineReaderInputStream stream = new BufferedLineReaderInputStream(mimeStream, 4 * 1024);
-            MimeEntity mimeentity = new MimeEntity(
-                    rootStream, 
-                    stream,
-                    body, 
-                    EntityStates.T_START_BODYPART, 
-                    EntityStates.T_END_BODYPART,
-                    maximalBodyDescriptor,
-                    strictParsing);
-            mimeentity.setRecursionMode(recursionMode);
-            return mimeentity;
-        }
-    }
-    
-    public InputStream getContentStream() {
-        switch (state) {
-        case EntityStates.T_START_MULTIPART:
-        case EntityStates.T_PREAMBLE:
-        case EntityStates.T_EPILOGUE:
-        case EntityStates.T_BODY:
-            return this.dataStream;
-        default:
-            throw new IllegalStateException("Invalid state: " + stateToString(state));
-        }
-    }
-
-}
+/****************************************************************
+ * Licensed to the Apache Software Foundation (ASF) under one   *
+ * or more contributor license agreements.  See the NOTICE file *
+ * distributed with this work for additional information        *
+ * regarding copyright ownership.  The ASF licenses this file   *
+ * to you 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 org.apache.james.mime4j.parser;
+
+import java.io.IOException;
+import java.io.InputStream;
+
+import org.apache.james.mime4j.MimeException;
+import org.apache.james.mime4j.decoder.Base64InputStream;
+import org.apache.james.mime4j.decoder.QuotedPrintableInputStream;
+import org.apache.james.mime4j.descriptor.BodyDescriptor;
+import org.apache.james.mime4j.io.BufferedLineReaderInputStream;
+import org.apache.james.mime4j.io.LineReaderInputStream;
+import org.apache.james.mime4j.io.LineReaderInputStreamAdaptor;
+import org.apache.james.mime4j.io.MimeBoundaryInputStream;
+import org.apache.james.mime4j.io.RootInputStream;
+import org.apache.james.mime4j.util.MimeUtil;
+
+public class MimeEntity extends AbstractEntity {
+
+    /**
+     * Internal state, not exposed.
+     */
+    private static final int T_IN_BODYPART = -2;
+    /**
+     * Internal state, not exposed.
+     */
+    private static final int T_IN_MESSAGE = -3;
+
+    private final RootInputStream rootStream;
+    private final BufferedLineReaderInputStream inbuffer;
+    
+    private int recursionMode;
+    private MimeBoundaryInputStream mimeStream;
+    private LineReaderInputStreamAdaptor dataStream;
+    private boolean skipHeader;
+    
+    private byte[] tmpbuf;
+    
+    public MimeEntity(
+            RootInputStream rootStream,
+            BufferedLineReaderInputStream inbuffer,
+            BodyDescriptor parent, 
+            int startState, 
+            int endState,
+            MimeEntityConfig config) {
+        super(parent, startState, endState, config);
+        this.rootStream = rootStream;
+        this.inbuffer = inbuffer;
+        this.dataStream = new LineReaderInputStreamAdaptor(
+                inbuffer,
+                config.getMaxLineLen());
+        this.skipHeader = false;
+    }
+
+    public MimeEntity(
+            RootInputStream rootStream,
+            BufferedLineReaderInputStream inbuffer,
+            BodyDescriptor parent, 
+            int startState, 
+            int endState) {
+        this(rootStream, inbuffer, parent, startState, endState, 
+                new MimeEntityConfig());
+    }
+
+    public int getRecursionMode() {
+        return recursionMode;
+    }
+
+    public void setRecursionMode(int recursionMode) {
+        this.recursionMode = recursionMode;
+    }
+
+    public void skipHeader(String contentType) {
+        if (state != EntityStates.T_START_MESSAGE) {
+            throw new IllegalStateException("Invalid state: " + stateToString(state));
+        }
+        skipHeader = true;
+        body.addField("Content-Type", contentType);
+    }
+    
+    protected int getLineNumber() {
+        return rootStream.getLineNumber();
+    }
+    
+    protected LineReaderInputStream getDataStream() {
+        return dataStream;
+    }
+    
+    public EntityStateMachine advance() throws IOException, MimeException {
+        switch (state) {
+        case EntityStates.T_START_MESSAGE:
+            if (skipHeader) {
+                state = EntityStates.T_END_HEADER;
+            } else {
+                state = EntityStates.T_START_HEADER;
+            }
+            break;
+        case EntityStates.T_START_BODYPART:
+            state = EntityStates.T_START_HEADER;
+            break;
+        case EntityStates.T_START_HEADER:
+        case EntityStates.T_FIELD:
+            state = parseField() ? EntityStates.T_FIELD : EntityStates.T_END_HEADER;
+            break;
+        case EntityStates.T_END_HEADER:
+            String mimeType = body.getMimeType();
+            if (recursionMode == RecursionMode.M_FLAT) {
+                state = EntityStates.T_BODY;
+            } else if (MimeUtil.isMultipart(mimeType)) {
+                state = EntityStates.T_START_MULTIPART;
+                clearMimeStream();
+            } else if (recursionMode != RecursionMode.M_NO_RECURSE 
+                    && MimeUtil.isMessage(mimeType)) {
+                state = T_IN_MESSAGE;
+                return nextMessage();
+            } else {
+                state = EntityStates.T_BODY;
+            }
+            break;
+        case EntityStates.T_START_MULTIPART:
+            if (dataStream.isUsed()) {
+                advanceToBoundary();            
+                state = EntityStates.T_END_MULTIPART;
+            } else {
+                createMimeStream();
+                state = EntityStates.T_PREAMBLE;
+            }
+            break;
+        case EntityStates.T_PREAMBLE:
+            advanceToBoundary();            
+            if (mimeStream.isLastPart()) {
+                clearMimeStream();
+                state = EntityStates.T_END_MULTIPART;
+            } else {
+                clearMimeStream();
+                createMimeStream();
+                state = T_IN_BODYPART;
+                return nextMimeEntity();
+            }
+            break;
+        case T_IN_BODYPART:
+            advanceToBoundary();
+            if (mimeStream.eof() && !mimeStream.isLastPart()) {
+                monitor(Event.MIME_BODY_PREMATURE_END);
+            } else {
+                if (!mimeStream.isLastPart()) {
+                    clearMimeStream();
+                    createMimeStream();
+                    state = T_IN_BODYPART;
+                    return nextMimeEntity();
+                }
+            }
+            clearMimeStream();
+            state = EntityStates.T_EPILOGUE;
+            break;
+        case EntityStates.T_EPILOGUE:
+            state = EntityStates.T_END_MULTIPART;
+            break;
+        case EntityStates.T_BODY:
+        case EntityStates.T_END_MULTIPART:
+        case T_IN_MESSAGE:
+            state = endState;
+            break;
+        default:
+            if (state == endState) {
+                state = EntityStates.T_END_OF_STREAM;
+                break;
+            }
+            throw new IllegalStateException("Invalid state: " + stateToString(state));
+        }
+        return null;
+    }
+
+    private void createMimeStream() throws IOException {
+        String boundary = body.getBoundary();
+        int bufferSize = 2 * boundary.length();
+        if (bufferSize < 4096) {
+            bufferSize = 4096;
+        }
+        try {
+            if (mimeStream != null) {
+                mimeStream = new MimeBoundaryInputStream(
+                        new BufferedLineReaderInputStream(
+                                mimeStream, 
+                                bufferSize, 
+                                config.getMaxLineLen()), 
+                        boundary);
+            } else {
+                inbuffer.ensureCapacity(bufferSize);
+                mimeStream = new MimeBoundaryInputStream(inbuffer, boundary);
+            }
+        } catch (IllegalArgumentException e) {
+            // thrown when boundary is too long
+            throw new MimeException(e.getMessage(), e);
+        }
+        dataStream = new LineReaderInputStreamAdaptor(
+                mimeStream,
+                config.getMaxLineLen()); 
+    }
+    
+    private void clearMimeStream() {
+        mimeStream = null;
+        dataStream = new LineReaderInputStreamAdaptor(
+                inbuffer,
+                config.getMaxLineLen()); 
+    }
+    
+    private void advanceToBoundary() throws IOException {
+        if (!dataStream.eof()) {
+            if (tmpbuf == null) {
+                tmpbuf = new byte[2048];
+            }
+            while (dataStream.read(tmpbuf)!= -1) {
+            }
+        }
+    }
+    
+    private EntityStateMachine nextMessage() {
+        String transferEncoding = body.getTransferEncoding();
+        InputStream instream;
+        if (MimeUtil.isBase64Encoding(transferEncoding)) {
+            log.debug("base64 encoded message/rfc822 detected");
+            instream = new Base64InputStream(dataStream);                    
+        } else if (MimeUtil.isQuotedPrintableEncoded(transferEncoding)) {
+            log.debug("quoted-printable encoded message/rfc822 detected");
+            instream = new QuotedPrintableInputStream(dataStream);                    
+        } else {
+            instream = dataStream;
+        }
+        
+        if (recursionMode == RecursionMode.M_RAW) {
+            RawEntity message = new RawEntity(instream);
+            return message;
+        } else {
+            MimeEntity message = new MimeEntity(
+                    rootStream, 
+                    new BufferedLineReaderInputStream(
+                            instream, 
+                            4 * 1024,
+                            config.getMaxLineLen()),
+                    body, 
+                    EntityStates.T_START_MESSAGE, 
+                    EntityStates.T_END_MESSAGE,
+                    config);
+            message.setRecursionMode(recursionMode);
+            return message;
+        }
+    }
+    
+    private EntityStateMachine nextMimeEntity() {
+        if (recursionMode == RecursionMode.M_RAW) {
+            RawEntity message = new RawEntity(mimeStream);
+            return message;
+        } else {
+            BufferedLineReaderInputStream stream = new BufferedLineReaderInputStream(
+                    mimeStream, 
+                    4 * 1024,
+                    config.getMaxLineLen());
+            MimeEntity mimeentity = new MimeEntity(
+                    rootStream, 
+                    stream,
+                    body, 
+                    EntityStates.T_START_BODYPART, 
+                    EntityStates.T_END_BODYPART,
+                    config);
+            mimeentity.setRecursionMode(recursionMode);
+            return mimeentity;
+        }
+    }
+    
+    public InputStream getContentStream() {
+        switch (state) {
+        case EntityStates.T_START_MULTIPART:
+        case EntityStates.T_PREAMBLE:
+        case EntityStates.T_EPILOGUE:
+        case EntityStates.T_BODY:
+            return this.dataStream;
+        default:
+            throw new IllegalStateException("Invalid state: " + stateToString(state));
+        }
+    }
+
+}



---------------------------------------------------------------------
To unsubscribe, e-mail: server-dev-unsubscribe@james.apache.org
For additional commands, e-mail: server-dev-help@james.apache.org


Re: svn commit: r697409

Posted by Oleg Kalnichevski <ol...@apache.org>.
On Sat, 2008-09-20 at 18:54 +0000, olegk@apache.org wrote:
> Author: olegk
> Date: Sat Sep 20 11:54:15 2008
> New Revision: 697409
> 
> URL: http://svn.apache.org/viewvc?rev=697409&view=rev
> Log:
> MIME4J-57: enforce a limit on the maximum line length
> 
> Added:
>     james/mime4j/trunk/src/main/java/org/apache/james/mime4j/parser/MimeEntityConfig.java   (with props)
> Modified:
>     james/mime4j/trunk/src/main/java/org/apache/james/mime4j/io/BufferedLineReaderInputStream.java
>     james/mime4j/trunk/src/main/java/org/apache/james/mime4j/io/LineReaderInputStreamAdaptor.java
>     james/mime4j/trunk/src/main/java/org/apache/james/mime4j/message/Message.java
>     james/mime4j/trunk/src/main/java/org/apache/james/mime4j/parser/AbstractEntity.java
>     james/mime4j/trunk/src/main/java/org/apache/james/mime4j/parser/MimeEntity.java
>     james/mime4j/trunk/src/main/java/org/apache/james/mime4j/parser/MimeStreamParser.java
>     james/mime4j/trunk/src/main/java/org/apache/james/mime4j/parser/MimeTokenStream.java
>     james/mime4j/trunk/src/test/java/org/apache/james/mime4j/message/ExampleMessagesRoundtripTest.java
>     james/mime4j/trunk/src/test/java/org/apache/james/mime4j/message/MessageParserTest.java
>     james/mime4j/trunk/src/test/java/org/apache/james/mime4j/parser/MimeStreamParserExampleMessagesTest.java
>     james/mime4j/trunk/src/test/java/org/apache/james/mime4j/stream/BufferedLineReaderInputStreamTest.java
>     james/mime4j/trunk/src/test/java/org/apache/james/mime4j/stream/LineReaderInputStreamAdaptorTest.java
> 

Folks,

I am really sorry. I do not how that happened. I just upgraded to
Eclipse 3.4 and I guess something went really screwy with the subsclipse
plugin.

Oleg   


---------------------------------------------------------------------
To unsubscribe, e-mail: server-dev-unsubscribe@james.apache.org
For additional commands, e-mail: server-dev-help@james.apache.org