org.springframework.context.ApplicationEvent Java Examples

The following examples show how to use org.springframework.context.ApplicationEvent. 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: ApplicationListenerMethodAdapter.java    From spring-analysis-note with MIT License 6 votes vote down vote up
/**
 * Resolve the method arguments to use for the specified {@link ApplicationEvent}.
 * <p>These arguments will be used to invoke the method handled by this instance.
 * Can return {@code null} to indicate that no suitable arguments could be resolved
 * and therefore the method should not be invoked at all for the specified event.
 */
@Nullable
protected Object[] resolveArguments(ApplicationEvent event) {
	ResolvableType declaredEventType = getResolvableType(event);
	if (declaredEventType == null) {
		return null;
	}
	if (this.method.getParameterCount() == 0) {
		return new Object[0];
	}
	Class<?> declaredEventClass = declaredEventType.toClass();
	if (!ApplicationEvent.class.isAssignableFrom(declaredEventClass) &&
			event instanceof PayloadApplicationEvent) {
		Object payload = ((PayloadApplicationEvent<?>) event).getPayload();
		if (declaredEventClass.isInstance(payload)) {
			return new Object[] {payload};
		}
	}
	return new Object[] {event};
}
 
Example #2
Source File: LandscapeWatcherTest.java    From microservices-dashboard with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldDispatchEventWhenServiceDisappeared() {
	when(this.discoveryClient.getServices()).thenReturn(Collections.singletonList("a"));
	when(this.catalog.getApplications()).thenReturn(Arrays.asList("a", "b"));
	when(this.discoveryClient.getInstances("a")).thenReturn(Collections.emptyList());

	this.landscapeWatcher.discoverLandscape();

	verify(this.catalogService, times(2)).getCatalog();
	verifyNoMoreInteractions(this.catalogService);

	verify(this.discoveryClient).getServices();
	verify(this.discoveryClient).getInstances("a");
	verifyNoMoreInteractions(this.discoveryClient);

	verify(this.publisher).publishEvent(this.applicationEventArgumentCaptor.capture());
	verifyNoMoreInteractions(this.publisher);
	ApplicationEvent event = this.applicationEventArgumentCaptor.getValue();
	assertThat(event).isInstanceOfSatisfying(ServiceDisappeared.class,
			e -> assertThat(e.getSource()).isEqualTo("b"));
}
 
Example #3
Source File: ChainingUserRegistrySynchronizer.java    From alfresco-repository with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Override
protected void onBootstrap(ApplicationEvent event)
{
    // Do an initial differential sync on startup, using transaction splitting. This ensures that on the very
    // first startup, we don't have to wait for a very long login operation to trigger the first sync!
    if (this.syncOnStartup)
    {
        AuthenticationUtil.runAs(new RunAsWork<Object>()
        {
            public Object doWork() throws Exception
            {
                try
                {
                    synchronizeInternal(false, false, true);
                }
                catch (Exception e)
                {
                    ChainingUserRegistrySynchronizer.logger.warn("Failed initial synchronize with user registries",
                            e);
                }
                return null;
            }
        }, AuthenticationUtil.getSystemUserName());
    }
}
 
Example #4
Source File: BerkeleyAccessorFactory.java    From jstarcraft-core with Apache License 2.0 6 votes vote down vote up
@Override
public synchronized void onApplicationEvent(ApplicationEvent event) {
    getObject();

    if (event instanceof ContextRefreshedEvent) {
        if (accessor.getState() == BerkeleyState.STOPPED) {
            accessor.start();
        }
        return;
    }

    if (event instanceof ContextClosedEvent) {
        if (accessor.getState() == BerkeleyState.STARTED) {
            accessor.stop();
        }
        return;
    }
}
 
Example #5
Source File: RepositoryContainer.java    From alfresco-remote-api with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Override
public void onApplicationEvent(ApplicationEvent event)
{
    if (event instanceof ContextRefreshedEvent)
    {
        ContextRefreshedEvent refreshEvent = (ContextRefreshedEvent)event;
        ApplicationContext refreshContext = refreshEvent.getApplicationContext();
        if (refreshContext != null && refreshContext.equals(applicationContext))
        {
            RunAsWork<Object> work = new RunAsWork<Object>()
            {
                public Object doWork() throws Exception
                {
                    reset();
                    return null;
                }
            };
            AuthenticationUtil.runAs(work, AuthenticationUtil.getSystemUserName());
        }
    }
}
 
