Java Code Examples for org.eclipse.jetty.websocket.api.Session

The following are top voted examples for showing how to use org.eclipse.jetty.websocket.api.Session. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: smockin   File: WebSocketServiceImpl.java   View source code 7 votes vote down vote up
/**
 *
 * Stores all websocket client sessions in the internal map 'sessionMap'.
 *
 * Note sessions are 'internally' identified using the encrypted handshake 'Sec-WebSocket-Accept' value and
 * 'externally' identified using an allocated UUID.
 *
 *
 * @param mockExtId
 * @param path
 * @param idleTimeoutMillis
 * @param session
 *
 */
public void registerSession(final String mockExtId, final String path, final long idleTimeoutMillis, final boolean proxyPushIdOnConnect, final Session session) {
    logger.debug("registerSession called");

    session.setIdleTimeout((idleTimeoutMillis > 0) ? idleTimeoutMillis : MAX_IDLE_TIMEOUT_MILLIS );

    final Set<SessionIdWrapper> sessions = sessionMap.getOrDefault(path, new HashSet<SessionIdWrapper>());

    final String assignedId = GeneralUtils.generateUUID();

    sessions.add(new SessionIdWrapper(assignedId, session, GeneralUtils.getCurrentDate()));

    sessionMap.put(path, sessions);

    if (proxyPushIdOnConnect) {
        try {
            sendMessage(assignedId, new WebSocketDTO(path, "clientId: " + assignedId));
        } catch (IOException ex) {
            logger.error("Error pushing client id to client on 1st connect", ex);
        }
    }

}
 
Example 2
Project: debug   File: Profiling.java   View source code 7 votes vote down vote up
public void onWebSocketConnect(Session session) {
    this.outbound = session;
    synchronized (connections) {
        connections.add(this);
    }
    Profiling.frontendConnected.countDown();
}
 
Example 3
Project: B4J_Server   File: WebSocketModule.java   View source code 7 votes vote down vote up
@Override
public void onWebSocketConnect(Session sess) {
	super.onWebSocketConnect(sess);
	((WebSocketRemoteEndpoint)sess.getRemote()).setBatchMode(BatchMode.ON);
	handler = new ThreadHandler();
	if (parentServlet.singleThread) {
		BA.firstInstance.postRunnable(handler);
	}
	else {
		Servlet.pool.submit(handler);
	}
}
 
Example 4
Project: Shape-Shmup   File: GameSocket.java   View source code 7 votes vote down vote up
/** Broadcast text to all connected clients. */
void broadcast(String message, Session sourceSession) {
	String sourceName = null;
	synchronized(sessionToName) {
		sourceName = sessionToName.get(sourceSession);
	}
	if (sourceName != null && !sourceName.isEmpty()) {
		message = "<strong>" + sourceName + "</strong>: " + message;
	}
	synchronized(sessionToName) {
		for (Session s : sessionToName.keySet()) {
			try {
				if (s.isOpen()) {
					s.getRemote().sendStringByFuture(message);
				}
			} catch (WebSocketException e) {
				System.out.println("The error " + e.getLocalizedMessage() + " occurred. This " 
						+ "can happen if the player dies before a broadcast arrives.");
			}
		}
	}
}
 
Example 5
Project: aliyun-cupid-sdk   File: WebSocketClient.java   View source code 6 votes vote down vote up
private void extractLoadBalanceKey(Session session) {
    String setCookieValue =
            session.getUpgradeResponse().getHeader(SDKConstants.CUPID_INTERACTION_HEADER_SET_COOKIE);
    if (setCookieValue != null) {
        setCookieValue = setCookieValue.trim();
        String[] kv = setCookieValue.split(";");
        for (String kvStr : kv) {
            if (kvStr.contains("=")) {
                String[] kAndV = kvStr.split("=");
                if (kAndV.length == 2 && kAndV[0] != null && kAndV[1] != null) {
                    if (SDKConstants.CUPID_INTERACTION_COOKIE_HASH_KEY.equals(kAndV[0].trim())) {
                        loadBalanceHashKey = kAndV[1].trim();
                        LOG.info(subProtocol + " - loadbalance key:" + loadBalanceHashKey);
                        return;
                    }
                }
            }
        }
    }
}
 
