001
014
015 package com.liferay.portal.jcr;
016
017 import com.liferay.portal.kernel.bean.PortalBeanLocatorUtil;
018 import com.liferay.portal.kernel.util.AutoResetThreadLocal;
019 import com.liferay.portal.kernel.util.PortalClassLoaderUtil;
020 import com.liferay.portal.kernel.util.ProxyUtil;
021 import com.liferay.portal.util.PropsValues;
022
023 import java.io.Closeable;
024 import java.io.IOException;
025
026 import java.util.HashMap;
027 import java.util.Map;
028
029 import javax.jcr.RepositoryException;
030 import javax.jcr.Session;
031
032
035 public class JCRFactoryUtil {
036
037 public static void closeSession(Session session) {
038 if (session != null) {
039 session.logout();
040 }
041 }
042
043 public static Session createSession() throws RepositoryException {
044 return createSession(null);
045 }
046
047 public static Session createSession(String workspaceName)
048 throws RepositoryException {
049
050 if (workspaceName == null) {
051 workspaceName = JCRFactory.WORKSPACE_NAME;
052 }
053
054 if (!PropsValues.JCR_WRAP_SESSION) {
055 return getJCRFactory().createSession(workspaceName);
056 }
057
058 CloseableSessionMap closableSessionMap = _closeableSessionMaps.get();
059
060 if (!closableSessionMap.containsKey(workspaceName)) {
061 Session session = getJCRFactory().createSession(workspaceName);
062
063 Object sessionProxy = ProxyUtil.newProxyInstance(
064 PortalClassLoaderUtil.getClassLoader(),
065 new Class<?>[] {Closeable.class, Map.class, Session.class},
066 new JCRSessionInvocationHandler(session));
067
068 closableSessionMap.put(workspaceName, (Closeable)sessionProxy);
069 }
070
071 return (Session)closableSessionMap.get(workspaceName);
072 }
073
074 public static JCRFactory getJCRFactory() {
075 if (_jcrFactory == null) {
076 _jcrFactory = (JCRFactory)PortalBeanLocatorUtil.locate(
077 JCRFactory.class.getName());
078 }
079
080 return _jcrFactory;
081 }
082
083 public static void initialize() throws RepositoryException {
084 getJCRFactory().initialize();
085 }
086
087 public static void prepare() throws RepositoryException {
088 getJCRFactory().prepare();
089 }
090
091 public static void shutdown() {
092 getJCRFactory().shutdown();
093 }
094
095 private static ThreadLocal<CloseableSessionMap> _closeableSessionMaps =
096 new AutoResetThreadLocal<CloseableSessionMap>(
097 JCRFactoryUtil.class + "._session", new CloseableSessionMap());
098 private static JCRFactory _jcrFactory;
099
100 private static class CloseableSessionMap extends HashMap<String, Closeable>
101 implements Closeable {
102
103 public void close() throws IOException {
104 for (Closeable closeableSession : values()) {
105 closeableSession.close();
106 }
107 }
108
109 }
110
111 }