io.vertx.ext.web.handler.sockjs.SockJSSocket Java Examples

The following examples show how to use io.vertx.ext.web.handler.sockjs.SockJSSocket. 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: SockJSSession.java    From vertx-web with Apache License 2.0 6 votes vote down vote up
SockJSSession(Vertx vertx, LocalMap<String, SockJSSession> sessions, RoutingContext rc, String id, long timeout, long heartbeatInterval,
              Handler<SockJSSocket> sockHandler) {
  super(vertx, rc.session(), rc.user());
  this.sessions = sessions;
  this.id = id;
  this.timeout = timeout;
  this.sockHandler = sockHandler;
  context = vertx.getOrCreateContext();
  pendingReads = new InboundBuffer<>(context);

  // Start a heartbeat

  heartbeatID = vertx.setPeriodic(heartbeatInterval, tid -> {
    if (listener != null) {
      listener.sendFrame("h", null);
    }
  });
}
 
Example #2
Source File: SockJSPushHandler.java    From vertx-vaadin with MIT License 6 votes vote down vote up
private void onConnect(SockJSSocket sockJSSocket) {
    RoutingContext routingContext = CurrentInstance.get(RoutingContext.class);

    String uuid = sockJSSocket.writeHandlerID();
    connectedSocketsLocalMap.put(uuid, sockJSSocket);
    PushSocket socket = new PushSocketImpl(sockJSSocket);

    initSocket(sockJSSocket, routingContext, socket);

    // Send an ACK
    socket.send("ACK-CONN|" + uuid);

    sessionHandler.handle(new SockJSRoutingContext(routingContext, rc ->
        callWithUi(new PushEvent(socket, routingContext, null), establishCallback)
    ));
}
 
Example #3
Source File: SockJSVisitor.java    From nubes with Apache License 2.0 6 votes vote down vote up
private Object[] getParamValues(Method method, SockJSSocket socket, Buffer msg) {
  final Vertx vertx = config.getVertx();
  List<Object> paramInstances = new ArrayList<>();
  for (Class<?> parameterClass : method.getParameterTypes()) {
    if (parameterClass.equals(SockJSSocket.class)) {
      paramInstances.add(socket);
    } else if (Buffer.class.isAssignableFrom(parameterClass)) {
      paramInstances.add(msg);
    } else if (parameterClass.equals(EventBus.class)) {
      paramInstances.add(vertx.eventBus());
    } else if (parameterClass.equals(Vertx.class)) {
      paramInstances.add(vertx);
    }
  }
  return paramInstances.toArray();
}
 
Example #4
Source File: SockJSPushHandler.java    From vertx-vaadin with MIT License 6 votes vote down vote up
private void onConnect(SockJSSocket sockJSSocket) {
    RoutingContext routingContext = CurrentInstance.get(RoutingContext.class);

    String uuid = sockJSSocket.writeHandlerID();
    connectedSocketsLocalMap.put(uuid, sockJSSocket);
    PushSocket socket = new PushSocketImpl(sockJSSocket);

    initSocket(sockJSSocket, routingContext, socket);

    // Send an ACK
    socket.send("ACK-CONN|" + uuid);

    sessionHandler.handle(new SockJSRoutingContext(routingContext, rc ->
        callWithUi(new PushEvent(socket, routingContext, null), establishCallback)
    ));
}
 
Example #5
Source File: SockJSTermHandlerImpl.java    From vertx-shell with Apache License 2.0 6 votes vote down vote up
@Override
public void handle(SockJSSocket socket) {
  if (termHandler != null) {
    SockJSTtyConnection conn = new SockJSTtyConnection(charset, vertx.getOrCreateContext(), socket);
    socket.handler(buf -> conn.writeToDecoder(buf.toString()));
    socket.endHandler(v -> {
      Consumer<Void> closeHandler = conn.getCloseHandler();
      if (closeHandler != null) {
        closeHandler.accept(null);
      }
    });
    termHandler.handle(new TermImpl(vertx, keymap, conn));
  } else {
    socket.close();
  }
}
 