Example 6
Project: aliyun-cupid-sdk   File: InteractionSocket.java   View source code 6 votes vote down vote up
@OnWebSocketConnect
public void onConnect(Session session) {
    LOG.info(webSocketClient.getSubProtocol() + " - Got connect.");
    if (mode == SDKConstants.INTERACTION_CLIENT_INPUT_MODE_INPUTSTREAM) {
        if (inputBuf == null) {
            this.inputBuf = ByteBuffer.allocate(SDKConstants.WEBSOCKET_MAX_BINARY_MESSAGE_SIZE);
            this.inputBuf.limit(0);
            this.inputStream = new ByteBufferBackedInputStream(inputBuf);
        }
    }
    if (outputBuf == null) {
        this.outputBuf = ByteBuffer.allocate(SDKConstants.WEBSOCKET_MAX_BINARY_MESSAGE_SIZE);
        this.outputStream = new ByteBufferBackedOutputStream(outputBuf, session);
    } else {
        synchronized (outputBuf) {
            ((ByteBufferBackedOutputStream) this.outputStream).setSession(session);
            outputBuf.notify();
        }
    }
    this.closed = false;
}
 
Example 7
Project: websocket   File: Jwslistner.java   View source code 6 votes vote down vote up
@Override
public void onWebSocketConnect(final Session session) {
	MAP.put(this.flag = this.getConnectFlag(session), session);
	MsgTo to = new MsgTo(MsgType.connect, "", this.flag, "200",
			System.currentTimeMillis(), null);
	send(session, JsonUtil.toJsonStr(to));

	// $version < 1.2.2 ;
	// s.scheduleWithFixedDelay(new Runnable() {
	// {
	//
	// Jwslistner.send(session, "200");
	// }
	//
	// @Override
	// public void run() {
	// Jwslistner.send(session, "heartbeat");
	// }
	// }, 30, 30, TimeUnit.SECONDS);

	this.getWh().onConnect(session, flag);
}
 
Example 8
Project: websocket   File: Jwslistner.java   View source code 6 votes vote down vote up
public static boolean send(Session session, String msg) {
	if (session == null)
		return false;
	try {
		if (session.isOpen())
			session.getRemote().sendString(msg);
	} catch (IOException e) {
		e.printStackTrace();
		return false;
	}
	return true;
}
 
Example 9
Project: IOTAFaucet   File: Frontend.java   View source code 6 votes vote down vote up
public WorkWebsocket(Backend backend) {
    backend.getWorkObservable(workResponses).subscribe((req) -> {
        String msg = GSON.toJson(req);
        int offset = 0;
        for (Session session : sessions) {
            final int finalOffset = ++offset;
            Schedulers.io().scheduleDirect(()-> {
                try {
                    JsonObject finalMsg = GSON.fromJson(msg, JsonObject.class);
                    finalMsg.addProperty("offset", finalOffset);
                    session.getRemote().sendString(GSON.toJson(finalMsg));
                    System.out.println("Send message to a session");
                } catch (IOException e) {
                    e.printStackTrace();
                }
            });
        }
    });

}
 
Example 10
Project: java-binance-api   File: DepthStreamTest.java   View source code 6 votes vote down vote up
@Test
public void testDepthStreamWatcher() throws Exception, BinanceApiException {
    Session session = binanceApi.websocketDepth(symbol, new BinanceWebSocketAdapterDepth() {
        @Override
        public void onMessage(BinanceEventDepthUpdate message) {
            log.info(message.toString());
        }
    });
    Thread.sleep(3000);
    session.close();
}
 
Example 11
Project: java-binance-api   File: AggTradesStreamTest.java   View source code 6 votes vote down vote up
@Test
public void testTradesStreamWatcher() throws Exception, BinanceApiException {
    Session session = binanceApi.websocketTrades(symbol, new BinanceWebSocketAdapterAggTrades() {
        @Override
        public void onMessage(BinanceEventAggTrade message) {
            log.info(message.toString());
        }
    });
    Thread.sleep(5000);
    session.close();
}
 
Example 12
Project: java-binance-api   File: KlinesStreamTest.java   View source code 6 votes vote down vote up
@Test
public void testKlinesStreamWatcher() throws Exception, BinanceApiException {
    Session session = binanceApi.websocketKlines(symbol, BinanceInterval.ONE_MIN, new BinanceWebSocketAdapterKline() {
        @Override
        public void onMessage(BinanceEventKline message) {
            log.info(message.toString());
        }
    });
    Thread.sleep(3000);
    session.close();
}
 
