geronimo-scm mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From bsny...@apache.org
Subject svn commit: r381393 [4/5] - in /geronimo/specs/trunk/geronimo-spec-javamail/src: main/java/javax/mail/internet/ main/java/org/apache/geronimo/mail/util/ main/resources/META-INF/ test/java/javax/mail/internet/
Date Mon, 27 Feb 2006 17:38:09 GMT
Modified: geronimo/specs/trunk/geronimo-spec-javamail/src/main/java/org/apache/geronimo/mail/util/Base64Encoder.java
URL: http://svn.apache.org/viewcvs/geronimo/specs/trunk/geronimo-spec-javamail/src/main/java/org/apache/geronimo/mail/util/Base64Encoder.java?rev=381393&r1=381392&r2=381393&view=diff
==============================================================================
--- geronimo/specs/trunk/geronimo-spec-javamail/src/main/java/org/apache/geronimo/mail/util/Base64Encoder.java (original)
+++ geronimo/specs/trunk/geronimo-spec-javamail/src/main/java/org/apache/geronimo/mail/util/Base64Encoder.java Mon Feb 27 09:38:03 2006
@@ -18,7 +18,9 @@
 package org.apache.geronimo.mail.util;
 
 import java.io.IOException;
+import java.io.InputStream;
 import java.io.OutputStream;
+import java.io.PrintStream;
 
 public class Base64Encoder
     implements Encoder
@@ -44,7 +46,7 @@
     /*
      * set up the decoding table.
      */
-    protected final byte[] decodingTable = new byte[128];
+    protected final byte[] decodingTable = new byte[256];
 
     protected void initialiseDecodingTable()
     {
@@ -336,5 +338,214 @@
         }
 
         return length;
+    }
+
+    /**
+     * decode the base 64 encoded byte data writing it to the provided byte array buffer.
+     *
+     * @return the number of bytes produced.
+     */
+    public int decode(byte[] data, int off, int length, byte[] out) throws IOException
+    {
+        byte[]    bytes;
+        byte    b1, b2, b3, b4;
+        int        outLen = 0;
+
+        int        end = off + length;
+
+        while (end > 0)
+        {
+            if (!ignore((char)data[end - 1]))
+            {
+                break;
+            }
+
+            end--;
+        }
+
+        int  i = off;
+        int  finish = end - 4;
+
+        while (i < finish)
+        {
+            while ((i < finish) && ignore((char)data[i]))
+            {
+                i++;
+            }
+
+            b1 = decodingTable[data[i++]];
+
+            while ((i < finish) && ignore((char)data[i]))
+            {
+                i++;
+            }
+
+            b2 = decodingTable[data[i++]];
+
+            while ((i < finish) && ignore((char)data[i]))
+            {
+                i++;
+            }
+
+            b3 = decodingTable[data[i++]];
+
+            while ((i < finish) && ignore((char)data[i]))
+            {
+                i++;
+            }
+
+            b4 = decodingTable[data[i++]];
+
+            out[outLen++] = (byte)((b1 << 2) | (b2 >> 4));
+            out[outLen++] = (byte)((b2 << 4) | (b3 >> 2));
+            out[outLen++] = (byte)((b3 << 6) | b4);
+        }
+
+        if (data[end - 2] == padding)
+        {
+            b1 = decodingTable[data[end - 4]];
+            b2 = decodingTable[data[end - 3]];
+
+            out[outLen++] = (byte)((b1 << 2) | (b2 >> 4));
+        }
+        else if (data[end - 1] == padding)
+        {
+            b1 = decodingTable[data[end - 4]];
+            b2 = decodingTable[data[end - 3]];
+            b3 = decodingTable[data[end - 2]];
+
+            out[outLen++] = (byte)((b1 << 2) | (b2 >> 4));
+            out[outLen++] = (byte)((b2 << 4) | (b3 >> 2));
+        }
+        else
+        {
+            b1 = decodingTable[data[end - 4]];
+            b2 = decodingTable[data[end - 3]];
+            b3 = decodingTable[data[end - 2]];
+            b4 = decodingTable[data[end - 1]];
+
+            out[outLen++] = (byte)((b1 << 2) | (b2 >> 4));
+            out[outLen++] = (byte)((b2 << 4) | (b3 >> 2));
+            out[outLen++] = (byte)((b3 << 6) | b4);
+        }
+
+        return outLen;
+    }
+
+    /**
+     * Test if a character is a valid Base64 encoding character.  This
+     * must be either a valid digit or the padding character ("=").
+     *
+     * @param ch     The test character.
+     *
+     * @return true if this is valid in Base64 encoded data, false otherwise.
+     */
+    public boolean isValidBase64(int ch) {
+        // 'A' has the value 0 in the decoding table, so we need a special one for that
+        return ch == padding || ch == 'A' || decodingTable[ch] != 0;
+    }
+
+
+    /**
+     * Perform RFC-2047 word encoding using Base64 data encoding.
+     *
+     * @param in      The source for the encoded data.
+     * @param charset The charset tag to be added to each encoded data section.
+     * @param out     The output stream where the encoded data is to be written.
+     * @param fold    Controls whether separate sections of encoded data are separated by
+     *                linebreaks or whitespace.
+     *
+     * @exception IOException
+     */
+    public void encodeWord(InputStream in, String charset, OutputStream out, boolean fold) throws IOException
+    {
+        PrintStream writer = new PrintStream(out);
+
+        // encoded words are restricted to 76 bytes, including the control adornments.
+        int limit = 76 - 7 - charset.length();
+        boolean firstLine = true;
+        StringBuffer encodedString = new StringBuffer(76);
+
+        while (true) {
+            // encode the next segment.
+            encode(in, encodedString, limit);
+            // if we're out of data, nothing will be encoded.
+            if (encodedString.length() == 0) {
+                break;
+            }
+
+            // if we have more than one segment, we need to insert separators.  Depending on whether folding
+            // was requested, this is either a blank or a linebreak.
+            if (!firstLine) {
+                if (fold) {
+                    writer.print("\r\n");
+                }
+                else {
+                    writer.print(" ");
+                }
+            }
+
+            // add the encoded word header
+            writer.print("=?");
+            writer.print(charset);
+            writer.print("?B?");
+            // the data
+            writer.print(encodedString.toString());
+            // and the word terminator.
+            writer.print("?=");
+            writer.flush();
+
+            // reset our string buffer for the next segment.
+            encodedString.setLength(0);
+        }
+    }
+
+    /**
+     * encode the input data producing a base 64 output stream.
+     *
+     * @return the number of bytes produced.
+     */
+    public void encode(InputStream in, StringBuffer out, int limit) throws IOException
+    {
+        int count = limit / 4;
+        byte [] inBuffer = new byte[3];
+
+        while (count-- > 0) {
+
+            int readCount = in.read(inBuffer);
+            // did we get a full triplet?  that's an easy encoding.
+            if (readCount == 3) {
+                byte a1 = (byte)(inBuffer[0] & 0xff);
+                byte a2 = (byte)(inBuffer[1] & 0xff);
+                byte a3 = (byte)(inBuffer[2] & 0xff);
+
+                out.append((char)encodingTable[(a1 >>> 2) & 0x3f]);
+                out.append((char)encodingTable[((a1 << 4) | (a2 >>> 4)) & 0x3f]);
+                out.append((char)encodingTable[((a2 << 2) | (a3 >>> 6)) & 0x3f]);
+                out.append((char)encodingTable[a3 & 0x3f]);
+            }
+            else if (readCount <= 0) {
+                // eof condition, don'e entirely.
+                return;
+            }
+            else if (readCount == 1) {
+                byte a1 = (byte)(inBuffer[0] & 0xff);
+                out.append((char)encodingTable[(a1 >>> 2) & 0x3f]);
+                out.append((char)encodingTable[(a1 << 4) & 0x3f]);
+                out.append((char)padding);
+                out.append((char)padding);
+                return;
+            }
+            else if (readCount == 2) {
+                byte a1 = (byte)(inBuffer[0] & 0xff);
+                byte a2 = (byte)(inBuffer[1] & 0xff);
+
+                out.append((char)encodingTable[(a1 >>> 2) & 0x3f]);
+                out.append((char)encodingTable[((a1 << 4) | (a2 >>> 4)) & 0x3f]);
+                out.append((char)encodingTable[(a2 << 2) & 0x3f]);
+                out.append((char)padding);
+                return;
+            }
+        }
     }
 }

