Java Code Examples for com.google.common.eventbus.EventBus#post()

The following examples show how to use com.google.common.eventbus.EventBus#post() . 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: CollectionUpdater.java    From tds with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
public void execute(JobExecutionContext context) throws JobExecutionException {
  EventBus eventBus = (EventBus) context.getJobDetail().getJobDataMap().get(EVENT_BUS);
  String collectionName = (String) context.getJobDetail().getJobDataMap().get(COLLECTION_NAME);
  org.slf4j.Logger loggerfc = (org.slf4j.Logger) context.getJobDetail().getJobDataMap().get(LOGGER);
  CollectionUpdateType type = (CollectionUpdateType) context.getTrigger().getJobDataMap().get(UpdateType);
  String source = (String) context.getTrigger().getJobDataMap().get(Source);
  String groupName = context.getTrigger().getKey().getGroup();

  try {
    eventBus.post(new CollectionUpdateEvent(type, collectionName, source));
    fcLogger.debug("CollectionUpdate post event {} on {}", type, collectionName);

  } catch (Throwable e) {
    if (loggerfc != null)
      loggerfc.error("UpdateCollectionJob.execute " + groupName + " failed collection=" + collectionName, e);
  }
}
 
Example 2
Source File: OriginsInventoryHandlerTest.java    From styx with Apache License 2.0 6 votes vote down vote up
@Test
public void prettyPrintsOriginsSnapshot() {
    EventBus eventBus = new EventBus();
    OriginsInventoryHandler handler = new OriginsInventoryHandler(eventBus);

    Set<Origin> disabledOrigins = generateOrigins(2);

    eventBus.post(new OriginsSnapshot(APP_ID, pool(emptySet()), pool(emptySet()), pool(disabledOrigins)));

    HttpResponse response = Mono.from(handler.handle(get("/?pretty=1").build(), requestContext())).block();
    assertThat(body(response).replace("\r\n", "\n"),
            matchesRegex("\\{\n" +
                    "  \"" + APP_ID + "\" : \\{\n" +
                    "    \"appId\" : \"" + APP_ID + "\",\n" +
                    "    \"activeOrigins\" : \\[ ],\n" +
                    "    \"inactiveOrigins\" : \\[ ],\n" +
                    "    \"disabledOrigins\" : \\[ \\{\n" +
                    "      \"id\" : \"origin.\",\n" +
                    "      \"host\" : \"localhost:....\"\n" +
                    "    }, \\{\n" +
                    "      \"id\" : \"origin.\",\n" +
                    "      \"host\" : \"localhost:....\"\n" +
                    "    } ]\n" +
                    "  }\n" +
                    "}"));
}
 
Example 3
Source File: EventBusPublishingTaskFactory.java    From incubator-gobblin with Apache License 2.0 6 votes vote down vote up
@Override
public List<WorkUnit> getWorkunits(SourceState state) {
  int numTasks = state.getPropAsInt(NUM_TASKS_KEY);
  String eventBusId = state.getProp(EVENTBUS_ID_KEY);
  EventBus eventBus = TestingEventBuses.getEventBus(eventBusId);

  Map<String, SourceState> previousStates = state.getPreviousDatasetStatesByUrns();
  for (Map.Entry<String, SourceState> entry : previousStates.entrySet()) {
    JobState.DatasetState datasetState = (JobState.DatasetState) entry.getValue();
    for (TaskState taskState : datasetState.getTaskStates()) {
      if (taskState.contains(Task.PERSISTENT_STATE) && eventBus != null) {
        eventBus.post(new Event(PREVIOUS_STATE_EVENT, taskState.getPropAsInt(Task.PERSISTENT_STATE)));
      }
    }
  }

  List<WorkUnit> workUnits = Lists.newArrayList();
  for (int i = 0; i < numTasks; i++) {
    workUnits.add(createWorkUnit(i, eventBusId));
  }
  return workUnits;
}
 
Example 4
Source File: SkyframeExecutor.java    From bazel with Apache License 2.0 6 votes vote down vote up
private void setPackageLocator(PathPackageLocator pkgLocator) {
  EventBus eventBus = this.eventBus.get();
  if (eventBus != null) {
    eventBus.post(pkgLocator);
  }

  PathPackageLocator oldLocator = this.pkgLocator.getAndSet(pkgLocator);
  PrecomputedValue.PATH_PACKAGE_LOCATOR.set(injectable(), pkgLocator);

  if (!pkgLocator.equals(oldLocator)) {
    // The package path is read not only by SkyFunctions but also by some other code paths.
    // We need to take additional steps to keep the corresponding data structures in sync.
    // (Some of the additional steps are carried out by ConfiguredTargetValueInvalidationListener,
    // and some by BuildView#buildHasIncompatiblePackageRoots and #updateSkyframe.)
    artifactFactory
        .setSourceArtifactRoots(
            createSourceArtifactRootMapOnNewPkgLocator(oldLocator, pkgLocator));
  }
}
 