Example #6
Source File: SockJSVisitor.java    From nubes with Apache License 2.0 5 votes vote down vote up
private void tryToInvoke(Object instance, Method method, SockJSSocket socket, Buffer msg) {
  try {
    method.invoke(instance, getParamValues(method, socket, msg));
  } catch (Exception e) {
    LOG.error("Error while handling websocket", e);
    socket.close();
  }
}
 
Example #7
Source File: HtmlFileTransport.java    From vertx-web with Apache License 2.0 5 votes vote down vote up
HtmlFileTransport(Vertx vertx, Router router, LocalMap<String, SockJSSession> sessions, SockJSHandlerOptions options,
                  Handler<SockJSSocket> sockHandler) {
  super(vertx, sessions, options);
  String htmlFileRE = COMMON_PATH_ELEMENT_RE + "htmlfile.*";

  router.getWithRegex(htmlFileRE).handler(rc -> {
    if (log.isTraceEnabled()) log.trace("HtmlFile, get: " + rc.request().uri());
    String callback = rc.request().getParam("callback");
    if (callback == null) {
      callback = rc.request().getParam("c");
      if (callback == null) {
        rc.response().setStatusCode(500).end("\"callback\" parameter required\n");
        return;
      }
    }

    if (CALLBACK_VALIDATION.matcher(callback).find()) {
      rc.response().setStatusCode(500);
      rc.response().end("invalid \"callback\" parameter\n");
      return;
    }

    HttpServerRequest req = rc.request();
    String sessionID = req.params().get("param0");
    SockJSSession session = getSession(rc, options.getSessionTimeout(), options.getHeartbeatInterval(), sessionID, sockHandler);
    session.register(req, new HtmlFileListener(options.getMaxBytesStreaming(), rc, callback, session));
  });
}
 
Example #8
Source File: RawWebSocketTransport.java    From vertx-web with Apache License 2.0 5 votes vote down vote up
RawWebSocketTransport(Vertx vertx, Router router,
                      Handler<SockJSSocket> sockHandler) {

  String wsRE = "/websocket";

  router.get(wsRE).handler(rc -> {
    ServerWebSocket ws = rc.request().upgrade();
    SockJSSocket sock = new RawWSSockJSSocket(vertx, rc.session(), rc.user(), ws);
    sockHandler.handle(sock);
  });

  router.get(wsRE).handler(rc -> rc.response().setStatusCode(400).end("Can \"Upgrade\" only to \"WebSocket\"."));

  router.get(wsRE).handler(rc -> rc.response().putHeader(HttpHeaders.ALLOW, "GET").setStatusCode(405).end());
}
 
Example #9
Source File: XhrTransport.java    From vertx-web with Apache License 2.0 5 votes vote down vote up
private void registerHandler(Router router, Handler<SockJSSocket> sockHandler, String re,
                             boolean streaming, SockJSHandlerOptions options) {
  router.postWithRegex(re).handler(rc -> {
    if (log.isTraceEnabled()) log.trace("XHR, post, " + rc.request().uri());
    setNoCacheHeaders(rc);
    String sessionID = rc.request().getParam("param0");
    SockJSSession session = getSession(rc, options.getSessionTimeout(), options.getHeartbeatInterval(), sessionID, sockHandler);
    HttpServerRequest req = rc.request();
    session.register(req, streaming? new XhrStreamingListener(options.getMaxBytesStreaming(), rc, session) : new XhrPollingListener(rc, session));
  });
}
 
Example #10
Source File: XhrTransport.java    From vertx-web with Apache License 2.0 5 votes vote down vote up
XhrTransport(Vertx vertx, Router router, LocalMap<String, SockJSSession> sessions, SockJSHandlerOptions options,
             Handler<SockJSSocket> sockHandler) {

  super(vertx, sessions, options);

  String xhrBase = COMMON_PATH_ELEMENT_RE;
  String xhrRE = xhrBase + "xhr";
  String xhrStreamRE = xhrBase + "xhr_streaming";

  Handler<RoutingContext> xhrOptionsHandler = createCORSOptionsHandler(options, "OPTIONS, POST");

  router.optionsWithRegex(xhrRE).handler(xhrOptionsHandler);
  router.optionsWithRegex(xhrStreamRE).handler(xhrOptionsHandler);

  registerHandler(router, sockHandler, xhrRE, false, options);
  registerHandler(router, sockHandler, xhrStreamRE, true, options);

  String xhrSendRE = COMMON_PATH_ELEMENT_RE + "xhr_send";

  router.optionsWithRegex(xhrSendRE).handler(xhrOptionsHandler);

  router.postWithRegex(xhrSendRE).handler(rc -> {
    if (log.isTraceEnabled()) log.trace("XHR send, post, " + rc.request().uri());
    String sessionID = rc.request().getParam("param0");
    final SockJSSession session = sessions.get(sessionID);
    if (session != null && !session.isClosed()) {
      handleSend(rc, session);
    } else {
      rc.response().setStatusCode(404);
      setJSESSIONID(options, rc);
      rc.response().end();
    }
  });
}
 
