类org.springframework.context.ApplicationEvent源码实例Demo

下面列出了怎么用org.springframework.context.ApplicationEvent的API类实例代码及写法,或者点击链接到github查看源代码。

源代码1 项目: jstarcraft-core   文件: BerkeleyAccessorFactory.java
@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;
    }
}
 
@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());
    }
}
 
源代码3 项目: alfresco-remote-api   文件: RepositoryContainer.java
@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());
        }
    }
}
 
@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();
                }
            }
        }
    }
}
 
源代码5 项目: chassis   文件: ChassisConfiguration.java
@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);
        }
    }
}
 
/**
 * 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};
}
 
源代码7 项目: haven-platform   文件: BalancerConfiguration.java
/**
 * 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); }
    };
}
 
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;
}
 
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);
}
 
源代码10 项目: flow-platform-x   文件: AppConfig.java
@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;
}
 
@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());
}
 
源代码12 项目: hawkbit   文件: DelayedEventBusPushStrategy.java
/**
 * 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);
}
 
@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"));
}
 
源代码14 项目: alfresco-repository   文件: ModuleStarter.java
@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());       
}
 
/**
 * 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};
	}
}
 
/**
 * 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);
}
 
@Override
public void onApplicationEvent(ApplicationEvent event) {
    if (event instanceof ServiceBeanExportedEvent) {
        onServiceBeanExportEvent((ServiceBeanExportedEvent) event);
    } else if (event instanceof ContextRefreshedEvent) {
        onContextRefreshedEvent((ContextRefreshedEvent) event);
    }
}
 
源代码18 项目: genie   文件: GenieEventBusImpl.java
/**
 * {@inheritDoc}
 */
@Override
public void multicastEvent(final ApplicationEvent event) {
    // TODO: Metric here?
    log.debug("Multi-casting event {}", event);
    this.asyncMulticaster.multicastEvent(event);
}
 
public void onApplicationEvent(ApplicationEvent event) {

        if (event instanceof ApplicationReadyEvent) {
            Runnable startupHook = getPlatformField(Runnable.class, "startupHook");
            if (startupHook != null) {
                startupHook.run();
            }
        } else if (event instanceof ContextStoppedEvent) {
            Runnable shutdownHook = getPlatformField(Runnable.class, "shutdownHook");
            if (shutdownHook != null) {
                shutdownHook.run();
            }
        }
    }
 
@Test
public void shouldDispatchDiscoveredEventsOnFirstHeartbeatEvent() {
	when(this.discoveryClient.getServices()).thenReturn(Collections.singletonList("a"));
	ServiceInstance serviceInstance = new DefaultServiceInstance("a-1", "a", "host", 8080, false);
	when(this.discoveryClient.getInstances("a")).thenReturn(Collections.singletonList(serviceInstance));

	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, times(2)).publishEvent(this.applicationEventArgumentCaptor.capture());
	verifyNoMoreInteractions(this.publisher);
	List<ApplicationEvent> applicationEvents = this.applicationEventArgumentCaptor.getAllValues();

	ApplicationEvent event = applicationEvents.get(0);
	assertThat(event).isInstanceOfSatisfying(ServiceDiscovered.class,
			e -> assertThat(e.getSource()).isEqualTo("a"));

	event = applicationEvents.get(1);
	assertThat(event).isInstanceOfSatisfying(ServiceInstanceDiscovered.class,
			e -> assertThat(e.getSource()).isEqualTo(serviceInstance));
}
 
源代码21 项目: cuba   文件: WebEvents.java
@Override
public void publish(ApplicationEvent event) {
    // check if we have active UI
    if (event instanceof UiEvent) {
        AppUI ui = AppUI.getCurrent();
        if (ui != null) {
            ui.getUiEventsMulticaster().multicastEvent(event);
        } else {
            throw new IllegalStateException("UiEvent cannot be sent since there is no active UI instance");
        }
    } else {
        super.publish(event);
    }
}
 