Example 5
Source File: EventBusTest.java    From onetwo with Apache License 2.0 5 votes vote down vote up
@Test
public void testEventBus(){
	EventBus eventBus = new EventBus();
	eventBus.register(new Object(){
		
		@Subscribe
		public void listener(TestEvent event){
			System.out.println("listener1:"+event.name);
		}
	});
	/*eventBus.register(new Object(){
		
		@Subscribe
		public void listener(TestEvent event){
			System.out.println("listener2:"+event.name);
			if(true)
				throw new BaseException("error");
		}
	});
	eventBus.register(new Object(){
		
		@Subscribe
		public void listener(TestEvent event){
			System.out.println("listener3:"+event.name);
			if(true)
				throw new BaseException("error");
		}
	});*/

	eventBus.post(new TestEvent("test"));
	eventBus.post(new TestEvent("test"));
}
 
Example 6
Source File: TestingEventBusAsserterTest.java    From incubator-gobblin with Apache License 2.0 5 votes vote down vote up
@Test
public void testAssertNext() throws InterruptedException, TimeoutException, IOException {
  EventBus testBus = TestingEventBuses.getEventBus("TestingEventBusAsserterTest.testHappyPath");

  try(final TestingEventBusAsserter asserter =
      new TestingEventBusAsserter("TestingEventBusAsserterTest.testHappyPath")) {
    testBus.post(new TestingEventBuses.Event("event1"));
    testBus.post(new TestingEventBuses.Event("event2"));

    asserter.assertNextValueEq("event1");
    Assert.assertThrows(new ThrowingRunnable() {
      @Override public void run() throws Throwable {
        asserter.assertNextValueEq("event3");
      }
    });

    testBus.post(new TestingEventBuses.Event("event13"));
    testBus.post(new TestingEventBuses.Event("event11"));
    testBus.post(new TestingEventBuses.Event("event12"));
    testBus.post(new TestingEventBuses.Event("event10"));

    asserter.assertNextValuesEq(Arrays.asList("event10", "event11", "event12", "event13"));

    testBus.post(new TestingEventBuses.Event("event22"));
    testBus.post(new TestingEventBuses.Event("event20"));

    Assert.assertThrows(new ThrowingRunnable() {
      @Override public void run() throws Throwable {
        asserter.assertNextValuesEq(Arrays.asList("event22", "event21"));
      }
    });
  }
}
 
Example 7
Source File: GenericEvent.java    From micro-server with Apache License 2.0 5 votes vote down vote up
public static <T> GenericEvent<T> trigger(String name, EventBus bus, T data, String[] subTypes) {
    GenericEvent<T> event = new GenericEvent<>(GenericEventData.<T>builder()
                                                       .name(name)
                                                       .data(data)
                                                       .subTypes(subTypes)
                                                       .build());
    bus.post(event);
    return event;
}
 
Example 8
Source File: LoveTrackService.java    From scroball with MIT License 5 votes vote down vote up
@Override
public void onHandleIntent(Intent intent) {
  Track track =
      Track.builder()
          .track(intent.getStringExtra(TRACK_KEY))
          .artist(intent.getStringExtra(ARTIST_KEY))
          .build();

  EventBus eventBus = ScroballApplication.getEventBus();
  eventBus.post(TrackLoveEvent.create(track));
}
 
Example 9
Source File: FlushResource.java    From DataLink with Apache License 2.0 5 votes vote down vote up
@POST
@Path("/reloadHBase/{mediaSourceId}")
public void reloadHBase(@PathParam("mediaSourceId") String mediaSourceId) throws Throwable {
    logger.info("Receive a request for reload hbase-media-source,with id " + mediaSourceId);

    MediaSourceInfo mediaSourceInfo = DataLinkFactory.getObject(MediaSourceService.class).getById(Long.valueOf(mediaSourceId));
    EventBus eventBus = EventBusFactory.getEventBus();
    HBaseConfigClearEvent event = new HBaseConfigClearEvent(new FutureCallback(), mediaSourceInfo);
    eventBus.post(event);
    event.getCallback().get();
    //清空相关Task的mapping缓存
    clearTaskMediaMappingCache(Long.valueOf(mediaSourceId));
}
 
