added call to remoting with correct check
[taxeditor.git] / eu.etaxonomy.taxeditor.cdmlib / src / main / java / org / hibernate / proxy / AbstractLazyInitializer.java
1 /*
2 * Hibernate, Relational Persistence for Idiomatic Java
3 *
4 * Copyright (c) 2008-2011, Red Hat Inc. or third-party contributors as
5 * indicated by the @author tags or express copyright attribution
6 * statements applied by the authors. All third-party contributions are
7 * distributed under license by Red Hat Inc.
8 *
9 * This copyrighted material is made available to anyone wishing to use, modify,
10 * copy, or redistribute it subject to the terms and conditions of the GNU
11 * Lesser General Public License, as published by the Free Software Foundation.
12 *
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
15 * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
16 * for more details.
17 *
18 * You should have received a copy of the GNU Lesser General Public License
19 * along with this distribution; if not, write to:
20 * Free Software Foundation, Inc.
21 * 51 Franklin Street, Fifth Floor
22 * Boston, MA 02110-1301 USA
23 */
24 package org.hibernate.proxy;
25
26 import java.io.Serializable;
27
28 import javax.naming.NamingException;
29
30 import org.hibernate.HibernateException;
31 import org.hibernate.LazyInitializationException;
32 import org.hibernate.Session;
33 import org.hibernate.SessionException;
34 import org.hibernate.TransientObjectException;
35 import org.hibernate.engine.spi.EntityKey;
36 import org.hibernate.engine.spi.SessionFactoryImplementor;
37 import org.hibernate.engine.spi.SessionImplementor;
38 import org.hibernate.internal.SessionFactoryRegistry;
39 import org.hibernate.persister.entity.EntityPersister;
40 import org.jboss.logging.Logger;
41 import org.springframework.beans.factory.annotation.Autowire;
42 import org.springframework.beans.factory.annotation.Configurable;
43 import org.springframework.stereotype.Component;
44
45 import eu.etaxonomy.cdm.api.application.ICdmApplicationConfiguration;
46 import eu.etaxonomy.cdm.api.service.ICommonService;
47 import eu.etaxonomy.cdm.model.common.CdmBase;
48
49 /**
50 * Convenience base class for lazy initialization handlers. Centralizes the basic plumbing of doing lazy
51 * initialization freeing subclasses to acts as essentially adapters to their intended entity mode and/or
52 * proxy generation strategy.
53 *
54 * @author Gavin King
55 */
56 @Component
57 @Configurable(dependencyCheck = true,autowire = Autowire.BY_TYPE)
58 public abstract class AbstractLazyInitializer implements LazyInitializer {
59 private static final Logger log = Logger.getLogger( AbstractLazyInitializer.class );
60
61 private String entityName;
62 private Serializable id;
63 private Object target;
64 private boolean initialized;
65 private boolean readOnly;
66 private boolean unwrap;
67 private transient SessionImplementor session;
68 private Boolean readOnlyBeforeAttachedToSession;
69
70 private String sessionFactoryUuid;
71 private boolean specjLazyLoad = false;
72
73 /**
74 * For serialization from the non-pojo initializers (HHH-3309)
75 */
76 protected AbstractLazyInitializer() {
77 }
78
79 /**
80 * Main constructor.
81 *
82 * @param entityName The name of the entity being proxied.
83 * @param id The identifier of the entity being proxied.
84 * @param session The session owning the proxy.
85 */
86 protected AbstractLazyInitializer(String entityName, Serializable id, SessionImplementor session) {
87 this.entityName = entityName;
88 this.id = id;
89 // initialize other fields depending on session state
90 if ( session == null ) {
91 unsetSession();
92 }
93 else {
94 setSession( session );
95 }
96 }
97
98 @Override
99 public final String getEntityName() {
100 return entityName;
101 }
102
103 @Override
104 public final Serializable getIdentifier() {
105 return id;
106 }
107
108 @Override
109 public final void setIdentifier(Serializable id) {
110 this.id = id;
111 }
112
113 @Override
114 public final boolean isUninitialized() {
115 return !initialized;
116 }
117
118 @Override
119 public final SessionImplementor getSession() {
120 return session;
121 }
122
123 @Override
124 public final void setSession(SessionImplementor s) throws HibernateException {
125 if ( s != session ) {
126 // check for s == null first, since it is least expensive
127 if ( s == null ) {
128 unsetSession();
129 }
130 else if ( isConnectedToSession() ) {
131 //TODO: perhaps this should be some other RuntimeException...
132 throw new HibernateException( "illegally attempted to associate a proxy with two open Sessions" );
133 }
134 else {
135 // s != null
136 session = s;
137 if ( readOnlyBeforeAttachedToSession == null ) {
138 // use the default read-only/modifiable setting
139 final EntityPersister persister = s.getFactory().getEntityPersister( entityName );
140 setReadOnly( s.getPersistenceContext().isDefaultReadOnly() || !persister.isMutable() );
141 }
142 else {
143 // use the read-only/modifiable setting indicated during deserialization
144 setReadOnly( readOnlyBeforeAttachedToSession.booleanValue() );
145 readOnlyBeforeAttachedToSession = null;
146 }
147 }
148 }
149 }
150
151 private static EntityKey generateEntityKeyOrNull(Serializable id, SessionImplementor s, String entityName) {
152 if ( id == null || s == null || entityName == null ) {
153 return null;
154 }
155 return s.generateEntityKey( id, s.getFactory().getEntityPersister( entityName ) );
156 }
157
158 @Override
159 public final void unsetSession() {
160 prepareForPossibleSpecialSpecjInitialization();
161 session = null;
162 readOnly = false;
163 readOnlyBeforeAttachedToSession = null;
164 }
165
166 @Override
167 public final void initialize() throws HibernateException {
168 // In remoting we are sure that session is null
169 // both when using property paths and switching off conversations
170 if(session == null) {
171 remoteInitialize();
172 }
173 if ( !initialized ) {
174 if ( specjLazyLoad ) {
175 specialSpecjInitialization();
176 }
177 else if ( session == null ) {
178 throw new LazyInitializationException( "could not initialize proxy - no Session" );
179 }
180 else if ( !session.isOpen() ) {
181 throw new LazyInitializationException( "could not initialize proxy - the owning Session was closed" );
182 }
183 else if ( !session.isConnected() ) {
184 throw new LazyInitializationException( "could not initialize proxy - the owning Session is disconnected" );
185 }
186 else {
187 target = session.immediateLoad( entityName, id );
188 initialized = true;
189 checkTargetState();
190 }
191 }
192 else {
193 checkTargetState();
194 }
195 }
196
197 protected void specialSpecjInitialization() {
198 if ( session == null ) {
199 //we have a detached collection thats set to null, reattach
200 if ( sessionFactoryUuid == null ) {
201 throw new LazyInitializationException( "could not initialize proxy - no Session" );
202 }
203 try {
204 SessionFactoryImplementor sf = (SessionFactoryImplementor)
205 SessionFactoryRegistry.INSTANCE.getSessionFactory( sessionFactoryUuid );
206 SessionImplementor session = (SessionImplementor) sf.openSession();
207
208 // TODO: On the next major release, add an
209 // 'isJTA' or 'getTransactionFactory' method to Session.
210 boolean isJTA = session.getTransactionCoordinator()
211 .getTransactionContext().getTransactionEnvironment()
212 .getTransactionFactory()
213 .compatibleWithJtaSynchronization();
214
215 if ( !isJTA ) {
216 // Explicitly handle the transactions only if we're not in
217 // a JTA environment. A lazy loading temporary session can
218 // be created even if a current session and transaction are
219 // open (ex: session.clear() was used). We must prevent
220 // multiple transactions.
221 ( ( Session) session ).beginTransaction();
222 }
223
224 try {
225 target = session.immediateLoad( entityName, id );
226 }
227 finally {
228 // make sure the just opened temp session gets closed!
229 try {
230 if ( !isJTA ) {
231 ( ( Session) session ).getTransaction().commit();
232 }
233 ( (Session) session ).close();
234 }
235 catch (Exception e) {
236 log.warn( "Unable to close temporary session used to load lazy proxy associated to no session" );
237 }
238 }
239 initialized = true;
240 checkTargetState();
241 }
242 catch (Exception e) {
243 e.printStackTrace();
244 throw new LazyInitializationException( e.getMessage() );
245 }
246 }
247 else if ( session.isOpen() && session.isConnected() ) {
248 target = session.immediateLoad( entityName, id );
249 initialized = true;
250 checkTargetState();
251 }
252 else {
253 throw new LazyInitializationException( "could not initialize proxy - Session was closed or disced" );
254 }
255 }
256
257 protected void prepareForPossibleSpecialSpecjInitialization() {
258 if ( session != null ) {
259 specjLazyLoad = session.getFactory().getSettings().isInitializeLazyStateOutsideTransactionsEnabled();
260
261 if ( specjLazyLoad && sessionFactoryUuid == null ) {
262 try {
263 sessionFactoryUuid = (String) session.getFactory().getReference().get( "uuid" ).getContent();
264 }
265 catch (NamingException e) {
266 //not much we can do if this fails...
267 }
268 }
269 }
270 }
271
272 private void checkTargetState() {
273 if ( !unwrap ) {
274 if ( target == null ) {
275 getSession().getFactory().getEntityNotFoundDelegate().handleEntityNotFound( entityName, id );
276 }
277 }
278 }
279
280 /**
281 * Getter for property 'connectedToSession'.
282 *
283 * @return Value for property 'connectedToSession'.
284 */
285 protected final boolean isConnectedToSession() {
286 return getProxyOrNull() != null;
287 }
288
289 private Object getProxyOrNull() {
290 final EntityKey entityKey = generateEntityKeyOrNull( getIdentifier(), session, getEntityName() );
291 if ( entityKey != null && session != null && session.isOpen() ) {
292 return session.getPersistenceContext().getProxy( entityKey );
293 }
294 return null;
295 }
296
297 @Override
298 public final Object getImplementation() {
299 initialize();
300 return target;
301 }
302
303 @Override
304 public final void setImplementation(Object target) {
305 this.target = target;
306 initialized = true;
307 }
308
309 @Override
310 public final Object getImplementation(SessionImplementor s) throws HibernateException {
311 final EntityKey entityKey = generateEntityKeyOrNull( getIdentifier(), s, getEntityName() );
312 return (entityKey == null ? null : s.getPersistenceContext().getEntity( entityKey ));
313 }
314
315 /**
316 * Getter for property 'target'.
317 * <p/>
318 * Same as {@link #getImplementation()} except that this method will not force initialization.
319 *
320 * @return Value for property 'target'.
321 */
322 protected final Object getTarget() {
323 return target;
324 }
325
326 @Override
327 public final boolean isReadOnlySettingAvailable() {
328 return (session != null && !session.isClosed());
329 }
330
331 private void errorIfReadOnlySettingNotAvailable() {
332 if ( session == null ) {
333 throw new TransientObjectException(
334 "Proxy is detached (i.e, session is null). The read-only/modifiable setting is only accessible when the proxy is associated with an open session."
335 );
336 }
337 if ( session.isClosed() ) {
338 throw new SessionException(
339 "Session is closed. The read-only/modifiable setting is only accessible when the proxy is associated with an open session."
340 );
341 }
342 }
343
344 @Override
345 public final boolean isReadOnly() {
346 errorIfReadOnlySettingNotAvailable();
347 return readOnly;
348 }
349
350 @Override
351 public final void setReadOnly(boolean readOnly) {
352 errorIfReadOnlySettingNotAvailable();
353 // only update if readOnly is different from current setting
354 if ( this.readOnly != readOnly ) {
355 final EntityPersister persister = session.getFactory().getEntityPersister( entityName );
356 if ( !persister.isMutable() && !readOnly ) {
357 throw new IllegalStateException( "cannot make proxies for immutable entities modifiable" );
358 }
359 this.readOnly = readOnly;
360 if ( initialized ) {
361 EntityKey key = generateEntityKeyOrNull( getIdentifier(), session, getEntityName() );
362 if ( key != null && session.getPersistenceContext().containsEntity( key ) ) {
363 session.getPersistenceContext().setReadOnly( target, readOnly );
364 }
365 }
366 }
367 }
368
369 /**
370 * Get the read-only/modifiable setting that should be put in affect when it is
371 * attached to a session.
372 * <p/>
373 * This method should only be called during serialization when read-only/modifiable setting
374 * is not available (i.e., isReadOnlySettingAvailable() == false)
375 *
376 * @return null, if the default setting should be used;
377 * true, for read-only;
378 * false, for modifiable
379 *
380 * @throws IllegalStateException if isReadOnlySettingAvailable() == true
381 */
382 protected final Boolean isReadOnlyBeforeAttachedToSession() {
383 if ( isReadOnlySettingAvailable() ) {
384 throw new IllegalStateException(
385 "Cannot call isReadOnlyBeforeAttachedToSession when isReadOnlySettingAvailable == true"
386 );
387 }
388 return readOnlyBeforeAttachedToSession;
389 }
390
391 /**
392 * Set the read-only/modifiable setting that should be put in affect when it is
393 * attached to a session.
394 * <p/>
395 * This method should only be called during deserialization, before associating
396 * the proxy with a session.
397 *
398 * @param readOnlyBeforeAttachedToSession, the read-only/modifiable setting to use when
399 * associated with a session; null indicates that the default should be used.
400 *
401 * @throws IllegalStateException if isReadOnlySettingAvailable() == true
402 */
403 /* package-private */
404 final void setReadOnlyBeforeAttachedToSession(Boolean readOnlyBeforeAttachedToSession) {
405 if ( isReadOnlySettingAvailable() ) {
406 throw new IllegalStateException(
407 "Cannot call setReadOnlyBeforeAttachedToSession when isReadOnlySettingAvailable == true"
408 );
409 }
410 this.readOnlyBeforeAttachedToSession = readOnlyBeforeAttachedToSession;
411 }
412
413 @Override
414 public boolean isUnwrap() {
415 return unwrap;
416 }
417
418 @Override
419 public void setUnwrap(boolean unwrap) {
420 this.unwrap = unwrap;
421 }
422
423 /** Below is section of code which makes remote service calls */
424
425 private static ICdmApplicationConfiguration configuration;
426
427 public static void setConfiguration(ICdmApplicationConfiguration conf) {
428 configuration = conf;
429 }
430
431
432 private void remoteInitialize() {
433
434 if(!initialized) {
435 int classid = ((Integer)getIdentifier()).intValue();
436 System.out.print("--> Remote Lazy Initializing" + getEntityName() + " with id " + classid);
437 Class clazz;
438 try {
439 clazz = (Class<? extends CdmBase>) Class.forName(getEntityName());
440 } catch (ClassNotFoundException e) {
441 throw new HibernateException("Class for " + getEntityName() + " not found", e);
442 }
443 if(configuration == null) {
444 throw new HibernateException("CdmApplicationRemoteConfiguration not initialized (null)");
445 }
446 ICommonService commonService = configuration.getCommonService();
447 if(commonService == null) {
448 throw new HibernateException("commonService not initialized (null)");
449 }
450
451 CdmBase cdmBase = CdmBase.deproxy(commonService.find(clazz,classid),clazz);
452 setImplementation(cdmBase);
453 System.out.println("....Done");
454 }
455 }
456
457
458 }