View Javadoc
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  
18  package org.apache.commons.codec.net;
19  
20  import java.io.UnsupportedEncodingException;
21  import java.nio.charset.Charset;
22  import java.nio.charset.StandardCharsets;
23  import java.nio.charset.UnsupportedCharsetException;
24  import java.util.BitSet;
25  
26  import org.apache.commons.codec.DecoderException;
27  import org.apache.commons.codec.EncoderException;
28  import org.apache.commons.codec.StringDecoder;
29  import org.apache.commons.codec.StringEncoder;
30  
31  /**
32   * Similar to the Quoted-Printable content-transfer-encoding defined in
33   * <a href="https://www.ietf.org/rfc/rfc1521.txt">RFC 1521</a> and designed to allow text containing mostly ASCII
34   * characters to be decipherable on an ASCII terminal without decoding.
35   * <p>
36   * <a href="https://www.ietf.org/rfc/rfc1522.txt">RFC 1522</a> describes techniques to allow the encoding of non-ASCII
37   * text in various portions of a RFC 822 [2] message header, in a manner which is unlikely to confuse existing message
38   * handling software.
39   * </p>
40   * <p>
41   * This class is conditionally thread-safe.
42   * The instance field for encoding blanks is mutable {@link #setEncodeBlanks(boolean)}
43   * but is not volatile, and accesses are not synchronized.
44   * If an instance of the class is shared between threads, the caller needs to ensure that suitable synchronization
45   * is used to ensure safe publication of the value between threads, and must not invoke
46   * {@link #setEncodeBlanks(boolean)} after initial setup.
47   * </p>
48   *
49   * @see <a href="https://www.ietf.org/rfc/rfc1522.txt">MIME (Multipurpose Internet Mail Extensions) Part Two: Message
50   *          Header Extensions for Non-ASCII Text</a>
51   *
52   * @since 1.3
53   */
54  public class QCodec extends RFC1522Codec implements StringEncoder, StringDecoder {
55  
56      /**
57       * BitSet of printable characters as defined in RFC 1522.
58       */
59      private static final BitSet PRINTABLE_CHARS = new BitSet(256);
60  
61      // Static initializer for printable chars collection
62      static {
63          // alpha characters
64          PRINTABLE_CHARS.set(' ');
65          PRINTABLE_CHARS.set('!');
66          PRINTABLE_CHARS.set('"');
67          PRINTABLE_CHARS.set('#');
68          PRINTABLE_CHARS.set('$');
69          PRINTABLE_CHARS.set('%');
70          PRINTABLE_CHARS.set('&');
71          PRINTABLE_CHARS.set('\'');
72          PRINTABLE_CHARS.set('(');
73          PRINTABLE_CHARS.set(')');
74          PRINTABLE_CHARS.set('*');
75          PRINTABLE_CHARS.set('+');
76          PRINTABLE_CHARS.set(',');
77          PRINTABLE_CHARS.set('-');
78          PRINTABLE_CHARS.set('.');
79          PRINTABLE_CHARS.set('/');
80          for (int i = '0'; i <= '9'; i++) {
81              PRINTABLE_CHARS.set(i);
82          }
83          PRINTABLE_CHARS.set(':');
84          PRINTABLE_CHARS.set(';');
85          PRINTABLE_CHARS.set('<');
86          PRINTABLE_CHARS.set('>');
87          PRINTABLE_CHARS.set('@');
88          for (int i = 'A'; i <= 'Z'; i++) {
89              PRINTABLE_CHARS.set(i);
90          }
91          PRINTABLE_CHARS.set('[');
92          PRINTABLE_CHARS.set('\\');
93          PRINTABLE_CHARS.set(']');
94          PRINTABLE_CHARS.set('^');
95          PRINTABLE_CHARS.set('`');
96          for (int i = 'a'; i <= 'z'; i++) {
97              PRINTABLE_CHARS.set(i);
98          }
99          PRINTABLE_CHARS.set('{');
100         PRINTABLE_CHARS.set('|');
101         PRINTABLE_CHARS.set('}');
102         PRINTABLE_CHARS.set('~');
103     }
104     private static final byte UNDERSCORE = 95;
105 
106     private boolean encodeBlanks;
107 
108     /**
109      * Constructs a new instance.
110      */
111     public QCodec() {
112         this(StandardCharsets.UTF_8);
113     }
114 
115     /**
116      * Constructs a new instance for the selection of a default Charset.
117      *
118      * @param charset
119      *            the default string Charset to use.
120      *
121      * @see Charset
122      * @since 1.7
123      */
124     public QCodec(final Charset charset) {
125         super(charset);
126     }
127 
128     /**
129      * Constructs a new instance for the selection of a default Charset.
130      *
131      * @param charsetName
132      *            the Charset to use.
133      * @throws java.nio.charset.UnsupportedCharsetException
134      *             If the named Charset is unavailable.
135      * @since 1.7 throws UnsupportedCharsetException if the named Charset is unavailable
136      * @see Charset
137      */
138     public QCodec(final String charsetName) {
139         this(Charset.forName(charsetName));
140     }
141 
142     /**
143      * Decodes a quoted-printable object into its original form. Escaped characters are converted back to their original
144      * representation.
145      *
146      * @param obj
147      *            quoted-printable object to convert into its original form.
148      * @return original object.
149      * @throws DecoderException
150      *             Thrown if the argument is not a {@code String}. Thrown if a failure condition is encountered
151      *             during the decode process.
152      */
153     @Override
154     public Object decode(final Object obj) throws DecoderException {
155         if (obj == null) {
156             return null;
157         }
158         if (obj instanceof String) {
159             return decode((String) obj);
160         }
161         throw new DecoderException("Objects of type " + obj.getClass().getName() + " cannot be decoded using Q codec");
162     }
163 
164     /**
165      * Decodes a quoted-printable string into its original form. Escaped characters are converted back to their original
166      * representation.
167      *
168      * @param str
169      *            quoted-printable string to convert into its original form.
170      * @return original string.
171      * @throws DecoderException
172      *             A decoder exception is thrown if a failure condition is encountered during the decode process.
173      */
174     @Override
175     public String decode(final String str) throws DecoderException {
176         try {
177             return decodeText(str);
178         } catch (final UnsupportedEncodingException e) {
179             throw new DecoderException(e.getMessage(), e);
180         }
181     }
182 
183     @Override
184     protected byte[] doDecoding(final byte[] bytes) throws DecoderException {
185         if (bytes == null) {
186             return null;
187         }
188         boolean hasUnderscores = false;
189         for (final byte b : bytes) {
190             if (b == UNDERSCORE) {
191                 hasUnderscores = true;
192                 break;
193             }
194         }
195         if (hasUnderscores) {
196             final byte[] tmp = new byte[bytes.length];
197             for (int i = 0; i < bytes.length; i++) {
198                 final byte b = bytes[i];
199                 if (b != UNDERSCORE) {
200                     tmp[i] = b;
201                 } else {
202                     tmp[i] = Utils.SPACE;
203                 }
204             }
205             return QuotedPrintableCodec.decodeQuotedPrintable(tmp);
206         }
207         return QuotedPrintableCodec.decodeQuotedPrintable(bytes);
208     }
209 
210     @Override
211     protected byte[] doEncoding(final byte[] bytes) {
212         if (bytes == null) {
213             return null;
214         }
215         final byte[] data = QuotedPrintableCodec.encodeQuotedPrintable(PRINTABLE_CHARS, bytes);
216         if (this.encodeBlanks) {
217             for (int i = 0; i < data.length; i++) {
218                 if (data[i] == Utils.SPACE) {
219                     data[i] = UNDERSCORE;
220                 }
221             }
222         }
223         return data;
224     }
225 
226     /**
227      * Encodes an object into its quoted-printable form using the default Charset. Unsafe characters are escaped.
228      *
229      * @param obj
230      *            object to convert to quoted-printable form.
231      * @return quoted-printable object.
232      * @throws EncoderException
233      *             thrown if a failure condition is encountered during the encoding process.
234      */
235     @Override
236     public Object encode(final Object obj) throws EncoderException {
237         if (obj == null) {
238             return null;
239         }
240         if (obj instanceof String) {
241             return encode((String) obj);
242         }
243         throw new EncoderException("Objects of type " + obj.getClass().getName() + " cannot be encoded using Q codec");
244     }
245 
246     /**
247      * Encodes a string into its quoted-printable form using the default Charset. Unsafe characters are escaped.
248      *
249      * @param sourceStr
250      *            string to convert to quoted-printable form.
251      * @return quoted-printable string.
252      * @throws EncoderException
253      *             thrown if a failure condition is encountered during the encoding process.
254      */
255     @Override
256     public String encode(final String sourceStr) throws EncoderException {
257         return encode(sourceStr, getCharset());
258     }
259 
260     /**
261      * Encodes a string into its quoted-printable form using the specified Charset. Unsafe characters are escaped.
262      *
263      * @param sourceStr
264      *            string to convert to quoted-printable form.
265      * @param sourceCharset
266      *            the Charset for sourceStr.
267      * @return quoted-printable string.
268      * @throws EncoderException
269      *             thrown if a failure condition is encountered during the encoding process.
270      * @since 1.7
271      */
272     public String encode(final String sourceStr, final Charset sourceCharset) throws EncoderException {
273         return encodeText(sourceStr, sourceCharset);
274     }
275 
276     /**
277      * Encodes a string into its quoted-printable form using the specified Charset. Unsafe characters are escaped.
278      *
279      * @param sourceStr
280      *            string to convert to quoted-printable form.
281      * @param sourceCharset
282      *            the Charset for sourceStr.
283      * @return quoted-printable string.
284      * @throws EncoderException
285      *             thrown if a failure condition is encountered during the encoding process.
286      */
287     public String encode(final String sourceStr, final String sourceCharset) throws EncoderException {
288         try {
289             return encodeText(sourceStr, sourceCharset);
290         } catch (final UnsupportedCharsetException e) {
291             throw new EncoderException(e.getMessage(), e);
292         }
293     }
294 
295     @Override
296     protected String getEncoding() {
297         return "Q";
298     }
299 
300     /**
301      * Tests if optional transformation of SPACE characters is to be used
302      *
303      * @return {@code true} if SPACE characters are to be transformed, {@code false} otherwise.
304      */
305     public boolean isEncodeBlanks() {
306         return this.encodeBlanks;
307     }
308 
309     /**
310      * Defines whether optional transformation of SPACE characters is to be used
311      *
312      * @param b
313      *            {@code true} if SPACE characters are to be transformed, {@code false} otherwise.
314      */
315     public void setEncodeBlanks(final boolean b) {
316         this.encodeBlanks = b;
317     }
318 }