Example 10
Source File: BlazeRuntime.java    From bazel with Apache License 2.0 5 votes vote down vote up
@Override
public void cleanUpForCrash(DetailedExitCode exitCode) {
  if (declareExitCode(exitCode)) {
    // Only try to publish events if we won the exit code race. Otherwise someone else is already
    // exiting for us.
    EventBus eventBus = workspace.getSkyframeExecutor().getEventBus();
    if (eventBus != null) {
      workspace
          .getSkyframeExecutor()
          .postLoggingStatsWhenCrashing(
              new ExtendedEventHandler() {
                @Override
                public void post(Postable obj) {
                  eventBus.post(obj);
                }

                @Override
                public void handle(Event event) {}
              });
      eventBus.post(new CommandCompleteEvent(exitCode));
    }
  }
  // We don't call #shutDown() here because all it does is shut down the modules, and who knows if
  // they can be trusted.  Instead, we call runtime#shutdownOnCrash() which attempts to cleanly
  // shut down those modules that might have something pending to do as a best-effort operation.
  shutDownModulesOnCrash();
}
 
Example 11
Source File: MediaServiceImpl.java    From DataLink with Apache License 2.0 5 votes vote down vote up
@Override
public void cleanTableMapping(Long taskId) throws Exception {
    EventBus eventBus = EventBusFactory.getEventBus();
    MediaMappingChangeEvent event = new MediaMappingChangeEvent(new FutureCallback(), taskId);
    eventBus.post(event);
    event.getCallback().get();
}
 
Example 12
Source File: FlushResource.java    From DataLink with Apache License 2.0 5 votes vote down vote up
@POST
@Path("/reloadKudu/{mediaSourceId}")
public void reloadKudu(@PathParam("mediaSourceId") String mediaSourceId) throws Throwable {
    logger.info("Receive a request for reload kudu-media-source,with id " + mediaSourceId);

    MediaSourceInfo mediaSourceInfo = DataLinkFactory.getObject(MediaSourceService.class).getById(Long.valueOf(mediaSourceId));
    EventBus eventBus = EventBusFactory.getEventBus();
    KuduConfigClearEvent event = new KuduConfigClearEvent(new FutureCallback(), mediaSourceInfo);
    eventBus.post(event);
    event.getCallback().get();
    //清空相关Task的mapping缓存
    clearTaskMediaMappingCache(Long.valueOf(mediaSourceId));
}
 
Example 13
Source File: SkyframeIncrementalBuildMonitor.java    From bazel with Apache License 2.0 4 votes vote down vote up
public void alertListeners(EventBus eventBus) {
  Set<PathFragment> changedFiles = (files != null) ? files : ImmutableSet.<PathFragment>of();
  eventBus.post(new ChangedFilesMessage(changedFiles, fileCount));
}
 
Example 14
Source File: EventBusStart.java    From tools-journey with Apache License 2.0 4 votes vote down vote up
private static void sync() {
    final EventBus eventBus = new EventBus();
    eventBus.register(new CommonListener());
    eventBus.post(new ChargeEvent());
}
 
Example 15
Source File: TestWorkUnitStreamSource.java    From incubator-gobblin with Apache License 2.0 4 votes vote down vote up
/**
 * This test uses a slow source to verify that we can stream work units through local job launcher, with available units
 * being processes eagerly even if not all work units are available.
 */
@Test
public void test() throws Exception {

  String eventBusId = UUID.randomUUID().toString();
  MyListener listener = new MyListener();

  EventBus eventBus = TestingEventBuses.getEventBus(eventBusId);
  eventBus.register(listener);

  EmbeddedGobblin embeddedGobblin = new EmbeddedGobblin("testStreamedSource")
      .setConfiguration(EventBusPublishingTaskFactory.EVENTBUS_ID_KEY, eventBusId)
      .setConfiguration(ConfigurationKeys.SOURCE_CLASS_KEY, MySource.class.getName())
      .setConfiguration(EventBusPublishingTaskFactory.Source.NUM_TASKS_KEY, "5");

  JobExecutionDriver driver = embeddedGobblin.runAsync();
  if (!listener.iteratorReady.tryAcquire(2, TimeUnit.SECONDS)) {
    throw new RuntimeException("Failed to get start signal.");
  }

  Assert.assertFalse(listener.tasksRun.tryAcquire(50, TimeUnit.MILLISECONDS));
  eventBus.post(new MySource.NextWorkUnit());
  Assert.assertTrue(listener.tasksRun.tryAcquire(500, TimeUnit.MILLISECONDS));
  Assert.assertFalse(listener.tasksRun.tryAcquire(50, TimeUnit.MILLISECONDS));

  eventBus.post(new MySource.NextWorkUnit());
  Assert.assertTrue(listener.tasksRun.tryAcquire(500, TimeUnit.MILLISECONDS));
  Assert.assertFalse(listener.tasksRun.tryAcquire(50, TimeUnit.MILLISECONDS));

  eventBus.post(new MySource.NextWorkUnit());
  eventBus.post(new MySource.NextWorkUnit());
  eventBus.post(new MySource.NextWorkUnit());

  JobExecutionResult result = driver.get(5, TimeUnit.SECONDS);
  Assert.assertTrue(result.isSuccessful());

  SetMultimap<String, Integer> eventsSeen = listener.getEventsSeenMap();
  Set<Integer> expected = Sets.newHashSet(0, 1, 2, 3, 4);
  Assert.assertEquals(eventsSeen.get(EventBusPublishingTaskFactory.RUN_EVENT), expected);
  Assert.assertEquals(eventsSeen.get(EventBusPublishingTaskFactory.COMMIT_EVENT), expected);
  Assert.assertEquals(eventsSeen.get(EventBusPublishingTaskFactory.PUBLISH_EVENT), expected);

}
 
