org.springframework.context.event.ContextRefreshedEvent Java Examples

The following examples show how to use org.springframework.context.event.ContextRefreshedEvent. 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: SpringProcessApplication.java    From camunda-bpm-platform with Apache License 2.0 6 votes vote down vote up
@Override
public void onApplicationEvent(ApplicationContextEvent event) {
  try {
    // we only want to listen for context events of the main application
    // context, not its children
    if (event.getSource().equals(applicationContext)) {
      if (event instanceof ContextRefreshedEvent && !isDeployed) {
        // deploy the process application
        afterPropertiesSet();
      } else if (event instanceof ContextClosedEvent) {
        // undeploy the process application
        destroy();
      } else {
        // ignore
      }
    }
  } catch (Exception e) {
    throw new RuntimeException(e);
  }
}
 
Example #2
Source File: SyncopeCoreTestingServer.java    From syncope with Apache License 2.0 6 votes vote down vote up
@Override
public void onApplicationEvent(final ContextRefreshedEvent event) {
    synchronized (ADDRESS) {
        if (serviceOps.list(NetworkService.Type.CORE).isEmpty()) {
            // 1. start (mocked) Core as embedded CXF
            JAXRSServerFactoryBean sf = new JAXRSServerFactoryBean();
            sf.setAddress(ADDRESS);
            sf.setResourceClasses(WAClientAppService.class, GoogleMfaAuthTokenService.class);
            sf.setResourceProvider(
                    WAClientAppService.class,
                    new SingletonResourceProvider(new StubWAClientAppService(), true));
            sf.setResourceProvider(
                    GoogleMfaAuthTokenService.class,
                    new SingletonResourceProvider(new StubGoogleMfaAuthTokenService(), true));
            sf.setProviders(List.of(new JacksonJsonProvider()));
            sf.create();

            // 2. register Core in Keymaster
            NetworkService core = new NetworkService();
            core.setType(NetworkService.Type.CORE);
            core.setAddress(ADDRESS);
            serviceOps.register(core);
        }
    }
}
 
Example #3
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 #4
Source File: JobServiceBoostrap.java    From usergrid with Apache License 2.0 6 votes vote down vote up
@Override
public void onApplicationEvent( ContextRefreshedEvent event ) {
    String start = properties.getProperty( START_SCHEDULER_PROP, "true" );
    if ( Boolean.parseBoolean( start ) ) {
        logger.info( "Starting Scheduler Service..." );
        jobScheduler.startAsync();
        jobScheduler.awaitRunning();

    } else {
        logger.info( "Scheduler Service disabled" );
    }

    boolean shouldRun = new Boolean(properties.getProperty("usergrid.notifications.listener.run","true"));
    if(shouldRun){
        notificationsQueueListener.start();
    }else{
        logger.info("QueueListener: never started due to config value usergrid.notifications.listener.run.");
    }

}
 
Example #5
Source File: FunctionEndpointInitializer.java    From spring-cloud-function with Apache License 2.0 6 votes vote down vote up
@Override
public void onApplicationEvent(ApplicationEvent event) {
	ApplicationContext context = ((ContextRefreshedEvent) event).getApplicationContext();
	if (context != this.context) {
		return;
	}
	if (!ClassUtils.isPresent("org.springframework.http.server.reactive.HttpHandler", null)) {
		logger.info("No web server classes found so no server to start");
		return;
	}
	Integer port = Integer.valueOf(context.getEnvironment().resolvePlaceholders("${server.port:${PORT:8080}}"));
	String address = context.getEnvironment().resolvePlaceholders("${server.address:0.0.0.0}");
	if (port >= 0) {
		HttpHandler handler = context.getBean(HttpHandler.class);
		ReactorHttpHandlerAdapter adapter = new ReactorHttpHandlerAdapter(handler);
		HttpServer httpServer = HttpServer.create().host(address).port(port).handle(adapter);
		Thread thread = new Thread(
				() -> httpServer.bindUntilJavaShutdown(Duration.ofSeconds(60), this::callback),
				"server-startup");
		thread.setDaemon(false);
		thread.start();
	}
}
 