Added: geronimo/specs/trunk/geronimo-spec-javamail/src/main/java/org/apache/geronimo/mail/util/Base64EncoderStream.java
URL: http://svn.apache.org/viewcvs/geronimo/specs/trunk/geronimo-spec-javamail/src/main/java/org/apache/geronimo/mail/util/Base64EncoderStream.java?rev=381393&view=auto
==============================================================================
--- geronimo/specs/trunk/geronimo-spec-javamail/src/main/java/org/apache/geronimo/mail/util/Base64EncoderStream.java (added)
+++ geronimo/specs/trunk/geronimo-spec-javamail/src/main/java/org/apache/geronimo/mail/util/Base64EncoderStream.java Mon Feb 27 09:38:03 2006
@@ -0,0 +1,170 @@
+/**
+ *
+ * Copyright 2003-2004 The Apache Software Foundation
+ *
+ *  Licensed 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.geronimo.mail.util;
+
+import java.io.IOException;
+import java.io.OutputStream;
+import java.io.FilterOutputStream;
+
+/**
+ * An implementation of a FilterOutputStream that encodes the
+ * stream data in BASE64 encoding format.  This version does the
+ * encoding "on the fly" rather than encoding a single block of
+ * data.  Since this version is intended for use by the MimeUtilty class,
+ * it also handles line breaks in the encoded data.
+ */
+public class Base64EncoderStream extends FilterOutputStream {
+
+    // our Filtered stream writes everything out as byte data.  This allows the CRLF sequence to
+    // be written with a single call.
+    protected static final byte[] CRLF = { '\r', '\n' };
+
+    // our hex encoder utility class.
+    protected Base64Encoder encoder = new Base64Encoder();
+
+    // our default for line breaks
+    protected static final int DEFAULT_LINEBREAK = 76;
+
+    // Data can only be written out in complete units of 3 bytes encoded as 4.  Therefore, we need to buffer
+    // as many as 2 bytes to fill out an encoding unit.
+
+    // the buffered byte count
+    protected int bufferedBytes = 0;
+
+    // we'll encode this part once it is filled up.
+    protected byte[] buffer = new byte[3];
+
+
+    // the size we process line breaks at.  If this is Integer.MAX_VALUE, no line breaks are handled.
+    protected int lineBreak;
+
+    // the number of encoded characters we've written to the stream, which determines where we
+    // insert line breaks.
+    protected int outputCount;
+
+    /**
+     * Create a Base64 encoder stream that wraps a specifed stream
+     * using the default line break size.
+     *
+     * @param out    The wrapped output stream.
+     */
+    public Base64EncoderStream(OutputStream out) {
+        this(out, DEFAULT_LINEBREAK);
+    }
+
+
+    public Base64EncoderStream(OutputStream out, int lineBreak) {
+        super(out);
+        // lines are processed only in multiple of 4, so round this down.
+        this.lineBreak = (lineBreak / 4) * 4 ;
+    }
+
+    // in order for this to work, we need to override the 3 different signatures for write
+
+    public void write(int ch) throws IOException {
+        // store this in the buffer.
+        buffer[bufferedBytes++] = (byte)ch;
+        // if the buffer is filled, encode these bytes
+        if (bufferedBytes == 3) {
+            // check for room in the current line for this character
+            checkEOL(4);
+            // write these directly to the stream.
+            encoder.encode(buffer, 0, 3, out);
+            bufferedBytes = 0;
+            // and update the line length checkers
+            updateLineCount(4);
+        }
+    }
+
+    public void write(byte [] data) throws IOException {
+        write(data, 0, data.length);
+    }
+
+    public void write(byte [] data, int offset, int length) throws IOException {
+        // if we have something in the buffer, we need to write enough bytes out to flush
+        // those into the output stream AND continue on to finish off a line.  Once we're done there
+        // we can write additional data out in complete blocks.
+        while ((bufferedBytes > 0 || outputCount > 0) && length > 0) {
+            write(data[offset++]);
+            length--;
+        }
+
+        if (length > 0) {
+            // no linebreaks requested?  YES!!!!!, we can just dispose of the lot with one call.
+            if (lineBreak == Integer.MAX_VALUE) {
+                encoder.encode(data, offset, length, out);
+            }
+            else {
+                // calculate the size of a segment we can encode directly as a line.
+                int segmentSize = (lineBreak / 4) * 3;
+
+                // write this out a block at a time, with separators between.
+                while (length > segmentSize) {
+                    // encode a segment
+                    encoder.encode(data, offset, segmentSize, out);
+                    // write an EOL marker
+                    out.write(CRLF);
+                    offset += segmentSize;
+                    length -= segmentSize;
+                }
+
+                // any remainder we write out a byte at a time to manage the groupings and
+                // the line count appropriately.
+                if (length > 0) {
+                    while (length > 0) {
+                        write(data[offset++]);
+                        length--;
+                    }
+                }
+            }
+        }
+    }
+
+
+    /**
+     * Check for whether we're about the reach the end of our
+     * line limit for an update that's about to occur.  If we will
+     * overflow, then a line break is inserted.
+     *
+     * @param required The space required for this pending write.
+     *
+     * @exception IOException
+     */
+    private void checkEOL(int required) throws IOException {
+        if (lineBreak != Integer.MAX_VALUE) {
+            // if this write would exceed the line maximum, add a linebreak to the stream.
+            if (outputCount + required > lineBreak) {
+                out.write(CRLF);
+                outputCount = 0;
+            }
+        }
+    }
+
+    /**
+     * Update the counter of characters on the current working line.
+     * This is conditional if we're not working with a line limit.
+     *
+     * @param added  The number of characters just added.
+     */
+    private void updateLineCount(int added) {
+        if (lineBreak != Integer.MAX_VALUE) {
+            outputCount += added;
+        }
+    }
+}
+

Propchange: geronimo/specs/trunk/geronimo-spec-javamail/src/main/java/org/apache/geronimo/mail/util/Base64EncoderStream.java
------------------------------------------------------------------------------
    svn:eol-style = native

Propchange: geronimo/specs/trunk/geronimo-spec-javamail/src/main/java/org/apache/geronimo/mail/util/Base64EncoderStream.java
------------------------------------------------------------------------------
    svn:keywords = Date Author Id Revision HeadURL

Propchange: geronimo/specs/trunk/geronimo-spec-javamail/src/main/java/org/apache/geronimo/mail/util/Base64EncoderStream.java
------------------------------------------------------------------------------
    svn:mime-type = text/plain

Added: geronimo/specs/trunk/geronimo-spec-javamail/src/main/java/org/apache/geronimo/mail/util/QuotedPrintable.java
URL: http://svn.apache.org/viewcvs/geronimo/specs/trunk/geronimo-spec-javamail/src/main/java/org/apache/geronimo/mail/util/QuotedPrintable.java?rev=381393&view=auto
==============================================================================
--- geronimo/specs/trunk/geronimo-spec-javamail/src/main/java/org/apache/geronimo/mail/util/QuotedPrintable.java (added)
+++ geronimo/specs/trunk/geronimo-spec-javamail/src/main/java/org/apache/geronimo/mail/util/QuotedPrintable.java Mon Feb 27 09:38:03 2006
@@ -0,0 +1,175 @@
+/**
+ *
+ * Copyright 2003-2004 The Apache Software Foundation
+ *
+ *  Licensed 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.geronimo.mail.util;
+
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+
+public class QuotedPrintable {
+    // NOTE:  the QuotedPrintableEncoder class needs to keep some active state about what's going on with
+    // respect to line breaks and significant white spaces.  This makes it difficult to keep one static
+    // instance of the decode around for reuse.
+
+
+    /**
+     * encode the input data producing a Q-P encoded byte array.
+     *
+     * @return a byte array containing the Q-P encoded data.
+     */
+    public static byte[] encode(
+        byte[]    data)
+    {
+        return encode(data, 0, data.length);
+    }
+
+    /**
+     * encode the input data producing a Q-P encoded byte array.
+     *
+     * @return a byte array containing the Q-P encoded data.
+     */
+    public static byte[] encode(
+        byte[]    data,
+        int       off,
+        int       length)
+    {
+        QuotedPrintableEncoder encoder = new QuotedPrintableEncoder();
+
+        ByteArrayOutputStream    bOut = new ByteArrayOutputStream();
+
+        try
+        {
+            encoder.encode(data, off, length, bOut);
+        }
+        catch (IOException e)
+        {
+            throw new RuntimeException("exception encoding Q-P encoded string: " + e);
+        }
+
+        return bOut.toByteArray();
+    }
+
+    /**
+     * Q-P encode the byte data writing it to the given output stream.
+     *
+     * @return the number of bytes produced.
+     */
+    public static int encode(
+        byte[]         data,
+        OutputStream   out)
+        throws IOException
+    {
+        QuotedPrintableEncoder encoder = new QuotedPrintableEncoder();
+
+        return encoder.encode(data, 0, data.length, out);
+    }
+
+    /**
+     * Q-P encode the byte data writing it to the given output stream.
+     *
+     * @return the number of bytes produced.
+     */
+    public static int encode(
+        byte[]         data,
+        int            off,
+        int            length,
+        OutputStream   out)
+        throws IOException
+    {
+        QuotedPrintableEncoder encoder = new QuotedPrintableEncoder();
+        return encoder.encode(data, 0, data.length, out);
+    }
+
+    /**
+     * decode the Q-P encoded input data. It is assumed the input data is valid.
+     *
+     * @return a byte array representing the decoded data.
+     */
+    public static byte[] decode(
+        byte[]    data)
+    {
+        ByteArrayOutputStream    bOut = new ByteArrayOutputStream();
+
+        QuotedPrintableEncoder encoder = new QuotedPrintableEncoder();
+        try
+        {
+            encoder.decode(data, 0, data.length, bOut);
+        }
+        catch (IOException e)
+        {
+            throw new RuntimeException("exception decoding Q-P encoded string: " + e);
+        }
+
+        return bOut.toByteArray();
+    }
+
+    /**
+     * decode the UUEncided String data.
+     *
+     * @return a byte array representing the decoded data.
+     */
+    public static byte[] decode(
+        String    data)
+    {
+        QuotedPrintableEncoder encoder = new QuotedPrintableEncoder();
+        ByteArrayOutputStream    bOut = new ByteArrayOutputStream();
+
+        try
+        {
+            encoder.decode(data, bOut);
+        }
+        catch (IOException e)
+        {
+            throw new RuntimeException("exception decoding Q-P encoded string: " + e);
+        }
+
+        return bOut.toByteArray();
+    }
+
+    /**
+     * decode the Q-P encoded encoded String data writing it to the given output stream.
+     *
+     * @return the number of bytes produced.
+     */
+    public static int decode(
+        String          data,
+        OutputStream    out)
+        throws IOException
+    {
+        QuotedPrintableEncoder encoder = new QuotedPrintableEncoder();
+        return encoder.decode(data, out);
+    }
+
+    /**
+     * decode the base Q-P encoded String data writing it to the given output stream,
+     * whitespace characters will be ignored.
+     *
+     * @param data   The array data to decode.
+     * @param out    The output stream for the data.
+     *
+     * @return the number of bytes produced.
+     * @exception IOException
+     */
+    public static int decode(byte [] data, OutputStream out) throws IOException
+    {
+        QuotedPrintableEncoder encoder = new QuotedPrintableEncoder();
+        return encoder.decode(data, 0, data.length, out);
+    }
+}
+

