001/** 002 * 003 * Copyright © 2014 Florian Schmaus 004 * 005 * Licensed under the Apache License, Version 2.0 (the "License"); 006 * you may not use this file except in compliance with the License. 007 * You may obtain a copy of the License at 008 * 009 * http://www.apache.org/licenses/LICENSE-2.0 010 * 011 * Unless required by applicable law or agreed to in writing, software 012 * distributed under the License is distributed on an "AS IS" BASIS, 013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 014 * See the License for the specific language governing permissions and 015 * limitations under the License. 016 */ 017package org.jivesoftware.smack.util.stringencoder.android; 018 019import java.io.UnsupportedEncodingException; 020 021import org.jivesoftware.smack.util.StringUtils; 022import org.jivesoftware.smack.util.stringencoder.StringEncoder; 023 024import android.util.Base64; 025 026 027/** 028 * 029 */ 030public class AndroidBase64UrlSafeEncoder implements StringEncoder { 031 032 private static AndroidBase64UrlSafeEncoder instance = new AndroidBase64UrlSafeEncoder(); 033 034 private static final int BASE64_ENCODER_FLAGS = Base64.URL_SAFE | Base64.NO_WRAP; 035 036 private AndroidBase64UrlSafeEncoder() { 037 // Use getInstance() 038 } 039 040 public static AndroidBase64UrlSafeEncoder getInstance() { 041 return instance; 042 } 043 044 @Override 045 public String encode(String string) { 046 try { 047 return Base64.encodeToString(string.getBytes(StringUtils.UTF8), BASE64_ENCODER_FLAGS); 048 } catch (UnsupportedEncodingException e) { 049 throw new IllegalStateException("UTF-8 not supported", e); 050 } 051 } 052 053 @Override 054 public String decode(String string) { 055 byte[] bytes = Base64.decode(string, BASE64_ENCODER_FLAGS); 056 try { 057 return new String(bytes, StringUtils.UTF8); 058 } catch (UnsupportedEncodingException e) { 059 throw new IllegalStateException("UTF-8 not supported", e); 060 } 061 } 062 063}