javax.enterprise.event.Event.fireAsync()方法的使用及代码示例

x33g5p2x  于2022-01-18 转载在 其他  
字(11.7k)|赞(0)|评价(0)|浏览(211)

本文整理了Java中javax.enterprise.event.Event.fireAsync()方法的一些代码示例,展示了Event.fireAsync()的具体用法。这些代码示例主要来源于Github/Stackoverflow/Maven等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。Event.fireAsync()方法的具体详情如下:
包路径:javax.enterprise.event.Event
类名称:Event
方法名:fireAsync

Event.fireAsync介绍

[英]Fires an event asynchronously with the specified qualifiers and notifies asynchronous observers.
[中]使用指定的限定符异步激发事件,并通知异步观察者。

代码示例

代码示例来源:origin: javaee-samples/javaee8-samples

@Override
  public CompletionStage<String> sendAsync(String message) {
    System.out.println("Sending async");
    return event.fireAsync(message);
  }
}

代码示例来源:origin: org.jboss.cdi.tck/cdi-tck-impl

public Throwable print() throws InterruptedException {
  BlockingQueue<Throwable> sync = new LinkedBlockingQueue<>();
  // this expects javax.ejb.EJBAccessException so the queue accepts only Throwable instance
  printer.fireAsync(new Text(TEACHER_MESSAGE)).whenComplete((text, throwable) -> sync.offer(throwable));
  return sync.poll(2l, TimeUnit.SECONDS);
}

代码示例来源:origin: org.jboss.cdi.tck/cdi-tck-impl

@Test
@SpecAssertions({ @SpecAssertion(section = OBSERVER_METHOD_INVOCATION_CONTEXT, id = "aa"), @SpecAssertion(section = REQUEST_CONTEXT, id = "da") })
public void testAsyncObserverIsCalledInNewRequestContext() throws Exception {
  counter.increment();
  BlockingQueue<String> queue = new LinkedBlockingQueue<>();
  stringEvent.fireAsync(new String()).thenAccept(queue::offer);
  String string = queue.poll(2l, TimeUnit.SECONDS);
  assertNotNull(string);
  assertTrue(AsyncMessageObserver.requestScopeActive.get());
  assertTrue(AsyncMessageObserver.counterIsZero.get());
}

代码示例来源:origin: org.jboss.cdi.tck/cdi-tck-impl

public Text print() throws ExecutionException, InterruptedException {
  BlockingQueue<Text> sync = new LinkedBlockingQueue<>();
  printer.fireAsync(new Text(STUDENT_MESSAGE)).thenAccept(sync::offer);
  return sync.poll(2l, TimeUnit.SECONDS);
}

代码示例来源:origin: org.jboss.cdi.tck/cdi-tck-impl

@Test
  @SpecAssertions({ @SpecAssertion(section = ASYNC_EXCEPTION, id = "a"), @SpecAssertion(section = ASYNC_EXCEPTION, id = "b"),
      @SpecAssertion(section = OBSERVER_NOTIFICATION, id = "cb") })
  public void testMultipleExceptionsDuringVariousObserversNotification() throws InterruptedException {
    BlockingQueue<Throwable> queue = new LinkedBlockingQueue<>();
    event.fireAsync(new RadioMessage()).handle((event, throwable) -> queue.offer(throwable));

    Throwable throwable = queue.poll(2, TimeUnit.SECONDS);
    assertNotNull(throwable);
    assertTrue(NewYorkRadioStation.observed.get());
    assertTrue(ParisRadioStation.observed.get());
    assertTrue(PragueRadioStation.observed.get());
    
    assertTrue(throwable instanceof CompletionException);

    List<Throwable> suppressedExceptions = Arrays.asList(throwable.getSuppressed());
    assertTrue(suppressedExceptions.contains(ParisRadioStation.exception.get()));
    assertTrue(suppressedExceptions.contains(NewYorkRadioStation.exception.get()));
    assertTrue(suppressedExceptions.stream().anyMatch(t -> t.getMessage().equals(ParisRadioStation.class.getName())));
    assertTrue(suppressedExceptions.stream().anyMatch(t -> t.getMessage().equals(NewYorkRadioStation.class.getName())));
  }
}

代码示例来源:origin: org.jboss.cdi.tck/cdi-tck-impl

@Test
@SpecAssertions({ @SpecAssertion(section = FIRING_EVENTS_ASYNCHRONOUSLY, id = "a") })
public void testAsyncObserversCalledInDifferentThread() throws InterruptedException {
  BlockingQueue<Experiment> queue = new LinkedBlockingQueue<>();
  int threadId = (int) Thread.currentThread().getId();
  event.fireAsync(new ScientificExperiment()).thenAccept(queue::offer);
  Experiment experiment2 = queue.poll(2, TimeUnit.SECONDS);
  assertEquals(experiment2.getUniversities().size(), 2);
  assertTrue(experiment2.getUniversities().contains(StandfordUniversityObserver.class));
  assertTrue(experiment2.getUniversities().contains(MassachusettsInstituteObserver.class));
  assertNotEquals(threadId, MassachusettsInstituteObserver.threadId.get());
}