Example 13
Project: Hydrograph   File: ExecutionTrackingWebsocketHandler.java   View source code 6 votes vote down vote up
private void killRequestedJob(ExecutionStatus executionStatus, Session session) {

		if (Constants.KILL.equalsIgnoreCase(executionStatus.getType())) {

			logger.info("Kill request received for job - " + executionStatus.getJobId());

			final String jobId = executionStatus.getJobId().trim();

			for (Session openSession : allSessions.keySet()) {

				if (openSession.isOpen()) {
					try {

						if (allSessions.get(openSession).get(Constants.CLIENTID) != null) {

							if (((String) allSessions.get(openSession).get(Constants.CLIENTID))
									.equalsIgnoreCase(Constants.ENGINE_CLIENT + executionStatus.getJobId())) {

								logger.debug("Before sending kill" + jobId);
								openSession.getRemote().sendStringByFuture("");
								logger.debug("After sending kill" + jobId);
							}
						}
					} catch (Exception e) {
						logger.error("Failed to send kill request for - " + jobId, e);
					}
				}
			}
		}

	}
 
Example 14
Project: robotoy   File: WebSocketHandlerImpl.java   View source code 6 votes vote down vote up
/**
 * Callback hook for Connection open events.
 *
 * @param session the user session which is opened.
 */
@OnWebSocketConnect
public void onConnect(Session session) {
	this.session = session;
	this.futureSession = null; // don't need this anymore
	this.addr = session.getRemoteAddress().getAddress();
	this.remotePort = session.getRemoteAddress().getPort();
	this.localAddr = session.getLocalAddress().getAddress();
	this.localPort = session.getLocalAddress().getPort();
	this.path = session.getUpgradeRequest().getRequestURI().getPath();
	if (session.getUpgradeRequest() instanceof ClientUpgradeRequest) {
		this.key = ((ClientUpgradeRequest)session.getUpgradeRequest()).getKey();
	}
	else {
		this.key = session.getUpgradeRequest().getHeader("Sec-WebSocket-Key");
	}
    if (log.isLoggable(Level.INFO)) 
    	log.log(Level.INFO,"Connected with "+((addr==null)?"<null>":addr.toString())+" through local address "+localAddr.getHostAddress());
    pool.addSession(this);
    pool.getInclusionCallback().onStartConnection(this);
}
 
Example 15
Project: spring4-understanding   File: JettyWebSocketSession.java   View source code 6 votes vote down vote up
@Override
public void initializeNativeSession(Session session) {
	super.initializeNativeSession(session);

	this.id = ObjectUtils.getIdentityHexString(getNativeSession());
	this.uri = session.getUpgradeRequest().getRequestURI();

	this.headers = new HttpHeaders();
	this.headers.putAll(getNativeSession().getUpgradeRequest().getHeaders());
	this.headers = HttpHeaders.readOnlyHttpHeaders(headers);

	this.acceptedProtocol = session.getUpgradeResponse().getAcceptedSubProtocol();

	List<ExtensionConfig> source = getNativeSession().getUpgradeResponse().getExtensions();
	this.extensions = new ArrayList<WebSocketExtension>(source.size());
	for (ExtensionConfig ec : source) {
		this.extensions.add(new WebSocketExtension(ec.getName(), ec.getParameters()));
	}

	if (this.user == null) {
		this.user = session.getUpgradeRequest().getUserPrincipal();
	}
}
 
Example 16
Project: spring4-understanding   File: JettyWebSocketSessionTests.java   View source code 6 votes vote down vote up
@Test
public void getPrincipalFromNativeSession() {

	TestPrincipal user = new TestPrincipal("joe");

	UpgradeRequest request = Mockito.mock(UpgradeRequest.class);
	given(request.getUserPrincipal()).willReturn(user);

	UpgradeResponse response = Mockito.mock(UpgradeResponse.class);
	given(response.getAcceptedSubProtocol()).willReturn(null);

	Session nativeSession = Mockito.mock(Session.class);
	given(nativeSession.getUpgradeRequest()).willReturn(request);
	given(nativeSession.getUpgradeResponse()).willReturn(response);

	JettyWebSocketSession session = new JettyWebSocketSession(attributes);
	session.initializeNativeSession(nativeSession);

	reset(nativeSession);

	assertSame(user, session.getPrincipal());
	verifyNoMoreInteractions(nativeSession);
}
 
