Java Code Examples for org.hibernate.event.service.spi.EventListenerRegistry

The following are top voted examples for showing how to use org.hibernate.event.service.spi.EventListenerRegistry. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: lams   File: TwoPhaseLoad.java   View source code 6 votes vote down vote up
/**
 * PostLoad cannot occur during initializeEntity, as that call occurs *before*
 * the Set collections are added to the persistence context by Loader.
 * Without the split, LazyInitializationExceptions can occur in the Entity's
 * postLoad if it acts upon the collection.
 *
 * HHH-6043
 * 
 * @param entity The entity
 * @param session The Session
 * @param postLoadEvent The (re-used) post-load event
 */
public static void postLoad(
		final Object entity,
		final SessionImplementor session,
		final PostLoadEvent postLoadEvent) {
	
	if ( session.isEventSource() ) {
		final PersistenceContext persistenceContext
				= session.getPersistenceContext();
		final EntityEntry entityEntry = persistenceContext.getEntry( entity );

		postLoadEvent.setEntity( entity ).setId( entityEntry.getId() ).setPersister( entityEntry.getPersister() );

		final EventListenerGroup<PostLoadEventListener> listenerGroup = session.getFactory()
						.getServiceRegistry()
						.getService( EventListenerRegistry.class )
						.getEventListenerGroup( EventType.POST_LOAD );
		for ( PostLoadEventListener listener : listenerGroup.listeners() ) {
			listener.onPostLoad( postLoadEvent );
		}
	}
}
 
Example 2
Project: spring-data-rest-webhook   File: EventListenerRegistryAdapter.java   View source code 6 votes vote down vote up
@PostConstruct
public void registerListeners() {
    // TODO: This method of getting a reference to the SessionFactory (and thereforce the ServiceRegistry) is Deprecated. Find out the right Hibernate 5.2 way to do this.
    EventListenerRegistry registry = entityManagerFactory.getSessionFactory().getServiceRegistry().getService(EventListenerRegistry.class);
    if (preInsertEventListeners != null) {
        registry.appendListeners(EventType.PRE_INSERT, preInsertEventListeners.toArray(new PreInsertEventListener[preInsertEventListeners.size()]));
    }
    if (postInsertEventListeners != null) {
        registry.appendListeners(EventType.POST_INSERT, postInsertEventListeners.toArray(new PostInsertEventListener[postInsertEventListeners.size()]));
    }
    if (preUpdateEventListeners != null) {
        registry.appendListeners(EventType.PRE_UPDATE, preUpdateEventListeners.toArray(new PreUpdateEventListener[preUpdateEventListeners.size()]));
    }
    if (postUpdateEventListeners != null) {
        registry.appendListeners(EventType.POST_UPDATE, postUpdateEventListeners.toArray(new PostUpdateEventListener[postUpdateEventListeners.size()]));
    }
    if (preDeleteEventListeners != null) {
        registry.appendListeners(EventType.PRE_DELETE, preDeleteEventListeners.toArray(new PreDeleteEventListener[preDeleteEventListeners.size()]));
    }
    if (postDeleteEventListeners != null) {
        registry.appendListeners(EventType.POST_DELETE, postDeleteEventListeners.toArray(new PostDeleteEventListener[postDeleteEventListeners.size()]));
    }
}
 
Example 3
Project: ipf-flow-manager   File: CustomEventRegistration.java   View source code 6 votes vote down vote up
@Override
public void integrate(Metadata metadata, SessionFactoryImplementor sessionFactory, SessionFactoryServiceRegistry serviceRegistry) {
    EventListenerRegistry service = serviceRegistry.getService(org.hibernate.event.service.spi.EventListenerRegistry.class);

    StandardPBEStringEncryptor encrypt = new StandardPBEStringEncryptor();
    encrypt.setPassword("test_password");
    RenderedMessageEncryptEventListener encryptListener = new RenderedMessageEncryptEventListener();
    encryptListener.setStringEncryptor(encrypt);

    RenderedMessageDecryptEventListener decryptListener = new RenderedMessageDecryptEventListener();
    decryptListener.setStringEncryptor(encrypt);

    FullTextIndexEventListener fullTextListener = new FullTextIndexEventListener();

    service.appendListeners(EventType.PRE_UPDATE, encryptListener);
    service.prependListeners(EventType.POST_UPDATE, decryptListener);
    service.appendListeners(EventType.PRE_INSERT, encryptListener);
    service.prependListeners(EventType.POST_INSERT, decryptListener);
    service.appendListeners(EventType.POST_LOAD, decryptListener);
}
 