Example #6
Source File: DelayedEventBusPushStrategy.java    From hawkbit with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * An application event publisher subscriber which subscribes
 * {@link TenantAwareEvent} from the repository to dispatch these events to
 * the UI {@link SessionEventBus} .
 * 
 * @param applicationEvent
 *            the entity event which has been published from the repository
 */
@Override
public void onApplicationEvent(final ApplicationEvent applicationEvent) {
    if (!(applicationEvent instanceof TenantAwareEvent)) {
        return;
    }

    final TenantAwareEvent event = (TenantAwareEvent) applicationEvent;

    collectRolloutEvent(event);
    // to dispatch too many events which are not interested on the UI
    if (!isEventProvided(event)) {
        LOG.trace("Event is not supported in the UI!!! Dropped event is {}", event);
        return;
    }
    offerEvent(event);
}
 
Example #7
Source File: ModuleStarter.java    From alfresco-repository with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Override
protected void onBootstrap(ApplicationEvent event)
{
    PropertyCheck.mandatory(this, "moduleService", moduleService);
    final RetryingTransactionCallback<Object> startModulesCallback = new RetryingTransactionCallback<Object>()
    {
        public Object execute() throws Throwable
        {
            moduleService.startModules();
            return null;
        }
    };
    
    AuthenticationUtil.runAs(new RunAsWork<Object>()
    {
        @Override
        public Object doWork() throws Exception 
        {
            transactionService.getRetryingTransactionHelper().doInTransaction(startModulesCallback, transactionService.isReadOnly());
            return null;
        }
    	
    }, AuthenticationUtil.getSystemUserName());       
}
 
Example #8
Source File: ApplicationContextEventTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
@SuppressWarnings("unchecked")
public void proxiedListeners() {
	MyOrderedListener1 listener1 = new MyOrderedListener1();
	MyOrderedListener2 listener2 = new MyOrderedListener2(listener1);
	ApplicationListener<ApplicationEvent> proxy1 = (ApplicationListener<ApplicationEvent>) new ProxyFactory(listener1).getProxy();
	ApplicationListener<ApplicationEvent> proxy2 = (ApplicationListener<ApplicationEvent>) new ProxyFactory(listener2).getProxy();

	SimpleApplicationEventMulticaster smc = new SimpleApplicationEventMulticaster();
	smc.addApplicationListener(proxy1);
	smc.addApplicationListener(proxy2);

	smc.multicastEvent(new MyEvent(this));
	smc.multicastEvent(new MyOtherEvent(this));
	assertEquals(2, listener1.seenEvents.size());
}
 
Example #9
Source File: AppConfig.java    From flow-platform-x with Apache License 2.0 6 votes vote down vote up
@Bean(name = "applicationEventMulticaster")
public ApplicationEventMulticaster simpleApplicationEventMulticaster() {
    SimpleApplicationEventMulticaster multicaster = new SimpleApplicationEventMulticaster() {

        @Override
        public void multicastEvent(ApplicationEvent event, ResolvableType eventType) {
            if (event instanceof SyncEvent) {
                ResolvableType type = (eventType != null ? eventType : ResolvableType.forInstance(event));
                for (final ApplicationListener<?> listener : getApplicationListeners(event, type)) {
                    invokeListener(listener, event);
                }
                return;
            }

            super.multicastEvent(event, eventType);
        }
    };

    SimpleAsyncTaskExecutor executor = new SimpleAsyncTaskExecutor("s-event-");
    multicaster.setTaskExecutor(executor);
    return multicaster;
}
 
Example #10
Source File: ApplicationListenerMethodAdapter.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
/**
 * Resolve the method arguments to use for the specified {@link ApplicationEvent}.
 * <p>These arguments will be used to invoke the method handled by this instance. Can
 * return {@code null} to indicate that no suitable arguments could be resolved and
 * therefore the method should not be invoked at all for the specified event.
 */
protected Object[] resolveArguments(ApplicationEvent event) {
	ResolvableType declaredEventType = getResolvableType(event);
	if (declaredEventType == null) {
		return null;
	}
	if (this.method.getParameterTypes().length == 0) {
		return new Object[0];
	}
	if (!ApplicationEvent.class.isAssignableFrom(declaredEventType.getRawClass())
			&& event instanceof PayloadApplicationEvent) {
		return new Object[] {((PayloadApplicationEvent) event).getPayload()};
	}
	else {
		return new Object[] {event};
	}
}
 
