List of usage examples for javax.websocket Session getId
String getId();
From source file:com.github.mrstampy.gameboot.otp.websocket.WebSocketEndpoint.java
private void unencrypted(Session ctx, byte[] msg) throws Exception { Response r = getResponse(msg); lastResponse = r;// w w w.j av a 2 s . c o m log.info("Unencrypted: on session {}\n{}", ctx.getId(), mapper.writeValueAsString(r)); if (!ok(r.getResponseCode())) return; if (ResponseCode.INFO == r.getResponseCode()) { Object[] payload = r.getPayload(); if (payload == null || payload.length == 0 || !(payload[0] instanceof Map<?, ?>)) { throw new IllegalStateException("Expecting map of systemId:[value]"); } systemId = (Long) ((Map<?, ?>) payload[0]).get("systemId"); log.info("Setting system id {}", systemId); this.session = ctx; return; } JsonNode node = mapper.readTree(msg); JsonNode response = node.get("payload"); boolean hasKey = response != null && response.isArray() && response.size() == 1; if (hasKey) { log.info("Setting key"); otpKey = response.get(0).binaryValue(); return; } switch (r.getType()) { case OtpKeyRequest.TYPE: log.info("Deleting key"); otpKey = null; break; default: break; } }
From source file:io.apicurio.hub.editing.EditApiDesignEndpoint.java
/** * Called when a web socket connection is made. The format for the web socket URL endpoint is: * /*from w w w . j a v a 2s . c o m*/ * /designs/{designId}?uuid={uuid}&user={user}&secret={secret} * * The uuid, user, and secret query parameters must be present for a connection to be * successfully made. * * @param session */ @OnOpen public void onOpenSession(Session session) { String designId = session.getPathParameters().get("designId"); logger.debug("WebSocket opened: {}", session.getId()); logger.debug("\tdesignId: {}", designId); String queryString = session.getQueryString(); Map<String, String> queryParams = parseQueryString(queryString); String uuid = queryParams.get("uuid"); String userId = queryParams.get("user"); String secret = queryParams.get("secret"); this.metrics.socketConnected(designId, userId); logger.debug("\tuuid: {}", uuid); logger.debug("\tuser: {}", userId); ApiDesignEditingSession editingSession = null; try { long contentVersion = editingSessionManager.validateSessionUuid(uuid, designId, userId, secret); // Join the editing session (or create a new one) for the API Design editingSession = this.editingSessionManager.getOrCreateEditingSession(designId); Set<Session> otherSessions = editingSession.getSessions(); if (editingSession.isEmpty()) { this.metrics.editingSessionCreated(designId); } editingSession.join(session, userId); // Send "join" messages for each user already in the session for (Session otherSession : otherSessions) { String otherUser = editingSession.getUser(otherSession); editingSession.sendJoinTo(session, otherUser, otherSession.getId()); } // Send any commands that have been created since the user asked to join the editing session. List<ApiDesignCommand> commands = this.storage.listContentCommands(userId, designId, contentVersion); for (ApiDesignCommand command : commands) { String cmdData = command.getCommand(); StringBuilder builder = new StringBuilder(); builder.append("{"); builder.append("\"contentVersion\": "); builder.append(command.getContentVersion()); builder.append(", "); builder.append("\"type\": \"command\", "); builder.append("\"command\": "); builder.append(cmdData); builder.append("}"); logger.debug("Sending command to client (onOpenSession): {}", builder.toString()); session.getBasicRemote().sendText(builder.toString()); } editingSession.sendJoinToOthers(session, userId); } catch (ServerError | StorageException | IOException e) { if (editingSession != null) { editingSession.leave(session); } logger.error("Error validating editing session UUID for API Design ID: " + designId, e); try { session.close(new CloseReason(CloseCodes.CANNOT_ACCEPT, "Error opening editing session: " + e.getMessage())); } catch (IOException e1) { logger.error( "Error closing web socket session (attempted to close due to error validating editing session UUID).", e1); } } }
From source file:ch.rasc.wampspring.broker.SimpleBrokerMessageHandlerTests.java
@SuppressWarnings("resource") @Test//from ww w . j a v a2 s. com public void testCleanupMessage() { this.messageHandler.handleMessage(subscribeMessage("sess1", "/foo")); this.messageHandler.handleMessage(subscribeMessage("sess2", "/foo")); Session nativeSession = Mockito.mock(Session.class); Mockito.when(nativeSession.getId()).thenReturn("sess1"); StandardWebSocketSession wsSession = new StandardWebSocketSession(null, null, null, null); wsSession.initializeNativeSession(nativeSession); UnsubscribeMessage cleanupMessage = UnsubscribeMessage.createCleanupMessage(wsSession); this.messageHandler.handleMessage(cleanupMessage); this.messageHandler.handleMessage(eventMessage("sess1", "/foo", "message1")); this.messageHandler.handleMessage(eventMessage("sess2", "/bar", "message2")); verify(this.clientOutboundChannel, times(1)).send(this.messageCaptor.capture()); assertCapturedMessage(eventMessage("sess2", "/foo", "message1")); }
From source file:com.github.mrstampy.gameboot.otp.websocket.OtpWebSocketTest.java
private void sendMessage(AbstractGameBootMessage message, Session channel) throws Exception { if (channel == null || !channel.isOpen()) return;/*from ww w. ja v a 2 s. c o m*/ CountDownLatch cdl = new CountDownLatch(1); endpoint.setResponseLatch(cdl); boolean b = endpoint.hasKey(); log.info("Sending {} to session {}: {}", (b ? "encrypted" : "unencrypted"), channel.getId(), converter.toJson(message)); endpoint.sendMessage(converter.toJsonArray(message), channel); cdl.await(1, TimeUnit.SECONDS); }
From source file:org.brutusin.rpc.websocket.WebsocketEndpoint.java
/** * * @param session/* www .j a v a 2s . c om*/ * @param config */ @Override public void onOpen(Session session, EndpointConfig config) { final WebsocketContext websocketContext = contextMap .get(session.getRequestParameterMap().get("requestId").get(0)); if (!allowAccess(session, websocketContext)) { try { session.close(new CloseReason(CloseReason.CloseCodes.CANNOT_ACCEPT, "Authentication required")); } catch (IOException ex) { throw new RuntimeException(ex); } return; } final SessionImpl sessionImpl = new SessionImpl(session, websocketContext); sessionImpl.init(); wrapperMap.put(session.getId(), sessionImpl); session.addMessageHandler(new MessageHandler.Whole<String>() { public void onMessage(String message) { WebsocketActionSupportImpl.setInstance(new WebsocketActionSupportImpl(sessionImpl)); try { String response = process(message, sessionImpl); if (response != null) { sessionImpl.sendToPeerRaw(response); } } finally { WebsocketActionSupportImpl.clear(); } } }); }
From source file:org.axonframework.commandhandling.distributed.websockets.WebsocketCommandBusConnectorClient.java
@Override public void onError(Session session, Throwable cause) { LOGGER.warn("Connection error on session " + session.getId(), cause); }
From source file:org.axonframework.commandhandling.distributed.websockets.WebsocketCommandBusConnectorClient.java
@Override public void onClose(Session session, CloseReason closeReason) { if (closeReason.getCloseCode() != CloseReason.CloseCodes.NORMAL_CLOSURE) { LOGGER.warn("Session closed because " + closeReason.getReasonPhrase()); }/* ww w . j a v a 2 s .c o m*/ try { sessions.invalidateObject(session); repository.cancelCallbacks(session.getId()); } catch (Exception e) { LOGGER.error("Could not invalidate session", e); } }
From source file:org.axonframework.commandhandling.distributed.websockets.WebsocketCommandBusConnectorClient.java
/** * Sends a command to the servewr/*from w w w. j a v a 2s. c om*/ * @param command The command to send * @param callback The callback to send Command results to. May be null if no callback is required * @param <C> The type of the Command * @param <R> The type of the Command result. */ public <C, R> void send(CommandMessage<C> command, CommandCallback<? super C, R> callback) { ByteBuffer data = ByteBuffer.wrap(serializer .serialize(new WebsocketCommandMessage<>(command, callback != null), byte[].class).getData()); try { Session session = sessions.borrowObject(); try { LOGGER.debug("Using session " + session.getId() + " to send " + command.getCommandName()); if (callback != null) { repository.store(command.getIdentifier(), new CommandCallbackWrapper<>(session.getId(), command, callback)); } session.getBasicRemote().sendBinary(data); } finally { sessions.returnObject(session); } } catch (Exception e) { LOGGER.error("Error sending command", e); if (callback != null) { callback.onFailure(command, new CommandBusConnectorCommunicationException( "Failed to send command of type " + command.getCommandName() + " to remote", e)); } } }
From source file:org.damcode.web.c4webserver.Player.java
public Player(int boardId, Session session) { printSysOut("player init id: " + session.getId() + ", board id: " + boardId); this.boardId = boardId; this.session = session; }
From source file:org.damcode.web.c4webserver.Server.java
@OnOpen public void onOpen(Session session, @PathParam("id") String gameId) throws IOException { printSysOut("new session: " + session.getId() + ", game id: " + gameId + "from ip: "); session.getUserProperties().put("gameid", gameId); session.getUserProperties().put("lobby", true); String connectedPlayers = ""; int pCount = 0; for (Session s : session.getOpenSessions()) { if (!s.equals(session)) { String name = (String) s.getUserProperties().get("name"); connectedPlayers += name + ", "; pCount++;/*from w ww .j a va 2s . c o m*/ } } if (pCount > 0) { printSysOut("Connected Players: " + connectedPlayers); session.getBasicRemote() .sendText(Utils.assembleChatMessage("Server", connectedPlayers, "other players")); } for (GameController gc : waitingGames) { sendGameAvailMessage(session, gc.getId().toString(), gc.players.get(0)); } }