Example 17
Project: spring4-understanding   File: JettyWebSocketSessionTests.java   View source code 6 votes vote down vote up
@Test
public void getPrincipalNotAvailable() {

	UpgradeRequest request = Mockito.mock(UpgradeRequest.class);
	given(request.getUserPrincipal()).willReturn(null);

	UpgradeResponse response = Mockito.mock(UpgradeResponse.class);
	given(response.getAcceptedSubProtocol()).willReturn(null);

	Session nativeSession = Mockito.mock(Session.class);
	given(nativeSession.getUpgradeRequest()).willReturn(request);
	given(nativeSession.getUpgradeResponse()).willReturn(response);

	JettyWebSocketSession session = new JettyWebSocketSession(attributes);
	session.initializeNativeSession(nativeSession);

	reset(nativeSession);

	assertNull(session.getPrincipal());
	verifyNoMoreInteractions(nativeSession);
}
 
Example 18
Project: guacamole-client   File: GuacamoleWebSocketTunnelListener.java   View source code 6 votes vote down vote up
/**
 * Sends the given status on the given WebSocket connection and closes the
 * connection.
 *
 * @param session The outbound WebSocket connection to close.
 * @param guac_status The status to send.
 */
private void closeConnection(Session session, GuacamoleStatus guac_status) {

    try {
        int code = guac_status.getWebSocketCode();
        String message = Integer.toString(guac_status.getGuacamoleStatusCode());
        session.close(new CloseStatus(code, message));
    }
    catch (IOException e) {
        logger.debug("Unable to close WebSocket connection.", e);
    }

}
 
Example 19
Project: grakn   File: GraqlSessionTest.java   View source code 6 votes vote down vote up
@Test
public void whenRunningAComputeQueryThenExiting_TheComputeQueryIsKilled() throws ExecutionException, InterruptedException {
    Session jettySesssion = mock(Session.class, RETURNS_DEEP_STUBS);

    GraknSession factory = mock(GraknSession.class);
    GraknTx graph = mock(GraknTx.class, RETURNS_DEEP_STUBS);
    QueryBuilder qb = mock(QueryBuilder.class);
    QueryParser parser = mock(QueryParser.class);
    CountQuery count = mock(CountQuery.class);

    when(factory.open(GraknTxType.WRITE)).thenReturn(graph);
    when(graph.graql()).thenReturn(qb);
    when(qb.infer(false)).thenReturn(qb);
    when(qb.materialise(false)).thenReturn(qb);
    when(qb.parser()).thenReturn(parser);
    when(parser.parseList("compute count;")).thenReturn(Stream.of(count));

    GraqlSession session = new GraqlSession(jettySesssion, factory, "json", false);
    session.receiveQuery(Json.object(QUERY, "compute count;"));
    session.executeQuery().get();

    // Make sure `kill` is called only after closing
    verify(count, never()).kill();
    session.close();
    verify(count).kill();
}
 
Example 20
Project: Shape-Shmup   File: GameSocket.java   View source code 6 votes vote down vote up
/** Send text to a single client */
void unicast(String message, Session session) {
	try {
		if (session.isOpen()) {
			session.getRemote().sendStringByFuture(message);
		}
	} catch (WebSocketException e) {
		System.out.println("The error " + e.getLocalizedMessage() + " occurred. This " 
				+ "can happen if the player dies before a unicast arrives.");
	}
}
 
Example 21
Project: warp10-platform   File: EgressMobiusHandler.java   View source code 6 votes vote down vote up
@Override
public int compare(Session session1, Session session2) {
  Long deadline1 = deadlines.get(session1);
  Long deadline2 = deadlines.get(session2);
  
  if(null == deadline1) {
    if (null == deadline2) {
      return 0;
    } else {
      return -1;
    }
  } else if (null == deadline2) {
    if (null == deadline1) {
      return 0;
    } else {
      return 1;
    }
  } else {
    return Long.signum((long) deadline1 - (long) deadline2);
  }
}
 
Example 22
Project: javafx_webview_debugger   File: DevToolsWebSocket.java   View source code 6 votes vote down vote up
@Override
public void onWebSocketConnect(Session session) {
	this.session = session;
	if (context.getAttribute(WEB_SOCKET_ATTR_NAME) != null) {
		session.close();
		System.out.println("Another client is already connected. Connection refused");
	} else {
		context.setAttribute(WEB_SOCKET_ATTR_NAME, this);
		System.out.println("Client connected");
	}
}
 