Example #11
Source File: MetricCassandraCollector.java    From realtime-analytics with GNU General Public License v2.0 6 votes vote down vote up
@Override
protected void processApplicationEvent(ApplicationEvent event) {
    if (event instanceof ContextBeanChangedEvent) {
        ContextBeanChangedEvent bcInfo = (ContextBeanChangedEvent) event;
        // Apply changes
        if (bcInfo.getBeanName().equals(getConfig().getBeanName())) {
            LOGGER.info("Received change bean:  - "
                    + event.getClass().getName());
            LOGGER.info("Received new configuration for  - "
                    + bcInfo.getBeanName());
            try {
                setConfig(((CassandraConfig) bcInfo.getChangedBean()));
            } catch (Exception e) {
                LOGGER.warn("Error while applying config to CassandraConfig - "
                                + e.getMessage());
            }
            if ((!getConfig().getKeySpace().equals(this.keySpace))
                    || (getConfig().getContactPoints() != this.contactPoints)) {
                if (config.getEnableCassandra()) {
                    disconnect();
                    connect();
                }
            }
        }
    }
}
 
Example #12
Source File: ApplicationContextEventTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
private void multicastEvent(boolean match, Class<?> listenerType, ApplicationEvent event, ResolvableType eventType) {
	@SuppressWarnings("unchecked")
	ApplicationListener<ApplicationEvent> listener =
			(ApplicationListener<ApplicationEvent>) mock(listenerType);
	SimpleApplicationEventMulticaster smc = new SimpleApplicationEventMulticaster();
	smc.addApplicationListener(listener);

	if (eventType != null) {
		smc.multicastEvent(event, eventType);
	}
	else {
		smc.multicastEvent(event);
	}
	int invocation = match ? 1 : 0;
	verify(listener, times(invocation)).onApplicationEvent(event);
}
 
Example #13
Source File: ApplicationListenerMethodAdapter.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
private ResolvableType getResolvableType(ApplicationEvent event) {
	ResolvableType payloadType = null;
	if (event instanceof PayloadApplicationEvent) {
		PayloadApplicationEvent<?> payloadEvent = (PayloadApplicationEvent<?>) event;
		payloadType = payloadEvent.getResolvableType().as(
				PayloadApplicationEvent.class).getGeneric(0);
	}
	for (ResolvableType declaredEventType : this.declaredEventTypes) {
		if (!ApplicationEvent.class.isAssignableFrom(declaredEventType.getRawClass())
				&& payloadType != null) {
			if (declaredEventType.isAssignableFrom(payloadType)) {
				return declaredEventType;
			}
		}
		if (declaredEventType.getRawClass().isAssignableFrom(event.getClass())) {
			return declaredEventType;
		}
	}
	return null;
}
 
Example #14
Source File: ChassisConfiguration.java    From chassis with Apache License 2.0 6 votes vote down vote up
@Override
public void onApplicationEvent(ApplicationEvent event) {
    //we only want to tell Eureka that the application is up
    //when the root application context (thisApplicationContext) has
    //been fully started.  we want to ignore any ContextRefreshedEvent
    //from child application contexts.
    if (!event.getSource().equals(thisApplicationContext)) {
        return;
    }
    if (event instanceof ContextRefreshedEvent) {
        if (!disableEureka) {
            // tell Eureka the server UP which in turn starts the health checks and heartbeat
            ApplicationInfoManager.getInstance().setInstanceStatus(InstanceStatus.UP);
        }
    } else if (event instanceof ContextClosedEvent) {
        if (!disableEureka) {
            ApplicationInfoManager.getInstance().setInstanceStatus(InstanceStatus.DOWN);
        }
    }
}
 
Example #15
Source File: BalancerConfiguration.java    From haven-platform with Apache License 2.0 6 votes vote down vote up
/**
 * Listens ContextClosedEvent and Closes all async http connections
 */