Example 4
Project: Audit4j-Hibernate   File: Audit4jIntegrator.java   View source code 6 votes vote down vote up
public void integrate(Configuration configuration, SessionFactoryImplementor sessionFactory,
        SessionFactoryServiceRegistry serviceRegistry) {
    System.out.println("Integrating......");

    //final AuditService auditService = serviceRegistry.getService(AuditService.class);
    final AuditService auditService = new AuditServiceImpl();
    auditService.init();
    if (!auditService.isInitialized()) {
        throw new InitializationException(
                "Audit4j hibernate integration can not be initialized..");
    }

    // Register listeners..
    final EventListenerRegistry listenerRegistry = serviceRegistry
            .getService(EventListenerRegistry.class);

    listenerRegistry.appendListeners(EventType.POST_INSERT,
            new AuditPostInsertEventListenerImpl(auditService));
    listenerRegistry.appendListeners(EventType.POST_UPDATE,
            new AuditPostUpdateEventListenerImpl(auditService));
    listenerRegistry.appendListeners(EventType.POST_DELETE,
            new AuditPostDeleteEventListenerImpl(auditService));
}
 
Example 5
Project: gorm-hibernate5   File: EventListenerIntegrator.java   View source code 6 votes vote down vote up
protected <T> void appendListeners(EventListenerRegistry listenerRegistry,
                                   EventType<T> eventType, Collection<T> listeners) {

    EventListenerGroup<T> group = listenerRegistry.getEventListenerGroup(eventType);
    for (T listener : listeners) {
        if (listener != null) {
            if(shouldOverrideListeners(eventType, listener)) {
                // since ClosureEventTriggeringInterceptor extends DefaultSaveOrUpdateEventListener we want to override instead of append the listener here
                // to avoid there being 2 implementations which would impact performance too
                group.clear();
                group.appendListener(listener);
            }
            else {
                group.appendListener(listener);
            }
        }
    }
}
 
Example 6
Project: gorm-hibernate5   File: EventListenerIntegrator.java   View source code 6 votes vote down vote up
@SuppressWarnings("unchecked")
protected <T> void appendListeners(final EventListenerRegistry listenerRegistry,
                                   final EventType<T> eventType, final Map<String, Object> listeners) {

    Object listener = listeners.get(eventType.eventName());
    if (listener != null) {
        if(shouldOverrideListeners(eventType, listener)) {
            // since ClosureEventTriggeringInterceptor extends DefaultSaveOrUpdateEventListener we want to override instead of append the listener here
            // to avoid there being 2 implementations which would impact performance too
            listenerRegistry.setListeners(eventType, (T) listener);
        }
        else {
            listenerRegistry.appendListeners(eventType, (T)listener);
        }
    }
}
 
Example 7
Project: windup-rulesets   File: MyIntegrator.java   View source code 6 votes vote down vote up
@Override
public void integrate(org.hibernate.cfg.Configuration configuration,
            org.hibernate.engine.spi.SessionFactoryImplementor sessionFactory,
            org.hibernate.service.spi.SessionFactoryServiceRegistry serviceRegistry) 
{
        
    
    final EventListenerRegistry eventRegistry =
        serviceRegistry.getService(EventListenerRegistry.class);

    eventRegistry.prependListeners(EventType.POST_COMMIT_INSERT, listener);
    
    final AuditConfiguration enversConfiguration = AuditConfiguration.getFor( configuration );
    AuditStrategy auditStrategy = enversConfiguration.getAuditStrategy();

    if (enversConfiguration.getEntCfg().hasAuditedEntities()) {
        listenerRegistry.appendListeners( EventType.POST_DELETE, new EnversPostDeleteEventListenerImpl( enversConfiguration ) );
        listenerRegistry.appendListeners( EventType.POST_INSERT, new EnversPostInsertEventListenerImpl( enversConfiguration ) );
        listenerRegistry.appendListeners( EventType.POST_UPDATE, new EnversPostUpdateEventListenerImpl( enversConfiguration ) );
        listenerRegistry.appendListeners( EventType.POST_COLLECTION_RECREATE, new EnversPostCollectionRecreateEventListenerImpl( enversConfiguration ) );
        listenerRegistry.appendListeners( EventType.PRE_COLLECTION_REMOVE, new EnversPreCollectionRemoveEventListenerImpl( enversConfiguration ) );
        listenerRegistry.appendListeners( EventType.PRE_COLLECTION_UPDATE, new EnversPreCollectionUpdateEventListenerImpl( enversConfiguration ) );
    }
    
}
 
