org.springframework.context.event.EventListener Java Examples

The following examples show how to use org.springframework.context.event.EventListener. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: SaveData.java    From Cleanstone with 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 #2
Source File: SimpleEntityTracker.java    From Cleanstone with 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 #3
Source File: DataInitializer.java    From spring-reactive-sample with GNU General Public License v3.0 6 votes vote down vote up
@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 #4
Source File: KafkaBasicsApplication.java    From spring_io_2019 with 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 #5
Source File: MetacatInitializationService.java    From metacat with 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 #6
Source File: DataInitializer.java    From spring-reactive-sample with GNU General Public License v3.0 6 votes vote down vote up
@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 #7
Source File: EnvironmentConfigurationLogger.java    From kubernetes-crash-course with MIT License 6 votes vote down vote up
@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 #8
Source File: PreMsgQueue.java    From md_blockchain with 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 File: CommentSimulator.java    From Learning-Spring-Boot-2.0-Second-Edition with MIT License 6 votes vote down vote up
@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 #10
Source File: HazelcastApplication.java    From spring-examples with GNU General Public License v3.0 6 votes vote down vote up
@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 #11
Source File: LoginAttemptListener.java    From zhcet-web with 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 #12
Source File: ConsumerListen.java    From spring-boot-starter-samples with Apache License 2.0 6 votes vote down vote up
@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 #13
Source File: MessageReceiverEndpointHealthIndicator.java    From synapse with Apache License 2.0 5 votes vote down vote up
@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 #14
Source File: WebAnnounceEventListener.java    From joal with 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 #15
Source File: TaskManager.java    From Taroco-Scheduler with 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 #16
Source File: DataInitializer.java    From spring-reactive-sample with GNU General Public License v3.0 5 votes vote down vote up
@EventListener(value = ContextRefreshedEvent.class)
public void init() {
    log.info("start data initialization  ...");
    this.initPosts();

    log.info("done data initialization  ...");
    //conn.hashCommands().hGetAll(key)
}
 
Example #17
Source File: EntityChunkRegistrationCauseListener.java    From Cleanstone with 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 #18
Source File: HtmlReportsController.java    From difido-reports with 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 #19
Source File: SecretServiceImpl.java    From flow-platform-x with Apache License 2.0 5 votes vote down vote up
@EventListener
public void onCreateAuthEvent(CreateAuthEvent event) {
    try {
        AuthSecret secret = createAuth(event.getName(), event.getPair());
        event.setSecret(secret);
    } catch (DuplicateException e) {
        event.setErr(e);
    }
}
 
Example #20
Source File: AbstractChannelHealthIndicator.java    From synapse with 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 #21
Source File: DiscoveryClientResolverFactory.java    From grpc-spring-boot-starter with MIT License 5 votes vote down vote up
/**
 * Triggers a refresh of the registered name resolvers.
 *
 * @param event The event that triggered the update.
 */
@EventListener(HeartbeatEvent.class)
public void heartbeat(final HeartbeatEvent event) {
    if (this.monitor.update(event.getValue())) {
        for (final DiscoveryClientNameResolver discoveryClientNameResolver : this.discoveryClientNameResolvers) {
            discoveryClientNameResolver.refreshFromExternal();
        }
    }
}
 
Example #22
Source File: SecurityTokenManager.java    From cuba with 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 #23
Source File: NakadiAuditLogInitialization.java    From nakadi with MIT License 5 votes vote down vote up
@EventListener
public void onApplicationEvent(final ContextRefreshedEvent event) throws IOException {
    if (!featureToggleService.isFeatureEnabled(Feature.AUDIT_LOG_COLLECTION)) {
        LOG.debug("Audit log collection is disabled, skip creation of audit log event type");
        return;
    }
    final Map<String, String> replacements = new HashMap<>();
    replacements.put("event_type_name_placeholder", eventType);
    replacements.put("owning_application_placeholder", owningApplication);
    replacements.put("auth_data_type_placeholder", authDataType);
    replacements.put("auth_value_placeholder", authValue);

    systemEventTypeInitializer.createEventTypesFromResource("audit_event_types.json", replacements);
}
 