Propchange: geronimo/specs/trunk/geronimo-spec-javamail/src/main/java/org/apache/geronimo/mail/util/QuotedPrintable.java
------------------------------------------------------------------------------
    svn:eol-style = native

Propchange: geronimo/specs/trunk/geronimo-spec-javamail/src/main/java/org/apache/geronimo/mail/util/QuotedPrintable.java
------------------------------------------------------------------------------
    svn:keywords = Date Author Id Revision HeadURL

Propchange: geronimo/specs/trunk/geronimo-spec-javamail/src/main/java/org/apache/geronimo/mail/util/QuotedPrintable.java
------------------------------------------------------------------------------
    svn:mime-type = text/plain

Added: geronimo/specs/trunk/geronimo-spec-javamail/src/main/java/org/apache/geronimo/mail/util/QuotedPrintableDecoderStream.java
URL: http://svn.apache.org/viewcvs/geronimo/specs/trunk/geronimo-spec-javamail/src/main/java/org/apache/geronimo/mail/util/QuotedPrintableDecoderStream.java?rev=381393&view=auto
==============================================================================
--- geronimo/specs/trunk/geronimo-spec-javamail/src/main/java/org/apache/geronimo/mail/util/QuotedPrintableDecoderStream.java (added)
+++ geronimo/specs/trunk/geronimo-spec-javamail/src/main/java/org/apache/geronimo/mail/util/QuotedPrintableDecoderStream.java Mon Feb 27 09:38:03 2006
@@ -0,0 +1,112 @@
+/**
+ *
+ * Copyright 2003-2004 The Apache Software Foundation
+ *
+ *  Licensed 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.geronimo.mail.util;
+
+import java.io.ByteArrayOutputStream;
+import java.io.FilterInputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.UnsupportedEncodingException;
+
+/**
+ * An implementation of a FilterOutputStream that decodes the
+ * stream data in Q-P encoding format.  This version does the
+ * decoding "on the fly" rather than decoding a single block of
+ * data.  Since this version is intended for use by the MimeUtilty class,
+ * it also handles line breaks in the encoded data.
+ */
+public class QuotedPrintableDecoderStream extends FilterInputStream {
+    // our decoder for processing the data
+    protected QuotedPrintableEncoder decoder;
+
+
+    /**
+     * Stream constructor.
+     *
+     * @param in     The InputStream this stream is filtering.
+     */
+    public QuotedPrintableDecoderStream(InputStream in) {
+        super(in);
+        decoder = new QuotedPrintableEncoder();
+    }
+
+    // in order to function as a filter, these streams need to override the different
+    // read() signatures.
+
+
+    /**
+     * Read a single byte from the stream.
+     *
+     * @return The next byte of the stream.  Returns -1 for an EOF condition.
+     * @exception IOException
+     */
+    public int read() throws IOException
+    {
+        // just get a single byte from the decoder
+        return decoder.decode(in);
+    }
+
+
+    /**
+     * Read a buffer of data from the input stream.
+     *
+     * @param buffer The target byte array the data is placed into.
+     * @param offset The starting offset for the read data.
+     * @param length How much data is requested.
+     *
+     * @return The number of bytes of data read.
+     * @exception IOException
+     */
+    public int read(byte [] buffer, int offset, int length) throws IOException {
+
+        for (int i = 0; i < length; i++) {
+            int ch = decoder.decode(in);
+            if (ch == -1) {
+                return i;
+            }
+            buffer[offset + i] = (byte)ch;
+        }
+
+        return length;
+    }
+
+
+    /**
+     * Indicate whether this stream supports the mark() operation.
+     *
+     * @return Always returns false.
+     */
+    public boolean markSupported() {
+        return false;
+    }
+
+
+    /**
+     * Give an estimate of how much additional data is available
+     * from this stream.
+     *
+     * @return Always returns -1.
+     * @exception IOException
+     */
+    public int available() throws IOException {
+        // this is almost impossible to determine at this point
+        return -1;
+    }
+}
+
+

Propchange: geronimo/specs/trunk/geronimo-spec-javamail/src/main/java/org/apache/geronimo/mail/util/QuotedPrintableDecoderStream.java
------------------------------------------------------------------------------
    svn:eol-style = native

Propchange: geronimo/specs/trunk/geronimo-spec-javamail/src/main/java/org/apache/geronimo/mail/util/QuotedPrintableDecoderStream.java
------------------------------------------------------------------------------
    svn:keywords = Date Author Id Revision HeadURL

Propchange: geronimo/specs/trunk/geronimo-spec-javamail/src/main/java/org/apache/geronimo/mail/util/QuotedPrintableDecoderStream.java
------------------------------------------------------------------------------
    svn:mime-type = text/plain