Example 8
Project: debop4j   File: HibernateTool.java   View source code 6 votes vote down vote up
/**
 * Register event listener.
 *
 * @param sessionFactory the session factory
 * @param listener       the listener
 * @param eventTypes     the event types
 */
@SuppressWarnings("unchecked")
public static void registerEventListener(SessionFactory sessionFactory, Object listener, EventType... eventTypes) {
    shouldNotBeNull(sessionFactory, "sessionFactory");
    shouldNotBeNull(listener, "listener");


        log.trace("sessionFactory에 event listener를 등록합니다... listener=[{}], eventTypes=[{}]",
                  listener, StringTool.listToString(eventTypes));

    EventListenerRegistry registry =
            ((SessionFactoryImpl) sessionFactory)
                    .getServiceRegistry()
                    .getService(EventListenerRegistry.class);

    for (EventType eventType : eventTypes) {
        try {
            registry.getEventListenerGroup(eventType).appendListener(listener);
        } catch (Exception ignored) {}
    }

}
 
Example 9
Project: lams   File: TypeSafeActivator.java   View source code 5 votes vote down vote up
@SuppressWarnings( {"UnusedDeclaration"})
public static void applyCallbackListeners(ValidatorFactory validatorFactory, ActivationContext activationContext) {
	final Set<ValidationMode> modes = activationContext.getValidationModes();
	if ( ! ( modes.contains( ValidationMode.CALLBACK ) || modes.contains( ValidationMode.AUTO ) ) ) {
		return;
	}

	// de-activate not-null tracking at the core level when Bean Validation is present unless the user explicitly
	// asks for it
	if ( activationContext.getConfiguration().getProperty( Environment.CHECK_NULLABILITY ) == null ) {
		activationContext.getSessionFactory().getSettings().setCheckNullability( false );
	}

	final BeanValidationEventListener listener = new BeanValidationEventListener(
			validatorFactory,
			activationContext.getConfiguration().getProperties()
	);

	final EventListenerRegistry listenerRegistry = activationContext.getServiceRegistry()
			.getService( EventListenerRegistry.class );

	listenerRegistry.addDuplicationStrategy( DuplicationStrategyImpl.INSTANCE );

	listenerRegistry.appendListeners( EventType.PRE_INSERT, listener );
	listenerRegistry.appendListeners( EventType.PRE_UPDATE, listener );
	listenerRegistry.appendListeners( EventType.PRE_DELETE, listener );

	listener.initialize( activationContext.getConfiguration() );
}
 
Example 10
Project: lams   File: AbstractEntityTuplizer.java   View source code 5 votes vote down vote up
private static Iterable<PersistEventListener> persistEventListeners(SessionImplementor session) {
	return session
			.getFactory()
			.getServiceRegistry()
			.getService( EventListenerRegistry.class )
			.getEventListenerGroup( EventType.PERSIST )
			.listeners();
}
 
Example 11
Project: lams   File: JaccIntegrator.java   View source code 5 votes vote down vote up
private void doIntegration(
		Map properties,
		JaccPermissionDeclarations permissionDeclarations,
		SessionFactoryServiceRegistry serviceRegistry) {
	boolean isSecurityEnabled = properties.containsKey( AvailableSettings.JACC_ENABLED );
	if ( ! isSecurityEnabled ) {
		log.debug( "Skipping JACC integration as it was not enabled" );
		return;
	}

	final String contextId = (String) properties.get( AvailableSettings.JACC_CONTEXT_ID );
	if ( contextId == null ) {
		throw new IntegrationException( "JACC context id must be specified" );
	}

	final JaccService jaccService = serviceRegistry.getService( JaccService.class );
	if ( jaccService == null ) {
		throw new IntegrationException( "JaccService was not set up" );
	}

	if ( permissionDeclarations != null ) {
		for ( GrantedPermission declaration : permissionDeclarations.getPermissionDeclarations() ) {
			jaccService.addPermission( declaration );
		}
	}

	final EventListenerRegistry eventListenerRegistry = serviceRegistry.getService( EventListenerRegistry.class );
	eventListenerRegistry.addDuplicationStrategy( DUPLICATION_STRATEGY );

	eventListenerRegistry.prependListeners( EventType.PRE_DELETE, new JaccPreDeleteEventListener() );
	eventListenerRegistry.prependListeners( EventType.PRE_INSERT, new JaccPreInsertEventListener() );
	eventListenerRegistry.prependListeners( EventType.PRE_UPDATE, new JaccPreUpdateEventListener() );
	eventListenerRegistry.prependListeners( EventType.PRE_LOAD, new JaccPreLoadEventListener() );
}
 
