View Javadoc
1   /*
2    * Copyright 2008 Web Cohesion
3    *
4    * Licensed under the Apache License, Version 2.0 (the "License");
5    * you may not use this file except in compliance with the License.
6    * You may obtain a copy of the License at
7    *
8    *   https://www.apache.org/licenses/LICENSE-2.0
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS,
12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13   * See the License for the specific language governing permissions and
14   * limitations under the License.
15   */
16  
17  package org.springframework.security.oauth.common;
18  
19  import org.apache.commons.codec.DecoderException;
20  import org.apache.commons.codec.net.URLCodec;
21  
22  import java.io.UnsupportedEncodingException;
23  import java.util.BitSet;
24  
25  /**
26   * Utility for parameter encoding according to the OAuth spec.
27   *
28   * @author Ryan Heaton
29   */
30  public class OAuthCodec extends URLCodec {
31  
32    protected static final BitSet SAFE_CHARACTERS = (BitSet) URLCodec.WWW_FORM_URL.clone();
33    static {
34      //The OAuth codec defines different safe characters than the standard URL codec.
35      SAFE_CHARACTERS.clear('*');
36      SAFE_CHARACTERS.clear(' ');
37      SAFE_CHARACTERS.set('~');
38    }
39  
40    /**
41     * Private constructor (instance methods not accessible).
42     */
43    private OAuthCodec() {
44    }
45  
46    /**
47     * Encode the specified value.
48     *
49     * @param value The value to encode.
50     * @return The encoded value.
51     */
52    public static String oauthEncode(String value) {
53      if (value == null) {
54        return "";
55      }
56  
57      try {
58        return new String(URLCodec.encodeUrl(SAFE_CHARACTERS, value.getBytes("UTF-8")), "US-ASCII");
59      }
60      catch (UnsupportedEncodingException e) {
61        throw new RuntimeException(e);
62      }
63    }
64  
65    /**
66     * Decode the specified value.
67     *
68     * @param value The value to decode.
69     * @return The decoded value.
70     * @throws DecoderException when URLCodec fails
71     */
72    public static String oauthDecode(String value) throws DecoderException {
73      if (value == null) {
74        return "";
75      }
76  
77      try {
78        return new String(URLCodec.decodeUrl(value.getBytes("US-ASCII")), "UTF-8");
79      }
80      catch (UnsupportedEncodingException e) {
81        throw new RuntimeException(e);
82      }
83    }
84  
85  }