@Test public void testEventSuperInterfaceHierarchy() { eventBus.register(this); eventBus.post(new MyEventInterfaceExtended() {}); assertEquals(0, countMyEventInterface); assertEquals(0, countMyEventInterfaceExtended); }
@Test public void testEventClassHierarchySticky() { eventBus.postSticky("Hello"); eventBus.postSticky(new MyEvent()); eventBus.postSticky(new MyEventExtended()); eventBus.register(new StickySubscriber()); assertEquals(1, countMyEventExtended); assertEquals(1, countMyEvent); assertEquals(0, countObjectEvent); }
public void testNoReentrantEvents() { ReentrantEventsHater hater = new ReentrantEventsHater(); bus.register(hater); bus.post(FIRST); assertEquals( "ReentrantEventHater expected 2 events", Lists.<Object>newArrayList(FIRST, SECOND), hater.eventsReceived); }
public void testEventOrderingIsPredictable() { EventProcessor processor = new EventProcessor(); bus.register(processor); EventRecorder recorder = new EventRecorder(); bus.register(recorder); bus.post(FIRST); assertEquals( "EventRecorder expected events in order", Lists.<Object>newArrayList(FIRST, SECOND), recorder.eventsReceived); }
@Test public void shouldNotifyAboutEvent() { FirstHandler firstHandler = mock(FirstHandler.class); SecondHandler secondHandler = mock(SecondHandler.class); EventBus eventBus = new EventBus(new EventHandler[] {firstHandler, secondHandler}); FirstEvent firstEvent = new FirstEvent(); eventBus.fireEvent(firstEvent); SecondEvent secondEvent = new SecondEvent(); eventBus.fireEvent(secondEvent); verify(firstHandler).onEvent(firstEvent); verify(secondHandler).onEvent(secondEvent); }
@Override public void run() { try { try { while (true) { PendingPost pendingPost = queue.poll(1000); if (pendingPost == null) { synchronized (this) { // Check again, this time in synchronized pendingPost = queue.poll(); if (pendingPost == null) { executorRunning = false; return; } } } eventBus.invokeSubscriber(pendingPost); } } catch (InterruptedException e) { Log.w("Event", Thread.currentThread().getName() + " was interruppted", e); } } finally { executorRunning = false; } }
@Test public void testEventClassHierarchy() { eventBus.register(this); eventBus.post("Hello"); assertEquals(0, countObjectEvent); eventBus.post(new MyEvent()); assertEquals(0, countObjectEvent); assertEquals(1, countMyEvent); eventBus.post(new MyEventExtended()); assertEquals(0, countObjectEvent); assertEquals(1, countMyEvent); assertEquals(1, countMyEventExtended); }
@QueueCallback(QueueCallbackType.LIMIT) private void queueLimit() { if (messageCountSinceLastFlush > 100_000) { now = Timer.timer().now(); logger.debug( "EventManager {}: Sending all " + "messages because we have more than 100K", name); sendMessages(); return; } now = Timer.timer().now(); long duration = now - lastFlushTime; if (duration > 50 && messageCountSinceLastFlush > 0) { if (debug) { logger.debug( "EventManager {}: Sending all " + "messages because 50 MS elapsed and we have more than 0", name); } sendMessages(); } eventBus.flush(); }
private void sendMessages() { flushCount++; lastFlushTime = now; stats.recordCount(eventCountStatsKey, messageCountSinceLastFlush); messageCountSinceLastFlush = 0; if (debug) { logger.debug("EventManager {} flushCount {}", name, flushCount); } final Set<Map.Entry<String, List<Object>>> entries = eventMap.entrySet(); for (Map.Entry<String, List<Object>> entry : entries) { String channelName = entry.getKey(); final List<Object> events = entry.getValue(); for (Object event : events) { eventBus.send(channelName, event); } events.clear(); } //noinspection Convert2streamapi for (SendQueue<Event<Object>> sendQueue : queuesToFlush) { sendQueue.flushSends(); } }
public HSVColorPicker6() { EventBus.getSystem() .addListener( this, MouseEvent.MouseAll, new Callback<MouseEvent>() { public void call(MouseEvent mouseEvent) throws Exception { if (mouseEvent.getType() == MouseEvent.MousePressed) { centerPoint = mouseEvent.getPointInNodeCoords(HSVColorPicker6.this); startColor = color; setDrawingDirty(); } if (mouseEvent.getType() == MouseEvent.MouseDragged) { double x = mouseEvent.getX() - centerPoint.getX(); double y = mouseEvent.getY() - centerPoint.getY(); float[] comps = toHSB(color); float[] start = toHSB(startColor); if (x > -10 && x < 10 && y > -10 && y < 10) { return; } if (x > -5 && x < 5 && y > -100 && y < 100) { double off = start[0]; color = FlatColor.hsb((y / 200.0 + off) * 360.0, comps[1], comps[2]); setDrawingDirty(); return; } double sin = Math.sin(Math.toRadians(-30)); double cos = Math.cos(Math.toRadians(-30)); double tx = cos * x + sin * y; double ty = sin * x + cos * y; if (tx > -100 && tx < 100 && ty > -5 && ty < 5) { double sat = (tx + 100) / 100.0; sat = start[1] - (1 - sat); sat = clamp(0, sat, 1); color = FlatColor.hsb(comps[0] * 360, sat, comps[2]); setDrawingDirty(); return; } sin = Math.sin(Math.toRadians(60)); cos = Math.cos(Math.toRadians(60)); tx = cos * x + sin * y; ty = sin * x + cos * y; if (tx > -5 && tx < 5 && ty > -100 && ty < 100) { double bright = ty / 100.0; bright = 1.0 - bright; bright = start[2] - (1 - bright); bright = clamp(0, bright, 1); color = FlatColor.hsb(comps[0] * 360, comps[1], bright); setDrawingDirty(); return; } return; } } }); }
@Override public void run() { PendingPost pendingPost = queue.poll(); if (pendingPost == null) { throw new IllegalStateException("No pending post available"); } eventBus.invokeSubscriber(pendingPost); }
/** * @param scope the scope of the events that this event bus handles. * @param parentEventBus the parent event bus to use, may be {@code null}; */ public ScopedEventBus(EventScope scope, EventBus parentEventBus) { eventScope = scope; if (parentEventBus != null) { logger.debug("Using parent event bus [{}]", parentEventBus); parentEventBus.subscribe(parentListener); } this.parentEventBus = parentEventBus; }
@Test public void testSubscriberClassHierarchyWithoutNewSubscriberMethod() { SubscriberExtendedWithoutNewSubscriberMethod subscriber = new SubscriberExtendedWithoutNewSubscriberMethod(); eventBus.register(subscriber); eventBus.post("Hello"); assertEquals(0, subscriber.countObjectEvent); eventBus.post(new MyEvent()); assertEquals(0, subscriber.countObjectEvent); assertEquals(1, subscriber.countMyEvent); eventBus.post(new MyEventExtended()); assertEquals(0, subscriber.countObjectEvent); assertEquals(1, subscriber.countMyEvent); assertEquals(1, subscriber.countMyEventExtended); }
public void setSelectedFill(Paint paint) { this.selectedFill = paint; if (!locked) { if (paint instanceof FlatColor) { freerangeColorPickerPopup.setSelectedColor((FlatColor) paint); rgbhsvpicker.setSelectedColor((FlatColor) paint); } } EventBus.getSystem().publish(new ChangedEvent(ChangedEvent.ObjectChanged, selectedFill, this)); setDrawingDirty(); }
@QueueCallback(QueueCallbackType.IDLE) private void queueIdle() { now = Timer.timer().now(); if (messageCountSinceLastFlush > 0) { sendMessages(); return; } eventBus.flush(); }
@SuppressWarnings("unchecked") @Override public void publish(LogRecord record) { if (record.getLoggerName().endsWith("PluginExecutable") && record.getMessage().contains("PluginExecutable")) { try { Class<? extends IPluginExecutable> clazz = (Class<? extends IPluginExecutable>) Class.forName(record.getLoggerName()); EventBus.getInstance().add(EventType.INFO, clazz, record.getSourceClassName()); } catch (ClassNotFoundException e) { throw new RuntimeException(e); } } }
private void setupColorTab(TabPanel panel) { freerangeColorPickerPopup = new FreerangeColorPickerPopup(null, 300, 170, false); freerangeColorPickerPopup.setOutsideColorProvider( new FreerangeColorPickerPopup.OutsideColorProvider() { @Override public FlatColor getColorAt(MouseEvent event) { if (context == null) return super.getColorAt(event); Point2D pt = event.getPointInNodeCoords(context.getSketchCanvas()); pt = context.getSketchCanvas().transformToCanvas(pt.getX(), pt.getY()); java.util.List<SNode> underCursor = new ArrayList<SNode>(); for (SNode node : context.getDocument().getCurrentPage().getNodes()) { if (node.getTransformedBounds().contains(pt)) { underCursor.add(node); } } if (underCursor.isEmpty()) { } else { SNode node = underCursor.get(underCursor.size() - 1); if (node instanceof SShape) { SShape shape = ((SShape) node); if (shape.getFillPaint() instanceof FlatColor) { return (FlatColor) shape.getFillPaint(); } } } return super.getColorAt( event); // To change body of overridden methods use File | Settings | File // Templates. } }); EventBus.getSystem() .addListener( freerangeColorPickerPopup, ChangedEvent.ColorChanged, new Callback<ChangedEvent>() { public void call(ChangedEvent event) throws Exception { locked = true; setSelectedFill((FlatColor) event.getValue()); locked = false; if (!event.isAdjusting()) { popup.setVisible(false); } } }); panel.add("Color", freerangeColorPickerPopup); }
@Override protected void setPressed(boolean pressed) { super.setPressed(pressed); if (pressed) { if (!popupadded) { Stage stage = getParent().getStage(); stage.getPopupLayer().add(popup); } Point2D pt = NodeUtils.convertToScene(this, 0, getHeight()); popup.setTranslateX(Math.round(Math.max(pt.getX(), 0))); popup.setTranslateY(Math.round(Math.max(pt.getY(), 0))); popup.setVisible(true); EventBus.getSystem().setPressedNode(popup); } else { // popup.setVisible(false); } }
@Override public <T> void publish(EventScope scope, Object sender, T payload) throws UnsupportedOperationException { logger.debug( "Trying to publish payload [{}] from sender [{}] using scope [{}] on event bus [{}]", payload, sender, scope, this); if (eventScope.equals(scope)) { publish(sender, payload); } else if (parentEventBus != null) { parentEventBus.publish(scope, sender, payload); } else { logger.warn("Could not publish payload with scope [{}] on event bus [{}]", scope, this); throw new UnsupportedOperationException("Could not publish event with scope " + scope); } }
private void setupRGBTab(TabPanel panel) { rgbhsvpicker = new ColorPickerPanel(280, 250); panel.add("RGB/HSV", rgbhsvpicker); EventBus.getSystem() .addListener( rgbhsvpicker, ChangedEvent.ColorChanged, new Callback<ChangedEvent>() { public void call(ChangedEvent changedEvent) throws Exception { locked = true; setSelectedFill((FlatColor) changedEvent.getValue()); if (!changedEvent.isAdjusting()) { popup.setVisible(false); } locked = false; } }); }
@QueueCallback(QueueCallbackType.EMPTY) private void queueEmpty() { if (messageCountSinceLastFlush > 100) { now = Timer.timer().now(); sendMessages(); return; } now = Timer.timer().now(); long duration = now - lastFlushTime; if (duration > 20 && messageCountSinceLastFlush > 0) { sendMessages(); } eventBus.flush(); }
private TabPanel buildPanel() throws IOException { final TabPanel panel = new TabPanel(); panel.setPrefWidth(300); panel.setPrefHeight(250); setupColorTab(panel); setupSwatchTab(panel); setupRGBTab(panel); setupGradientTab(panel); setupPatternTab(panel); // TODO: is this popup event really working? EventBus.getSystem() .addListener( panel, MouseEvent.MouseAll, new Callback<MouseEvent>() { public void call(MouseEvent event) { if (event.getType() == MouseEvent.MouseDragged) { if (!popup.isVisible()) return; Control control = panel.getSelected(); if (control instanceof ListView) { ListView lv = (ListView) control; Object item = lv.getItemAt(event.getPointInNodeCoords(lv)); if (item instanceof Paint) { setSelectedFill((Paint) item); } } } if (event.getType() == MouseEvent.MouseReleased) { Point2D pt = event.getPointInNodeCoords(panel); pt = new Point2D.Double( pt.getX() + panel.getTranslateX(), pt.getY() + panel.getTranslateY()); if (panel.getVisualBounds().contains(pt)) { popup.setVisible(false); } } } }); return panel; }
@SuppressWarnings("Convert2Lambda") @Override public void subscribe(final String channelName, final SendQueue<Event<Object>> sendQueue) { logger.info( "EventManager {}::subscribe() channel name {} sendQueue {}", name, channelName, sendQueue.name()); queuesToFlush.add(sendQueue); //noinspection Anonymous2MethodRef eventBus.register( channelName, new EventSubscriber<Object>() { @Override public void listen(Event<Object> event) { sendQueue.send(event); } }); }
private void startEngine() throws Exception, InterruptedException { setMetaServers( Arrays.asList( // new Pair<String, HostPort>("ms1", new HostPort("1.1.1.1", 1111)) // )); final CountDownLatch latch = new CountDownLatch(1); doAnswer( new Answer<Void>() { @Override public Void answer(InvocationOnMock invocation) throws Throwable { latch.countDown(); return null; } }) .when(m_metaServerAssignmentHolder) .reassign(anyListOf(Server.class), anyListOf(Topic.class)); m_eventBus.pubEvent(new Event(EventType.LEADER_INIT, 0, createClusterStateHolder(), null)); latch.await(5, TimeUnit.SECONDS); }
@Inject public ApplicationErrorHandler(EventBus eventBus, ResourceBundleProvider resourceBundleProvider) { eventBus.register(this); this.resourceBundle = resourceBundleProvider.getResourceBundle(); }
@Before public void setUp() throws Exception { eventBus = EventBus.builder().eventInheritance(false).build(); }
private ListView<Paint> setupGradientTab(TabPanel panel) { double size = 40; // linears Paint gf1 = new LinearGradientFill() .setStartX(0) .setStartXSnapped(Snap.Start) .setEndX(size) .setEndXSnapped(Snap.End) .setStartY(size / 2) .setStartYSnapped(Snap.Middle) .setEndY(size / 2) .setEndYSnapped(Snap.Middle) .addStop(0, FlatColor.BLACK) .addStop(1, FlatColor.WHITE); Paint gf2 = new LinearGradientFill() .setStartX(size / 2) .setStartXSnapped(Snap.Middle) .setEndX(size / 2) .setEndXSnapped(Snap.Middle) .setStartY(0) .setStartYSnapped(Snap.Start) .setEndY(size) .setEndYSnapped(Snap.End) .addStop(0, FlatColor.BLACK) .addStop(1, FlatColor.WHITE); Paint gf3 = new LinearGradientFill() .setStartX(0) .setStartXSnapped(Snap.Start) .setEndX(size) .setEndXSnapped(Snap.End) .setStartY(0) .setStartYSnapped(Snap.Start) .setEndY(size) .setEndYSnapped(Snap.End) .addStop(0, FlatColor.BLACK) .addStop(1, FlatColor.WHITE); // linears 2 Paint gf6 = new LinearGradientFill() .setStartX(0) .setStartXSnapped(Snap.Start) .setStartY(size / 2) .setStartYSnapped(Snap.Middle) .setEndX(size) .setEndXSnapped(Snap.End) .setEndY(size / 2) .setEndYSnapped(Snap.Middle) .addStop(0.0, FlatColor.BLACK) .addStop(0.5, FlatColor.WHITE) .addStop(1.0, FlatColor.BLACK); // radials Paint gf4 = new RadialGradientFill() .setCenterX(size / 2) .setCenterY(size / 2) .setRadius(size / 2) .addStop(0, FlatColor.BLACK) .addStop(1, FlatColor.WHITE); Paint gf5 = new RadialGradientFill() .setCenterX(size / 2) .setCenterY(size / 2) .setRadius(size / 2) .addStop(0.0, FlatColor.BLACK) .addStop(0.5, FlatColor.WHITE) .addStop(1.0, FlatColor.BLACK); ListModel<Paint> gradientModel = ListView.createModel(gf1, gf2, gf3, gf6, gf4, gf5); final ListView<Paint> gradientList = new ListView<Paint>() .setModel(gradientModel) .setColumnWidth(size) .setRowHeight(size) .setOrientation(ListView.Orientation.HorizontalWrap) .setRenderer(paintItemRenderer); panel.add("gradients", gradientList); EventBus.getSystem() .addListener( gradientList, SelectionEvent.Changed, new Callback<SelectionEvent>() { public void call(SelectionEvent e) throws Exception { int n = e.getView().getSelectedIndex(); setSelectedFill(gradientList.getModel().get(n)); popup.setVisible(false); } }); return gradientList; }
@Override public void forwardEvent(final EventTransferObject<Object> event) { messageCountSinceLastFlush++; eventBus.forwardEvent(event); }
@Override public <T> void unregister(String channelName, EventListener<T> listener) { eventBus.unregister(channelName, listener); }
private void setupSwatchTab(TabPanel panel) { final ListView<FlatColor> colorList = new ListView<FlatColor>(); colorList.setModel(manager.colorManager.getSwatchModel()); colorList.setColumnWidth(20); colorList.setRowHeight(20); colorList.setOrientation(ListView.Orientation.HorizontalWrap); colorList.setRenderer( new ListView.ItemRenderer<FlatColor>() { public void draw( GFX gfx, ListView listView, FlatColor flatColor, int i, double x, double y, double w, double h) { gfx.setPaint(flatColor); gfx.fillRect(x, y, w, h); } }); EventBus.getSystem() .addListener( colorList, SelectionEvent.Changed, new Callback<SelectionEvent>() { public void call(SelectionEvent e) throws Exception { int n = e.getView().getSelectedIndex(); setSelectedFill(colorList.getModel().get(n)); popup.setVisible(false); } }); final PopupMenuButton switcher = new PopupMenuButton(); final ArrayListModel<Palette> palettes = manager.colorManager.getPalettes(); switcher.setModel(palettes); Button addButton = new Button("+"); addButton.onClicked( new Callback<ActionEvent>() { public void call(ActionEvent actionEvent) throws Exception { if (!palettes.get(switcher.getSelectedIndex()).isEditable()) { return; } final Stage dialog = Stage.createStage(); dialog.setTitle("Color"); final ColorPickerPanel picker = new ColorPickerPanel(); Callback<ActionEvent> okay = new Callback<ActionEvent>() { public void call(ActionEvent event) { FlatColor color = picker.getColor(); manager.colorManager.addSwatch(color); dialog.hide(); } }; Callback<ActionEvent> canceled = new Callback<ActionEvent>() { public void call(ActionEvent event) { dialog.hide(); } }; dialog.setContent( new VFlexBox() .add(picker) .add( new HFlexBox() .add(new Button("okay").onClicked(okay)) .add(new Button("cancel").onClicked(canceled)))); dialog.setWidth(400); dialog.setHeight(370); dialog.centerOnScreen(); } }); switcher.setTextRenderer( new ListView.TextRenderer() { public String toString(SelectableControl selectableControl, Object palette, int i) { if (palette instanceof Palette) { return ((Palette) palette).getName(); } else { return "foo"; } } }); EventBus.getSystem() .addListener( switcher, SelectionEvent.Changed, new Callback<SelectionEvent>() { public void call(SelectionEvent selectionEvent) throws Exception { int n = selectionEvent.getView().getSelectedIndex(); manager.colorManager.setCurrentPalette(palettes.get(n)); colorList.setModel(manager.colorManager.getSwatchModel()); } }); VFlexBox vbox = new VFlexBox(); vbox.setFill(FlatColor.GRAY); vbox.add(colorList, 1); vbox.add(new HFlexBox().add(addButton).add(switcher)); vbox.setBoxAlign(FlexBox.Align.Stretch); panel.add("Swatches", vbox); }