org.eclipse.jetty.websocket.api.RemoteEndpoint Java Examples

The following examples show how to use org.eclipse.jetty.websocket.api.RemoteEndpoint. 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: JettyWebSocketHandlerTest.java    From engine.io-server-java with MIT License 6 votes vote down vote up
@Test
public void testSocket_write_string() throws IOException {
    final String queryString = ParseQS.encode(new HashMap<String, String>() {{
        put("transport", WebSocket.NAME);
    }});
    final UpgradeRequest upgradeRequest = Mockito.mock(UpgradeRequest.class);
    final RemoteEndpoint remoteEndpoint = Mockito.mock(RemoteEndpoint.class);
    final Session session = Mockito.mock(Session.class);
    final EngineIoServer server = Mockito.spy(new EngineIoServer());

    Mockito.doAnswer(invocationOnMock -> queryString).when(upgradeRequest).getQueryString();
    Mockito.doAnswer(invocationOnMock -> upgradeRequest).when(session).getUpgradeRequest();
    Mockito.doAnswer(invocationOnMock -> remoteEndpoint).when(session).getRemote();
    Mockito.doAnswer(invocationOnMock -> null).when(server).handleWebSocket(Mockito.any(EngineIoWebSocket.class));

    final JettyWebSocketHandler handler = new JettyWebSocketHandler(server);
    handler.onWebSocketConnect(session);

    final String message = "FooBar";
    handler.write(message);
    Mockito.verify(remoteEndpoint, Mockito.times(1))
            .sendString(Mockito.eq(message));
}
 
Example #2
Source File: JettyWebSocketHandlerTest.java    From engine.io-server-java with MIT License 6 votes vote down vote up
@Test
public void testSocket_write_binary() throws IOException {
    final String queryString = ParseQS.encode(new HashMap<String, String>() {{
        put("transport", WebSocket.NAME);
    }});
    final UpgradeRequest upgradeRequest = Mockito.mock(UpgradeRequest.class);
    final RemoteEndpoint remoteEndpoint = Mockito.mock(RemoteEndpoint.class);
    final Session session = Mockito.mock(Session.class);
    final EngineIoServer server = Mockito.spy(new EngineIoServer());

    Mockito.doAnswer(invocationOnMock -> queryString).when(upgradeRequest).getQueryString();
    Mockito.doAnswer(invocationOnMock -> upgradeRequest).when(session).getUpgradeRequest();
    Mockito.doAnswer(invocationOnMock -> remoteEndpoint).when(session).getRemote();
    Mockito.doAnswer(invocationOnMock -> null).when(server).handleWebSocket(Mockito.any(EngineIoWebSocket.class));

    final JettyWebSocketHandler handler = new JettyWebSocketHandler(server);
    handler.onWebSocketConnect(session);

    final byte[] message = new byte[16];
    (new Random()).nextBytes(message);
    handler.write(message);
    Mockito.verify(remoteEndpoint, Mockito.times(1))
            .sendBytes(Mockito.any(ByteBuffer.class));
}
 
Example #3
Source File: WebSocketSessionImpl.java    From purplejs with Apache License 2.0 6 votes vote down vote up
@Override
public void send( final String message )
{
    final RemoteEndpoint endpoint = getRemote();
    if ( endpoint == null )
    {
        return;
    }

    try
    {
        endpoint.sendString( message );
    }
    catch ( final Exception e )
    {
        LOG.log( Level.SEVERE, "Failed to send web-socket message", e );
    }
}
 
Example #4
Source File: WebSocketSessionImpl.java    From purplejs with Apache License 2.0 6 votes vote down vote up
@Override
public void send( final ByteSource bytes )
{
    final RemoteEndpoint endpoint = getRemote();
    if ( endpoint == null )
    {
        return;
    }

    try
    {
        final ByteBuffer buffer = ByteBuffer.wrap( bytes.read() );
        endpoint.sendBytes( buffer );
    }
    catch ( final Exception e )
    {
        LOG.log( Level.SEVERE, "Failed to send web-socket message", e );
    }
}
 