Example 23
Project: cicomponents   File: OutputWebSocketServlet.java   View source code 6 votes vote down vote up
@Override public void onWebSocketConnect(Session sess) {
    String[] pathComponents = sess.getUpgradeRequest().getRequestURI().getPath().split("/");
    UUID uuid = UUID.fromString(pathComponents[pathComponents.length - 1]);
    OutputProvider provider = registry.getProviders().get(uuid);
    ObjectMapper mapper = new ObjectMapper();
    executor.execute(() -> {
        Iterator<OutputProvider.TimestampedOutput> iterator = provider.getOutput().iterator();
        while (iterator.hasNext()) {
            if (!sess.isOpen()) {
                return;
            }
            try {
                sess.getRemote().sendString(mapper.writeValueAsString(iterator.next()));
            } catch (Exception e) {
                log.error("Exception while serializing a timestamped output", e);
                try {
                    sess.disconnect();
                } catch (IOException e1) {
                }
            }
        }
    });
}
 
Example 24
Project: hawkcd   File: WSSocket.java   View source code 6 votes vote down vote up
private void initialize(Session session) {
        String tokenQuery = session.getUpgradeRequest().getQueryString();
        if (!tokenQuery.equals("api_key=null")) {
            String token = tokenQuery.substring(8);
            TokenInfo tokenInfo = TokenAdapter.verifyToken(token);
            if (tokenInfo == null) {
                return;
            }

            User user = tokenInfo.getUser();
            this.setLoggedUser(user);

            //Fill in the sessionDetails
            this.sessionDetails.setUserId(user.getId());
            this.sessionDetails.setUserEmail(user.getEmail());

            ISessionManager sessionManager = SessionFactory.getSessionManager();
            sessionManager.openSession(this);
            sessionManager.updateSessionLoggedUser(user.getId());

//            WsContractDto contract = extractUserDetails(user);
//            sessionManager.send(this, contract);
        }
    }
 
Example 25
Project: trvedb   File: EventsConnection.java   View source code 6 votes vote down vote up
/**
 * Called by Jetty when a text frame is received from the WebSocket client.
 */
@Override
public void onWebSocketText(String message) {
    log.info("Received unsupported text message from peer {}", peerID);
    Session session = getSession();
    if (session != null && session.isOpen()) {
        session.close(StatusCode.BAD_DATA, "This endpoint only accepts binary messages");
    }
}
 
Example 26
Project: trvedb   File: EventsConnection.java   View source code 6 votes vote down vote up
/**
 * @see ClientConnection#offerMessage(ServerToClient)
 */
public boolean offerMessage(ServerToClient message) {
    Session session = getSession();
    if (session == null || !session.isOpen()) return false;

    if (inFlightMessages.incrementAndGet() > MAX_IN_FLIGHT_MESSAGES) {
        inFlightMessages.decrementAndGet();
        return false;
    }

    ByteArrayOutputStream stream = new ByteArrayOutputStream();
    try {
        BinaryEncoder encoder = EncoderFactory.get().binaryEncoder(stream, null);
        writeToClient.write(message, encoder);
        encoder.flush();
    } catch (Exception e) {
        log.warn("Failed to encode message to client", e);
        session.close(StatusCode.SERVER_ERROR, "Internal server error");
        return true;
    }

    session.getRemote().sendBytes(ByteBuffer.wrap(stream.toByteArray()), new WriteCallback() {
        @Override
        public void writeSuccess() {
            inFlightMessages.decrementAndGet();
        }

        @Override
        public void writeFailed(Throwable error) {
            inFlightMessages.decrementAndGet();
            log.info("Sending message to WebSocket client failed: ", error);
        }
    });

    return true;
}
 
