Java Code Examples for org.springframework.context.event.EventListener

The following examples show how to use org.springframework.context.event.EventListener. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: Cleanstone   Source File: SimpleEntityTracker.java    License: MIT License 6 votes vote down vote up
@Override
@Async
@EventListener
public synchronized void onEntityMove(EntityMoveEvent e) {
    Entity movingEntity = e.getEntity();
    // When the entity is in the same Chunk, just return
    if (ChunkCoords.of(e.getOldPosition()).equals(ChunkCoords.of(e.getNewPosition()))) {
        return;
    }
    Collection<Entity> inRangeEntities = getInRangeEntities(movingEntity);

    if (isObserver(movingEntity)) {
        makeTheObserverUntrackOutOfRangeEntities(movingEntity, inRangeEntities);
        makeTheObserverTrackInRangeEntities(movingEntity, inRangeEntities);
    }

    makeInRangeObserversTrackTheEntity(movingEntity, inRangeEntities);
    makeOutOfRangeObserversUntrackTheEntity(movingEntity, inRangeEntities);
}
 
Example 2
@EventListener(condition = "#event.topic=='test'")
public void testListen(RocketmqEvent event) {
	MQPushConsumer consumer = consumerTemplate.getConsumer();
	try {
		String id = new String(event.getMessageExt().getBody(),"utf-8");
		System.out.println("bl"+ id);
	} catch (Exception e) {
		e.printStackTrace();
		if (event.getMessageExt().getReconsumeTimes() <= 1) {// 重复消费1次
			try {
				consumer.sendMessageBack(event.getMessageExt(), 1, null);
			} catch (RemotingException | MQBrokerException | InterruptedException | MQClientException e1) {
				e1.printStackTrace();
				//消息进行定时重试
			}
		} else {
			System.out.println("消息消费失败,定时重试");
		}
	}
}
 
Example 3
Source Project: zhcet-web   Source File: LoginAttemptListener.java    License: Apache License 2.0 6 votes vote down vote up
@EventListener
public void auditEventHappened(AuditApplicationEvent auditApplicationEvent) {
    AuditEvent auditEvent = auditApplicationEvent.getAuditEvent();

    StringBuilder stringBuilder = new StringBuilder();
    stringBuilder.append("Principal ").append(auditEvent.getPrincipal()).append(" - ").append(auditEvent.getType());
    stringBuilder.append("\n  Authorities: ").append(auditEvent.getData().get("authorities"));

    WebAuthenticationDetails details = (WebAuthenticationDetails) auditEvent.getData().get("details");

    loginAttemptService.loginAttempt(auditEvent);

    if (details != null) {
        stringBuilder.append("\n  Remote IP address: ").append(details.getRemoteAddress());
        stringBuilder.append("\n  Session ID: ").append(details.getSessionId());
    }
    stringBuilder.append("\n  Request URL: ").append(auditEvent.getData().get("requestUrl"));
    stringBuilder.append("\n  Source: ").append(auditEvent.getData().get("source"));

    String message = stringBuilder.toString();
    if (auditEvent.getType().equals(AuthenticationAuditListener.AUTHENTICATION_FAILURE)) {
        log.warn(message);
    } else {
        log.info(message);
    }
}
 
Example 4
@SuppressWarnings("rawtypes")
@EventListener
public void handleContextRefresh(ContextRefreshedEvent event) {
	final Environment environment = event.getApplicationContext().getEnvironment();
	LOGGER.info("====== Environment and configuration ======");
	LOGGER.info("Active profiles: {}", Arrays.toString(environment.getActiveProfiles()));
	final MutablePropertySources sources = ((AbstractEnvironment) environment).getPropertySources();
	StreamSupport.stream(sources.spliterator(), false).filter(ps -> ps instanceof EnumerablePropertySource)
			.map(ps -> ((EnumerablePropertySource) ps).getPropertyNames()).flatMap(Arrays::stream).distinct()
			.forEach(prop -> {
				Object resolved = environment.getProperty(prop, Object.class);
				if (resolved instanceof String) {
					LOGGER.info("{} - {}", prop, environment.getProperty(prop));
				} else {
					LOGGER.info("{} - {}", prop, "NON-STRING-VALUE");
				}
				
			});
	LOGGER.debug("===========================================");
}
 
