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.  *      https://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 java.nio.charset.UnsupportedCharsetException;
  21. import java.util.Objects;

  22. import org.apache.commons.codec.DecoderException;
  23. import org.apache.commons.codec.EncoderException;
  24. import org.apache.commons.codec.binary.StringUtils;

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

  41.     /** Separator. */
  42.     protected static final char SEP = '?';

  43.     /** Prefix. */
  44.     protected static final String POSTFIX = "?=";

  45.     /** Postfix. */
  46.     protected static final String PREFIX = "=?";

  47.     /**
  48.      * The default Charset used for string decoding and encoding.
  49.      */
  50.     protected final Charset charset;

  51.     RFC1522Codec(final Charset charset) {
  52.         this.charset = Objects.requireNonNull(charset, "charset");
  53.     }

  54.     /**
  55.      * Applies an RFC 1522 compliant decoding scheme to the given string of text.
  56.      * <p>
  57.      * This method processes the "encoded-word" header common to all the RFC 1522 codecs and then invokes
  58.      * {@link #doDecoding(byte[])}  method of a concrete class to perform the specific decoding.
  59.      * </p>
  60.      *
  61.      * @param text
  62.      *            a string to decode
  63.      * @return A new decoded String or {@code null} if the input is {@code null}.
  64.      * @throws DecoderException
  65.      *             thrown if there is an error condition during the decoding process.
  66.      * @throws UnsupportedEncodingException
  67.      *             thrown if charset specified in the "encoded-word" header is not supported
  68.      */
  69.     protected String decodeText(final String text) throws DecoderException, UnsupportedEncodingException {
  70.         if (text == null) {
  71.             return null;
  72.         }
  73.         if (!text.startsWith(PREFIX) || !text.endsWith(POSTFIX)) {
  74.             throw new DecoderException("RFC 1522 violation: malformed encoded content");
  75.         }
  76.         final int terminator = text.length() - 2;
  77.         int from = 2;
  78.         int to = text.indexOf(SEP, from);
  79.         if (to == terminator) {
  80.             throw new DecoderException("RFC 1522 violation: charset token not found");
  81.         }
  82.         final String charset = text.substring(from, to);
  83.         if (charset.isEmpty()) {
  84.             throw new DecoderException("RFC 1522 violation: charset not specified");
  85.         }
  86.         from = to + 1;
  87.         to = text.indexOf(SEP, from);
  88.         if (to == terminator) {
  89.             throw new DecoderException("RFC 1522 violation: encoding token not found");
  90.         }
  91.         final String encoding = text.substring(from, to);
  92.         if (!getEncoding().equalsIgnoreCase(encoding)) {
  93.             throw new DecoderException("This codec cannot decode " + encoding + " encoded content");
  94.         }
  95.         from = to + 1;
  96.         to = text.indexOf(SEP, from);
  97.         byte[] data = StringUtils.getBytesUsAscii(text.substring(from, to));
  98.         data = doDecoding(data);
  99.         return new String(data, charset);
  100.     }

  101.     /**
  102.      * Decodes an array of bytes using the defined encoding scheme.
  103.      *
  104.      * @param bytes
  105.      *            Data to be decoded
  106.      * @return a byte array that contains decoded data
  107.      * @throws DecoderException
  108.      *             A decoder exception is thrown if a Decoder encounters a failure condition during the decode process.
  109.      */
  110.     protected abstract byte[] doDecoding(byte[] bytes) throws DecoderException;

  111.     /**
  112.      * Encodes an array of bytes using the defined encoding scheme.
  113.      *
  114.      * @param bytes
  115.      *            Data to be encoded
  116.      * @return A byte array containing the encoded data
  117.      * @throws EncoderException
  118.      *             thrown if the Encoder encounters a failure condition during the encoding process.
  119.      */
  120.     protected abstract byte[] doEncoding(byte[] bytes) throws EncoderException;

  121.     /**
  122.      * Applies an RFC 1522 compliant encoding scheme to the given string of text with the given charset.
  123.      * <p>
  124.      * This method constructs the "encoded-word" header common to all the RFC 1522 codecs and then invokes
  125.      * {@link #doEncoding(byte[])}  method of a concrete class to perform the specific encoding.
  126.      * </p>
  127.      *
  128.      * @param text
  129.      *            a string to encode
  130.      * @param charset
  131.      *            a charset to be used
  132.      * @return RFC 1522 compliant "encoded-word"
  133.      * @throws EncoderException
  134.      *             thrown if there is an error condition during the Encoding process.
  135.      * @see Charset
  136.      */
  137.     protected String encodeText(final String text, final Charset charset) throws EncoderException {
  138.         if (text == null) {
  139.             return null;
  140.         }
  141.         final StringBuilder buffer = new StringBuilder();
  142.         buffer.append(PREFIX);
  143.         buffer.append(charset);
  144.         buffer.append(SEP);
  145.         buffer.append(getEncoding());
  146.         buffer.append(SEP);
  147.         buffer.append(StringUtils.newStringUsAscii(doEncoding(text.getBytes(charset))));
  148.         buffer.append(POSTFIX);
  149.         return buffer.toString();
  150.     }

  151.     /**
  152.      * Applies an RFC 1522 compliant encoding scheme to the given string of text with the given charset.
  153.      * <p>
  154.      * This method constructs the "encoded-word" header common to all the RFC 1522 codecs and then invokes
  155.      * {@link #doEncoding(byte[])}  method of a concrete class to perform the specific encoding.
  156.      * </p>
  157.      *
  158.      * @param text
  159.      *            a string to encode
  160.      * @param charsetName
  161.      *            the charset to use
  162.      * @return RFC 1522 compliant "encoded-word"
  163.      * @throws EncoderException
  164.      *             thrown if there is an error condition during the Encoding process.
  165.      * @throws UnsupportedCharsetException
  166.      *             if charset is not available
  167.      * @see Charset
  168.      */
  169.     protected String encodeText(final String text, final String charsetName) throws EncoderException {
  170.         if (text == null) {
  171.             // Don't attempt charsetName conversion.
  172.             return null;
  173.         }
  174.         return encodeText(text, Charset.forName(charsetName));
  175.     }

  176.     /**
  177.      * Gets the default Charset name used for string decoding and encoding.
  178.      *
  179.      * @return the default Charset name
  180.      * @since 1.7
  181.      */
  182.     public Charset getCharset() {
  183.         return charset;
  184.     }

  185.     /**
  186.      * Gets the default Charset name used for string decoding and encoding.
  187.      *
  188.      * @return the default Charset name
  189.      */
  190.     public String getDefaultCharset() {
  191.         return charset.name();
  192.     }

  193.     /**
  194.      * Returns the codec name (referred to as encoding in the RFC 1522).
  195.      *
  196.      * @return name of the codec.
  197.      */
  198.     protected abstract String getEncoding();
  199. }