Example 12
Project: lams   File: StandardCacheEntryImpl.java   View source code 5 votes vote down vote up
/**
 * 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;
}
 
Example 13
Project: lams   File: CollectionCacheInvalidator.java   View source code 5 votes vote down vote up
private void integrate(SessionFactoryServiceRegistry serviceRegistry, SessionFactoryImplementor sessionFactory) {
	if ( !sessionFactory.getSettings().isAutoEvictCollectionCache() ) {
		// feature is disabled
		return;
	}
	if ( !sessionFactory.getSettings().isSecondLevelCacheEnabled() ) {
		// Nothing to do, if caching is disabled
		return;
	}
	EventListenerRegistry eventListenerRegistry = serviceRegistry.getService( EventListenerRegistry.class );
	eventListenerRegistry.appendListeners( EventType.POST_INSERT, this );
	eventListenerRegistry.appendListeners( EventType.POST_DELETE, this );
	eventListenerRegistry.appendListeners( EventType.POST_UPDATE, this );
}
 
Example 14
Project: lams   File: EventListenerServiceInitiator.java   View source code 5 votes vote down vote up
@Override
public EventListenerRegistry initiateService(
		SessionFactoryImplementor sessionFactory,
		Configuration configuration,
		ServiceRegistryImplementor registry) {
	return new EventListenerRegistryImpl();
}
 
Example 15
Project: lams   File: EventListenerServiceInitiator.java   View source code 5 votes vote down vote up
@Override
public EventListenerRegistry initiateService(
		SessionFactoryImplementor sessionFactory,
		MetadataImplementor metadata,
		ServiceRegistryImplementor registry) {
	return new EventListenerRegistryImpl();
}
 
Example 16
Project: lams   File: DefaultLoadEventListener.java   View source code 5 votes vote down vote up
private Iterable<PostLoadEventListener> postLoadEventListeners(EventSource session) {
	return session
			.getFactory()
			.getServiceRegistry()
			.getService( EventListenerRegistry.class )
			.getEventListenerGroup( EventType.POST_LOAD )
			.listeners();
}
 
Example 17
Project: lams   File: AbstractFlushingEventListener.java   View source code 5 votes vote down vote up
/**
 * 1. detect any dirty entities
 * 2. schedule any entity updates
 * 3. search out any reachable collections
 */
private int flushEntities(final FlushEvent event, final PersistenceContext persistenceContext) throws HibernateException {

	LOG.trace( "Flushing entities and processing referenced collections" );

	final EventSource source = event.getSession();
	final Iterable<FlushEntityEventListener> flushListeners = source.getFactory().getServiceRegistry()
			.getService( EventListenerRegistry.class )
			.getEventListenerGroup( EventType.FLUSH_ENTITY )
			.listeners();

	// Among other things, updateReachables() will recursively load all
	// collections that are moving roles. This might cause entities to
	// be loaded.

	// So this needs to be safe from concurrent modification problems.

	final Map.Entry<Object,EntityEntry>[] entityEntries = persistenceContext.reentrantSafeEntityEntries();
	final int count = entityEntries.length;

	for ( Map.Entry<Object,EntityEntry> me : entityEntries ) {

		// Update the status of the object and if necessary, schedule an update

		EntityEntry entry = me.getValue();
		Status status = entry.getStatus();

		if ( status != Status.LOADING && status != Status.GONE ) {
			final FlushEntityEvent entityEvent = new FlushEntityEvent( source, me.getKey(), entry );
			for ( FlushEntityEventListener listener : flushListeners ) {
				listener.onFlushEntity( entityEvent );
			}
		}
	}

	source.getActionQueue().sortActions();

	return count;
}
 
Example 18
Project: lams   File: EntityAction.java   View source code 5 votes vote down vote up
protected <T> EventListenerGroup<T> listenerGroup(EventType<T> eventType) {
	return getSession()
			.getFactory()
			.getServiceRegistry()
			.getService( EventListenerRegistry.class )
			.getEventListenerGroup( eventType );
}
 
Example 19
Project: lams   File: CollectionAction.java   View source code 5 votes vote down vote up
protected <T> EventListenerGroup<T> listenerGroup(EventType<T> eventType) {
	return getSession()
			.getFactory()
			.getServiceRegistry()
			.getService( EventListenerRegistry.class )
			.getEventListenerGroup( eventType );
}
 
