Java 类org.springframework.context.event.EventListener 实例源码
项目:stdds-monitor
文件:StatusController.java
/**
* Start the controller
*/
@EventListener(ApplicationReadyEvent.class)
public void start() {
log.info("Starting sessions");
// setup reconnect tasks
for (final GroupSession group : groups.values()) {
group.start();
Runnable reconnectTask = new Runnable() {
@Override
public void run() {
try {
if (group.isStopped()) {
group.stop();
log.info("Attempting to reconnect...");
group.start();
}
} catch (Exception e) {
log.error(e.getLocalizedMessage());
}
}
};
Schedule.getInstance().at(reconnectTask, reconnectInterval, true);
}
}
项目:Learning-Spring-Boot-2.0-Second-Edition
文件:CommentSimulator.java
@EventListener
public void simulateComments(ApplicationReadyEvent event) {
Flux
.interval(Duration.ofMillis(1000))
.flatMap(tick -> repository.findAll())
.map(image -> {
Comment comment = new Comment();
comment.setImageId(image.getId());
comment.setComment(
"Comment #" + counter.getAndIncrement());
return Mono.just(comment);
})
.flatMap(newComment ->
Mono.defer(() ->
commentController.addComment(newComment)))
.subscribe();
}
项目:travel-agency
文件:AgencyBot.java
@Async
@EventListener
public void handleUserMessage(UserMessageCreatedEvent event){
log.info("UserMessageCreatedEvent" );
await( 100L );
ConversationMessage message = event.getMessage();
for(BotAnswer answer : answers){
if(answer.tryAnswer(message)){
log.info("Bot answered on message {}" , message.getId());
break;
}
}
}
项目:Learning-Spring-Boot-2.0-Second-Edition
文件:CommentSimulator.java
@EventListener
public void simulateComments(ApplicationReadyEvent event) {
Flux
.interval(Duration.ofMillis(1000))
.flatMap(tick -> repository.findAll())
.map(image -> {
Comment comment = new Comment();
comment.setImageId(image.getId());
comment.setComment(
"Comment #" + counter.getAndIncrement());
return Mono.just(comment);
})
.flatMap(newComment ->
Mono.defer(() ->
commentController.addComment(newComment)))
.subscribe();
}
项目:freqtrade-java
文件:CommandEventListener.java
@EventListener
public void onCommandEvent(CommandEvent event) {
LOGGER.debug("Received event: {}", event);
final String command = event.getCommand();
if (!availableCommandNames.contains(command)) {
final String unknownCommandMessage = String.format("Unkown command received: %s", command);
LOGGER.debug(unknownCommandMessage);
try {
telegramService.sendMessage(unknownCommandMessage);
telegramService.sendMessage(String.format("Available commands: %s", availableCommandNames));
} catch (TelegramApiException e) {
LOGGER.warn("Unable to reply to message", e);
}
}
}
项目:cmc-claim-store
文件:ClaimIssuedCitizenActionsHandler.java
@EventListener
public void sendDefendantNotification(CitizenClaimIssuedEvent event) {
Claim claim = event.getClaim();
if (!claim.getClaimData().isClaimantRepresented()) {
claim.getClaimData().getDefendant().getEmail()
.ifPresent(defendantEmail ->
claimIssuedNotificationService.sendMail(
claim,
defendantEmail,
event.getPin().orElseThrow(IllegalArgumentException::new),
getEmailTemplates().getDefendantClaimIssued(),
"defendant-issue-notification-" + claim.getReferenceNumber(),
event.getSubmitterName()
));
}
}
项目:cas-5.1.0
文件:CasConfigurationEventListener.java
/**
* Handle configuration modified event.
*
* @param event the event
*/
@EventListener
public void handleConfigurationModifiedEvent(final CasConfigurationModifiedEvent event) {
if (this.contextRefresher == null) {
LOGGER.warn("Unable to refresh application context, since no refresher is available");
return;
}
if (event.isEligibleForContextRefresh()) {
LOGGER.info("Received event [{}]. Refreshing CAS configuration...", event);
Collection<String> keys = null;
try {
keys = this.contextRefresher.refresh();
LOGGER.debug("Refreshed the following settings: [{}].", keys);
} catch (final Throwable e) {
LOGGER.trace(e.getMessage(), e);
} finally {
rebind();
LOGGER.info("CAS finished rebinding configuration with new settings [{}]",
ObjectUtils.defaultIfNull(keys, Collections.emptyList()));
}
}
}
项目:spring-reactive-sample
文件:DataInitializer.java
@EventListener(value = ContextRefreshedEvent.class)
public void init() {
log.info("start data initialization ...");
this.posts
.deleteAll()
.thenMany(
Flux
.range(1, 1000)
.flatMap(
num -> this.posts.save(Post.builder().title("Title" + num).content("content of " + "Title" + num).build())
)
)
.log()
.subscribe(
null,
null,
() -> log.info("done initialization...")
);
}
项目:spring-reactive-sample
文件:DataInitializer.java
@EventListener(value = ContextRefreshedEvent.class)
public void init() {
log.info("start data initialization ...");
this.posts
.deleteAll()
.thenMany(
Flux
.just("Post one", "Post two")
.flatMap(
title -> this.posts.save(Post.builder().title(title).content("content of " + title).build())
)
)
.log()
.subscribe(
null,
null,
() -> log.info("done initialization...")
);
}
项目:spring-reactive-sample
文件:DataInitializer.java
@EventListener(value = ContextRefreshedEvent.class)
public void init() {
log.info("start data initialization ...");
this.posts
.deleteAll()
.thenMany(
Flux
.range(1, 100)
.flatMap(
num -> this.posts.save(Post.builder().title("Title" + num).content("content of " + "Title" + num).build())
)
)
.log()
.subscribe(
null,
null,
() -> log.info("done initialization...")
);
}
项目:spring-reactive-sample
文件:DataInitializer.java
@EventListener(value = ContextRefreshedEvent.class)
public void init() {
log.info("start data initialization ...");
this.posts
.deleteAll()
.thenMany(
Flux
.just("Post one", "Post two")
.flatMap(
title -> this.posts.save(Post.builder().id(UUID.randomUUID().toString()).title(title).content("content of " + title).build())
)
)
.log()
.subscribe(
null,
null,
() -> log.info("done initialization...")
);
}
项目:spring-reactive-sample
文件:DataInitializer.java
@EventListener(value = ContextRefreshedEvent.class)
public void init() {
log.info("start data initialization ...");
this.posts
.deleteAll()
.thenMany(
Flux
.range(1, 1000)
.flatMap(
num -> this.posts.save(Post.builder().title("Title" + num).content("content of " + "Title" + num).build())
)
)
.log()
.subscribe(
null,
null,
() -> log.info("done initialization...")
);
}
项目:devops-cstack
文件:ApplicationListener.java
@EventListener
public void onApplicationStop(ApplicationStopEvent applicationStopEvent) {
Application application = (Application) applicationStopEvent.getSource();
try {
int counter = 0;
boolean started = false;
do {
started = applicationService.isStopped(application.getName());
Thread.sleep(1000);
} while (counter++ < 30 && !started);
if (counter <= 30) {
application.setStatus(Status.STOP);
} else {
application.setStatus(Status.FAIL);
}
logger.info("Application status : " + application.getStatus());
applicationService.saveInDB(application);
} catch (Exception e) {
e.printStackTrace();
}
}
项目:devops-cstack
文件:ModuleListener.java
@EventListener
@Async
public void onModuleStop(ModuleStopEvent moduleStopEvent) {
Module module = (Module) moduleStopEvent.getSource();
try {
int counter = 0;
boolean isStopped = false;
do {
isStopped = dockerService.isStoppedGracefully(module.getName());
Thread.sleep(1000);
} while (counter++ < 30 && !isStopped);
if (counter <= 30) {
module.setStatus(Status.STOP);
} else {
module.setStatus(Status.FAIL);
}
logger.info("Server status : " + module.getStatus());
moduleService.update(module);
} catch (Exception e) {
logger.error(module.getName(), e);
e.printStackTrace();
}
}
项目:happy-news
文件:Setup.java
/**
* Run setup when application starts.
*/
@EventListener(ContextRefreshedEvent.class)
public void contextRefreshedEvent() {
logger.info("Running setup");
if (userRepository.count() == 0) {
logger.info("No users have been configured, creating default user");
User user = new User(defaultUsername,
defaultPassword,
Collections.singleton("ROLE_" + WebSecurityConfig.Roles.ADMIN));
userRepository.save(user);
logger.info("Created user \"{}\" with password \"{}\". Change this password for security reasons!",
defaultUsername,
defaultPassword);
}
logger.info("Setup completed");
}
项目:onboarding-service
文件:UserNameUpdater.java
@EventListener
public void onBeforeTokenGrantedEvent(BeforeTokenGrantedEvent event) {
Person person = (Person) event.getAuthentication().getPrincipal();
String firstName = capitalizeFully(person.getFirstName());
String lastName = capitalizeFully(person.getLastName());
log.info("Updating user name: timestamp: {}, name: {} {}",
event.getTimestamp(),
firstName,
lastName
);
userService.findByPersonalCode(person.getPersonalCode()).ifPresent(user -> {
user.setFirstName(firstName);
user.setLastName(lastName);
userService.save(user);
});
}
项目:smarti
文件:ConversationIndexer.java
/**
* Processes update events as e.g. sent by the {@link StoreService}
* @param storeEvent
*/
@EventListener
protected void conversationUpdated(StoreServiceEvent storeEvent){
log.debug("StoreServiceEvent for {}", storeEvent.getConversationId());
if(storeEvent.getOperation() == Operation.SAVE){
if(storeEvent.getConversationStatus() == Status.Complete){
log.debug(" - SAVE operation of a COMPLETED conversation");
indexConversation(storeService.get(storeEvent.getConversationId()), true);
} //else we do not index uncompleted conversations
} else if(storeEvent.getOperation() == Operation.DELETE){
log.debug(" - DELETE operation");
removeConversation(storeEvent.getConversationId(), true);
} else {
log.debug(" - {} ignored", storeEvent);
}
}
项目:spring-cloud-skipper
文件:DeployerInitializationService.java
@EventListener
@Transactional
public void initialize(ApplicationReadyEvent event) {
platforms.forEach(platform -> {
platform.getDeployers().forEach(deployer -> {
this.deployerRepository.save(deployer);
logger.info(String.format(
"Added '%s' platform account '%s' into deployer repository.",
platform.getName(),
deployer.getName()));
});
});
}
项目:camunda-bpm-swagger
文件:MainApplication.java
@EventListener
public void run(PostDeployEvent event) {
event.getProcessEngine().getRepositoryService().createDeployment()
.addModelInstance("dummy.bpmn", Bpmn.createExecutableProcess("dummy")
.startEvent()
.userTask("task").name("Do Stuff")
.endEvent()
.done())
.deploy();
}
项目:joal
文件:CoreEventListener.java
@Async
@Order(Ordered.HIGHEST_PRECEDENCE)
@EventListener
void handleSeedSessionHasStarted(final SeedSessionHasStartedEvent event) {
logger.debug("Event SeedSessionHasStartedEvent caught.");
// TODO : add a log to tell which BitTorrent client.
// TODO : detailed BitTorrent client log at debug log level
}
项目:Learning-Spring-Boot-2.0-Second-Edition
文件:CommentSimulator.java
@EventListener
public void simulateUsersClicking(ApplicationReadyEvent event) {
Flux
.interval(Duration.ofMillis(500))
.flatMap(tick ->
Mono.defer(() ->
homeController.index(new BindingAwareModelMap())))
.subscribe();
}
项目:meparty
文件:StartupMapConfigurationRegistry.java
/**
* On context refreshed event, merges singleton instance
* of the registry with custom bean instance of the registry.
*/
@EventListener(ContextRefreshedEvent.class)
public void contextRefreshEvent() {
MapConfigurationRegistrySingleton.getSingleton()
.merge(mapConfigurationRegistry);
}
项目:cmc-claim-store
文件:DocumentUploader.java
@EventListener
public void uploadIntoDocumentManagementStore(DocumentGeneratedEvent event) {
event.getDocuments().forEach(document -> {
String documentSelfPath = this.documentManagementService.uploadDocument(event.getAuthorisation(),
document.getFilename(), document.getBytes(), PDF.CONTENT_TYPE);
if (isSealedClaim(document.getFilename())) {
claimService.linkSealedClaimDocument(event.getClaim().getId(), documentSelfPath);
}
});
}
项目:akir
文件:EmailVerifyService.java
@EventListener
public void onUserRegister(UserRegistrationEvent event) {
userRepo.findById(event.getUserId()).ifPresent(user -> {
if (config.isRequireEmailVerfied()) {
sendVerifyEmail(user);
} else {
user.setEmailVerified(true);
userRepo.save(user);
}
});
}
项目:cmc-claim-store
文件:DefendantResponseCitizenNotificationsHandler.java
@EventListener
public void notifyDefendantResponse(DefendantResponseEvent event) {
defendantResponseNotificationService.notifyDefendant(
event.getClaim(),
event.getUserEmail(),
referenceForDefendant(event.getClaim().getReferenceNumber())
);
}
项目:travel-agency
文件:AgencyBot.java
@EventListener
public void handleNewSubscription(SessionSubscribeEvent event){
SimpMessageHeaderAccessor headers = SimpMessageHeaderAccessor.wrap(event.getMessage());
Optional<Conversation> conversation = conversationUtils.conversationOf(headers);
if( conversation.isPresent() && shouldAskForPhoneNumber(conversation.get()) ){
Optional<Participant> participant = conversationUtils.participantOf(headers);
if(participant.isPresent() && participant.get().isUser()){
Participant bot = conversation.get().assignBot();
conversationRepository.save(conversation.get());
String destination = "/topic/chat/" + conversation.get().getId();
CreateMessage message = MessageBuilder.message(MessageType.PHONE_NUMBER_REQUEST)
.withAuthor( bot )
.withConversation( conversation.get() )
.build();
ConversationMessage conversationMessage = conversationService.create(message);
messagingTemplate.convertAndSend(destination, conversationMessage);
log.info("Phone number request sent: {}" , conversationMessage);
}
}
}
项目:cmc-claim-store
文件:MoreTimeRequestedStaffNotificationHandler.java
@EventListener
public void sendNotifications(MoreTimeRequestedEvent event) {
notificationService.sendMail(
staffEmailProperties.getRecipient(),
notificationsProperties.getTemplates().getEmail().getStaffMoreTimeRequested(),
prepareNotificationParameters(event),
String.format(REFERENCE_TEMPLATE, "staff", event.getClaim().getReferenceNumber())
);
}
项目:cmc-claim-store
文件:DefendantResponseStaffNotificationHandler.java
@EventListener
public void onDefendantResponseSubmitted(DefendantResponseEvent event) {
defendantResponseStaffNotificationService.notifyStaffDefenceSubmittedFor(
event.getClaim(),
event.getUserEmail()
);
}
项目:cmc-claim-store
文件:ClaimIssuedCitizenActionsHandler.java
@EventListener
public void sendClaimantNotification(CitizenClaimIssuedEvent event) {
Claim claim = event.getClaim();
claimIssuedNotificationService.sendMail(
claim,
claim.getSubmitterEmail(),
null,
getEmailTemplates().getClaimantClaimIssued(),
"claimant-issue-notification-" + claim.getReferenceNumber(),
event.getSubmitterName()
);
}
项目:onboarding-service
文件:LoginAuditEventBroadcaster.java
@EventListener
public void onBeforeTokenGrantedEvent(BeforeTokenGrantedEvent event) {
Person person = (Person) event.getAuthentication().getPrincipal();
log.info("Broadcasting login audit event from BeforeTokenGrantedEvent: timestamp: {}, name: {} {}",
event.getTimestamp(),
person.getFirstName(),
person.getLastName()
);
auditEventPublisher.publish(person.getPersonalCode(), AuditEventType.LOGIN);
}
项目:travel-agency
文件:WebsocketSessionListener.java
@EventListener
private void handleSessionDisconnect(SessionDisconnectEvent event) {
Optional<SessionConversations> removeSession = sessionRepository.remove(event.getSessionId());
if(removeSession.isPresent()){
removeSession.get().getConversations().forEach( conversation -> {
notifyUserLeft(conversation, removeSession.get().getParticipantId());
});
log.debug("User {} disconnected No conversations {}",
removeSession.get().getParticipantId(),
removeSession.get().getNumberOfConversations());
}
}
项目:cmc-claim-store
文件:OfferRespondedCitizenActionsHandler.java
@EventListener
public void sendNotificationToClaimantOnOfferAcceptedByClaimant(OfferAcceptedEvent event) {
Claim claim = event.getClaim();
offerMadeNotificationService.sendNotificationEmail(
claim.getSubmitterEmail(),
notificationsProperties.getTemplates().getEmail().getOfferAcceptedByClaimantEmailToClaimant(),
aggregateParams(claim),
NotificationReferenceBuilder.OfferAccepted.referenceForClaimant(claim.getReferenceNumber())
);
}
项目:dashboard1b
文件:ControladorHTML.java
@RequestMapping( value = "/newSugerence")
@EventListener
public void newSugerence(Sugerencia data){
System.out.println("Evento escuchado!");
SseEventBuilder newSugerenceEvent = SseEmitter.event().name("evento").data("{ \"tipo\": \"newSugerence\" , \"title\":\"" + data.getTitulo() + "\"}");
sendEvent(newSugerenceEvent);
}
项目:cmc-claim-store
文件:OfferRespondedCitizenActionsHandler.java
@EventListener
public void sendNotificationToClaimantOnOfferRejectedByClaimant(OfferRejectedEvent event) {
Claim claim = event.getClaim();
offerMadeNotificationService.sendNotificationEmail(
claim.getSubmitterEmail(),
notificationsProperties.getTemplates().getEmail().getOfferRejectedByClaimantEmailToClaimant(),
aggregateParams(claim),
NotificationReferenceBuilder.OfferRejected.referenceForClaimant(claim.getReferenceNumber())
);
}
项目:joal
文件:CoreEventListener.java
@Async
@Order(Ordered.HIGHEST_PRECEDENCE)
@EventListener
void handleNoMoreLeechers(final NoMoreLeechersEvent event) throws IOException {
logger.debug("Event NoMoreLeechersEvent caught.");
//logger.warn("0 peers are currently leeching, moving torrent to archived and restarting seed.");
}
项目:cmc-claim-store
文件:OfferMadeCitizenActionsHandler.java
@EventListener
public void sendClaimantNotification(OfferMadeEvent event) {
Claim claim = event.getClaim();
offerMadeNotificationService.sendNotificationEmail(
claim.getSubmitterEmail(),
notificationsProperties.getTemplates().getEmail().getClaimantOfferMade(),
aggregateParams(claim),
NotificationReferenceBuilder.OfferMade.referenceForClaimant(claim.getReferenceNumber())
);
}
项目:errai-spring-server
文件:ErraiApplicationListener.java
@EventListener
public void onApplicationEvent(ContextClosedEvent event) {
logger.info("ContextClosedEvent");
MessageBus bus = ErraiServiceSingleton.getService().getBus();
if (bus != null) {
for (ServiceImplementation serviceImplementation : services) {
String subject = serviceImplementation.getSubject();
logger.info("Unsubscribing " + subject);
bus.unsubscribeAll(subject);
}
}
}
项目:cas-5.1.0
文件:OidcRegisteredServicePreProcessorEventListener.java
/**
* Handle registered service loaded event.
*
* @param event the event
*/
@EventListener
public void handleRegisteredServicesLoadedEvent(final CasRegisteredServicesLoadedEvent event) {
event.getServices()
.stream()
.filter(s -> s instanceof OidcRegisteredService)
.forEach(s -> {
LOGGER.debug("Attempting to reconcile scopes and attributes for service [{}] of type [{}]",
s.getServiceId(), s.getClass().getSimpleName());
this.scopeToAttributesFilter.reconcile(s);
});
}
项目:joal
文件:WebConfigEventListener.java
@Order(Ordered.LOWEST_PRECEDENCE)
@EventListener
void handleClientFilesDiscovered(final ClientFilesDiscoveredEvent event) {
logger.debug("Send ClientFilesDiscoveredEvent to clients.");
this.messagingTemplate.convertAndSend("/config", new ClientFilesDiscoveredPayload(event));
}
项目:cas-5.1.0
文件:DefaultCasEventListener.java
/**
* Handle TGT creation event.
*
* @param event the event
*/
@EventListener
public void handleCasTicketGrantingTicketCreatedEvent(final CasTicketGrantingTicketCreatedEvent event) {
if (this.casEventRepository != null) {
final CasEvent dto = prepareCasEvent(event);
dto.putCreationTime(event.getTicketGrantingTicket().getCreationTime());
dto.putId(TicketIdSanitizationUtils.sanitize(event.getTicketGrantingTicket().getId()));
dto.setPrincipalId(event.getTicketGrantingTicket().getAuthentication().getPrincipal().getId());
this.casEventRepository.save(dto);
}
}