Search in sources :

Example 1 with WebSocket

use of io.vertx.core.http.WebSocket in project incubator-servicecomb-java-chassis by apache.

the class TestConfigCenterClient method testConfigRefresh.

@SuppressWarnings("unchecked")
@Test
public void testConfigRefresh() {
    ConfigCenterConfigurationSourceImpl impl = new ConfigCenterConfigurationSourceImpl();
    impl.init(ConfigUtil.createLocalConfig());
    UpdateHandler updateHandler = impl.new UpdateHandler();
    HttpClientRequest request = Mockito.mock(HttpClientRequest.class);
    Mockito.when(request.headers()).thenReturn(MultiMap.caseInsensitiveMultiMap());
    Buffer rsp = Mockito.mock(Buffer.class);
    Mockito.when(rsp.toString()).thenReturn("{\"application\":{\"2\":\"2\",\"aa\":\"1\"},\"vmalledge\":{\"aa\":\"3\"}}");
    HttpClientResponse event = Mockito.mock(HttpClientResponse.class);
    Mockito.when(event.bodyHandler(Mockito.any(Handler.class))).then(invocation -> {
        Handler<Buffer> handler = invocation.getArgumentAt(0, Handler.class);
        handler.handle(rsp);
        return null;
    });
    Mockito.when(event.statusCode()).thenReturn(200);
    Buffer buf = Mockito.mock(Buffer.class);
    Mockito.when(buf.toJsonObject()).thenReturn(new JsonObject("{\"action\":\"UPDATE\",\"key\":\"vmalledge\",\"value\":\"{\\\"aa\\\":\\\"3\\\"}\"}"));
    WebSocket websocket = Mockito.mock(WebSocket.class);
    Mockito.when(websocket.handler(Mockito.any(Handler.class))).then(invocation -> {
        Handler<Buffer> handler = invocation.getArgumentAt(0, Handler.class);
        handler.handle(buf);
        return websocket;
    });
    HttpClient httpClient = Mockito.mock(HttpClient.class);
    Mockito.when(httpClient.get(Mockito.anyInt(), Mockito.anyString(), Mockito.anyString(), Mockito.any(Handler.class))).then(invocation -> {
        Handler<HttpClientResponse> handler = invocation.getArgumentAt(3, Handler.class);
        handler.handle(event);
        return request;
    });
    Mockito.when(httpClient.websocket(Mockito.anyInt(), Mockito.anyString(), Mockito.anyString(), Mockito.any(MultiMap.class), Mockito.any(Handler.class), Mockito.any(Handler.class))).then(invocation -> {
        Handler<WebSocket> handler = invocation.getArgumentAt(4, Handler.class);
        handler.handle(websocket);
        return null;
    });
    new MockUp<HttpClientWithContext>() {

        @Mock
        public void runOnContext(RunHandler handler) {
            handler.run(httpClient);
        }
    };
    ConfigCenterClient cc = new ConfigCenterClient(updateHandler);
    ParseConfigUtils parseConfigUtils = new ParseConfigUtils(updateHandler);
    MemberDiscovery memberdis = new MemberDiscovery(Arrays.asList("http://configcentertest:30103"));
    ConfigRefresh refresh = cc.new ConfigRefresh(parseConfigUtils, memberdis);
    refresh.run();
    Map<String, Object> flatItems = Deencapsulation.getField(parseConfigUtils, "flatItems");
    Assert.assertEquals(2, flatItems.size());
    Deencapsulation.setField(cc, "refreshMode", 0);
    refresh.run();
}
Also used : Buffer(io.vertx.core.buffer.Buffer) UpdateHandler(org.apache.servicecomb.config.archaius.sources.ConfigCenterConfigurationSourceImpl.UpdateHandler) ConfigCenterConfigurationSourceImpl(org.apache.servicecomb.config.archaius.sources.ConfigCenterConfigurationSourceImpl) RunHandler(org.apache.servicecomb.foundation.vertx.client.http.HttpClientWithContext.RunHandler) UpdateHandler(org.apache.servicecomb.config.archaius.sources.ConfigCenterConfigurationSourceImpl.UpdateHandler) Handler(io.vertx.core.Handler) JsonObject(io.vertx.core.json.JsonObject) MockUp(mockit.MockUp) RunHandler(org.apache.servicecomb.foundation.vertx.client.http.HttpClientWithContext.RunHandler) WebSocket(io.vertx.core.http.WebSocket) MultiMap(io.vertx.core.MultiMap) HttpClientRequest(io.vertx.core.http.HttpClientRequest) ConfigRefresh(org.apache.servicecomb.config.client.ConfigCenterClient.ConfigRefresh) HttpClientResponse(io.vertx.core.http.HttpClientResponse) HttpClient(io.vertx.core.http.HttpClient) JsonObject(io.vertx.core.json.JsonObject) Test(org.junit.Test)

