URLCodec.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.ByteArrayOutputStream;
  19. import java.io.UnsupportedEncodingException;
  20. import java.util.BitSet;

  21. import org.apache.commons.codec.BinaryDecoder;
  22. import org.apache.commons.codec.BinaryEncoder;
  23. import org.apache.commons.codec.CharEncoding;
  24. import org.apache.commons.codec.DecoderException;
  25. import org.apache.commons.codec.EncoderException;
  26. import org.apache.commons.codec.StringDecoder;
  27. import org.apache.commons.codec.StringEncoder;
  28. import org.apache.commons.codec.binary.StringUtils;

  29. /**
  30.  * Implements the 'www-form-urlencoded' encoding scheme, also misleadingly known as URL encoding.
  31.  * <p>
  32.  * This codec is meant to be a replacement for standard Java classes {@link java.net.URLEncoder} and
  33.  * {@link java.net.URLDecoder} on older Java platforms, as these classes in Java versions below
  34.  * 1.4 rely on the platform's default charset encoding.
  35.  * <p>
  36.  * This class is thread-safe since 1.11
  37.  *
  38.  * @see <a href="http://www.w3.org/TR/html4/interact/forms.html#h-17.13.4.1">Chapter 17.13.4 Form content types</a>
  39.  *           of the <a href="http://www.w3.org/TR/html4/">HTML 4.01 Specification</a>
  40.  *
  41.  * @since 1.2
  42.  * @version $Id: URLCodec.java 1789142 2017-03-28 13:58:58Z sebb $
  43.  */
  44. public class URLCodec implements BinaryEncoder, BinaryDecoder, StringEncoder, StringDecoder {

  45.     /**
  46.      * The default charset used for string decoding and encoding.
  47.      *
  48.      * @deprecated TODO: This field will be changed to a private final Charset in 2.0. (CODEC-126)
  49.      */
  50.     @Deprecated
  51.     protected volatile String charset; // added volatile: see CODEC-232

  52.     /**
  53.      * Release 1.5 made this field final.
  54.      */
  55.     protected static final byte ESCAPE_CHAR = '%';

  56.     /**
  57.      * BitSet of www-form-url safe characters.
  58.      * This is a copy of the internal BitSet which is now used for the conversion.
  59.      * Changes to this field are ignored.
  60.      * @deprecated 1.11 Will be removed in 2.0 (CODEC-230)
  61.      */
  62.     @Deprecated
  63.     protected static final BitSet WWW_FORM_URL;

  64.     private static final BitSet WWW_FORM_URL_SAFE = new BitSet(256);

  65.     // Static initializer for www_form_url
  66.     static {
  67.         // alpha characters
  68.         for (int i = 'a'; i <= 'z'; i++) {
  69.             WWW_FORM_URL_SAFE.set(i);
  70.         }
  71.         for (int i = 'A'; i <= 'Z'; i++) {
  72.             WWW_FORM_URL_SAFE.set(i);
  73.         }
  74.         // numeric characters
  75.         for (int i = '0'; i <= '9'; i++) {
  76.             WWW_FORM_URL_SAFE.set(i);
  77.         }
  78.         // special chars
  79.         WWW_FORM_URL_SAFE.set('-');
  80.         WWW_FORM_URL_SAFE.set('_');
  81.         WWW_FORM_URL_SAFE.set('.');
  82.         WWW_FORM_URL_SAFE.set('*');
  83.         // blank to be replaced with +
  84.         WWW_FORM_URL_SAFE.set(' ');

  85.         // Create a copy in case anyone (ab)uses it
  86.         WWW_FORM_URL = (BitSet) WWW_FORM_URL_SAFE.clone();
  87.     }


  88.     /**
  89.      * Default constructor.
  90.      */
  91.     public URLCodec() {
  92.         this(CharEncoding.UTF_8);
  93.     }

  94.     /**
  95.      * Constructor which allows for the selection of a default charset.
  96.      *
  97.      * @param charset the default string charset to use.
  98.      */
  99.     public URLCodec(final String charset) {
  100.         super();
  101.         this.charset = charset;
  102.     }

  103.     /**
  104.      * Encodes an array of bytes into an array of URL safe 7-bit characters. Unsafe characters are escaped.
  105.      *
  106.      * @param urlsafe
  107.      *            bitset of characters deemed URL safe
  108.      * @param bytes
  109.      *            array of bytes to convert to URL safe characters
  110.      * @return array of bytes containing URL safe characters
  111.      */
  112.     public static final byte[] encodeUrl(BitSet urlsafe, final byte[] bytes) {
  113.         if (bytes == null) {
  114.             return null;
  115.         }
  116.         if (urlsafe == null) {
  117.             urlsafe = WWW_FORM_URL_SAFE;
  118.         }

  119.         final ByteArrayOutputStream buffer = new ByteArrayOutputStream();
  120.         for (final byte c : bytes) {
  121.             int b = c;
  122.             if (b < 0) {
  123.                 b = 256 + b;
  124.             }
  125.             if (urlsafe.get(b)) {
  126.                 if (b == ' ') {
  127.                     b = '+';
  128.                 }
  129.                 buffer.write(b);
  130.             } else {
  131.                 buffer.write(ESCAPE_CHAR);
  132.                 final char hex1 = Utils.hexDigit(b >> 4);
  133.                 final char hex2 = Utils.hexDigit(b);
  134.                 buffer.write(hex1);
  135.                 buffer.write(hex2);
  136.             }
  137.         }
  138.         return buffer.toByteArray();
  139.     }

  140.     /**
  141.      * Decodes an array of URL safe 7-bit characters into an array of original bytes. Escaped characters are converted
  142.      * back to their original representation.
  143.      *
  144.      * @param bytes
  145.      *            array of URL safe characters
  146.      * @return array of original bytes
  147.      * @throws DecoderException
  148.      *             Thrown if URL decoding is unsuccessful
  149.      */
  150.     public static final byte[] decodeUrl(final byte[] bytes) throws DecoderException {
  151.         if (bytes == null) {
  152.             return null;
  153.         }
  154.         final ByteArrayOutputStream buffer = new ByteArrayOutputStream();
  155.         for (int i = 0; i < bytes.length; i++) {
  156.             final int b = bytes[i];
  157.             if (b == '+') {
  158.                 buffer.write(' ');
  159.             } else if (b == ESCAPE_CHAR) {
  160.                 try {
  161.                     final int u = Utils.digit16(bytes[++i]);
  162.                     final int l = Utils.digit16(bytes[++i]);
  163.                     buffer.write((char) ((u << 4) + l));
  164.                 } catch (final ArrayIndexOutOfBoundsException e) {
  165.                     throw new DecoderException("Invalid URL encoding: ", e);
  166.                 }
  167.             } else {
  168.                 buffer.write(b);
  169.             }
  170.         }
  171.         return buffer.toByteArray();
  172.     }

  173.     /**
  174.      * Encodes an array of bytes into an array of URL safe 7-bit characters. Unsafe characters are escaped.
  175.      *
  176.      * @param bytes
  177.      *            array of bytes to convert to URL safe characters
  178.      * @return array of bytes containing URL safe characters
  179.      */
  180.     @Override
  181.     public byte[] encode(final byte[] bytes) {
  182.         return encodeUrl(WWW_FORM_URL_SAFE, bytes);
  183.     }


  184.     /**
  185.      * Decodes an array of URL safe 7-bit characters into an array of original bytes. Escaped characters are converted
  186.      * back to their original representation.
  187.      *
  188.      * @param bytes
  189.      *            array of URL safe characters
  190.      * @return array of original bytes
  191.      * @throws DecoderException
  192.      *             Thrown if URL decoding is unsuccessful
  193.      */
  194.     @Override
  195.     public byte[] decode(final byte[] bytes) throws DecoderException {
  196.         return decodeUrl(bytes);
  197.     }

  198.     /**
  199.      * Encodes a string into its URL safe form using the specified string charset. Unsafe characters are escaped.
  200.      *
  201.      * @param str
  202.      *            string to convert to a URL safe form
  203.      * @param charset
  204.      *            the charset for str
  205.      * @return URL safe string
  206.      * @throws UnsupportedEncodingException
  207.      *             Thrown if charset is not supported
  208.      */
  209.     public String encode(final String str, final String charset) throws UnsupportedEncodingException {
  210.         if (str == null) {
  211.             return null;
  212.         }
  213.         return StringUtils.newStringUsAscii(encode(str.getBytes(charset)));
  214.     }

  215.     /**
  216.      * Encodes a string into its URL safe form using the default string charset. Unsafe characters are escaped.
  217.      *
  218.      * @param str
  219.      *            string to convert to a URL safe form
  220.      * @return URL safe string
  221.      * @throws EncoderException
  222.      *             Thrown if URL encoding is unsuccessful
  223.      *
  224.      * @see #getDefaultCharset()
  225.      */
  226.     @Override
  227.     public String encode(final String str) throws EncoderException {
  228.         if (str == null) {
  229.             return null;
  230.         }
  231.         try {
  232.             return encode(str, getDefaultCharset());
  233.         } catch (final UnsupportedEncodingException e) {
  234.             throw new EncoderException(e.getMessage(), e);
  235.         }
  236.     }


  237.     /**
  238.      * Decodes a URL safe string into its original form using the specified encoding. Escaped characters are converted
  239.      * back to their original representation.
  240.      *
  241.      * @param str
  242.      *            URL safe string to convert into its original form
  243.      * @param charset
  244.      *            the original string charset
  245.      * @return original string
  246.      * @throws DecoderException
  247.      *             Thrown if URL decoding is unsuccessful
  248.      * @throws UnsupportedEncodingException
  249.      *             Thrown if charset is not supported
  250.      */
  251.     public String decode(final String str, final String charset) throws DecoderException, UnsupportedEncodingException {
  252.         if (str == null) {
  253.             return null;
  254.         }
  255.         return new String(decode(StringUtils.getBytesUsAscii(str)), charset);
  256.     }

  257.     /**
  258.      * Decodes a URL safe string into its original form using the default string charset. Escaped characters are
  259.      * converted back to their original representation.
  260.      *
  261.      * @param str
  262.      *            URL safe string to convert into its original form
  263.      * @return original string
  264.      * @throws DecoderException
  265.      *             Thrown if URL decoding is unsuccessful
  266.      * @see #getDefaultCharset()
  267.      */
  268.     @Override
  269.     public String decode(final String str) throws DecoderException {
  270.         if (str == null) {
  271.             return null;
  272.         }
  273.         try {
  274.             return decode(str, getDefaultCharset());
  275.         } catch (final UnsupportedEncodingException e) {
  276.             throw new DecoderException(e.getMessage(), e);
  277.         }
  278.     }

  279.     /**
  280.      * Encodes an object into its URL safe form. Unsafe characters are escaped.
  281.      *
  282.      * @param obj
  283.      *            string to convert to a URL safe form
  284.      * @return URL safe object
  285.      * @throws EncoderException
  286.      *             Thrown if URL encoding is not applicable to objects of this type or if encoding is unsuccessful
  287.      */
  288.     @Override
  289.     public Object encode(final Object obj) throws EncoderException {
  290.         if (obj == null) {
  291.             return null;
  292.         } else if (obj instanceof byte[]) {
  293.             return encode((byte[])obj);
  294.         } else if (obj instanceof String) {
  295.             return encode((String)obj);
  296.         } else {
  297.             throw new EncoderException("Objects of type " + obj.getClass().getName() + " cannot be URL encoded");

  298.         }
  299.     }

  300.     /**
  301.      * Decodes a URL safe object into its original form. Escaped characters are converted back to their original
  302.      * representation.
  303.      *
  304.      * @param obj
  305.      *            URL safe object to convert into its original form
  306.      * @return original object
  307.      * @throws DecoderException
  308.      *             Thrown if the argument is not a <code>String</code> or <code>byte[]</code>. Thrown if a failure
  309.      *             condition is encountered during the decode process.
  310.      */
  311.     @Override
  312.     public Object decode(final Object obj) throws DecoderException {
  313.         if (obj == null) {
  314.             return null;
  315.         } else if (obj instanceof byte[]) {
  316.             return decode((byte[]) obj);
  317.         } else if (obj instanceof String) {
  318.             return decode((String) obj);
  319.         } else {
  320.             throw new DecoderException("Objects of type " + obj.getClass().getName() + " cannot be URL decoded");

  321.         }
  322.     }

  323.     /**
  324.      * The default charset used for string decoding and encoding.
  325.      *
  326.      * @return the default string charset.
  327.      */
  328.     public String getDefaultCharset() {
  329.         return this.charset;
  330.     }

  331.     /**
  332.      * The <code>String</code> encoding used for decoding and encoding.
  333.      *
  334.      * @return Returns the encoding.
  335.      *
  336.      * @deprecated Use {@link #getDefaultCharset()}, will be removed in 2.0.
  337.      */
  338.     @Deprecated
  339.     public String getEncoding() {
  340.         return this.charset;
  341.     }

  342. }