Java Code Examples for org.springframework.boot.context.event.ApplicationReadyEvent

The following examples show how to use org.springframework.boot.context.event.ApplicationReadyEvent. 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: ChengFeng1.5   Source File: ChengfengReadyListener.java    License: MIT License 6 votes vote down vote up
@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 2
@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 3
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 4
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 5
Source Project: graphql-java-demo   Source File: ApplicationStartup.java    License: MIT License 6 votes vote down vote up
@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 6
/**
 * 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 7
@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 8
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 9
Source Project: blog-spring   Source File: BroccoliServer.java    License: MIT License 6 votes vote down vote up
@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 10
Source Project: POC   Source File: MongoConfiguration.java    License: Apache License 2.0 6 votes vote down vote up
@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 11
Source Project: Almost-Famous   Source File: ApplicationEventListener.java    License: MIT License 6 votes vote down vote up
@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 12
@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 13
@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 14
@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 15
Source Project: inception   Source File: INCEpTION.java    License: Apache License 2.0 6 votes vote down vote up
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 Project: Refactoring-Bot   Source File: ApplicationStartup.java    License: MIT License 6 votes vote down vote up
/**
 * 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 17
Source Project: mercury   Source File: SpringEventListener.java    License: Apache License 2.0 6 votes vote down vote up
@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 18
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 19
Source Project: ReCiter   Source File: Application.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * This function will load all the necessary data from files folder to dynamodb
 */
@EventListener(ApplicationReadyEvent.class)
public void loadDynamoDbTablesAfterStartUp() {
	if(isFileImport) {
		ScienceMetrixDepartmentCategoryFileImport scienceMetrixDepartmentCategoryFileImport = ApplicationContextHolder.getContext().getBean(ScienceMetrixDepartmentCategoryFileImport.class);
		scienceMetrixDepartmentCategoryFileImport.importScienceMetrixDepartmentCategory();
		
		ScienceMetrixFileImport scienceMetrixFileImport = ApplicationContextHolder.getContext().getBean(ScienceMetrixFileImport.class);
		scienceMetrixFileImport.importScienceMetrix();
		
		MeshTermFileImport meshTermFileImport = ApplicationContextHolder.getContext().getBean(MeshTermFileImport.class);
		meshTermFileImport.importMeshTerms();
		
		IdentityFileImport identityFileImport = ApplicationContextHolder.getContext().getBean(IdentityFileImport.class);
		identityFileImport.importIdentity();
		
		if(useGenderStrategy) {
			GenderFileImport genderFileImport = ApplicationContextHolder.getContext().getBean(GenderFileImport.class);
			genderFileImport.importGender();
		} else {
			log.info("Gender strategy use is set to false. Please update strategy.gender to true in application.properties file to use it.\n"
		+ "Its recommened to use this strategy to get better scores.");
		}
		
		if(useScopusArticles) {
			InstitutionAfidFileImport institutionAfidFileImport = ApplicationContextHolder.getContext().getBean(InstitutionAfidFileImport.class);
			institutionAfidFileImport.importInstitutionAfids();
		}
	}
}
 
Example 20
@Test
void givenApplicationReadyEvent_whenEurekaRegisterEvent_thenCallRegisterEventListener() {
    EurekaClient eurekaClient = mock(EurekaClient.class);
    EurekaEventsRegistry eventRegister = new EurekaEventsRegistry(eurekaClient,
        Collections.singletonList(mock(RibbonMetadataProcessor.class)));

    eventRegister.onApplicationEvent(mock(ApplicationReadyEvent.class));

    verify(eurekaClient, times(1)).registerEventListener(any());
}
 
Example 21
@Override
public void onApplicationEvent(ApplicationReadyEvent event) {
    if (!event.getApplicationContext().equals(this.context)) {
        return;
    }
    if (isSpringBootApplication(sources(event))) {
        ((DefaultListableBeanFactory) event.getApplicationContext().getBeanFactory())
                .registerDisposableBean(SHUTDOWN_LISTENER, this);
    }
}
 
