01: /*
02: * Copyright 2004-2006 the original author or authors.
03: *
04: * Licensed under the Apache License, Version 2.0 (the "License");
05: * you may not use this file except in compliance with the License.
06: * You may obtain a copy of the License at
07: *
08: * http://www.apache.org/licenses/LICENSE-2.0
09: *
10: * Unless required by applicable law or agreed to in writing, software
11: * distributed under the License is distributed on an "AS IS" BASIS,
12: * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13: * See the License for the specific language governing permissions and
14: * limitations under the License.
15: */
16:
17: package org.compass.spring.device.hibernate.dep;
18:
19: import java.lang.reflect.Field;
20: import java.lang.reflect.InvocationHandler;
21: import java.lang.reflect.Proxy;
22:
23: import org.compass.gps.device.hibernate.HibernateGpsDeviceException;
24: import org.compass.gps.device.hibernate.dep.Hibernate3GpsDevice;
25: import org.hibernate.SessionFactory;
26:
27: /**
28: * A special <code>Hibernate3GpsDevice</code> that handled cases when spring
29: * proxies the <code>SessionFactory</code> (like when
30: * <code>exposeTransactionAwareSessionFactory</code> is set to
31: * <code>true</code>, which is the default from spring 1.2.X).
32: * <p>
33: * Use this hibernate gps device instead of
34: * <code>org.compass.gps.device.hibernate.dep.Hibernate3GpsDevice</code> if you
35: * are using Hibernate 3 and Spring.
36: *
37: * @author kimchy
38: */
39: public class SpringHibernate3GpsDevice extends Hibernate3GpsDevice {
40:
41: public static SessionFactory getNativeSessionFactory(
42: SessionFactory sessionFactory) {
43: if (Proxy.isProxyClass(sessionFactory.getClass())) {
44: InvocationHandler invocationHandler = Proxy
45: .getInvocationHandler(sessionFactory);
46: try {
47: Field target = invocationHandler.getClass()
48: .getDeclaredField("target");
49: target.setAccessible(true);
50: sessionFactory = (SessionFactory) target
51: .get(invocationHandler);
52: } catch (Exception e) {
53: throw new HibernateGpsDeviceException(
54: "Failed to fetch actual session factory, "
55: + "sessionFactory["
56: + sessionFactory.getClass().getName()
57: + "], "
58: + "invocationHandler["
59: + invocationHandler.getClass()
60: .getName() + "]", e);
61: }
62: }
63: return sessionFactory;
64: }
65:
66: /**
67: * Returns the actual <code>SessionFactory</code> in case it is proxied by
68: * spring.
69: */
70: protected SessionFactory doGetActualSessionFactory() {
71: return getNativeSessionFactory(super
72: .doGetActualSessionFactory());
73: }
74: }
|