Added: geronimo/specs/trunk/geronimo-spec-javamail/src/main/java/org/apache/geronimo/mail/util/QuotedPrintableEncoder.java
URL: http://svn.apache.org/viewcvs/geronimo/specs/trunk/geronimo-spec-javamail/src/main/java/org/apache/geronimo/mail/util/QuotedPrintableEncoder.java?rev=381393&view=auto
==============================================================================
--- geronimo/specs/trunk/geronimo-spec-javamail/src/main/java/org/apache/geronimo/mail/util/QuotedPrintableEncoder.java (added)
+++ geronimo/specs/trunk/geronimo-spec-javamail/src/main/java/org/apache/geronimo/mail/util/QuotedPrintableEncoder.java Mon Feb 27 09:38:03 2006
@@ -0,0 +1,678 @@
+/**
+ *
+ * Copyright 2003-2004 The Apache Software Foundation
+ *
+ *  Licensed 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.geronimo.mail.util;
+
+import java.io.EOFException;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.io.PrintStream;
+import java.io.PushbackInputStream;
+import java.io.UnsupportedEncodingException;
+
+public class QuotedPrintableEncoder implements Encoder {
+
+    static protected final byte[] encodingTable =
+    {
+        (byte)'0', (byte)'1', (byte)'2', (byte)'3', (byte)'4', (byte)'5', (byte)'6', (byte)'7',
+        (byte)'8', (byte)'9', (byte)'A', (byte)'B', (byte)'C', (byte)'D', (byte)'E', (byte)'F'
+    };
+
+    /*
+     * set up the decoding table.
+     */
+    static protected final byte[] decodingTable = new byte[128];
+
+    static {
+        // initialize the decoding table
+        for (int i = 0; i < encodingTable.length; i++)
+        {
+            decodingTable[encodingTable[i]] = (byte)i;
+        }
+    }
+
+
+    // default number of characters we will write per line.
+    static private final int DEFAULT_CHARS_PER_LINE = 76;
+
+    // the output stream we're wrapped around
+    protected OutputStream out;
+    // the number of bytes written;
+    protected int bytesWritten = 0;
+    // number of bytes written on the current line
+    protected int lineCount = 0;
+    // line length we're dealing with
+    protected int lineLength;
+    // number of deferred whitespace characters in decode mode.
+    protected int deferredWhitespace = 0;
+
+    protected int cachedCharacter = -1;
+
+    // indicates whether the last character was a '\r', potentially part of a CRLF sequence.
+    protected boolean lastCR = false;
+    // remember whether last character was a white space.
+    protected boolean lastWhitespace = false;
+
+    public QuotedPrintableEncoder() {
+        this(null, DEFAULT_CHARS_PER_LINE);
+    }
+
+    public QuotedPrintableEncoder(OutputStream out) {
+        this(out, DEFAULT_CHARS_PER_LINE);
+    }
+
+    public QuotedPrintableEncoder(OutputStream out, int lineLength) {
+        this.out = out;
+        this.lineLength = lineLength;
+    }
+
+    private void checkDeferred(int ch) throws IOException {
+        // was the last character we looked at a whitespace?  Try to decide what to do with it now.
+        if (lastWhitespace) {
+            // if this whitespace is at the end of the line, write it out encoded
+            if (ch == '\r' || ch == '\n') {
+                writeEncodedCharacter(' ');
+            }
+            else {
+                // we can write this out without encoding.
+                writeCharacter(' ');
+            }
+            // we always turn this off.
+            lastWhitespace = false;
+        }
+        // deferred carriage return?
+        else if (lastCR) {
+            // if the char following the CR was not a new line, write an EOL now.
+            if (ch != '\n') {
+                writeEOL();
+            }
+            // we always turn this off too
+            lastCR = false;
+        }
+    }
+
+
+    /**
+     * encode the input data producing a UUEncoded output stream.
+     *
+     * @param data   The array of byte data.
+     * @param off    The starting offset within the data.
+     * @param length Length of the data to encode.
+     *
+     * @return the number of bytes produced.
+     */
+    public int encode(byte[] data, int off, int length) throws IOException {
+        int endOffset = off + length;
+
+        while (off < endOffset) {
+            // get the character
+            byte ch = data[off++];
+
+            // handle the encoding of this character.
+            encode(ch);
+        }
+
+        return bytesWritten;
+    }
+
+
+    public void encode(int ch) throws IOException {
+        // make sure this is just a single byte value.
+        ch = ch &0xFF;
+
+        // see if we had to defer handling of a whitespace or '\r' character, and handle it if necessary.
+        checkDeferred(ch);
+        // different characters require special handling.
+        switch (ch) {
+            // spaces require special handling.  If the next character is a line terminator, then
+            // the space needs to be encoded.
+            case ' ':
+            {
+                // at this point, we don't know whether this needs encoding or not.  If the next
+                // character is a linend, it gets encoded.  If anything else, we just write it as is.
+                lastWhitespace = true;
+                // turn off any CR flags.
+                lastCR = false;
+                break;
+            }
+
+            // carriage return, which may be part of a CRLF sequence.
+            case '\r':
+            {
+                // just flag this until we see the next character.
+                lastCR = true;
+                break;
+            }
+
+            // a new line character...we need to check to see if it was paired up with a '\r' char.
+            case '\n':
+            {
+                // we always write this out for a newline.  We defer CRs until we see if the LF follows.
+                writeEOL();
+                break;
+            }
+
+            // an '=' is the escape character for an encoded character, so it must also
+            // be written encoded.
+            case '=':
+            {
+                writeEncodedCharacter(ch);
+                break;
+            }
+
+            // all other characters.  If outside the printable character range, write it encoded.
+            default:
+            {
+                if (ch < 32 || ch >= 127) {
+                    writeEncodedCharacter(ch);
+                }
+                else {
+                    writeCharacter(ch);
+                }
+                break;
+            }
+        }
+    }
+
+
+    /**
+     * encode the input data producing a UUEncoded output stream.
+     *
+     * @param data   The array of byte data.
+     * @param off    The starting offset within the data.
+     * @param length Length of the data to encode.
+     *
+     * @return the number of bytes produced.
+     */
+    public int encode(byte[] data, int off, int length, String specials) throws IOException {
+        int endOffset = off + length;
+
+        while (off < endOffset) {
+            // get the character
+            byte ch = data[off++];
+
+            // handle the encoding of this character.
+            encode(ch, specials);
+        }
+
+        return bytesWritten;
+    }
+
+
+    /**
+     * encode the input data producing a UUEncoded output stream.
+     *
+     * @param data   The array of byte data.
+     * @param off    The starting offset within the data.
+     * @param length Length of the data to encode.
+     *
+     * @return the number of bytes produced.
+     */
+    public int encode(PushbackInputStream in, StringBuffer out, String specials, int limit) throws IOException {
+        int count = 0;
+
+        while (count < limit) {
+            int ch = in.read();
+
+            if (ch == -1) {
+                return count;
+            }
+            // make sure this is just a single byte value.
+            ch = ch &0xFF;
+
+            // spaces require special handling.  If the next character is a line terminator, then
+            // the space needs to be encoded.
+            if (ch == ' ') {
+                // blanks get translated into underscores, because the encoded tokens can't have embedded blanks.
+                out.append('_');
+                count++;
+            }
+            // non-ascii chars and the designated specials all get encoded.
+            else if (ch < 32 || ch >= 127 || specials.indexOf(ch) != -1) {
+                // we need at least 3 characters to write this out, so we need to
+                // forget we saw this one and try in the next segment.
+                if (count + 3 > limit) {
+                    in.unread(ch);
+                    return count;
+                }
+                out.append('=');
+                out.append((char)encodingTable[ch >> 4]);
+                out.append((char)encodingTable[ch & 0x0F]);
+                count += 3;
+            }
+            else {
+                // good character, just use unchanged.
+                out.append((char)ch);
+                count++;
+            }
+        }
+        return count;
+    }
+
+
+    /**
+     * Specialized version of the decoder that handles encoding of
+     * RFC 2047 encoded word values.  This has special handling for
+     * certain characters, but less special handling for blanks and
+     * linebreaks.
+     *
+     * @param ch
+     * @param specials
+     *
+     * @exception IOException
+     */
+    public void encode(int ch, String specials) throws IOException {
+        // make sure this is just a single byte value.
+        ch = ch &0xFF;
+
+        // spaces require special handling.  If the next character is a line terminator, then
+        // the space needs to be encoded.
+        if (ch == ' ') {
+            // blanks get translated into underscores, because the encoded tokens can't have embedded blanks.
+            writeCharacter('_');
+        }
+        // non-ascii chars and the designated specials all get encoded.
+        else if (ch < 32 || ch >= 127 || specials.indexOf(ch) != -1) {
+            writeEncodedCharacter(ch);
+        }
+        else {
+            // good character, just use unchanged.
+            writeCharacter(ch);
+        }
+    }
+
+
+    /**
+     * encode the input data producing a UUEncoded output stream.
+     *
+     * @param data   The array of byte data.
+     * @param off    The starting offset within the data.
+     * @param length Length of the data to encode.
+     * @param out    The output stream the encoded data is written to.
+     *
+     * @return the number of bytes produced.
+     */
+    public int encode(byte[] data, int off, int length, OutputStream out) throws IOException {
+        // make sure we're writing to the correct stream
+        this.out = out;
+        bytesWritten = 0;
+
+        // do the actual encoding
+        return encode(data, off, length);
+    }
+
+
+    /**
+     * decode the uuencoded byte data writing it to the given output stream
+     *
+     * @param data   The array of byte data to decode.
+     * @param off    Starting offset within the array.
+     * @param length The length of data to encode.
+     * @param out    The output stream used to return the decoded data.
+     *
+     * @return the number of bytes produced.
+     * @exception IOException
+     */
+    public int decode(byte[] data, int off, int length, OutputStream out) throws IOException {
+        // make sure we're writing to the correct stream
+        this.out = out;
+
+        int endOffset = off + length;
+        int bytesWritten = 0;
+
+        while (off < endOffset) {
+            byte ch = data[off++];
+
+            // space characters are a pain.  We need to scan ahead until we find a non-space character.
+            // if the character is a line terminator, we need to discard the blanks.
+            if (ch == ' ') {
+                int trailingSpaces = 1;
+                // scan forward, counting the characters.
+                while (off < endOffset && data[off] == ' ') {
+                    // step forward and count this.
+                    off++;
+                    trailingSpaces++;
+                }
+                // is this a lineend at the current location?
+                if (off >= endOffset || data[off] == '\r' || data[off] == '\n') {
+                    // go to the next one
+                    continue;
+                }
+                else {
+                    // make sure we account for the spaces in the output count.
+                    bytesWritten += trailingSpaces;
+                    // write out the blank characters we counted and continue with the non-blank.
+                    while (trailingSpaces-- > 0) {
+                        out.write(' ');
+                    }
+                }
+            }
+            else if (ch == '=') {
+                // we found an encoded character.  Reduce the 3 char sequence to one.
+                // but first, make sure we have two characters to work with.
+                if (off + 1 >= endOffset) {
+                    throw new IOException("Invalid quoted printable encoding");
+                }
+                // convert the two bytes back from hex.
+                byte b1 = data[off++];
+                byte b2 = data[off++];
+
+                // we've found an encoded carriage return.  The next char needs to be a newline
+                if (b1 == '\r') {
+                    if (b2 != '\n') {
+                        throw new IOException("Invalid quoted printable encoding");
+                    }
+                    // this was a soft linebreak inserted by the encoding.  We just toss this away
+                    // on decode.
+                }
+                else {
+                    // this is a hex pair we need to convert back to a single byte.
+                    b1 = decodingTable[b1];
+                    b2 = decodingTable[b2];
+                    out.write((b1 << 4) | b2);
+                    // 3 bytes in, one byte out
+                    bytesWritten++;
+                }
+            }
+            else {
+                // simple character, just write it out.
+                out.write(ch);
+                bytesWritten++;
+            }
+        }
+
+        return bytesWritten;
+    }
+
+    /**
+     * Decode a byte array of data.
+     *
+     * @param data   The data array.
+     * @param out    The output stream target for the decoded data.
+     *
+     * @return The number of bytes written to the stream.
+     * @exception IOException
+     */
+    public int decodeWord(byte[] data, OutputStream out) throws IOException {
+        return decodeWord(data, 0, data.length, out);
+    }
+
+
+    /**
+     * decode the uuencoded byte data writing it to the given output stream
+     *
+     * @param data   The array of byte data to decode.
+     * @param off    Starting offset within the array.
+     * @param length The length of data to encode.
+     * @param out    The output stream used to return the decoded data.
+     *
+     * @return the number of bytes produced.
+     * @exception IOException
+     */
+    public int decodeWord(byte[] data, int off, int length, OutputStream out) throws IOException {
+        // make sure we're writing to the correct stream
+        this.out = out;
+
+        int endOffset = off + length;
+        int bytesWritten = 0;
+
+        while (off < endOffset) {
+            byte ch = data[off++];
+
+            // space characters were translated to '_' on encode, so we need to translate them back.
+            if (ch == '_') {
+                out.write(' ');
+            }
+            else if (ch == '=') {
+                // we found an encoded character.  Reduce the 3 char sequence to one.
+                // but first, make sure we have two characters to work with.
+                if (off + 1 >= endOffset) {
+                    throw new IOException("Invalid quoted printable encoding");
+                }
+                // convert the two bytes back from hex.
+                byte b1 = data[off++];
+                byte b2 = data[off++];
+
+                // we've found an encoded carriage return.  The next char needs to be a newline
+                if (b1 == '\r') {
+                    if (b2 != '\n') {
+                        throw new IOException("Invalid quoted printable encoding");
+                    }
+                    // this was a soft linebreak inserted by the encoding.  We just toss this away
+                    // on decode.
+                }
+                else {
+                    // this is a hex pair we need to convert back to a single byte.
+                    byte c1 = decodingTable[b1];
+                    byte c2 = decodingTable[b2];
+                    out.write((c1 << 4) | c2);
+                    // 3 bytes in, one byte out
+                    bytesWritten++;
+                }
+            }
+            else {
+                // simple character, just write it out.
+                out.write(ch);
+                bytesWritten++;
+            }
+        }
+
+        return bytesWritten;
+    }
+
+
+    /**
+     * decode the UUEncoded String data writing it to the given output stream.
+     *
+     * @param data   The String data to decode.
+     * @param out    The output stream to write the decoded data to.
+     *
+     * @return the number of bytes produced.
+     * @exception IOException
+     */
+    public int decode(String data, OutputStream out) throws IOException {
+        try {
+            // just get the byte data and decode.
+            byte[] bytes = data.getBytes("US-ASCII");
+            return decode(bytes, 0, bytes.length, out);
+        } catch (UnsupportedEncodingException e) {
+            throw new IOException("Invalid UUEncoding");
+        }
+    }
+
+    private void checkLineLength(int required) throws IOException {
+        // if we're at our line length limit, write out a soft line break and reset.
+        if ((lineCount + required) > lineLength ) {
+            out.write('=');
+            out.write('\r');
+            out.write('\n');
+            bytesWritten += 3;
+            lineCount = 0;
+        }
+    }
+
+
+    public void writeEncodedCharacter(int ch) throws IOException {
+        // we need 3 characters for an encoded value
+        checkLineLength(3);
+        out.write('=');
+        out.write(encodingTable[ch >> 4]);
+        out.write(encodingTable[ch & 0x0F]);
+        lineCount += 3;
+        bytesWritten += 3;
+    }
+
+
+    public void writeCharacter(int ch) throws IOException {
+        // we need 3 characters for an encoded value
+        checkLineLength(1);
+        out.write(ch);
+        lineCount++;
+        bytesWritten++;
+    }
+
+
+    public void writeEOL() throws IOException {
+        out.write('\r');
+        out.write('\n');
+        lineCount = 0;
+        bytesWritten += 3;
+    }
+
+
+    public int decode(InputStream in) throws IOException {
+
+        // we potentially need to scan over spans of whitespace characters to determine if they're real
+        // we just return blanks until the count goes to zero.
+        if (deferredWhitespace > 0) {
+            deferredWhitespace--;
+            return ' ';
+        }
+
+        // we may have needed to scan ahead to find the first non-blank character, which we would store here.
+        // hand that back once we're done with the blanks.
+        if (cachedCharacter != -1) {
+            int result = cachedCharacter;
+            cachedCharacter = -1;
+            return result;
+        }
+
+        int ch = in.read();
+
+        // reflect back an EOF condition.
+        if (ch == -1) {
+            return -1;
+        }
+
+        // space characters are a pain.  We need to scan ahead until we find a non-space character.
+        // if the character is a line terminator, we need to discard the blanks.
+        if (ch == ' ') {
+            // scan forward, counting the characters.
+            while ((ch = in.read()) == ' ') {
+                deferredWhitespace++;
+            }
+
+            // is this a lineend at the current location?
+            if (ch == -1 || ch == '\r' || ch == '\n') {
+                // those blanks we so zealously counted up don't really exist.  Clear out the counter.
+                deferredWhitespace = 0;
+                // return the real significant character now.
+                return ch;
+            }
+            else {
+            // remember this character for later, after we've used up the deferred blanks.
+                cachedCharacter = ch;
+                // return this space.  We did not include this one in the deferred count, so we're right in sync.
+                return ' ';
+            }
+        }
+        else if (ch == '=') {
+            int b1 = in.read();
+            // we need to get two characters after the quotation marker
+            if (b1 == -1) {
+                throw new IOException("Truncated quoted printable data");
+            }
+            int b2 = in.read();
+            // we need to get two characters after the quotation marker
+            if (b2 == -1) {
+                throw new IOException("Truncated quoted printable data");
+            }
+
+            // we've found an encoded carriage return.  The next char needs to be a newline
+            if (b1 == '\r') {
+                if (b2 != '\n') {
+                    throw new IOException("Invalid quoted printable encoding");
+                }
+                // this was a soft linebreak inserted by the encoding.  We just toss this away
+                // on decode.  We need to return something, so recurse and decode the next.
+                return decode(in);
+            }
+            else {
+                // this is a hex pair we need to convert back to a single byte.
+                b1 = decodingTable[b1];
+                b2 = decodingTable[b2];
+                return (b1 << 4) | b2;
+            }
+        }
+        else {
+            return ch;
+        }
+    }
+
+
+    /**
+     * Perform RFC-2047 word encoding using Q-P data encoding.
+     *
+     * @param in       The source for the encoded data.
+     * @param charset  The charset tag to be added to each encoded data section.
+     * @param specials The set of special characters that we require to encoded.
+     * @param out      The output stream where the encoded data is to be written.
+     * @param fold     Controls whether separate sections of encoded data are separated by
+     *                 linebreaks or whitespace.
+     *
+     * @exception IOException
+     */
+    public void encodeWord(InputStream in, String charset, String specials, OutputStream out, boolean fold) throws IOException
+    {
+        // we need to scan ahead in a few places, which may require pushing characters back on to the stream.
+        // make sure we have a stream where this is possible.
+        PushbackInputStream inStream = new PushbackInputStream(in);
+        PrintStream writer = new PrintStream(out);
+
+        // segments of encoded data are limited to 76 byes, including the control sections.
+        int limit = 76 - 7 - charset.length();
+        boolean firstLine = true;
+        StringBuffer encodedString = new StringBuffer(76);
+
+        while (true) {
+
+            // encode another segment of data.
+            encode(inStream, encodedString, specials, limit);
+            // nothing encoded means we've hit the end of the data.
+            if (encodedString.length() == 0) {
+                break;
+            }
+            // if we have more than one segment, we need to insert separators.  Depending on whether folding
+            // was requested, this is either a blank or a linebreak.
+            if (!firstLine) {
+                if (fold) {
+                    writer.print("\r\n");
+                }
+                else {
+                    writer.print(" ");
+                }
+            }
+
+            // add the encoded word header
+            writer.print("=?");
+            writer.print(charset);
+            writer.print("?Q?");
+            // the data
+            writer.print(encodedString.toString());
+            // and the terminator mark
+            writer.print("?=");
+            writer.flush();
+
+            // we reset the string buffer and reuse it.
+            encodedString.setLength(0);
+        }
+    }
+}
+
+
+