Example 5
Source Project: spring_io_2019   Source File: KafkaBasicsApplication.java    License: Apache License 2.0 6 votes vote down vote up
@EventListener(ApplicationReadyEvent.class)
public void process() throws Exception {

	try (Stream<String> stream = Files.lines(Paths.get(moviesFile.getURI()))) {
		stream.forEach(s -> {
			Movie movie = Parser.parseMovie(s);
			log.info("sending " + movie.getMovieId() + " for movie " + movie.toString() + " to " + MOVIES_TOPIC);
			movieTemplate.send(MOVIES_TOPIC, movie.getMovieId(), movie);
		});
	}
	catch (IOException e) {
		e.printStackTrace();
	}
	Random ran = new Random();
	while (true) {
		int movieId = ran.nextInt(920) + 1;
		int rating = 5 + ran.nextInt(6);
		Rating rat = new Rating((long) movieId, (double) rating);
		log.info(rat.toString());
		Thread.sleep(1_000);
		this.ratingTemplate.send(KafkaBasicsApplication.RATINGS_TOPIC, rat.getMovieId(), rat);
	}
}
 
Example 6
Source Project: metacat   Source File: MetacatInitializationService.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Metacat service shutdown.
 *
 * @param event Event when the context is shutting down
 */
@EventListener
public void stop(final ContextClosedEvent event) {
    log.info("Metacat application is stopped per {}. Stopping services.", event);
    try {
        this.pluginsLoaded.set(false);
        this.connectorManager.stop();
        this.catalogsLoaded.set(false);
        this.threadServiceManager.stop();
        this.metacatThriftService.stop();
        this.thriftStarted.set(false);
    } catch (final Exception e) {
        // Just log it since we're shutting down anyway shouldn't matter to propagate it
        log.error("Unable to properly shutdown services due to {}", e.getMessage(), e);
    }
    log.info("Finished stopping services.");
}
 
Example 7
@EventListener(ApplicationStartedEvent.class)
public void generateDefaultData() {
    Long count = carRepository.count();
    if (count == 0L) {
        List<String> colors = List.of("Black", "White", "Red", "Blue");
        List<Car> carList = new ArrayList<>();
        Date newDate = new Date();
        for (int i = 0; i < 500; i++) {
            carList.add(
                    Car.builder()
                            .brand("HKCar")
                            .colour(colors.get(i % 3))
                            .date(newDate)
                            .doorCount(4)
                            .fuel("Diesel")
                            .model("SuperCar")
                            .serial("SR" + i)
                            .type("TypeC")
                            .year(2020)
                            .build()
            );
        }
        carRepository.saveAll(carList);
    }
}
 
Example 8
Source Project: md_blockchain   Source File: PreMsgQueue.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 新区块生成后,clear掉map中number比区块小的所有数据
 */
@Order(3)
@EventListener(AddBlockEvent.class)
public void blockGenerated(AddBlockEvent addBlockEvent) {
    Block block = (Block) addBlockEvent.getSource();
    int number = block.getBlockHeader().getNumber();
    CompletableFuture.supplyAsync(() -> {
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        for (String key : blockConcurrentHashMap.keySet()) {
            if (blockConcurrentHashMap.get(key).getNumber() <= number) {
                blockConcurrentHashMap.remove(key);
            }
        }
        return null;
    });
}
 
