001    /**
002     * Copyright (c) 2000-2010 Liferay, Inc. All rights reserved.
003     *
004     * The contents of this file are subject to the terms of the Liferay Enterprise
005     * Subscription License ("License"). You may not use this file except in
006     * compliance with the License. You can obtain a copy of the License by
007     * contacting Liferay, Inc. See the License for the specific language governing
008     * permissions and limitations under the License, including but not limited to
009     * distribution rights of the Software.
010     *
011     *
012     *
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 org.hibernate.SessionFactory;
022    
023    import org.springframework.aop.TargetSource;
024    
025    /**
026     * @author Michael Young
027     */
028    public class ShardSessionFactoryTargetSource implements TargetSource {
029    
030            public SessionFactory getSessionFactory() {
031                    return _sessionFactory.get();
032            }
033    
034            public Object getTarget() throws Exception {
035                    return getSessionFactory();
036            }
037    
038            public Class<?> getTargetClass() {
039                    return _sessionFactories.get(PropsValues.SHARD_DEFAULT_NAME).getClass();
040            }
041    
042            public boolean isStatic() {
043                    return false;
044            }
045    
046            public void releaseTarget(Object target) throws Exception {
047            }
048    
049            public void setSessionFactory(String shardName) {
050                    _sessionFactory.set(_sessionFactories.get(shardName));
051            }
052    
053            public void setSessionFactories(
054                    Map<String, SessionFactory> sessionFactories) {
055    
056                    _sessionFactories = sessionFactories;
057            }
058    
059            private static ThreadLocal<SessionFactory> _sessionFactory =
060                    new ThreadLocal<SessionFactory>() {
061    
062                    protected SessionFactory initialValue() {
063                            return _sessionFactories.get(PropsValues.SHARD_DEFAULT_NAME);
064                    }
065    
066            };
067    
068            private static Map<String, SessionFactory> _sessionFactories;
069    
070    }