Example 16
Source File: TestApplication.java    From pulsar with Apache License 2.0 3 votes vote down vote up
@Test
public void testBasicConfiguration() throws Exception {

    EventBus eventBus = new EventBus("test-event-bus");

    MaterializedConfiguration materializedConfiguration = new
            SimpleMaterializedConfiguration();

    SourceRunner sourceRunner = mockLifeCycle(SourceRunner.class);
    materializedConfiguration.addSourceRunner("test", sourceRunner);

    SinkRunner sinkRunner = mockLifeCycle(SinkRunner.class);
    materializedConfiguration.addSinkRunner("test", sinkRunner);

    Channel channel = mockLifeCycle(Channel.class);
    materializedConfiguration.addChannel("test", channel);


    ConfigurationProvider configurationProvider = mock(ConfigurationProvider.class);
    when(configurationProvider.getConfiguration()).thenReturn(materializedConfiguration);

    Application application = new Application();
    eventBus.register(application);
    eventBus.post(materializedConfiguration);
    application.start();

    Thread.sleep(1000L);

    verify(sourceRunner).start();
    verify(sinkRunner).start();
    verify(channel).start();

    application.stop();

    Thread.sleep(1000L);

    verify(sourceRunner).stop();
    verify(sinkRunner).stop();
    verify(channel).stop();
}
 
Example 17
Source File: LabelledEvents.java    From micro-server with Apache License 2.0 3 votes vote down vote up
/**
 * Publish start events for each of the specified query types
 *
 * <pre>
 * {@code
    LabelledEvents.start("get", 1l, bus, "typeA", "custom");
    try {
        return "ok";
    } finally {
        RequestEvents.finish("get", 1l, bus, "typeA", "custom");
    }
 * }
 * </pre>
 *
 * @param query Completed query
 * @param correlationId Identifier
 * @param bus EventBus to post events to
 * @param labels Query labels to post to event bus
 */
public static <T> void start(T query, String correlationId, EventBus bus, String... labels) {

    for (String label : labels) {
        AddLabelledQuery<T> next = start(query, correlationId, label, null);
        bus.post(next);
    }

}
 
Example 18
Source File: LabelledEvents.java    From micro-server with Apache License 2.0 3 votes vote down vote up
/**
 * Publish finish events for each of the specified query labels
 *
 * <pre>
 * {@code
 * LabelledEvents.start("get", 1l, bus, "typeA", "custom");
   try {
        return "ok";
    } finally {
        RequestEvents.finish("get", 1l, bus, "typeA", "custom");
    }
 *
 * }
 * </pre>
 *
 *
 * @param query Completed query
 * @param correlationId Identifier
 * @param bus EventBus to post events to
 * @param labels Query types to post to event bus
 */
public static <T> void finish(T query, String correlationId, EventBus bus, String... labels) {
    for (String type : labels) {
        RemoveLabelledQuery<T> next = finish(query, correlationId, type);
        bus.post(next);
    }
}
 
Example 19
Source File: RequestEvents.java    From micro-server with Apache License 2.0 3 votes vote down vote up
/**
 * Publish start events for each of the specified query types
 * 
 * <pre>
 * {@code 
    RequestEvents.start("get", 1l, bus, "typeA", "custom");
    try {
        return "ok";
    } finally {
        RequestEvents.finish("get", 1l, bus, "typeA", "custom");
    }     
 * }
 * </pre>
 * 
 * @param query Completed query
 * @param correlationId Identifier
 * @param bus EventBus to post events to
 * @param types Query types to post to event bus
 */
public static <T> void start(T query, String correlationId, EventBus bus, String... types) {

    for (String type : types) {
        AddQuery<T> next = start(query, correlationId, type, null);
        bus.post(next);
    }

}
 
Example 20
Source File: OriginsInventoryHandler.java    From styx with Apache License 2.0 2 votes vote down vote up
/**
 * Construct an instance.
 *
 * @param eventBus an event-bus to listen to for inventory state changes
 */
public OriginsInventoryHandler(EventBus eventBus) {
    eventBus.register(this);
    eventBus.post(new GetOriginsInventorySnapshot());
}