Example #11
Source File: EventSourceTransport.java    From vertx-web with Apache License 2.0 5 votes vote down vote up
EventSourceTransport(Vertx vertx, Router router, LocalMap<String, SockJSSession> sessions, SockJSHandlerOptions options,
                     Handler<SockJSSocket> sockHandler) {
  super(vertx, sessions, options);

  String eventSourceRE = COMMON_PATH_ELEMENT_RE + "eventsource";

  router.getWithRegex(eventSourceRE).handler(rc -> {
    if (log.isTraceEnabled()) log.trace("EventSource transport, get: " + rc.request().uri());
    String sessionID = rc.request().getParam("param0");
    SockJSSession session = getSession(rc, options.getSessionTimeout(), options.getHeartbeatInterval(), sessionID, sockHandler);
    HttpServerRequest req = rc.request();
    session.register(req, new EventSourceListener(options.getMaxBytesStreaming(), rc, session));
  });
}
 
Example #12
Source File: WebSocketTransport.java    From vertx-web with Apache License 2.0 5 votes vote down vote up
WebSocketTransport(Vertx vertx,
                   Router router, LocalMap<String, SockJSSession> sessions,
                   SockJSHandlerOptions options,
                   Handler<SockJSSocket> sockHandler) {
  super(vertx, sessions, options);
  String wsRE = COMMON_PATH_ELEMENT_RE + "websocket";

  router.getWithRegex(wsRE).handler(rc -> {
    HttpServerRequest req = rc.request();
    String connectionHeader = req.headers().get(io.vertx.core.http.HttpHeaders.CONNECTION);
    if (connectionHeader == null || !connectionHeader.toLowerCase().contains("upgrade")) {
      rc.response().setStatusCode(400);
      rc.response().end("Can \"Upgrade\" only to \"WebSocket\".");
    } else {
      ServerWebSocket ws = rc.request().upgrade();
      if (log.isTraceEnabled()) log.trace("WS, handler");
      SockJSSession session = new SockJSSession(vertx, sessions, rc, options.getHeartbeatInterval(), sockHandler);
      session.register(req, new WebSocketListener(ws, session));
    }
  });

  router.getWithRegex(wsRE).handler(rc -> {
    if (log.isTraceEnabled()) log.trace("WS, get: " + rc.request().uri());
    rc.response().setStatusCode(400);
    rc.response().end("Can \"Upgrade\" only to \"WebSocket\".");
  });

  router.routeWithRegex(wsRE).handler(rc -> {
    if (log.isTraceEnabled()) log.trace("WS, all: " + rc.request().uri());
    rc.response().putHeader(HttpHeaders.ALLOW, "GET").setStatusCode(405).end();
  });
}
 
Example #13
Source File: ServiceHandler.java    From Lealone-Plugins with Apache License 2.0 5 votes vote down vote up
@Override
public void handle(SockJSSocket sockJSSocket) {
    sockJSSocket.endHandler(v -> {
        removeConnection(sockJSSocket.hashCode());
    });
    sockJSSocket.exceptionHandler(t -> {
        removeConnection(sockJSSocket.hashCode());
        logger.error("sockJSSocket exception", t);
    });

    sockJSSocket.handler(buffer -> {
        Buffer ret = ServiceHandler.handle(sockJSSocket, buffer.getString(0, buffer.length()));
        sockJSSocket.end(ret);
    });
}
 
