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

The following examples show how to use org.hibernate.event.service.spi.EventListenerRegistry. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ReactiveIntegrator.java    From hibernate-reactive with GNU Lesser General Public License v2.1 6 votes vote down vote up
private void attachEventContextManagingListenersIfRequired(SessionFactoryServiceRegistry serviceRegistry) {
	if ( ReactiveModeCheck.isReactiveRegistry( serviceRegistry ) ) {

		CoreLogging.messageLogger(ReactiveIntegrator.class).info("HRX000001: Hibernate Reactive Preview");

		EventListenerRegistry eventListenerRegistry = serviceRegistry.getService( EventListenerRegistry.class );
		eventListenerRegistry.addDuplicationStrategy( ReplacementDuplicationStrategy.INSTANCE );

		eventListenerRegistry.getEventListenerGroup( EventType.AUTO_FLUSH ).appendListener( new DefaultReactiveAutoFlushEventListener() );
		eventListenerRegistry.getEventListenerGroup( EventType.FLUSH ).appendListener( new DefaultReactiveFlushEventListener() );
		eventListenerRegistry.getEventListenerGroup( EventType.FLUSH_ENTITY ).appendListener( new DefaultReactiveFlushEntityEventListener() );
		eventListenerRegistry.getEventListenerGroup( EventType.PERSIST ).appendListener( new DefaultReactivePersistEventListener() );
		eventListenerRegistry.getEventListenerGroup( EventType.PERSIST_ONFLUSH ).appendListener( new DefaultReactivePersistOnFlushEventListener() );
		eventListenerRegistry.getEventListenerGroup( EventType.MERGE ).appendListener( new DefaultReactiveMergeEventListener() );
		eventListenerRegistry.getEventListenerGroup( EventType.DELETE ).appendListener( new DefaultReactiveDeleteEventListener() );
		eventListenerRegistry.getEventListenerGroup( EventType.REFRESH ).appendListener( new DefaultReactiveRefreshEventListener() );
		eventListenerRegistry.getEventListenerGroup( EventType.LOCK ).appendListener( new DefaultReactiveLockEventListener() );
		eventListenerRegistry.getEventListenerGroup( EventType.LOAD ).appendListener( new DefaultReactiveLoadEventListener() );
		eventListenerRegistry.getEventListenerGroup( EventType.INIT_COLLECTION ).appendListener( new DefaultReactiveInitializeCollectionEventListener() );
	}
}
 
Example #2
Source File: EventListenerIntegrator.java    From gorm-hibernate5 with Apache License 2.0 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 #3
Source File: TwoPhaseLoad.java    From lams with GNU General Public License v2.0 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 SharedSessionContractImplementor 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 #4
Source File: EventListenerIntegrator.java    From gorm-hibernate5 with Apache License 2.0 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 #5
Source File: SessionFactoryImpl.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
private void prepareEventListeners(MetadataImplementor metadata) {
	final EventListenerRegistry eventListenerRegistry = serviceRegistry.getService( EventListenerRegistry.class );
	final ConfigurationService cfgService = serviceRegistry.getService( ConfigurationService.class );
	final ClassLoaderService classLoaderService = serviceRegistry.getService( ClassLoaderService.class );

	eventListenerRegistry.prepare( metadata );

	for ( Map.Entry entry : ( (Map<?, ?>) cfgService.getSettings() ).entrySet() ) {
		if ( !String.class.isInstance( entry.getKey() ) ) {
			continue;
		}
		final String propertyName = (String) entry.getKey();
		if ( !propertyName.startsWith( org.hibernate.jpa.AvailableSettings.EVENT_LISTENER_PREFIX ) ) {
			continue;
		}
		final String eventTypeName = propertyName.substring(
				org.hibernate.jpa.AvailableSettings.EVENT_LISTENER_PREFIX.length() + 1
		);
		final EventType eventType = EventType.resolveEventTypeByName( eventTypeName );
		final EventListenerGroup eventListenerGroup = eventListenerRegistry.getEventListenerGroup( eventType );
		for ( String listenerImpl : ( (String) entry.getValue() ).split( " ," ) ) {
			eventListenerGroup.appendListener( instantiate( listenerImpl, classLoaderService ) );
		}
	}
}
 