Example #6
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 #7
Source File: SwarmAdapterConfiguration.java    From haven-platform with Apache License 2.0 6 votes vote down vote up
@Override
public void onApplicationEvent(ContextRefreshedEvent event) {
    try (TempAuth auth = TempAuth.asSystem()) {
        Map<String, ClusterConfigImpl.Builder> configs = swarmsConfig.getConfigs();
        DiscoveryStorageImpl storage = storageFactory.getObject();
        if(CollectionUtils.isEmpty(configs)) {
            LoggerFactory.getLogger(getClass()).info("No configs in " + swarmsConfig);
        } else {
            for(Map.Entry<String, ClusterConfigImpl.Builder> e: configs.entrySet()) {
                String cluster = e.getKey();
                ClusterConfigImpl.Builder config = ClusterConfigImpl.builder().from(e.getValue());
                config.cluster(cluster);
                SwarmNodesGroupConfig ngc = new SwarmNodesGroupConfig();
                ngc.setConfig(config.build());
                ngc.setName(cluster);
                storage.getOrCreateGroup(ngc);
            }
        }
        storage.load();
    }
}
 
Example #8
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.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 #9
Source File: ExchangeSpringEvent.java    From ZTuoExchange_framework with MIT License 6 votes vote down vote up
@Override
public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) {
    log.info("======程序启动成功======");
    coinTraderFactory.getTraderMap();
    HashMap<String,CoinTrader> traders = coinTraderFactory.getTraderMap();
    traders.forEach((symbol,trader) ->{
        List<ExchangeOrder> orders = exchangeOrderService.findAllTradingOrderBySymbol(symbol);
        List<ExchangeOrder> tradingOrders = new ArrayList<>();
        orders.forEach(order -> {
            BigDecimal tradedAmount = BigDecimal.ZERO;
            BigDecimal turnover = BigDecimal.ZERO;
            List<ExchangeOrderDetail> details = exchangeOrderDetailService.findAllByOrderId(order.getOrderId());
            order.setDetail(details);
            for(ExchangeOrderDetail trade:details){
                tradedAmount = tradedAmount.add(trade.getAmount());
                turnover = turnover.add(trade.getAmount().multiply(trade.getPrice()));
            }
            order.setTradedAmount(tradedAmount);
            order.setTurnover(turnover);
            if(!order.isCompleted()){
                tradingOrders.add(order);
            }
        });
        trader.trade(tradingOrders);
    });
}
 
Example #10
Source File: LicenseCheckListener.java    From LicenseDemo with Apache License 2.0 6 votes vote down vote up
@Override
public void onApplicationEvent(ContextRefreshedEvent event) {
    //root application context 没有parent
    ApplicationContext context = event.getApplicationContext().getParent();
    if(context == null){
        if(StringUtils.isNotBlank(licensePath)){
            logger.info("++++++++ 开始安装证书 ++++++++");

            LicenseVerifyParam param = new LicenseVerifyParam();
            param.setSubject(subject);
            param.setPublicAlias(publicAlias);
            param.setStorePass(storePass);
            param.setLicensePath(licensePath);
            param.setPublicKeysStorePath(publicKeysStorePath);

            LicenseVerify licenseVerify = new LicenseVerify();
            //安装证书
            licenseVerify.install(param);

            logger.info("++++++++ 证书安装结束 ++++++++");
        }
    }
}
 
Example #11
Source File: EnvironmentConfigurationLogger.java    From pcf-crash-course-with-spring-boot 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 -> {
					LOGGER.info("{}", prop);
//					Object resolved = environment.getProperty(prop, Object.class);
//					if (resolved instanceof String) {
//						LOGGER.info("{}", environment.getProperty(prop));
//					}
				});
		LOGGER.info("===========================================");
	}
 