Example #14
Source File: SockJSTtyConnection.java    From vertx-shell with Apache License 2.0 5 votes vote down vote up
private static Vector getInitialSize(SockJSSocket socket) {
  QueryStringDecoder decoder = new QueryStringDecoder(socket.uri());
  Map<String, List<String>> params = decoder.parameters();
  try {
    int cols = getParamValue(params, "cols", 80);
    int rows = getParamValue(params, "rows", 24);
    return new Vector(cols, rows);
  } catch (Exception e) {
    return new Vector(80, 24);
  }
}
 
Example #15
Source File: ChatMessageChainHandler.java    From slime with MIT License 5 votes vote down vote up
@Override
	public boolean handle(BridgeEvent event) throws EventBridgeChainException {
		boolean isHandle = Boolean.FALSE;
		
		if(BridgeEventType.PUBLISH == event.type()) {
			Vertx vertx = VertxHolder.getVertx();
			SockJSSocket sockJSSocket = event.socket();
			Map<String, Object> rawMessage = event.getRawMessage().getMap();
			
			String senderId = sockJSSocket.headers().get(WebSocketSessionHolder.USER_KEY);
			String address = (String) rawMessage.get("address");
			String msg = (String) rawMessage.get("body");
			
			RedisSockjsClient.PUBLISH(address,
		            new JsonObject()
		                .put("message", msg)
		                .put("sender", senderId));
//			vertx.eventBus().publish(address,
//		            new JsonObject()
//		                .put("message", msg)
//		                .put("sender", senderId));
			
			isHandle = Boolean.TRUE;
			
		}
		
		return isHandle;
	}
 
Example #16
Source File: OfflineChainHandler.java    From slime with MIT License 5 votes vote down vote up
@Override
	public boolean handle(BridgeEvent event) throws EventBridgeChainException {
		boolean isHandle = Boolean.FALSE;
		
		if(BridgeEventType.SOCKET_CLOSED == event.type()) {
			Vertx vertx = VertxHolder.getVertx();
			
			isHandle = Boolean.TRUE;
			
			SockJSSocket sockJSSocket = event.socket();
			
			// notify user offline
			String address = "topic/chat/offline";
			String userId = sockJSSocket.headers().get(WebSocketSessionHolder.USER_KEY);
			
			WebSocketSessionHolder.remove(userId);

			RedisSockjsClient.PUBLISH(address,
		            new JsonObject()
	                .put("userId", userId));
					
//			vertx.eventBus().publish(address,
//		            new JsonObject()
//		                .put("userId", userId));
			
		}
		
		return isHandle;
	}
 
Example #17
Source File: SockJSPushHandler.java    From vertx-vaadin with MIT License 5 votes vote down vote up
private void initSocket(SockJSSocket sockJSSocket, RoutingContext routingContext, PushSocket socket) {
    sockJSSocket.handler(data -> sessionHandler.handle(
        new SockJSRoutingContext(routingContext, rc -> onMessage(new PushEvent(socket, rc, data)))
    ));
    sockJSSocket.endHandler(unused -> sessionHandler.handle(
        new SockJSRoutingContext(routingContext, rc -> onDisconnect(new PushEvent(socket, rc, null)))
    ));
    sockJSSocket.exceptionHandler(t -> sessionHandler.handle(
        new SockJSRoutingContext(routingContext, rc -> onError(new PushEvent(socket, routingContext, null), t))
    ));

}
 
Example #18
Source File: SockJSPushHandler.java    From vertx-vaadin with MIT License 5 votes vote down vote up
private void initSocket(SockJSSocket sockJSSocket, RoutingContext routingContext, PushSocket socket) {
    sockJSSocket.handler(data -> sessionHandler.handle(
        new SockJSRoutingContext(routingContext, rc -> onMessage(new PushEvent(socket, rc, data)))
    ));
    sockJSSocket.endHandler(unused -> sessionHandler.handle(
        new SockJSRoutingContext(routingContext, rc -> onDisconnect(new PushEvent(socket, rc, null)))
    ));
    sockJSSocket.exceptionHandler(t -> sessionHandler.handle(
        new SockJSRoutingContext(routingContext, rc -> onError(new PushEvent(socket, routingContext, null), t))
    ));

}
 