Example #5
Source File: SonyAudioClientSocket.java    From smarthome with Eclipse Public License 2.0 6 votes vote down vote up
public boolean isConnected() {
    if (session == null || !session.isOpen()) {
        connected = false;
        return connected;
    }

    RemoteEndpoint remote = session.getRemote();

    ByteBuffer payload = ByteBuffer.allocate(4).putInt(ping++);
    try {
        remote.sendPing(payload);
    } catch (IOException e) {
        logger.error("Connection to {} lost {}", uri, e);
        connected = false;
    }

    return connected;
}
 
Example #6
Source File: EchoSocket.java    From knox with Apache License 2.0 6 votes vote down vote up
@Override
public void onWebSocketText(String message) {
  if (isNotConnected()) {
    return;
  }

  try {
    RemoteEndpoint remote = getRemote();
    remote.sendString(message, null);
    if (remote.getBatchMode() == BatchMode.ON) {
      remote.flush();
    }
  } catch (IOException x) {
    throw new RuntimeIOException(x);
  }
}
 
Example #7
Source File: EchoSocket.java    From knox with Apache License 2.0 6 votes vote down vote up
@Override
public void onWebSocketBinary(byte[] payload, int offset, int len) {
  if (isNotConnected()) {
    return;
  }

  try {
    RemoteEndpoint remote = getRemote();
    remote.sendBytes(BufferUtil.toBuffer(payload, offset, len), null);
    if (remote.getBatchMode() == BatchMode.ON) {
      remote.flush();
    }
  } catch (IOException x) {
    throw new RuntimeIOException(x);
  }
}
 
Example #8
Source File: BadSocket.java    From knox with Apache License 2.0 6 votes vote down vote up
@Override
public void onWebSocketBinary(byte[] payload, int offset, int len) {
  if (isNotConnected()) {
    return;
  }

  try {
    RemoteEndpoint remote = getRemote();
    remote.sendBytes(BufferUtil.toBuffer(payload, offset, len), null);
    if (remote.getBatchMode() == BatchMode.ON) {
      remote.flush();
    }
  } catch (IOException x) {
    throw new RuntimeIOException(x);
  }
}
 
Example #9
Source File: WebSocketRunner.java    From codenjoy with GNU General Public License v3.0 6 votes vote down vote up
@OnWebSocketMessage
public void onMessage(String data) {
    try {
        Matcher matcher = BOARD_PATTERN.matcher(data);
        if (!matcher.matches()) {
            throw new IllegalArgumentException("Unexpected board format, should be: " + BOARD_FORMAT);
        }

        board.forString(matcher.group(1));
        print("Board: \n" + board);

        String answer = solver.get(board);
        print("Answer: " + answer);

        RemoteEndpoint remote = session.getRemote();
        if (remote == null) { // TODO to understand why this can happen?
            WebSocketRunner.this.tryToConnect();
            return;
        }
        remote.sendString(answer);
    } catch (Exception e) {
        print("Error processing data: " + data);
        print(e);
    }
    printBreak();
}
 
Example #10
Source File: WebsocketServerInitiatedPingTest.java    From knox with Apache License 2.0 6 votes vote down vote up
@Override
public void onWebSocketConnect(Session sess) {
  super.onWebSocketConnect(sess);
  try {
    Thread.sleep(1000);
  } catch (Exception e) {
  }
  final String textMessage = "PingPong";
  final ByteBuffer binaryMessage = ByteBuffer.wrap(
             textMessage.getBytes(StandardCharsets.UTF_8));

  try {
    RemoteEndpoint remote = getRemote();
    remote.sendPing(binaryMessage);
    if (remote.getBatchMode() == BatchMode.ON) {
      remote.flush();
    }
  } catch (IOException x) {
    throw new RuntimeIOException(x);
  }
}
 
Example #11
Source File: JettyWebSocketSession.java    From java-technology-stack with MIT License 5 votes vote down vote up
private RemoteEndpoint getRemoteEndpoint() throws IOException {
	try {
		return getNativeSession().getRemote();
	}
	catch (WebSocketException ex) {
		throw new IOException("Unable to obtain RemoteEndpoint in session " + getId(), ex);
	}
}
 