@Bean
ApplicationListener<?> applicationListener() {
    return new SmartApplicationListener() {
        @Override
        public int getOrder() { return 0; }

        @Override
        public boolean supportsEventType(Class<? extends ApplicationEvent> eventType) {
            return ContextClosedEvent.class.isAssignableFrom(eventType);
        }

        @Override
        public boolean supportsSourceType(Class<?> sourceType) { return true; }

        @Override
        public void onApplicationEvent(ApplicationEvent event) { Closeables.close(proxyInstance); }
    };
}
 
Example #16
Source File: EventPublicationInterceptor.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Override
public Object invoke(MethodInvocation invocation) throws Throwable {
	Object retVal = invocation.proceed();

	Assert.state(this.applicationEventClassConstructor != null, "No ApplicationEvent class set");
	ApplicationEvent event = (ApplicationEvent)
			this.applicationEventClassConstructor.newInstance(invocation.getThis());

	Assert.state(this.applicationEventPublisher != null, "No ApplicationEventPublisher available");
	this.applicationEventPublisher.publishEvent(event);

	return retVal;
}
 
Example #17
Source File: SimpleApplicationEventMulticaster.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Override
public void multicastEvent(final ApplicationEvent event, @Nullable ResolvableType eventType) {
	ResolvableType type = (eventType != null ? eventType : resolveDefaultEventType(event));
	for (final ApplicationListener<?> listener : getApplicationListeners(event, type)) {
		Executor executor = getTaskExecutor();
		if (executor != null) {
			executor.execute(() -> invokeListener(listener, event));
		}
		else {
			invokeListener(listener, event);
		}
	}
}
 
Example #18
Source File: ApplicationListenerMethodAdapter.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Process the specified {@link ApplicationEvent}, checking if the condition
 * match and handling non-null result, if any.
 */
public void processEvent(ApplicationEvent event) {
	Object[] args = resolveArguments(event);
	if (shouldHandle(event, args)) {
		Object result = doInvoke(args);
		if (result != null) {
			handleResult(result);
		}
		else {
			logger.trace("No result object given - no result to handle");
		}
	}
}
 
Example #19
Source File: SpringSecurityListener.java    From lemon with Apache License 2.0 5 votes vote down vote up
public void logLoginSuccess(ApplicationEvent event) throws Exception {
    InteractiveAuthenticationSuccessEvent interactiveAuthenticationSuccessEvent = (InteractiveAuthenticationSuccessEvent) event;
    Authentication authentication = interactiveAuthenticationSuccessEvent
            .getAuthentication();

    String tenantId = this.getTenantId(authentication);
    Object principal = authentication.getPrincipal();
    String userId = null;

    if (principal instanceof SpringSecurityUserAuth) {
        userId = ((SpringSecurityUserAuth) principal).getId();
    } else {
        userId = authentication.getName();
    }

    AuditDTO auditDto = new AuditDTO();
    auditDto.setUserId(userId);
    auditDto.setAuditTime(new Date());
    auditDto.setAction("login");
    auditDto.setResult("success");
    auditDto.setApplication("lemon");
    auditDto.setClient(getUserIp(authentication));
    auditDto.setServer(InetAddress.getLocalHost().getHostAddress());
    auditDto.setTenantId(tenantId);
    auditConnector.log(auditDto);

    // 登录成功,再发送一个消息,以后这里的功能都要改成listener,不用直接写接口了。解耦更好一些。
    ctx.publishEvent(new LoginEvent(authentication, userId, this
            .getSessionId(authentication), "success", "default", tenantId));
}
 
Example #20
Source File: ShutdownBackstop.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
protected void onShutdown(ApplicationEvent event) 
{
	if(isEnabled())
	{
		log.info("Shutdown backstop timer started");
		Thread selfDestructThread = new ShutdownBackstopThread(timeout);
		selfDestructThread.start();
	}
}
 
Example #21
Source File: LoggingEnvironmentApplicationListener.java    From spring-cloud-formula with Apache License 2.0 5 votes vote down vote up
@Override
public void onApplicationEvent(ApplicationEvent event) {
    if (event instanceof ApplicationStartingEvent) {
        onApplicationStartingEvent((ApplicationStartingEvent) event);
    }
    else if (event instanceof ApplicationEnvironmentPreparedEvent) {
        onApplicationEnvironmentPreparedEvent(
                (ApplicationEnvironmentPreparedEvent) event);
    }
}
 
Example #22
Source File: ApplicationListenerMethodAdapter.java    From java-technology-stack with MIT License 5 votes vote down vote up
/**
 * Process the specified {@link ApplicationEvent}, checking if the condition
 * match and handling non-null result, if any.
 */
