001/*
002 *  Copyright (c) 2022-2023, Mybatis-Flex (fuhai999@gmail.com).
003 *  <p>
004 *  Licensed under the Apache License, Version 2.0 (the "License");
005 *  you may not use this file except in compliance with the License.
006 *  You may obtain a copy of the License at
007 *  <p>
008 *  http://www.apache.org/licenses/LICENSE-2.0
009 *  <p>
010 *  Unless required by applicable law or agreed to in writing, software
011 *  distributed under the License is distributed on an "AS IS" BASIS,
012 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 *  See the License for the specific language governing permissions and
014 *  limitations under the License.
015 */
016package com.mybatisflex.core.datasource;
017
018import com.mybatisflex.core.util.ClassUtil;
019import org.apache.ibatis.logging.LogFactory;
020
021import javax.sql.DataSource;
022import java.lang.reflect.Method;
023
024public class DataSourceManager {
025
026    private static DataSourceDecipher decipher;
027
028    public static DataSourceDecipher getDecipher() {
029        return decipher;
030    }
031
032    public static void setDecipher(DataSourceDecipher decipher) {
033        DataSourceManager.decipher = decipher;
034    }
035
036
037    public static void decryptDataSource(DataSource dataSource) {
038        if (decipher == null) {
039            return;
040        }
041
042        for (DataSourceProperty property : DataSourceProperty.values()) {
043            Method getterMethod = ClassUtil.getAnyMethod(dataSource.getClass(), property.getGetterMethods());
044            if (getterMethod != null) {
045                String value = invokeMethod(getterMethod, dataSource);
046                if (value != null) {
047                    value = decipher.decrypt(property, value);
048                    Method setter = ClassUtil.getAnyMethod(dataSource.getClass(), property.getSetterMethods());
049                    if (setter != null && value != null) {
050                        invokeMethod(setter, dataSource, value);
051                    }
052                }
053            }
054        }
055    }
056
057
058    static String invokeMethod(Method method, Object object, Object... params) {
059        try {
060            return (String) method.invoke(object, params);
061        } catch (Exception e) {
062            LogFactory.getLog(DataSourceManager.class).error("Can not invoke method: " + method.getName(), e);
063        }
064        return null;
065    }
066
067
068}