View Javadoc

1   /*
2    * Copyright 2004 Sun Microsystems, Inc.
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    *     http://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 com.sun.syndication.io.impl;
18  
19  import java.io.UnsupportedEncodingException;
20  
21  /***
22   * Encodes/decodes String values into/from a base 64 String.
23   * <p>
24   * It uses Jakarta commons codec Base64 class.
25   * <p>
26   * @author Alejandro Abdelnur
27   *
28   */
29  public class Base64 {
30  
31      /***
32       * Encodes a String into a base 64 String. The resulting encoding is chunked at 76 bytes.
33       * <p>
34       * @param s String to encode.
35       * @param encoding the encoding of the original String, <b>null</b> indicates platform's default.
36       * @return encoded string.
37       * @throws java.io.UnsupportedEncodingException thrown if the given encoding is not supported.
38       *
39       */
40      public static String encode(String s,String encoding) throws UnsupportedEncodingException {
41          if (s==null) {
42              throw new IllegalArgumentException("Cannot encode null");
43          }
44          byte[] sBytes = (encoding!=null) ? s.getBytes(encoding) : s.getBytes();
45          sBytes = org.apache.commons.codec.binary.Base64.encodeBase64Chunked(sBytes);
46          s = new String(sBytes); // no need to specify encoding as it's all 7bits
47          return s;
48      }
49  
50      /***
51       * Decodes a base 64 String into a String.
52       * <p>
53       * @param s String to decode.
54       * @param encoding the encoding of the String being decoded, <b>null</b> indicates platform's default.
55       * @return encoded string.
56       * @throws java.io.UnsupportedEncodingException thrown if the given encoding is not supported.
57       *
58       */
59      public static String decode(String s,String encoding) throws UnsupportedEncodingException {
60          if (s==null) {
61              throw new IllegalArgumentException("Cannot decode null");
62          }
63          byte[] sBytes = s.getBytes();  // no need to specify encoding as it's all 7bits (it should be)
64          sBytes = org.apache.commons.codec.binary.Base64.decodeBase64(sBytes);
65          s = (encoding!=null) ? new String(sBytes,encoding) : new String(sBytes);
66          return s;
67      }
68  
69  }
70