Package org.jboss.errai.bus.server.util

Examples of org.jboss.errai.bus.server.util.LocalContext


      if (BusCommand.Associate.name().equals(commandType)) {
        final String sessionKey = ejObject.get(MessageParts.ConnectionSessionKey.name()).isString().stringValue();

        // has this client already attempted a connection, and is in a wait verify state
        if (sessionKey != null && (session = svc.getBus().getSessionBySessionId(sessionKey)) != null) {
          final LocalContext localContext = LocalContext.get(session);

          if (localContext.hasAttribute(SESSION_ATTR_WS_STATUS) &&
              WEBSOCKET_ACTIVE.equals(localContext.getAttribute(String.class, SESSION_ATTR_WS_STATUS))) {

            final MessageQueue queueBySession = svc.getBus().getQueueBySession(sessionKey);
            queueBySession.setDeliveryHandler(DirectDeliveryHandler.createFor(new NettyQueueChannel(ctx.getChannel())));

            // open the channel
            activeChannels.put(ctx.getChannel(), session);
            ctx.getChannel().getCloseFuture().addListener(new ChannelFutureListener() {
              @Override
              public void operationComplete(final ChannelFuture channelFuture) throws Exception {
                activeChannels.remove(ctx.getChannel());
                queueBySession.setDeliveryHandlerToDefault();
              }
            });

            // set the session queue into direct channel mode.

            localContext.removeAttribute(SESSION_ATTR_WS_STATUS);

//            service.schedule(new Runnable() {
//              @Override
//              public void run() {
//                ctx.getChannel().close();
//              }
//            }, 5, TimeUnit.SECONDS);

            return;
          }

          // check the activation key matches.
          final EJString activationKey = ejObject.get(MessageParts.WebSocketToken.name()).isString();
          if (activationKey == null || !WebSocketTokenManager.verifyOneTimeToken(session, activationKey.stringValue())) {
            // nope. go away!
            sendMessage(ctx, getFailedNegotiation("bad negotiation key"));
          }
          else {
            // the key matches. now we send the reverse challenge to prove this client is actually
            // already talking to the bus over the COMET channel.
            final String reverseToken = WebSocketTokenManager.getNewOneTimeToken(session);
            localContext.setAttribute(MessageParts.WebSocketToken.name(), reverseToken);
            localContext.setAttribute(SESSION_ATTR_WS_STATUS, WEBSOCKET_AWAIT_ACTIVATION);

            // send the challenge.
            sendMessage(ctx, getReverseChallenge(reverseToken));
            return;
          }
View Full Code Here


          case WebsocketChannelVerify:
            if (message.hasPart(MessageParts.WebSocketToken)) {
              if (verifyOneTimeToken(session, message.get(String.class, MessageParts.WebSocketToken))) {
                final String reconnectionToken = getNewOneTimeToken(session);

                final LocalContext localContext = LocalContext.get(session);

                localContext.setAttribute(WebSocketServerHandler.SESSION_ATTR_WS_STATUS,
                    WebSocketServerHandler.WEBSOCKET_ACTIVE);

                createConversation(message)
                    .toSubject(BuiltInServices.ClientBus.name())
                    .command(BusCommand.WebsocketChannelOpen)
View Full Code Here

          case WebsocketChannelVerify:
            if (message.hasPart(MessageParts.WebSocketToken)) {
              if (verifyOneTimeToken(session, message.get(String.class, MessageParts.WebSocketToken))) {
                final String reconnectionToken = getNewOneTimeToken(session);

                final LocalContext localContext = LocalContext.get(session);

                localContext.setAttribute(WebSocketServerHandler.SESSION_ATTR_WS_STATUS,
                    WebSocketServerHandler.WEBSOCKET_ACTIVE);

                createConversation(message)
                    .toSubject(BuiltInServices.ClientBus.name())
                    .command(BusCommand.WebsocketChannelOpen)
View Full Code Here

  private final static Pattern StartMatcher = Pattern.compile("^Start[0-9]{1}$");
  private final static Pattern StopMatcher = Pattern.compile("^Stop[0-9]{1}$");

  public void callback(Message message) {
    LocalContext ctx = LocalContext.get(message);

    String commandType = message.getCommandType();
    String taskName = getTaskName(commandType);

    if (StartMatcher.matcher(commandType).matches()) {
      AsyncTask task = ctx.getAttribute(AsyncTask.class, taskName);

      // there's no task running in this context.
      if (task == null) {
        ResourceProvider<Double> randomNumberProvider = new ResourceProvider<Double>() {
          public Double get() {
            return Math.random();
          }
        };

        task = MessageBuilder.createConversation(message)
            .subjectProvided()
            .withProvided("Data", randomNumberProvider)
            .noErrorHandling()
            .replyRepeating(TimeUnit.MILLISECONDS, 50);

        System.out.println("New task started: " + taskName);
        ctx.setAttribute(taskName, task);
      }
      else {
        System.out.println("Task already started: " + taskName);
      }
    }
    else if (StopMatcher.matcher(commandType).matches()) {
      AsyncTask task = ctx.getAttribute(AsyncTask.class, taskName);

      if (task == null) {
        System.out.println("Nothing to stop: " + taskName);
      }
      else {
        System.out.println("Stopping: " + taskName);
        task.cancel(true);
        ctx.removeAttribute(taskName);
      }
    }
  }
View Full Code Here

      return;

    try {
      ScopeUtil.associateRequestContext(message);

      final LocalContext localContext = LocalContext.get(message);

      switch (CDICommands.valueOf(message.getCommandType())) {
        case RemoteSubscribe:
          if (afterBeanDiscovery != null) {
            final String signature = getSignatureFromMessage(message);
            final String typeName = message.get(String.class, CDIProtocol.BeanType);
            final Class<?> type = Class.forName(typeName);
            final Set<String> annotationTypes = message.get(Set.class, CDIProtocol.Qualifiers);

            if (!activeObserverSignatures.contains(signature)) {

              if (type == null || !EnvUtil.isPortableType(type)) {
                log.warn("client tried to register a non-portable type: " + type);
                return;
              }

              final DynamicEventObserverMethod observerMethod
                  = new DynamicEventObserverMethod(eventRoutingTable, messagebus, type, annotationTypes);

              if (!activeObserverMethods.contains(observerMethod)) {
                afterBeanDiscovery.addObserverMethod(observerMethod);
                int clearCount = clearBeanManagerObserverCaches(beanManager);
                log.debug("Cleared observer resolution caches of " + clearCount + " bean managers");
                activeObserverMethods.add(observerMethod);
              }

              activeObserverSignatures.add(signature);
            }

            eventRoutingTable.activateRoute(typeName, annotationTypes, message.getResource(QueueSession.class, "Session"));
          }
          break;

        case RemoteUnsubscribe:
          final String typeName = message.get(String.class, CDIProtocol.BeanType);
          final Set<String> annotationTypes = message.get(Set.class, CDIProtocol.Qualifiers);

          eventRoutingTable.deactivateRoute(typeName, annotationTypes, message.getResource(QueueSession.class, "Session"));
          break;

        case CDIEvent:
          if (!isRoutable(localContext, message)) {
            return;
          }

          final Object o = message.get(Object.class, CDIProtocol.BeanReference);
          EventConversationContext.activate(o, CDIServerUtil.getSession(message));
          try {
            @SuppressWarnings("unchecked")
            final Set<String> qualifierNames = message.get(Set.class, CDIProtocol.Qualifiers);
            List<Annotation> qualifiers = null;
            if (qualifierNames != null) {
              for (final String qualifierName : qualifierNames) {
                if (qualifiers == null) {
                  qualifiers = new ArrayList<Annotation>();
                }
                final Annotation qualifier = allQualifiers.get(qualifierName);
                if (qualifier != null) {
                  qualifiers.add(qualifier);
                }
              }
            }

            if (qualifiers != null) {
              beanManager.fireEvent(o, qualifiers.toArray(new Annotation[qualifiers.size()]));
            }
            else {
              beanManager.fireEvent(o);
            }
          }
          finally {
            EventConversationContext.deactivate();
          }

          break;

        case AttachRemote:
          if (observedEvents.size() > 0) {
            MessageBuilder.createConversation(message).toSubject(CDI.CLIENT_DISPATCHER_SUBJECT)
                .command(CDICommands.AttachRemote)
                .with(MessageParts.RemoteServices, getEventTypes()).done().reply();
          }
          else {
            MessageBuilder.createConversation(message).toSubject(CDI.CLIENT_DISPATCHER_SUBJECT)
                .command(CDICommands.AttachRemote)
                .with(MessageParts.RemoteServices, "").done().reply();
          }

          localContext.setAttribute(CDI_EVENT_CHANNEL_OPEN, "1");
          break;

        default:
          throw new IllegalArgumentException("Unknown command type " + message.getCommandType());
      }
View Full Code Here

      return;

    try {
      ScopeUtil.associateRequestContext(message);

      final LocalContext localContext = LocalContext.get(message);

      switch (CDICommands.valueOf(message.getCommandType())) {
        case RemoteSubscribe:
          if (afterBeanDiscovery != null) {

            final String signature = getSignatureFromMessage(message);
            final String typeName = message.get(String.class, CDIProtocol.BeanType);
            final Class<?> type = Class.forName(typeName);
            final Set<String> annotationTypes = message.get(Set.class, CDIProtocol.Qualifiers);

            if (!activeObserverSignatures.contains(signature)) {

              if (type == null || !EnvUtil.isPortableType(type)) {
                log.warn("client tried to register a non-portable type: " + type);
                return;
              }

              final DynamicEventObserverMethod observerMethod
                  = new DynamicEventObserverMethod(eventRoutingTable, messagebus, type, annotationTypes);

              if (!activeObserverMethods.contains(observerMethod)) {
                afterBeanDiscovery.addObserverMethod(observerMethod);
                activeObserverMethods.add(observerMethod);
              }

              activeObserverSignatures.add(signature);
            }

            eventRoutingTable.activateRoute(typeName, annotationTypes, message.getResource(QueueSession.class, "Session"));
          }
          break;

        case RemoteUnsubscribe:
          final String typeName = message.get(String.class, CDIProtocol.BeanType);
          final Set<String> annotationTypes = message.get(Set.class, CDIProtocol.Qualifiers);

          eventRoutingTable.deactivateRoute(typeName, annotationTypes, message.getResource(QueueSession.class, "Session"));
          break;

        case CDIEvent:
          if (!isRoutable(localContext, message)) {
            return;
          }

          final Object o = message.get(Object.class, CDIProtocol.BeanReference);
          EventConversationContext.activate(o, CDIServerUtil.getSession(message));
          try {
            @SuppressWarnings("unchecked")
            final Set<String> qualifierNames = message.get(Set.class, CDIProtocol.Qualifiers);
            List<Annotation> qualifiers = null;
            if (qualifierNames != null) {
              for (final String qualifierName : qualifierNames) {
                if (qualifiers == null) {
                  qualifiers = new ArrayList<Annotation>();
                }
                final Annotation qualifier = allQualifiers.get(qualifierName);
                if (qualifier != null) {
                  qualifiers.add(qualifier);
                }
              }
            }

            if (qualifiers != null) {
              beanManager.fireEvent(o, qualifiers.toArray(new Annotation[qualifiers.size()]));
            }
            else {
              beanManager.fireEvent(o);
            }
          }
          finally {
            EventConversationContext.deactivate();
          }

          break;

        case AttachRemote:
          MessageBuilder.createConversation(message).toSubject(CDI.CLIENT_DISPATCHER_SUBJECT)
              .command(BusCommands.RemoteSubscribe)
              .with(MessageParts.Value, observedEvents.toArray(new String[observedEvents.size()])).done().reply();

          localContext.setAttribute(CDI_EVENT_CHANNEL_OPEN, "1");
          break;

        default:
          throw new IllegalArgumentException("Unknown command type " + message.getCommandType());
      }
View Full Code Here

            case WebsocketChannelVerify:
              if (message.hasPart(MessageParts.WebSocketToken)) {
                if (verifyOneTimeToken(session, message.get(String.class, MessageParts.WebSocketToken))) {

                  LocalContext localContext = LocalContext.get(session);

                  localContext.setAttribute(WebSocketServerHandler.SESSION_ATTR_WS_STATUS,
                          WebSocketServerHandler.WEBSOCKET_ACTIVE);

                  createConversation(message)
                          .toSubject(BuiltInServices.ClientBus.name())
                          .command(BusCommands.WebsocketChannelOpen)
View Full Code Here

      if (BusCommands.ConnectToQueue.name().equals(commandType)) {
        String sessionKey = val.get(MessageParts.ConnectionSessionKey.name()).isString().stringValue();

        // has this client already attempted a connection, and is in a wait verify state
        if (sessionKey != null && (session = svc.getBus().getSessionBySessionId(sessionKey)) != null) {
          LocalContext localContext = LocalContext.get(session);

          if (localContext.hasAttribute(SESSION_ATTR_WS_STATUS) &&
                  WEBSOCKET_ACTIVE.equals(localContext.getAttribute(String.class, SESSION_ATTR_WS_STATUS))) {

            // open the channel
            activeChannels.put(ctx.getChannel(), session);

            // set the session queue into direct channel mode.
            svc.getBus().getQueueBySession(sessionKey).setDirectSocketChannel(new NettyQueueChannel(ctx.getChannel()));

            // remove the web socket token so it cannot be re-used for authentication.
            localContext.removeAttribute(MessageParts.WebSocketToken.name());
            localContext.removeAttribute(SESSION_ATTR_WS_STATUS);

            return;
          }

          // check the activation key matches.
          EJString activationKey = val.get(MessageParts.WebSocketToken.name()).isString();
          if (activationKey == null || !WebSocketTokenManager.verifyOneTimeToken(session, activationKey.stringValue())) {
            // nope. go away!
            sendMessage(ctx, getFailedNegotiation("bad negotiation key"));
          }
          else {
            // the key matches. now we send the reverse challenge to prove this client is actually
            // already talking to the bus over the COMET channel.
            String reverseToken = WebSocketTokenManager.getNewOneTimeToken(session);
            localContext.setAttribute(MessageParts.WebSocketToken.name(), reverseToken);
            localContext.setAttribute(SESSION_ATTR_WS_STATUS, WEBSOCKET_AWAIT_ACTIVATION);

            // send the challenge.
            sendMessage(ctx, getReverseChallenge(reverseToken));
            return;
          }
View Full Code Here

  @Override
  protected void onSocketClosed(WebSocket socket) throws IOException {
    final QueueSession session = sessionProvider.getSession(socket.getHttpSession(),
            socket.getSocketID());

    final LocalContext localSessionContext = LocalContext.get(session);
    QueueSession cometSession = localSessionContext.getAttribute(QueueSession.class, WEBSOCKET_SESSION_ALIAS);
    service.getBus().getQueue(cometSession).setDirectSocketChannel(null);
  }
View Full Code Here

    if (text.length() == 0) return;

    @SuppressWarnings("unchecked") EJObject val = JSONDecoder.decode(text).isObject();

    final LocalContext localSessionContext = LocalContext.get(session);

    QueueSession cometSession = localSessionContext.getAttribute(QueueSession.class, WEBSOCKET_SESSION_ALIAS);

    // this is not an active channel.
    if (cometSession == null) {
      String commandType = val.get(MessageParts.CommandType.name()).isString().stringValue();

      // this client apparently wants to connect.
      if (BusCommands.ConnectToQueue.name().equals(commandType)) {
        String sessionKey = val.get(MessageParts.ConnectionSessionKey.name()).isString().stringValue();

        // has this client already attempted a connection, and is in a wait verify state
        if (sessionKey != null && (cometSession = service.getBus().getSessionBySessionId(sessionKey)) != null) {
          LocalContext localCometSession = LocalContext.get(cometSession);

          if (localCometSession.hasAttribute(WebSocketServerHandler.SESSION_ATTR_WS_STATUS) &&
                  WebSocketServerHandler.WEBSOCKET_ACTIVE.equals(localCometSession.getAttribute(String.class, WebSocketServerHandler.SESSION_ATTR_WS_STATUS))) {

            // set the session queue into direct channel mode.
            service.getBus().getQueue(cometSession).setDirectSocketChannel(new SimpleEventChannelWrapped(socket));

            localSessionContext.setAttribute(WEBSOCKET_SESSION_ALIAS, cometSession);
            cometSession.removeAttribute(WebSocketServerHandler.SESSION_ATTR_WS_STATUS);

            return;
          }

          // check the activation key matches.
          EJString activationKey = val.get(MessageParts.WebSocketToken.name()).isString();
          if (activationKey == null || !WebSocketTokenManager.verifyOneTimeToken(cometSession, activationKey.stringValue())) {

            // nope. go away!
            sendMessage(new SimpleEventChannelWrapped(socket), getFailedNegotiation("bad negotiation key"));
          }
          else {
            // the key matches. now we send the reverse challenge to prove this client is actually
            // already talking to the bus over the COMET channel.
            String reverseToken = WebSocketTokenManager.getNewOneTimeToken(cometSession);
            localCometSession.setAttribute(WebSocketServerHandler.SESSION_ATTR_WS_STATUS, WebSocketServerHandler.WEBSOCKET_AWAIT_ACTIVATION);

            // send the challenge.
            sendMessage(new SimpleEventChannelWrapped(socket), getReverseChallenge(reverseToken));
            return;
          }
View Full Code Here

TOP

Related Classes of org.jboss.errai.bus.server.util.LocalContext

Copyright © 2018 www.massapicom. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.