Example 22
Source Project: eds-starter6-jpa   Source File: DevelopmentConfig.java    License: Apache License 2.0 5 votes vote down vote up
@EventListener
public void handleContextRefresh(ApplicationReadyEvent event) throws IOException {
	String extDirectConfig = ExtDirectSpringUtil
			.generateApiString(event.getApplicationContext());
	String userDir = System.getProperty("user.dir");
	Files.write(Paths.get(userDir, "client", "api.js"),
			extDirectConfig.getBytes(StandardCharsets.UTF_8));

	Path clientDir = Paths.get(userDir, "client");
	writeI18n(clientDir);
	writeEnums(clientDir);
}
 
Example 23
Source Project: mPass   Source File: SystemReadyListener.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void onApplicationEvent(ApplicationReadyEvent event) {
    // 保存插件
    if (SystemLoadListener.LOADER.pluginLoader != null) {
        SystemLoadListener.LOADER.pluginLoader.save();
        SystemLoadListener.LOADER.pluginLoader = null;
    }
    // 保存模块
    if (SystemLoadListener.LOADER.moduleLoader != null) {
        SystemLoadListener.LOADER.moduleLoader.save();
        SystemLoadListener.LOADER.moduleLoader = null;
    }
    // 激活插件变化监听
    activeListener();
}
 
Example 24
Source Project: spring-cloud-dataflow   Source File: ConfigCommands.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Will execute the targeting of the Data Flow server ONLY if the shell
 * is executing shell command passed directly from the console using
 * {@code --spring.shell.commandFile}.
 *
 * see also: https://github.com/spring-projects/spring-shell/issues/252
 */
@Override
public void onApplicationEvent(ApplicationReadyEvent event) {
	// Only invoke if the shell is executing in the same application context as the data flow server.
	if (!initialized && this.commandLine.getShellCommandsToExecute() != null) {
		triggerTarget();
	}
}
 
Example 25
/**
 * Verify that if a TaskExecutionListener Bean is present that the onTaskEnd method is
 * called.
 */
@Test
public void testTaskUpdate() {
	setupContextForTaskExecutionListener();
	DefaultTaskListenerConfiguration.TestTaskExecutionListener taskExecutionListener = this.context
			.getBean(
					DefaultTaskListenerConfiguration.TestTaskExecutionListener.class);
	this.context.publishEvent(new ApplicationReadyEvent(new SpringApplication(),
			new String[0], this.context));

	TaskExecution taskExecution = new TaskExecution(0, 0, "wombat", new Date(),
			new Date(), null, new ArrayList<>(), null, null);
	verifyListenerResults(true, false, taskExecution, taskExecutionListener);
}
 
Example 26
Source Project: cloud-spanner-r2dbc   Source File: SpringDataR2dbcApp.java    License: Apache License 2.0 5 votes vote down vote up
@EventListener(ApplicationReadyEvent.class)
public void setUpData() {
  LOGGER.info("Setting up test table BOOK...");
  try {
    r2dbcClient.execute("CREATE TABLE BOOK ("
        + "  ID STRING(36) NOT NULL,"
        + "  TITLE STRING(MAX) NOT NULL"
        + ") PRIMARY KEY (ID)")
        .fetch().rowsUpdated().block();
  } catch (Exception e) {
    LOGGER.info("Failed to set up test table BOOK", e);
    return;
  }
  LOGGER.info("Finished setting up test table BOOK");
}
 
Example 27
@EventListener
@Order(Ordered.LOWEST_PRECEDENCE)
public void onApplicationReady(ApplicationReadyEvent event) {
	if (autoRegister) {
		startRegisterTask();
	}
}
 
Example 28
Source Project: spring_io_2019   Source File: AzureApplication.java    License: Apache License 2.0 5 votes vote down vote up
@EventListener(ApplicationReadyEvent.class)
public void demo() throws Exception {

	this.rr.deleteAll();

	Stream.of("A", "B", "C")
		.map(name -> new Reservation(null, name))
		.map(this.rr::save)
		.forEach(log::info);

}
 
Example 29
Source Project: java-trader   Source File: MarketDataServiceImpl.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 启动后, 连接行情数据源
 */
@EventListener(ApplicationReadyEvent.class)
public void onApplicationReady(){
    state = ServiceState.Ready;
    executorService.execute(()->{
        for(AbsMarketDataProducer p:producers.values()) {
            if ( p.getState()==ConnState.Initialized ) {
                p.connect();
            }
        }
    });
}
 
Example 30
Source Project: joinfaces   Source File: JsfTomcatApplicationListenerIT.java    License: Apache License 2.0 5 votes vote down vote up
@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();
}