Example 27
Project: aliyun-cupid-sdk   File: WebSocketClient.java   View source code 5 votes vote down vote up
public void connect(boolean isReconnect) {
    if (client == null) {
        client = new org.eclipse.jetty.websocket.client.WebSocketClient();
    }
    // For debug usage
    // client.setConnectTimeout(SDKConstants.ONE_HOUR);
    try {
        if (!client.isStarted()) {
            client.start();
        }
        ClientUpgradeRequest request = new ClientUpgradeRequest();
        request.setSubProtocols(subProtocol);
        setLoadBalanceKey(request);
        if (token != null) {
            request.setHeader(SDKConstants.CUPID_INTERACTION_HEADER_TOKEN, token);
        }
        if (isReconnect) {
            request.setHeader(SDKConstants.CUPID_INTERACTION_HEADER_RECONNECT,
                    String.valueOf(System.currentTimeMillis()));
        }
        LOG.info(subProtocol + " - Connecting to : " + destUri);
        Future<Session> future = client.connect(interactionSocket, destUri, request);
        Session session = future.get(5l, TimeUnit.SECONDS);
        if (!isReconnect && SDKConstants.CUPID_INTERACTION_SUB_PROTOCOL_CLIENT.equals(subProtocol)) {
            // will be used for reconnect
            token = session.getUpgradeResponse().getHeader(SDKConstants.CUPID_INTERACTION_HEADER_TOKEN);
            routeInfo =
                    session.getUpgradeResponse()
                            .getHeader(SDKConstants.CUPID_INTERACTION_HEADER_ROUTE_INFO);
        }
        extractLoadBalanceKey(session);
        LOG.info(subProtocol + " - Connected!");
    } catch (Throwable t) {
        String errMsg = subProtocol + " - Websocket connect failed";
        LOG.error(errMsg, t);
        close();
    }
}
 
Example 28
Project: buabook-api-interface   File: ClientWebSocket.java   View source code 5 votes vote down vote up
@OnWebSocketConnect
public void onConnect(Session newWebSocket) {
	this.session = newWebSocket;
	
	log.info("Broker Client WebSocket open: " + session.getRemoteAddress());
	session.setIdleTimeout(CLIENT_WS_IDLE_TIMEOUT_MS);
	
	Broadcaster.getInstance().subscribe(this);
	onConnectQuerier.queryApiOnClientConnect();
}
 
Example 29
Project: NoMoreOversleeps   File: UltiwakerWebSocketHandler.java   View source code 5 votes vote down vote up
@OnWebSocketConnect
public void onConnect(Session session) throws AuthenticationException
{
	Map<String, List<String>> params = session.getUpgradeRequest().getParameterMap();
	List<String> keys = params.get("key");
	if (keys == null || keys.size() != 1 || !keys.get(0).equals(NMOConfiguration.INSTANCE.integrations.webUI.ultiwakerAPI.apiSecurityKey))
	{
		throw new AuthenticationException("Not authorized");
	}
	this.session = session;
	this.connectionIP = session.getRemoteAddress().getAddress().toString();
	connections.add(this);
	log.info("UWAPI connect from " + this.connectionIP);
}
 
Example 30
Project: smockin   File: WebSocketServiceImpl.java   View source code 5 votes vote down vote up
public String getExternalId(final String path, final Session session) {

        final String sessionHandshake = session.getUpgradeResponse().getHeader(WS_HAND_SHAKE_KEY);

        for (SessionIdWrapper sw : sessionMap.get(path)) {
            if (sw.getSession().getUpgradeResponse().getHeader(WS_HAND_SHAKE_KEY).equals(sessionHandshake)) {
                return sw.getId();
            }
        }

        return null;
    }
 
Example 31
Project: jobson   File: ObservableSocket.java   View source code 5 votes vote down vote up
@OnWebSocketClose
public void onWebSocketClose(Session session, int closeCode, String closeReason) {
    log.debug("Closing websocket");
    this.eventsSubscription.dispose();
    session.close(closeCode, closeReason);
}
 
Example 32
Project: SECP   File: ChatSocketListener.java   View source code 5 votes vote down vote up
@Override
public void onWebSocketConnect(Session session) {

    log.info("New session was added : " + session.getLocalAddress().getHostName());
    this.outbound = session;
    this.messageHandler.attachSession(this);
}
 
Example 33
Project: traccar-service   File: AsyncSocket.java   View source code 5 votes vote down vote up
@Override
public void onWebSocketConnect(Session session) {
    super.onWebSocketConnect(session);

    Map<String, Collection<?>> data = new HashMap<>();
    data.put(KEY_POSITIONS, Context.getDeviceManager().getInitialState(userId));
    sendData(data);

    Context.getConnectionManager().addListener(userId, this);
}
 
Example 34
Project: gitplex-mit   File: WebSocketConnection.java   View source code 5 votes vote down vote up
/**
 * Constructor.
 *
 * @param session
 *            the jetty websocket connection
 */