Example 9
Source Project: Cleanstone   Source File: SaveData.java    License: MIT License 6 votes vote down vote up
@Order(value = 50)
@EventListener
public void onTerminate(AsyncPlayerTerminationEvent e) {
    Player player = e.getPlayer();
    if (player.getEntity() == null) {
        return;
    }
    EntityData entityData = new EntityData(player.getEntity().getPosition(),
            player.getEntity().getWorld().getID(), player.getGameMode(), player.isFlying());
    try {
        playerManager.getPlayerDataSource().setPlayerData(player, StandardPlayerDataType.ENTITY_DATA,
                entityData);
    } catch (IOException e1) {
        log.error("Failed to save player data for " + player, e1);
    }
}
 
Example 10
@EventListener(value = ContextRefreshedEvent.class)
public void init() {
    log.info("start data initialization...");
    this.databaseClient.delete().from("posts")
            .then().
            and(

                    this.databaseClient.insert()
                            .into("posts")
                            //.nullValue("id", Integer.class)
                            .value("title", "First post title")
                            .value("content", "Content of my first post")
                            .map((r, m) -> r.get("id", Integer.class)).all()
                            .log()
            )
            .thenMany(
                    this.databaseClient.select()
                            .from("posts")
                            .orderBy(Sort.by(desc("id")))
                            .as(Post.class)
                            .fetch()
                            .all()
                            .log()
            )
            .subscribe(null, null, () -> log.info("initialization is done..."));
}
 
Example 11
@EventListener
public void onApplicationReadyEvent(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(() ->
				controller.addComment(newComment)))
		.subscribe();
}
 
Example 12
@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...")
        );

}
 
Example 13
Source Project: hyena   Source File: HyenaInitialization.java    License: Apache License 2.0 5 votes vote down vote up
@EventListener(ApplicationReadyEvent.class)
public void onApplicationReady() {
    log.info("application ready");
    sysPropertyDs.createSysPropertyTable();

    int dbSqlVer = this.upgradeSql();
    if (dbSqlVer != HyenaConstants.SQL_VERSION) {
        sysPropertyDs.setSqlVersion(HyenaConstants.SQL_VERSION);
    }
}
 
Example 14
Source Project: hedera-mirror-node   Source File: LeaderAspect.java    License: Apache License 2.0 5 votes vote down vote up
@EventListener
public void revoked(OnRevokedEvent event) {
    if (leader) {
        leader = false;
        log.info("Transitioned to follower");
    }
}
 
Example 15
Source Project: flow-platform-x   Source File: StatsServiceImpl.java    License: Apache License 2.0 5 votes vote down vote up
@EventListener
public void onJobStatusChange(JobStatusChangeEvent event) {
    Job job = event.getJob();

    if (!job.isDone()) {
        return;
    }

    StatsType t = defaultTypes.get(StatsType.JOB_STATUS);
    StatsItem item = t.createEmptyItem();
    item.getCounter().put(job.getStatus().name(), 1.0F);

    int day = DateHelper.toIntDay(job.getCreatedAt());
    add(job.getFlowId(), day, item.getType(), item.getCounter());
}
 
Example 16
Source Project: library   Source File: SheetsReadModel.java    License: MIT License 5 votes vote down vote up
@Override
@Transactional
@EventListener
public void handle(BookPlacedOnHold event) {
    try {
        createNewHold(event);
    } catch (DuplicateKeyException ex) {
        //idempotent operation
    }
}
 
Example 17
Source Project: synapse   Source File: AbstractChannelHealthIndicator.java    License: Apache License 2.0 5 votes vote down vote up
@EventListener
public void on(final MessageReceiverNotification notification) {
    if (notification.getStatus() == MessageReceiverStatus.RUNNING) {
        notification.getChannelDurationBehind().ifPresent(channelDurationBehind -> {
            if (channelDurationBehind.getDurationBehind().toMillis() <= TEN_SECONDS) {
                healthyChannels.add(notification.getChannelName());
            }
        });
    }
}
 