代码示例来源:origin: org.jboss.cdi.tck/cdi-tck-impl

@Test
@SpecAssertion(section = OBSERVER_METHOD_INVOCATION_CONTEXT, id = "ab")
public void testAsyncObserverIsCalledInNewTransactionContext() throws Exception {
  userTransaction.begin();
  BlockingQueue<Message> queue = new LinkedBlockingQueue<>();
  event.fireAsync(new Message()).thenAccept(queue::offer);
  Message message = queue.poll(2l, TimeUnit.SECONDS);
  assertNotNull(message);
  assertEquals(Status.STATUS_NO_TRANSACTION, AsyncMessageObserver.status.get());
  userTransaction.commit();
}

代码示例来源:origin: org.jboss.cdi.tck/cdi-tck-impl

@Test
@SpecAssertions({ @SpecAssertion(section = EVENT, id = "ee") })
public void testCustomExecutor() throws InterruptedException {
  BlockingQueue<Message> queue = new LinkedBlockingQueue<>();
  NotificationOptions notificationOptions = NotificationOptions.ofExecutor(new CustomExecutor());
  event.fireAsync(new Message(), notificationOptions).thenAccept(queue::add);
  Message message = queue.poll(2, TimeUnit.SECONDS);
  assertNotNull(message);
  assertTrue(MessageObserver.observed.get());
  assertTrue(CustomExecutor.executed.get());
}

代码示例来源:origin: org.jboss.cdi.tck/cdi-tck-impl

@Test
@SpecAssertion(section = CONDITIONAL_OBSERVER_METHODS, id = "a")
public void testAsyncConditionalObserver() throws InterruptedException {
  BlockingQueue<AsyncConditionalEvent> queue = new LinkedBlockingQueue<>();
  asyncConditionalEventEvent.fireAsync(new AsyncConditionalEvent()).thenAccept(queue::offer);
  AsyncConditionalEvent event = queue.poll(2, TimeUnit.SECONDS);
  assertFalse(AsyncConditionalObserver.IsNotified().get());
  
  AsyncConditionalObserver observer = getContextualReference(AsyncConditionalObserver.class);
  assertNotNull(observer);
  observer.ping();
  
  asyncConditionalEventEvent.fireAsync(new AsyncConditionalEvent()).thenAccept(queue::offer);
  event = queue.poll(2, TimeUnit.SECONDS);
  assertTrue(AsyncConditionalObserver.IsNotified().get());
}

代码示例来源:origin: org.jboss.cdi.tck/cdi-tck-impl

@Test
@SpecAssertions({ @SpecAssertion(section = OBSERVER_RESOLUTION, id = "f"), @SpecAssertion(section = EVENT, id = "eda") })
public void testQualifiedAsyncEventIsDeliveredOnlyToAsyncObservers() throws InterruptedException {
  BlockingQueue<Experiment> queue = new LinkedBlockingQueue<>();
  event.select(American.AmericanLiteral.INSTANCE).fireAsync(new ScientificExperiment()).thenAccept(queue::offer);
  Experiment experiment = queue.poll(2, TimeUnit.SECONDS);
  assertEquals(experiment.getUniversities().size(), 3);
  assertTrue(experiment.getUniversities().contains(YaleUniversityObserver.class));
  assertTrue(experiment.getUniversities().contains(StandfordUniversityObserver.class));
  assertTrue(experiment.getUniversities().contains(MassachusettsInstituteObserver.class));
}

代码示例来源:origin: org.jboss.cdi.tck/cdi-tck-impl

@Test
@SpecAssertions({
    @SpecAssertion(section = OBSERVER_METHOD_CONFIGURATOR, id = "bg"),
    @SpecAssertion(section = OBSERVER_METHOD_CONFIGURATOR, id = "bd"),
    @SpecAssertion(section = OBSERVER_METHOD_CONFIGURATOR, id = "bi") })
public void addQualifiersAndSetPriorityAndChangeToAsync() throws InterruptedException {
  Set<ObserverMethod<? super Pear>> pearEventObservers = getCurrentManager()
      .resolveObserverMethods(new Pear(), Any.Literal.INSTANCE, Ripe.RipeLiteral.INSTANCE, Delicious.DeliciousLiteral.INSTANCE);
  assertEquals(pearEventObservers.size(), 1);
  assertEquals(pearEventObservers.iterator().next().getPriority(), ObserverMethod.DEFAULT_PRIORITY + 100);
  assertEquals(pearEventObservers.iterator().next().isAsync(), true);
  assertEquals(pearEventObservers.iterator().next().getObservedQualifiers(),
      Stream.of(Ripe.RipeLiteral.INSTANCE, Delicious.DeliciousLiteral.INSTANCE).collect(
          Collectors.toSet()));
  BlockingQueue<Pear> queue = new LinkedBlockingQueue<>();
  pearEvent.select(Any.Literal.INSTANCE, Ripe.RipeLiteral.INSTANCE, Delicious.DeliciousLiteral.INSTANCE).fireAsync(new Pear()).thenAccept(queue::offer);
  Pear pear = queue.poll(2, TimeUnit.SECONDS);
  assertNotNull(pear);
  assertTrue(FruitObserver.pearObserverNotified.get());
}