Example #6
Source File: ReactiveLoaderBasedResultSetProcessor.java    From hibernate-reactive with GNU Lesser General Public License v2.1 5 votes vote down vote up
public ReactiveLoaderBasedResultSetProcessor(ReactiveLoaderBasedLoader loader) {
	this.loader = loader;
	this.listeners = loader
			.getFactory()
			.getServiceRegistry()
			.getService(EventListenerRegistry.class)
			.getEventListenerGroup(EventType.PRE_LOAD)
			.listeners();
}
 
Example #7
Source File: EventListenerIntegrator.java    From high-performance-java-persistence with Apache License 2.0 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.POST_LOAD,
        AuditLogPostLoadEventListener.INSTANCE
    );
}
 
Example #8
Source File: EntityReplicationTest.java    From high-performance-java-persistence with Apache License 2.0 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.POST_INSERT, ReplicationInsertEventListener.INSTANCE);
    eventListenerRegistry.appendListeners(EventType.POST_UPDATE, ReplicationUpdateEventListener.INSTANCE);
    eventListenerRegistry.appendListeners(EventType.PRE_DELETE, ReplicationDeleteEventListener.INSTANCE);
}
 
Example #9
Source File: OptimisticLockingBidirectionalChildUpdatesRootVersionTest.java    From high-performance-java-persistence with Apache License 2.0 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 #10
Source File: OptimisticLockingChildUpdatesRootVersionTest.java    From high-performance-java-persistence with Apache License 2.0 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 #11
Source File: DeletedObjectListenerConfigurer.java    From dhis2-core with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@PostConstruct
protected void init()
{
    SessionFactoryImpl sessionFactory = emf.unwrap( SessionFactoryImpl.class );

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

    registry.getEventListenerGroup( EventType.POST_COMMIT_INSERT ).appendListener( insertEventListener );

    registry.getEventListenerGroup( EventType.POST_COMMIT_DELETE ).appendListener( deleteEventListener );
}
 
Example #12
Source File: HibernateEventListenerConfig.java    From mojito with Apache License 2.0 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 #13
Source File: CollectionAction.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
protected <T> EventListenerGroup<T> listenerGroup(EventType<T> eventType) {
	return getSession()
			.getFactory()
			.getServiceRegistry()
			.getService( EventListenerRegistry.class )
			.getEventListenerGroup( eventType );
}
 
Example #14
Source File: EntityAction.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
protected <T> EventListenerGroup<T> listenerGroup(EventType<T> eventType) {
	return getSession()
			.getFactory()
			.getServiceRegistry()
			.getService( EventListenerRegistry.class )
			.getEventListenerGroup( eventType );
}
 
Example #15
Source File: AbstractFlushingEventListener.java    From lams with GNU General Public License v2.0 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 #16
Source File: DefaultLoadEventListener.java    From lams with GNU General Public License v2.0 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
Source File: EventListenerServiceInitiator.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
public EventListenerRegistry initiateService(
		SessionFactoryImplementor sessionFactory,
		SessionFactoryOptions sessionFactoryOptions,
		ServiceRegistryImplementor registry) {
	return new EventListenerRegistryImpl( sessionFactory, sessionFactoryOptions, registry );
}
 
Example #18
Source File: CollectionCacheInvalidator.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
private void integrate(SessionFactoryServiceRegistry serviceRegistry, SessionFactoryImplementor sessionFactory) {
	if ( !sessionFactory.getSessionFactoryOptions().isAutoEvictCollectionCache() ) {
		// feature is disabled
		return;
	}
	if ( !sessionFactory.getSessionFactoryOptions().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 #19
Source File: StandardCacheEntryImpl.java    From lams with GNU General Public License v2.0 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[] state = 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( state )
			.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, state );

	return state;
}
 
