org.springframework.boot.context.event.ApplicationReadyEvent Java Examples
The following examples show how to use
org.springframework.boot.context.event.ApplicationReadyEvent.
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: TaskExecutionListenerTests.java From spring-cloud-task with Apache License 2.0 | 7 votes |
/** * Verify that if a TaskExecutionListener Bean is present that the onTaskFailed method * is called. */ @Test public void testTaskFail() { RuntimeException exception = new RuntimeException(EXCEPTION_MESSAGE); setupContextForTaskExecutionListener(); SpringApplication application = new SpringApplication(); DefaultTaskListenerConfiguration.TestTaskExecutionListener taskExecutionListener = this.context .getBean( DefaultTaskListenerConfiguration.TestTaskExecutionListener.class); this.context.publishEvent(new ApplicationFailedEvent(application, new String[0], this.context, exception)); this.context.publishEvent( new ApplicationReadyEvent(application, new String[0], this.context)); TaskExecution taskExecution = new TaskExecution(0, 1, "wombat", new Date(), new Date(), null, new ArrayList<>(), null, null); verifyListenerResults(true, true, taskExecution, taskExecutionListener); }
Example #2
Source File: BroccoliServer.java From blog-spring with MIT License | 6 votes |
@EventListener(ApplicationReadyEvent.class) public void start() { ProcessBuilder processBuilder = new ProcessBuilder( System.getProperty("os.name").startsWith("Windows") ? "broccoli.cmd" : "broccoli", "serve", "--host", broccoliConfig.getHost(), "--port", Integer.toString(broccoliConfig.getPort())); processBuilder.redirectOutput(ProcessBuilder.Redirect.INHERIT); processBuilder.redirectError(ProcessBuilder.Redirect.INHERIT); try { process = processBuilder.start(); } catch (IOException e) { throw new RuntimeException(e); } }
Example #3
Source File: CommentSimulator.java From Learning-Spring-Boot-2.0-Second-Edition with MIT License | 6 votes |
@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 #4
Source File: SpringEventListener.java From mercury with Apache License 2.0 | 6 votes |
@EventListener public void handleEvent(Object event) { // do optional life-cycle management if (event instanceof ServletWebServerInitializedEvent) { // when deploy as WAR, this event will not happen log.debug("Loading Spring Boot"); } if (event instanceof ApplicationReadyEvent) { /* * this event will happen in both WAR and JAR deployment mode * At this point, Spring Boot is ready */ if (!started) { new MainApps().start(); } } // in case Spring Boot fails, it does not make sense to keep the rest of the application running. if (event instanceof ApplicationFailedEvent) { log.error("{}", ((ApplicationFailedEvent) event).getException().getMessage()); System.exit(-1); } }
Example #5
Source File: DetectorIndexCreatorIfNotPresent.java From adaptive-alerting with Apache License 2.0 | 6 votes |
@Override public void onApplicationEvent(ApplicationReadyEvent applicationReadyEvent) { if (properties.isCreateIndexIfNotFound() && properties.getDetectorIndexName() != null && properties.getDetectorDocType() != null) { try { boolean isPresent = client.indices().exists(getIndexRequest(), RequestOptions.DEFAULT); if (!isPresent) { val response = client.indices().create(createIndexRequest(), RequestOptions.DEFAULT); if (!response.isAcknowledged()) { throw new RuntimeException("Index creation failed"); } log.info("Successfully created index: {}", properties.getDetectorIndexName()); } } catch (IOException e) { log.error("Index creation failed", e); throw new RuntimeException(e); } } }
Example #6
Source File: ChengfengReadyListener.java From ChengFeng1.5 with MIT License | 6 votes |
@Override public void onApplicationEvent(ApplicationReadyEvent event) { log.info("》》》》》》》》》》城风已就绪《《《《《《《《《《"); CommunityNoticeMapper communityNoticeMapper = event.getApplicationContext().getBean(CommunityNoticeMapper.class); ProperNoticeMapper properNoticeMapper = event.getApplicationContext().getBean(ProperNoticeMapper.class); StringRedisTemplate stringRedisTemplate=event.getApplicationContext().getBean(StringRedisTemplate.class); List<CommunityNotice> communityNotices = communityNoticeMapper.selectAllCommunities(); List<ProperNotice> properNotices = properNoticeMapper.selectAllPropers(); ZSetOperations<String, String> zset = stringRedisTemplate.opsForZSet(); HashOperations<String, Object, Object> hash = stringRedisTemplate.opsForHash(); communityNotices.parallelStream() .forEach(communityNotice ->{ zset.add(RedisConstant.COMMUNITY_NOTICE_ORDER+communityNotice.getCommunityId(),RedisConstant.COMMUNITY_NOTICE_PREFIX+communityNotice.getId(), new DateTime(communityNotice.getShowtime()).getMillis()); hash.put(RedisConstant.COMMUNITY_NOTICES+communityNotice.getCommunityId(),RedisConstant.COMMUNITY_NOTICE_PREFIX+communityNotice.getId(), JsonSerializableUtil.obj2String(communityNotice)); }); properNotices.parallelStream() .forEach(properNotice -> { zset.add(RedisConstant.PROPER_NOTICE_ORDER+properNotice.getUserId(),RedisConstant.PROPER_NOTICE_PREFIX+properNotice.getId(), new DateTime(properNotice.getShowtime()).getMillis()); hash.put(RedisConstant.PROPER_NOTICES+properNotice.getUserId(),RedisConstant.PROPER_NOTICE_PREFIX+properNotice.getId(), JsonSerializableUtil.obj2String(properNotice)); }); }
Example #7
Source File: IndexCreatorIfNotPresent.java From adaptive-alerting with Apache License 2.0 | 6 votes |
@Override public void onApplicationEvent(ApplicationReadyEvent applicationReadyEvent) { if (properties.isCreateIndexIfNotFound()) { try { boolean isPresent = client.indices().exists(getIndexRequest(), RequestOptions.DEFAULT); if (!isPresent) { val response = client.indices().create(createIndexRequest(), RequestOptions.DEFAULT); if (!response.isAcknowledged()) { throw new RuntimeException("Index creation failed"); } log.info("Successfully created index: {}", properties.getIndexName()); } } catch (IOException e) { log.error("Index creation failed", e); throw new RuntimeException(e); } } }
Example #8
Source File: StartupApplicationListener.java From spring-boot-graal-feature with Apache License 2.0 | 6 votes |
private Set<Class<?>> sources(ApplicationReadyEvent event) { Method method = ReflectionUtils.findMethod(SpringApplication.class, "getAllSources"); if (method == null) { method = ReflectionUtils.findMethod(SpringApplication.class, "getSources"); } ReflectionUtils.makeAccessible(method); @SuppressWarnings("unchecked") Set<Object> objects = (Set<Object>) ReflectionUtils.invokeMethod(method, event.getSpringApplication()); Set<Class<?>> result = new LinkedHashSet<>(); for (Object object : objects) { if (object instanceof String) { object = ClassUtils.resolveClassName((String) object, null); } result.add((Class<?>) object); } return result; }
Example #9
Source File: ShutdownApplicationListener.java From spring-boot-graal-feature with Apache License 2.0 | 6 votes |
private Set<Class<?>> sources(ApplicationReadyEvent event) { Method method = ReflectionUtils.findMethod(SpringApplication.class, "getAllSources"); if (method == null) { method = ReflectionUtils.findMethod(SpringApplication.class, "getSources"); } ReflectionUtils.makeAccessible(method); @SuppressWarnings("unchecked") Set<Object> objects = (Set<Object>) ReflectionUtils.invokeMethod(method, event.getSpringApplication()); Set<Class<?>> result = new LinkedHashSet<>(); for (Object object : objects) { if (object instanceof String) { object = ClassUtils.resolveClassName((String) object, null); } result.add((Class<?>) object); } return result; }
Example #10
Source File: ApplicationStartup.java From Refactoring-Bot with MIT License | 6 votes |
/** * This method opens the Swagger-UI in the browser on startup of the * application. */ @Override public void onApplicationEvent(ApplicationReadyEvent applicationReadyEvent) { Runtime runtime = Runtime.getRuntime(); String url = "http://localhost:" + port + "/swagger-ui.html#"; // Check OS-System String os = System.getProperty("os.name").toLowerCase(); try { // Windows if (os.contains("win")) { runtime.exec("rundll32 url.dll,FileProtocolHandler " + url); } // MacOS if (os.contains("mac")) { runtime.exec("open " + url); } // Linux if (os.contains("nix") || os.contains("nux")) { runtime.exec("xdg-open " + url); } } catch (IOException e) { logger.error("Could not open Swagger-UI in the browser!"); } }
Example #11
Source File: ReservationServiceApplication.java From bootiful-reactive-microservices with Apache License 2.0 | 6 votes |
@EventListener(ApplicationReadyEvent.class) public void serve() throws Exception { var abstractRSocket = new AbstractRSocket() { @Override public Flux<Payload> requestStream(Payload payload) { return reservationRepository.findAll() .map(RsocketServer.this::toJson) .map(DefaultPayload::create); } }; SocketAcceptor socketAcceptor = (connectionSetupPayload, rSocket) -> Mono.just(abstractRSocket); RSocketFactory .receive() .acceptor(socketAcceptor) .transport(this.tcp) .start() .subscribe(); }
Example #12
Source File: ApplicationEventListener.java From Almost-Famous with MIT License | 6 votes |
@Override public void onApplicationEvent(ApplicationEvent event) { if (event instanceof ApplicationEnvironmentPreparedEvent) { LOG.debug("初始化环境变量"); } else if (event instanceof ApplicationPreparedEvent) { LOG.debug("初始化完成"); LOG.debug("初始GameData策划数据"); ConfigManager.loadGameData(this.configPath); } else if (event instanceof ContextRefreshedEvent) { LOG.debug("应用刷新"); } else if (event instanceof ApplicationReadyEvent) { LOG.debug("应用已启动完成"); } else if (event instanceof ContextStartedEvent) { LOG.debug("应用启动,需要在代码动态添加监听器才可捕获"); } else if (event instanceof ContextStoppedEvent) { LOG.debug("应用停止"); } else if (event instanceof ContextClosedEvent) { ApplicationContext context = ((ContextClosedEvent) event).getApplicationContext(); rpcClient = context.getBean(RpcClient.class); rpcClient.close(); LOG.error("应用关闭"); } else { } }
Example #13
Source File: CommentSimulator.java From Learning-Spring-Boot-2.0-Second-Edition with MIT License | 6 votes |
@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(() -> controller.addComment(newComment))) .subscribe(); }
Example #14
Source File: MongoConfiguration.java From POC with Apache License 2.0 | 6 votes |
@EventListener(ApplicationReadyEvent.class) public void initIndicesAfterStartup() { log.info("Mongo InitIndicesAfterStartup init"); var init = System.currentTimeMillis(); var mappingContext = this.mongoTemplate.getConverter().getMappingContext(); if (mappingContext instanceof MongoMappingContext) { var resolver = IndexResolver.create(mappingContext); mappingContext.getPersistentEntities().stream().filter(clazz -> clazz.isAnnotationPresent(Document.class)) .forEach(o -> { IndexOperations indexOps = this.mongoTemplate.indexOps(o.getType()); resolver.resolveIndexFor(o.getType()).forEach(indexOps::ensureIndex); }); } log.info("Mongo InitIndicesAfterStartup took: {}", (System.currentTimeMillis() - init)); }
Example #15
Source File: INCEpTION.java From inception with Apache License 2.0 | 6 votes |
public static void main(String[] args) throws Exception { Optional<JWindow> splash = LoadingSplashScreen .setupScreen(INCEpTION.class.getResource("splash.png")); SpringApplicationBuilder builder = new SpringApplicationBuilder(); // Add the main application as the root Spring context builder.sources(INCEpTION.class).web(SERVLET); // Signal that we may need the shutdown dialog builder.properties("running.from.commandline=true"); init(builder); builder.listeners(event -> { if (event instanceof ApplicationReadyEvent || event instanceof ShutdownDialogAvailableEvent) { splash.ifPresent(it -> it.dispose()); } }); builder.run(args); }
Example #16
Source File: KafkaBasicsApplication.java From spring_io_2019 with Apache License 2.0 | 6 votes |
@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 #17
Source File: ApplicationStartup.java From graphql-java-demo with MIT License | 6 votes |
@Override public void onApplicationEvent(final ApplicationReadyEvent event) { try { List<InputConference> inputConferencess = CsvReader.loadObjectList(InputConference.class, "csv/conferences.csv"); for (InputConference inputConference : inputConferencess) { conferenceService.save(InputConference.convert(inputConference)); } List<InputPerson> speakers = CsvReader.loadObjectList(InputPerson.class, "csv/speakers.csv"); for (InputPerson speaker : speakers) { personService.save(InputPerson.convert(speaker)); } List<CsvTalk> talks = CsvReader.loadObjectList(CsvTalk.class, "csv/talks.csv"); for (CsvTalk talk : talks) { talkService.save(talk.convert(conferenceService, personService)); } } catch (IOException e) { log.error("Error loading data: " + e.getMessage()); } }
Example #18
Source File: UserDetailsServiceTestBaseClass.java From Spring with Apache License 2.0 | 5 votes |
@Override public void onApplicationEvent(ApplicationReadyEvent evt) { Consumer<UserDetails> process = user -> { this.userDetailsManager.deleteUser(user.getUsername()); this.userDetailsManager.createUser(user); }; Collection<UserDetails> userDetails = IntStream.range(0, 5) .mapToObj(i -> new User("user" + i, this.passwordEncoder.encode("password" + i), true, true, true, true, AuthorityUtils.createAuthorityList("USER"))) .collect(Collectors.toList()); userDetails.forEach(process); }
Example #19
Source File: GatewayInstanceInitializer.java From api-layer with Eclipse Public License 2.0 | 5 votes |
/** * EventListener method that starts the lookup for Gateway * Listens for {@link ApplicationReadyEvent} to start the {@link InstanceLookupExecutor} and provides the processing logic for the executor */ @EventListener(ApplicationReadyEvent.class) public void init() { if (gatewayClient.isInitialized()) { return; } log.info("GatewayInstanceInitializer starting asynchronous initialization of Gateway configuration"); instanceLookupExecutor.run( CoreService.GATEWAY.getServiceId(), instance -> { GatewayConfigProperties foundGatewayConfigProperties = process(instance); log.info( "GatewayInstanceInitializer has been initialized with Gateway instance on url: {}://{}", foundGatewayConfigProperties.getScheme(), foundGatewayConfigProperties.getHostname() ); gatewayClient.setGatewayConfigProperties(foundGatewayConfigProperties); applicationEventPublisher.publishEvent(new GatewayLookupCompleteEvent(this)); }, (exception, isStopped) -> { if (Boolean.TRUE.equals(isStopped)) { apimlLog.log("org.zowe.apiml.common.gatewayInstanceInitializerStopped", exception.getMessage()); } } ); }
Example #20
Source File: PingPongApp.java From spring-cloud-rsocket with Apache License 2.0 | 5 votes |
@Override public void onApplicationEvent(ApplicationReadyEvent event) { log.info("Starting Ping" + id); ConfigurableEnvironment env = event.getApplicationContext().getEnvironment(); Integer take = env.getProperty("ping.take", Integer.class, null); Integer gatewayPort = env.getProperty("spring.rsocket.server.port", Integer.class, 7002); log.debug("ping.take: " + take); MicrometerRSocketInterceptor interceptor = new MicrometerRSocketInterceptor( meterRegistry, Tag.of("component", "ping")); ByteBuf metadata = getRouteSetupMetadata(strategies, "ping", id); Payload setupPayload = DefaultPayload.create(EMPTY_BUFFER, metadata); pongFlux = RSocketFactory.connect().frameDecoder(PayloadDecoder.ZERO_COPY) .metadataMimeType(COMPOSITE_MIME_TYPE.toString()) .setupPayload(setupPayload).addRequesterPlugin(interceptor) .transport(TcpClientTransport.create(gatewayPort)) // proxy .start().log("startPing" + id) .flatMapMany(socket -> doPing(take, socket)).cast(String.class) .doOnSubscribe(o -> { if (log.isDebugEnabled()) { log.debug("ping doOnSubscribe"); } }); boolean subscribe = env.getProperty("ping.subscribe", Boolean.class, true); if (subscribe) { pongFlux.subscribe(); } }
Example #21
Source File: NodeServiceImpl.java From java-trader with Apache License 2.0 | 5 votes |
@EventListener(ApplicationReadyEvent.class) public void onAppReady() { String mgmtURL = ConfigUtil.getString(ITEM_MGMTURL); if ( StringUtil.isEmpty(mgmtURL) ){ logger.info("Node "+consistentId+" works in standalone mode"); }else { logger.info("Node "+consistentId+" mgmt service: "+mgmtURL); wsUrl = mgmtURL+NodeMgmtService.URI_WS_NODEMGMT; } if ( !StringUtil.isEmpty(wsUrl)) { recreateWsConnection(true); } }
Example #22
Source File: TaskLifecycleListenerTests.java From spring-cloud-task with Apache License 2.0 | 5 votes |
@Test public void testTaskUpdate() { this.context.refresh(); this.taskExplorer = this.context.getBean(TaskExplorer.class); this.context.publishEvent(new ApplicationReadyEvent(new SpringApplication(), new String[0], this.context)); verifyTaskExecution(0, true, 0); }
Example #23
Source File: ExitCodeGeneratorExceptionBootstrap.java From thinking-in-spring-boot-samples with Apache License 2.0 | 5 votes |
public static void main(String[] args) { new SpringApplicationBuilder(Object.class) .listeners( // event -> { // 取消所有 Spring Boot 事件监听 (ApplicationListener<ApplicationReadyEvent>) event -> { throw new ExitCodeGeneratorThrowable(event.getClass().getSimpleName()); }) .web(false) // 非 Web 应用 .run(args) // 运行 SpringApplication .close(); // 关闭 ConfigurableApplicationContext }
Example #24
Source File: ZookeeperConfigsInitializer.java From tutorials with MIT License | 5 votes |
@EventListener public void appReady(ApplicationReadyEvent event) throws Exception { String pathOne = APPLICATION_BASE_NODE_PATH + "/baeldung.archaius.properties.one"; String valueOne = "one FROM:zookeeper"; String pathThree = APPLICATION_BASE_NODE_PATH + "/baeldung.archaius.properties.three"; String valueThree = "three FROM:zookeeper"; createBaseNodes(); setValue(pathOne, valueOne); setValue(pathThree, valueThree); }
Example #25
Source File: ConsumerOffsetListenerContainerService.java From eventapis with Apache License 2.0 | 5 votes |
@org.springframework.context.event.EventListener public void onApplicationEvent(ApplicationReadyEvent applicationReadyEvent) { synchronized (listenerManagementLock) { if (defaultQuorum == null || defaultQuorum.isPresent()) { startListen(); } } }
Example #26
Source File: StartupNotification.java From spring-backend-boilerplate with Apache License 2.0 | 5 votes |
@Override public void onApplicationEvent(ApplicationReadyEvent event) { if (StringUtils.isEmpty(webhookConfigurationProperties.getUrl())) { return; } webHookClient.sendMessage(webhookConfigurationProperties.getUrl(), String.format("%s startup succeed.", getAppName())); }
Example #27
Source File: JsfTomcatApplicationListenerIT.java From joinfaces with Apache License 2.0 | 5 votes |
@Test public void resourcesNull() { Context standardContext = mock(Context.class); Mockito.when(standardContext.getResources()).thenReturn(null); Mockito.when(standardContext.getAddWebinfClassesResources()).thenReturn(Boolean.FALSE); JsfTomcatContextCustomizer jsfTomcatContextCustomizer = new JsfTomcatContextCustomizer(); jsfTomcatContextCustomizer.customize(standardContext); JsfTomcatApplicationListener jsfTomcatApplicationListener = new JsfTomcatApplicationListener(jsfTomcatContextCustomizer.getContext()); jsfTomcatApplicationListener.onApplicationEvent(mock(ApplicationReadyEvent.class)); assertThat(jsfTomcatApplicationListener) .isNotNull(); }
Example #28
Source File: ClientComponent.java From sample-webflux-websocket-netty with Apache License 2.0 | 5 votes |
@Override public void onApplicationEvent(ApplicationReadyEvent event) { ClientLogic clientLogic = new ClientLogic(); Disposable logicOne = clientLogic.start(webSocketClient, getURI(), new ClientWebSocketHandler()); Disposable logicTwo = clientLogic.start(webSocketClient, getURI(), new ClientWebSocketHandler()); Mono .delay(Duration.ofSeconds(10)) .doOnEach(value -> logicOne.dispose()) .doOnEach(value -> logicTwo.dispose()) .map(value -> SpringApplication.exit(applicationContext, () -> 0)) .subscribe(exitValue -> System.exit(exitValue)); }
Example #29
Source File: WingtipsReactorInitializer.java From wingtips with Apache License 2.0 | 5 votes |
/** * Register a {@link reactor.core.scheduler.Scheduler} hook when a Spring Boot application is ready, * that ensures that when a thread is borrowed, tracing details are propagated to the thread. * * @param event The {@link ApplicationReadyEvent} (ignored). */ @Override public void onApplicationEvent(ApplicationReadyEvent event) { if (enabled) { Schedulers.addExecutorServiceDecorator( WINGTIPS_SCHEDULER_KEY, (scheduler, schedulerService) -> new ScheduledExecutorServiceWithTracing(schedulerService) ); } }
Example #30
Source File: ExitCodeGeneratorExceptionBootstrap.java From thinking-in-spring-boot-samples with Apache License 2.0 | 5 votes |
public static void main(String[] args) { new SpringApplicationBuilder(Object.class) .listeners( // event -> { // 取消所有 Spring Boot 事件监听 (ApplicationListener<ApplicationReadyEvent>) event -> { throw new ExitCodeGeneratorThrowable(event.getClass().getSimpleName()); }) .web(false) // 非 Web 应用 .run(args) // 运行 SpringApplication .close(); // 关闭 ConfigurableApplicationContext }