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

The following examples show how to use org.springframework.boot.context.event.ApplicationStartedEvent. 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: openvsx   Source File: LicenseInitializer.java    License: Eclipse Public License 2.0 6 votes vote down vote up
@EventListener
@Transactional
public void initExtensionLicenses(ApplicationStartedEvent event) {
    var detection = new LicenseDetection(Arrays.asList(detectLicenseIds));
    var undetected = new int[1];
    repositories.findVersionsByLicense(null).forEach(extVersion -> {
        var license = repositories.findFile(extVersion, FileResource.LICENSE);
        if (license != null) {
            var detectedId = detection.detectLicense(license.getContent());
            if (detectedId == null) {
                undetected[0]++;
            } else {
                extVersion.setLicense(detectedId);
                var extension = extVersion.getExtension();
                logger.info("License of " + extension.getNamespace().getName() + "." + extension.getName()
                        + " v" + extVersion.getVersion() + " set to " + detectedId);
            }
        }
    });

    if (undetected[0] > 0)
        logger.warn("Failed to detect license type for " + undetected[0] + " extensions.");
}
 
Example 2
@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 3
Source Project: x7   Source File: RepositoryListener.java    License: Apache License 2.0 6 votes vote down vote up
private void customizeDataTransform(ApplicationStartedEvent applicationStartedEvent) {
    DataTransformCustomizer customizer = null;
    try {
        customizer = applicationStartedEvent.getApplicationContext().getBean(DataTransformCustomizer.class);
    } catch (Exception e) {

    }

    if (customizer == null)
        return;

    DataTransform dataTransform = customizer.customize();
    if (dataTransform == null)
        return;

    Repository repository = applicationStartedEvent.getApplicationContext().getBean(Repository.class);
    if (repository == null)
        return;
    ((CacheableRepository) repository).setDataTransform(dataTransform);
}
 
Example 4
Source Project: x7   Source File: RepositoryListener.java    License: Apache License 2.0 6 votes vote down vote up
private void customizeL2CacheConsistency(ApplicationStartedEvent applicationStartedEvent) {
    L2CacheConsistencyCustomizer customizer = null;
    try {
        customizer = applicationStartedEvent.getApplicationContext().getBean(L2CacheConsistencyCustomizer.class);
    } catch (Exception e) {

    }

    if (customizer == null || customizer.customize() == null)
        return;

    L2CacheResolver levelTwoCacheResolver = applicationStartedEvent.getApplicationContext().getBean(L2CacheResolver.class);
    if (levelTwoCacheResolver == null)
        return;
    levelTwoCacheResolver.setL2CacheConsistency(customizer.customize());
}
 
Example 5
Source Project: tomato   Source File: TomatoStartListener.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void onApplicationEvent(ApplicationEvent applicationEvent) {
    if (applicationEvent instanceof ApplicationStartedEvent) {
        Idempotent idempotent = applicationContext.getBean(Idempotent.class);
        if (idempotent != null) {
            Banner.print();
        }
    }
}
 
Example 6
Source Project: openvsx   Source File: SearchService.java    License: Eclipse Public License 2.0 5 votes vote down vote up
@EventListener
@Transactional
public void initSearchIndex(ApplicationStartedEvent event) {
    if (!isEnabled()) {
        return;
    }
    var stopWatch = new StopWatch();
    stopWatch.start();
    updateSearchIndex();
    stopWatch.stop();
    logger.info("Initialized search index in " + stopWatch.getTotalTimeMillis() + " ms");
}
 
Example 7
Source Project: openvsx   Source File: VersionInitializer.java    License: Eclipse Public License 2.0 5 votes vote down vote up
@EventListener
@Transactional
public void initExtensionLicenses(ApplicationStartedEvent event) {
    var count = new int[2];
    repositories.findAllExtensions().forEach(extension -> {
        ExtensionVersion latest = null;
        SemanticVersion latestVer = null;
        ExtensionVersion preview = null;
        SemanticVersion previewVer = null;
        for (var extVersion : extension.getVersions()) {
            var ver = new SemanticVersion(extVersion.getVersion());
            if (extVersion.isPreview() && isGreater(extVersion, ver, preview, previewVer)) {
                preview = extVersion;
                previewVer = ver;
            } else if (!extVersion.isPreview() && isGreater(extVersion, ver, latest, latestVer)) {
                latest = extVersion;
                latestVer = ver;
            }
        }
        if (latest != null && latest != extension.getLatest()) {
            extension.setLatest(latest);
            count[0]++;
        }
        if (preview != null && preview != extension.getPreview()) {
            extension.setPreview(preview);
            count[1]++;
        }
    });

    if (count[0] > 0)
        logger.info("Updated latest version for " + count[0] + " extensions.");
    if (count[1] > 0)
        logger.info("Updated preview version for " + count[1] + " extensions.");
}
 
