001/** 002 * 003 * Copyright the original author or authors 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.java7; 018 019import java.nio.charset.StandardCharsets; 020import java.util.Base64; 021 022import org.jivesoftware.smack.util.stringencoder.StringEncoder; 023 024 025/** 026 * A Base 64 encoding implementation that generates filename and Url safe encodings. 027 * 028 * <p> 029 * Note: This does NOT produce standard Base 64 encodings, but a variant as defined in 030 * Section 4 of RFC3548: 031 * <a href="http://www.faqs.org/rfcs/rfc3548.html">http://www.faqs.org/rfcs/rfc3548.html</a>. 032 * </p> 033 * 034 * @author Robin Collier 035 */ 036public final class Java7Base64UrlSafeEncoder implements StringEncoder<String> { 037 038 private static final Java7Base64UrlSafeEncoder instance = new Java7Base64UrlSafeEncoder(); 039 040 private final Base64.Encoder encoder; 041 private final Base64.Decoder decoder; 042 043 private Java7Base64UrlSafeEncoder() { 044 encoder = Base64.getUrlEncoder(); 045 decoder = Base64.getUrlDecoder(); 046 } 047 048 public static Java7Base64UrlSafeEncoder getInstance() { 049 return instance; 050 } 051 052 @Override 053 public String encode(String s) { 054 byte[] bytes = s.getBytes(StandardCharsets.UTF_8); 055 return encoder.encodeToString(bytes); 056 } 057 058 @Override 059 public String decode(String s) { 060 byte[] bytes = decoder.decode(s); 061 return new String(bytes, StandardCharsets.UTF_8); 062 } 063 064}