Propchange: geronimo/specs/trunk/geronimo-spec-javamail/src/main/java/org/apache/geronimo/mail/util/QuotedPrintableEncoder.java
------------------------------------------------------------------------------
    svn:eol-style = native

Propchange: geronimo/specs/trunk/geronimo-spec-javamail/src/main/java/org/apache/geronimo/mail/util/QuotedPrintableEncoder.java
------------------------------------------------------------------------------
    svn:keywords = Date Author Id Revision HeadURL

Propchange: geronimo/specs/trunk/geronimo-spec-javamail/src/main/java/org/apache/geronimo/mail/util/QuotedPrintableEncoder.java
------------------------------------------------------------------------------
    svn:mime-type = text/plain

Added: geronimo/specs/trunk/geronimo-spec-javamail/src/main/java/org/apache/geronimo/mail/util/QuotedPrintableEncoderStream.java
URL: http://svn.apache.org/viewcvs/geronimo/specs/trunk/geronimo-spec-javamail/src/main/java/org/apache/geronimo/mail/util/QuotedPrintableEncoderStream.java?rev=381393&view=auto
==============================================================================
--- geronimo/specs/trunk/geronimo-spec-javamail/src/main/java/org/apache/geronimo/mail/util/QuotedPrintableEncoderStream.java (added)
+++ geronimo/specs/trunk/geronimo-spec-javamail/src/main/java/org/apache/geronimo/mail/util/QuotedPrintableEncoderStream.java Mon Feb 27 09:38:03 2006
@@ -0,0 +1,85 @@
+/**
+ *
+ * Copyright 2003-2004 The Apache Software Foundation
+ *
+ *  Licensed 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.geronimo.mail.util;
+
+import java.io.IOException;
+import java.io.OutputStream;
+import java.io.FilterOutputStream;
+
+/**
+ * An implementation of a FilterOutputStream that encodes the
+ * stream data in Q-P encoding format.  This version does the
+ * encoding "on the fly" rather than encoding a single block of
+ * data.  Since this version is intended for use by the MimeUtilty class,
+ * it also handles line breaks in the encoded data.
+ */
+public class QuotedPrintableEncoderStream extends FilterOutputStream {
+    // our hex encoder utility class.
+    protected QuotedPrintableEncoder encoder;
+
+    // our default for line breaks
+    protected static final int DEFAULT_LINEBREAK = 76;
+
+    // the instance line break value
+    protected int lineBreak;
+
+    /**
+     * Create a Base64 encoder stream that wraps a specifed stream
+     * using the default line break size.
+     *
+     * @param out    The wrapped output stream.
+     */
+    public QuotedPrintableEncoderStream(OutputStream out) {
+        this(out, DEFAULT_LINEBREAK);
+    }
+
+
+    public QuotedPrintableEncoderStream(OutputStream out, int lineBreak) {
+        super(out);
+        // lines are processed only in multiple of 4, so round this down.
+        this.lineBreak = (lineBreak / 4) * 4 ;
+
+        // create an encoder configured to this amount
+        encoder = new QuotedPrintableEncoder(out, this.lineBreak);
+    }
+
+
+    public void write(int ch) throws IOException {
+        // have the encoder do the heavy lifting here.
+        encoder.encode(ch);
+    }
+
+    public void write(byte [] data) throws IOException {
+        write(data, 0, data.length);
+    }
+
+    public void write(byte [] data, int offset, int length) throws IOException {
+        // the encoder does the heavy lifting here.
+        encoder.encode(data, offset, length);
+    }
+
+    public void close() throws IOException {
+        out.close();
+    }
+
+    public void flush() throws IOException {
+        out.flush();
+    }
+}
+
+