代码示例来源:origin: org.jboss.cdi.tck/cdi-tck-impl

@Test
@SpecAssertion(section = Sections.REQUEST_CONTEXT, id="da")
@SpecAssertion(section = Sections.REQUEST_CONTEXT, id="ea")
public void requestContextIsActiveDuringAsyncObserverNotification() throws InterruptedException {
  SeContainerInitializer seContainerInitializer = SeContainerInitializer.newInstance();
  try (SeContainer container = seContainerInitializer
      .initialize()) {
    Event<Object> event = container.getBeanManager().getEvent();
    BlockingQueue<Payload> queue = new LinkedBlockingQueue<>();
    //fire event twice but each event gets new requestContext
    event.select(Payload.class).fireAsync(new Payload()).thenAccept(queue::offer);
    Payload payload = queue.poll(2, TimeUnit.SECONDS);
    event.select(Payload.class).fireAsync(payload).thenAccept(queue::offer);
    payload = queue.poll(2, TimeUnit.SECONDS);
    assertEquals(payload.getI(), 2);
  }
}

代码示例来源:origin: org.microbean/microbean-kubernetes-controller-cdi

stage = broadcaster.fireAsync(resource);
} else {
 stage = broadcaster.fireAsync(resource, this.notificationOptions);

代码示例来源:origin: org.talend.sdk.component/component-server-proxy

final HttpRequestContext requestContext = new HttpRequestContext(lang, placeholderProvider, request);
return onFindByIdEvent
    .fireAsync(new OnFindById(requestContext, id), notificationOptions)
    .thenCompose(event -> event
        .getFormId()
              .collect(toJsonObject());
      return onEditEvent
          .fireAsync(new OnEdit(id, requestContext, jsonb, enrichment, config.getProperties(),
              configurationFormatter.flatten(configuration)), notificationOptions)
          .thenCompose(OnEdit::getCompletionListener)

代码示例来源:origin: org.talend.sdk.component/component-server-proxy

@ApiOperation(value = "Return a form description ( Ui Spec ) of a specific configuration ", response = UiNode.class,
    tags = { "form", "ui spec", "configurations", "datastore", "dataset" }, produces = "application/json",
    responseHeaders = { @ResponseHeader(name = HEADER_TALEND_COMPONENT_SERVER_ERROR,
        description = ERROR_HEADER_DESC, response = Boolean.class) })
@GET
@Path("form/{id}")
public CompletionStage<UiNode> getForm(@PathParam("id") final String id,
    @Context final HttpServletRequest request) {
  final String lang = getLang(request);
  final Function<String, String> placeholderProvider = placeholderProviderFactory.newProvider(request);
  final HttpRequestContext requestContext = new HttpRequestContext(lang, placeholderProvider, request);
  return onFindByIdEvent
      .fireAsync(new OnFindById(requestContext, id), notificationOptions)
      .thenCompose(event -> event
          .getFormId()
          .thenCompose(formId -> toUiSpecAndMetadata(lang, placeholderProvider,
              configurationClient.getDetails(lang, formId, placeholderProvider), false)
                  .thenCompose(uiNode -> event.getProperties().thenApply(props -> {
                    uiNode.getUi().setProperties(props);
                    return uiNode;
                  }))));
}

代码示例来源:origin: org.talend.sdk.component/component-server-proxy

.collect(toJsonObject());
return onPersistEvent
    .fireAsync(new OnPersist(requestContext, jsonb, node.getId(), enrichment,
        node.getProperties(), configurationFormatter.flatten(configuration)),
        notificationOptions)

代码示例来源:origin: org.talend.sdk.component/component-server-proxy

@Override
public CompletionStage<Map<String, String>> resolveConfiguration(final RequestContext context, final String id) {
  final UiSpecContext uiSpecContext = new UiSpecContext(context.language(), context::findPlaceholder);
  return onFindByIdEvent
      .fireAsync(new OnFindById(context, id))
      .thenCompose(byId -> byId
          .getFormId()
          .thenCompose(formId -> configurationClient
              .getAllConfigurations(context.language(), context::findPlaceholder)
              .thenApply(nodes -> configurationService.getFamilyOf(formId, nodes))
              .thenCompose(family -> configurationClient
                  .getDetails(context.language(), formId, context::findPlaceholder)
                  .thenCompose(detail -> configurationService
                      .filterNestedConfigurations(family.getName(), detail, uiSpecContext)))
              .thenCompose(detail -> byId
                  .getProperties()
                  .thenCompose(props -> configurationService
                      .replaceReferences(uiSpecContext, detail, props)))));
}

相关文章