public WebSocketConnection(Session session, AbstractWebSocketProcessor webSocketProcessor, PageKey pageKey)
{
	super(webSocketProcessor);
	this.session = Args.notNull(session, "connection");
	this.pageKey = pageKey;
}
 
Example 35
Project: Hydrograph   File: ExecutionTrackingWebsocketHandler.java   View source code 5 votes vote down vote up
@OnWebSocketMessage
public void trackingCommunicator(Session session, String msg) throws IOException {
	logger.debug("In trackingCommunicator method trigged on websoket messsage ");

	Gson gson = new Gson();
	logger.debug("Converting execution json to object ");
	ExecutionStatus executionStatus = gson.fromJson(msg, ExecutionStatus.class);

	logger.debug("Execution Tracking Request - " + executionStatus.toString());

	/** Mapping session and it client id,to track Ui and engine session */
	allSessions.get(session).put(Constants.CLIENTID, executionStatus.getClientId());

	/**
	 * Ui Client send connection request and save jobid with it session in
	 * map.
	 */

	getTrackingStatus(executionStatus, session);

	/**
	 * Status posted by engine client will delivered to requested UI client
	 * based on Job Id.
	 */
	postTrackingStatus(executionStatus, session);

	/**
	 * UI will send kill request along with job id, server intern call
	 * engine client to kill the job. For remote and remote debug run
	 */
	killRequestedJob(executionStatus, session);
}
 
Example 36
Project: Hydrograph   File: ExecutionTrackingWebsocketHandler.java   View source code 5 votes vote down vote up
private void getTrackingStatus(ExecutionStatus executionStatus, Session session) {
	if (Constants.GET.equalsIgnoreCase(executionStatus.getType())) {

		logger.debug(" Mapping session and it job id ");
		allSessions.get(session).put(Constants.JOBID, executionStatus.getJobId());

	}
}
 
Example 37
Project: javalin-websocket-example   File: Chat.java   View source code 5 votes vote down vote up
private static void broadcastMessage(String sender, String message) {
    userUsernameMap.keySet().stream().filter(Session::isOpen).forEach(session -> {
        try {
            session.send(
                new JSONObject()
                    .put("userMessage", createHtmlMessageFromSender(sender, message))
                    .put("userlist", userUsernameMap.values()).toString()
            );
        } catch (Exception e) {
            e.printStackTrace();
        }
    });
}
 
Example 38
Project: javafx-dataviewer   File: ChartsOpenedConnections.java   View source code 5 votes vote down vote up
public void sendMessage(int target, String payload) {
	for (Session session : openedSessions.get(target)) {
		try {
			session.getRemote().sendString(payload);
		} catch (IOException ex) {
			logger.error("IOException : ", ex);
		}
	}

	if (openedSessions.get(target).isEmpty()) {
		logger.debug("Keeped unsent message for : {}", target);
		unsentMessagesMap.put(target, payload);
	}
}
 
Example 39
Project: CasseroleLib   File: CasseroleDriverViewStreamerSocket.java   View source code 5 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
   public void onWebSocketConnect(Session sess) {

       super.onWebSocketConnect(sess);
       // On client connect, broadcast the configuration which has been (presumably) set up
       // already.
       if (isConnected()) {
           try {
               JSONObject full_obj = new JSONObject();
               JSONArray data_array = new JSONArray();

               // Package all data array elements into a JSON array
               for (DriverViewObject obj : CasseroleDriverView.getAllObjects()) {
                   data_array.add(obj.getInitJsonObj());
               }

               full_obj.put("step", "init");
               full_obj.put("obj_array", data_array);
               getRemote().sendString(full_obj.toJSONString());

           } catch (IOException e) {
               e.printStackTrace(System.err);
           }
       }

       // Start broadcasting data at the right rate. Delay a few period before broadcast start.
       updater.scheduleAtFixedRate(new dataBroadcastTask(), updatePeriodMS * 10, updatePeriodMS);
   }
 
Example 40
Project: CasseroleLib   File: CasseroleStateStreamerSocket.java   View source code 5 votes vote down vote up
@Override
public void onWebSocketConnect(Session sess) {

    super.onWebSocketConnect(sess);
    // On client connect, begin new task to braodcast data at 1 second intervals
    test_data = 0;
    updater.scheduleAtFixedRate(new dataBroadcastTask(), 0, updatePeriodMS);
}