001    /**
002     * Copyright (c) 2000-2010 Liferay, Inc. All rights reserved.
003     *
004     * This library is free software; you can redistribute it and/or modify it under
005     * the terms of the GNU Lesser General Public License as published by the Free
006     * Software Foundation; either version 2.1 of the License, or (at your option)
007     * any later version.
008     *
009     * This library is distributed in the hope that it will be useful, but WITHOUT
010     * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
011     * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
012     * details.
013     */
014    
015    package com.liferay.portal.dao.shard;
016    
017    import com.liferay.portal.util.PropsValues;
018    
019    import java.util.Map;
020    
021    import javax.sql.DataSource;
022    
023    import org.springframework.aop.TargetSource;
024    
025    /**
026     * @author Michael Young
027     */
028    public class ShardDataSourceTargetSource implements TargetSource {
029    
030            public DataSource getDataSource() {
031                    return _dataSource.get();
032            }
033    
034            public Object getTarget() throws Exception {
035                    return getDataSource();
036            }
037    
038            public Class<DataSource> getTargetClass() {
039                    return DataSource.class;
040            }
041    
042            public boolean isStatic() {
043                    return false;
044            }
045    
046            public void releaseTarget(Object target) throws Exception {
047            }
048    
049            public void setDataSource(String shardName) {
050                    _dataSource.set(_dataSources.get(shardName));
051            }
052    
053            public void setDataSources(Map<String, DataSource> dataSources) {
054                    _dataSources = dataSources;
055            }
056    
057            private static ThreadLocal<DataSource> _dataSource =
058                    new ThreadLocal<DataSource>() {
059    
060                    protected DataSource initialValue() {
061                            return _dataSources.get(PropsValues.SHARD_DEFAULT_NAME);
062                    }
063    
064            };
065    
066            private static Map<String, DataSource> _dataSources;
067    
068    }