1
22
23 package com.liferay.portal.spring.hibernate;
24
25 import java.lang.Object;
26 import java.lang.reflect.InvocationHandler;
27 import java.lang.reflect.InvocationTargetException;
28 import java.lang.reflect.Method;
29 import java.lang.reflect.Proxy;
30
31 import org.hibernate.HibernateException;
32 import org.hibernate.SessionFactory;
33 import org.hibernate.classic.Session;
34
35 import org.springframework.orm.hibernate3.SessionFactoryUtils;
36
37
47 public class SessionFactoryInvocationHandler implements InvocationHandler {
48
49 public SessionFactoryInvocationHandler(SessionFactory sessionFactory) {
50 _sessionFactory = sessionFactory;
51 }
52
53 public Object invoke(Object proxy, Method method, Object[] args)
54 throws Throwable {
55
56 String methodName = method.getName();
57
58 if (methodName.equals(_GET_CURRENT_SESSION)) {
59 try {
60 Session session = (Session)SessionFactoryUtils.doGetSession(
61 (SessionFactory)proxy, false);
62
63 return wrapSession(session);
64 }
65 catch (IllegalStateException ise) {
66 throw new HibernateException(ise.getMessage());
67 }
68 }
69 else if (methodName.equals(_OPEN_SESSION)) {
70 Session session = (Session)method.invoke(_sessionFactory, args);
71
72 return wrapSession(session);
73 }
74 else if (methodName.equals(_EQUALS)) {
75 if (proxy == args[0]) {
76 return Boolean.TRUE;
77 }
78 else {
79 return Boolean.FALSE;
80 }
81 }
82 else if (methodName.equals(_HASHCODE)) {
83 return new Integer(hashCode());
84 }
85
86 try {
87 return method.invoke(_sessionFactory, args);
88 }
89 catch (InvocationTargetException ite) {
90 throw ite.getTargetException();
91 }
92 }
93
94 protected Session wrapSession(Session session) {
95 if (Proxy.isProxyClass(session.getClass())) {
96 return session;
97 }
98 else {
99 return (Session)Proxy.newProxyInstance(
100 Session.class.getClassLoader(), new Class[] {Session.class},
101 new SessionInvocationHandler(session));
102 }
103 }
104
105 private static final String _EQUALS = "equals";
106
107 private static final String _GET_CURRENT_SESSION = "getCurrentSession";
108
109 private static final String _HASHCODE = "hashCode";
110
111 private static final String _OPEN_SESSION = "openSession";
112
113 private final SessionFactory _sessionFactory;
114
115 }