001
014
015 package com.liferay.portal.dao.shard;
016
017 import com.liferay.portal.kernel.log.Log;
018 import com.liferay.portal.kernel.log.LogFactoryUtil;
019 import com.liferay.portal.kernel.util.CentralizedThreadLocal;
020 import com.liferay.portal.util.PropsValues;
021
022 import java.util.Map;
023 import java.util.Set;
024
025 import javax.sql.DataSource;
026
027 import org.springframework.aop.TargetSource;
028
029
032 public class ShardDataSourceTargetSource implements TargetSource {
033
034 public String[] getAvailableShardNames() {
035 return _availableShardNames;
036 }
037
038 public DataSource getDataSource() {
039 return _dataSource.get();
040 }
041
042 public Map<String, DataSource> getDataSources() {
043 return _dataSources;
044 }
045
046 @Override
047 public Object getTarget() throws Exception {
048 return getDataSource();
049 }
050
051 @Override
052 public Class<DataSource> getTargetClass() {
053 return DataSource.class;
054 }
055
056 @Override
057 public boolean isStatic() {
058 return false;
059 }
060
061 @Override
062 public void releaseTarget(Object target) throws Exception {
063 }
064
065 public void resetDataSource() {
066 DataSource dataSource = _dataSources.get(
067 PropsValues.SHARD_DEFAULT_NAME);
068
069 _dataSource.set(dataSource);
070 }
071
072 public void setDataSource(String shardName) {
073 DataSource dataSource = _dataSources.get(shardName);
074
075 _dataSource.set(dataSource);
076 }
077
078 public void setDataSources(Map<String, DataSource> dataSources) {
079 _dataSources = dataSources;
080
081 Set<String> shardNames = _dataSources.keySet();
082
083 _availableShardNames = shardNames.toArray(
084 new String[shardNames.size()]);
085
086 if (_log.isInfoEnabled()) {
087 _log.info(
088 "Sharding configured with " + _availableShardNames.length +
089 " data sources");
090 }
091 }
092
093 private static Log _log = LogFactoryUtil.getLog(
094 ShardDataSourceTargetSource.class);
095
096 private static String[] _availableShardNames;
097
098 private static ThreadLocal<DataSource> _dataSource =
099 new CentralizedThreadLocal<DataSource>(false) {
100
101 @Override
102 protected DataSource initialValue() {
103 return _dataSources.get(PropsValues.SHARD_DEFAULT_NAME);
104 }
105
106 };
107
108 private static Map<String, DataSource> _dataSources;
109
110 }