public void processEvent(ApplicationEvent event) {
	Object[] args = resolveArguments(event);
	if (shouldHandle(event, args)) {
		Object result = doInvoke(args);
		if (result != null) {
			handleResult(result);
		}
		else {
			logger.trace("No result object given - no result to handle");
		}
	}
}
 
Example #23
Source File: HmilyTransactionSelfRecoveryScheduled.java    From hmily with Apache License 2.0 5 votes vote down vote up
@Override
public void onApplicationEvent(@NonNull final ApplicationEvent event) {
    if (!isInit.compareAndSet(false, true)) {
        return;
    }
    hmilyCoordinatorRepository = SpringBeanUtils.getInstance().getBean(HmilyCoordinatorRepository.class);
    this.scheduledExecutorService =
            new ScheduledThreadPoolExecutor(1,
                    HmilyThreadFactory.create("hmily-transaction-self-recovery", true));
    hmilyTransactionRecoveryService = new HmilyTransactionRecoveryService(hmilyCoordinatorRepository);
    selfRecovery();
}
 
Example #24
Source File: DeferredApplicationEventPublisher.java    From spring-context-support with Apache License 2.0 5 votes vote down vote up
private void deferEvent(ApplicationEvent event) {
    try {
        deferredEvents.add(event);
    } catch (Exception ignore) {
        deferredEvents.add(event);
    }
}
 
Example #25
Source File: RuntimeExecShutdownBean.java    From alfresco-core with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
protected void onBootstrap(ApplicationEvent event)
{
    // register shutdown hook
    shutdownHook = new ShutdownThread();
    Runtime.getRuntime().addShutdownHook(shutdownHook);

    if (logger.isDebugEnabled())
    {
        logger.debug("Registered shutdown hook");
    }
}
 
Example #26
Source File: UiEventListenerMethodAdapter.java    From cuba with Apache License 2.0 5 votes vote down vote up
protected boolean shouldHandle(ApplicationEvent event, Object[] args) {
    if (args == null) {
        return false;
    }
    String condition = getCondition();
    if (!Strings.isNullOrEmpty(condition)) {
        throw new UnsupportedOperationException("@EventListener condition is not supported for UiEvents");
    }
    return true;
}
 
Example #27
Source File: ServiceRegisterableExecutionVenue.java    From cougar with Apache License 2.0 5 votes vote down vote up
/**
 * In the case of ContextRefreshedEvent (that is, once all Spring configuration is loaded), the services will be
    * initialised
 */
@Override
public void onApplicationEvent(ApplicationEvent event) {
	if (event instanceof ContextRefreshedEvent) {
	    // Firstly dump out all the properties read from the various files
	    dumpProperties();
           // now init the identity resolver
           setIdentityResolver(identityResolverFactory.getIdentityResolver());
           // start
           start();
	}
}
 
Example #28
Source File: PublishedEventsParameterResolver.java    From moduliths with Apache License 2.0 5 votes vote down vote up
@Override
public void onApplicationEvent(ApplicationEvent event) {

	ApplicationListener<ApplicationEvent> listener = delegate.get();

	if (listener != null) {
		listener.onApplicationEvent(event);
	}
}
 
Example #29
Source File: StarterHmilyTransactionHandler.java    From hmily with Apache License 2.0 5 votes vote down vote up
@Override
public void onApplicationEvent(ApplicationEvent applicationEvent) {
    if (hmilyConfig.getStarted()) {
        disruptorProviderManage = new DisruptorProviderManage<>(new HmilyConsumerTransactionDataHandler(),
                hmilyConfig.getAsyncThreads(),
                DisruptorProviderManage.DEFAULT_SIZE);
        disruptorProviderManage.startup();
    }
}
 
Example #30
Source File: SourceFilteringListener.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
/**
 * Actually process the event, after having filtered according to the
 * desired event source already.
 * <p>The default implementation invokes the specified delegate, if any.
 * @param event the event to process (matching the specified source)
 */
protected void onApplicationEventInternal(ApplicationEvent event) {
	if (this.delegate == null) {
		throw new IllegalStateException(
				"Must specify a delegate object or override the onApplicationEventInternal method");
	}
	this.delegate.onApplicationEvent(event);
}