@Subscribe public void onSelectionResized(SelectionResizeEvent event) { if (timelineModel.getSelectedKeyFrame() == null) { return; } if (event.getType() == START) { startValues = new HashMap<>(); filterByKeyAndForEach(getKeyValues(), NodeModel::isSelected, this::storeStartKeyValues); } else if (event.getType() == DRAG) { event.getNewPositions().keySet().forEach(node -> moveNode(node, event)); } else if (event.getType() == FINISHED) { Map<KeyValueModel, Object> endValues = getEndValues(event); if (startValues != null && anyNodeMoved(endValues)) { commandStack.append(new NodeDragCommand(startValues, endValues, timelineModel, sceneModel)); } } }
@Subscribe public void onTwitchHostInEvent(TwitchHostInEvent event) { User channel = usersService.getUser(event.getChannelName()); boolean isCooldownExpired = isCooldownExpired(channel); if (isCooldownExpired) { hostRecordService.recordIncomingHost(channel, event.isAuto()); if (settings.getReward() > 0) { pointsService.give(channel, settings.getReward()); } Template template = templateDao.getByKey(HostWatchComponent.INCOMING_HOST_NOTICE_TEMPLATE); assert template != null; // Template cannot be null since it's set during install/update if (StringUtils.isNotEmpty(template.getTemplate())) { chat.say(Templater.template(template.getTemplate()) .add("username", channel::getDisplayName) .add("points", pointsService.asString(settings.getReward()))); } } }
@Subscribe public void applicationThemeRequestCallback(ThemeRequestCallback event) { if (event.requestedTheme().isPresent()) { Theme applicationTheme = event.requestedTheme().get(); try { stage.getScene().getStylesheets().clear(); stage.getScene().getStylesheets().add(applicationTheme.getPath()); return; } catch (MalformedURLException e) { console.warning("Unable to load application theme " + applicationTheme.getName()); return; } } console.warning("Unable to load application theme."); }
@Test public void testWatchOpen(@Mocked ServiceRegistryConfig serviceRegistryConfig, @Mocked ServiceRegistryClient srClient, @Mocked Microservice microservice) { initWatch(serviceRegistryConfig, srClient, microservice); new MockUp<ServiceRegistryClient>(srClient) { @Mock void watch(String selfMicroserviceId, AsyncResultCallback<MicroserviceInstanceChangedEvent> callback, AsyncResultCallback<Void> onOpen, AsyncResultCallback<Void> onClose) { onOpen.success(null); } }; Holder<Boolean> openHolder = new Holder<>(); eventBus.register(new Object() { @Subscribe public void onOpen(RecoveryEvent event) { openHolder.value = true; } }); Assert.assertNull(openHolder.value); microserviceWatchTask.run(); Assert.assertTrue(openHolder.value); }
@Test public void testWatchFailed(@Mocked ServiceRegistryConfig serviceRegistryConfig, @Mocked ServiceRegistryClient srClient, @Mocked Microservice microservice) { initWatch(serviceRegistryConfig, srClient, microservice); new MockUp<ServiceRegistryClient>(srClient) { @Mock void watch(String selfMicroserviceId, AsyncResultCallback<MicroserviceInstanceChangedEvent> callback, AsyncResultCallback<Void> onOpen, AsyncResultCallback<Void> onClose) { callback.fail(new Error("test failed")); } }; Holder<Throwable> holder = new Holder<>(); eventBus.register(new Object() { @Subscribe public void onException(ExceptionEvent event) { holder.value = event.getThrowable(); } }); Assert.assertNull(holder.value); microserviceWatchTask.run(); Assert.assertEquals("test failed", holder.value.getMessage()); }
@Subscribe public void onShowGraph(ShowGraphEvent event) { Synset rootSynset = service.synsetRemote().findSynsetBySense(event.getSense(), Arrays.asList(1l, 2l, 3l)); ui.releaseDataSetCache(); if (rootSynset != null) { Map<Long, DataEntry> entries = service.synsetRemote() .prepareCacheForRootNode(rootSynset, Arrays.asList(1l, 2l, 3l), new NodeDirection[]{NodeDirection.LEFT,NodeDirection.TOP, NodeDirection.BOTTOM, NodeDirection.RIGHT}); if (entries != null) { ui.setEntrySets((HashMap<Long, DataEntry>) entries); } //pobieranie synsetu z wcześniej pobranej mapy, aby otrzymać obiekt, który ma relacje (nie są leniwymi kolekcjami) DataEntry dataEntry = entries.get(rootSynset.getId()); if (dataEntry != null) { rootSynset = dataEntry.getSynset(); } ui.refreshView(rootSynset); } else { ui.clear(); } }
@Subscribe public final void updateTileViewModel( final BuildTypeData data ) { if ( data != _buildTypeData ) return; Platform.runLater( ( ) -> { _displayedName.set( Strings.isNullOrEmpty( data.getAliasName( ) ) ? data.getName( ) : data.getAliasName( ) ); _running.setValue( data.hasRunningBuild( ) ); _queued.setValue( data.isQueued( ) ); updateLastFinishedDate( ); updateTimeLeft( ); updatePercentageComplete( ); updateBackground( ); updateIcon( ); } ); }
/** * Retrieves metadata as soon as the layout is done. * * @param event a {@link LayoutDoneEvent} */ @Subscribe public void layoutDone(final LayoutDoneEvent event) { if (currentRadius >= RADIUS_THRESHOLD) { retrievalExecutor.stop(); return; } retrievalExecutor.run(() -> { retrieveMetadata(gfaFile, event.getSubgraph()); if (Thread.interrupted()) { return; } pathCalculator.computePaths(event.getSubgraph()); HygeneEventBus.getInstance().post(new NodeMetadataCacheUpdateEvent(event.getSubgraph())); }); }
@Subscribe public void onTextMessage(MessageReceivedEvent event) { CGuild cGuild = charrizard.getCGuildManager().getGuild(event.getGuild()); if (cGuild == null) { charrizard.getCGuildManager().createGuild(event.getGuild()); cGuild = charrizard.getCGuildManager().getGuild(event.getGuild()); } if (!event.getMessage().getContent().startsWith(prefix)) { CTextChannel cTextChannel = cGuild.getTextChannel(event.getTextChannel()); if (cTextChannel == null) { cGuild.createTextChannel(event.getTextChannel()); cTextChannel = cGuild.getTextChannel(event.getTextChannel()); } cTextChannel.addMessage(); return; } String[] args = event.getMessage().getContent().split(" "); args[0] = args[0].substring(1); Command command = commands.stream().filter(c -> c.getLabel().equals(args[0])).findFirst().orElse(null); if (command == null) { return; } cGuild.runCommand(command, new CMessage(event.getMessage()), args); }
public void testAnonymous() { final AtomicReference<String> holder = new AtomicReference<String>(); final AtomicInteger deliveries = new AtomicInteger(); EventBus bus = new EventBus(); bus.register(new Object() { @Subscribe public void accept(String str) { holder.set(str); deliveries.incrementAndGet(); } }); String EVENT = "Hello!"; bus.post(EVENT); assertEquals("Only one event should be delivered.", 1, deliveries.get()); assertEquals("Correct string should be delivered.", EVENT, holder.get()); }
@Subscribe public void onStreamLabsDonationEvent(StreamLabsDonationEvent event) { User user = usersService.getUser(event.getUsername()); if (user != null) { double reward = (event.getAmount() * DonationRegisterConstants.POINTS_MULTIPLIER); donationsService.registerDonation(user, event.getFormattedAmount(), event.getMessage()); pointsService.give(user, reward); Template template = templateDao.getByKey(DonationRegisterConstants.INCOMING_DONATION_NOTICE); assert template != null; // Template cannot be null since it's set during install/update if (StringUtils.isNotEmpty(template.getTemplate())) { chat.say(Templater.template(template.getTemplate()) .add("username", user::getDisplayName) .add("points", pointsService.asString(reward)) .add("formattedamount", event::getFormattedAmount) .add("message", event::getMessage)); } } }
@SuppressWarnings("restriction") @Subscribe public void registerWatchResult(RegWatchResponseEvent e) { if (!e.isSuccess()) throw new IllegalArgumentException("There isn't a register with the name " + e.getRegisterName()); String id = e.getRegisterID(); String registerName = e.getRegisterName(); LongProperty register = e.getRegObject(); System.out.println("suc" + id + " -- " + registerName + " -- " + register); register.addListener(new ChangeListener<Number>() { @Override public void changed(ObservableValue<? extends Number> observable, Number oldValue, Number newValue) { //watchedRegisters.refresh(); System.out.println("Success" + id + " -- " + registerName + " -- " + register); session.setAttribute("idd", register.getValue()); //System.out.println("id is: " + session.getAttribute("idd")); } }); }
@Subscribe public void onConsoleInputEvent(ConsoleInputEvent event) { char identifier = event.getIdentifier(); switch (identifier) { case PREFIX_COMMAND: runCommand(event); break; case PREFIX_CMD_COMMAND: executeConsoleCommand(event); break; case PREFIX_WHISPER: doWhisper(event); break; case PREFIX_SAY: doSay(event); break; default: break; } }
@Subscribe private void toggleSettingsPane(ToggleEvent e){ Platform.runLater(()-> { if (e == ToggleEvent.SHOW_SETTINGS && !showSettings){ settingsPane.toFront(); showSettings = true; }else if (e == ToggleEvent.HIDE_SETTINGS && showSettings){ settingsPane.toBack(); showSettings = false; }else if (e == ToggleEvent.TOGGLE_SETTINGS){ if (showSettings){ settingsPane.toBack(); }else{ settingsPane.toFront(); } showSettings = !showSettings; } }); }
@Subscribe private void toggleRoomSettings(ToggleEvent e) { if (e == ToggleEvent.SHOW_ROOM_SETTINGS && !showRoomSettings) { settingsPane.toFront(); showRoomSettings = true; } else if (e == ToggleEvent.HIDE_ROOM_SETTINGS && showRoomSettings) { settingsPane.toBack(); showRoomSettings = false; } else if (e == ToggleEvent.TOGGLE_ROOM_SETTINGS) { if (showRoomSettings) { settingsPane.toBack(); } else { settingsPane.toFront(); } showRoomSettings = !showRoomSettings; } }
@Subscribe public void onEventReceived(Event event) { if (event instanceof NetworkEvent) { handleNetworkEvent((NetworkEvent) event); } else if (event instanceof ApiEvent) { if (event.getSubscriber().equals(getClass().getSimpleName())) { handleApiEvents((ApiEvent) event); } } }
@Subscribe public void receivedWatchRequest(MemWatchRequestEvent e) { long address = e.getMemoryAddress(); if (!validateAddress(address)) return; LongProperty valueProperty = null; for(HashMap.Entry<String, IOMemoryModule> entry : modules.entrySet()) { IOMemoryModule mod = entry.getValue(); if(mod.isAddressWithModule(address)) { if(!mod.isPhantom()) valueProperty = mod.getMemoryValueProperty(address); else { //verify: why are we even calling read of the module if not interested in its value //mod.read(addr); } break; } } EventRegistry.getGlobalRegistry().post(new MemWatchResponseEvent(true, address, valueProperty)); }
@Subscribe public void onMicroserviceInstanceHeartbeatTask(MicroserviceInstanceHeartbeatTask task) { if (task.getHeartbeatResult() != HeartbeatResult.SUCCESS && isSameMicroservice(task.getMicroservice())) { LOGGER.info("read MicroserviceInstanceHeartbeatTask status is {}", task.taskStatus); this.taskStatus = TaskStatus.READY; this.registered = false; } }
@Subscribe public void onRegisterTask(AbstractRegisterTask task) { LOGGER.info("read {} status is {}", task.getClass().getSimpleName(), task.taskStatus); if (task.getTaskStatus() == TaskStatus.FINISHED) { registerInstanceSuccess = true; } else { onException(); } }
@Subscribe public void outputFromDevice(DeviceOutputEvent e) { if (e.getDeviceName() != this.deviceName) return; long value = (long)(e.getDeviceData()); for(int i = 7; i >= 0; i--) { if((value & (long) Math.pow(2, i)) == (long) Math.pow(2, i)) setLEDState(i, true); else setLEDState(i, false); } }
/** * Percepts any {@link TestEvent test event} and registers it to the underlying queue. * * @param event * the percepted test event to register. */ @Subscribe @AllowConcurrentEvents public void receivedTestEvent(final TestEvent event) { synchronized (events) { events.put(event.getSessionId(), valueOf(event)); } if (null != latch) { latch.countDown(); } }
/** * Percepts a test session failure event, registers the session ID of the failed session. * * @param event * the failure event. */ @Subscribe @AllowConcurrentEvents public void sessionFailed(final SessionFailedEvent event) { LOGGER.info("Received test session failed event. " + (event.getComment().isPresent() ? event.getComment().get() : "")); failedSessionIds.add(event.getSessionId()); countDown(); }
/** * Whenever a new test event from 'mangelhaft' on the Javascript side is being received by the HTTP server, this * method will be invoked. * <p> * <b>This is the only method in this class that may be invoked from a non-UI thread.</b> */ @Subscribe @AllowConcurrentEvents public void onTestEvent(TestEvent ev) { Display.getDefault().asyncExec(() -> { notifyTestEvent(ev); }); }
@Test public void testPolling() throws Exception { // let first event fire Thread.sleep(2000L); final List<MaterializedConfiguration> events = Lists.newArrayList(); Object eventHandler = new Object() { @Subscribe public synchronized void handleConfigurationEvent(MaterializedConfiguration event) { events.add(event); } }; eventBus.register(eventHandler); configFile.setLastModified(System.currentTimeMillis()); // now wait for second event to fire Thread.sleep(2000L); Assert.assertEquals(String.valueOf(events), 1, events.size()); MaterializedConfiguration materializedConfiguration = events.remove(0); Assert.assertEquals(1, materializedConfiguration.getSourceRunners().size()); Assert.assertEquals(1, materializedConfiguration.getSinkRunners().size()); Assert.assertEquals(1, materializedConfiguration.getChannels().size()); }
@Subscribe public void propogateStateMessage(FMLEvent stateEvent) { if (stateEvent instanceof FMLPreInitializationEvent) { modObjectList = buildModObjectList(); } ProgressBar bar = ProgressManager.push(stateEvent.description(), activeModList.size(), true); for (ModContainer mc : activeModList) { bar.step(mc.getName()); sendEventToModContainer(stateEvent, mc); } ProgressManager.pop(bar); }
/** * Derived from {@link com.google.common.eventbus.AnnotatedSubscriberFinder#getAnnotatedMethodsInternal} */ public static boolean hasSubscriberMethods(Class<?> type) { for(Class<?> cls : TypeToken.of(type).getTypes().rawTypes()) { for(Method method : cls.getMethods()) { if(method.isAnnotationPresent(Subscribe.class)) return true; } } return false; }
@Subscribe public void onReconfigure(LocalServerReconfigureEvent event) { // Invalidate everything if local realms change if(event.getOldConfig() != null && !event.getOldConfig().realms().equals(event.getNewConfig().realms())) { prioritiesByPlayer.invalidateAll(); } }
@Subscribe @SuppressWarnings("unused") public void handle(AccountWithdrawnEvent event) { TransactionProjection tx = new TransactionProjection( event.getAggregateId(), WITHDRAWAL, event.getAmount(), event.getTimestamp(), event.getVersion()); transactionsRepository.save(tx); }
@Subscribe public void onIrcPrivateMessageEvent(IrcPrivateMessageEvent event) { if (event.getUsername().equalsIgnoreCase(IrcSession.SYSTEM_USER)) { return; } Template template = templateDao.getByKey(PM_RESPONSE_TEMPLATE_ID); if (template == null || StringUtils.isEmpty(template.getTemplate())) { return; } chat.whisper(event.getUsername(), Templater.template(template.getTemplate()) .add("moderators", this::createModeratorList)); }
@Subscribe private void toggleLoadingScreen(ToggleEvent e) { Platform.runLater(() -> { if (e == ToggleEvent.SHOW_LOADING) { loadingPane.toFront(); } else if (e == ToggleEvent.HIDE_LOADING) { loadingPane.toBack(); } }); }
@Subscribe private void handleLoginStateChange(ToggleEvent e) { if (e == ToggleEvent.LOGOUT) { showRoomSettings = false; settingsPane.toBack(); } }
@Subscribe private void roomCollectionChanged(RoomCollection roomCollection) { Platform.runLater(()->{ if (backendListForView != null) { backendListForView.dispose(); } backendListForView = new FXThreadedObservableListWrapper<>(roomCollection.getRoomsProperty()); roomListView.setCellFactory(listView -> { RoomListItemView roomListItemView = new RoomListItemView(); roomListItemView.getView(); return (RoomListItemPresenter) roomListItemView.getPresenter(); }); roomListView.setItems(backendListForView.getList()); serverName.textProperty().unbind(); if (roomCollection instanceof Server) { serverName.textProperty().bind( new FXThreadedObservableValueWrapper<>( ((Server) roomCollection).nameProperty() ) ); } else if (roomCollection instanceof PMCollection) { serverName.textProperty().setValue(bundle.getString("pm")); } else if (roomCollection instanceof GeneralCollection) { serverName.textProperty().setValue(bundle.getString("general")); } // Handle room selection (selects the first room in the RoomCollection if the RoomCollection // isn't empty and if the previously selected room isn't in the current RoomCollection) if (roomCollection.getRoomsProperty().contains(client.getSelectedRoom())) { roomListView.getSelectionModel().select(client.getSelectedRoom()); } else if (roomCollection.getRoomsProperty().size() > 0) { eventBus.post(roomCollection.getRoomsProperty().get(0)); roomListView.getSelectionModel().select(0); } }); }
@Subscribe private void handleLoginStateChange(ToggleEvent e) { if (e == ToggleEvent.LOGOUT) { showDirectory = false; directoryPane.toBack(); } }
@Subscribe private void toggleLoadingScreen(ToggleEvent e) { Platform.runLater(() -> { if (e == ToggleEvent.SHOW_LOADING) { imageView.setImage(new Image(LoadingPresenter.class.getResourceAsStream("/images/loading.gif"))); } else if (e == ToggleEvent.HIDE_LOADING) { imageView.setImage(null); } }); }
@Subscribe public void updateBuildList( final IBuildTypeManager buildManager ) { Platform.runLater( ( ) -> { _displayedBuilds.forEach( _eventBus::unregister ); _displayedBuilds.setAll( (List<TileViewModel>) buildManager.getMonitoredBuildTypes( ).stream( ) .map( _tileViewModeFactory::forBuildTypeData ) .collect( Collectors.toList( ) ) ); _displayedBuilds.forEach( _eventBus::register ); } ); }
@Subscribe public void onReconfigure(LocalServerReconfigureEvent event) { final Instant oldTime, newTime; final String oldReason, newReason; final int oldPriority, newPriority; if(event.getOldConfig() == null) { oldTime = null; oldReason = null; oldPriority = ServerDoc.Restart.Priority.NORMAL; } else { oldTime = event.getOldConfig().restart_queued_at(); oldReason = event.getOldConfig().restart_reason(); oldPriority = event.getOldConfig().restart_priority(); } newTime = event.getNewConfig().restart_queued_at(); newReason = event.getNewConfig().restart_reason(); newPriority = event.getNewConfig().restart_priority(); if(Objects.equals(oldTime, newTime) && Objects.equals(oldReason, newReason) && Objects.equals(oldPriority, newPriority)) return; if(oldTime != null) { logger.info("Restart cancelled"); currentRequest = null; eventBus.post(new CancelRestartEvent()); } if(newTime != null) { logger.info("Restart requested at " + newTime + ", with " + newPriority + " priority, because \"" + newReason + '"'); currentRequest = new RequestRestartEvent(logger, newReason, newPriority, this::restartIfRequested); eventBus.post(currentRequest); restartIfRequested(); } }
@Subscribe public void onIrcUserModeEvent(IrcUserModeEvent event) { if (event.isModeratorMode()) { User user = usersService.getUser(event.getUsername()); if (!user.isModerator()) { user.setModerator(true); userDao.save(user); } } }
/** * onLoadCommand * * @param command */ @Subscribe public void onLoadCommand(BloomFilterCommand command) { if (command != null && command.getAction() == BloomFilterCommand.BloomFilterAction.FORCELOAD) { String cmd = command.getCommand(); if (cmd != null && cmd.equalsIgnoreCase(getBloomFilterName())) { triggerLoad(true); if (logger.isInfoEnabled()) { logger.info("ScheduleBloomFilterLoadTrigger,onLoadCommand,BloomFilterCommand[" + command + "]"); } } } }
@Subscribe public void onIrcConnectedEvent(IrcChannelJoinedEvent event) { logger.info("Initializing components..."); coreComponents.forEach(Component::init); components.forEach(Component::init); logger.info("All components loaded succesfully"); logger.info("Biliomi is ready for commands!"); }
@Subscribe public void modPreinitialization(FMLPreInitializationEvent evt) { // Initialize all Forge/Vanilla registries {invoke the static init) if (ForgeRegistries.ITEMS == null) throw new RuntimeException("Something horrible went wrong in init, ForgeRegistres didn't create..."); }