Example #1
0
  public void engageOffer(String client, String subject, ShoutboxCallback callback) {
    this.delegate = callback;

    // shout box example
    bus.subscribe(
        subject,
        new MessageCallback() {
          public void callback(Message message) {
            System.out.println("Shoutbox client: " + message.getCommandType());
            switch (ShoutboxCmd.valueOf(message.getCommandType())) {
              case SUBMIT_OFFER: // provider enters the game
                delegate.offerSubmitted(message.get(String.class, ShoutboxCmdParts.PROVIDER));
                break;
              case RETRACT_OFFER:
                delegate.offerRetracted(message.get(String.class, ShoutboxCmdParts.PROVIDER));
            }
          }
        });

    // engage an offer right away
    MessageBuilder.createMessage()
        .toSubject(ShoutboxModule.INBOX)
        .command(ShoutboxCmd.ENGAGE_OFFER)
        .with(ShoutboxCmdParts.SUBJECT, subject)
        .with(ShoutboxCmdParts.CLIENT, client)
        .noErrorHandling()
        .sendNowWith(bus);
  }
Example #2
0
  private void createRPCScaffolding(
      final Class remoteIface, final MessageBus bus, final BeanManager beanManager) {
    final Map<String, MessageCallback> epts = new HashMap<String, MessageCallback>();

    // beware of classloading issues. better reflect on the actual instance
    for (final Method method : remoteIface.getMethods()) {
      if (RebindUtils.isMethodInInterface(remoteIface, method)) {

        epts.put(
            RebindUtils.createCallSignature(remoteIface, method),
            new ConversationalEndpointCallback(
                new ServiceInstanceProvider() {
                  @SuppressWarnings("unchecked")
                  @Override
                  public Object get(final Message message) {
                    if (message.hasPart(CDIProtocol.Qualifiers)) {
                      final List<String> quals = message.get(List.class, CDIProtocol.Qualifiers);
                      final Annotation[] qualAnnos = new Annotation[quals.size()];
                      for (int i = 0; i < quals.size(); i++) {
                        qualAnnos[i] = beanQualifiers.get(quals.get(i));
                      }
                      return lookupRPCBean(beanManager, remoteIface, qualAnnos);
                    } else {
                      return lookupRPCBean(beanManager, remoteIface, null);
                    }
                  }
                },
                method,
                bus));
      }
    }

    final RemoteServiceCallback delegate = new RemoteServiceCallback(epts);
    bus.subscribe(
        remoteIface.getName() + ":RPC",
        new MessageCallback() {
          @Override
          public void callback(final Message message) {
            delegate.callback(message);
          }
        });

    // note: this method just exists because we want AbstractRemoteCallBuilder to be package
    // private.
    DefaultRemoteCallBuilder.setProxyFactory(
        Assert.notNull(
            new ProxyFactory() {
              @Override
              public <T> T getRemoteProxy(final Class<T> proxyType) {
                throw new RuntimeException(
                    "There is not yet an available Errai RPC implementation for the server-side environment.");
              }
            }));
  }
Example #3
0
    @Override
    public void run() {
      if (System.currentTimeMillis() > expiryTime) {
        scheduledExecutorService.shutdown();
        throw new RuntimeException(
            "failed to discover beans: " + managedTypes.getServiceEndpoints());
      }

      if (registered.isEmpty()) {
        scheduledExecutorService.shutdown();
        log.info("all services registered successfully");
        return;
      }

      for (final AnnotatedType<?> type : managedTypes.getServiceEndpoints()) {
        if (!registered.contains(type) || beanManager.getBeans(type.getJavaClass()).size() == 0) {
          continue;
        }

        final MessageCallback callback =
            (MessageCallback) CDIServerUtil.lookupBean(beanManager, type.getJavaClass());

        registered.remove(type);

        // Discriminate on @Command
        final Map<String, Method> commandPoints = new HashMap<String, Method>();
        for (final AnnotatedMethod method : type.getMethods()) {
          if (method.isAnnotationPresent(Command.class)) {
            final Command command = method.getAnnotation(Command.class);
            for (String cmdName : command.value()) {
              if (cmdName.equals("")) cmdName = method.getJavaMember().getName();
              commandPoints.put(cmdName, method.getJavaMember());
            }
          }
        }

        final String subjectName = CDIServerUtil.resolveServiceName(type.getJavaClass());

        if (commandPoints.isEmpty()) {
          bus.subscribe(subjectName, callback);
        } else {
          bus.subscribeLocal(
              subjectName, new CommandBindingsCallback(commandPoints, callback, bus));
        }
      }
    }
