commons-dev mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From ggreg...@apache.org
Subject cvs commit: jakarta-commons/codec/src/java/org/apache/commons/codec/net QCodec.java RFC1522Codec.java BCodec.java
Date Mon, 29 Mar 2004 07:59:57 GMT
ggregory    2004/03/28 23:59:57

  Added:       codec/src/java/org/apache/commons/codec/net QCodec.java
                        RFC1522Codec.java BCodec.java
  Log:
  
  PR: Bugzilla Bug 28002 [Codec][Patch] RFC 1522 codecs (Q-codec & B-codec)
  Submitted by:	Oleg Kalnichevski
  Reviewed by:	Gary Gregory
  
  Revision  Changes    Path
  1.1                  jakarta-commons/codec/src/java/org/apache/commons/codec/net/QCodec.java
  
  Index: QCodec.java
  ===================================================================
  /*
   * Copyright 2001-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.commons.codec.net;
  
  import java.io.UnsupportedEncodingException;
  import java.util.BitSet;
  import org.apache.commons.codec.DecoderException;
  import org.apache.commons.codec.EncoderException;
  import org.apache.commons.codec.StringDecoder;
  import org.apache.commons.codec.StringEncoder;
  
  /**
   * <p>
   * The "Q" encoding is similar to the Quoted-Printable content-transfer-encoding defined
in <a
   * href="http://www.ietf.org/rfc/rfc1521.txt">RFC 1521 </a>. It is designed to
allow text containing mostly ASCII
   * characters to be decipherable on an ASCII terminal without decoding.
   * </p>
   * 
   * <p>
   * <a href="http://www.ietf.org/rfc/rfc1522.txt">RFC 1522 </a> describes techniques
to allow the encoding of non-ASCII
   * text in various portions of a RFC 822 [2] message header, in a manner which is unlikely
to confuse existing message
   * handling software.
   * </p>
   * 
   * @see <a href="http://www.ietf.org/rfc/rfc1522.txt"> MIME (Multipurpose Internet
Mail Extensions) Part Two: Message
   *          Header Extensions for Non-ASCII Text </a>
   * 
   * @author Apache Software Foundation
   * @since 1.3
   * @version $Id: QCodec.java,v 1.1 2004/03/29 07:59:57 ggregory Exp $
   */
  public class QCodec extends RFC1522Codec implements StringEncoder, StringDecoder {
      /**
       * The default charset used for string decoding and encoding.
       */
      private String charset = StringEncodings.UTF8;
  
      /**
       * BitSet of printable characters as defined in RFC 1522.
       */
      private static final BitSet PRINTABLE_CHARS = new BitSet(256);
      // Static initializer for printable chars collection
      static {
          // alpha characters
          PRINTABLE_CHARS.set(' ');
          PRINTABLE_CHARS.set('!');
          PRINTABLE_CHARS.set('"');
          PRINTABLE_CHARS.set('#');
          PRINTABLE_CHARS.set('$');
          PRINTABLE_CHARS.set('%');
          PRINTABLE_CHARS.set('&');
          PRINTABLE_CHARS.set('\'');
          PRINTABLE_CHARS.set('(');
          PRINTABLE_CHARS.set(')');
          PRINTABLE_CHARS.set('*');
          PRINTABLE_CHARS.set('+');
          PRINTABLE_CHARS.set(',');
          PRINTABLE_CHARS.set('-');
          PRINTABLE_CHARS.set('.');
          PRINTABLE_CHARS.set('/');
          for (int i = '0'; i <= '9'; i++) {
              PRINTABLE_CHARS.set(i);
          }
          PRINTABLE_CHARS.set(':');
          PRINTABLE_CHARS.set(';');
          PRINTABLE_CHARS.set('<');
          PRINTABLE_CHARS.set('>');
          PRINTABLE_CHARS.set('@');
          for (int i = 'A'; i <= 'Z'; i++) {
              PRINTABLE_CHARS.set(i);
          }
          PRINTABLE_CHARS.set('[');
          PRINTABLE_CHARS.set('\\');
          PRINTABLE_CHARS.set(']');
          PRINTABLE_CHARS.set('^');
          PRINTABLE_CHARS.set('`');
          for (int i = 'a'; i <= 'z'; i++) {
              PRINTABLE_CHARS.set(i);
          }
          PRINTABLE_CHARS.set('{');
          PRINTABLE_CHARS.set('|');
          PRINTABLE_CHARS.set('}');
          PRINTABLE_CHARS.set('~');
      }
  
      private static byte BLANK = 32;
  
      private static byte UNDERSCORE = 95;
  
      private boolean encodeBlanks = false;
  
      /**
       * Default constructor.
       */
      public QCodec() {
          super();
      }
  
      /**
       * Constructor which allows for the selection of a default charset
       * 
       * @param charset
       *                  the default string charset to use.
       * 
       * @see <a href="http://java.sun.com/j2se/1.3/docs/api/java/lang/package-summary.html#charenc">JRE
character
       *          encoding names</a>
       */
      public QCodec(final String charset) {
          super();
          this.charset = charset;
      }
  
      protected String getEncoding() {
          return "Q";
      }
  
      protected byte[] doEncoding(byte[] bytes) throws EncoderException {
          if (bytes == null) {
              return null;
          }
          byte[] data = QuotedPrintableCodec.encodeQuotedPrintable(PRINTABLE_CHARS, bytes);
          if (this.encodeBlanks) {
              for (int i = 0; i < data.length; i++) {
                  if (data[i] == BLANK) {
                      data[i] = UNDERSCORE;
                  }
              }
          }
          return data;
      }
  
      protected byte[] doDecoding(byte[] bytes) throws DecoderException {
          if (bytes == null) {
              return null;
          }
          boolean hasUnderscores = false;
          for (int i = 0; i < bytes.length; i++) {
              if (bytes[i] == UNDERSCORE) {
                  hasUnderscores = true;
                  break;
              }
          }
          if (hasUnderscores) {
              byte[] tmp = new byte[bytes.length];
              for (int i = 0; i < bytes.length; i++) {
                  byte b = bytes[i];
                  if (b != UNDERSCORE) {
                      tmp[i] = b;
                  } else {
                      tmp[i] = BLANK;
                  }
              }
              return QuotedPrintableCodec.decodeQuotedPrintable(tmp);
          } else {
              return QuotedPrintableCodec.decodeQuotedPrintable(bytes);
          }
      }
  
      /**
       * Encodes a string into its quoted-printable form using the specified charset. Unsafe
characters are escaped.
       * 
       * @param pString
       *                  string to convert to quoted-printable form
       * @param charset
       *                  the charset for pString
       * @return quoted-printable string
       * 
       * @throws EncoderException
       *                  thrown if a failure condition is encountered during the encoding
process.
       */
      public String encode(final String pString, final String charset) throws EncoderException
{
          if (pString == null) {
              return null;
          }
          try {
              return encodeText(pString, charset);
          } catch (UnsupportedEncodingException e) {
              throw new EncoderException(e.getMessage());
          }
      }
  
      /**
       * Encodes a string into its quoted-printable form using the default charset. Unsafe
characters are escaped.
       * 
       * @param pString
       *                  string to convert to quoted-printable form
       * @return quoted-printable string
       * 
       * @throws EncoderException
       *                  thrown if a failure condition is encountered during the encoding
process.
       */
      public String encode(String pString) throws EncoderException {
          if (pString == null) {
              return null;
          }
          return encode(pString, getDefaultCharset());
      }
  
      /**
       * Decodes a quoted-printable string into its original form. Escaped characters are
converted back to their original
       * representation.
       * 
       * @param pString
       *                  quoted-printable string to convert into its original form
       * 
       * @return original string
       * 
       * @throws DecoderException
       *                  A decoder exception is thrown if a failure condition is encountered
during the decode process.
       */
      public String decode(String pString) throws DecoderException {
          if (pString == null) {
              return null;
          }
          try {
              return decodeText(pString);
          } catch (UnsupportedEncodingException e) {
              throw new DecoderException(e.getMessage());
          }
      }
  
      /**
       * Encodes an object into its quoted-printable form using the default charset. Unsafe
characters are escaped.
       * 
       * @param pObject
       *                  object to convert to quoted-printable form
       * @return quoted-printable object
       * 
       * @throws EncoderException
       *                  thrown if a failure condition is encountered during the encoding
process.
       */
      public Object encode(Object pObject) throws EncoderException {
          if (pObject == null) {
              return null;
          } else if (pObject instanceof String) {
              return encode((String) pObject);
          } else {
              throw new EncoderException("Objects of type "
                  + pObject.getClass().getName()
                  + " cannot be encoded using Q codec");
          }
      }
  
      /**
       * Decodes a quoted-printable object into its original form. Escaped characters are
converted back to their original
       * representation.
       * 
       * @param pObject
       *                  quoted-printable object to convert into its original form
       * 
       * @return original object
       * 
       * @throws DecoderException
       *                  A decoder exception is thrown if a failure condition is encountered
during the decode process.
       */
      public Object decode(Object pObject) throws DecoderException {
          if (pObject == null) {
              return null;
          } else if (pObject instanceof String) {
              return decode((String) pObject);
          } else {
              throw new DecoderException("Objects of type "
                  + pObject.getClass().getName()
                  + " cannot be decoded using Q codec");
          }
      }
  
      /**
       * The default charset used for string decoding and encoding.
       * 
       * @return the default string charset.
       */
      public String getDefaultCharset() {
          return this.charset;
      }
  
      /**
       * Tests if optional tranformation of SPACE characters is to be used
       * 
       * @return <code>true</code> if SPACE characters are to be transformed,
<code>false</code> otherwise
       */
      public boolean isEncodeBlanks() {
          return this.encodeBlanks;
      }
  
      /**
       * Defines whether optional tranformation of SPACE characters is to be used
       * 
       * @param b
       *                  <code>true</code> if SPACE characters are to be transformed,
<code>false</code> otherwise
       */
      public void setEncodeBlanks(boolean b) {
          this.encodeBlanks = b;
      }
  }
  
  
  1.1                  jakarta-commons/codec/src/java/org/apache/commons/codec/net/RFC1522Codec.java
  
  Index: RFC1522Codec.java
  ===================================================================
  /*
   * Copyright 2001-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.commons.codec.net;
  
  import java.io.UnsupportedEncodingException;
  
  import org.apache.commons.codec.DecoderException;
  import org.apache.commons.codec.EncoderException;
  
  /**
   * <p>
   * Implements methods common to all codecs defined in RFC 1522.
   * </p>
   * 
   * <p>
   * <a href="http://www.ietf.org/rfc/rfc1522.txt">RFC 1522</a> 
   * describes techniques to allow the encoding of non-ASCII text in 
   * various portions of a RFC 822 [2] message header, in a manner which
   * is unlikely to confuse existing message handling software.
   * </p>
  
   * @see <a href="http://www.ietf.org/rfc/rfc1522.txt">
   * MIME (Multipurpose Internet Mail Extensions) Part Two:
   * Message Header Extensions for Non-ASCII Text</a>
   * </p>
   * 
   * @author Apache Software Foundation
   * @since 1.3
   * @version $Id: RFC1522Codec.java,v 1.1 2004/03/29 07:59:57 ggregory Exp $
   */
  abstract class RFC1522Codec {
      
      /**
       * Applies an RFC 1522 compliant encoding scheme to the given string of text with the

       * given charset. This method constructs the "encoded-word" header common to all the

       * RFC 1522 codecs and then invokes {@link #doEncoding(byte [])} method of a concrete

       * class to perform the specific enconding.
       * 
       * @param text a string to encode
       * @param charset a charset to be used
       * 
       * @return RFC 1522 compliant "encoded-word"
       * 
       * @throws EncoderException thrown if there is an error conidition during the Encoding

       *  process.
       * @throws UnsupportedEncodingException thrown if charset is not supported 
       * 
       * @see <a href="http://java.sun.com/j2se/1.3/docs/api/java/lang/package-summary.html#charenc">JRE
character
       *          encoding names</a>
       */
      protected String encodeText(final String text, final String charset)
       throws EncoderException, UnsupportedEncodingException  
      {
          if (text == null) {
              return null;
          }
          StringBuffer buffer = new StringBuffer();
          buffer.append("=?"); 
          buffer.append(charset); 
          buffer.append('?'); 
          buffer.append(getEncoding()); 
          buffer.append('?');
          byte [] rawdata = doEncoding(text.getBytes(charset)); 
          buffer.append(new String(rawdata, StringEncodings.US_ASCII));
          buffer.append("?="); 
          return buffer.toString();
      }
      
      /**
       * Applies an RFC 1522 compliant decoding scheme to the given string of text. This method

       * processes the "encoded-word" header common to all the RFC 1522 codecs and then invokes

       * {@link #doEncoding(byte [])} method of a concrete class to perform the specific deconding.
       * 
       * @param text a string to decode
       * 
       * @throws DecoderException thrown if there is an error conidition during the Decoding

       *  process.
       * @throws UnsupportedEncodingException thrown if charset specified in the "encoded-word"

       *  header is not supported 
       */
      protected String decodeText(final String text)
       throws DecoderException, UnsupportedEncodingException  
      {
          if (text == null) {
              return null;
          }
          if ((!text.startsWith("=?")) || (!text.endsWith("?="))) {
              throw new DecoderException("RFC 1521 violation: malformed encoded content");
          }
          int termnator = text.length() - 2;
          int from = 2;
          int to = text.indexOf("?", from);
          if ((to == -1) || (to == termnator)) {
              throw new DecoderException("RFC 1521 violation: charset token not found");
          }
          String charset = text.substring(from, to);
          from = to + 1;
          to = text.indexOf("?", from);
          if ((to == -1) || (to == termnator)) {
              throw new DecoderException("RFC 1521 violation: encoding token not found");
          }
          String encoding = text.substring(from, to);
          if (!getEncoding().equalsIgnoreCase(encoding)) {
              throw new DecoderException("This codec cannot decode " + 
                  encoding + " encoded content");
          }
          from = to + 1;
          to = text.indexOf("?", from);
          if ((to == -1) || (to != termnator)) {
              throw new DecoderException("RFC 1521 violation: encoded content not found");
          }
          byte[] data = text.substring(from, to).getBytes(StringEncodings.US_ASCII);
          data = doDecoding(data); 
          return new String(data, charset);
      }
  
      /**
       * Returns the codec name (referred to as encoding in the RFC 1522)
       * 
       * @return name of the codec
       */    
      protected abstract String getEncoding();
  
      /**
       * Encodes an array of bytes using the defined encoding scheme
       * 
       * @param bytes Data to be encoded
       *
       * @return A byte array containing the encoded data
       * 
       * @throws EncoderException thrown if the Encoder encounters a failure condition 
       *  during the encoding process.
       */    
      protected abstract byte[] doEncoding(byte[] bytes) throws EncoderException;
  
      /**
       * Decodes an array of bytes using the defined encoding scheme
       * 
       * @param bytes Data to be decoded
       *
       * @return a byte array that contains decoded data
       * 
       * @throws DecoderException A decoder exception is thrown if a Decoder encounters a

       *  failure condition during the decode process.
       */    
      protected abstract byte[] doDecoding(byte[] bytes) throws DecoderException;
  }
  
  
  
  1.1                  jakarta-commons/codec/src/java/org/apache/commons/codec/net/BCodec.java
  
  Index: BCodec.java
  ===================================================================
  /*
   * Copyright 2001-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.commons.codec.net;
  
  import java.io.UnsupportedEncodingException;
  import org.apache.commons.codec.DecoderException;
  import org.apache.commons.codec.EncoderException;
  import org.apache.commons.codec.StringDecoder;
  import org.apache.commons.codec.StringEncoder;
  import org.apache.commons.codec.binary.Base64;
  
  /**
   * <p>
   * The "B" encoding is identical to the Base64 encoding defined by <a href="http://www.ietf.org/rfc/rfc1521.txt">RFC
   * 1521 </a> and allows a character set to be specified.
   * </p>
   * 
   * <p>
   * <a href="http://www.ietf.org/rfc/rfc1522.txt">RFC 1522 </a> describes techniques
to allow the encoding of non-ASCII
   * text in various portions of a RFC 822 [2] message header, in a manner which is unlikely
to confuse existing message
   * handling software.
   * </p>
   * 
   * @see <a href="http://www.ietf.org/rfc/rfc1522.txt"> MIME (Multipurpose Internet
Mail Extensions) Part Two: Message
   *          Header Extensions for Non-ASCII Text </a>
   * 
   * @author Apache Software Foundation
   * @since 1.3
   * @version $Id: BCodec.java,v 1.1 2004/03/29 07:59:57 ggregory Exp $
   */
  public class BCodec extends RFC1522Codec implements StringEncoder, StringDecoder {
      /**
       * The default charset used for string decoding and encoding.
       */
      private String charset = StringEncodings.UTF8;
  
      /**
       * Default constructor.
       */
      public BCodec() {
          super();
      }
  
      /**
       * Constructor which allows for the selection of a default charset
       * 
       * @param charset
       *                  the default string charset to use.
       * 
       * @see <a href="http://java.sun.com/j2se/1.3/docs/api/java/lang/package-summary.html#charenc">JRE
character
       *          encoding names</a>
       */
      public BCodec(final String charset) {
          super();
          this.charset = charset;
      }
  
      protected String getEncoding() {
          return "B";
      }
  
      protected byte[] doEncoding(byte[] bytes) throws EncoderException {
          if (bytes == null) {
              return null;
          }
          return Base64.encodeBase64(bytes);
      }
  
      protected byte[] doDecoding(byte[] bytes) throws DecoderException {
          if (bytes == null) {
              return null;
          }
          return Base64.decodeBase64(bytes);
      }
  
      /**
       * Encodes a string into its Base64 form using the specified charset. Unsafe characters
are escaped.
       * 
       * @param value
       *                  string to convert to Base64 form
       * @param charset
       *                  the charset for pString
       * @return Base64 string
       * 
       * @throws EncoderException
       *                  thrown if a failure condition is encountered during the encoding
process.
       */
      public String encode(final String value, final String charset) throws EncoderException
{
          if (value == null) {
              return null;
          }
          try {
              return encodeText(value, charset);
          } catch (UnsupportedEncodingException e) {
              throw new EncoderException(e.getMessage());
          }
      }
  
      /**
       * Encodes a string into its Base64 form using the default charset. Unsafe characters
are escaped.
       * 
       * @param value
       *                  string to convert to Base64 form
       * @return Base64 string
       * 
       * @throws EncoderException
       *                  thrown if a failure condition is encountered during the encoding
process.
       */
      public String encode(String value) throws EncoderException {
          if (value == null) {
              return null;
          }
          return encode(value, getDefaultCharset());
      }
  
      /**
       * Decodes a Base64 string into its original form. Escaped characters are converted
back to their original
       * representation.
       * 
       * @param value
       *                  Base64 string to convert into its original form
       * 
       * @return original string
       * 
       * @throws DecoderException
       *                  A decoder exception is thrown if a failure condition is encountered
during the decode process.
       */
      public String decode(String value) throws DecoderException {
          if (value == null) {
              return null;
          }
          try {
              return decodeText(value);
          } catch (UnsupportedEncodingException e) {
              throw new DecoderException(e.getMessage());
          }
      }
  
      /**
       * Encodes an object into its Base64 form using the default charset. Unsafe characters
are escaped.
       * 
       * @param value
       *                  object to convert to Base64 form
       * @return Base64 object
       * 
       * @throws EncoderException
       *                  thrown if a failure condition is encountered during the encoding
process.
       */
      public Object encode(Object value) throws EncoderException {
          if (value == null) {
              return null;
          } else if (value instanceof String) {
              return encode((String) value);
          } else {
              throw new EncoderException("Objects of type "
                  + value.getClass().getName()
                  + " cannot be encoded using BCodec");
          }
      }
  
      /**
       * Decodes a Base64 object into its original form. Escaped characters are converted
back to their original
       * representation.
       * 
       * @param value
       *                  Base64 object to convert into its original form
       * 
       * @return original object
       * 
       * @throws DecoderException
       *                  A decoder exception is thrown if a failure condition is encountered
during the decode process.
       */
      public Object decode(Object value) throws DecoderException {
          if (value == null) {
              return null;
          } else if (value instanceof String) {
              return decode((String) value);
          } else {
              throw new DecoderException("Objects of type "
                  + value.getClass().getName()
                  + " cannot be decoded using BCodec");
          }
      }
  
      /**
       * The default charset used for string decoding and encoding.
       * 
       * @return the default string charset.
       */
      public String getDefaultCharset() {
          return this.charset;
      }
  }
  
  

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


Mime
View raw message