private boolean shouldHandle(ApplicationEvent event, @Nullable Object[] args) {
	if (args == null) {
		return false;
	}
	String condition = getCondition();
	if (StringUtils.hasText(condition)) {
		Assert.notNull(this.evaluator, "EventExpressionEvaluator must not be null");
		return this.evaluator.condition(
				condition, event, this.targetMethod, this.methodKey, args, this.applicationContext);
	}
	return true;
}
 
@Override
public void onApplicationEvent(ApplicationEvent event) {
    if (event instanceof ApplicationReadyEvent) {
        onApplicationReadyEvent((ApplicationReadyEvent) event);
    } else if (event instanceof ContextClosedEvent) {
        onContextClosedEvent((ContextClosedEvent) event);
    }
}
 
@Test
public void invokeListenerInvalidProxy() {
	Object target = new InvalidProxyTestBean();
	ProxyFactory proxyFactory = new ProxyFactory();
	proxyFactory.setTarget(target);
	proxyFactory.addInterface(SimpleService.class);
	Object bean = proxyFactory.getProxy(getClass().getClassLoader());

	Method method = ReflectionUtils.findMethod(InvalidProxyTestBean.class, "handleIt2", ApplicationEvent.class);
	StaticApplicationListenerMethodAdapter listener =
			new StaticApplicationListenerMethodAdapter(method, bean);
	thrown.expect(IllegalStateException.class);
	thrown.expectMessage("handleIt2");
	listener.onApplicationEvent(createGenericTestEvent("test"));
}
 
@Override
@SuppressWarnings("unchecked")
public boolean supportsEventType(ResolvableType eventType) {
	if (this.delegate instanceof SmartApplicationListener) {
		Class<? extends ApplicationEvent> eventClass = (Class<? extends ApplicationEvent>) eventType.getRawClass();
		return ((SmartApplicationListener) this.delegate).supportsEventType(eventClass);
	}
	else {
		return (this.declaredEventType == null || this.declaredEventType.isAssignableFrom(eventType));
	}
}
 
源代码26 项目: webanno   文件: SuccessfulLoginListener.java
@Override
public void onApplicationEvent(ApplicationEvent aEvent)
{
    if (aEvent instanceof AuthenticationSuccessEvent)
    {
        AuthenticationSuccessEvent event = (AuthenticationSuccessEvent) aEvent;
        User user = userRepository.get(event.getAuthentication().getName());
        user.setLastLogin(new Date(event.getTimestamp()));
        userRepository.update(user);
    }
}
 
源代码27 项目: lams   文件: SimpleApplicationEventMulticaster.java
/**
 * Invoke the given listener with the given event.
 * @param listener the ApplicationListener to invoke
 * @param event the current event to propagate
 * @since 4.1
 */
protected void invokeListener(ApplicationListener<?> listener, ApplicationEvent event) {
	ErrorHandler errorHandler = getErrorHandler();
	if (errorHandler != null) {
		try {
			doInvokeListener(listener, event);
		}
		catch (Throwable err) {
			errorHandler.handleError(err);
		}
	}
	else {
		doInvokeListener(listener, event);
	}
}
 
/**
 * 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);
}
 
@Test
public void simpleApplicationEventMulticasterWithErrorHandler() {
	@SuppressWarnings("unchecked")
	ApplicationListener<ApplicationEvent> listener = mock(ApplicationListener.class);
	ApplicationEvent evt = new ContextClosedEvent(new StaticApplicationContext());

	SimpleApplicationEventMulticaster smc = new SimpleApplicationEventMulticaster();
	smc.setErrorHandler(TaskUtils.LOG_AND_SUPPRESS_ERROR_HANDLER);
	smc.addApplicationListener(listener);

	willThrow(new RuntimeException()).given(listener).onApplicationEvent(evt);
	smc.multicastEvent(evt);
}
 
/**
 * Process the specified {@link ApplicationEvent}, checking if the condition
 * matches and handling a 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");
		}
	}
}
 
 类方法
 同包方法