Example 20
Project: devwars.tv   File: DatabaseManager.java   View source code 5 votes vote down vote up
@Override
public void init() {
    boolean testing = Boolean.parseBoolean(System.getProperty("testing"));

    Configuration configuration = new Configuration();
    configuration.configure("hibernate.cfg.xml");
    configuration.setInterceptor(new HibernateInterceptor());

    if (!testing) {
        configuration.setProperty("hibernate.connection.username", Reference.getEnvironmentProperty("db.username"));
        configuration.setProperty("hibernate.connection.password", Reference.getEnvironmentProperty("db.password"));
        String url = "jdbc:mysql://" + Reference.getEnvironmentProperty("db.host") + ":" + Reference.getEnvironmentProperty("db.port") + "/devwars";
        configuration.setProperty("hibernate.connection.url", url);
    } else {
        configuration.setProperty("hibernate.connection.driver_class", "org.hsqldb.jdbcDriver");
        configuration.setProperty("hibernate.connection.url", "jdbc:hsqldb:mem:testdb");
        configuration.setProperty("hibernate.connection.username", "sa");
        configuration.setProperty("hibernate.dialect", "org.hibernate.dialect.HSQLDialect");
    }

    ServiceRegistry serviceRegistry = new ServiceRegistryBuilder().applySettings(configuration.getProperties()).buildServiceRegistry();
    sessionFactory = configuration.buildSessionFactory(serviceRegistry);

    EventListenerRegistry registry = ((SessionFactoryImpl) DatabaseManager.sessionFactory).getServiceRegistry().getService(EventListenerRegistry.class);

    registry.getEventListenerGroup(EventType.POST_LOAD).appendListener(postLoadEvent ->
    {
        HibernateInterceptor.postLoadAny(postLoadEvent.getEntity());
        HibernateInterceptor.invokeMethodWithAnnotation(postLoadEvent.getEntity(), PostLoad.class);
    });
}
 
Example 21
Project: mojito   File: HibernateEventListenerConfig.java   View source code 5 votes vote down vote up
@PostConstruct
public void registerListeners() {
    EntityManagerFactoryImpl emf = (EntityManagerFactoryImpl) lcemfb.getNativeEntityManagerFactory();
    SessionFactoryImpl sf = emf.getSessionFactory();
    EventListenerRegistry registry = (EventListenerRegistry)sf.getServiceRegistry().getService(EventListenerRegistry.class);
    registry.getEventListenerGroup(EventType.POST_COMMIT_INSERT).appendListener(entityCrudEventListener);
    registry.getEventListenerGroup(EventType.POST_COMMIT_UPDATE).appendListener(entityCrudEventListener);
    registry.getEventListenerGroup(EventType.POST_COMMIT_DELETE).appendListener(entityCrudEventListener);
}
 
Example 22
Project: cibet   File: CibetIntegrator.java   View source code 5 votes vote down vote up
@Override
public void integrate(Configuration configuration, SessionFactoryImplementor sessionFactory,
      SessionFactoryServiceRegistry serviceRegistry) {
   log.info("start CibetIntegrator");
   final boolean autoRegister = ConfigurationHelper.getBoolean(AUTO_REGISTER, configuration.getProperties(), true);
   if (autoRegister) {
      log.debug("Skipping Cibet Envers listener auto registration");
      return;
   }

   log.info("CibetIntegrator registers Cibet Envers listeners");

   EventListenerRegistry listenerRegistry = serviceRegistry.getService(EventListenerRegistry.class);
   listenerRegistry.addDuplicationStrategy(EnversListenerDuplicationStrategy.INSTANCE);

   enversConfiguration = AuditConfiguration.getFor(configuration,
         serviceRegistry.getService(ClassLoaderService.class));

   if (enversConfiguration.getEntCfg().hasAuditedEntities()) {
      listenerRegistry.appendListeners(EventType.POST_DELETE, new CibetPostDeleteEventListener(enversConfiguration));
      listenerRegistry.appendListeners(EventType.POST_INSERT, new CibetPostInsertEventListener(enversConfiguration));
      listenerRegistry.appendListeners(EventType.POST_UPDATE, new CibetPostUpdateEventListener(enversConfiguration));
      listenerRegistry.appendListeners(EventType.POST_COLLECTION_RECREATE,
            new CibetPostCollectionRecreateEventListener(enversConfiguration));
      listenerRegistry.appendListeners(EventType.PRE_COLLECTION_REMOVE,
            new CibetPreCollectionRemoveEventListener(enversConfiguration));
      listenerRegistry.appendListeners(EventType.PRE_COLLECTION_UPDATE,
            new CibetPreCollectionUpdateEventListener(enversConfiguration));
   }
}
 