Example #19
Source File: SockJSPushHandler.java    From vertx-vaadin with MIT License 5 votes vote down vote up
private <T> CompletableFuture<T> runCommand(Function<SockJSSocket, T> action) {
    CompletableFuture<T> future = new CompletableFuture<>();
    Vertx vertx = Vertx.currentContext().owner();
    SockJSSocket socket = SockJSPushHandler.socketsMap(vertx).get(socketUUID);
    if (socket != null) {
        try {
            future.complete(action.apply(socket));
        } catch (Exception ex) {
            future.completeExceptionally(ex);
        }
    } else {
        future.completeExceptionally(new RuntimeException("Socket not registered: " + socketUUID));
    }
    return future;
}
 
Example #20
Source File: SockJSPushHandler.java    From vertx-vaadin with MIT License 5 votes vote down vote up
private <T> CompletableFuture<T> runCommand(Function<SockJSSocket, T> action) {
    CompletableFuture<T> future = new CompletableFuture<>();
    Vertx vertx = Vertx.currentContext().owner();
    SockJSSocket socket = SockJSPushHandler.socketsMap(vertx).get(socketUUID);
    if (socket != null) {
        try {
            future.complete(action.apply(socket));
        } catch (Exception ex) {
            future.completeExceptionally(ex);
        }
    } else {
        future.completeExceptionally(new RuntimeException("Socket not registered: " + socketUUID));
    }
    return future;
}
 
Example #21
Source File: RawWebSocketTransport.java    From vertx-web with Apache License 2.0 4 votes vote down vote up
public SockJSSocket pause() {
  ws.pause();
  return this;
}
 
Example #22
Source File: WebSocketSessionHolder.java    From slime with MIT License 4 votes vote down vote up
public static SockJSSocket get(String userId) {
	return sessions.get(userId);
}
 
Example #23
Source File: SockJSSession.java    From vertx-web with Apache License 2.0 4 votes vote down vote up
SockJSSession(Vertx vertx, LocalMap<String, SockJSSession> sessions, RoutingContext rc, long heartbeatInterval,
              Handler<SockJSSocket> sockHandler) {
  this(vertx, sessions, rc, null, -1, heartbeatInterval, sockHandler);
}
 
Example #24
Source File: BaseTransport.java    From vertx-web with Apache License 2.0 4 votes vote down vote up
protected SockJSSession getSession(RoutingContext rc, long timeout, long heartbeatInterval, String sessionID,
                                   Handler<SockJSSocket> sockHandler) {
  SockJSSession session = sessions.computeIfAbsent(sessionID, s -> new SockJSSession(vertx, sessions, rc, s, timeout, heartbeatInterval, sockHandler));
  return session;
}
 
Example #25
Source File: SockJSSocketBase.java    From vertx-web with Apache License 2.0 4 votes vote down vote up
@Override
public abstract SockJSSocket exceptionHandler(Handler<Throwable> handler);
 
Example #26
Source File: SockJSPushHandler.java    From vertx-vaadin with MIT License 4 votes vote down vote up
private static LocalMap<String, SockJSSocket> socketsMap(Vertx vertx) {
    return vertx.sharedData().getLocalMap(SockJSPushHandler.class.getName() + ".push-sockets");
}
 
Example #27
Source File: BridgeEventImpl.java    From vertx-web with Apache License 2.0 4 votes vote down vote up
@Override
public SockJSSocket socket() {
  return socket;
}
 
Example #28
Source File: BridgeEventImpl.java    From vertx-web with Apache License 2.0 4 votes vote down vote up
public BridgeEventImpl(BridgeEventType type, JsonObject rawMessage, SockJSSocket socket) {
  this.type = type;
  this.rawMessage = rawMessage;
  this.socket = socket;
  this.promise = Promise.promise();
}
 
Example #29
Source File: SockJSPushHandler.java    From vertx-vaadin with MIT License 4 votes vote down vote up
PushSocketImpl(SockJSSocket socket) {
    this.socketUUID = socket.writeHandlerID();
    this.remoteAddress = socket.remoteAddress().toString();
}
 
Example #30
Source File: RawWebSocketTransport.java    From vertx-web with Apache License 2.0 4 votes vote down vote up
public SockJSSocket exceptionHandler(Handler<Throwable> handler) {
  ws.exceptionHandler(handler);
  return this;
}