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.  *      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.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.  * <p>
  37.  * This class is thread-safe as of 1.11
  38.  * </p>
  39.  *
  40.  * @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>
  41.  *           of the <a href="http://www.w3.org/TR/html4/">HTML 4.01 Specification</a>
  42.  *
  43.  * @since 1.2
  44.  */
  45. public class URLCodec implements BinaryEncoder, BinaryDecoder, StringEncoder, StringDecoder {

  46.     /**
  47.      * Release 1.5 made this field final.
  48.      */
  49.     protected static final byte ESCAPE_CHAR = '%';

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

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

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

  79.         // Create a copy in case anyone (ab)uses it
  80.         WWW_FORM_URL = (BitSet) WWW_FORM_URL_SAFE.clone();
  81.     }

  82.     /**
  83.      * Decodes an array of URL safe 7-bit characters into an array of original bytes. Escaped characters are converted
  84.      * back to their original representation.
  85.      *
  86.      * @param bytes
  87.      *            array of URL safe characters
  88.      * @return array of original bytes
  89.      * @throws DecoderException
  90.      *             Thrown if URL decoding is unsuccessful
  91.      */
  92.     public static final byte[] decodeUrl(final byte[] bytes) throws DecoderException {
  93.         if (bytes == null) {
  94.             return null;
  95.         }
  96.         final ByteArrayOutputStream buffer = new ByteArrayOutputStream();
  97.         for (int i = 0; i < bytes.length; i++) {
  98.             final int b = bytes[i];
  99.             if (b == '+') {
  100.                 buffer.write(' ');
  101.             } else if (b == ESCAPE_CHAR) {
  102.                 try {
  103.                     final int u = Utils.digit16(bytes[++i]);
  104.                     final int l = Utils.digit16(bytes[++i]);
  105.                     buffer.write((char) ((u << 4) + l));
  106.                 } catch (final ArrayIndexOutOfBoundsException e) {
  107.                     throw new DecoderException("Invalid URL encoding: ", e);
  108.                 }
  109.             } else {
  110.                 buffer.write(b);
  111.             }
  112.         }
  113.         return buffer.toByteArray();
  114.     }

  115.     /**
  116.      * Encodes an array of bytes into an array of URL safe 7-bit characters. Unsafe characters are escaped.
  117.      *
  118.      * @param urlsafe
  119.      *            bitset of characters deemed URL safe
  120.      * @param bytes
  121.      *            array of bytes to convert to URL safe characters
  122.      * @return array of bytes containing URL safe characters
  123.      */
  124.     public static final byte[] encodeUrl(BitSet urlsafe, final byte[] bytes) {
  125.         if (bytes == null) {
  126.             return null;
  127.         }
  128.         if (urlsafe == null) {
  129.             urlsafe = WWW_FORM_URL_SAFE;
  130.         }

  131.         final ByteArrayOutputStream buffer = new ByteArrayOutputStream();
  132.         for (final byte c : bytes) {
  133.             int b = c;
  134.             if (b < 0) {
  135.                 b = 256 + b;
  136.             }
  137.             if (urlsafe.get(b)) {
  138.                 if (b == ' ') {
  139.                     b = '+';
  140.                 }
  141.                 buffer.write(b);
  142.             } else {
  143.                 buffer.write(ESCAPE_CHAR);
  144.                 final char hex1 = Utils.hexDigit(b >> 4);
  145.                 final char hex2 = Utils.hexDigit(b);
  146.                 buffer.write(hex1);
  147.                 buffer.write(hex2);
  148.             }
  149.         }
  150.         return buffer.toByteArray();
  151.     }

  152.     /**
  153.      * The default charset used for string decoding and encoding.
  154.      *
  155.      * @deprecated TODO: This field will be changed to a private final Charset in 2.0. (CODEC-126)
  156.      */
  157.     @Deprecated
  158.     protected volatile String charset; // added volatile: see CODEC-232

  159.     /**
  160.      * Default constructor.
  161.      */
  162.     public URLCodec() {
  163.         this(CharEncoding.UTF_8);
  164.     }

  165.     /**
  166.      * Constructor which allows for the selection of a default charset.
  167.      *
  168.      * @param charset the default string charset to use.
  169.      */
  170.     public URLCodec(final String charset) {
  171.         this.charset = charset;
  172.     }

  173.     /**
  174.      * Decodes an array of URL safe 7-bit characters into an array of original bytes. Escaped characters are converted
  175.      * back to their original representation.
  176.      *
  177.      * @param bytes
  178.      *            array of URL safe characters
  179.      * @return array of original bytes
  180.      * @throws DecoderException
  181.      *             Thrown if URL decoding is unsuccessful
  182.      */
  183.     @Override
  184.     public byte[] decode(final byte[] bytes) throws DecoderException {
  185.         return decodeUrl(bytes);
  186.     }

  187.     /**
  188.      * Decodes a URL safe object into its original form. Escaped characters are converted back to their original
  189.      * representation.
  190.      *
  191.      * @param obj
  192.      *            URL safe object to convert into its original form
  193.      * @return original object
  194.      * @throws DecoderException
  195.      *             Thrown if the argument is not a {@code String} or {@code byte[]}. Thrown if a failure
  196.      *             condition is encountered during the decode process.
  197.      */
  198.     @Override
  199.     public Object decode(final Object obj) throws DecoderException {
  200.         if (obj == null) {
  201.             return null;
  202.         }
  203.         if (obj instanceof byte[]) {
  204.             return decode((byte[]) obj);
  205.         }
  206.         if (obj instanceof String) {
  207.             return decode((String) obj);
  208.         }
  209.         throw new DecoderException("Objects of type " + obj.getClass().getName() + " cannot be URL decoded");
  210.     }

  211.     /**
  212.      * Decodes a URL safe string into its original form using the default string charset. Escaped characters are
  213.      * converted back to their original representation.
  214.      *
  215.      * @param str
  216.      *            URL safe string to convert into its original form
  217.      * @return original string
  218.      * @throws DecoderException
  219.      *             Thrown if URL decoding is unsuccessful
  220.      * @see #getDefaultCharset()
  221.      */
  222.     @Override
  223.     public String decode(final String str) throws DecoderException {
  224.         if (str == null) {
  225.             return null;
  226.         }
  227.         try {
  228.             return decode(str, getDefaultCharset());
  229.         } catch (final UnsupportedEncodingException e) {
  230.             throw new DecoderException(e.getMessage(), e);
  231.         }
  232.     }

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

  254.     /**
  255.      * Encodes an array of bytes into an array of URL safe 7-bit characters. Unsafe characters are escaped.
  256.      *
  257.      * @param bytes
  258.      *            array of bytes to convert to URL safe characters
  259.      * @return array of bytes containing URL safe characters
  260.      */
  261.     @Override
  262.     public byte[] encode(final byte[] bytes) {
  263.         return encodeUrl(WWW_FORM_URL_SAFE, bytes);
  264.     }

  265.     /**
  266.      * Encodes an object into its URL safe form. Unsafe characters are escaped.
  267.      *
  268.      * @param obj
  269.      *            string to convert to a URL safe form
  270.      * @return URL safe object
  271.      * @throws EncoderException
  272.      *             Thrown if URL encoding is not applicable to objects of this type or if encoding is unsuccessful
  273.      */
  274.     @Override
  275.     public Object encode(final Object obj) throws EncoderException {
  276.         if (obj == null) {
  277.             return null;
  278.         }
  279.         if (obj instanceof byte[]) {
  280.             return encode((byte[]) obj);
  281.         }
  282.         if (obj instanceof String) {
  283.             return encode((String) obj);
  284.         }
  285.         throw new EncoderException("Objects of type " + obj.getClass().getName() + " cannot be URL encoded");
  286.     }

  287.     /**
  288.      * Encodes a string into its URL safe form using the default string charset. Unsafe characters are escaped.
  289.      *
  290.      * @param str
  291.      *            string to convert to a URL safe form
  292.      * @return URL safe string
  293.      * @throws EncoderException
  294.      *             Thrown if URL encoding is unsuccessful
  295.      *
  296.      * @see #getDefaultCharset()
  297.      */
  298.     @Override
  299.     public String encode(final String str) throws EncoderException {
  300.         if (str == null) {
  301.             return null;
  302.         }
  303.         try {
  304.             return encode(str, getDefaultCharset());
  305.         } catch (final UnsupportedEncodingException e) {
  306.             throw new EncoderException(e.getMessage(), e);
  307.         }
  308.     }

  309.     /**
  310.      * Encodes a string into its URL safe form using the specified string charset. Unsafe characters are escaped.
  311.      *
  312.      * @param str
  313.      *            string to convert to a URL safe form
  314.      * @param charsetName
  315.      *            the charset for str
  316.      * @return URL safe string
  317.      * @throws UnsupportedEncodingException
  318.      *             Thrown if charset is not supported
  319.      */
  320.     public String encode(final String str, final String charsetName) throws UnsupportedEncodingException {
  321.         if (str == null) {
  322.             return null;
  323.         }
  324.         return StringUtils.newStringUsAscii(encode(str.getBytes(charsetName)));
  325.     }

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

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

  344. }