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 @Override
046 public Object getTarget() throws Exception {
047 return getDataSource();
048 }
049
050 @Override
051 public Class<DataSource> getTargetClass() {
052 return DataSource.class;
053 }
054
055 @Override
056 public boolean isStatic() {
057 return false;
058 }
059
060 @Override
061 public void releaseTarget(Object target) throws Exception {
062 }
063
064 public void resetDataSource() {
065 DataSource dataSource = _dataSources.get(
066 PropsValues.SHARD_DEFAULT_NAME);
067
068 _dataSource.set(dataSource);
069 }
070
071 public void setDataSource(String shardName) {
072 DataSource dataSource = _dataSources.get(shardName);
073
074 _dataSource.set(dataSource);
075 }
076
077 public void setDataSources(Map<String, DataSource> dataSources) {
078 _dataSources = dataSources;
079
080 Set<String> shardNames = _dataSources.keySet();
081
082 _availableShardNames = shardNames.toArray(
083 new String[shardNames.size()]);
084
085 if (_log.isInfoEnabled()) {
086 _log.info(
087 "Sharding configured with " + _availableShardNames.length +
088 " data sources");
089 }
090 }
091
092 private static Log _log = LogFactoryUtil.getLog(
093 ShardDataSourceTargetSource.class);
094
095 private static String[] _availableShardNames;
096
097 private static ThreadLocal<DataSource> _dataSource =
098 new ThreadLocal<DataSource>() {
099
100 @Override
101 protected DataSource initialValue() {
102 return _dataSources.get(PropsValues.SHARD_DEFAULT_NAME);
103 }
104
105 };
106
107 private static Map<String, DataSource> _dataSources;
108
109 }