Example 23
Project: dhis2-core   File: DeletedObjectIntegrator.java   View source code 5 votes vote down vote up
@Override
public void integrate( Metadata metadata, SessionFactoryImplementor sessionFactory, SessionFactoryServiceRegistry serviceRegistry )
{
    final EventListenerRegistry registry = serviceRegistry.getService( EventListenerRegistry.class );

    DeletedObjectPostDeleteEventListener listener = new DeletedObjectPostDeleteEventListener();
    registry.appendListeners( EventType.POST_DELETE, listener );
}
 
Example 24
Project: bygle-ldp   File: HibernateListenersConfigurer.java   View source code 5 votes vote down vote up
@PostConstruct
public void registerListeners() {
   	EventListenerRegistry registry = ((SessionFactoryImpl) sessionFactory).getServiceRegistry().getService(EventListenerRegistry.class);
    registry.getEventListenerGroup(EventType.POST_INSERT).appendListener(dbEventInsertListener);
    registry.getEventListenerGroup(EventType.POST_UPDATE).appendListener(dbEventUpdateListener);
    registry.getEventListenerGroup(EventType.POST_DELETE).appendListener(dbEventDeleteListener);
}
 
Example 25
Project: UMLS-Terminology-Server   File: TermServerEnversIntegrator.java   View source code 5 votes vote down vote up
@Override
public void integrate(Configuration configuration,
  SessionFactoryImplementor sessionFactory,
  SessionFactoryServiceRegistry serviceRegistry) {

  // Avoid custom behavior is autoregister is true
  try {
    if (!"true".equals(ConfigUtility.getConfigProperties()
        .getProperty("hibernate.listeners.envers.autoRegister"))) {

      super.integrate(configuration, sessionFactory, serviceRegistry);

      final AuditConfiguration enversConfiguration =
          AuditConfiguration.getFor(configuration,
              serviceRegistry.getService(ClassLoaderService.class));
      EventListenerRegistry listenerRegistry =
          serviceRegistry.getService(EventListenerRegistry.class);

      listenerRegistry
          .addDuplicationStrategy(EnversListenerDuplicationStrategy.INSTANCE);

      if (enversConfiguration.getEntCfg().hasAuditedEntities()) {
        listenerRegistry.appendListeners(EventType.POST_INSERT,
            new EmptyEnversPostInsertEventListenerImpl(enversConfiguration));
        listenerRegistry.appendListeners(EventType.POST_DELETE,
            new CustomEnversPostDeleteEventListenerImpl(enversConfiguration));
      }
    }
  } catch (Exception e) {
    throw new RuntimeException(e);
  }

}
 
Example 26
Project: AgileAlligators   File: HibernateEventListenerWiring.java   View source code 5 votes vote down vote up
@PostConstruct
public void registerListeners()
{
    EventListenerRegistry registry = ((SessionFactoryImpl) sessionFactory).getServiceRegistry()
        .getService( EventListenerRegistry.class );

    registry.getEventListenerGroup( EventType.PRE_COLLECTION_UPDATE ).appendListener( preCollectionUpdateEventListener );
    registry.getEventListenerGroup( EventType.POST_COMMIT_UPDATE ).appendListener( postUpdateEventListener );
    registry.getEventListenerGroup( EventType.POST_COMMIT_INSERT ).appendListener( postInsertEventListener );
    registry.getEventListenerGroup( EventType.POST_COMMIT_DELETE ).appendListener( postDeleteEventListener );
}
 
Example 27
Project: high-performance-java-persistence   File: OptimisticLockingChildUpdatesRootVersionTest.java   View source code 5 votes vote down vote up
@Override
public void integrate(
        Metadata metadata,
        SessionFactoryImplementor sessionFactory,
        SessionFactoryServiceRegistry serviceRegistry) {

    final EventListenerRegistry eventListenerRegistry =
            serviceRegistry.getService( EventListenerRegistry.class );

    eventListenerRegistry.appendListeners(EventType.PERSIST, RootAwareInsertEventListener.INSTANCE);
    eventListenerRegistry.appendListeners(EventType.FLUSH_ENTITY, RootAwareUpdateAndDeleteEventListener.INSTANCE);
}
 
Example 28
Project: high-performance-java-persistence   File: OptimisticLockingBidirectionalChildUpdatesRootVersionTest.java   View source code 5 votes vote down vote up
@Override
public void integrate(
        Metadata metadata,
        SessionFactoryImplementor sessionFactory,
        SessionFactoryServiceRegistry serviceRegistry) {

    final EventListenerRegistry eventListenerRegistry =
            serviceRegistry.getService( EventListenerRegistry.class );

    eventListenerRegistry.appendListeners( EventType.PERSIST, RootAwareInsertEventListener.INSTANCE);
    eventListenerRegistry.appendListeners( EventType.FLUSH_ENTITY, RootAwareUpdateAndDeleteEventListener.INSTANCE);
}
 