Example #4
0
  private void subscribeServices(final BeanManager beanManager, final MessageBus bus) {
    for (final Map.Entry<AnnotatedType, List<AnnotatedMethod>> entry :
        managedTypes.getServiceMethods().entrySet()) {
      final Class<?> type = entry.getKey().getJavaClass();

      for (final AnnotatedMethod method : entry.getValue()) {
        final Service svc = method.getAnnotation(Service.class);
        final String svcName =
            svc.value().equals("") ? method.getJavaMember().getName() : svc.value();

        final Method callMethod = method.getJavaMember();

        bus.subscribe(
            svcName,
            new MessageCallback() {

              @Override
              public void callback(final Message message) {
                final Object targetBean = CDIServerUtil.lookupBean(beanManager, type);

                try {
                  callMethod.invoke(targetBean, message);
                } catch (Exception e) {
                  ErrorHelper.sendClientError(bus, message, "Error dispatching service", e);
                }
              }
            });
      }
    }

    /**
     * Due to the lack of contract in CDI guaranteeing when beans will be available, we use an
     * executor to search for the beans every 100ms until it finds them. Or, after a 25 seconds,
     * blow up if they don't become available.
     */
    final ScheduledExecutorService startupScheduler = Executors.newScheduledThreadPool(1);
    startupScheduler.scheduleAtFixedRate(
        new StartupCallback(beanManager, bus, startupScheduler, 25), 0, 100, TimeUnit.MILLISECONDS);

    for (final Class<?> remoteInterfaceType : managedTypes.getRemoteInterfaces()) {
      createRPCScaffolding(remoteInterfaceType, bus, beanManager);
    }
  }
Example #5
0
  @SuppressWarnings({"UnusedDeclaration", "CdiInjectionPointsInspection"})
  public void afterBeanDiscovery(@Observes final AfterBeanDiscovery abd, final BeanManager bm) {
    final ErraiService service = ErraiServiceSingleton.getService();
    final MessageBus bus = service.getBus();
    final EventRoutingTable eventRoutingTable = new EventRoutingTable();

    if (bus.isSubscribed(CDI.SERVER_DISPATCHER_SUBJECT)) {
      return;
    }

    final byte[] randBytes = new byte[32];
    final Random random = new Random(System.currentTimeMillis());

    random.nextBytes(randBytes);

    abd.addBean(new ErraiServiceBean(bm, SecureHashUtil.hashToHexString(randBytes)));

    for (final MessageSender ms : messageSenders) {
      abd.addBean(new SenderBean(ms.getSenderType(), ms.getQualifiers(), bus));
    }

    // Errai bus injection
    abd.addBean(new MessageBusBean(bus));

    // Support to inject the request dispatcher.
    abd.addBean(new RequestDispatcherMetaData(bm, service.getDispatcher()));

    // Register observers
    abd.addObserverMethod(new ShutdownEventObserver(managedTypes, bus));

    // subscribe service and rpc endpoints
    subscribeServices(bm, bus);

    final EventDispatcher eventDispatcher =
        new EventDispatcher(bm, eventRoutingTable, bus, observableEvents, eventQualifiers, abd);

    // subscribe event dispatcher
    bus.subscribe(CDI.SERVER_DISPATCHER_SUBJECT, eventDispatcher);
  }
Example #6
0
  public static void setInputTreeToSection(
      final DispatchAsync dispatcher,
      final LangConstants lang,
      final EventBus eventBus,
      SectionStack sectionStack,
      final PlaceManager placeManager,
      final MessageBus messageBus,
      boolean force) {

    SectionStackSection section1 = new SectionStackSection();
    section1.setTitle(lang.inputQueue());
    String isInputSection = sectionStack.getSection(0).getAttribute(Constants.SECTION_INPUT_ID);
    boolean notContains = isInputSection == null || !"yes".equals(isInputSection);
    if (notContains || force) {
      if (!notContains) {
        sectionStack.collapseSection(0);
        sectionStack.removeSection(0);
      }
      if (inputQueueTree == null) {
        inputQueueTree = new InputQueueTree(dispatcher, lang, eventBus);
        inputQueueTree
            .getCreateMenuItem()
            .addClickHandler(
                new com.smartgwt.client.widgets.menu.events.ClickHandler() {

                  @Override
                  public void onClick(final MenuItemClickEvent event) {
                    String msg = event.getMenu().getEmptyMessage();
                    String model = msg.substring(0, msg.indexOf("/"));
                    String path = msg.substring(msg.indexOf("/") + 1);
                    String id = path;
                    if (path.contains("/")) {
                      id = path.substring(0, path.indexOf("/"));
                    }

                    placeManager.revealRelativePlace(
                        new PlaceRequest(NameTokens.FIND_METADATA)
                            .with(Constants.ATTR_MODEL, model)
                            .with(Constants.URL_PARAM_SYSNO, id)
                            .with(Constants.URL_PARAM_PATH, path));
                  }
                });

        messageBus.subscribe(
            "InputQueueBroadcastReceiver",
            new MessageCallback() {
              @Override
              public void callback(Message message) {
                String inputItem = message.get(String.class, "ingested");
                for (ListGridRecord record : inputQueueTree.getRecords()) {
                  if (record.getAttribute(Constants.ATTR_ID).equals(inputItem)) {
                    record.setAttribute(Constants.ATTR_INGEST_INFO, true);
                    inputQueueTree.redraw();
                  }
                }
              }
            });
      }

      section1.setItems(inputQueueTree);
      section1.setControls(getRefreshButton(lang, eventBus, dispatcher));
      section1.setResizeable(true);
      section1.setExpanded(true);
      sectionStack.addSection(section1, 0);
      section1.setAttribute(Constants.SECTION_INPUT_ID, "yes");
    }
  }