Propchange: geronimo/specs/trunk/geronimo-spec-javamail/src/main/java/org/apache/geronimo/mail/util/QuotedPrintableEncoderStream.java
------------------------------------------------------------------------------
    svn:eol-style = native

Propchange: geronimo/specs/trunk/geronimo-spec-javamail/src/main/java/org/apache/geronimo/mail/util/QuotedPrintableEncoderStream.java
------------------------------------------------------------------------------
    svn:keywords = Date Author Id Revision HeadURL

Propchange: geronimo/specs/trunk/geronimo-spec-javamail/src/main/java/org/apache/geronimo/mail/util/QuotedPrintableEncoderStream.java
------------------------------------------------------------------------------
    svn:mime-type = text/plain

Added: geronimo/specs/trunk/geronimo-spec-javamail/src/main/java/org/apache/geronimo/mail/util/RFC2231Encoder.java
URL: http://svn.apache.org/viewcvs/geronimo/specs/trunk/geronimo-spec-javamail/src/main/java/org/apache/geronimo/mail/util/RFC2231Encoder.java?rev=381393&view=auto
==============================================================================
--- geronimo/specs/trunk/geronimo-spec-javamail/src/main/java/org/apache/geronimo/mail/util/RFC2231Encoder.java (added)
+++ geronimo/specs/trunk/geronimo-spec-javamail/src/main/java/org/apache/geronimo/mail/util/RFC2231Encoder.java Mon Feb 27 09:38:03 2006
@@ -0,0 +1,259 @@
+/**
+ *
+ * Copyright 2003-2004 The Apache Software Foundation
+ *
+ *  Licensed 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.geronimo.mail.util;
+
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.io.OutputStream;
+import java.io.UnsupportedEncodingException;
+
+import javax.mail.internet.MimeUtility;
+
+/**
+ * Encoder for RFC2231 encoded parameters
+ *
+ * RFC2231 string are encoded as
+ *
+ *    charset'language'encoded-text
+ *
+ * and
+ *
+ *    encoded-text = *(char / hexchar)
+ *
+ * where
+ *
+ *    char is any ASCII character in the range 33-126, EXCEPT
+ *    the characters "%" and " ".
+ *
+ *    hexchar is an ASCII "%" followed by two upper case
+ *    hexadecimal digits.
+ */
+
+public class RFC2231Encoder implements Encoder
+{
+    protected final byte[] encodingTable =
+        {
+            (byte)'0', (byte)'1', (byte)'2', (byte)'3', (byte)'4', (byte)'5', (byte)'6', (byte)'7',
+            (byte)'8', (byte)'9', (byte)'A', (byte)'B', (byte)'C', (byte)'D', (byte)'E', (byte)'F'
+        };
+
+    protected String DEFAULT_SPECIALS = " *\\%";
+    protected String specials = DEFAULT_SPECIALS;
+
+    /*
+     * set up the decoding table.
+     */
+    protected final byte[] decodingTable = new byte[128];
+
+    protected void initialiseDecodingTable()
+    {
+        for (int i = 0; i < encodingTable.length; i++)
+        {
+            decodingTable[encodingTable[i]] = (byte)i;
+        }
+    }
+
+    public RFC2231Encoder()
+    {
+        this(null);
+    }
+
+    public RFC2231Encoder(String specials)
+    {
+        if (specials != null) {
+            this.specials = DEFAULT_SPECIALS + specials;
+        }
+        initialiseDecodingTable();
+    }
+
+
+    /**
+     * encode the input data producing an RFC2231 output stream.
+     *
+     * @return the number of bytes produced.
+     */
+    public int encode(byte[] data, int off, int length, OutputStream out) throws IOException {
+
+        int bytesWritten = 0;
+        for (int i = off; i < (off + length); i++)
+        {
+            byte ch = data[i];
+            // character tha must be encoded?  Prefix with a '%' and encode in hex.
+            if (ch <= 32 || ch >= 127 || specials.indexOf(ch) != -1) {
+                out.write((byte)'%');
+                out.write(encodingTable[(ch >> 4)]);
+                out.write(encodingTable[ch & 0xf]);
+                bytesWritten += 3;
+            }
+            else {
+                // add unchanged.
+                out.write((byte)ch);
+                bytesWritten++;
+            }
+        }
+
+        return bytesWritten;
+    }
+
+
+    /**
+     * decode the RFC2231 encoded byte data writing it to the given output stream
+     *
+     * @return the number of bytes produced.
+     */
+    public int decode(byte[] data, int off, int length, OutputStream out) throws IOException {
+        int        outLen = 0;
+        int        end = off + length;
+
+        int i = off;
+        while (i < end)
+        {
+            byte v = data[i++];
+            // a percent is a hex character marker, need to decode a hex value.
+            if (v == '%') {
+                byte b1 = decodingTable[data[i++]];
+                byte b2 = decodingTable[data[i++]];
+                out.write((b1 << 4) | b2);
+            }
+            else {
+                // copied over unchanged.
+                out.write(v);
+            }
+            // always just one byte added
+            outLen++;
+        }
+
+        return outLen;
+    }
+
+    /**
+     * decode the RFC2231 encoded String data writing it to the given output stream.
+     *
+     * @return the number of bytes produced.
+     */
+    public int decode(String data, OutputStream out) throws IOException
+    {
+        int        length = 0;
+        int        end = data.length();
+
+        int i = 0;
+        while (i < end)
+        {
+            char v = data.charAt(i++);
+            if (v == '%') {
+                byte b1 = decodingTable[data.charAt(i++)];
+                byte b2 = decodingTable[data.charAt(i++)];
+
+                out.write((b1 << 4) | b2);
+            }
+            else {
+                out.write((byte)v);
+            }
+            length++;
+        }
+
+        return length;
+    }
+
+
+    /**
+     * Encode a string as an RFC2231 encoded parameter, using the
+     * given character set and language.
+     *
+     * @param charset  The source character set (the MIME version).
+     * @param language The encoding language.
+     * @param data     The data to encode.
+     *
+     * @return The encoded string.
+     */
+    public String encode(String charset, String language, String data) throws IOException {
+
+        byte[] bytes = null;
+        try {
+            // the charset we're adding is the MIME-defined name.  We need the java version
+            // in order to extract the bytes.
+            bytes = data.getBytes(MimeUtility.javaCharset(charset));
+        } catch (UnsupportedEncodingException e) {
+            // we have a translation problem here.
+            return null;
+        }
+
+        StringBuffer result = new StringBuffer();
+
+        // append the character set, if we have it.
+        if (charset != null) {
+            result.append(charset);
+        }
+        // the field marker is required.
+        result.append("'");
+
+        // and the same for the language.
+        if (language != null) {
+            result.append(language);
+        }
+        // the field marker is required.
+        result.append("'");
+
+        // wrap an output stream around our buffer for the decoding
+        OutputStream out = new StringBufferOutputStream(result);
+
+        // encode the data stream
+        encode(bytes, 0, bytes.length, out);
+
+        // finis!
+        return result.toString();
+    }
+
+
+    /**
+     * Decode an RFC2231 encoded string.
+     *
+     * @param data   The data to decode.
+     *
+     * @return The decoded string.
+     * @exception IOException
+     * @exception UnsupportedEncodingException
+     */
+    public String decode(String data) throws IOException, UnsupportedEncodingException {
+        // get the end of the language field
+        int charsetEnd = data.indexOf('\'');
+        // uh oh, might not be there
+        if (charsetEnd == -1) {
+            throw new IOException("Missing charset in RFC2231 encoded value");
+        }
+
+        String charset = data.substring(0, charsetEnd);
+
+        // now pull out the language the same way
+        int languageEnd = data.indexOf('\'', charsetEnd + 1);
+        if (languageEnd == -1) {
+            throw new IOException("Missing language in RFC2231 encoded value");
+        }
+
+        String language = data.substring(charsetEnd + 1, languageEnd);
+
+        ByteArrayOutputStream out = new ByteArrayOutputStream(data.length());
+
+        // decode the data
+        decode(data.substring(languageEnd + 1), out);
+
+        byte[] bytes = out.toByteArray();
+        // build a new string from this using the java version of the encoded charset.
+        return new String(bytes, 0, bytes.length, MimeUtility.javaCharset(charset));
+    }
+}