Example #12
Source File: PermissionInitializationTest.java    From credhub with Apache License 2.0 6 votes vote down vote up
@Test
public void itDoesNotOverwriteExistingPermissions() {
  final PermissionEntry permissionEntry = new PermissionEntry();
  permissionEntry.setActor(actors.get(0));
  permissionEntry.setAllowedOperations(Arrays.asList(PermissionOperation.READ, PermissionOperation.WRITE, PermissionOperation.READ_ACL, PermissionOperation.WRITE_ACL));
  permissionEntry.setPath("/test/path");
  permissionService.savePermissions(Arrays.asList(permissionEntry));

  applicationEventPublisher.publishEvent(new ContextRefreshedEvent(applicationContext));

  final List<PermissionData> savedPermissions = permissionRepository.findAllByPath(credentialPath);
  assertThat(savedPermissions, hasSize(2));
  assertThat(savedPermissions.stream().map(p -> p.getActor()).collect(Collectors.toList()), containsInAnyOrder(actors.get(0), actors.get(1)));
  assertThat(savedPermissions.stream().allMatch(p -> p.hasReadPermission() && p.hasWritePermission()), is(true));
  assertThat(savedPermissions.get(0).hasWriteAclPermission() && savedPermissions.get(1).hasWriteAclPermission(), is(false));
  assertThat(savedPermissions.get(0).hasReadAclPermission() && savedPermissions.get(1).hasReadAclPermission(), is(false));
  assertThat(savedPermissions.stream().allMatch(p -> p.hasDeletePermission()), is(false));
}
 
Example #13
Source File: Application.java    From chassis with Apache License 2.0 6 votes vote down vote up
@Override
public void onApplicationEvent(ContextRefreshedEvent event) {
    logger.debug("Received ContextRefreshedEvent {}", event);

    if (event.getSource().equals(getBootstrapApplicationContext())) {
        //the root context is fully started
        appMetadata = bootstrapApplicationContext.getBean(AppMetadata.class);
        configuration = bootstrapApplicationContext.getBean(AbstractConfiguration.class);
        configurationProvider = bootstrapApplicationContext.getBean(ConfigurationProvider.class);

        logger.debug("Root context started");

        initClientApplication();

        return;
    }

    if (event.getSource() instanceof ApplicationContext && ((ApplicationContext) event.getSource()).getId().equals(appMetadata.getName())) {
        //the child context is fully started
        this.applicationContext = (AbstractApplicationContext) event.getSource();

        logger.debug("Child context started");
    }

    state.compareAndSet(State.STARTING, State.RUNNING);
}
 
Example #14
Source File: RegisterToApiLayer.java    From api-layer with Eclipse Public License 2.0 6 votes vote down vote up
@EventListener(ContextRefreshedEvent.class)
public void onContextRefreshedEventEvent() {
    if (apimlEnabled) {
        if (apiMediationClient.getEurekaClient() != null) {
            if (config != null) {
                logger.log( "org.zowe.apiml.enabler.registration.renew"
                    , config.getBaseUrl(), config.getServiceIpAddress(), config.getDiscoveryServiceUrls()
                    , newConfig.getBaseUrl(), newConfig.getServiceIpAddress(), newConfig.getDiscoveryServiceUrls()
                );
            }

            unregister();
        } else {
            logger.log("org.zowe.apiml.enabler.registration.initial"
                , newConfig.getBaseUrl(), newConfig.getServiceIpAddress(), newConfig.getDiscoveryServiceUrls()
            );
        }

        register(newConfig);
    }
}
 
Example #15
Source File: ContainerAwareExecutionVenueTest.java    From cougar with Apache License 2.0 6 votes vote down vote up
@Test
public void testOnApplicationEvent() {
	//Set up dependencies
	JMXControl jmxControl = new JMXControl(null);
	when(appContext.getBean(JMXControl.BEAN_JMX_CONTROL)).thenReturn(jmxControl);
	setupExportables();
	setupGateListeners();

	//raise the event
	ev.onApplicationEvent(new ContextRefreshedEvent(appContext));

	//Verify that all exportables were exported
	verify(exportable1).export(jmxControl);
	verify(exportable2).export(jmxControl);

	//Verify that all registered gate listeners have been notified
	verify(gateListener1).onCougarStart();
	verify(gateListener2).onCougarStart();
}
 
