/** * Start the controller */ @EventListener(ApplicationReadyEvent.class) public void start() { log.info("Starting sessions"); // setup reconnect tasks for (final GroupSession group : groups.values()) { group.start(); Runnable reconnectTask = new Runnable() { @Override public void run() { try { if (group.isStopped()) { group.stop(); log.info("Attempting to reconnect..."); group.start(); } } catch (Exception e) { log.error(e.getLocalizedMessage()); } } }; Schedule.getInstance().at(reconnectTask, reconnectInterval, true); } }
@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(); }
@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(() -> commentController.addComment(newComment))) .subscribe(); }
@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(); }
@SuppressWarnings("unchecked") @Override public void onApplicationEvent(ApplicationReadyEvent event) { URI uri = URI.create("http://localhost:" + port); if (Desktop.isDesktopSupported()) { Desktop desktop = Desktop.getDesktop(); if (desktop.isSupported(Desktop.Action.BROWSE)) { try { desktop.browse(uri); } catch (IOException e) { e.printStackTrace(); } } } else if (IS_MAC) { openUrlInBrowser(uri.toString()); } }
@Override public void onApplicationEvent(ApplicationReadyEvent applicationReadyEvent) { log.info("Checking subscriptions to {}", config.aws.topic.subscribeArn); String thisEndpoint = "http://" + appInfo.getPublicHostname() + SnsCamEchoResponseEndpoint.SNS_EP_CAM_ECHO_RESPONSE; List<Subscription> subscriptions = amazonSns.listSubscriptionsByTopic(config.aws.topic.subscribeArn).getSubscriptions(); boolean notSubscribed = true; for (Subscription subscription : subscriptions) { if (thisEndpoint.equals(subscription.getEndpoint())) { log.info("Found subscription {} on topic {} for endpoint {}", subscription.getSubscriptionArn(), subscription.getTopicArn(), thisEndpoint); notSubscribed = false; } } if (notSubscribed) { log.info("Subscribing to topic {} with endpoint {}", config.aws.topic.subscribeArn, thisEndpoint); SubscribeResult subscribeResult = amazonSns.subscribe(config.aws.topic.subscribeArn, "http", thisEndpoint); log.info("Subscription: {}", subscribeResult.getSubscriptionArn()); } }
@Override public void onApplicationEvent(ApplicationReadyEvent event) { if (event.getApplicationContext().getParent() == null) { // HystrixPlugins.getInstance().registerCommandExecutionHook(impl); // HystrixPlugins.getInstance().getCommandExecutionHook(); // if(!(HystrixPlugins.getInstance().getCommandExecutionHook() instanceof SecurityContextRegistratorCommandHook)){ try { HystrixPlugins.getInstance().registerCommandExecutionHook(new SecurityContextRegistratorCommandHook()); } catch (Exception e) { // TODO: handle exception } // } logger.debug("初始化HystrixPlugins完成"); } }
@Override public void onApplicationEvent(ApplicationReadyEvent arg0) { Random n = new Random(); int i = 1; int max = 40; System.out.println("SAVING SEATS..."); // System.out.println("SAVING ATTENTIONS..."); // System.out.println("SAVING HISTORY POINTS..."); for (i = 1; i <= max; i++) { Seat seat = saveSeats(i); // saveAttentions(i, seat); // saveHistoryPoints(i, seat); } System.out.println("SAVING SEATS... COMPLETED"); // System.out.println("SAVING ATTENTIONS... COMPLETED"); // System.out.println("SAVING HISTORY POINTS... COMPLETED"); saveQuestions(); }
@Test public void customize() throws LifecycleException { Context standardContext = mock(Context.class); StandardRoot webResourceRoot = new StandardRoot(standardContext); Mockito.when(standardContext.getResources()).thenReturn(webResourceRoot); Mockito.when(standardContext.getAddWebinfClassesResources()).thenReturn(Boolean.FALSE); JsfTomcatContextCustomizer jsfTomcatContextCustomizer = new JsfTomcatContextCustomizer(); jsfTomcatContextCustomizer.customize(standardContext); JsfTomcatApplicationListener jsfTomcatApplicationListener = JsfTomcatApplicationListener .builder().context(jsfTomcatContextCustomizer.getContext()).build(); jsfTomcatApplicationListener.onApplicationEvent(mock(ApplicationReadyEvent.class)); assertThat(webResourceRoot.getPostResources().length) .isEqualTo(9); }
@Test public void resourcesNull() throws LifecycleException { 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 = JsfTomcatApplicationListener .builder().context(jsfTomcatContextCustomizer.getContext()).build(); jsfTomcatApplicationListener.onApplicationEvent(mock(ApplicationReadyEvent.class)); assertThat(jsfTomcatApplicationListener) .isNotNull(); }
@Test public void jarResourcesNull() throws LifecycleException { Context standardContext = mock(Context.class); WebResourceRoot webResourceRoot = mock(WebResourceRoot.class); Mockito.when(standardContext.getResources()).thenReturn(webResourceRoot); Mockito.when(standardContext.getAddWebinfClassesResources()).thenReturn(Boolean.FALSE); Mockito.when(webResourceRoot.getJarResources()).thenReturn(null); JsfTomcatContextCustomizer jsfTomcatContextCustomizer = new JsfTomcatContextCustomizer(); jsfTomcatContextCustomizer.customize(standardContext); JsfTomcatApplicationListener jsfTomcatApplicationListener = JsfTomcatApplicationListener .builder().context(jsfTomcatContextCustomizer.getContext()).build(); jsfTomcatApplicationListener.onApplicationEvent(mock(ApplicationReadyEvent.class)); assertThat(jsfTomcatApplicationListener) .isNotNull(); }
@Test public void applicationRunningEventListener() { SpringApplication application = new SpringApplication(ExampleConfig.class); application.setWebEnvironment(false); final AtomicReference<SpringApplication> reference = new AtomicReference<SpringApplication>(); class ApplicationReadyEventListener implements ApplicationListener<ApplicationReadyEvent> { @Override public void onApplicationEvent(ApplicationReadyEvent event) { reference.set(event.getSpringApplication()); } } application.addListeners(new ApplicationReadyEventListener()); this.context = application.run("--foo=bar"); assertThat(application).isSameAs(reference.get()); }
@Test public void eventsOrder() { SpringApplication application = new SpringApplication(ExampleConfig.class); application.setWebEnvironment(false); final List<ApplicationEvent> events = new ArrayList<ApplicationEvent>(); class ApplicationRunningEventListener implements ApplicationListener<ApplicationEvent> { @Override public void onApplicationEvent(ApplicationEvent event) { events.add((event)); } } application.addListeners(new ApplicationRunningEventListener()); this.context = application.run(); assertThat(events).hasSize(5); assertThat(events.get(0)).isInstanceOf(ApplicationStartedEvent.class); assertThat(events.get(1)).isInstanceOf(ApplicationEnvironmentPreparedEvent.class); assertThat(events.get(2)).isInstanceOf(ApplicationPreparedEvent.class); assertThat(events.get(3)).isInstanceOf(ContextRefreshedEvent.class); assertThat(events.get(4)).isInstanceOf(ApplicationReadyEvent.class); }
@Override public void onApplicationEvent(ApplicationEvent event) { if (event instanceof ApplicationStartedEvent) { onApplicationStartedEvent((ApplicationStartedEvent) event); } if (event instanceof ApplicationPreparedEvent) { Restarter.getInstance() .prepare(((ApplicationPreparedEvent) event).getApplicationContext()); } if (event instanceof ApplicationReadyEvent || event instanceof ApplicationFailedEvent) { Restarter.getInstance().finish(); if (event instanceof ApplicationFailedEvent) { Restarter.getInstance().prepare(null); } } }
private void testInitialize(boolean failed) { Restarter.clearInstance(); RestartApplicationListener listener = new RestartApplicationListener(); SpringApplication application = new SpringApplication(); ConfigurableApplicationContext context = mock( ConfigurableApplicationContext.class); listener.onApplicationEvent(new ApplicationStartedEvent(application, ARGS)); assertThat(Restarter.getInstance()).isNotEqualTo(nullValue()); assertThat(Restarter.getInstance().isFinished()).isFalse(); listener.onApplicationEvent( new ApplicationPreparedEvent(application, ARGS, context)); if (failed) { listener.onApplicationEvent(new ApplicationFailedEvent(application, ARGS, context, new RuntimeException())); } else { listener.onApplicationEvent( new ApplicationReadyEvent(application, ARGS, context)); } }
@Override public void onApplicationEvent(final ApplicationReadyEvent event) { LOGGER.debug("{} autostarts will be executed", simulationProperties.getAutostarts().size()); simulationProperties.getAutostarts().forEach(autostart -> { LOGGER.debug("Autostart runs for tenant {} and API {}", autostart.getTenant(), autostart.getApi()); for (int i = 0; i < autostart.getAmount(); i++) { final String deviceId = autostart.getName() + i; try { if (amqpProperties.isEnabled()) { repository.add(deviceFactory.createSimulatedDeviceWithImmediatePoll(deviceId, autostart.getTenant(), autostart.getApi(), autostart.getPollDelay(), new URL(autostart.getEndpoint()), autostart.getGatewayToken())); } } catch (final MalformedURLException e) { LOGGER.error("Creation of simulated device at startup failed.", e); } } }); }
@Test public void applicationRunningEventListener() { SpringApplication application = new SpringApplication(ExampleConfig.class); application.setWebEnvironment(false); final AtomicReference<SpringApplication> reference = new AtomicReference<SpringApplication>(); class ApplicationReadyEventListener implements ApplicationListener<ApplicationReadyEvent> { @Override public void onApplicationEvent(ApplicationReadyEvent event) { reference.set(event.getSpringApplication()); } } application.addListeners(new ApplicationReadyEventListener()); this.context = application.run("--foo=bar"); assertThat(application, sameInstance(reference.get())); }
@Test public void eventsOrder() { SpringApplication application = new SpringApplication(ExampleConfig.class); application.setWebEnvironment(false); final List<ApplicationEvent> events = new ArrayList<ApplicationEvent>(); class ApplicationRunningEventListener implements ApplicationListener<ApplicationEvent> { @Override public void onApplicationEvent(ApplicationEvent event) { events.add((event)); } } application.addListeners(new ApplicationRunningEventListener()); this.context = application.run(); assertThat(5, is(events.size())); assertThat(events.get(0), is(instanceOf(ApplicationStartedEvent.class))); assertThat(events.get(1), is(instanceOf(ApplicationEnvironmentPreparedEvent.class))); assertThat(events.get(2), is(instanceOf(ApplicationPreparedEvent.class))); assertThat(events.get(3), is(instanceOf(ContextRefreshedEvent.class))); assertThat(events.get(4), is(instanceOf(ApplicationReadyEvent.class))); }
private void testInitialize(boolean failed) { Restarter.clearInstance(); RestartApplicationListener listener = new RestartApplicationListener(); SpringApplication application = new SpringApplication(); ConfigurableApplicationContext context = mock( ConfigurableApplicationContext.class); listener.onApplicationEvent(new ApplicationStartedEvent(application, ARGS)); assertThat(Restarter.getInstance(), not(nullValue())); assertThat(Restarter.getInstance().isFinished(), equalTo(false)); if (failed) { listener.onApplicationEvent(new ApplicationFailedEvent(application, ARGS, context, new RuntimeException())); } else { listener.onApplicationEvent( new ApplicationReadyEvent(application, ARGS, context)); } }
public static void main(String[] args) throws Exception { Optional<JWindow> splash = LoadingSplashScreen .setupScreen(WebAnno.class.getResource("splash.png")); SpringApplicationBuilder builder = new SpringApplicationBuilder(); // Signal that we may need the shutdown dialog builder.properties("running.from.commandline=true"); init(builder); builder.sources(WebAnno.class); builder.listeners(event -> { if (event instanceof ApplicationReadyEvent || event instanceof ShutdownDialogAvailableEvent) { splash.ifPresent(it -> it.dispose()); } }); builder.run(args); }
@Test public void givenWarmupEnabledWhenApplicationStartedThenVerbruikPerUurOpDagWarmedup() { setWarmupCacheEnabled(); timeTravelTo(clock, LocalDate.of(2017, 12, 30).atTime(13, 20)); warmupCache.onApplicationEvent(mock(ApplicationReadyEvent.class)); verify(energieController, times(14)).getVerbruikPerUurOpDag(dateCaptor.capture()); assertThat(dateCaptor.getAllValues()).containsExactly( LocalDate.of(2017, 12, 16), LocalDate.of(2017, 12, 17), LocalDate.of(2017, 12, 18), LocalDate.of(2017, 12, 19), LocalDate.of(2017, 12, 20), LocalDate.of(2017, 12, 21), LocalDate.of(2017, 12, 22), LocalDate.of(2017, 12, 23), LocalDate.of(2017, 12, 24), LocalDate.of(2017, 12, 25), LocalDate.of(2017, 12, 26), LocalDate.of(2017, 12, 27), LocalDate.of(2017, 12, 28), LocalDate.of(2017, 12, 29) ); }
@SuppressWarnings({"unchecked", "rawtypes"}) @Test public void test_no_register_after_close() { ApplicationRegistrator registrator = mock(ApplicationRegistrator.class); TaskScheduler scheduler = mock(TaskScheduler.class); RegistrationApplicationListener listener = new RegistrationApplicationListener(registrator, scheduler); ScheduledFuture task = mock(ScheduledFuture.class); when(scheduler.scheduleAtFixedRate(isA(Runnable.class), eq(Duration.ofSeconds(10)))).thenReturn(task); listener.onApplicationReady(new ApplicationReadyEvent(mock(SpringApplication.class), null, mock(ConfigurableWebApplicationContext.class))); verify(scheduler).scheduleAtFixedRate(isA(Runnable.class), eq(Duration.ofSeconds(10))); listener.onClosedContext(new ContextClosedEvent(mock(WebApplicationContext.class))); verify(task).cancel(true); }
@EventListener @Transactional public void initialize(ApplicationReadyEvent event) { platforms.forEach(platform -> { platform.getDeployers().forEach(deployer -> { this.deployerRepository.save(deployer); logger.info(String.format( "Added '%s' platform account '%s' into deployer repository.", platform.getName(), deployer.getName())); }); }); }
@EventListener public void simulateUsersClicking(ApplicationReadyEvent event) { Flux .interval(Duration.ofMillis(500)) .flatMap(tick -> Mono.defer(() -> homeController.index(new BindingAwareModelMap()))) .subscribe(); }
@Override public void onApplicationEvent(ApplicationReadyEvent event) { try { userSearchService.getUserByUsername(USERNAME); } catch (ResourceNotFoundException ex) { userPersistenceService.createAdmin(initAdmin()); } }
@Override public void onApplicationEvent(final ApplicationReadyEvent event) { try { LOGGER.info("Comenzando la creacion de documentacion"); ResourcesBuilder.getInstance().build(context); } catch (Exception e) { LOGGER.error("problemas al crear la documentacion", e); } }
public void onApplicationEvent(ApplicationReadyEvent arg0) { System.out.println("initialize dummy database entries..."); repo.save(new FlightEntity("F654", "STR", "FDH", new Date(), new Date(System.currentTimeMillis() + 1000000), null, null)); repo.save(new FlightEntity("S876", "FDH", "STR", new Date(System.currentTimeMillis() + 10000000), new Date(System.currentTimeMillis() + 11000000), null, null)); repo.save(new FlightEntity("O987", "STR", "FDH", new Date(System.currentTimeMillis() + 990000000), new Date(System.currentTimeMillis() + 991000000), null, null)); repo.save(new FlightEntity("L5U3", "FDH", "STR", new Date(System.currentTimeMillis() + 998000000), new Date(System.currentTimeMillis() + 999000000), null, null)); }
@Override public void onApplicationEvent(ApplicationReadyEvent event) { try { locationService.syncLocation(); channelService.syncChannelsFromSlack(); employeeService.syncEmployeeFromSlack(); visitorService.syncVisitorOrigin(); } catch(Exception e) { logger.error("Exception while syncing on startup {}.", e); throw new RuntimeException(e); } }
@EventListener public void init(ApplicationReadyEvent event) { if (postRepository.count() > 0) { return; } IntStream.range(0, 10).forEach( n -> { Tag tag = new Tag(); tag.setName(faker.lorem().word()); Comment comment = new Comment(); comment.setText(faker.lorem().sentence()); Post post = new Post(); post.setTitle(faker.company().name()); post.setContent(faker.lorem().paragraph()); post.setComments(Arrays.asList(comment)); post.setTags(Arrays.asList(tag)); comment.setPost(post); postRepository.save(post); } ); }
@Override public void onApplicationEvent(final ApplicationReadyEvent event) { try { EntityManager entityManager = entityManagerFactory.createEntityManager(); try { FullTextEntityManager fullTextEntityManager = Search.getFullTextEntityManager(entityManager); fullTextEntityManager.createIndexer(CLASSES).startAndWait(); } finally { entityManager.close(); } } catch (InterruptedException e) { System.out.println("An error occurred trying to build the search index: " + e.toString()); } }
@Override public void onApplicationEvent(ApplicationReadyEvent event) { if (StringUtils.isEmpty(webhookConfigurationProperties.getUrl())) { return; } webHookClient.sendMessage(webhookConfigurationProperties.getUrl(), String.format("%s startup succeed.", getAppName())); }
/** * Build lucene search index * * @param event application ready event */ @Override public void onApplicationEvent(final ApplicationReadyEvent event) { try { final FullTextEntityManager fullTextEntityManager = Search.getFullTextEntityManager(entityManager); fullTextEntityManager.createIndexer().startAndWait(); } catch (InterruptedException e) { logger.info("[BuildSearchIndex] [onApplicationEvent] Build Search Index Failure", e); } }
@Override public void onApplicationEvent(ApplicationReadyEvent event) { try { touch(new File("/tmp/app-initialized")); } catch (IOException e) { log.error("Could not indicate NGINX that it can start accepting traffic", e); } }