Example #24
Source File: TotpTwoFactorProvider.java    From hsweb-framework with 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 #25
Source File: BusAutoConfiguration.java    From spring-cloud-bus with 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());
	}
}
 
Example #26
Source File: AgentHostServiceImpl.java    From flow-platform-x with Apache License 2.0 5 votes vote down vote up
@EventListener
public void onNoIdleAgent(NoIdleAgentEvent event) {
    if (!appProperties.isAutoLocalAgentHost()) {
        return;
    }

    Set<String> agentTags = event.getSelector().getLabel();

    List<AgentHost> hosts;
    if (agentTags.isEmpty()) {
        hosts = list();
    } else {
        hosts = agentHostDao.findAllByTagsIn(agentTags);
    }

    if (hosts.isEmpty()) {
        log.warn("Unable to find matched agent host for job {}", event.getJobId());
        return;
    }

    for (AgentHost host : hosts) {
        if (start(host)) {
            return;
        }
    }

    log.info("Unable to start agent from hosts");
}
 
Example #27
Source File: AsyncBackgroundAnalysis.java    From data-prep with Apache License 2.0 5 votes vote down vote up
/**
 * Handle an application event.
 *
 * @param event the event to respond to
 */
@EventListener
@Async
public void onEvent(DatasetImportedEvent event) {
    LOGGER.debug("Processing spring dataset imported event: {}", event);
    String datasetId = event.getSource();
    analysisEventProcessingUtil.processAnalysisEvent(datasetId);
}
 
Example #28
Source File: VnfmManager.java    From NFVO with Apache License 2.0 5 votes vote down vote up
@EventListener
public void handleEventFinishNFVO(EventFinishNFVO eventFinishNFVO) {
  VirtualNetworkFunctionRecord virtualNetworkFunctionRecord =
      eventFinishNFVO.getEventNFVO().getVirtualNetworkFunctionRecord();
  publishEvent(
      eventFinishNFVO.getEventNFVO().getAction(),
      virtualNetworkFunctionRecord,
      virtualNetworkFunctionRecord.getProjectId());
  if ((eventFinishNFVO.getEventNFVO().getAction().ordinal()
          != Action.ALLOCATE_RESOURCES.ordinal())
      && (eventFinishNFVO.getEventNFVO().getAction().ordinal()
          != Action.GRANT_OPERATION.ordinal())) {
    findAndSetNSRStatus(virtualNetworkFunctionRecord);
  }
}
 
Example #29
Source File: BlockGeneratedListener.java    From md_blockchain with Apache License 2.0 5 votes vote down vote up
@Order(2)
@EventListener(AddBlockEvent.class)
public void blockGenerated(AddBlockEvent addBlockEvent) {
    Block block = (Block) addBlockEvent.getSource();
    BlockPacket blockPacket = new PacketBuilder<>().setType(PacketType.GENERATE_COMPLETE_REQUEST).setBody(new
            RpcSimpleBlockBody(block.getHash())).build();

    //广播给其他人做验证
    packetSender.sendGroup(blockPacket);
}
 
Example #30
Source File: PlayerMoveChunkLoadListener.java    From Cleanstone with MIT License 5 votes vote down vote up
@Async("playerExec")
@EventListener
public void onPlayerMove(PlayerMoveEvent playerMoveEvent) {
    ChunkCoords coords = ChunkCoords.of(playerMoveEvent.getNewPosition());

    final Player player = playerMoveEvent.getPlayer();
    UUID uuid = player.getID().getUUID();

    // reject unneeded updates early
    if (chunkUpdateNotNeeded(playerMoveEvent, coords, uuid)) {
        return;
    }

    int loadingToken = acquireLoadingToken(uuid);
    //noinspection SynchronizationOnLocalVariableOrMethodParameter
    synchronized (uuid) {
        // return early
        if (shouldAbortLoading(uuid, loadingToken)) {
            return;
        }
        // check again because the chunk could already have been loaded inside synchronized block
        if (chunkUpdateNotNeeded(playerMoveEvent, coords, uuid)) {
            return;
        }

        log.debug("loading chunks around {} for {}", coords, player.getID().getName());
        updateViewPosition(player, coords);
        sendNewNearbyChunks(player, coords, loadingToken);
        unloadRemoteChunks(player, coords);
    }
}