Example #16
Source File: ApplicationStartup.java    From DataM with Apache License 2.0 5 votes vote down vote up
@Override
public void onApplicationEvent(ContextRefreshedEvent event) {
    ApplicationContext applicationContext = event.getApplicationContext();
    AsyncTaskService asyncTaskService = applicationContext.getBean(AsyncTaskService.class);
    int threadNum = Integer.parseInt(applicationContext.getEnvironment().getProperty("consumer.thread.num"));
    for (int i = 0; i < threadNum; i++) {
        asyncTaskService.executeAsyncTask(i);
    }
}
 
Example #17
Source File: ApplicationEvent.java    From ZTuoExchange_framework with MIT License 5 votes vote down vote up
@Override
public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) {
    log.info("====应用初始化完成,开启CoinProcessor====");
    List<ExchangeCoin> coins = coinService.findAllEnabled();
    coins.forEach(coin->{
        CoinProcessor processor = coinProcessorFactory.getProcessor(coin.getSymbol());
        processor.initializeThumb();
        processor.initializeUsdRate();
        processor.setIsHalt(false);
    });
}
 
Example #18
Source File: ApplicationEvent.java    From ZTuoExchange_framework with MIT License 5 votes vote down vote up
@Override
public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) {
    log.info("====应用初始化完成,开启CoinProcessor====");
    List<ExchangeCoin> coins = coinService.findAllEnabled();
    coins.forEach(coin->{
        CoinProcessor processor = coinProcessorFactory.getProcessor(coin.getSymbol());
        processor.initializeThumb();
        processor.initializeUsdRate();
        processor.setIsHalt(false);
    });
}
 
Example #19
Source File: ApplicationContextListenerTest.java    From jwala with Apache License 2.0 5 votes vote down vote up
@Test
public void testNoApplicationContext() {
    JpaMedia mockJdkMedia = mock(JpaMedia.class);
    when(mockJdkMedia.getType()).thenReturn(MediaType.JDK);
    List<JpaMedia> mediaList = Collections.singletonList(mockJdkMedia);

    when(Config.mediaServiceMock.findAll()).thenReturn(mediaList);
    ContextRefreshedEvent mockStartupEvent = mock(ContextRefreshedEvent.class);

    applicationContextListener.handleEvent(mockStartupEvent);

    verify(Config.jvmServiceMock, never()).updateJvm(any(UpdateJvmRequest.class), eq(true));
    verify(Config.mediaServiceMock, never()).create(anyMap(), anyMap());
}
 
Example #20
Source File: ScheduledAnnotationBeanPostProcessor.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Override
public void onApplicationEvent(ContextRefreshedEvent event) {
	if (event.getApplicationContext() == this.applicationContext) {
		// Running in an ApplicationContext -> register tasks this late...
		// giving other ContextRefreshedEvent listeners a chance to perform
		// their work at the same time (e.g. Spring Batch's job registration).
		finishRegistration();
	}
}
 
Example #21
Source File: AclConfiguration.java    From strategy-spring-security-acl with Apache License 2.0 5 votes vote down vote up
@EventListener(ContextRefreshedEvent.class)
public void logStrategies() {
  if (logger.isDebugEnabled()) {
    Map<String, AclStrategy> strategies = applicationContext.getBeansOfType(AclStrategy.class);
    strategies.entrySet().stream() //
        .forEach(e -> logger.debug("Strategy {}: {}", e.getKey(), e.getValue()));
  }
}
 
Example #22
Source File: Bootstrapper.java    From flowable-engine with Apache License 2.0 5 votes vote down vote up
@Override
public void onApplicationEvent(ContextRefreshedEvent event) {
    if (event.getApplicationContext().getParent() == null) { // Using Spring MVC, there are multiple child contexts. We only care about the root

        if (taskAppProperties == null || taskAppProperties.isAppMigrationEnabled()) {
            String appMigrationResult = appDefinitionService.migrateAppDefinitions();
            LOGGER.info(appMigrationResult);
        } 
    }
}
 
Example #23
Source File: FileContentStore.java    From alfresco-simple-content-stores with Apache License 2.0 5 votes vote down vote up
/**
 *
 * {@inheritDoc}
 */
@Override
public void onApplicationEvent(final ContextRefreshedEvent event)
{
    if (this.extendedEventParameters == null)
    {
        this.extendedEventParameters = Collections.<String, Serializable> emptyMap();
    }

    if (event.getSource() == this.applicationContext)
    {
        final ApplicationContext context = event.getApplicationContext();
        context.publishEvent(new ContentStoreCreatedEvent(this, this.extendedEventParameters));
    }
}
 