Example #20
Source File: JaccIntegrator.java    From lams with GNU General Public License v2.0 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 #21
Source File: SessionFactoryImpl.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
private void applyCfgXmlValues(LoadedConfig aggregatedConfig, SessionFactoryServiceRegistry serviceRegistry) {
	final JaccService jaccService = serviceRegistry.getService( JaccService.class );
	if ( jaccService.getContextId() != null ) {
		final JaccPermissionDeclarations permissions = aggregatedConfig.getJaccPermissions( jaccService.getContextId() );
		if ( permissions != null ) {
			for ( GrantedPermission grantedPermission : permissions.getPermissionDeclarations() ) {
				jaccService.addPermission( grantedPermission );
			}
		}
	}

	if ( aggregatedConfig.getEventListenerMap() != null ) {
		final ClassLoaderService cls = serviceRegistry.getService( ClassLoaderService.class );
		final EventListenerRegistry eventListenerRegistry = serviceRegistry.getService( EventListenerRegistry.class );
		for ( Map.Entry<EventType, Set<String>> entry : aggregatedConfig.getEventListenerMap().entrySet() ) {
			final EventListenerGroup group = eventListenerRegistry.getEventListenerGroup( entry.getKey() );
			for ( String listenerClassName : entry.getValue() ) {
				try {
					group.appendListener( cls.classForName( listenerClassName ).newInstance() );
				}
				catch (Exception e) {
					throw new ConfigurationException( "Unable to instantiate event listener class : " + listenerClassName, e );
				}
			}
		}
	}
}
 
Example #22
Source File: TypeSafeActivator.java    From lams with GNU General Public License v2.0 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;
	}

	final ConfigurationService cfgService = activationContext.getServiceRegistry().getService( ConfigurationService.class );
	final ClassLoaderService classLoaderService = activationContext.getServiceRegistry().getService( ClassLoaderService.class );

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

	final BeanValidationEventListener listener = new BeanValidationEventListener(
			validatorFactory,
			cfgService.getSettings(),
			classLoaderService
	);

	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( cfgService.getSettings(), classLoaderService );
}
 
Example #23
Source File: HibernateQueryMetrics.java    From micrometer with Apache License 2.0 5 votes vote down vote up
@Override
public void bindTo(MeterRegistry meterRegistry) {
    if (sessionFactory instanceof SessionFactoryImplementor) {
        EventListenerRegistry eventListenerRegistry = ((SessionFactoryImplementor) sessionFactory).getServiceRegistry().getService(EventListenerRegistry.class);
        MetricsEventHandler metricsEventHandler = new MetricsEventHandler(meterRegistry);
        eventListenerRegistry.appendListeners(EventType.POST_LOAD, metricsEventHandler);
    }
}
 
Example #24
Source File: AbstractReactiveFlushingEventListener.java    From hibernate-reactive with GNU Lesser General Public License v2.1 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 #25
Source File: ReactiveSessionImpl.java    From hibernate-reactive with GNU Lesser General Public License v2.1 5 votes vote down vote up
@SuppressWarnings("deprecation")
private <T> Iterable<T> eventListeners(EventType<T> type) {
	return getFactory().unwrap( SessionFactoryImplementor.class )
			.getServiceRegistry().getService( EventListenerRegistry.class )
			.getEventListenerGroup( type )
			.listeners();
}
 
