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