Propchange: geronimo/specs/trunk/geronimo-spec-javamail/src/main/java/org/apache/geronimo/mail/util/RFC2231Encoder.java
------------------------------------------------------------------------------
    svn:eol-style = native

Propchange: geronimo/specs/trunk/geronimo-spec-javamail/src/main/java/org/apache/geronimo/mail/util/RFC2231Encoder.java
------------------------------------------------------------------------------
    svn:keywords = Date Author Id Revision HeadURL

Propchange: geronimo/specs/trunk/geronimo-spec-javamail/src/main/java/org/apache/geronimo/mail/util/RFC2231Encoder.java
------------------------------------------------------------------------------
    svn:mime-type = text/plain

Added: geronimo/specs/trunk/geronimo-spec-javamail/src/main/java/org/apache/geronimo/mail/util/SessionUtil.java
URL: http://svn.apache.org/viewcvs/geronimo/specs/trunk/geronimo-spec-javamail/src/main/java/org/apache/geronimo/mail/util/SessionUtil.java?rev=381393&view=auto
==============================================================================
--- geronimo/specs/trunk/geronimo-spec-javamail/src/main/java/org/apache/geronimo/mail/util/SessionUtil.java (added)
+++ geronimo/specs/trunk/geronimo-spec-javamail/src/main/java/org/apache/geronimo/mail/util/SessionUtil.java Mon Feb 27 09:38:03 2006
@@ -0,0 +1,196 @@
+/**
+ *
+ * Copyright 2003-2004 The Apache Software Foundation
+ *
+ *  Licensed 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.geronimo.mail.util;
+
+import java.security.Security;
+
+import javax.mail.Session;
+
+/**
+ * Simple utility class for managing session properties.
+ */
+public class SessionUtil {
+
+    /**
+     * Get a property associated with this mail session.  Returns
+     * the provided default if it doesn't exist.
+     *
+     * @param session The attached session.
+     * @param name    The name of the property.
+     * @param defaultValue
+     *                The default value to return if the property doesn't exist.
+     *
+     * @return The property value (returns defaultValue if the property has not been set).
+     */
+    static public String getProperty(Session session, String name, String defaultValue) {
+        String result = session.getProperty(name);
+        if (result == null) {
+            return defaultValue;
+        }
+        return result;
+    }
+
+
+    /**
+     * Process a session property as a boolean value, returning
+     * either true or false.
+     *
+     * @param session The source session.
+     * @param name
+     *
+     * @return True if the property value is "true".  Returns false for any
+     *         other value (including null).
+     */
+    static public boolean isPropertyTrue(Session session, String name) {
+        String property = session.getProperty(name);
+        if (property != null) {
+            return property.equals("true");
+        }
+        return false;
+    }
+
+    /**
+     * Process a session property as a boolean value, returning
+     * either true or false.
+     *
+     * @param session The source session.
+     * @param name
+     *
+     * @return True if the property value is "false".  Returns false for
+     *         other value (including null).
+     */
+    static public boolean isPropertyFalse(Session session, String name) {
+        String property = session.getProperty(name);
+        if (property != null) {
+            return property.equals("false");
+        }
+        return false;
+    }
+
+    /**
+     * Get a property associated with this mail session as an integer value.  Returns
+     * the default value if the property doesn't exist or it doesn't have a valid int value.
+     *
+     * @param session The source session.
+     * @param name    The name of the property.
+     * @param defaultValue
+     *                The default value to return if the property doesn't exist.
+     *
+     * @return The property value converted to an int.
+     */
+    static public int getIntProperty(Session session, String name, int defaultValue) {
+        String result = session.getProperty(name);
+        if (result != null) {
+            try {
+                // convert into an int value.
+                return Integer.parseInt(result);
+            } catch (NumberFormatException e) {
+            }
+        }
+        // return default value if it doesn't exist is isn't convertable.
+        return defaultValue;
+    }
+
+
+    /**
+     * Get a property associated with this mail session as a boolean value.  Returns
+     * the default value if the property doesn't exist or it doesn't have a valid boolean value.
+     *
+     * @param session The source session.
+     * @param name    The name of the property.
+     * @param defaultValue
+     *                The default value to return if the property doesn't exist.
+     *
+     * @return The property value converted to a boolean.
+     */
+    static public boolean getBooleanProperty(Session session, String name, boolean defaultValue) {
+        String result = session.getProperty(name);
+        if (result != null) {
+            return Boolean.valueOf(result).booleanValue();
+        }
+        // return default value if it doesn't exist is isn't convertable.
+        return defaultValue;
+    }
+
+
+    /**
+     * Get a system property associated with this mail session as a boolean value.  Returns
+     * the default value if the property doesn't exist or it doesn't have a valid boolean value.
+     *
+     * @param name    The name of the property.
+     * @param defaultValue
+     *                The default value to return if the property doesn't exist.
+     *
+     * @return The property value converted to a boolean.
+     */
+    static public boolean getBooleanProperty(String name, boolean defaultValue) {
+        try {
+            String result = System.getProperty(name);
+            if (result != null) {
+                return Boolean.valueOf(result).booleanValue();
+            }
+        } catch (SecurityException e) {
+            // we can't access the property, so for all intents, it doesn't exist.
+        }
+        // return default value if it doesn't exist is isn't convertable.
+        return defaultValue;
+    }
+
+
+    /**
+     * Get a system property associated with this mail session as a boolean value.  Returns
+     * the default value if the property doesn't exist.
+     *
+     * @param name    The name of the property.
+     * @param defaultValue
+     *                The default value to return if the property doesn't exist.
+     *
+     * @return The property value
+     */
+    static public String getProperty(String name, String defaultValue) {
+        try {
+            String result = System.getProperty(name);
+            if (result != null) {
+                return result;
+            }
+        } catch (SecurityException e) {
+            // we can't access the property, so for all intents, it doesn't exist.
+        }
+        // return default value if it doesn't exist is isn't convertable.
+        return defaultValue;
+    }
+
+
+    /**
+     * Get a system property associated with this mail session as a boolean value.  Returns
+     * the default value if the property doesn't exist.
+     *
+     * @param name    The name of the property.
+     *
+     * @return The property value
+     */
+    static public String getProperty(String name) {
+        try {
+            return System.getProperty(name);
+        } catch (SecurityException e) {
+            // we can't access the property, so for all intents, it doesn't exist.
+        }
+        // return null if we got an exception.
+        return null;
+    }
+}

Propchange: geronimo/specs/trunk/geronimo-spec-javamail/src/main/java/org/apache/geronimo/mail/util/SessionUtil.java
------------------------------------------------------------------------------
    svn:eol-style = native

Propchange: geronimo/specs/trunk/geronimo-spec-javamail/src/main/java/org/apache/geronimo/mail/util/SessionUtil.java
------------------------------------------------------------------------------
    svn:keywords = Date Author Id Revision HeadURL

Propchange: geronimo/specs/trunk/geronimo-spec-javamail/src/main/java/org/apache/geronimo/mail/util/SessionUtil.java
------------------------------------------------------------------------------
    svn:mime-type = text/plain

Added: geronimo/specs/trunk/geronimo-spec-javamail/src/main/java/org/apache/geronimo/mail/util/StringBufferOutputStream.java
URL: http://svn.apache.org/viewcvs/geronimo/specs/trunk/geronimo-spec-javamail/src/main/java/org/apache/geronimo/mail/util/StringBufferOutputStream.java?rev=381393&view=auto
==============================================================================
--- geronimo/specs/trunk/geronimo-spec-javamail/src/main/java/org/apache/geronimo/mail/util/StringBufferOutputStream.java (added)
+++ geronimo/specs/trunk/geronimo-spec-javamail/src/main/java/org/apache/geronimo/mail/util/StringBufferOutputStream.java Mon Feb 27 09:38:03 2006
@@ -0,0 +1,53 @@
+/**
+ *
+ * Copyright 2003-2004 The Apache Software Foundation
+ *
+ *  Licensed 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.geronimo.mail.util;
+
+import java.io.IOException;
+import java.io.OutputStream;
+
+/**
+ * An implementation of an OutputStream that writes the data directly
+ * out to a StringBuffer object.  Useful for applications where an
+ * intermediate ByteArrayOutputStream is required to append generated
+ * characters to a StringBuffer;
+ */
+public class StringBufferOutputStream extends OutputStream {
+
+    // the target buffer
+    protected StringBuffer buffer;
+
+    /**
+     * Create an output stream that writes to the target StringBuffer
+     *
+     * @param out    The wrapped output stream.
+     */
+    public StringBufferOutputStream(StringBuffer out) {
+        buffer = out;
+    }
+
+
+    // in order for this to work, we only need override the single character form, as the others
+    // funnel through this one by default.
+    public void write(int ch) throws IOException {
+        // just append the character
+        buffer.append((char)ch);
+    }
+}
+
+
+