Example 29
Project: jspresso-ce   File: JspressoHibernateIntegrator.java   View source code 5 votes vote down vote up
/**
 * Appends the {@link LifecyclePostLoadEventListener}.
 * <p>
 * {@inheritDoc}
 */
@Override
public void integrate(Configuration configuration,
    SessionFactoryImplementor sessionFactory,
    SessionFactoryServiceRegistry serviceRegistry) {
  serviceRegistry.getService(EventListenerRegistry.class)
      .getEventListenerGroup(EventType.POST_LOAD)
      .appendListener(postLoadListener);
}
 
Example 30
Project: jspresso-ce   File: JspressoHibernateIntegrator.java   View source code 5 votes vote down vote up
/**
 * Appends the {@link LifecyclePostLoadEventListener}.
 * <p>
 * {@inheritDoc}
 */
@Override
public void integrate(MetadataImplementor metadata,
    SessionFactoryImplementor sessionFactory,
    SessionFactoryServiceRegistry serviceRegistry) {
  serviceRegistry.getService(EventListenerRegistry.class)
      .getEventListenerGroup(EventType.POST_LOAD)
      .appendListener(postLoadListener);
}
 
Example 31
Project: spring-entity-listener   File: HibernateEntityListenersAdapter.java   View source code 5 votes vote down vote up
@PostConstruct
public void findMethods() {
    for (Object listener : listeners) {
        findMethodsForListener(listener);
    }

    HibernateEntityManagerFactory hemf = (HibernateEntityManagerFactory) emf;
    SessionFactory sf = hemf.getSessionFactory();
    registry = ((SessionFactoryImpl) sf).getServiceRegistry().getService(EventListenerRegistry.class);
}
 
Example 32
Project: spring-entity-listener   File: HibernateEntityListenersConfigurer.java   View source code 5 votes vote down vote up
@PostConstruct
public void registerListeners() {
    HibernateEntityManagerFactory hemf = (HibernateEntityManagerFactory) emf;
    SessionFactory sf = hemf.getSessionFactory();
    EventListenerRegistry registry = ((SessionFactoryImpl) sf).getServiceRegistry().getService(
            EventListenerRegistry.class);

    registry.getEventListenerGroup(EventType.PRE_INSERT).appendListener(listener);
    registry.getEventListenerGroup(EventType.POST_COMMIT_INSERT).appendListener(listener);
    registry.getEventListenerGroup(EventType.PRE_UPDATE).appendListener(listener);
    registry.getEventListenerGroup(EventType.POST_COMMIT_UPDATE).appendListener(listener);
    registry.getEventListenerGroup(EventType.PRE_DELETE).appendListener(listener);
    registry.getEventListenerGroup(EventType.POST_COMMIT_DELETE).appendListener(listener);
    registry.getEventListenerGroup(EventType.POST_LOAD).appendListener(listener);
}
 
Example 33
Project: ix3   File: IntegratorImplRuleEngine.java   View source code 5 votes vote down vote up
private void prependListeners(EventListenerRegistry eventListenerRegistry) {
    eventListenerRegistry.prependListeners(EventType.PRE_INSERT, new EventListenerImplRuleEngine());
    eventListenerRegistry.prependListeners(EventType.PRE_LOAD, new EventListenerImplRuleEngine());
    eventListenerRegistry.prependListeners(EventType.PRE_UPDATE, new EventListenerImplRuleEngine());
    eventListenerRegistry.prependListeners(EventType.PRE_DELETE, new EventListenerImplRuleEngine());
    eventListenerRegistry.prependListeners(EventType.POST_INSERT, new EventListenerImplRuleEngine());
    eventListenerRegistry.prependListeners(EventType.POST_LOAD, new EventListenerImplRuleEngine());
    eventListenerRegistry.prependListeners(EventType.POST_UPDATE, new EventListenerImplRuleEngine());
    eventListenerRegistry.prependListeners(EventType.POST_DELETE, new EventListenerImplRuleEngine());
}
 