Example #26
Source File: ReactivePlanEntityLoader.java    From hibernate-reactive with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * This method is based on {@link AbstractRowReader#performTwoPhaseLoad}
 */
public CompletionStage<Void> reactivePerformTwoPhaseLoad(
		ReactiveLoadPlanBasedResultSetProcessor resultSetProcessor,
		PreLoadEvent preLoadEvent,
		ResultSetProcessingContextImpl context,
		List<HydratedEntityRegistration> hydratedEntityRegistrations) {
	final int numberOfHydratedObjects = hydratedEntityRegistrations == null
			? 0
			: hydratedEntityRegistrations.size();
	//log.tracev( "Total objects hydrated: {0}", numberOfHydratedObjects );

	CompletionStage<Void> stage = CompletionStages.nullFuture();

	if ( numberOfHydratedObjects == 0 ) {
		return stage;
	}

	final SharedSessionContractImplementor session = context.getSession();
	final Iterable<PreLoadEventListener> listeners = session
			.getFactory()
			.getServiceRegistry()
			.getService( EventListenerRegistry.class )
			.getEventListenerGroup( EventType.PRE_LOAD )
			.listeners();

	for ( HydratedEntityRegistration registration : hydratedEntityRegistrations ) {
		final EntityEntry entityEntry = session.getPersistenceContext().getEntry( registration.getInstance() );
		stage = stage.thenCompose( v -> resultSetProcessor.initializeEntity(
				registration.getInstance(),
				false,
				session,
				preLoadEvent,
				listeners
		));
	}

	return stage;
}
 
Example #27
Source File: EventListenerServiceInitiator.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
@Override
public EventListenerRegistry initiateService(SessionFactoryServiceInitiatorContext context) {
	return new EventListenerRegistryImpl( context.getSessionFactory(), context.getSessionFactoryOptions(), context.getServiceRegistry());
}
 
Example #28
Source File: EventListenerServiceInitiator.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
@Override
public Class<EventListenerRegistry> getServiceInitiated() {
	return EventListenerRegistry.class;
}
 
Example #29
Source File: SessionImpl.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
private <T> EventListenerGroup<T> eventListenerGroup(EventType<T> type) {
	return getFactory().getServiceRegistry().getService( EventListenerRegistry.class ).getEventListenerGroup( type );
}
 
Example #30
Source File: EventIntegrator.java    From micronaut-data with Apache License 2.0 4 votes vote down vote up
@Override
public void integrate(
        Metadata metadata,
        SessionFactoryImplementor sessionFactory,
        SessionFactoryServiceRegistry serviceRegistry) {
    EventListenerRegistry eventListenerRegistry =
            serviceRegistry.getService(EventListenerRegistry.class);

    Collection<PersistentClass> entityBindings = metadata.getEntityBindings();
    Map<Class, BeanProperty> lastUpdates = new HashMap<>(entityBindings.size());
    Map<Class, BeanProperty> dateCreated = new HashMap<>(entityBindings.size());

    entityBindings.forEach(e -> {
                Class<?> mappedClass = e.getMappedClass();
                if (mappedClass != null) {
                    BeanIntrospection<?> introspection = BeanIntrospector.SHARED.findIntrospection(mappedClass).orElse(null);
                    if (introspection != null) {
                        introspection.getIndexedProperty(DateCreated.class).ifPresent(bp ->
                                dateCreated.put(mappedClass, bp)
                        );
                        introspection.getIndexedProperty(DateUpdated.class).ifPresent(bp ->
                                lastUpdates.put(mappedClass, bp)
                        );
                    }
                }
            }
    );

    ConversionService<?> conversionService = ConversionService.SHARED;

    if (CollectionUtils.isNotEmpty(dateCreated)) {

        eventListenerRegistry.getEventListenerGroup(EventType.PRE_INSERT)
                .appendListener((PreInsertEventListener) event -> {
                    Object[] state = event.getState();
                    timestampIfNecessary(
                            dateCreated,
                            lastUpdates,
                            conversionService,
                            event,
                            state,
                            true
                    );
                    return false;
                });
    }

    if (CollectionUtils.isNotEmpty(lastUpdates)) {

        eventListenerRegistry.getEventListenerGroup(EventType.PRE_UPDATE)
                .appendListener((PreUpdateEventListener) event -> {
                    timestampIfNecessary(
                            dateCreated, lastUpdates,
                            conversionService,
                            event,
                            event.getState(),
                            false
                    );
                    return false;
                });
    }
}