Propchange: geronimo/specs/trunk/geronimo-spec-javamail/src/main/java/org/apache/geronimo/mail/util/StringBufferOutputStream.java
------------------------------------------------------------------------------
    svn:eol-style = native

Propchange: geronimo/specs/trunk/geronimo-spec-javamail/src/main/java/org/apache/geronimo/mail/util/StringBufferOutputStream.java
------------------------------------------------------------------------------
    svn:keywords = Date Author Id Revision HeadURL

Propchange: geronimo/specs/trunk/geronimo-spec-javamail/src/main/java/org/apache/geronimo/mail/util/StringBufferOutputStream.java
------------------------------------------------------------------------------
    svn:mime-type = text/plain

Added: geronimo/specs/trunk/geronimo-spec-javamail/src/main/java/org/apache/geronimo/mail/util/UUDecoderStream.java
URL: http://svn.apache.org/viewcvs/geronimo/specs/trunk/geronimo-spec-javamail/src/main/java/org/apache/geronimo/mail/util/UUDecoderStream.java?rev=381393&view=auto
==============================================================================
--- geronimo/specs/trunk/geronimo-spec-javamail/src/main/java/org/apache/geronimo/mail/util/UUDecoderStream.java (added)
+++ geronimo/specs/trunk/geronimo-spec-javamail/src/main/java/org/apache/geronimo/mail/util/UUDecoderStream.java Mon Feb 27 09:38:03 2006
@@ -0,0 +1,262 @@
+/**
+ *
+ * Copyright 2003-2004 The Apache Software Foundation
+ *
+ *  Licensed 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.geronimo.mail.util;
+
+import java.io.ByteArrayOutputStream;
+import java.io.FilterInputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.UnsupportedEncodingException;
+
+/**
+ * An implementation of a FilterOutputStream that decodes the
+ * stream data in UU encoding format.  This version does the
+ * decoding "on the fly" rather than decoding a single block of
+ * data.  Since this version is intended for use by the MimeUtilty class,
+ * it also handles line breaks in the encoded data.
+ */
+public class UUDecoderStream extends FilterInputStream {
+    // maximum number of chars that can appear in a single line
+    protected static final int MAX_CHARS_PER_LINE = 45;
+
+    // our decoder for processing the data
+    protected UUEncoder decoder = new UUEncoder();
+
+    // a buffer for one decoding unit's worth of data (45 bytes).
+    protected byte[] decodedChars;
+    // count of characters in the buffer
+    protected int decodedCount = 0;
+    // index of the next decoded character
+    protected int decodedIndex = 0;
+
+    // indicates whether we've already processed the "begin" prefix.
+    protected boolean beginRead = false;
+
+
+    public UUDecoderStream(InputStream in) {
+        super(in);
+    }
+
+
+    /**
+     * Test for the existance of decoded characters in our buffer
+     * of decoded data.
+     *
+     * @return True if we currently have buffered characters.
+     */
+    private boolean dataAvailable() {
+        return decodedCount != 0;
+    }
+
+    /**
+     * Get the next buffered decoded character.
+     *
+     * @return The next decoded character in the buffer.
+     */
+    private byte getBufferedChar() {
+        decodedCount--;
+        return decodedChars[decodedIndex++];
+    }
+
+    /**
+     * Decode a requested number of bytes of data into a buffer.
+     *
+     * @return true if we were able to obtain more data, false otherwise.
+     */
+    private boolean decodeStreamData() throws IOException {
+        decodedIndex = 0;
+
+        // fill up a data buffer with input data
+        return fillEncodedBuffer() != -1;
+    }
+
+
+    /**
+     * Retrieve a single byte from the decoded characters buffer.
+     *
+     * @return The decoded character or -1 if there was an EOF condition.
+     */
+    private int getByte() throws IOException {
+        if (!dataAvailable()) {
+            if (!decodeStreamData()) {
+                return -1;
+            }
+        }
+        decodedCount--;
+        return decodedChars[decodedIndex++];
+    }
+
+    private int getBytes(byte[] data, int offset, int length) throws IOException {
+
+        int readCharacters = 0;
+        while (length > 0) {
+            // need data?  Try to get some
+            if (!dataAvailable()) {
+                // if we can't get this, return a count of how much we did get (which may be -1).
+                if (!decodeStreamData()) {
+                    return readCharacters > 0 ? readCharacters : -1;
+                }
+            }
+
+            // now copy some of the data from the decoded buffer to the target buffer
+            int copyCount = Math.min(decodedCount, length);
+            System.arraycopy(data, offset, decodedChars, decodedIndex, copyCount);
+            decodedIndex += copyCount;
+            decodedCount -= copyCount;
+            offset += copyCount;
+            length -= copyCount;
+            readCharacters += copyCount;
+        }
+        return readCharacters;
+    }
+
+    private void checkBegin() throws IOException {
+        // we only do this the first time we're requested to read from the stream.
+        if (beginRead) {
+            return;
+        }
+
+        // we might have to skip over lines to reach the marker.  If we hit the EOF without finding
+        // the begin, that's an error.
+        while (true) {
+            String line = readLine();
+            if (line == null) {
+                throw new IOException("Missing UUEncode begin command");
+            }
+
+            // is this our begin?
+            if (line.regionMatches(true, 0, "begin ", 0, 6)) {
+                // This is the droid we're looking for.....
+                beginRead = true;
+                return;
+            }
+        }
+    }
+
+
+    protected String readLine() throws IOException {
+        decodedIndex = 0;
+        // get an accumulator for the data
+        StringBuffer buffer = new StringBuffer();
+
+        // now process a character at a time.
+        int ch = in.read();
+        while (ch != -1) {
+            // a naked new line completes the line.
+            if (ch == '\n') {
+                break;
+            }
+            // a carriage return by itself is ignored...we're going to assume that this is followed
+            // by a new line because we really don't have the capability of pushing this back .
+            else if (ch == '\r') {
+                ;
+            }
+            else {
+                // add this to our buffer
+                buffer.append((byte)ch);
+            }
+            ch = in.read();
+        }
+
+        // if we didn't get any data at all, return nothing
+        if (ch == -1 && buffer.length() == 0) {
+            return null;
+        }
+        // convert this into a string.
+        return buffer.toString();
+    }
+
+
+    /**
+     * Fill our buffer of input characters for decoding from the
+     * stream.  This will attempt read a full buffer, but will
+     * terminate on an EOF or read error.  This will filter out
+     * non-Base64 encoding chars and will only return a valid
+     * multiple of 4 number of bytes.
+     *
+     * @return The count of characters read.
+     */
+    private int fillEncodedBuffer() throws IOException
+    {
+        checkBegin();
+        // reset the buffer position
+        decodedIndex = 0;
+
+        while (true) {
+
+            // we read these as character lines.  We need to be looking for the "end" marker for the
+            // end of the data.
+            String line = readLine();
+
+            // this should NOT be happening....
+            if (line == null) {
+                throw new IOException("Missing end in UUEncoded data");
+            }
+
+            // Is this the end marker?  EOF baby, EOF!
+            if (line.equalsIgnoreCase("end")) {
+                // this indicates we got nuttin' more to do.
+                return -1;
+            }
+
+            ByteArrayOutputStream out = new ByteArrayOutputStream(MAX_CHARS_PER_LINE);
+
+            byte [] lineBytes;
+            try {
+                lineBytes = line.getBytes("US-ASCII");
+            } catch (UnsupportedEncodingException e) {
+                throw new IOException("Invalid UUEncoding");
+            }
+
+            // decode this line
+            decodedCount = decoder.decode(lineBytes, 0, lineBytes.length, out);
+
+            // not just a zero-length line?
+            if (decodedCount != 0) {
+                // get the resulting byte array
+                decodedChars = out.toByteArray();
+                return decodedCount;
+            }
+        }
+    }
+
+
+    // in order to function as a filter, these streams need to override the different
+    // read() signature.
+
+    public int read() throws IOException
+    {
+        return getByte();
+    }
+
+
+    public int read(byte [] buffer, int offset, int length) throws IOException {
+        return getBytes(buffer, offset, length);
+    }
+
+
+    public boolean markSupported() {
+        return false;
+    }
+
+
+    public int available() throws IOException {
+        return ((in.available() / 4) * 3) + decodedCount;
+    }
+}
+

Propchange: geronimo/specs/trunk/geronimo-spec-javamail/src/main/java/org/apache/geronimo/mail/util/UUDecoderStream.java
------------------------------------------------------------------------------
    svn:eol-style = native

Propchange: geronimo/specs/trunk/geronimo-spec-javamail/src/main/java/org/apache/geronimo/mail/util/UUDecoderStream.java
------------------------------------------------------------------------------
    svn:keywords = Date Author Id Revision HeadURL

Propchange: geronimo/specs/trunk/geronimo-spec-javamail/src/main/java/org/apache/geronimo/mail/util/UUDecoderStream.java
------------------------------------------------------------------------------
    svn:mime-type = text/plain



Mime
View raw message