Example 2 with WebSocket

use of io.vertx.core.http.WebSocket in project vertx-web by vert-x3.

the class SockJSHandlerTest method testCombineBinaryContinuationFramesRawWebSocket.

/**
 * Writing multiple continuation frames from the client side should result in a single message on the server side
 * after the frames are re-combined
 */
@Test
public void testCombineBinaryContinuationFramesRawWebSocket() throws InterruptedException {
    String serverPath = "/combine";
    AtomicReference<Buffer> serverReceivedMessage = new AtomicReference<>();
    setupSockJsServer(serverPath, (sock, requestBuffer) -> {
        serverReceivedMessage.set(requestBuffer);
        sock.write(Buffer.buffer("reply"));
        sock.close();
    });
    Buffer largeMessage = Buffer.buffer(TestUtils.randomAlphaString(30));
    WebSocketFrame frame1 = WebSocketFrame.binaryFrame(largeMessage.slice(0, 10), false);
    WebSocketFrame frame2 = WebSocketFrame.continuationFrame(largeMessage.slice(10, 20), false);
    WebSocketFrame frame3 = WebSocketFrame.continuationFrame(largeMessage.slice(20, largeMessage.length()), true);
    WebSocket ws = setupRawWebsocketClient(serverPath);
    ws.writeFrame(frame1);
    ws.writeFrame(frame2);
    ws.writeFrame(frame3);
    await(5, TimeUnit.SECONDS);
    assertEquals("Server did not combine continuation frames correctly", largeMessage, serverReceivedMessage.get());
}
Also used : Buffer(io.vertx.core.buffer.Buffer) AtomicReference(java.util.concurrent.atomic.AtomicReference) WebSocketFrame(io.vertx.core.http.WebSocketFrame) WebSocket(io.vertx.core.http.WebSocket) Test(org.junit.Test)

Example 3 with WebSocket

use of io.vertx.core.http.WebSocket in project vertx-web by vert-x3.

the class SockJSHandlerTest method testSplitLargeReplySockJs.

@Test
public void testSplitLargeReplySockJs() throws InterruptedException {
    String serverPath = "/large-reply-sockjs";
    String largeMessage = TestUtils.randomAlphaString(65536 * 2);
    Buffer largeReplyBuffer = Buffer.buffer(largeMessage);
    setupSockJsServer(serverPath, (sock, requestBuffer) -> {
        sock.write(largeReplyBuffer);
        sock.close();
    });
    List<Buffer> receivedMessages = new ArrayList<>();
    WebSocket openedWebSocket = setupSockJsClient(serverPath, receivedMessages);
    String messageToSend = "[\"hello\"]";
    openedWebSocket.writeFrame(WebSocketFrame.textFrame(messageToSend, true));
    await(5, TimeUnit.SECONDS);
    int receivedReplyCount = receivedMessages.size();
    assertTrue("Should have received > 2 reply frame, actually received " + receivedReplyCount, receivedReplyCount > 2);
    Buffer expectedReplyBuffer = Buffer.buffer("a[\"").appendBuffer(largeReplyBuffer).appendBuffer(Buffer.buffer("\"]"));
    Buffer clientReplyBuffer = combineReplies(receivedMessages.subList(0, receivedMessages.size() - 1));
    assertEquals(String.format("Combined reply on client (length %s) should equal message from server (%s)", clientReplyBuffer.length(), expectedReplyBuffer.length()), expectedReplyBuffer, clientReplyBuffer);
    Buffer finalMessage = receivedMessages.get(receivedMessages.size() - 1);
    assertEquals("Final message should have been a close", SOCKJS_CLOSE_REPLY, finalMessage);
}
Also used : Buffer(io.vertx.core.buffer.Buffer) ArrayList(java.util.ArrayList) WebSocket(io.vertx.core.http.WebSocket) Test(org.junit.Test)

Example 4 with WebSocket

use of io.vertx.core.http.WebSocket in project vertx-web by vert-x3.

the class SockJSHandlerTest method setupSockJsClient.

/**
 * This sets up a handler on the websocket
 */