Example 8
Source Project: SENS   Source File: StartedListener.java    License: GNU General Public License v3.0 5 votes vote down vote up
@Override
    public void onApplicationEvent(ApplicationStartedEvent event) {
        try {
            this.loadActiveTheme();
        } catch (TemplateModelException e) {
            e.printStackTrace();
        }
        this.loadOptions();
        this.loadOwo();
        //启动定时任务
//        CronUtil.start();
        log.info("The scheduled task starts successfully!");
    }
 
Example 9
@EventListener(ApplicationStartedEvent.class)
public void appStart() {
    if (employeeRepository.count().block() == 0) {
        IntStream.range(0, 100)
                .mapToObj(this::generate)
                .map(employeeRepository::save)
                .collect(Collectors.toList())
                .forEach(item -> item.subscribe(System.out::println));
    }
}
 
Example 10
Source Project: stone   Source File: StartedListener.java    License: GNU General Public License v3.0 5 votes vote down vote up
@Override
public void onApplicationEvent(ApplicationStartedEvent event) {
    try {
        this.loadActiveTheme();
    } catch (TemplateModelException e) {
        e.printStackTrace();
    }
    this.loadOptions();
    this.loadThemes();
    this.loadOwo();
    //启动定时任务
    CronUtil.start();
    log.info("The scheduled task starts successfully!");
}
 
Example 11
Source Project: sbp   Source File: MainAppStartedListener.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void onApplicationEvent(ApplicationStartedEvent event) {
    pluginManager.getPlugins(PluginState.STARTED).forEach(pluginWrapper -> {
        SpringBootPlugin springBootPlugin = (SpringBootPlugin) pluginWrapper.getPlugin();
        ApplicationContext pluginAppCtx = springBootPlugin.getApplicationContext();
        pluginAppCtx.publishEvent(new SbpMainAppStartedEvent(applicationContext));
    });
    pluginManager.setMainApplicationStarted(true);
}
 
Example 12
public static void main(String[] args) {
    new SpringApplicationBuilder(Object.class)
            .listeners((ApplicationListener<ApplicationStartedEvent>) event -> {
                System.out.println("监听 Spring Boot 事件 ApplicationStartedEvent");
            }, (ApplicationListener<ApplicationStartingEvent>) event -> {
                System.out.println("监听 Spring Boot 事件 ApplicationStartingEvent ");
            })
            .web(false) // 非 Web 应用
            .run(args)  // 运行 SpringApplication
            .close();   // 关闭 Spring 应用上下文
}
 
Example 13
Source Project: Taroco   Source File: RouteConfigInitListener.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Callback used to run the bean.
 * 初始化路由配置的数据,避免gateway 依赖业务模块
 */
@Override
public void onApplicationEvent(ApplicationStartedEvent event) {
    log.info("开始初始化路由配置数据");
    QueryWrapper<SysRoute> wrapper = new QueryWrapper<>();
    wrapper.eq(CommonConstant.DEL_FLAG, CommonConstant.STATUS_NORMAL);
    List<SysRoute> routeList = sysRouteService.list(wrapper);
    if (!CollectionUtils.isEmpty(routeList)) {
        redisRepository.set(CacheConstants.ROUTE_KEY, JsonUtils.toJsonString(routeList));
        log.info("更新Redis中路由配置数据:{}条", routeList.size());
    }
    log.info("初始化路由配置数据完毕");
}
 
Example 14
Source Project: BlogManagePlatform   Source File: ValidateCodeChecker.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void onApplicationEvent(ApplicationStartedEvent event) {
	try {
		if (codeChecker.needCheck()) {
			log.info("[frodez.config.validator.ValidateChecker]hibernate-validator代码校验开始");
			check();
			log.info("[frodez.config.validator.ValidateChecker]hibernate-validator代码校验结束");
		} else {
			log.info("[frodez.config.validator.ValidateChecker]未开启hibernate-validator代码校验功能");
		}
	} catch (IOException | ClassNotFoundException | LinkageError e) {
		log.error("[frodez.config.validator.ValidateChecker]发生错误,程序终止", e);
		ContextUtil.exit();
	}
}
 
