RFC1522Codec.java

  1. /*
  2.  * Licensed to the Apache Software Foundation (ASF) under one or more
  3.  * contributor license agreements.  See the NOTICE file distributed with
  4.  * this work for additional information regarding copyright ownership.
  5.  * The ASF licenses this file to You under the Apache License, Version 2.0
  6.  * (the "License"); you may not use this file except in compliance with
  7.  * the License.  You may obtain a copy of the License at
  8.  *
  9.  *      http://www.apache.org/licenses/LICENSE-2.0
  10.  *
  11.  * Unless required by applicable law or agreed to in writing, software
  12.  * distributed under the License is distributed on an "AS IS" BASIS,
  13.  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14.  * See the License for the specific language governing permissions and
  15.  * limitations under the License.
  16.  */

  17. package org.apache.commons.codec.net;

  18. import java.io.UnsupportedEncodingException;
  19. import java.nio.charset.Charset;

  20. import org.apache.commons.codec.DecoderException;
  21. import org.apache.commons.codec.EncoderException;
  22. import org.apache.commons.codec.binary.StringUtils;

  23. /**
  24.  * Implements methods common to all codecs defined in RFC 1522.
  25.  * <p>
  26.  * <a href="http://www.ietf.org/rfc/rfc1522.txt">RFC 1522</a> describes techniques to allow the
  27.  * encoding of non-ASCII text in various portions of a RFC 822 [2] message header, in a manner which
  28.  * is unlikely to confuse existing message handling software.
  29.  * <p>
  30.  * This class is immutable and thread-safe.
  31.  *
  32.  * @see <a href="http://www.ietf.org/rfc/rfc1522.txt">MIME (Multipurpose Internet Mail Extensions) Part Two:
  33.  *          Message Header Extensions for Non-ASCII Text</a>
  34.  *
  35.  * @since 1.3
  36.  * @version $Id: RFC1522Codec.java 1619948 2014-08-22 22:53:55Z ggregory $
  37.  */
  38. abstract class RFC1522Codec {

  39.     /** Separator. */
  40.     protected static final char SEP = '?';

  41.     /** Prefix. */
  42.     protected static final String POSTFIX = "?=";

  43.     /** Postfix. */
  44.     protected static final String PREFIX = "=?";

  45.     /**
  46.      * Applies an RFC 1522 compliant encoding scheme to the given string of text with the given charset.
  47.      * <p>
  48.      * This method constructs the "encoded-word" header common to all the RFC 1522 codecs and then invokes
  49.      * {@link #doEncoding(byte [])} method of a concrete class to perform the specific encoding.
  50.      *
  51.      * @param text
  52.      *            a string to encode
  53.      * @param charset
  54.      *            a charset to be used
  55.      * @return RFC 1522 compliant "encoded-word"
  56.      * @throws EncoderException
  57.      *             thrown if there is an error condition during the Encoding process.
  58.      * @see <a href="http://download.oracle.com/javase/6/docs/api/java/nio/charset/Charset.html">Standard charsets</a>
  59.      */
  60.     protected String encodeText(final String text, final Charset charset) throws EncoderException {
  61.         if (text == null) {
  62.             return null;
  63.         }
  64.         final StringBuilder buffer = new StringBuilder();
  65.         buffer.append(PREFIX);
  66.         buffer.append(charset);
  67.         buffer.append(SEP);
  68.         buffer.append(this.getEncoding());
  69.         buffer.append(SEP);
  70.         final byte [] rawData = this.doEncoding(text.getBytes(charset));
  71.         buffer.append(StringUtils.newStringUsAscii(rawData));
  72.         buffer.append(POSTFIX);
  73.         return buffer.toString();
  74.     }

  75.     /**
  76.      * Applies an RFC 1522 compliant encoding scheme to the given string of text with the given charset.
  77.      * <p>
  78.      * This method constructs the "encoded-word" header common to all the RFC 1522 codecs and then invokes
  79.      * {@link #doEncoding(byte [])} method of a concrete class to perform the specific encoding.
  80.      *
  81.      * @param text
  82.      *            a string to encode
  83.      * @param charsetName
  84.      *            the charset to use
  85.      * @return RFC 1522 compliant "encoded-word"
  86.      * @throws EncoderException
  87.      *             thrown if there is an error condition during the Encoding process.
  88.      * @throws UnsupportedEncodingException
  89.      *             if charset is not available
  90.      *
  91.      * @see <a href="http://download.oracle.com/javase/6/docs/api/java/nio/charset/Charset.html">Standard charsets</a>
  92.      */
  93.     protected String encodeText(final String text, final String charsetName)
  94.             throws EncoderException, UnsupportedEncodingException {
  95.         if (text == null) {
  96.             return null;
  97.         }
  98.         return this.encodeText(text, Charset.forName(charsetName));
  99.     }

  100.     /**
  101.      * Applies an RFC 1522 compliant decoding scheme to the given string of text.
  102.      * <p>
  103.      * This method processes the "encoded-word" header common to all the RFC 1522 codecs and then invokes
  104.      * {@link #doEncoding(byte [])} method of a concrete class to perform the specific decoding.
  105.      *
  106.      * @param text
  107.      *            a string to decode
  108.      * @return A new decoded String or <code>null</code> if the input is <code>null</code>.
  109.      * @throws DecoderException
  110.      *             thrown if there is an error condition during the decoding process.
  111.      * @throws UnsupportedEncodingException
  112.      *             thrown if charset specified in the "encoded-word" header is not supported
  113.      */
  114.     protected String decodeText(final String text)
  115.             throws DecoderException, UnsupportedEncodingException {
  116.         if (text == null) {
  117.             return null;
  118.         }
  119.         if (!text.startsWith(PREFIX) || !text.endsWith(POSTFIX)) {
  120.             throw new DecoderException("RFC 1522 violation: malformed encoded content");
  121.         }
  122.         final int terminator = text.length() - 2;
  123.         int from = 2;
  124.         int to = text.indexOf(SEP, from);
  125.         if (to == terminator) {
  126.             throw new DecoderException("RFC 1522 violation: charset token not found");
  127.         }
  128.         final String charset = text.substring(from, to);
  129.         if (charset.equals("")) {
  130.             throw new DecoderException("RFC 1522 violation: charset not specified");
  131.         }
  132.         from = to + 1;
  133.         to = text.indexOf(SEP, from);
  134.         if (to == terminator) {
  135.             throw new DecoderException("RFC 1522 violation: encoding token not found");
  136.         }
  137.         final String encoding = text.substring(from, to);
  138.         if (!getEncoding().equalsIgnoreCase(encoding)) {
  139.             throw new DecoderException("This codec cannot decode " + encoding + " encoded content");
  140.         }
  141.         from = to + 1;
  142.         to = text.indexOf(SEP, from);
  143.         byte[] data = StringUtils.getBytesUsAscii(text.substring(from, to));
  144.         data = doDecoding(data);
  145.         return new String(data, charset);
  146.     }

  147.     /**
  148.      * Returns the codec name (referred to as encoding in the RFC 1522).
  149.      *
  150.      * @return name of the codec
  151.      */
  152.     protected abstract String getEncoding();

  153.     /**
  154.      * Encodes an array of bytes using the defined encoding scheme.
  155.      *
  156.      * @param bytes
  157.      *            Data to be encoded
  158.      * @return A byte array containing the encoded data
  159.      * @throws EncoderException
  160.      *             thrown if the Encoder encounters a failure condition during the encoding process.
  161.      */
  162.     protected abstract byte[] doEncoding(byte[] bytes) throws EncoderException;

  163.     /**
  164.      * Decodes an array of bytes using the defined encoding scheme.
  165.      *
  166.      * @param bytes
  167.      *            Data to be decoded
  168.      * @return a byte array that contains decoded data
  169.      * @throws DecoderException
  170.      *             A decoder exception is thrown if a Decoder encounters a failure condition during the decode process.
  171.      */
  172.     protected abstract byte[] doDecoding(byte[] bytes) throws DecoderException;
  173. }