add ConfigFilter

This commit is contained in:
wenshao
2012-08-16 12:51:07 +08:00
parent 569c33efb2
commit f3d655e5df
10 changed files with 692 additions and 110 deletions
@@ -0,0 +1,185 @@
package com.alibaba.druid.filter.config;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.net.URL;
import java.security.KeyFactory;
import java.security.PublicKey;
import java.security.spec.X509EncodedKeySpec;
import java.util.Properties;
import javax.crypto.Cipher;
import com.alibaba.druid.filter.FilterAdapter;
import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.pool.DruidDataSourceFactory;
import com.alibaba.druid.proxy.jdbc.DataSourceProxy;
import com.alibaba.druid.support.logging.Log;
import com.alibaba.druid.support.logging.LogFactory;
import com.alibaba.druid.util.Base64;
import com.alibaba.druid.util.JdbcUtils;
public class ConfigFilter extends FilterAdapter {
public final static String URL_PREFIX = "druid-configFile=";
public final static String SYS_PROP = "druid.configFile";
public final static String DEFAULT_ALGORITHM = "RSA";
private final static Log LOG = LogFactory.getLog(ConfigFilter.class);
private String file;
private Cipher cipher;
private String algorithm;
private String key;
public ConfigFilter(){
this.setAlgorithm(DEFAULT_ALGORITHM);
}
public String getAlgorithm() {
return algorithm;
}
public void setAlgorithm(String algorithm) {
this.algorithm = algorithm;
try {
this.cipher = Cipher.getInstance(algorithm);
} catch (Exception e) {
throw new IllegalArgumentException("illegal algorithm", e);
}
}
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
byte[] bytes = Base64.base64ToByteArray(key);
try {
if (cipher.getAlgorithm().startsWith("RSA")) {
X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(bytes);
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
PublicKey publicKey = keyFactory.generatePublic(x509KeySpec);
cipher.init(Cipher.DECRYPT_MODE, publicKey);
}
} catch (Exception e) {
throw new IllegalArgumentException("illegal key", e);
}
}
public void init(DataSourceProxy dataSourceProxy) {
if (!(dataSourceProxy instanceof DruidDataSource)) {
LOG.error("ConfigLoader only support DruidDataSource");
}
DruidDataSource dataSource = (DruidDataSource) dataSourceProxy;
Properties properties = loadConfig(dataSource);
if (properties == null) {
LOG.error("load config error, return null");
return;
}
try {
if (this.cipher != null) {
String password = properties.getProperty(DruidDataSourceFactory.PROP_PASSWORD);
if (password != null && password.length() != 0) {
byte[] passwordBytes = Base64.base64ToByteArray(password);
byte[] decryptedBytes = cipher.doFinal(passwordBytes);
String decryptedPassword = new String(decryptedBytes, "ISO-8859-1");
properties.put(DruidDataSourceFactory.PROP_PASSWORD, decryptedPassword);
}
}
} catch (Exception e) {
LOG.error("decrypt password error", e);
}
try {
DruidDataSourceFactory.config(dataSource, properties);
} catch (Exception e) {
LOG.error("config dataSource error", e);
}
}
public Properties loadConfig(DruidDataSource dataSource) {
String filePath = this.file;
// jdbc:druid-config:
if (file == null && dataSource.getUrl() != null && dataSource.getUrl().startsWith(ConfigFilter.URL_PREFIX)) {
filePath = dataSource.getUrl().substring(ConfigFilter.URL_PREFIX.length());
}
if (filePath == null) {
filePath = System.getProperty(SYS_PROP);
}
if (filePath == null) {
LOG.error("load config error, file is null");
return null;
}
Properties properties = new Properties();
InputStream inStream = null;
try {
boolean xml = false;
if (filePath.startsWith("http://")) {
URL url = new URL(filePath);
inStream = url.openStream();
xml = url.getPath().endsWith(".xml");
} else {
File file = new File(filePath);
if (file.exists()) {
inStream = new FileInputStream(file);
} else {
inStream = Thread.currentThread().getContextClassLoader().getResourceAsStream(filePath);
}
xml = filePath.endsWith(".xml");
}
if (inStream == null) {
LOG.error("load config file error, file : " + filePath);
return null;
}
if (xml) {
properties.loadFromXML(inStream);
} else {
properties.load(inStream);
}
return properties;
} catch (Exception ex) {
LOG.error("load config file error, file : " + filePath, ex);
return null;
} finally {
JdbcUtils.close(inStream);
}
}
public String getFile() {
return file;
}
public void setFile(String file) {
this.file = file;
}
public Cipher getCipher() {
return cipher;
}
public void setCipher(Cipher cipher) {
this.cipher = cipher;
}
}
@@ -34,6 +34,7 @@ import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.locks.ReentrantLock;
import java.util.logging.Logger;
@@ -48,6 +49,7 @@ import javax.sql.DataSource;
import com.alibaba.druid.filter.Filter;
import com.alibaba.druid.filter.FilterChainImpl;
import com.alibaba.druid.filter.FilterManager;
import com.alibaba.druid.filter.config.ConfigFilter;
import com.alibaba.druid.pool.DruidDataSource.ActiveConnectionTraceInfo;
import com.alibaba.druid.pool.vendor.NullExceptionSorter;
import com.alibaba.druid.proxy.jdbc.DataSourceProxy;
@@ -131,7 +133,7 @@ public abstract class DruidAbstractDataSource extends WrapperAdapter implements
protected PrintWriter logWriter = new PrintWriter(
System.out);
protected List<Filter> filters = new ArrayList<Filter>();
protected List<Filter> filters = new CopyOnWriteArrayList<Filter>();
protected ExceptionSorter exceptionSorter = null;
protected Driver driver;
@@ -921,7 +923,15 @@ public abstract class DruidAbstractDataSource extends WrapperAdapter implements
throw new UnsupportedOperationException();
}
if (jdbcUrl != null) {
jdbcUrl = jdbcUrl.trim();
}
this.jdbcUrl = jdbcUrl;
if (jdbcUrl.startsWith(ConfigFilter.URL_PREFIX)) {
this.filters.add(new ConfigFilter());
}
}
public String getDriverClassName() {
@@ -957,6 +967,10 @@ public abstract class DruidAbstractDataSource extends WrapperAdapter implements
}
protected void initConnectionFactory() throws SQLException {
if (connectionFactory != null) {
return;
}
connectionFactory = createConnectionFactory();
}
@@ -1259,7 +1273,7 @@ public abstract class DruidAbstractDataSource extends WrapperAdapter implements
@Override
public Connection createConnection() throws SQLException {
Connection conn;
PasswordCallback passwordCallback = dataSource.getPasswordCallback();
if (passwordCallback != null) {
char[] chars = passwordCallback.getPassword();
@@ -1272,32 +1286,13 @@ public abstract class DruidAbstractDataSource extends WrapperAdapter implements
long startNano = System.nanoTime();
try {
if (dataSource.getProxyFilters().size() != 0) {
conn = new FilterChainImpl(dataSource).connection_connect(info);
} else {
conn = dataSource.getDriver().connect(url, info);
}
conn = connect();
if (conn == null) {
throw new SQLException("connect error, url " + url);
}
conn.setAutoCommit(dataSource.isDefaultAutoCommit());
if (dataSource.getDefaultReadOnly() != null) {
if (conn.isReadOnly() != dataSource.getDefaultReadOnly()) {
conn.setReadOnly(dataSource.getDefaultReadOnly());
}
}
if (dataSource.getDefaultTransactionIsolation() != null) {
if (conn.getTransactionIsolation() != dataSource.getDefaultTransactionIsolation().intValue()) {
conn.setTransactionIsolation(dataSource.getDefaultTransactionIsolation());
}
}
if (dataSource.getDefaultCatalog() != null && dataSource.getDefaultCatalog().length() != 0) {
conn.setCatalog(dataSource.getDefaultCatalog());
}
initConnection(conn);
dataSource.validateConnection(conn);
dataSource.createError = null;
@@ -1325,6 +1320,35 @@ public abstract class DruidAbstractDataSource extends WrapperAdapter implements
return conn;
}
public Connection connect() throws SQLException {
Connection conn;
if (dataSource.getProxyFilters().size() != 0) {
conn = new FilterChainImpl(dataSource).connection_connect(info);
} else {
conn = dataSource.getDriver().connect(url, info);
}
return conn;
}
public void initConnection(Connection conn) throws SQLException {
conn.setAutoCommit(dataSource.isDefaultAutoCommit());
if (dataSource.getDefaultReadOnly() != null) {
if (conn.isReadOnly() != dataSource.getDefaultReadOnly()) {
conn.setReadOnly(dataSource.getDefaultReadOnly());
}
}
if (dataSource.getDefaultTransactionIsolation() != null) {
if (conn.getTransactionIsolation() != dataSource.getDefaultTransactionIsolation().intValue()) {
conn.setTransactionIsolation(dataSource.getDefaultTransactionIsolation());
}
}
if (dataSource.getDefaultCatalog() != null && dataSource.getDefaultCatalog().length() != 0) {
conn.setCatalog(dataSource.getDefaultCatalog());
}
}
}
public CompositeDataSupport getCompositeData() throws JMException {
@@ -257,9 +257,11 @@ public class DruidDataSource extends DruidAbstractDataSource implements DruidDat
}
initStackTrace = IOUtils.toString(Thread.currentThread().getStackTrace());
this.id = DruidDriver.createDataSourceId();
loadFilterFromSystemProperty();
for (Filter filter : filters) {
filter.init(this);
}
@@ -284,41 +286,11 @@ public class DruidDataSource extends DruidAbstractDataSource implements DruidDat
this.driverClass = driverClass.trim();
}
if (isTestOnBorrow() || isTestOnReturn() || isTestWhileIdle()) {
if (this.getValidationQuery() == null || this.getValidationQuery().length() == 0) {
String errorMessage = "";
if (isTestOnBorrow()) {
errorMessage += "testOnBorrow is true, ";
}
if (isTestOnReturn()) {
errorMessage += "testOnReturn is true, ";
}
if (isTestWhileIdle()) {
errorMessage += "testWhileIdle is true, ";
}
LOG.error(errorMessage + "validationQuery not set");
}
}
validationQueryCheck();
if (this.jdbcUrl != null) {
this.jdbcUrl = this.jdbcUrl.trim();
if (jdbcUrl.startsWith(DruidDriver.DEFAULT_PREFIX)) {
DataSourceProxyConfig config = DruidDriver.parseConfig(jdbcUrl, null);
this.driverClass = config.getRawDriverClassName();
LOG.error("error url : '" + jdbcUrl + "', it should be : '" + config.getRawUrl() + "'");
this.jdbcUrl = config.getRawUrl();
if (this.name == null) {
this.name = config.getName();
}
this.filters.addAll(config.getFilters());
}
initFromWrapDriverUrl();
}
if (this.driver == null) {
@@ -342,41 +314,13 @@ public class DruidDataSource extends DruidAbstractDataSource implements DruidDat
}
if ("oracle".equals(this.dbType)) {
isOracle = true;
if (driver.getMajorVersion() < 10) {
throw new SQLException("not support oracle driver " + driver.getMajorVersion() + "."
+ driver.getMinorVersion());
}
if (driver.getMajorVersion() == 10 && isUseOracleImplicitCache()) {
this.getConnectProperties().setProperty("oracle.jdbc.FreeMemoryOnEnterImplicitCache", "true");
}
initOracle();
}
String realDriverClassName = driver.getClass().getName();
if (realDriverClassName.equals("com.mysql.jdbc.Driver")) {
this.validConnectionChecker = new MySqlValidConnectionChecker();
this.exceptionSorter = new MySqlExceptionSorter();
initExceptionSorter();
initValidConnectionChecker();
} else if (realDriverClassName.equals("oracle.jdbc.driver.OracleDriver")) {
this.validConnectionChecker = new OracleValidConnectionChecker();
this.exceptionSorter = new OracleExceptionSorter();
} else if (realDriverClassName.equals("com.microsoft.jdbc.sqlserver.SQLServerDriver")) {
this.validConnectionChecker = new MSSQLValidConnectionChecker();
} else if (realDriverClassName.equals("com.informix.jdbc.IfxDriver")) {
this.exceptionSorter = new InformixExceptionSorter();
} else if (realDriverClassName.equals("com.sybase.jdbc2.jdbc.SybDriver")) {
this.exceptionSorter = new SybaseExceptionSorter();
} else if (realDriverClassName.equals("com.alibaba.druid.mock.MockDriver")) {
this.exceptionSorter = new MockExceptionSorter();
}
if (realDriverClassName.equals("com.mysql.jdbc.Driver")) {
if (driver.getClass().getName().equals("com.mysql.jdbc.Driver")) {
if (this.isPoolPreparedStatements()) {
LOG.error("mysql should not use 'PoolPreparedStatements'");
}
@@ -384,13 +328,6 @@ public class DruidDataSource extends DruidAbstractDataSource implements DruidDat
dataSourceStat = new JdbcDataSourceStat(this.name, this.jdbcUrl, this.dbType);
{
String property = System.getProperty("druid.filters");
if (property != null && property.length() > 0) {
this.setFilters(property);
}
}
initConnectionFactory();
connections = new ConnectionHolder[maxActive];
@@ -440,6 +377,117 @@ public class DruidDataSource extends DruidAbstractDataSource implements DruidDat
}
}
private void loadFilterFromSystemProperty() throws SQLException {
String property = System.getProperty("druid.filters");
if (property == null || property.length() == 0) {
return;
}
this.setFilters(property);
}
private void initFromWrapDriverUrl() throws SQLException {
if (!jdbcUrl.startsWith(DruidDriver.DEFAULT_PREFIX)) {
return;
}
DataSourceProxyConfig config = DruidDriver.parseConfig(jdbcUrl, null);
this.driverClass = config.getRawDriverClassName();
LOG.error("error url : '" + jdbcUrl + "', it should be : '" + config.getRawUrl() + "'");
this.jdbcUrl = config.getRawUrl();
if (this.name == null) {
this.name = config.getName();
}
// 防止重复
for (Filter filter : config.getFilters()) {
boolean exists = false;
for (Filter initedFilter : this.filters) {
if (initedFilter.getClass() == filter.getClass()) {
exists = true;
break;
}
}
if (exists) {
continue;
}
filter.init(this);
this.filters.add(filter);
}
}
private void validationQueryCheck() {
if (!(isTestOnBorrow() || isTestOnReturn() || isTestWhileIdle())) {
return;
}
if (this.getValidationQuery() != null && this.getValidationQuery().length() > 0) {
return;
}
String errorMessage = "";
if (isTestOnBorrow()) {
errorMessage += "testOnBorrow is true, ";
}
if (isTestOnReturn()) {
errorMessage += "testOnReturn is true, ";
}
if (isTestWhileIdle()) {
errorMessage += "testWhileIdle is true, ";
}
LOG.error(errorMessage + "validationQuery not set");
}
private void initOracle() throws SQLException {
isOracle = true;
if (driver.getMajorVersion() < 10) {
throw new SQLException("not support oracle driver " + driver.getMajorVersion() + "."
+ driver.getMinorVersion());
}
if (driver.getMajorVersion() == 10 && isUseOracleImplicitCache()) {
this.getConnectProperties().setProperty("oracle.jdbc.FreeMemoryOnEnterImplicitCache", "true");
}
}
private void initValidConnectionChecker() {
String realDriverClassName = driver.getClass().getName();
if (realDriverClassName.equals("com.mysql.jdbc.Driver")) {
this.validConnectionChecker = new MySqlValidConnectionChecker();
} else if (realDriverClassName.equals("oracle.jdbc.driver.OracleDriver")) {
this.validConnectionChecker = new OracleValidConnectionChecker();
} else if (realDriverClassName.equals("com.microsoft.jdbc.sqlserver.SQLServerDriver")) {
this.validConnectionChecker = new MSSQLValidConnectionChecker();
}
}
private void initExceptionSorter() {
String realDriverClassName = driver.getClass().getName();
if (realDriverClassName.equals("com.mysql.jdbc.Driver")) {
this.exceptionSorter = new MySqlExceptionSorter();
} else if (realDriverClassName.equals("oracle.jdbc.driver.OracleDriver")) {
this.exceptionSorter = new OracleExceptionSorter();
} else if (realDriverClassName.equals("com.informix.jdbc.IfxDriver")) {
this.exceptionSorter = new InformixExceptionSorter();
} else if (realDriverClassName.equals("com.sybase.jdbc2.jdbc.SybDriver")) {
this.exceptionSorter = new SybaseExceptionSorter();
} else if (realDriverClassName.equals("com.alibaba.druid.mock.MockDriver")) {
this.exceptionSorter = new MockExceptionSorter();
}
}
@Override
public DruidPooledConnection getConnection() throws SQLException {
return getConnection(maxWait);
@@ -771,12 +819,12 @@ public class DruidDataSource extends DruidAbstractDataSource implements DruidDat
for (int i = 0; i < poolingCount; ++i) {
try {
ConnectionHolder connHolder = connections[i];
for (PreparedStatementHolder stmtHolder : connHolder.getStatementPool().getMap().values()) {
connHolder.getStatementPool().closeRemovedStatement(stmtHolder);
}
connHolder.getStatementPool().getMap().clear();
JdbcUtils.close(connHolder.getConnection());
connections[i] = null;
destroyCount++;
@@ -1590,16 +1638,16 @@ public class DruidDataSource extends DruidAbstractDataSource implements DruidDat
map.put("LastCreateErrorTime", this.getLastCreateErrorTime());
map.put("CreateErrorCount", this.getCreateErrorCount());
map.put("DiscardCount", this.getDiscardCount());
return map;
} catch (JMException ex) {
throw new IllegalStateException("getStatData error", ex);
throw new IllegalStateException("getStatData error", ex);
}
}
public Map<String, Object> getStatData() {
Map<String, Object> dataMap = new LinkedHashMap<String, Object>();
dataMap.put("Identity", System.identityHashCode(this));
dataMap.put("Name", this.getName());
dataMap.put("DbType", this.getDbType());
@@ -1615,13 +1663,11 @@ public class DruidDataSource extends DruidAbstractDataSource implements DruidDat
dataMap.put("PoolingCount", this.getPoolingCount());
dataMap.put("PoolingPeak", this.getPoolingPeak());
dataMap.put("PoolingPeakTime",
this.getPoolingPeakTime() == null ? null : this.getPoolingPeakTime().toString());
dataMap.put("PoolingPeakTime", this.getPoolingPeakTime() == null ? null : this.getPoolingPeakTime().toString());
dataMap.put("ActiveCount", this.getActiveCount());
dataMap.put("ActivePeak", this.getActivePeak());
dataMap.put("ActivePeakTime",
this.getActivePeakTime() == null ? null : this.getActivePeakTime().toString());
dataMap.put("ActivePeakTime", this.getActivePeakTime() == null ? null : this.getActivePeakTime().toString());
dataMap.put("InitialSize", this.getInitialSize());
dataMap.put("MinIdle", this.getMinIdle());
@@ -1661,17 +1707,16 @@ public class DruidDataSource extends DruidAbstractDataSource implements DruidDat
dataMap.put("StartTransactionCount", this.getStartTransactionCount());
dataMap.put("TransactionHistogram", this.getTransactionHistogramValues());
dataMap.put("ConnectionHoldTimeHistogram",
this.getDataSourceStat().getConnectionHoldHistogram().toArray());
dataMap.put("ConnectionHoldTimeHistogram", this.getDataSourceStat().getConnectionHoldHistogram().toArray());
dataMap.put("RemoveAbandoned", this.isRemoveAbandoned());
return dataMap;
}
public JdbcSqlStat getSqlStat(int sqlId) {
return this.getDataSourceStat().getSqlStat(sqlId);
}
public Map<String, JdbcSqlStat> getSqlStatMap() {
return this.getDataSourceStat().getSqlStatMap();
}
@@ -0,0 +1,185 @@
package com.alibaba.druid.util;
/**
* Static methods for translating Base64 encoded strings to byte arrays and vice-versa.
*
* @author Josh Bloch
* @version %I%, %G%
* @see Preferences
* @since 1.4
*/
public class Base64 {
/**
* Translates the specified byte array into a Base64 string as per Preferences.put(byte[]).
*/
public static String byteArrayToBase64(byte[] a) {
return byteArrayToBase64(a, false);
}
/**
* Translates the specified byte array into an "alternate representation" Base64 string. This non-standard variant
* uses an alphabet that does not contain the uppercase alphabetic characters, which makes it suitable for use in
* situations where case-folding occurs.
*/
public static String byteArrayToAltBase64(byte[] a) {
return byteArrayToBase64(a, true);
}
private static String byteArrayToBase64(byte[] a, boolean alternate) {
int aLen = a.length;
int numFullGroups = aLen / 3;
int numBytesInPartialGroup = aLen - 3 * numFullGroups;
int resultLen = 4 * ((aLen + 2) / 3);
StringBuffer result = new StringBuffer(resultLen);
char[] intToAlpha = (alternate ? intToAltBase64 : intToBase64);
// Translate all full groups from byte array elements to Base64
int inCursor = 0;
for (int i = 0; i < numFullGroups; i++) {
int byte0 = a[inCursor++] & 0xff;
int byte1 = a[inCursor++] & 0xff;
int byte2 = a[inCursor++] & 0xff;
result.append(intToAlpha[byte0 >> 2]);
result.append(intToAlpha[(byte0 << 4) & 0x3f | (byte1 >> 4)]);
result.append(intToAlpha[(byte1 << 2) & 0x3f | (byte2 >> 6)]);
result.append(intToAlpha[byte2 & 0x3f]);
}
// Translate partial group if present
if (numBytesInPartialGroup != 0) {
int byte0 = a[inCursor++] & 0xff;
result.append(intToAlpha[byte0 >> 2]);
if (numBytesInPartialGroup == 1) {
result.append(intToAlpha[(byte0 << 4) & 0x3f]);
result.append("==");
} else {
// assert numBytesInPartialGroup == 2;
int byte1 = a[inCursor++] & 0xff;
result.append(intToAlpha[(byte0 << 4) & 0x3f | (byte1 >> 4)]);
result.append(intToAlpha[(byte1 << 2) & 0x3f]);
result.append('=');
}
}
// assert inCursor == a.length;
// assert result.length() == resultLen;
return result.toString();
}
/**
* This array is a lookup table that translates 6-bit positive integer index values into their "Base64 Alphabet"
* equivalents as specified in Table 1 of RFC 2045.
*/
private static final char intToBase64[] = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M',
'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h',
'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2',
'3', '4', '5', '6', '7', '8', '9', '+', '/' };
/**
* This array is a lookup table that translates 6-bit positive integer index values into their
* "Alternate Base64 Alphabet" equivalents. This is NOT the real Base64 Alphabet as per in Table 1 of RFC 2045. This
* alternate alphabet does not use the capital letters. It is designed for use in environments where "case folding"
* occurs.
*/
private static final char intToAltBase64[] = { '!', '"', '#', '$', '%', '&', '\'', '(', ')', ',', '-', '.', ':',
';', '<', '>', '@', '[', ']', '^', '`', '_', '{', '|', '}', '~', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h',
'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2',
'3', '4', '5', '6', '7', '8', '9', '+', '?' };
/**
* Translates the specified Base64 string (as per Preferences.get(byte[])) into a byte array.
*
* @throw IllegalArgumentException if <tt>s</tt> is not a valid Base64 string.
*/
public static byte[] base64ToByteArray(String s) {
return base64ToByteArray(s, false);
}
/**
* Translates the specified "alternate representation" Base64 string into a byte array.
*
* @throw IllegalArgumentException or ArrayOutOfBoundsException if <tt>s</tt> is not a valid alternate
* representation Base64 string.
*/
public static byte[] altBase64ToByteArray(String s) {
return base64ToByteArray(s, true);
}
private static byte[] base64ToByteArray(String s, boolean alternate) {
byte[] alphaToInt = (alternate ? altBase64ToInt : base64ToInt);
int sLen = s.length();
int numGroups = sLen / 4;
if (4 * numGroups != sLen) throw new IllegalArgumentException("String length must be a multiple of four.");
int missingBytesInLastGroup = 0;
int numFullGroups = numGroups;
if (sLen != 0) {
if (s.charAt(sLen - 1) == '=') {
missingBytesInLastGroup++;
numFullGroups--;
}
if (s.charAt(sLen - 2) == '=') missingBytesInLastGroup++;
}
byte[] result = new byte[3 * numGroups - missingBytesInLastGroup];
// Translate all full groups from base64 to byte array elements
int inCursor = 0, outCursor = 0;
for (int i = 0; i < numFullGroups; i++) {
int ch0 = base64toInt(s.charAt(inCursor++), alphaToInt);
int ch1 = base64toInt(s.charAt(inCursor++), alphaToInt);
int ch2 = base64toInt(s.charAt(inCursor++), alphaToInt);
int ch3 = base64toInt(s.charAt(inCursor++), alphaToInt);
result[outCursor++] = (byte) ((ch0 << 2) | (ch1 >> 4));
result[outCursor++] = (byte) ((ch1 << 4) | (ch2 >> 2));
result[outCursor++] = (byte) ((ch2 << 6) | ch3);
}
// Translate partial group, if present
if (missingBytesInLastGroup != 0) {
int ch0 = base64toInt(s.charAt(inCursor++), alphaToInt);
int ch1 = base64toInt(s.charAt(inCursor++), alphaToInt);
result[outCursor++] = (byte) ((ch0 << 2) | (ch1 >> 4));
if (missingBytesInLastGroup == 1) {
int ch2 = base64toInt(s.charAt(inCursor++), alphaToInt);
result[outCursor++] = (byte) ((ch1 << 4) | (ch2 >> 2));
}
}
// assert inCursor == s.length()-missingBytesInLastGroup;
// assert outCursor == result.length;
return result;
}
/**
* Translates the specified character, which is assumed to be in the "Base 64 Alphabet" into its equivalent 6-bit
* positive integer.
*
* @throw IllegalArgumentException or ArrayOutOfBoundsException if c is not in the Base64 Alphabet.
*/
private static int base64toInt(char c, byte[] alphaToInt) {
int result = alphaToInt[c];
if (result < 0) throw new IllegalArgumentException("Illegal character " + c);
return result;
}
/**
* This array is a lookup table that translates unicode characters drawn from the "Base64 Alphabet" (as specified in
* Table 1 of RFC 2045) into their 6-bit positive integer equivalents. Characters that are not in the Base64
* alphabet but fall within the bounds of the array are translated to -1.
*/
private static final byte base64ToInt[] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 62,
-1, -1, -1, 63, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1, -1, -1, -1, -1, -1, 0, 1, 2, 3, 4, 5, 6, 7,
8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1, -1, 26, 27, 28,
29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51 };
/**
* This array is the analogue of base64ToInt, but for the nonstandard variant that avoids the use of uppercase
* alphabetic characters.
*/
private static final byte altBase64ToInt[] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, -1, 62, 9, 10,
11, -1, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 12, 13, 14, -1, 15, 63, 16, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 17, -1, 18, 19, 21, 20, 26, 27, 28,
29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 22, 23, 24, 25 };
}