public boolean onFlushDirty(Object entity, Serializable id, Object[] currentState, Object[] previuosState,String[] propertyNames, Type[] types) throws CallbackException { boolean bool = Boolean.FALSE; if(null!=interceptors && !interceptors.isEmpty()){ Iterator it = interceptors.iterator(); while(it.hasNext()){ Interceptor interceptor = (Interceptor) it.next(); boolean temp=false; if(interceptor!=null){ temp= interceptor.onFlushDirty(entity, id, currentState, previuosState, propertyNames, types); if(temp) bool = true; } } } return bool; }
/** * Return the current Hibernate entity interceptor, or {@code null} if none. * Resolves an entity interceptor bean name via the bean factory, * if necessary. * @throws IllegalStateException if bean name specified but no bean factory set * @throws BeansException if bean name resolution via the bean factory failed * @see #setEntityInterceptor * @see #setEntityInterceptorBeanName * @see #setBeanFactory */ public Interceptor getEntityInterceptor() throws IllegalStateException, BeansException { if (this.entityInterceptor instanceof Interceptor) { return (Interceptor) entityInterceptor; } else if (this.entityInterceptor instanceof String) { if (this.beanFactory == null) { throw new IllegalStateException("Cannot get entity interceptor via bean name if no bean factory set"); } String beanName = (String) this.entityInterceptor; return this.beanFactory.getBean(beanName, Interceptor.class); } else { return null; } }
/** * Note method sets user session information in the database and opens a connection for this. */ public Session openSession(Connection connection, Interceptor interceptor) { // NOTE: workaround for this issue: // http://opensource.atlassian.com/projects/hibernate/browse/HHH-3529 final Session session = delegateSessionFactory.openSession(connection, interceptor); final ClassLoader currentLoader = Thread.currentThread().getContextClassLoader(); try { Thread.currentThread().setContextClassLoader(BorrowedConnectionProxy.class.getClassLoader()); Connection conn = ((SessionImplementor) session).connection(); SessionInfo.initDB(conn, OBPropertiesProvider.getInstance().getOpenbravoProperties() .getProperty("bbdd.rdbms")); SessionInfo.setDBSessionInfo(conn); } finally { Thread.currentThread().setContextClassLoader(currentLoader); } return session; }
/** * Note method sets user session information in the database and opens a connection for this. */ public Session openSession(Interceptor interceptor) throws HibernateException { // NOTE: workaround for this issue: // http://opensource.atlassian.com/projects/hibernate/browse/HHH-3529 final Session session = delegateSessionFactory.openSession(interceptor); final ClassLoader currentLoader = Thread.currentThread().getContextClassLoader(); try { Thread.currentThread().setContextClassLoader(BorrowedConnectionProxy.class.getClassLoader()); Connection conn = ((SessionImplementor) session).connection(); SessionInfo.initDB(conn, OBPropertiesProvider.getInstance().getOpenbravoProperties() .getProperty("bbdd.rdbms")); SessionInfo.setDBSessionInfo(conn); } finally { Thread.currentThread().setContextClassLoader(currentLoader); } return session; }
public JDBCContext(Context owner, Connection connection, Interceptor interceptor) { this.owner = owner; this.connectionManager = new ConnectionManager( owner.getFactory(), this, owner.getConnectionReleaseMode(), connection, interceptor ); final boolean registerSynchronization = owner.isAutoCloseSessionEnabled() || owner.isFlushBeforeCompletionEnabled() || owner.getConnectionReleaseMode() == ConnectionReleaseMode.AFTER_TRANSACTION; if ( registerSynchronization ) { registerSynchronizationIfPossible(); } }
/** * Custom deserialization routine used during deserialization of a * Session/PersistenceContext for increased performance. * * @param ois The stream from which to read the entry. * @throws IOException */ public static JDBCContext deserialize( ObjectInputStream ois, Context context, Interceptor interceptor) throws IOException { JDBCContext jdbcContext = new JDBCContext(); jdbcContext.owner = context; jdbcContext.connectionManager = ConnectionManager.deserialize( ois, context.getFactory(), interceptor, context.getConnectionReleaseMode(), jdbcContext ); return jdbcContext; }
/** * Constructs a ConnectionManager. * <p/> * This is the form used internally. * * @param factory The SessionFactory. * @param callback An observer for internal state change. * @param releaseMode The mode by which to release JDBC connections. * @param connection An externally supplied connection. */ public ConnectionManager( SessionFactoryImplementor factory, Callback callback, ConnectionReleaseMode releaseMode, Connection connection, Interceptor interceptor) { this.factory = factory; this.callback = callback; this.interceptor = interceptor; this.batcher = factory.getSettings().getBatcherFactory().createBatcher( this, interceptor ); this.connection = connection; wasConnectionSupplied = ( connection != null ); this.releaseMode = wasConnectionSupplied ? ConnectionReleaseMode.ON_CLOSE : releaseMode; }
/** * Private constructor used exclusively from custom serialization */ private ConnectionManager( SessionFactoryImplementor factory, Callback callback, ConnectionReleaseMode releaseMode, Interceptor interceptor, boolean wasConnectionSupplied, boolean isClosed) { this.factory = factory; this.callback = callback; this.interceptor = interceptor; this.batcher = factory.getSettings().getBatcherFactory().createBatcher( this, interceptor ); this.wasConnectionSupplied = wasConnectionSupplied; this.isClosed = isClosed; this.releaseMode = wasConnectionSupplied ? ConnectionReleaseMode.ON_CLOSE : releaseMode; }
private SessionImpl openSession( Connection connection, boolean autoClose, long timestamp, Interceptor sessionLocalInterceptor ) { return new SessionImpl( connection, this, autoClose, timestamp, sessionLocalInterceptor == null ? interceptor : sessionLocalInterceptor, settings.getDefaultEntityMode(), settings.isFlushBeforeCompletionEnabled(), settings.isAutoCloseSessionEnabled(), settings.getConnectionReleaseMode() ); }
@Override protected Interceptor interceptor() { return new EmptyInterceptor() { private Long startNanos; @Override public void preFlush(Iterator entities) { startNanos = System.nanoTime(); } @Override public boolean onFlushDirty(Object entity, Serializable id, Object[] currentState, Object[] previousState, String[] propertyNames, Type[] types) { if (enableMetrics) { timer.update(System.nanoTime() - startNanos, TimeUnit.NANOSECONDS); } return false; } }; }
@Test public void testEntityInterceptor() throws Exception { List<Interceptor> interceptors = getValue(entityInterceptorService, "interceptors"); assertEquals(2, interceptors.size()); boolean containsAuditTrailInterceptor = false; boolean containsIdBucketInterceptor = false; for (Interceptor interceptor : interceptors) { containsAuditTrailInterceptor = containsAuditTrailInterceptor || interceptor.getClass().equals(AuditTrailInterceptor.class); containsIdBucketInterceptor = containsIdBucketInterceptor || interceptor.getClass().equals(IdBucketInterceptor.class); } assertTrue(containsAuditTrailInterceptor); assertTrue(containsIdBucketInterceptor); }
private SessionFactory newSessionFactory() { Properties properties = getProperties(); Configuration configuration = new Configuration().addProperties(properties); for(Class<?> entityClass : entities()) { configuration.addAnnotatedClass(entityClass); } String[] packages = packages(); if(packages != null) { for(String scannedPackage : packages) { configuration.addPackage(scannedPackage); } } Interceptor interceptor = interceptor(); if(interceptor != null) { configuration.setInterceptor(interceptor); } return configuration.buildSessionFactory( new StandardServiceRegistryBuilder() .applySettings(properties) .build() ); }
@Override public boolean onFlushDirty(Object entity, Serializable id, Object[] currentState, Object[] previousState, String[] propertyNames, Type[] types) { if (!isExists()) return false; if (isTraceEnabled) log.trace("인터셉터의 onFlush 메소드를 멀티캐스트로 수행합니다."); for (final Interceptor interceptor : interceptors) { interceptor.onFlushDirty(entity, id, currentState, previousState, propertyNames, types); } return false; }
@Override public boolean onSave(Object entity, Serializable id, Object[] state, String[] propertyNames, Type[] types) { if (!isExists()) return false; if (isTraceEnabled) log.trace("인터셉터의 onSave 메소드를 멀티캐스트로 수행합니다."); List<FutureTask<Boolean>> tasks = Lists.newLinkedList(); for (final Interceptor interceptor : interceptors) { interceptor.onSave(entity, id, state, propertyNames, types); } return false; }
/** * Constructor to build the hibernate helper. * @param namingStrategy the name strategy, if one is needed, null otherwise. * @param interceptor the interceptor, if one is needed, null otherwise. */ public HibernateHelper(NamingStrategy namingStrategy, Interceptor interceptor) { try { configuration = new AnnotationConfiguration(); initializeConfig(namingStrategy, interceptor); configuration = configuration.configure(); // We call buildSessionFactory twice, because it appears that the annotated classes are // not 'activated' in the config until we build. The filters required the classes to // be present, so we throw away the first factory and use the second. If this is // removed, you'll likely see a NoClassDefFoundError in the unit tests configuration.buildSessionFactory(); sessionFactory = configuration.buildSessionFactory(); } catch (HibernateException e) { // LOG.error(e.getMessage(), e); // throw new ExceptionInInitializerError(e); LOG.warn("Failed to initialize HibernateHelper using hibernate.cfg.xml. " + "This is expected behavior during unit testing." , e); e.printStackTrace(); } }
/** * Get a new Hibernate Session from the given SessionFactory. * Will return a new Session even if there already is a pre-bound * Session for the given SessionFactory. * <p>Within a transaction, this method will create a new Session * that shares the transaction's JDBC Connection. More specifically, * it will use the same JDBC Connection as the pre-bound Hibernate Session. * @param sessionFactory Hibernate SessionFactory to create the session with * @param entityInterceptor Hibernate entity interceptor, or {@code null} if none * @return the new Session */ @SuppressWarnings("deprecation") public static Session getNewSession(SessionFactory sessionFactory, Interceptor entityInterceptor) { Assert.notNull(sessionFactory, "No SessionFactory specified"); try { SessionHolder sessionHolder = (SessionHolder) TransactionSynchronizationManager.getResource(sessionFactory); if (sessionHolder != null && !sessionHolder.isEmpty()) { if (entityInterceptor != null) { return sessionFactory.openSession(sessionHolder.getAnySession().connection(), entityInterceptor); } else { return sessionFactory.openSession(sessionHolder.getAnySession().connection()); } } else { if (entityInterceptor != null) { return sessionFactory.openSession(entityInterceptor); } else { return sessionFactory.openSession(); } } } catch (HibernateException ex) { throw new DataAccessResourceFailureException("Could not open Hibernate Session", ex); } }
/** * Used by JDK serialization... * * @param ois The input stream from which we are being read... * @throws IOException Indicates a general IO stream exception * @throws ClassNotFoundException Indicates a class resolution issue */ private void readObject(ObjectInputStream ois) throws IOException, ClassNotFoundException { LOG.trace( "Deserializing session" ); ois.defaultReadObject(); entityNameResolver = new CoordinatingEntityNameResolver(); connectionReleaseMode = ConnectionReleaseMode.parse( ( String ) ois.readObject() ); autoClear = ois.readBoolean(); autoJoinTransactions = ois.readBoolean(); flushMode = FlushMode.valueOf( ( String ) ois.readObject() ); cacheMode = CacheMode.valueOf( ( String ) ois.readObject() ); flushBeforeCompletionEnabled = ois.readBoolean(); autoCloseSessionEnabled = ois.readBoolean(); interceptor = ( Interceptor ) ois.readObject(); factory = SessionFactoryImpl.deserialize( ois ); sessionOwner = ( SessionOwner ) ois.readObject(); transactionCoordinator = TransactionCoordinatorImpl.deserialize( ois, this ); persistenceContext = StatefulPersistenceContext.deserialize( ois, this ); actionQueue = ActionQueue.deserialize( ois, this ); loadQueryInfluencers = (LoadQueryInfluencers) ois.readObject(); // LoadQueryInfluencers.getEnabledFilters() tries to validate each enabled // filter, which will fail when called before FilterImpl.afterDeserialize( factory ); // Instead lookup the filter by name and then call FilterImpl.afterDeserialize( factory ). for ( String filterName : loadQueryInfluencers.getEnabledFilterNames() ) { ((FilterImpl) loadQueryInfluencers.getEnabledFilter( filterName )).afterDeserialize( factory ); } }
/** * Assemble the previously disassembled state represented by this entry into the given entity instance. * * Additionally manages the PreLoadEvent callbacks. * * @param instance The entity instance * @param id The entity identifier * @param persister The entity persister * @param interceptor (currently unused) * @param session The session * * @return The assembled state * * @throws HibernateException Indicates a problem performing assembly or calling the PreLoadEventListeners. * * @see org.hibernate.type.Type#assemble * @see org.hibernate.type.Type#disassemble */ public Object[] assemble( final Object instance, final Serializable id, final EntityPersister persister, final Interceptor interceptor, final EventSource session) throws HibernateException { if ( !persister.getEntityName().equals( subclass ) ) { throw new AssertionFailure( "Tried to assemble a different subclass instance" ); } //assembled state gets put in a new array (we read from cache by value!) final Object[] assembledProps = TypeHelper.assemble( disassembledState, persister.getPropertyTypes(), session, instance ); //persister.setIdentifier(instance, id); //before calling interceptor, for consistency with normal load //TODO: reuse the PreLoadEvent final PreLoadEvent preLoadEvent = new PreLoadEvent( session ) .setEntity( instance ) .setState( assembledProps ) .setId( id ) .setPersister( persister ); final EventListenerGroup<PreLoadEventListener> listenerGroup = session .getFactory() .getServiceRegistry() .getService( EventListenerRegistry.class ) .getEventListenerGroup( EventType.PRE_LOAD ); for ( PreLoadEventListener listener : listenerGroup.listeners() ) { listener.onPreLoad( preLoadEvent ); } persister.setPropertyValues( instance, assembledProps ); return assembledProps; }
@Inject public DefaultPersistManager(PhysicalNamingStrategy physicalNamingStrategy, HibernateProperties properties, Interceptor interceptor, IdManager idManager, Dao dao, EntityValidator validator) { this.physicalNamingStrategy = physicalNamingStrategy; this.properties = properties; this.interceptor = interceptor; this.idManager = idManager; this.dao = dao; this.validator = validator; serviceRegistry = new StandardServiceRegistryBuilder().applySettings(properties).build(); }
@Inject public UpgradeCommand(PhysicalNamingStrategy physicalNamingStrategy, HibernateProperties properties, Interceptor interceptor, IdManager idManager, Dao dao, EntityValidator validator, PluginManager pluginManager) { super(physicalNamingStrategy, properties, interceptor, idManager, dao, validator); appName = pluginManager.getProduct().getName(); }
@Inject public ResetAdminPasswordCommand(PhysicalNamingStrategy physicalNamingStrategy, HibernateProperties properties, Interceptor interceptor, IdManager idManager, Dao dao, EntityValidator validator, UserManager userManager, PasswordService passwordService) { super(physicalNamingStrategy, properties, interceptor, idManager, dao, validator); this.userManager = userManager; this.passwordService = passwordService; }
private SessionFactory newSessionFactory() { Properties properties = properties(); Configuration configuration = new Configuration().addProperties(properties); for (Class<?> entityClass : entities()) { configuration.addAnnotatedClass(entityClass); } String[] packages = packages(); if (packages != null) { for (String scannedPackage : packages) { configuration.addPackage(scannedPackage); } } String[] resources = resources(); if (resources != null) { for (String resource : resources) { configuration.addResource(resource); } } Interceptor interceptor = interceptor(); if (interceptor != null) { configuration.setInterceptor(interceptor); } configuration.setProperties(properties); return configuration.buildSessionFactory( new BootstrapServiceRegistryBuilder() .build() ); }
@Override public boolean onFlushDirty(Object entity, Serializable id, Object[] currentState, Object[] previousState, String[] propertyNames, Type[] types) throws CallbackException { boolean modified = false; for (Interceptor interceptor : chain) { modified |= interceptor.onFlushDirty(entity, id, currentState, previousState, propertyNames, types); } return modified; }
@Override public boolean onSave(Object entity, Serializable id, Object[] state, String[] propertyNames, Type[] types) throws CallbackException { boolean modified = false; for (Interceptor interceptor : chain) { modified |= interceptor.onSave(entity, id, state, propertyNames, types); } return modified; }
@Test @SuppressWarnings("serial") public void testLocalSessionFactoryBeanWithEntityInterceptor() throws Exception { LocalSessionFactoryBean sfb = new LocalSessionFactoryBean() { @Override protected Configuration newConfiguration() { return new Configuration() { @Override public Configuration setInterceptor(Interceptor interceptor) { throw new IllegalArgumentException(interceptor.toString()); } }; } }; sfb.setMappingResources(new String[0]); sfb.setDataSource(new DriverManagerDataSource()); Interceptor entityInterceptor = mock(Interceptor.class); sfb.setEntityInterceptor(entityInterceptor); try { sfb.afterPropertiesSet(); fail("Should have thrown IllegalArgumentException"); } catch (IllegalArgumentException ex) { // expected assertTrue("Correct exception", ex.getMessage().equals(entityInterceptor.toString())); } }
@Test public void testTransactionCommitWithEntityInterceptor() throws Exception { Interceptor entityInterceptor = mock(Interceptor.class); Connection con = mock(Connection.class); final SessionFactory sf = mock(SessionFactory.class); ImplementingSession session = mock(ImplementingSession.class); SessionBuilder options = mock(SessionBuilder.class); Transaction tx = mock(Transaction.class); given(sf.withOptions()).willReturn(options); given(options.interceptor(entityInterceptor)).willReturn(options); given(options.openSession()).willReturn(session); given(session.beginTransaction()).willReturn(tx); given(session.isOpen()).willReturn(true); given(session.isConnected()).willReturn(true); given(session.connection()).willReturn(con); HibernateTransactionManager tm = new HibernateTransactionManager(sf); tm.setEntityInterceptor(entityInterceptor); tm.setAllowResultAccessAfterCompletion(true); TransactionTemplate tt = new TransactionTemplate(tm); tt.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); assertTrue("Hasn't thread session", !TransactionSynchronizationManager.hasResource(sf)); assertTrue("JTA synchronizations not active", !TransactionSynchronizationManager.isSynchronizationActive()); tt.execute(new TransactionCallbackWithoutResult() { @Override public void doInTransactionWithoutResult(TransactionStatus status) { assertTrue("Has thread session", TransactionSynchronizationManager.hasResource(sf)); } }); assertTrue("Hasn't thread session", !TransactionSynchronizationManager.hasResource(sf)); assertTrue("JTA synchronizations not active", !TransactionSynchronizationManager.isSynchronizationActive()); verify(session).close(); verify(tx).commit(); }
/** * Used during deserialization. * * @param ois The stream from which we are being read. * @throws IOException Indicates an I/O error reading the stream * @throws ClassNotFoundException Indicates resource class resolution. */ private void readObject(ObjectInputStream ois) throws IOException, ClassNotFoundException { factory = (SessionFactoryImplementor) ois.readObject(); interceptor = (Interceptor) ois.readObject(); ois.defaultReadObject(); this.batcher = factory.getSettings().getBatcherFactory().createBatcher( this, interceptor ); }
public static ConnectionManager deserialize( ObjectInputStream ois, SessionFactoryImplementor factory, Interceptor interceptor, ConnectionReleaseMode connectionReleaseMode, JDBCContext jdbcContext) throws IOException { return new ConnectionManager( factory, jdbcContext, connectionReleaseMode, interceptor, ois.readBoolean(), ois.readBoolean() ); }
public Object[] assemble( final Object instance, final Serializable id, final EntityPersister persister, final Interceptor interceptor, final EventSource session) throws HibernateException { if ( !persister.getEntityName().equals(subclass) ) { throw new AssertionFailure("Tried to assemble a different subclass instance"); } return assemble(disassembledState, instance, id, persister, interceptor, session); }
private static Object[] assemble( final Serializable[] values, final Object result, final Serializable id, final EntityPersister persister, final Interceptor interceptor, final EventSource session) throws HibernateException { //assembled state gets put in a new array (we read from cache by value!) Object[] assembledProps = TypeFactory.assemble( values, persister.getPropertyTypes(), session, result ); //persister.setIdentifier(result, id); //before calling interceptor, for consistency with normal load //TODO: reuse the PreLoadEvent PreLoadEvent preLoadEvent = new PreLoadEvent( session ) .setEntity(result) .setState(assembledProps) .setId(id) .setPersister(persister); PreLoadEventListener[] listeners = session.getListeners().getPreLoadEventListeners(); for ( int i = 0; i < listeners.length; i++ ) { listeners[i].onPreLoad(preLoadEvent); } persister.setPropertyValues( result, assembledProps, session.getEntityMode() ); return assembledProps; }
/** * Constructor used for openSession(...) processing, as well as construction * of sessions for getCurrentSession(). * * @param connection The user-supplied connection to use for this session. * @param factory The factory from which this session was obtained * @param autoclose NOT USED * @param timestamp The timestamp for this session * @param interceptor The interceptor to be applied to this session * @param entityMode The entity-mode for this session * @param flushBeforeCompletionEnabled Should we auto flush before completion of transaction * @param autoCloseSessionEnabled Should we auto close after completion of transaction * @param connectionReleaseMode The mode by which we should release JDBC connections. */ SessionImpl( final Connection connection, final SessionFactoryImpl factory, final boolean autoclose, final long timestamp, final Interceptor interceptor, final EntityMode entityMode, final boolean flushBeforeCompletionEnabled, final boolean autoCloseSessionEnabled, final ConnectionReleaseMode connectionReleaseMode) { super( factory ); this.rootSession = null; this.timestamp = timestamp; this.entityMode = entityMode; this.interceptor = interceptor; this.listeners = factory.getEventListeners(); this.actionQueue = new ActionQueue( this ); this.persistenceContext = new StatefulPersistenceContext( this ); this.flushBeforeCompletionEnabled = flushBeforeCompletionEnabled; this.autoCloseSessionEnabled = autoCloseSessionEnabled; this.connectionReleaseMode = connectionReleaseMode; this.jdbcContext = new JDBCContext( this, connection, interceptor ); if ( factory.getStatistics().isStatisticsEnabled() ) { factory.getStatisticsImplementor().openSession(); } if ( log.isDebugEnabled() ) { log.debug( "opened session at timestamp: " + timestamp ); } }