private WebSocket setupSockJsClient(String serverPath, List<Buffer> receivedMessagesCollector) throws InterruptedException {
    String requestURI = serverPath + "/000/000/websocket";
    AtomicReference<WebSocket> openedWebSocketReference = new AtomicReference<>();
    CountDownLatch openSocketCountDown = new CountDownLatch(1);
    client.websocket(requestURI, ws -> {
        openedWebSocketReference.set(ws);
        ws.handler(replyBuffer -> {
            log.debug("Client received " + replyBuffer);
            String textReply = replyBuffer.toString();
            if ("o".equals(textReply)) {
                openSocketCountDown.countDown();
            } else {
                receivedMessagesCollector.add(replyBuffer);
            }
        });
        ws.endHandler(v -> testComplete());
        ws.exceptionHandler(this::fail);
    });
    openSocketCountDown.await(5, TimeUnit.SECONDS);
    return openedWebSocketReference.get();
}
Also used : AtomicReference(java.util.concurrent.atomic.AtomicReference) CountDownLatch(java.util.concurrent.CountDownLatch) WebSocket(io.vertx.core.http.WebSocket)

Example 5 with WebSocket

use of io.vertx.core.http.WebSocket in project vertx-web by vert-x3.

the class SockJSHandlerTest method testCombineTextFrameSockJs.

@Test
public void testCombineTextFrameSockJs() throws InterruptedException {
    String serverPath = "/text-combine-sockjs";
    setupSockJsServer(serverPath, this::echoRequest);
    List<Buffer> receivedMessages = new ArrayList<>();
    WebSocket openedWebSocket = setupSockJsClient(serverPath, receivedMessages);
    Buffer largeMessage = Buffer.buffer("[\"" + TestUtils.randomAlphaString(30) + "\"]");
    WebSocketFrame frame1 = new WebSocketFrameImpl(FrameType.TEXT, largeMessage.slice(0, 10).getByteBuf(), false);
    WebSocketFrame frame2 = WebSocketFrame.continuationFrame(largeMessage.slice(10, 20), false);
    WebSocketFrame frame3 = WebSocketFrame.continuationFrame(largeMessage.slice(20, largeMessage.length()), true);
    log.debug("Client sending " + frame1.textData());
    openedWebSocket.writeFrame(frame1);
    log.debug("Client sending " + frame2.textData());
    openedWebSocket.writeFrame(frame2);
    log.debug("Client sending " + frame3.textData());
    openedWebSocket.writeFrame(frame3);
    await(5, TimeUnit.SECONDS);
    assertEquals("Client should have received 2 messages: the reply and the close.", 2, receivedMessages.size());
    Buffer expectedReply = Buffer.buffer("a" + largeMessage.toString());
    assertEquals("Client reply should have matched request", expectedReply, receivedMessages.get(0));
    assertEquals("Final message should have been a close", SOCKJS_CLOSE_REPLY, receivedMessages.get(1));
}
Also used : Buffer(io.vertx.core.buffer.Buffer) WebSocketFrameImpl(io.vertx.core.http.impl.ws.WebSocketFrameImpl) ArrayList(java.util.ArrayList) WebSocketFrame(io.vertx.core.http.WebSocketFrame) WebSocket(io.vertx.core.http.WebSocket) Test(org.junit.Test)

Aggregations

WebSocket (io.vertx.core.http.WebSocket)13 Buffer (io.vertx.core.buffer.Buffer)8 Test (org.junit.Test)8 AtomicReference (java.util.concurrent.atomic.AtomicReference)5 ArrayList (java.util.ArrayList)4 WebSocketFrame (io.vertx.core.http.WebSocketFrame)3 JsonObject (io.vertx.core.json.JsonObject)3 CountDownLatch (java.util.concurrent.CountDownLatch)3 Handler (io.vertx.core.Handler)2 MultiMap (io.vertx.core.MultiMap)2 HttpClient (io.vertx.core.http.HttpClient)2 WebSocketFrameImpl (io.vertx.core.http.impl.ws.WebSocketFrameImpl)2 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)2 BufferFactoryImpl (io.vertx.core.buffer.impl.BufferFactoryImpl)1 CaseInsensitiveHeaders (io.vertx.core.http.CaseInsensitiveHeaders)1 HttpClientOptions (io.vertx.core.http.HttpClientOptions)1 HttpClientRequest (io.vertx.core.http.HttpClientRequest)1 HttpClientResponse (io.vertx.core.http.HttpClientResponse)1 RequestOptions (io.vertx.core.http.RequestOptions)1 FrameType (io.vertx.core.http.impl.FrameType)1