Example #12
Source File: KafkaClient.java    From opensoc-streaming with Apache License 2.0 5 votes vote down vote up
public KafkaClient(String zooKeeper, String groupId, String topic, RemoteEndpoint remote) 
   {
       this.consumer = kafka.consumer.Consumer.createJavaConsumerConnector(
               createConsumerConfig(zooKeeper, groupId ));
       
       this.topic = topic;
       this.remote = remote;
}
 
Example #13
Source File: WebSocketHandlerTest.java    From roboconf-platform with Apache License 2.0 5 votes vote down vote up
private WebSocketHandler configuredHandler() {

		this.session = Mockito.mock( Session.class );
		this.remoteEndpoint = Mockito.mock( RemoteEndpoint.class );
		Mockito.when( this.session.getRemote()).thenReturn( this.remoteEndpoint );

		WebSocketHandler.addSession( this.session );
		WebSocketHandler handler = new WebSocketHandler();

		return handler;
	}
 
Example #14
Source File: HttpDmClientTest.java    From roboconf-platform with Apache License 2.0 5 votes vote down vote up
@Test
public void testProcess() throws Exception {

	HttpRoutingContext routingContext = new HttpRoutingContext();
	HttpDmClient httpDmClient = new HttpDmClient( routingContext );

	// Not connected => no processing
	Message message = Mockito.mock( Message.class );
	Session session = Mockito.mock( Session.class );
	Mockito.when( session.isOpen()).thenReturn( false );

	httpDmClient.process( session, message );
	Mockito.verifyZeroInteractions( message );
	Mockito.verify( session, Mockito.only()).isOpen();

	// Connected => processing...
	Mockito.reset( session );
	Future<Void> future = Mockito.mock( Future.class );
	RemoteEndpoint remote = Mockito.mock( RemoteEndpoint.class );
	Mockito.when( remote.sendBytesByFuture( Mockito.any( ByteBuffer.class ) )).thenReturn( future );

	Mockito.when( session.getRemote()).thenReturn( remote );
	Mockito.when( session.isOpen()).thenReturn( true );

	httpDmClient.process( session, message );

	Mockito.verifyZeroInteractions( message );
	Mockito.verify( session, Mockito.times( 1 )).isOpen();
	Mockito.verify( session, Mockito.times( 1 )).getRemote();
	Mockito.verifyNoMoreInteractions( session );
}
 
Example #15
Source File: WebsocketServerInitiatedMessageTest.java    From knox with Apache License 2.0 5 votes vote down vote up
@Override
public void onWebSocketConnect(Session sess) {
  super.onWebSocketConnect(sess);

  try {
    RemoteEndpoint remote = getRemote();
    remote.sendString("echo", null);
    if (remote.getBatchMode() == BatchMode.ON) {
      remote.flush();
    }
  } catch (IOException x) {
    throw new RuntimeIOException(x);
  }
}
 
Example #16
Source File: ProxyWebSocketAdapter.java    From knox with Apache License 2.0 5 votes vote down vote up
private void flushBufferedMessages(final RemoteEndpoint remote) throws IOException {
  LOG.debugLog("Flushing old buffered messages");
  for(String obj:messageBuffer) {
    LOG.debugLog("Sending old buffered message [From Backend <---]: " + obj);
    remote.sendString(obj);
  }
  messageBuffer.clear();
}
 
Example #17
Source File: PlayerTransportTest.java    From codenjoy with GNU General Public License v3.0 5 votes vote down vote up
private PlayerSocket connectWebSocketClient(String authId) {
    when(authentication.authenticate(any(HttpServletRequest.class))).thenReturn(authId);

    PlayerSocket webSocket = createWebSocket();

    if (webSocket == null) return null;

    Session session = mock(Session.class);
    when(session.isOpen()).thenReturn(true);
    RemoteEndpoint remote = mock(RemoteEndpoint.class);
    when(session.getRemote()).thenReturn(remote);
    webSocket.onWebSocketConnect(session);
    return webSocket;
}
 
Example #18
Source File: WebSocketSessionImpl.java    From purplejs with Apache License 2.0 5 votes vote down vote up
private RemoteEndpoint getRemote()
{
    try
    {
        return this.raw.getRemote();
    }
    catch ( final Exception e )
    {
        return null;
    }
}
 
