Here are the examples of the java api org.springframework.context.ApplicationEventPublisher taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
753 Examples
19
View Source File : CustomizePublisher.java
License : Apache License 2.0
Project Creator : zq2599
License : Apache License 2.0
Project Creator : zq2599
/**
* @Description : 自定义的广播发送器
* @Author : [email protected]
* @Date : 2018-08-16 06:09
*/
@Service
public clreplaced CustomizePublisher implements ApplicationEventPublisherAware, ApplicationContextAware {
private ApplicationEventPublisher applicationEventPublisher;
private ApplicationContext applicationContext;
@Override
public void setApplicationEventPublisher(ApplicationEventPublisher applicationEventPublisher) {
this.applicationEventPublisher = applicationEventPublisher;
Utils.printTrack("applicationEventPublisher is set : " + applicationEventPublisher);
}
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext = applicationContext;
}
/**
* 发送一条广播
*/
public void publishEvent() {
applicationEventPublisher.publishEvent(new CustomizeEvent(applicationContext));
}
}
19
View Source File : DynamicRouteService.java
License : Apache License 2.0
Project Creator : zhangdaiscott
License : Apache License 2.0
Project Creator : zhangdaiscott
@Override
public void setApplicationEventPublisher(ApplicationEventPublisher applicationEventPublisher) {
this.publisher = applicationEventPublisher;
}
19
View Source File : ZeebeClientLifecycle.java
License : Apache License 2.0
Project Creator : zeebe-io
License : Apache License 2.0
Project Creator : zeebe-io
public clreplaced ZeebeClientLifecycle extends ZeebeAutoStartUpLifecycle<ZeebeClient> implements ZeebeClient {
public static final int PHASE = 22222;
private final ApplicationEventPublisher publisher;
private final Set<Consumer<ZeebeClient>> startListener = new LinkedHashSet<>();
public ZeebeClientLifecycle(final ZeebeClientObjectFactory factory, final ApplicationEventPublisher publisher) {
super(PHASE, factory);
this.publisher = publisher;
}
public ZeebeClientLifecycle addStartListener(final Consumer<ZeebeClient> consumer) {
startListener.add(consumer);
return this;
}
@Override
public void start() {
super.start();
publisher.publishEvent(new ClientStartedEvent());
startListener.forEach(c -> c.accept(this));
}
@Override
public ZeebeClientConfiguration getConfiguration() {
return get().getConfiguration();
}
@Override
public void close() {
// needed to fulfill the ZeebeClient Interface
stop();
}
@Override
public TopologyRequestStep1 newTopologyRequest() {
return get().newTopologyRequest();
}
@Override
public DeployWorkflowCommandStep1 newDeployCommand() {
return get().newDeployCommand();
}
@Override
public CreateWorkflowInstanceCommandStep1 newCreateInstanceCommand() {
return get().newCreateInstanceCommand();
}
@Override
public CancelWorkflowInstanceCommandStep1 newCancelInstanceCommand(long workflowInstanceKey) {
return get().newCancelInstanceCommand(workflowInstanceKey);
}
@Override
public SetVariablesCommandStep1 newSetVariablesCommand(long elementInstanceKey) {
return get().newSetVariablesCommand(elementInstanceKey);
}
@Override
public PublishMessageCommandStep1 newPublishMessageCommand() {
return get().newPublishMessageCommand();
}
@Override
public ResolveIncidentCommandStep1 newResolveIncidentCommand(long incidentKey) {
return get().newResolveIncidentCommand(incidentKey);
}
@Override
public UpdateRetriesJobCommandStep1 newUpdateRetriesCommand(long jobKey) {
return get().newUpdateRetriesCommand(jobKey);
}
@Override
public JobWorkerBuilderStep1 newWorker() {
return get().newWorker();
}
@Override
public ActivateJobsCommandStep1 newActivateJobsCommand() {
return get().newActivateJobsCommand();
}
@Override
public CompleteJobCommandStep1 newCompleteCommand(long jobKey) {
return get().newCompleteCommand(jobKey);
}
@Override
public FailJobCommandStep1 newFailCommand(long jobKey) {
return get().newFailCommand(jobKey);
}
@Override
public ThrowErrorCommandStep1 newThrowErrorCommand(long jobKey) {
return get().newThrowErrorCommand(jobKey);
}
}
19
View Source File : AwareBean.java
License : MIT License
Project Creator : yuriytkach
License : MIT License
Project Creator : yuriytkach
public clreplaced AwareBean implements ApplicationContextAware, BeanNameAware, ApplicationEventPublisherAware {
private ApplicationEventPublisher eventPublisher;
private String name;
private ApplicationContext ctx;
public void init() {
System.out.println(this.getClreplaced().getSimpleName() + " > My name is '" + name + "'");
if (ctx != null) {
System.out.println(this.getClreplaced().getSimpleName() + " > My context is " + ctx.getClreplaced().toString());
} else {
System.out.println(this.getClreplaced().getSimpleName() + " > Context is not set");
}
if (eventPublisher != null) {
System.out.println(this.getClreplaced().getSimpleName() + " > My eventPublisher is " + eventPublisher.getClreplaced().toString());
} else {
System.out.println(this.getClreplaced().getSimpleName() + " > EventPublisher is not set");
}
}
@Override
public void setApplicationEventPublisher(ApplicationEventPublisher ep) {
this.eventPublisher = ep;
}
@Override
public void setBeanName(String name) {
this.name = name;
}
@Override
public void setApplicationContext(ApplicationContext context) throws BeansException {
this.ctx = context;
}
}
19
View Source File : AwareBean.java
License : MIT License
Project Creator : yuriytkach
License : MIT License
Project Creator : yuriytkach
@Override
public void setApplicationEventPublisher(ApplicationEventPublisher ep) {
this.eventPublisher = ep;
}
19
View Source File : AuthorizationAuditListenerTests.java
License : Apache License 2.0
Project Creator : yuanmabiji
License : Apache License 2.0
Project Creator : yuanmabiji
/**
* Tests for {@link AuthorizationAuditListener}.
*/
public clreplaced AuthorizationAuditListenerTests {
private final AuthorizationAuditListener listener = new AuthorizationAuditListener();
private final ApplicationEventPublisher publisher = mock(ApplicationEventPublisher.clreplaced);
@Before
public void init() {
this.listener.setApplicationEventPublisher(this.publisher);
}
@Test
public void testAuthenticationCredentialsNotFound() {
AuditApplicationEvent event = handleAuthorizationEvent(new AuthenticationCredentialsNotFoundEvent(this, Collections.singletonList(new SecurityConfig("USER")), new AuthenticationCredentialsNotFoundException("Bad user")));
replacedertThat(event.getAuditEvent().getType()).isEqualTo(AuthenticationAuditListener.AUTHENTICATION_FAILURE);
}
@Test
public void testAuthorizationFailure() {
AuditApplicationEvent event = handleAuthorizationEvent(new AuthorizationFailureEvent(this, Collections.singletonList(new SecurityConfig("USER")), new UsernamePreplacedwordAuthenticationToken("user", "preplacedword"), new AccessDeniedException("Bad user")));
replacedertThat(event.getAuditEvent().getType()).isEqualTo(AuthorizationAuditListener.AUTHORIZATION_FAILURE);
}
@Test
public void testDetailsAreIncludedInAuditEvent() {
Object details = new Object();
UsernamePreplacedwordAuthenticationToken authentication = new UsernamePreplacedwordAuthenticationToken("user", "preplacedword");
authentication.setDetails(details);
AuditApplicationEvent event = handleAuthorizationEvent(new AuthorizationFailureEvent(this, Collections.singletonList(new SecurityConfig("USER")), authentication, new AccessDeniedException("Bad user")));
replacedertThat(event.getAuditEvent().getType()).isEqualTo(AuthorizationAuditListener.AUTHORIZATION_FAILURE);
replacedertThat(event.getAuditEvent().getData()).containsEntry("details", details);
}
private AuditApplicationEvent handleAuthorizationEvent(AbstractAuthorizationEvent event) {
ArgumentCaptor<AuditApplicationEvent> eventCaptor = ArgumentCaptor.forClreplaced(AuditApplicationEvent.clreplaced);
this.listener.onApplicationEvent(event);
verify(this.publisher).publishEvent(eventCaptor.capture());
return eventCaptor.getValue();
}
}
19
View Source File : AuthenticationAuditListenerTests.java
License : Apache License 2.0
Project Creator : yuanmabiji
License : Apache License 2.0
Project Creator : yuanmabiji
/**
* Tests for {@link AuthenticationAuditListener}.
*/
public clreplaced AuthenticationAuditListenerTests {
private final AuthenticationAuditListener listener = new AuthenticationAuditListener();
private final ApplicationEventPublisher publisher = mock(ApplicationEventPublisher.clreplaced);
@Before
public void init() {
this.listener.setApplicationEventPublisher(this.publisher);
}
@Test
public void testAuthenticationSuccess() {
AuditApplicationEvent event = handleAuthenticationEvent(new AuthenticationSuccessEvent(new UsernamePreplacedwordAuthenticationToken("user", "preplacedword")));
replacedertThat(event.getAuditEvent().getType()).isEqualTo(AuthenticationAuditListener.AUTHENTICATION_SUCCESS);
}
@Test
public void testOtherAuthenticationSuccess() {
this.listener.onApplicationEvent(new InteractiveAuthenticationSuccessEvent(new UsernamePreplacedwordAuthenticationToken("user", "preplacedword"), getClreplaced()));
// No need to audit this one (it shadows a regular AuthenticationSuccessEvent)
verify(this.publisher, never()).publishEvent(any(ApplicationEvent.clreplaced));
}
@Test
public void testAuthenticationFailed() {
AuditApplicationEvent event = handleAuthenticationEvent(new AuthenticationFailureExpiredEvent(new UsernamePreplacedwordAuthenticationToken("user", "preplacedword"), new BadCredentialsException("Bad user")));
replacedertThat(event.getAuditEvent().getType()).isEqualTo(AuthenticationAuditListener.AUTHENTICATION_FAILURE);
}
@Test
public void testAuthenticationSwitch() {
AuditApplicationEvent event = handleAuthenticationEvent(new AuthenticationSwitchUserEvent(new UsernamePreplacedwordAuthenticationToken("user", "preplacedword"), new User("user", "preplacedword", AuthorityUtils.commaSeparatedStringToAuthorityList("USER"))));
replacedertThat(event.getAuditEvent().getType()).isEqualTo(AuthenticationAuditListener.AUTHENTICATION_SWITCH);
}
@Test
public void testDetailsAreIncludedInAuditEvent() {
Object details = new Object();
UsernamePreplacedwordAuthenticationToken authentication = new UsernamePreplacedwordAuthenticationToken("user", "preplacedword");
authentication.setDetails(details);
AuditApplicationEvent event = handleAuthenticationEvent(new AuthenticationFailureExpiredEvent(authentication, new BadCredentialsException("Bad user")));
replacedertThat(event.getAuditEvent().getType()).isEqualTo(AuthenticationAuditListener.AUTHENTICATION_FAILURE);
replacedertThat(event.getAuditEvent().getData()).containsEntry("details", details);
}
private AuditApplicationEvent handleAuthenticationEvent(AbstractAuthenticationEvent event) {
ArgumentCaptor<AuditApplicationEvent> eventCaptor = ArgumentCaptor.forClreplaced(AuditApplicationEvent.clreplaced);
this.listener.onApplicationEvent(event);
verify(this.publisher).publishEvent(eventCaptor.capture());
return eventCaptor.getValue();
}
}
19
View Source File : AbstractAuthorizationAuditListener.java
License : Apache License 2.0
Project Creator : yuanmabiji
License : Apache License 2.0
Project Creator : yuanmabiji
/**
* Abstract {@link ApplicationListener} to expose Spring Security
* {@link AbstractAuthorizationEvent authorization events} as {@link AuditEvent}s.
*
* @author Dave Syer
* @author Vedran Pavic
* @since 1.3.0
*/
public abstract clreplaced AbstractAuthorizationAuditListener implements ApplicationListener<AbstractAuthorizationEvent>, ApplicationEventPublisherAware {
private ApplicationEventPublisher publisher;
@Override
public void setApplicationEventPublisher(ApplicationEventPublisher publisher) {
this.publisher = publisher;
}
protected ApplicationEventPublisher getPublisher() {
return this.publisher;
}
protected void publish(AuditEvent event) {
if (getPublisher() != null) {
getPublisher().publishEvent(new AuditApplicationEvent(event));
}
}
}
19
View Source File : AbstractAuthenticationAuditListener.java
License : Apache License 2.0
Project Creator : yuanmabiji
License : Apache License 2.0
Project Creator : yuanmabiji
/**
* Abstract {@link ApplicationListener} to expose Spring Security
* {@link AbstractAuthenticationEvent authentication events} as {@link AuditEvent}s.
*
* @author Dave Syer
* @author Vedran Pavic
* @since 1.3.0
*/
public abstract clreplaced AbstractAuthenticationAuditListener implements ApplicationListener<AbstractAuthenticationEvent>, ApplicationEventPublisherAware {
private ApplicationEventPublisher publisher;
@Override
public void setApplicationEventPublisher(ApplicationEventPublisher publisher) {
this.publisher = publisher;
}
protected ApplicationEventPublisher getPublisher() {
return this.publisher;
}
protected void publish(AuditEvent event) {
if (getPublisher() != null) {
getPublisher().publishEvent(new AuditApplicationEvent(event));
}
}
}
19
View Source File : ApplicationLepProcessingEventPublisher.java
License : Apache License 2.0
Project Creator : xm-online
License : Apache License 2.0
Project Creator : xm-online
/**
* The {@link ApplicationLepProcessingEventPublisher} clreplaced.
*/
public clreplaced ApplicationLepProcessingEventPublisher implements LepProcessingListener {
private final ApplicationEventPublisher publisher;
public ApplicationLepProcessingEventPublisher(ApplicationEventPublisher publisher) {
this.publisher = Objects.requireNonNull(publisher, "publisher can't be null");
}
/**
* {@inheritDoc}
*/
@Override
public void accept(LepProcessingEvent lepProcessingEvent) {
ApplicationLepProcessingEvent springAppEvent = new ApplicationLepProcessingEvent(lepProcessingEvent);
publisher.publishEvent(springAppEvent);
}
}
19
View Source File : DynamicRouteServiceImpl.java
License : MIT License
Project Creator : xk11961677
License : MIT License
Project Creator : xk11961677
/**
* @author
* @description 动态路由实现
*/
@Service
public clreplaced DynamicRouteServiceImpl implements ApplicationEventPublisherAware {
@Override
public void setApplicationEventPublisher(ApplicationEventPublisher applicationEventPublisher) {
}
@Autowired
private RouteDefinitionWriter routeDefinitionWriter;
@Autowired
private ApplicationEventPublisher publisher;
/**
* 增加路由
*
* @param definition
* @return
*/
public String add(RouteDefinition definition) {
routeDefinitionWriter.save(Mono.just(definition)).subscribe();
this.publisher.publishEvent(new RefreshRoutesEvent(this));
return "success";
}
/**
* 更新路由
*
* @param definition
* @return
*/
public String update(RouteDefinition definition) {
// 移除原有路由配置
try {
this.routeDefinitionWriter.delete(Mono.just(definition.getId()));
} catch (Exception e) {
return "update fail, not find route routeId: " + definition.getId();
}
// 保存新的路由配置
try {
routeDefinitionWriter.save(Mono.just(definition)).subscribe();
this.publisher.publishEvent(new RefreshRoutesEvent(this));
return "success";
} catch (Exception e) {
return "update route fail";
}
}
/**
* 删除路由
*
* @param id
* @return
*/
public Mono<ResponseEnreplacedy<Object>> delete(String id) {
return this.routeDefinitionWriter.delete(Mono.just(id)).then(Mono.defer(() -> Mono.just(ResponseEnreplacedy.ok().build()))).onErrorResume(t -> t instanceof NotFoundException, t -> Mono.just(ResponseEnreplacedy.notFound().build()));
}
}
19
View Source File : DynamicRouteServiceImpl.java
License : MIT License
Project Creator : xk11961677
License : MIT License
Project Creator : xk11961677
@Override
public void setApplicationEventPublisher(ApplicationEventPublisher applicationEventPublisher) {
}
19
View Source File : RouteService.java
License : MIT License
Project Creator : xiuhuai
License : MIT License
Project Creator : xiuhuai
/**
* 动态路由服务
*/
@Service
public clreplaced RouteService implements ApplicationEventPublisherAware {
@Autowired
private RouteDefinitionWriter routeDefinitionWriter;
private ApplicationEventPublisher publisher;
@Override
public void setApplicationEventPublisher(ApplicationEventPublisher applicationEventPublisher) {
this.publisher = applicationEventPublisher;
}
// 更新路由
public String update(RouteDefinition definition) {
try {
delete(definition.getId());
} catch (Exception e) {
return "失败,没有找到Id: " + definition.getId();
}
try {
routeDefinitionWriter.save(Mono.just(definition)).subscribe();
this.publisher.publishEvent(new RefreshRoutesEvent(this));
return "success";
} catch (Exception e) {
return "失败";
}
}
// 删除路由
public Mono<ResponseEnreplacedy<Object>> delete(String id) {
return this.routeDefinitionWriter.delete(Mono.just(id)).then(Mono.defer(() -> {
return Mono.just(ResponseEnreplacedy.ok().build());
})).onErrorResume((t) -> {
return t instanceof NotFoundException;
}, (t) -> {
return Mono.just(ResponseEnreplacedy.notFound().build());
});
}
}
19
View Source File : DynamicRouteService.java
License : MIT License
Project Creator : wells2333
License : MIT License
Project Creator : wells2333
/**
* 动态路由Service
*
* @author tangyi
* @date 2019/3/27 10:59
*/
@Service
public clreplaced DynamicRouteService implements ApplicationEventPublisherAware {
private final RouteDefinitionWriter routeDefinitionWriter;
private ApplicationEventPublisher applicationEventPublisher;
@Autowired
public DynamicRouteService(RouteDefinitionWriter routeDefinitionWriter) {
this.routeDefinitionWriter = routeDefinitionWriter;
}
@Override
public void setApplicationEventPublisher(ApplicationEventPublisher applicationEventPublisher) {
this.applicationEventPublisher = applicationEventPublisher;
}
/**
* 增加路由
*
* @param definition definition
* @return String
*/
public String add(RouteDefinition definition) {
routeDefinitionWriter.save(Mono.just(definition)).subscribe();
this.applicationEventPublisher.publishEvent(new RefreshRoutesEvent(this));
return "success";
}
/**
* 更新路由
*
* @param definition definition
* @return String
*/
public String update(RouteDefinition definition) {
try {
this.routeDefinitionWriter.delete(Mono.just(definition.getId()));
} catch (Exception e) {
return "update fail,not find route routeId: " + definition.getId();
}
try {
routeDefinitionWriter.save(Mono.just(definition)).subscribe();
this.applicationEventPublisher.publishEvent(new RefreshRoutesEvent(this));
return "success";
} catch (Exception e) {
return "update route fail";
}
}
/**
* 删除路由
*
* @param id id
* @return Mono
*/
public Mono<ResponseEnreplacedy<Object>> delete(Long id) {
return this.routeDefinitionWriter.delete(Mono.just(String.valueOf(id))).then(Mono.defer(() -> Mono.just(ResponseEnreplacedy.ok().build()))).onErrorResume(t -> t instanceof NotFoundException, t -> Mono.just(ResponseEnreplacedy.notFound().build()));
}
}
19
View Source File : JdbcRepositoryFactoryBean.java
License : Apache License 2.0
Project Creator : VonChange
License : Apache License 2.0
Project Creator : VonChange
/*
* (non-Javadoc)
* @see org.springframework.data.repository.core.support.RepositoryFactoryBeanSupport#setApplicationEventPublisher(org.springframework.context.ApplicationEventPublisher)
*/
@Override
public void setApplicationEventPublisher(ApplicationEventPublisher publisher) {
super.setApplicationEventPublisher(publisher);
}
19
View Source File : StompSubProtocolHandler.java
License : MIT License
Project Creator : Vip-Augus
License : MIT License
Project Creator : Vip-Augus
@Override
public void setApplicationEventPublisher(ApplicationEventPublisher applicationEventPublisher) {
this.eventPublisher = applicationEventPublisher;
}
19
View Source File : StompSubProtocolHandler.java
License : MIT License
Project Creator : Vip-Augus
License : MIT License
Project Creator : Vip-Augus
private void publishEvent(ApplicationEventPublisher publisher, ApplicationEvent event) {
try {
publisher.publishEvent(event);
} catch (Throwable ex) {
if (logger.isErrorEnabled()) {
logger.error("Error publishing " + event, ex);
}
}
}
19
View Source File : AbstractBrokerMessageHandler.java
License : MIT License
Project Creator : Vip-Augus
License : MIT License
Project Creator : Vip-Augus
@Override
public void setApplicationEventPublisher(@Nullable ApplicationEventPublisher publisher) {
this.eventPublisher = publisher;
}
19
View Source File : EventPublicationInterceptorTests.java
License : MIT License
Project Creator : Vip-Augus
License : MIT License
Project Creator : Vip-Augus
/**
* @author Dmitriy Kopylenko
* @author Juergen Hoeller
* @author Rick Evans
*/
public clreplaced EventPublicationInterceptorTests {
private ApplicationEventPublisher publisher;
@Before
public void setUp() {
this.publisher = mock(ApplicationEventPublisher.clreplaced);
}
@Test(expected = IllegalArgumentException.clreplaced)
public void testWithNoApplicationEventClreplacedSupplied() throws Exception {
EventPublicationInterceptor interceptor = new EventPublicationInterceptor();
interceptor.setApplicationEventPublisher(this.publisher);
interceptor.afterPropertiesSet();
}
@Test(expected = IllegalArgumentException.clreplaced)
public void testWithNonApplicationEventClreplacedSupplied() throws Exception {
EventPublicationInterceptor interceptor = new EventPublicationInterceptor();
interceptor.setApplicationEventPublisher(this.publisher);
interceptor.setApplicationEventClreplaced(getClreplaced());
interceptor.afterPropertiesSet();
}
@Test(expected = IllegalArgumentException.clreplaced)
public void testWithAbstractStraightApplicationEventClreplacedSupplied() throws Exception {
EventPublicationInterceptor interceptor = new EventPublicationInterceptor();
interceptor.setApplicationEventPublisher(this.publisher);
interceptor.setApplicationEventClreplaced(ApplicationEvent.clreplaced);
interceptor.afterPropertiesSet();
}
@Test(expected = IllegalArgumentException.clreplaced)
public void testWithApplicationEventClreplacedThatDoesntExposeAValidCtor() throws Exception {
EventPublicationInterceptor interceptor = new EventPublicationInterceptor();
interceptor.setApplicationEventPublisher(this.publisher);
interceptor.setApplicationEventClreplaced(TestEventWithNoValidOneArgObjectCtor.clreplaced);
interceptor.afterPropertiesSet();
}
@Test
public void testExpectedBehavior() throws Exception {
TestBean target = new TestBean();
final TestListener listener = new TestListener();
clreplaced TestContext extends StaticApplicationContext {
@Override
protected void onRefresh() throws BeansException {
addApplicationListener(listener);
}
}
StaticApplicationContext ctx = new TestContext();
MutablePropertyValues pvs = new MutablePropertyValues();
pvs.add("applicationEventClreplaced", TestEvent.clreplaced.getName());
// should automatically receive applicationEventPublisher reference
ctx.registerSingleton("publisher", EventPublicationInterceptor.clreplaced, pvs);
ctx.registerSingleton("otherListener", FactoryBeanTestListener.clreplaced);
ctx.refresh();
EventPublicationInterceptor interceptor = (EventPublicationInterceptor) ctx.getBean("publisher");
ProxyFactory factory = new ProxyFactory(target);
factory.addAdvice(0, interceptor);
ITestBean testBean = (ITestBean) factory.getProxy();
// invoke any method on the advised proxy to see if the interceptor has been invoked
testBean.getAge();
// two events: ContextRefreshedEvent and TestEvent
replacedertTrue("Interceptor must have published 2 events", listener.getEventCount() == 2);
TestListener otherListener = (TestListener) ctx.getBean("&otherListener");
replacedertTrue("Interceptor must have published 2 events", otherListener.getEventCount() == 2);
}
@SuppressWarnings("serial")
public static final clreplaced TestEventWithNoValidOneArgObjectCtor extends ApplicationEvent {
public TestEventWithNoValidOneArgObjectCtor() {
super("");
}
}
public static clreplaced FactoryBeanTestListener extends TestListener implements FactoryBean<Object> {
@Override
public Object getObject() {
return "test";
}
@Override
public Clreplaced<String> getObjectType() {
return String.clreplaced;
}
@Override
public boolean isSingleton() {
return true;
}
}
}
19
View Source File : EventPublicationInterceptor.java
License : MIT License
Project Creator : Vip-Augus
License : MIT License
Project Creator : Vip-Augus
/**
* {@link MethodInterceptor Interceptor} that publishes an
* {@code ApplicationEvent} to all {@code ApplicationListeners}
* registered with an {@code ApplicationEventPublisher} after each
* <i>successful</i> method invocation.
*
* <p>Note that this interceptor is only capable of publishing <i>stateless</i>
* events configured via the
* {@link #setApplicationEventClreplaced "applicationEventClreplaced"} property.
*
* @author Dmitriy Kopylenko
* @author Juergen Hoeller
* @author Rick Evans
* @see #setApplicationEventClreplaced
* @see org.springframework.context.ApplicationEvent
* @see org.springframework.context.ApplicationListener
* @see org.springframework.context.ApplicationEventPublisher
* @see org.springframework.context.ApplicationContext
*/
public clreplaced EventPublicationInterceptor implements MethodInterceptor, ApplicationEventPublisherAware, InitializingBean {
@Nullable
private Constructor<?> applicationEventClreplacedConstructor;
@Nullable
private ApplicationEventPublisher applicationEventPublisher;
/**
* Set the application event clreplaced to publish.
* <p>The event clreplaced <b>must</b> have a constructor with a single
* {@code Object} argument for the event source. The interceptor
* will preplaced in the invoked object.
* @throws IllegalArgumentException if the supplied {@code Clreplaced} is
* {@code null} or if it is not an {@code ApplicationEvent} subclreplaced or
* if it does not expose a constructor that takes a single {@code Object} argument
*/
public void setApplicationEventClreplaced(Clreplaced<?> applicationEventClreplaced) {
if (ApplicationEvent.clreplaced == applicationEventClreplaced || !ApplicationEvent.clreplaced.isreplacedignableFrom(applicationEventClreplaced)) {
throw new IllegalArgumentException("'applicationEventClreplaced' needs to extend ApplicationEvent");
}
try {
this.applicationEventClreplacedConstructor = applicationEventClreplaced.getConstructor(Object.clreplaced);
} catch (NoSuchMethodException ex) {
throw new IllegalArgumentException("ApplicationEvent clreplaced [" + applicationEventClreplaced.getName() + "] does not have the required Object constructor: " + ex);
}
}
@Override
public void setApplicationEventPublisher(ApplicationEventPublisher applicationEventPublisher) {
this.applicationEventPublisher = applicationEventPublisher;
}
@Override
public void afterPropertiesSet() throws Exception {
if (this.applicationEventClreplacedConstructor == null) {
throw new IllegalArgumentException("Property 'applicationEventClreplaced' is required");
}
}
@Override
public Object invoke(MethodInvocation invocation) throws Throwable {
Object retVal = invocation.proceed();
replacedert.state(this.applicationEventClreplacedConstructor != null, "No ApplicationEvent clreplaced set");
ApplicationEvent event = (ApplicationEvent) this.applicationEventClreplacedConstructor.newInstance(invocation.getThis());
replacedert.state(this.applicationEventPublisher != null, "No ApplicationEventPublisher available");
this.applicationEventPublisher.publishEvent(event);
return retVal;
}
}
19
View Source File : CoapShellCommands.java
License : Apache License 2.0
Project Creator : tzolov
License : Apache License 2.0
Project Creator : tzolov
@Override
public void setApplicationEventPublisher(ApplicationEventPublisher applicationEventPublisher) {
eventPublisher = applicationEventPublisher;
}
19
View Source File : ProcessTailInboundChannelAdapterFactoryBean.java
License : MIT License
Project Creator : Toparvion
License : MIT License
Project Creator : Toparvion
/**
* @author Gary Russell
* @author Artem Bilan
* @author Ali Shahbour
* @author Vladimir Plizga
* @since 3.0
*/
public clreplaced ProcessTailInboundChannelAdapterFactoryBean extends AbstractFactoryBean<FileTailingMessageProducerSupport> implements BeanNameAware, SmartLifecycle, ApplicationEventPublisherAware {
private volatile String nativeOptions;
private volatile boolean enableStatusReader = true;
private volatile Long idleEventInterval;
private volatile String executbale;
private volatile File file;
private volatile TaskExecutor taskExecutor;
private volatile TaskScheduler taskScheduler;
private volatile Long fileDelay;
private volatile FileTailingMessageProducerSupport adapter;
private volatile String beanName;
private volatile MessageChannel outputChannel;
private volatile MessageChannel errorChannel;
private volatile Boolean autoStartup;
private volatile Integer phase;
private volatile ApplicationEventPublisher applicationEventPublisher;
public void setNativeOptions(String nativeOptions) {
if (StringUtils.hasText(nativeOptions)) {
this.nativeOptions = nativeOptions;
}
}
/**
* If false, thread for capturing stderr will not be started
* and stderr output will be ignored
*
* @param enableStatusReader true or false
* @since 4.3.6
*/
public void setEnableStatusReader(boolean enableStatusReader) {
this.enableStatusReader = enableStatusReader;
}
/**
* How often to emit {@link FileTailingMessageProducerSupport.FileTailingIdleEvent}s in milliseconds.
*
* @param idleEventInterval the interval.
* @since 5.0
*/
public void setIdleEventInterval(long idleEventInterval) {
this.idleEventInterval = idleEventInterval;
}
public void setTaskExecutor(TaskExecutor taskExecutor) {
this.taskExecutor = taskExecutor;
}
public void setTaskScheduler(TaskScheduler taskScheduler) {
this.taskScheduler = taskScheduler;
}
public void setFileDelay(Long fileDelay) {
this.fileDelay = fileDelay;
}
public void setFile(File file) {
this.file = file;
}
@Override
public void setBeanName(String name) {
this.beanName = name;
}
public void setOutputChannel(MessageChannel outputChannel) {
this.outputChannel = outputChannel;
}
public void setErrorChannel(MessageChannel errorChannel) {
this.errorChannel = errorChannel;
}
public void setAutoStartup(boolean autoStartup) {
this.autoStartup = autoStartup;
}
public void setPhase(int phase) {
this.phase = phase;
}
@Override
public void setApplicationEventPublisher(ApplicationEventPublisher applicationEventPublisher) {
this.applicationEventPublisher = applicationEventPublisher;
}
@Override
public void start() {
if (this.adapter != null) {
this.adapter.start();
}
}
@Override
public void stop() {
if (this.adapter != null) {
this.adapter.stop();
}
}
@Override
public boolean isRunning() {
return this.adapter != null && this.adapter.isRunning();
}
@Override
public int getPhase() {
if (this.adapter != null) {
return this.adapter.getPhase();
}
return 0;
}
@Override
public boolean isAutoStartup() {
return this.adapter != null && this.adapter.isAutoStartup();
}
@Override
public void stop(Runnable callback) {
if (this.adapter != null) {
this.adapter.stop(callback);
} else {
callback.run();
}
}
@Override
public Clreplaced<?> getObjectType() {
return this.adapter == null ? FileTailingMessageProducerSupport.clreplaced : this.adapter.getClreplaced();
}
@Override
protected FileTailingMessageProducerSupport createInstance() throws Exception {
ProcessTailMessageProducer adapter = new ProcessTailMessageProducer();
adapter.setOptions(this.nativeOptions);
adapter.setEnableStatusReader(this.enableStatusReader);
adapter.setFile(this.file);
adapter.setExecutable(this.executbale);
if (this.taskExecutor != null) {
adapter.setTaskExecutor(this.taskExecutor);
}
if (this.taskScheduler != null) {
adapter.setTaskScheduler(this.taskScheduler);
}
if (this.fileDelay != null) {
adapter.setTailAttemptsDelay(this.fileDelay);
}
if (this.idleEventInterval != null) {
adapter.setIdleEventInterval(this.idleEventInterval);
}
adapter.setOutputChannel(this.outputChannel);
adapter.setErrorChannel(this.errorChannel);
adapter.setBeanName(this.beanName);
if (this.autoStartup != null) {
adapter.setAutoStartup(this.autoStartup);
}
if (this.phase != null) {
adapter.setPhase(this.phase);
}
if (this.applicationEventPublisher != null) {
adapter.setApplicationEventPublisher(this.applicationEventPublisher);
}
if (getBeanFactory() != null) {
adapter.setBeanFactory(getBeanFactory());
}
adapter.afterPropertiesSet();
this.adapter = adapter;
return adapter;
}
public void setExecutbale(String executbale) {
this.executbale = executbale;
}
}
19
View Source File : SpringEventPublisher.java
License : Apache License 2.0
Project Creator : SpringCloud
License : Apache License 2.0
Project Creator : SpringCloud
/**
* @author saleson
* @date 2020-05-05 13:38
*/
public clreplaced SpringEventPublisher implements ApplicationEventPublisherAware {
private ApplicationEventPublisher applicationEventPublisher;
@Override
public void setApplicationEventPublisher(ApplicationEventPublisher applicationEventPublisher) {
this.applicationEventPublisher = applicationEventPublisher;
}
public void publishEvent(ApplicationEvent event) {
applicationEventPublisher.publishEvent(event);
}
}
19
View Source File : DynamicRouteServiceImpl.java
License : Apache License 2.0
Project Creator : SpringCloud
License : Apache License 2.0
Project Creator : SpringCloud
@Service
public clreplaced DynamicRouteServiceImpl implements ApplicationEventPublisherAware {
@Autowired
private RouteDefinitionWriter routeDefinitionWriter;
private ApplicationEventPublisher publisher;
/**
* 增加路由
* @param definition
* @return
*/
public String add(RouteDefinition definition) {
routeDefinitionWriter.save(Mono.just(definition)).subscribe();
this.publisher.publishEvent(new RefreshRoutesEvent(this));
return "success";
}
/**
* 更新路由
* @param definition
* @return
*/
public String update(RouteDefinition definition) {
try {
this.routeDefinitionWriter.delete(Mono.just(definition.getId()));
} catch (Exception e) {
return "update fail,not find route routeId: " + definition.getId();
}
try {
routeDefinitionWriter.save(Mono.just(definition)).subscribe();
this.publisher.publishEvent(new RefreshRoutesEvent(this));
return "success";
} catch (Exception e) {
return "update route fail";
}
}
/**
* 删除路由
* @param id
* @return
*/
public String delete(String id) {
try {
this.routeDefinitionWriter.delete(Mono.just(id));
return "delete success";
} catch (Exception e) {
e.printStackTrace();
return "delete fail";
}
}
@Override
public void setApplicationEventPublisher(ApplicationEventPublisher applicationEventPublisher) {
this.publisher = applicationEventPublisher;
}
/**
* spring:
* cloud:
* gateway:
* routes: #当访问http://localhost:8080/baidu,直接转发到https://www.baidu.com/
* - id: baidu_route
* uri: http://baidu.com:80/
* predicates:
* - Path=/baidu
* @param args
*/
public static void main(String[] args) {
GatewayRouteDefinition definition = new GatewayRouteDefinition();
GatewayPredicateDefinition predicate = new GatewayPredicateDefinition();
Map<String, String> predicateParams = new HashMap<>(8);
definition.setId("jd_route");
predicate.setName("Path");
predicateParams.put("pattern", "/jd");
predicate.setArgs(predicateParams);
definition.setPredicates(Arrays.asList(predicate));
String uri = "http://www.jd.com";
// URI uri = UriComponentsBuilder.fromHttpUrl("http://www.baidu.com").build().toUri();
definition.setUri(uri);
System.out.println("definition:" + JSON.toJSONString(definition));
RouteDefinition definition1 = new RouteDefinition();
PredicateDefinition predicate1 = new PredicateDefinition();
Map<String, String> predicateParams1 = new HashMap<>(8);
definition1.setId("baidu_route");
predicate1.setName("Path");
predicateParams1.put("pattern", "/baidu");
predicate1.setArgs(predicateParams1);
definition1.setPredicates(Arrays.asList(predicate1));
URI uri1 = UriComponentsBuilder.fromHttpUrl("http://www.baidu.com").build().toUri();
definition1.setUri(uri1);
System.out.println("definition1:" + JSON.toJSONString(definition1));
}
}
19
View Source File : BootGeodeClientApplication.java
License : Apache License 2.0
Project Creator : spring-projects
License : Apache License 2.0
Project Creator : spring-projects
@Bean
TemperatureMonitor temperatureMonitor(ApplicationEventPublisher applicationEventPublisher) {
return new TemperatureMonitor(applicationEventPublisher);
}
19
View Source File : MultipleHopsIntegrationTests.java
License : Apache License 2.0
Project Creator : spring-cloud-incubator
License : Apache License 2.0
Project Creator : spring-cloud-incubator
@SpringBootTest(webEnvironment = RANDOM_PORT)
@ContextConfiguration(clreplacedes = MultipleHopsIntegrationTests.Config.clreplaced)
@TestPropertySource(properties = "spring.sleuth.otel.propagation.sleuth-baggage.enabled=true")
public clreplaced MultipleHopsIntegrationTests extends org.springframework.cloud.sleuth.baggage.multiple.MultipleHopsIntegrationTests {
@Autowired
MyBaggageChangedListener myBaggageChangedListener;
@Autowired
DemoApplication demoApplication;
@Autowired
ApplicationEventPublisher publisher;
// TODO: Why do we have empty names here
@Override
protected void replacedertSpanNames() {
then(this.spans).extracting(FinishedSpan::getName).containsAll(asList("HTTP GET", "handle", "send"));
}
@BeforeEach
void setUp() {
// manually set a context storage that doesn't use the standard default wrappers,
// so we can test that baggage changes get emitted as events properly.
SettableContextStorageProvider.setContextStorage(new EventPublishingContextWrapper(publisher).apply(ContextStorage.defaultStorage()));
}
@Override
protected void replacedertBaggage(Span initialSpan) {
then(this.myBaggageChangedListener.baggageChanged).as("All have request ID").filteredOn(b -> b.getBaggage() != null).filteredOn(b -> b.getBaggage().getEntryValue(REQUEST_ID) != null).isNotEmpty().allMatch(event -> "f4308d05-2228-4468-80f6-92a8377ba193".equals(event.getBaggage().getEntryValue(REQUEST_ID)));
then(this.demoApplication.getBaggageValue()).isEqualTo("FO");
}
@Configuration(proxyBeanMethods = false)
@EnableAutoConfiguration(exclude = { MongoAutoConfiguration.clreplaced, QuartzAutoConfiguration.clreplaced, JmxAutoConfiguration.clreplaced })
static clreplaced Config {
@Bean
OtelTestSpanHandler testSpanHandlerSupplier() {
return new OtelTestSpanHandler(new ArrayListSpanProcessor());
}
@Bean
Sampler alwaysSampler() {
return Sampler.alwaysOn();
}
@Bean
MyBaggageChangedListener myBaggageChangedListener() {
return new MyBaggageChangedListener();
}
}
static clreplaced MyBaggageChangedListener implements ApplicationListener<ApplicationEvent> {
Queue<EventPublishingContextWrapper.ScopeAttachedEvent> baggageChanged = new LinkedBlockingQueue<>();
@Override
public void onApplicationEvent(ApplicationEvent event) {
if (event instanceof EventPublishingContextWrapper.ScopeAttachedEvent) {
this.baggageChanged.add((EventPublishingContextWrapper.ScopeAttachedEvent) event);
}
}
}
}
19
View Source File : OtelTracer.java
License : Apache License 2.0
Project Creator : spring-cloud-incubator
License : Apache License 2.0
Project Creator : spring-cloud-incubator
/**
* OpenTelemetry implementation of a {@link Tracer}.
*
* @author Marcin Grzejszczak
* @since 1.0.0
*/
public clreplaced OtelTracer implements Tracer {
private final io.opentelemetry.api.trace.Tracer tracer;
private final BaggageManager otelBaggageManager;
private final ApplicationEventPublisher publisher;
public OtelTracer(io.opentelemetry.api.trace.Tracer tracer, ApplicationEventPublisher publisher, BaggageManager otelBaggageManager) {
this.tracer = tracer;
this.publisher = publisher;
this.otelBaggageManager = otelBaggageManager;
}
@Override
public Span nextSpan(Span parent) {
if (parent == null) {
return nextSpan();
}
return OtelSpan.fromOtel(this.tracer.spanBuilder("").setParent(OtelTraceContext.toOtelContext(parent.context())).startSpan());
}
@Override
public SpanInScope withSpan(Span span) {
io.opentelemetry.api.trace.Span delegate = delegate(span);
return new OtelSpanInScope((OtelSpan) span, delegate);
}
private io.opentelemetry.api.trace.Span delegate(Span span) {
if (span == null) {
// remove any existing span/baggage data from the current state of anything
// that might be holding on to it.
this.publisher.publishEvent(new EventPublishingContextWrapper.ScopeClosedEvent(this));
return io.opentelemetry.api.trace.Span.getInvalid();
}
return ((OtelSpan) span).delegate;
}
@Override
public SpanCustomizer currentSpanCustomizer() {
return new OtelSpanCustomizer();
}
@Override
public Span currentSpan() {
io.opentelemetry.api.trace.Span currentSpan = io.opentelemetry.api.trace.Span.current();
if (currentSpan == null || currentSpan.equals(io.opentelemetry.api.trace.Span.getInvalid())) {
return null;
}
return new OtelSpan(currentSpan);
}
@Override
public Span nextSpan() {
return new OtelSpan(this.tracer.spanBuilder("").startSpan());
}
@Override
public ScopedSpan startScopedSpan(String name) {
io.opentelemetry.api.trace.Span span = this.tracer.spanBuilder(name).startSpan();
return new OtelScopedSpan(span, span.makeCurrent());
}
@Override
public Span.Builder spanBuilder() {
return new OtelSpanBuilder(this.tracer.spanBuilder(""));
}
@Override
public Map<String, String> getAllBaggage() {
return this.otelBaggageManager.getAllBaggage();
}
@Override
public BaggageInScope getBaggage(String name) {
return this.otelBaggageManager.getBaggage(name);
}
@Override
public BaggageInScope getBaggage(TraceContext traceContext, String name) {
return this.otelBaggageManager.getBaggage(traceContext, name);
}
@Override
public BaggageInScope createBaggage(String name) {
return this.otelBaggageManager.createBaggage(name);
}
@Override
public BaggageInScope createBaggage(String name, String value) {
return this.otelBaggageManager.createBaggage(name, value);
}
}
19
View Source File : EventPublishingContextWrapper.java
License : Apache License 2.0
Project Creator : spring-cloud-incubator
License : Apache License 2.0
Project Creator : spring-cloud-incubator
public final clreplaced EventPublishingContextWrapper implements Function<ContextStorage, ContextStorage> {
private final ApplicationEventPublisher publisher;
public EventPublishingContextWrapper(ApplicationEventPublisher publisher) {
this.publisher = publisher;
}
@Override
public ContextStorage apply(ContextStorage contextStorage) {
return new ContextStorage() {
@Override
public io.opentelemetry.context.Scope attach(Context context) {
Context currentContext = Context.current();
io.opentelemetry.context.Scope scope = contextStorage.attach(context);
if (scope == io.opentelemetry.context.Scope.noop()) {
return scope;
}
publisher.publishEvent(new ScopeAttachedEvent(this, context));
return () -> {
scope.close();
publisher.publishEvent(new ScopeClosedEvent(this));
publisher.publishEvent(new ScopeRestoredEvent(this, currentContext));
};
}
@Override
public Context current() {
return contextStorage.current();
}
};
}
public static clreplaced ScopeAttachedEvent extends ApplicationEvent {
/**
* Context corresponding to the attached scope. Might be {@code null}.
*/
final Context context;
/**
* Create a new {@code ApplicationEvent}.
* @param source the object on which the event initially occurred or with which
* the event is replacedociated (never {@code null})
* @param context corresponding otel context
*/
public ScopeAttachedEvent(Object source, @Nullable Context context) {
super(source);
this.context = context;
}
Span getSpan() {
return Span.fromContextOrNull(context);
}
Baggage getBaggage() {
return Baggage.fromContextOrNull(context);
}
@Override
public String toString() {
return "ScopeAttached{context: [span: " + getSpan() + "] [baggage: " + getBaggage() + "]}";
}
}
public static clreplaced ScopeClosedEvent extends ApplicationEvent {
/**
* Create a new {@code ApplicationEvent}.
* @param source the object on which the event initially occurred or with which
* the event is replacedociated (never {@code null})
*/
public ScopeClosedEvent(Object source) {
super(source);
}
}
public static clreplaced ScopeRestoredEvent extends ApplicationEvent {
/**
* {@link Context} corresponding to the scope being restored. Might be
* {@code null}.
*/
final Context context;
/**
* Create a new {@code ApplicationEvent}.
* @param source the object on which the event initially occurred or with which
* the event is replacedociated (never {@code null})
* @param context corresponding otel context
*/
public ScopeRestoredEvent(Object source, @Nullable Context context) {
super(source);
this.context = context;
}
Span getSpan() {
return Span.fromContextOrNull(context);
}
Baggage getBaggage() {
return Baggage.fromContextOrNull(context);
}
@Override
public String toString() {
return "ScopeRestored{context: [span: " + getSpan() + "] [baggage: " + getBaggage() + "]}";
}
}
}
19
View Source File : BrokerClientConnectionListener.java
License : Apache License 2.0
Project Creator : spring-cloud-incubator
License : Apache License 2.0
Project Creator : spring-cloud-incubator
/**
* Automatically subscribes to {@link BrokerClient}. On subscribe it publishes a
* {@link PayloadApplicationEvent} with a generic type of {@link RSocketRequester}.
*/
public clreplaced BrokerClientConnectionListener implements ApplicationListener<ApplicationReadyEvent>, Ordered {
private final BrokerClient brokerClient;
private final ApplicationEventPublisher publisher;
public BrokerClientConnectionListener(BrokerClient brokerClient, ApplicationEventPublisher publisher) {
this.brokerClient = brokerClient;
this.publisher = publisher;
}
@Override
public void onApplicationEvent(ApplicationReadyEvent event) {
// TODO: is there a better event the just RSocketRequester?
// TODO: save Disposable?
this.brokerClient.connect().subscribe(publishEvent());
}
private Consumer<RSocketRequester> publishEvent() {
return requester -> publisher.publishEvent(new RSocketRequesterEvent<>(BrokerClientConnectionListener.this, requester));
}
@Override
public int getOrder() {
// TODO: configurable
return Ordered.HIGHEST_PRECEDENCE;
}
private static final clreplaced RSocketRequesterEvent<T extends RSocketRequester> extends PayloadApplicationEvent<T> {
private RSocketRequesterEvent(Object source, T payload) {
super(source, payload);
}
@Override
public ResolvableType getResolvableType() {
return ResolvableType.forClreplacedWithGenerics(getClreplaced(), ResolvableType.forClreplaced(RSocketRequester.clreplaced));
}
}
}
19
View Source File : Fabric8LeaderAutoConfiguration.java
License : Apache License 2.0
Project Creator : spring-cloud
License : Apache License 2.0
Project Creator : spring-cloud
@Bean
@ConditionalOnMissingBean(LeaderEventPublisher.clreplaced)
public LeaderEventPublisher defaultLeaderEventPublisher(ApplicationEventPublisher applicationEventPublisher) {
return new DefaultLeaderEventPublisher(applicationEventPublisher);
}
19
View Source File : SpannerTemplateTests.java
License : Apache License 2.0
Project Creator : spring-cloud
License : Apache License 2.0
Project Creator : spring-cloud
private void verifyEvents(ApplicationEvent expectedBefore, ApplicationEvent expectedAfter, Runnable operation, Consumer<InOrder> verifyOperation) {
ApplicationEventPublisher mockPublisher = mock(ApplicationEventPublisher.clreplaced);
ApplicationEventPublisher mockBeforePublisher = mock(ApplicationEventPublisher.clreplaced);
ApplicationEventPublisher mockAfterPublisher = mock(ApplicationEventPublisher.clreplaced);
InOrder inOrder = Mockito.inOrder(mockBeforePublisher, this.databaseClient, mockAfterPublisher);
doAnswer((invocationOnMock) -> {
ApplicationEvent event = invocationOnMock.getArgument(0);
if (expectedBefore != null && event.getClreplaced().equals(expectedBefore.getClreplaced())) {
mockBeforePublisher.publishEvent(event);
} else if (expectedAfter != null && event.getClreplaced().equals(expectedAfter.getClreplaced())) {
mockAfterPublisher.publishEvent(event);
}
return null;
}).when(mockPublisher).publishEvent(any());
this.spannerTemplate.setApplicationEventPublisher(mockPublisher);
operation.run();
if (expectedBefore != null) {
inOrder.verify(mockBeforePublisher, times(1)).publishEvent(eq(expectedBefore));
}
verifyOperation.accept(inOrder);
if (expectedAfter != null) {
inOrder.verify(mockAfterPublisher, times(1)).publishEvent(eq(expectedAfter));
}
}
19
View Source File : DiscoveryClientRouteDefinitionLocatorIntegrationTests.java
License : Apache License 2.0
Project Creator : spring-cloud
License : Apache License 2.0
Project Creator : spring-cloud
@RunWith(SpringRunner.clreplaced)
@SpringBootTest(clreplacedes = DiscoveryClientRouteDefinitionLocatorIntegrationTests.Config.clreplaced, properties = { "spring.cloud.gateway.discovery.locator.enabled=true", "spring.cloud.gateway.discovery.locator.route-id-prefix=test__" })
public clreplaced DiscoveryClientRouteDefinitionLocatorIntegrationTests {
@Autowired
private RouteLocator routeLocator;
@Autowired
private ApplicationEventPublisher publisher;
@Autowired
private TestDiscoveryClient discoveryClient;
@Test
public void newServiceAddsRoute() throws Exception {
List<Route> routes = routeLocator.getRoutes().filter(route -> route.getId().startsWith("test__")).collectList().block();
replacedertThat(routes).hreplacedize(1);
discoveryClient.multiple();
publisher.publishEvent(new HeartbeatEvent(this, 1L));
Thread.sleep(2000);
routes = routeLocator.getRoutes().filter(route -> route.getId().startsWith("test__")).collectList().block();
replacedertThat(routes).hreplacedize(2);
}
@SpringBootConfiguration
@EnableAutoConfiguration
protected static clreplaced Config {
@Bean
TestDiscoveryClient discoveryClient() {
return new TestDiscoveryClient();
}
}
private static clreplaced TestDiscoveryClient implements ReactiveDiscoveryClient {
AtomicBoolean single = new AtomicBoolean(true);
DefaultServiceInstance instance1 = new DefaultServiceInstance("service1_1", "service1", "localhost", 8001, false);
DefaultServiceInstance instance2 = new DefaultServiceInstance("service2_1", "service2", "localhost", 8001, false);
public void multiple() {
single.set(false);
}
@Override
public String description() {
return null;
}
@Override
public Flux<ServiceInstance> getInstances(String serviceId) {
if (serviceId.equals("service1")) {
return Flux.just(instance1);
}
if (serviceId.equals("service2")) {
return Flux.just(instance2);
}
return Flux.empty();
}
@Override
public Flux<String> getServices() {
if (single.get()) {
return Flux.just("service1");
}
return Flux.just("service1", "service2");
}
}
}
19
View Source File : RouteRefreshListener.java
License : Apache License 2.0
Project Creator : spring-cloud
License : Apache License 2.0
Project Creator : spring-cloud
// see ZuulDiscoveryRefreshListener
// TODO: make abstract clreplaced in commons?
public clreplaced RouteRefreshListener implements ApplicationListener<ApplicationEvent> {
private final ApplicationEventPublisher publisher;
private HeartbeatMonitor monitor = new HeartbeatMonitor();
public RouteRefreshListener(ApplicationEventPublisher publisher) {
replacedert.notNull(publisher, "publisher may not be null");
this.publisher = publisher;
}
@Override
public void onApplicationEvent(ApplicationEvent event) {
if (event instanceof ContextRefreshedEvent) {
ContextRefreshedEvent refreshedEvent = (ContextRefreshedEvent) event;
if (!WebServerApplicationContext.hreplacederverNamespace(refreshedEvent.getApplicationContext(), "management")) {
reset();
}
} else if (event instanceof RefreshScopeRefreshedEvent || event instanceof InstanceRegisteredEvent) {
reset();
} else if (event instanceof ParentHeartbeatEvent) {
ParentHeartbeatEvent e = (ParentHeartbeatEvent) event;
resetIfNeeded(e.getValue());
} else if (event instanceof HeartbeatEvent) {
HeartbeatEvent e = (HeartbeatEvent) event;
resetIfNeeded(e.getValue());
}
}
private void resetIfNeeded(Object value) {
if (this.monitor.update(value)) {
reset();
}
}
private void reset() {
this.publisher.publishEvent(new RefreshRoutesEvent(this));
}
}
19
View Source File : WeightRoutePredicateFactory.java
License : Apache License 2.0
Project Creator : spring-cloud
License : Apache License 2.0
Project Creator : spring-cloud
/**
* @author Spencer Gibb
*/
// TODO: make this a generic Choose out of group predicate?
public clreplaced WeightRoutePredicateFactory extends AbstractRoutePredicateFactory<WeightConfig> implements ApplicationEventPublisherAware {
/**
* Weight config group key.
*/
public static final String GROUP_KEY = WeightConfig.CONFIG_PREFIX + ".group";
/**
* Weight config weight key.
*/
public static final String WEIGHT_KEY = WeightConfig.CONFIG_PREFIX + ".weight";
private static final Log log = LogFactory.getLog(WeightRoutePredicateFactory.clreplaced);
private ApplicationEventPublisher publisher;
public WeightRoutePredicateFactory() {
super(WeightConfig.clreplaced);
}
@Override
public void setApplicationEventPublisher(ApplicationEventPublisher publisher) {
this.publisher = publisher;
}
@Override
public List<String> shortcutFieldOrder() {
return Arrays.asList(GROUP_KEY, WEIGHT_KEY);
}
@Override
public String shortcutFieldPrefix() {
return WeightConfig.CONFIG_PREFIX;
}
@Override
public void beforeApply(WeightConfig config) {
if (publisher != null) {
publisher.publishEvent(new WeightDefinedEvent(this, config));
}
}
@Override
public Predicate<ServerWebExchange> apply(WeightConfig config) {
return new GatewayPredicate() {
@Override
public boolean test(ServerWebExchange exchange) {
Map<String, String> weights = exchange.getAttributeOrDefault(WEIGHT_ATTR, Collections.emptyMap());
String routeId = exchange.getAttribute(GATEWAY_PREDICATE_ROUTE_ATTR);
// all calculations and comparison against random num happened in
// WeightCalculatorWebFilter
String group = config.getGroup();
if (weights.containsKey(group)) {
String chosenRoute = weights.get(group);
if (log.isTraceEnabled()) {
log.trace("in group weight: " + group + ", current route: " + routeId + ", chosen route: " + chosenRoute);
}
return routeId.equals(chosenRoute);
} else if (log.isTraceEnabled()) {
log.trace("no weights found for group: " + group + ", current route: " + routeId);
}
return false;
}
@Override
public String toString() {
return String.format("Weight: %s %s", config.getGroup(), config.getWeight());
}
};
}
}
19
View Source File : AbstractGatewayFilterFactory.java
License : Apache License 2.0
Project Creator : spring-cloud
License : Apache License 2.0
Project Creator : spring-cloud
/**
* This clreplaced is BETA and may be subject to change in a future release.
*
* @param <C> {@link AbstractConfigurable} subtype
*/
public abstract clreplaced AbstractGatewayFilterFactory<C> extends AbstractConfigurable<C> implements GatewayFilterFactory<C>, ApplicationEventPublisherAware {
private ApplicationEventPublisher publisher;
@SuppressWarnings("unchecked")
public AbstractGatewayFilterFactory() {
super((Clreplaced<C>) Object.clreplaced);
}
public AbstractGatewayFilterFactory(Clreplaced<C> configClreplaced) {
super(configClreplaced);
}
protected ApplicationEventPublisher getPublisher() {
return this.publisher;
}
@Override
public void setApplicationEventPublisher(ApplicationEventPublisher publisher) {
this.publisher = publisher;
}
public static clreplaced NameConfig {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
}
19
View Source File : ServiceInstanceLogStreamAutoConfiguration.java
License : Apache License 2.0
Project Creator : spring-cloud
License : Apache License 2.0
Project Creator : spring-cloud
@Bean
public ApplicationLogStreamPublisher applicationLogsPublisher(LogStreamPublisher<Envelope> logStreamPublisher, ApplicationEventPublisher eventPublisher) {
return new ApplicationLogStreamPublisher(logStreamPublisher, eventPublisher);
}
19
View Source File : ServiceInstanceLogStreamAutoConfiguration.java
License : Apache License 2.0
Project Creator : spring-cloud
License : Apache License 2.0
Project Creator : spring-cloud
@Bean
public StreamingLogWebSocketHandler streamingLogWebSocketHandler(ApplicationEventPublisher applicationEventPublisher) {
return new StreamingLogWebSocketHandler(applicationEventPublisher);
}
19
View Source File : EurekaClientEventListener.java
License : Apache License 2.0
Project Creator : spring-avengers
License : Apache License 2.0
Project Creator : spring-avengers
public clreplaced EurekaClientEventListener implements EurekaEventListener {
private ApplicationEventPublisher publisher;
public EurekaClientEventListener(ApplicationEventPublisher publisher) {
this.publisher = publisher;
}
@Override
public void onEvent(EurekaEvent event) {
if (event instanceof CacheRefreshedEvent) {
publisher.publishEvent(new EurekaClientLocalCacheRefreshedEvent((CacheRefreshedEvent) event));
} else if (event instanceof StatusChangeEvent) {
publisher.publishEvent(new EurekaClientStatusChangeEvent((StatusChangeEvent) event));
}
}
}
19
View Source File : DefaultEventService.java
License : Apache License 2.0
Project Creator : spot-next
License : Apache License 2.0
Project Creator : spot-next
/**
* <p>DefaultEventService clreplaced.</p>
*
* @author mojo2012
* @version 1.0
* @since 1.0
*/
@Service
public clreplaced DefaultEventService extends AbstractService implements EventService {
private boolean isReady = false;
// asynchronous events
@Autowired
protected ApplicationEventMulticaster applicationEventMulticaster;
// synchronous events
@Autowired
protected ApplicationEventPublisher applicationEventPublisher;
@EventListener
protected void onApplicationReady(final ApplicationReadyEvent event) {
isReady = true;
}
/**
* {@inheritDoc}
*/
@Override
public <E extends ApplicationEvent> void publishEvent(final E event) {
if (isReady) {
applicationEventPublisher.publishEvent(event);
}
}
/**
* {@inheritDoc}
*/
@Override
public <E extends ApplicationEvent> void multicastEvent(final E event) {
if (isReady) {
applicationEventMulticaster.multicastEvent(event);
}
}
}
19
View Source File : AdminController.java
License : Apache License 2.0
Project Creator : spinnaker
License : Apache License 2.0
Project Creator : spinnaker
@RestController
@RequestMapping("/admin/orca")
public clreplaced AdminController {
private final ApplicationEventPublisher publisher;
@Autowired
public AdminController(ApplicationEventPublisher publisher) {
this.publisher = publisher;
}
@RequestMapping(value = "/instance/enabled", consumes = "application/json", method = RequestMethod.POST)
void setInstanceEnabled(@RequestBody Map<String, Boolean> enabledWrapper) {
Boolean enabled = enabledWrapper.get("enabled");
if (enabled == null) {
throw new ValidationException("The field 'enabled' must be set.", null);
}
setInstanceEnabled(enabled);
}
private void setInstanceEnabled(boolean enabled) {
InstanceStatus currentStatus = enabled ? UP : OUT_OF_SERVICE;
InstanceStatus previousStatus = currentStatus == OUT_OF_SERVICE ? UP : UNKNOWN;
publisher.publishEvent(new RemoteStatusChangedEvent(new DiscoveryStatusChangeEvent(previousStatus, currentStatus)));
}
}
19
View Source File : AbstractExecutionCompleteEventProcessor.java
License : Apache License 2.0
Project Creator : spinnaker
License : Apache License 2.0
Project Creator : spinnaker
public abstract clreplaced AbstractExecutionCompleteEventProcessor implements ApplicationListener<ExecutionComplete> {
protected final ApplicationEventPublisher applicationEventPublisher;
private final ExecutionRepository executionRepository;
@Autowired
public AbstractExecutionCompleteEventProcessor(ApplicationEventPublisher applicationEventPublisher, ExecutionRepository executionRepository) {
this.applicationEventPublisher = applicationEventPublisher;
this.executionRepository = executionRepository;
}
@Override
public void onApplicationEvent(ExecutionComplete event) {
if (event.getExecutionType() != ExecutionType.PIPELINE) {
return;
}
PipelineExecution execution = executionRepository.retrieve(ExecutionType.PIPELINE, event.getExecutionId());
if (shouldProcessExecution(execution)) {
processCompletedPipelineExecution(execution);
}
}
public abstract boolean shouldProcessExecution(PipelineExecution execution);
public abstract void processCompletedPipelineExecution(PipelineExecution execution);
}
19
View Source File : EventPublicationInterceptorTests.java
License : Apache License 2.0
Project Creator : SourceHot
License : Apache License 2.0
Project Creator : SourceHot
/**
* @author Dmitriy Kopylenko
* @author Juergen Hoeller
* @author Rick Evans
*/
public clreplaced EventPublicationInterceptorTests {
private final ApplicationEventPublisher publisher = mock(ApplicationEventPublisher.clreplaced);
@Test
public void testWithNoApplicationEventClreplacedSupplied() {
EventPublicationInterceptor interceptor = new EventPublicationInterceptor();
interceptor.setApplicationEventPublisher(this.publisher);
replacedertThatIllegalArgumentException().isThrownBy(interceptor::afterPropertiesSet);
}
@Test
public void testWithNonApplicationEventClreplacedSupplied() {
EventPublicationInterceptor interceptor = new EventPublicationInterceptor();
interceptor.setApplicationEventPublisher(this.publisher);
replacedertThatIllegalArgumentException().isThrownBy(() -> {
interceptor.setApplicationEventClreplaced(getClreplaced());
interceptor.afterPropertiesSet();
});
}
@Test
public void testWithAbstractStraightApplicationEventClreplacedSupplied() {
EventPublicationInterceptor interceptor = new EventPublicationInterceptor();
interceptor.setApplicationEventPublisher(this.publisher);
replacedertThatIllegalArgumentException().isThrownBy(() -> {
interceptor.setApplicationEventClreplaced(ApplicationEvent.clreplaced);
interceptor.afterPropertiesSet();
});
}
@Test
public void testWithApplicationEventClreplacedThatDoesntExposeAValidCtor() {
EventPublicationInterceptor interceptor = new EventPublicationInterceptor();
interceptor.setApplicationEventPublisher(this.publisher);
replacedertThatIllegalArgumentException().isThrownBy(() -> {
interceptor.setApplicationEventClreplaced(TestEventWithNoValidOneArgObjectCtor.clreplaced);
interceptor.afterPropertiesSet();
});
}
@Test
public void testExpectedBehavior() {
TestBean target = new TestBean();
final TestApplicationListener listener = new TestApplicationListener();
clreplaced TestContext extends StaticApplicationContext {
@Override
protected void onRefresh() throws BeansException {
addApplicationListener(listener);
}
}
StaticApplicationContext ctx = new TestContext();
MutablePropertyValues pvs = new MutablePropertyValues();
pvs.add("applicationEventClreplaced", TestEvent.clreplaced.getName());
// should automatically receive applicationEventPublisher reference
ctx.registerSingleton("publisher", EventPublicationInterceptor.clreplaced, pvs);
ctx.registerSingleton("otherListener", FactoryBeanTestListener.clreplaced);
ctx.refresh();
EventPublicationInterceptor interceptor = (EventPublicationInterceptor) ctx.getBean("publisher");
ProxyFactory factory = new ProxyFactory(target);
factory.addAdvice(0, interceptor);
ITestBean testBean = (ITestBean) factory.getProxy();
// invoke any method on the advised proxy to see if the interceptor has been invoked
testBean.getAge();
// two events: ContextRefreshedEvent and TestEvent
replacedertThat(listener.getEventCount() == 2).as("Interceptor must have published 2 events").isTrue();
TestApplicationListener otherListener = (TestApplicationListener) ctx.getBean("&otherListener");
replacedertThat(otherListener.getEventCount() == 2).as("Interceptor must have published 2 events").isTrue();
}
@SuppressWarnings("serial")
public static final clreplaced TestEventWithNoValidOneArgObjectCtor extends ApplicationEvent {
public TestEventWithNoValidOneArgObjectCtor() {
super("");
}
}
public static clreplaced FactoryBeanTestListener extends TestApplicationListener implements FactoryBean<Object> {
@Override
public Object getObject() {
return "test";
}
@Override
public Clreplaced<String> getObjectType() {
return String.clreplaced;
}
@Override
public boolean isSingleton() {
return true;
}
}
}
19
View Source File : LogAutoConfiguration.java
License : Apache License 2.0
Project Creator : SophiaLeo
License : Apache License 2.0
Project Creator : SophiaLeo
@Bean
public ApiLogAspect apiLogAspect(ApplicationEventPublisher publisher) {
return new ApiLogAspect(publisher);
}
19
View Source File : DynamicRouteServiceImpl.java
License : GNU Affero General Public License v3.0
Project Creator : romeoblog
License : GNU Affero General Public License v3.0
Project Creator : romeoblog
/**
* The type support Nacos Dynamic Route service implement
*
* @author willlu.zheng
* @date 2020-06-15
*/
@Service("dynamicRouteServiceImpl")
public clreplaced DynamicRouteServiceImpl implements IDynamicRouteService, ApplicationEventPublisherAware {
@Autowired
private RouteDefinitionWriter routeDefinitionWriter;
private ApplicationEventPublisher publisher;
@Override
public void setApplicationEventPublisher(ApplicationEventPublisher applicationEventPublisher) {
this.publisher = applicationEventPublisher;
}
@Override
public String add(RouteDefinition definition) {
routeDefinitionWriter.save(Mono.just(definition)).subscribe();
this.publisher.publishEvent(new RefreshRoutesEvent(this));
return "success";
}
@Override
public String update(RouteDefinition definition) {
try {
this.routeDefinitionWriter.delete(Mono.just(definition.getId()));
} catch (Exception e) {
return "update fail,not find route routeId: " + definition.getId();
}
try {
routeDefinitionWriter.save(Mono.just(definition)).subscribe();
this.publisher.publishEvent(new RefreshRoutesEvent(this));
return "success";
} catch (Exception e) {
return "update route fail";
}
}
@Override
public String delete(String id) {
try {
this.routeDefinitionWriter.delete(Mono.just(id));
return "delete success";
} catch (Exception e) {
e.printStackTrace();
return "delete fail";
}
}
}
19
View Source File : UserServiceUnitTest.java
License : MIT License
Project Creator : rieckpil
License : MIT License
Project Creator : rieckpil
@ExtendWith(MockitoExtension.clreplaced)
clreplaced UserServiceUnitTest {
@Mock
private ApplicationEventPublisher applicationEventPublisher;
@Captor
private ArgumentCaptor<UserCreationEvent> eventArgumentCaptor;
@InjectMocks
private UserService userService;
@Test
void userCreationShouldPublishEvent() {
Long result = this.userService.createUser("duke");
Mockito.verify(applicationEventPublisher).publishEvent(eventArgumentCaptor.capture());
replacedertEquals("duke", eventArgumentCaptor.getValue().getUsername());
}
@Test
void batchUserCreationShouldPublishEvents() {
List<Long> result = this.userService.createUser(List.of("duke", "mike", "alice"));
Mockito.verify(applicationEventPublisher, Mockito.times(3)).publishEvent(any(UserCreationEvent.clreplaced));
}
}
19
View Source File : UserService.java
License : MIT License
Project Creator : rieckpil
License : MIT License
Project Creator : rieckpil
@Service
public clreplaced UserService {
private final ApplicationEventPublisher eventPublisher;
public UserService(ApplicationEventPublisher eventPublisher) {
this.eventPublisher = eventPublisher;
}
public Long createUser(String username) {
// logic to create a user and store it in a database
Long primaryKey = ThreadLocalRandom.current().nextLong(1, 1000);
this.eventPublisher.publishEvent(new UserCreationEvent(this, username, primaryKey));
return primaryKey;
}
public List<Long> createUser(List<String> usernames) {
List<Long> resultIds = new ArrayList<>();
for (String username : usernames) {
resultIds.add(createUser(username));
}
return resultIds;
}
}
19
View Source File : SimpleController.java
License : Apache License 2.0
Project Creator : q920447939
License : Apache License 2.0
Project Creator : q920447939
/**
* ClreplacedName: SimpleController
*
* @author leegoo
* @Description:
* @date 2019年06月28日
*/
@RestController
public clreplaced SimpleController implements ApplicationEventPublisherAware, ApplicationContextAware {
private ApplicationEventPublisher publisher;
private ApplicationContext applicationContext;
// private DiscoveryClient client;
@GetMapping("/event")
public void event(String beanname, String property, Object value) {
// client.getInstances("");
publisher.publishEvent(new UpdateBeanProperty(beanname, property, value));
}
@Override
public void setApplicationEventPublisher(ApplicationEventPublisher applicationEventPublisher) {
this.publisher = applicationEventPublisher;
}
@EventListener
public void publishEvent(PayloadApplicationEvent<UpdateBeanProperty> event) {
UpdateBeanProperty updateBeanProperty = event.getPayload();
Object bean = applicationContext.getBean(updateBeanProperty.getBeanname());
System.out.println(12);
try {
Clreplaced<?> aClreplaced = Clreplaced.forName(bean.getClreplaced().getCanonicalName());
Field field = aClreplaced.getDeclaredField(updateBeanProperty.getProperty());
field.setAccessible(true);
String fistUpdate = updateBeanProperty.getProperty().substring(0, 1).toUpperCase();
String property = fistUpdate + updateBeanProperty.getProperty().substring(1, updateBeanProperty.getProperty().length());
Method method = aClreplaced.getMethod("set" + property, field.getType());
method.invoke(bean, updateBeanProperty.getValue());
System.out.println(bean);
// field.set(, );
} catch (ClreplacedNotFoundException | NoSuchFieldException | NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
e.printStackTrace();
}
}
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext = applicationContext;
}
clreplaced UpdateBeanProperty {
String beanname;
String property;
Object value;
public UpdateBeanProperty(String beanname, String property, Object value) {
this.beanname = beanname;
this.property = property;
this.value = value;
}
public String getBeanname() {
return beanname;
}
public void setBeanname(String beanname) {
this.beanname = beanname;
}
public String getProperty() {
return property;
}
public void setProperty(String property) {
this.property = property;
}
public Object getValue() {
return value;
}
public void setValue(Object value) {
this.value = value;
}
}
}
19
View Source File : AdminResource.java
License : MIT License
Project Creator : puzzle
License : MIT License
Project Creator : puzzle
@RestController
@RequestMapping("/api/admin")
public clreplaced AdminResource {
private final DynamicConfigurationService dynamicConfigurationService;
private final ApplicationEventPublisher eventPublisher;
public AdminResource(DynamicConfigurationService dynamicConfigurationService, ApplicationEventPublisher eventPublisher) {
this.dynamicConfigurationService = dynamicConfigurationService;
this.eventPublisher = eventPublisher;
}
@GetMapping("/config/{key}")
@Secured(AuthoritiesConstants.ADMIN)
public DynamicConfiguration getConfig(@PathVariable String key) {
return dynamicConfigurationService.getByKey(key);
}
@PostMapping("/config/{key}")
@Secured(AuthoritiesConstants.ADMIN)
public ResponseEnreplacedy<Void> updateConfig(@PathVariable String key, @RequestBody DynamicConfiguration config) {
dynamicConfigurationService.setValue(key, config.getValue());
return new ResponseEnreplacedy<>(HttpStatus.OK);
}
@PostMapping("/shop/restart")
@Secured(AuthoritiesConstants.ADMIN)
public ResponseEnreplacedy<Void> restart() {
eventPublisher.publishEvent(new ShopEvent(this, ShopEventType.RESTART));
return new ResponseEnreplacedy<>(HttpStatus.OK);
}
}
19
View Source File : RESTRequestParameterProcessingFilter.java
License : GNU General Public License v3.0
Project Creator : popeen
License : GNU General Public License v3.0
Project Creator : popeen
public void setEventPublisher(ApplicationEventPublisher eventPublisher) {
this.eventPublisher = eventPublisher;
}
19
View Source File : FacebookLoginFilter.java
License : MIT License
Project Creator : PacktPublishing
License : MIT License
Project Creator : PacktPublishing
public void setApplicationEventPublisher(ApplicationEventPublisher eventPublisher) {
this.eventPublisher = eventPublisher;
super.setApplicationEventPublisher(eventPublisher);
}
See More Examples