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