Example #19
Source File: BrowserVisualization.java    From coordination_oru with GNU General Public License v3.0 5 votes vote down vote up
private void sendMessage(String text) {
	if (BrowserVisualizationSocket.ENDPOINTS != null) {
		for (RemoteEndpoint rep : BrowserVisualizationSocket.ENDPOINTS) {
			try {
				rep.sendString(text);
			}
			catch(IOException e) { e.printStackTrace(); }
		}
	}
}
 
Example #20
Source File: JettyWebSocketSession.java    From spring-analysis-note with MIT License 5 votes vote down vote up
private RemoteEndpoint getRemoteEndpoint() throws IOException {
	try {
		return getNativeSession().getRemote();
	}
	catch (WebSocketException ex) {
		throw new IOException("Unable to obtain RemoteEndpoint in session " + getId(), ex);
	}
}
 
Example #21
Source File: PlayerTransportTest.java    From codenjoy with GNU General Public License v3.0 4 votes vote down vote up
@Test
    public void shouldCollectErrors_whenSendDataToAllWebSocketClients() throws IOException {
        // given
        createServices(PlayerSocket.CLIENT_SEND_FIRST);

        createServerWebSocket("id1");
        createServerWebSocket("id2");
        createServerWebSocket("id3");

        PlayerSocket webSocket1 = connectWebSocketClient("id1");
        PlayerSocket webSocket2 = connectWebSocketClient("id2");
        PlayerSocket webSocket3 = connectWebSocketClient("id3");

        // when client answer
        answerClient(webSocket1);
        answerClient(webSocket2);
        answerClient(webSocket3);

        // simulate errors
        RemoteEndpoint remote1 = webSocket1.getSession().getRemote();
        doThrow(new IOException("Error1")).when(remote1).sendString(anyString());

        RemoteEndpoint remote2 = webSocket2.getSession().getRemote();
        doThrow(new IOException("Error2")).when(remote2).sendString(anyString());

        RemoteEndpoint remote3 = webSocket3.getSession().getRemote();
        doThrow(new IOException("Error3")).when(remote3).sendString(anyString());

        // when send state
//        try { // TODO мы не ловим больше ошибков а потому надо про другому проверить факт недосылки
            transport.sendStateToAll(new LinkedHashMap<String, Integer>() {{
                put("one", 1);
                put("two", 2);
                put("three", 3);
            }});

//            fail("Expected exception");
//        } catch (Exception e) {
//            // then
//            assertEquals("Error during send state to all players: [Error1, Error2, Error3]",
//                    e.getMessage());
//        }
    }
 
Example #22
Source File: SimpleTestProducerSocket.java    From pulsar with Apache License 2.0 4 votes vote down vote up
public RemoteEndpoint getRemote() {
    return this.session.getRemote();
}
 
Example #23
Source File: CmdProduce.java    From pulsar with Apache License 2.0 4 votes vote down vote up
public RemoteEndpoint getRemote() {
    return this.session.getRemote();
}
 
Example #24
Source File: CmdConsume.java    From pulsar with Apache License 2.0 4 votes vote down vote up
public RemoteEndpoint getRemote() {
    return this.session.getRemote();
}
 
Example #25
Source File: SimpleConsumerSocket.java    From pulsar with Apache License 2.0 4 votes vote down vote up
public RemoteEndpoint getRemote() {
    return this.session.getRemote();
}
 
Example #26
Source File: SimpleProducerSocket.java    From pulsar with Apache License 2.0 4 votes vote down vote up
public RemoteEndpoint getRemote() {
    return this.session.getRemote();
}
 
Example #27
Source File: KafkaConsumer.java    From opensoc-streaming with Apache License 2.0 4 votes vote down vote up
public KafkaConsumer( RemoteEndpoint remote, KafkaStream a_stream, int a_threadNumber) 
{
    this.m_threadNumber = a_threadNumber;
    this.m_stream = a_stream;
    this.remote = remote;
}
 
Example #28
Source File: MockSession.java    From buck with Apache License 2.0 4 votes vote down vote up
@Override
public RemoteEndpoint getRemote() {
  return null;
}