Example 34
Project: Hibernate-Search-GenericJPA   File: HibernateSynchronizedUpdateSourceProvider.java   View source code 5 votes vote down vote up
@Override
public SynchronizedUpdateSource getUpdateSource(
		ExtendedSearchIntegrator searchIntegrator,
		Map<Class<?>, RehashedTypeMetadata> rehashedTypeMetadataPerIndexRoot,
		Map<Class<?>, List<Class<?>>> containedInIndexOf,
		Properties properties,
		EntityManagerFactory emf,
		TransactionManager transactionManager,
		Set<Class<?>> indexRelevantEntities) {
	HibernateEntityManagerFactory hibernateEntityManagerFactory =
			(HibernateEntityManagerFactory) emf;
	SessionFactoryImpl sessionFactory = (SessionFactoryImpl) hibernateEntityManagerFactory.getSessionFactory();
	ServiceRegistry serviceRegistry = sessionFactory.getServiceRegistry();
	EventListenerRegistry listenerRegistry = serviceRegistry.getService( EventListenerRegistry.class );

	HibernateUpdateSource updateSource = new HibernateUpdateSource();
	updateSource.initialize( searchIntegrator );

	listenerRegistry.addDuplicationStrategy( new DuplicationStrategyImpl( HibernateUpdateSource.class ) );

	listenerRegistry.appendListeners( EventType.POST_INSERT, updateSource );
	listenerRegistry.appendListeners( EventType.POST_UPDATE, updateSource );
	listenerRegistry.appendListeners( EventType.POST_DELETE, updateSource );
	listenerRegistry.appendListeners( EventType.POST_COLLECTION_RECREATE, updateSource );
	listenerRegistry.appendListeners( EventType.POST_COLLECTION_REMOVE, updateSource );
	listenerRegistry.appendListeners( EventType.POST_COLLECTION_UPDATE, updateSource );

	return updateSource;
}
 
Example 35
Project: Hibernate-Search-GenericJPA   File: EventSourceTransactionContext.java   View source code 5 votes vote down vote up
private HibernateUpdateSource getIndexWorkFlushEventListener() {
	if ( this.flushListener != null ) {
		//for the "transient" case: might have been nullified.
		return flushListener;
	}
	final Iterable<FlushEventListener> listeners = getService( EventListenerRegistry.class )
			.getEventListenerGroup( EventType.FLUSH ).listeners();
	for ( FlushEventListener listener : listeners ) {
		if ( HibernateUpdateSource.class.isAssignableFrom( listener.getClass() ) ) {
			return (HibernateUpdateSource) listener;
		}
	}
	LOGGER.fine( "FullTextIndexEventListener was not registered as FlushEventListener" );
	return null;
}
 
Example 36
Project: jooby   File: Hbm.java   View source code 5 votes vote down vote up
/**
 * Register an hibernate event listener. Listener will be created and injected by Guice.
 *
 * @param type Event type.
 * @param listenerType Listener type.
 * @return This module.
 */
@SuppressWarnings("unchecked")
public <T> Hbm onEvent(final EventType<T> type, final Class<? extends T> listenerType) {
  bindings.add(b -> {
    b.bind(listenerType).asEagerSingleton();
  });

  listeners.add((s, r) -> {
    ServiceRegistryImplementor serviceRegistry = s.getServiceRegistry();
    EventListenerRegistry service = serviceRegistry.getService(EventListenerRegistry.class);
    T listener = r.require(listenerType);
    service.appendListeners(type, listener);
  });
  return this;
}
 
Example 37
Project: lams   File: SessionImpl.java   View source code 4 votes vote down vote up
private <T> EventListenerGroup<T> eventListenerGroup(EventType<T> type) {
	return factory.getServiceRegistry().getService( EventListenerRegistry.class ).getEventListenerGroup( type );
}
 
Example 38
Project: lams   File: EventListenerServiceInitiator.java   View source code 4 votes vote down vote up
@Override
public Class<EventListenerRegistry> getServiceInitiated() {
	return EventListenerRegistry.class;
}
 
Example 39
Project: rpb   File: HibernateListenerRegistration.java   View source code 4 votes vote down vote up
private <T> void register(EventType<T> eventType, T t) {
    EventListenerRegistry registry = ((SessionFactoryImpl) sessionFactory).getServiceRegistry().getService(EventListenerRegistry.class);
    log.info("Registering " + t.getClass() + " listener on " + eventType + " events.");
    registry.getEventListenerGroup(eventType).appendListener(t);
}
 
Example 40
Project: rpb   File: HibernateListenerRegistration.java   View source code 4 votes vote down vote up
private <T> void register(EventType<T> eventType, T t) {
    EventListenerRegistry registry = ((SessionFactoryImpl) sessionFactory).getServiceRegistry().getService(EventListenerRegistry.class);
    log.info("Registering " + t.getClass() + " listener on " + eventType + " events.");
    registry.getEventListenerGroup(eventType).appendListener(t);
}