Example 18
Source Project: joal   Source File: WebAnnounceEventListener.java    License: Apache License 2.0 5 votes vote down vote up
@Order(Ordered.LOWEST_PRECEDENCE)
@EventListener
public void successfullyAnnounce(final SuccessfullyAnnounceEvent event) {
    logger.debug("Send SuccessfullyAnnouncePayload to clients.");

    this.messagingTemplate.convertAndSend("/announce", new SuccessfullyAnnouncePayload(event));
}
 
Example 19
Source Project: spring4-sandbox   Source File: Receiver.java    License: Apache License 2.0 5 votes vote down vote up
@EventListener
public void onPostSaved(Post savedPost) {
	LOG.debug("=================received post data============== @\r\n"+ savedPost);
	
	ESPost doc=new ESPost();
	doc.setId("1");
	doc.setTitle(savedPost.getTitle());
	doc.setContent(savedPost.getContent());
	repository.save(doc);
}
 
Example 20
Source Project: flow-platform-x   Source File: PushServiceImpl.java    License: Apache License 2.0 5 votes vote down vote up
@Override
@EventListener
public void onJobCreated(JobCreatedEvent event) {
    Job job = event.getJob();
    socketPushManager.push(topicForJobs, PushEvent.NEW_CREATED, job);
    log.debug("Job created event {} been pushed", job.getId());
}
 
Example 21
Source Project: mPaaS   Source File: EurekaStateChangeListener.java    License: Apache License 2.0 5 votes vote down vote up
/**
     * 服务实例注册事件
     * @param event
     */
    @EventListener
    public void listen(EurekaInstanceRegisteredEvent event) {
        /**
         * 获取当前已注册的所有服务器实例
         */
        int total = EurekaServerContextHolder.getInstance().getServerContext().getRegistry().getSortedApplications().size();
//        event.getInstanceInfo().getActionType()
        log.info("服务实例[{}]注册成功,当前服务器已注册服务实例数量[{}]", event.getInstanceInfo().getAppName(), total);

    }
 
Example 22
Source Project: spring-batch-lightmin   Source File: JournalServiceBean.java    License: Apache License 2.0 5 votes vote down vote up
@EventListener(LightminClientApplicationChangedEvent.class)
public void addJournal(final LightminClientApplicationChangedEvent event) {
    final Journal journal = new Journal();
    final LightminClientApplication lightminClientApplication = (LightminClientApplication) event.getSource();
    journal.setApplicationName(lightminClientApplication.getName());
    journal.setHost(lightminClientApplication.getServiceUrl());
    journal.setTimestamp(new Date(event.getEventDateInMillis()));
    journal.setOldStatus(event.getOldStatus());
    journal.setNewStatus(event.getNewStatus());
    log.info("Journal change event: {}", journal);
    this.journalRepository.add(journal);
}
 
Example 23
Source Project: difido-reports   Source File: HtmlReportsController.java    License: Apache License 2.0 5 votes vote down vote up
@EventListener
public void onTestDetailsCreatedEvent(TestDetailsCreatedEvent testDetailsCreatedEvent) {
	final ExecutionMetadata metadata = metadataRepository.findById(testDetailsCreatedEvent.getExecutionId());
	if (creationLevel.ordinal() >= HtmlGenerationLevel.TEST_DETAILS.ordinal()) {
		writeTestDetails(testDetailsCreatedEvent.getTestDetails(), metadata);
	}

}
 
Example 24
Source Project: Cleanstone   Source File: EntityChunkRegistrationCauseListener.java    License: MIT License 5 votes vote down vote up
@EventListener
public void onEntityAdd(EntityAddEvent e) {
    Entity entity = e.getEntity();
    entity.getWorld().getChunkAt(entity.getPosition()).addCallback(chunk -> {
        Preconditions.checkNotNull(chunk);
        chunk.getEntities().add(entity);
    }, Throwable::printStackTrace);
}
 
Example 25
@EventListener(value = ContextRefreshedEvent.class)
public void init() {
    log.info("start data initialization  ...");
    this.initPosts();

    log.info("done data initialization  ...");
    //conn.hashCommands().hGetAll(key)
}
 
