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 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    }