Example 15
Source Project: blog-sharon   Source File: StartedListener.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void onApplicationEvent(ApplicationStartedEvent event) {
    try {
        this.loadActiveTheme();
    } catch (TemplateModelException e) {
        e.printStackTrace();
    }
    this.loadOptions();
    this.loadThemes();
    this.loadOwo();
    //启动定时任务
    CronUtil.start();
    log.info("The scheduled task starts successfully!");
}
 
Example 16
@Override
public void onApplicationEvent(ApplicationStartedEvent event) {
    List<BindingParam> bindingParams = new ArrayList<>();
    bindingParams.add(new RestBindingParam());

    ServiceParam serviceParam = new ServiceParam();
    serviceParam.setInterfaceType(SwaggerService.class);
    serviceParam.setInstance(new SwaggerServiceImpl());
    serviceParam.setBindingParams(bindingParams);

    ServiceClient serviceClient = clientFactory.getClient(ServiceClient.class);
    serviceClient.service(serviceParam);
}
 
Example 17
Source Project: halo   Source File: StartedListener.java    License: GNU General Public License v3.0 5 votes vote down vote up
@Override
public void onApplicationEvent(ApplicationStartedEvent event) {
    try {
        this.migrate();
    } catch (SQLException e) {
        log.error("Failed to migrate database!", e);
    }
    this.initThemes();
    this.initDirectory();
    this.printStartInfo();
}
 
Example 18
@EventListener
@Order(Ordered.HIGHEST_PRECEDENCE + 1)
public void onApplicationStartedEvent(ApplicationStartedEvent applicationStartedEvent) throws TemplateModelException {
    log.debug("Received application started event");

    loadThemeConfig();
    loadOptionsConfig();
    loadUserConfig();
}
 
Example 19
/**
 * This event is executed as late as conceivably possible to indicate that 
 * the application is ready to service requests.
 */

@Override
public void onApplicationEvent(final ApplicationStartedEvent applicationStartedEvent) {
	//System.out.println("DEBUGGING: Found new Spring Boot App property : " + applicationStartedEvent.getApplicationContext().getEnvironment().getProperty("spring.cloud.stream.bindings.input.group"));

	System.out.println("======= ApplicationStartingEvent ===== ");
    System.out.println("What is the Event Hubs Consumer Group Name?");
	System.out.println("NOTIFICATIONS_EVENT_HUB_CONSUMER_GROUP_NAME=" +
			applicationStartedEvent.
					getApplicationContext().
					getEnvironment().
					getProperty("spring.cloud.stream.bindings.input.group"));
}
 
Example 20
Source Project: x7   Source File: ReyListener.java    License: Apache License 2.0 5 votes vote down vote up
private void customizeRestTemplate(ApplicationStartedEvent event) {

        try {
            RestTemplateCustomizer bean = event.getApplicationContext().getBean(RestTemplateCustomizer.class);
            if (bean == null)
                return;
            SimpleRestTemplate simpleRestTemplate = bean.customize();
            if (simpleRestTemplate == null)
                return;
            HttpClientResolver.setRestTemplate(simpleRestTemplate);
        }catch (Exception e) {

        }
    }
 
Example 21
Source Project: x7   Source File: RepositoryListener.java    License: Apache License 2.0 5 votes vote down vote up
private void txConfig(ApplicationStartedEvent event){
    try {
        PlatformTransactionManager platformTransactionManager = event.getApplicationContext().getBean(PlatformTransactionManager.class);
        if (platformTransactionManager == null)
            return;
        new TxConfig(platformTransactionManager);
    }catch (Exception e){

    }
}
 
Example 22
Source Project: joinfaces   Source File: JoinfacesApplicationAnalyzer.java    License: Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public void onApplicationEvent(ApplicationStartedEvent event) {
	try {
		Class<? extends Annotation> managedBeanClass = (Class<? extends Annotation>) Class.forName("javax.faces.bean.ManagedBean");
		warnAboutJsfManagedBeans(event.getApplicationContext(), managedBeanClass);
	}
	catch (ClassNotFoundException | LinkageError ignored) {
	}
}
 
Example 23
@Test
public void testJsfManagedBeans() {
	this.applicationContextRunner
			.withUserConfiguration(DummyConfiguration.class)
			.run(context -> {
				assertThat(context.getBeanNamesForAnnotation(ManagedBean.class)).isNotEmpty();

				ApplicationStartedEvent applicationStartedEvent = mock(ApplicationStartedEvent.class);
				when(applicationStartedEvent.getApplicationContext()).thenReturn(context.getSourceApplicationContext());

				this.joinfacesApplicationAnalyzer.onApplicationEvent(applicationStartedEvent);
			});
}
 