Example 26
Source Project: Taroco-Scheduler   Source File: TaskManager.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * 新增server节点,重新分配任务
 * 将现有的任务数 除以节点数量,除得尽就不分配,不然就按照商值进行分配
 */
@EventListener
public void serverNodeAdd(ServerNodeAddEvent event) throws Exception {
    final List<String> serverList = zkClient.getTaskGenerator().getSchedulerServer().loadScheduleServerNames();
    //黑名单
    for (String ip : zkClient.getSchedulerProperties().getIpBlackList()) {
        int index = serverList.indexOf(ip);
        if (index > -1) {
            serverList.remove(index);
        }
    }
    if (!this.zkClient.getTaskGenerator().getSchedulerServer().isLeader(ScheduleServer.getInstance().getUuid(), serverList)) {
        log.info("当前server:[" + ScheduleServer.getInstance().getUuid() + "]: 不是负责任务分配的Leader,直接返回");
        return;
    }
    final String path = (String) event.getSource();
    final String serverId = path.substring(path.lastIndexOf("/") + 1);
    final List<String> tasks = zkClient.getClient().getChildren().forPath(zkClient.getTaskPath());

    if (tasks.size() <= serverList.size()) {
        log.info("任务数小于 server 节点数, 不进行任务重新分配");
        return;
    }
    final BigDecimal len = new BigDecimal(tasks.size()).divide(new BigDecimal(serverList.size()), 0, RoundingMode.DOWN);
    for (int i = 0; i < len.longValue(); i++) {
        // 分配指定任务给指定server
        assignTask2Server(tasks.get(i), serverId);
    }
}
 
Example 27
@EventListener
public void on(final MessageReceiverNotification messageEndpointNotification) {
    if (messageEndpointNotification.getStatus() == MessageReceiverStatus.FAILED) {
        health = Health.down()
                .withDetail("channelName", messageEndpointNotification.getChannelName())
                .withDetail("message", messageEndpointNotification.getMessage())
                .build();
    }
}
 
Example 28
Source Project: cuba   Source File: SecurityTokenManager.java    License: Apache License 2.0 5 votes vote down vote up
@EventListener(AppContextInitializedEvent.class)
protected void applicationInitialized() {
    if ("CUBA.Platform".equals(config.getKeyForSecurityTokenEncryption())) {
        log.warn("\nWARNING:\n" +
                "=================================================================\n" +
                "'cuba.keyForSecurityTokenEncryption' app property is set to\n " +
                "default value. Use a unique value in production environments.\n" +
                "=================================================================");
    }
}
 
Example 29
Source Project: hsweb-framework   Source File: TotpTwoFactorProvider.java    License: Apache License 2.0 5 votes vote down vote up
@EventListener
public void handleUserCreatedEvent(UserCreatedEvent event) {
    //生成totp
    String key = TotpUtil.getRandomSecretBase32(64);
    UserEntity userEntity = event.getUserEntity();
    String keyUrl = TotpUtil.generateTotpString(userEntity.getUsername(), domain, key);
    //创建一个用户没有操作权限的配置
    userSettingManager.saveSetting(userEntity.getId(), settingId, key, UserSettingPermission.NONE);
    eventPublisher.publishEvent(new TotpTwoFactorCreatedEvent(userEntity, keyUrl));
}
 
Example 30
Source Project: spring-cloud-bus   Source File: BusAutoConfiguration.java    License: Apache License 2.0 5 votes vote down vote up
@EventListener(classes = RemoteApplicationEvent.class)
public void acceptLocal(RemoteApplicationEvent event) {
	if (this.serviceMatcher.isFromSelf(event)
			&& !(event instanceof AckRemoteApplicationEvent)) {
		if (log.isDebugEnabled()) {
			log.debug("Sending remote event on bus: " + event);
		}
		this.cloudBusOutboundChannel.send(MessageBuilder.withPayload(event).build());
	}
}