Example #24
Source File: CoinTraderEvent.java    From ZTuoExchange_framework with MIT License 5 votes vote down vote up
@Override
public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) {
    log.info("======initialize coinTrader======");
    coinTraderFactory.getTraderMap();
    HashMap<String,CoinTrader> traders = coinTraderFactory.getTraderMap();
    traders.forEach((symbol,trader) ->{
        List<ExchangeOrder> orders = exchangeOrderService.findAllTradingOrderBySymbol(symbol);
        List<ExchangeOrder> tradingOrders = new ArrayList<>();
        List<ExchangeOrder> completedOrders = new ArrayList<>();
        orders.forEach(order -> {
            BigDecimal tradedAmount = BigDecimal.ZERO;
            BigDecimal turnover = BigDecimal.ZERO;
            List<ExchangeOrderDetail> details = exchangeOrderDetailService.findAllByOrderId(order.getOrderId());
            //order.setDetail(details);
            for(ExchangeOrderDetail trade:details){
                tradedAmount = tradedAmount.add(trade.getAmount());
                turnover = turnover.add(trade.getAmount().multiply(trade.getPrice()));
            }
            order.setTradedAmount(tradedAmount);
            order.setTurnover(turnover);
            if(!order.isCompleted()){
                tradingOrders.add(order);
            }
            else{
                completedOrders.add(order);
            }
        });
        trader.trade(tradingOrders);
        //判断已完成的订单发送消息通知
        if(completedOrders.size() > 0){
            kafkaTemplate.send("exchange-order-completed", JSON.toJSONString(completedOrders));
        }
        trader.setReady(true);
    });
}
 
Example #25
Source File: Bootstrap.java    From chronus with Apache License 2.0 5 votes vote down vote up
@Override
public void onApplicationEvent(ContextRefreshedEvent event) {
    if (supports == null) {
        return;
    }
    try {
        this.start();
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
 
Example #26
Source File: Bootstrap.java    From mojito with Apache License 2.0 5 votes vote down vote up
@Override
public void onApplicationEvent(ContextRefreshedEvent event) {
    if (!initialized) {

        if (bootstrapConfig.isEnabled()) {
            createData();
        }

        initialized = true;
    }
}
 
Example #27
Source File: ImportServiceIT.java    From molgenis with GNU Lesser General Public License v3.0 5 votes vote down vote up
@BeforeEach
public void beforeEach() {
  ContextRefreshedEvent contextRefreshedEvent = Mockito.mock(ContextRefreshedEvent.class);
  Mockito.when(contextRefreshedEvent.getApplicationContext()).thenReturn(applicationContext);
  importServiceRegistrar.register(contextRefreshedEvent);
  RunAsSystemAspect.runAsSystem(() -> dataService.add(USER, getTestUser()));
}
 
Example #28
Source File: SecurityManagerProxyConfiguration.java    From spring-boot-data-geode with Apache License 2.0 5 votes vote down vote up
@Override
public void onApplicationEvent(ContextRefreshedEvent event) {

	SecurityManagerProxy securityManagerProxy = SecurityManagerProxy.getInstance();

	securityManagerProxy.setBeanFactory(event.getApplicationContext().getAutowireCapableBeanFactory());
	securityManagerProxy.init(new Properties());
}
 
Example #29
Source File: EventConsumer.java    From cougar with Apache License 2.0 5 votes vote down vote up
@Override
public void onApplicationEvent(ApplicationEvent event) {
    System.out.println(event.getClass().getName());

    if (event instanceof ContextRefreshedEvent) {
        subscribe();
    }
}
 
Example #30
Source File: AbstractValidatorHandler.java    From DesignPatterns with Apache License 2.0 5 votes vote down vote up
@Override
public void onApplicationEvent(ContextRefreshedEvent event) {
    if (event.getApplicationContext().getParent() == null) {
        LOGGER.info("Start to add the validator into current handler,base packages contains:{}",this.getBasePackages());
        this.addValidators();
    }
}