Example 24
@Test
public void issue_notDecryptedDuringBoostrapPhase() {
	// making spring.cloud.bootstrap.enabled=true in order to bootstrap the application.
	// making jasypt.encryptor.bootstrap=false otherwise JasyptSpringCloudBootstrapConfiguration becomes active.
	startWith(new BaseBootstrappingTestListener() {
		
		@Override
		public void onApplicationEvent(final ApplicationStartedEvent event) {
			assertEquals("ENC() value is not decrypted during bootstrap phase", "mypassword", event.getApplicationContext().getEnvironment().getProperty("spring.cloud.config.server.svn.password"));
		}
	}, "--spring.cloud.bootstrap.enabled=true", "--jasypt.encryptor.bootstrap=false");
	
	assertNotNull(this.context.getBean(EnableEncryptablePropertiesBeanFactoryPostProcessor.class));
}
 
Example 25
@Test
public void fix_decryptedDuringBoostrapPhase() {
	// making spring.cloud.bootstrap.enabled=true in order to bootstrap the application.
	// making jasypt.encryptor.bootstrap=true in order to bootstrap Jasypt.
	startWith(new BaseBootstrappingTestListener() {
		
		@Override
		public void onApplicationEvent(final ApplicationStartedEvent event) {
			assertEquals("ENC() value is decrypted during bootstrap phase", "mypassword", event.getApplicationContext().getEnvironment().getProperty("spring.cloud.config.server.svn.password"));
		}
	}, "--spring.cloud.bootstrap.enabled=true", "--jasypt.encryptor.bootstrap=true");
	
	assertNotNull(this.context.getBean(EnableEncryptablePropertiesBeanFactoryPostProcessor.class));
}
 
Example 26
@Test
public void encryptableBFPPBeanCreatedWhenBoostrapTrue() {
	startWith(new BaseBootstrappingTestListener() {

		@Override
		public void onApplicationEvent(final ApplicationStartedEvent event) {
			assertEquals("ENC() value is decrypted during bootstrap phase", "mypassword", event.getApplicationContext().getEnvironment().getProperty("spring.cloud.config.server.svn.password"));
		}
	}, "--spring.cloud.bootstrap.enabled=true");
	assertNotNull("EnableEncryptablePropertiesBeanFactoryPostProcessor not created when spring.cloud.bootstrap.enabled=true", 
			this.context.getBean(EnableEncryptablePropertiesBeanFactoryPostProcessor.class));
}
 
Example 27
@Test
public void encryptableBFPPBeanCreatedWhenBoostrapFalse() {
	startWith(new BaseBootstrappingTestListener() {

		@Override
		public void onApplicationEvent(final ApplicationStartedEvent event) {
			assertNotEquals("ENC() value is decrypted during bootstrap phase", "mypassword", event.getApplicationContext().getEnvironment().getProperty("spring.cloud.config.server.svn.password"));
		}
	}, "--spring.cloud.bootstrap.enabled=false");
	assertNotNull("EnableEncryptablePropertiesBeanFactoryPostProcessor not created when spring.cloud.bootstrap.enabled=false", 
			this.context.getBean(EnableEncryptablePropertiesBeanFactoryPostProcessor.class));
}
 
Example 28
Source Project: micro-service   Source File: StartedEventApplicationListener.java    License: MIT License 5 votes vote down vote up
@Override
public void onApplicationEvent(ApplicationStartedEvent event) {
	
	SpringApplication app = event.getSpringApplication();
       app.setBannerMode(Mode.OFF);
       
	logger.info("1 spring boot启动, StartedEventApplicationListener...");
}
 
Example 29
Source Project: cim   Source File: CIMConfig.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void onApplicationEvent(ApplicationStartedEvent applicationStartedEvent) {

	appHandlerMap.put("client_bind",applicationContext.getBean(BindHandler.class));
	appHandlerMap.put("client_closed",applicationContext.getBean(SessionClosedHandler.class));

	applicationContext.getBean(CIMNioSocketAcceptor.class).bind();
}
 
Example 30
Source Project: Milkomeda   Source File: DelayTimer.java    License: MIT License 4 votes vote down vote up
@Override
public void onApplicationEvent(@NonNull ApplicationStartedEvent event) {
    taskScheduler.scheduleWithFixedDelay(delegatingDelayJobHandler, props.getDelayBucketPollRate());
}