Search in sources :

Example 1 with WebSocket

use of okhttp3.WebSocket in project Rocket.Chat.Android by RocketChat.

the class RxWebSocket method connect.

public ConnectableFlowable<RxWebSocketCallback.Base> connect(String url) {
    final Request request = new Request.Builder().url(url).build();
    return Flowable.create((FlowableOnSubscribe<RxWebSocketCallback.Base>) emitter -> httpClient.newWebSocket(request, new WebSocketListener() {

        @Override
        public void onOpen(WebSocket webSocket, Response response) {
            RxWebSocket.this.webSocket = webSocket;
            emitter.onNext(new RxWebSocketCallback.Open(RxWebSocket.this.webSocket, response));
        }

        @Override
        public void onFailure(WebSocket webSocket, Throwable err, Response response) {
            try {
                emitter.onError(new RxWebSocketCallback.Failure(webSocket, err, response));
            } catch (OnErrorNotImplementedException ex) {
                RCLog.w(ex, "OnErrorNotImplementedException ignored");
            }
        }

        @Override
        public void onMessage(WebSocket webSocket, String text) {
            emitter.onNext(new RxWebSocketCallback.Message(webSocket, text));
        }

        @Override
        public void onClosed(WebSocket webSocket, int code, String reason) {
            emitter.onNext(new RxWebSocketCallback.Close(webSocket, code, reason));
            emitter.onComplete();
        }
    }), BackpressureStrategy.BUFFER).publish();
}
Also used : FlowableOnSubscribe(io.reactivex.FlowableOnSubscribe) WebSocketListener(okhttp3.WebSocketListener) Request(okhttp3.Request) OnErrorNotImplementedException(io.reactivex.exceptions.OnErrorNotImplementedException) WebSocket(okhttp3.WebSocket) Response(okhttp3.Response)

Example 2 with WebSocket

use of okhttp3.WebSocket in project okhttp by square.

the class RealWebSocket method connect.

public void connect(OkHttpClient client) {
    client = client.newBuilder().protocols(ONLY_HTTP1).build();
    final int pingIntervalMillis = client.pingIntervalMillis();
    final Request request = originalRequest.newBuilder().header("Upgrade", "websocket").header("Connection", "Upgrade").header("Sec-WebSocket-Key", key).header("Sec-WebSocket-Version", "13").build();
    call = Internal.instance.newWebSocketCall(client, request);
    call.enqueue(new Callback() {

        @Override
        public void onResponse(Call call, Response response) {
            try {
                checkResponse(response);
            } catch (ProtocolException e) {
                failWebSocket(e, response);
                closeQuietly(response);
                return;
            }
            // Promote the HTTP streams into web socket streams.
            StreamAllocation streamAllocation = Internal.instance.streamAllocation(call);
            // Prevent connection pooling!
            streamAllocation.noNewStreams();
            Streams streams = streamAllocation.connection().newWebSocketStreams(streamAllocation);
            // Process all web socket messages.
            try {
                listener.onOpen(RealWebSocket.this, response);
                String name = "OkHttp WebSocket " + request.url().redact();
                initReaderAndWriter(name, pingIntervalMillis, streams);
                streamAllocation.connection().socket().setSoTimeout(0);
                loopReader();
            } catch (Exception e) {
                failWebSocket(e, null);
            }
        }

        @Override
        public void onFailure(Call call, IOException e) {
            failWebSocket(e, null);
        }
    });
}
Also used : Response(okhttp3.Response) StreamAllocation(okhttp3.internal.connection.StreamAllocation) Call(okhttp3.Call) ProtocolException(java.net.ProtocolException) Callback(okhttp3.Callback) Request(okhttp3.Request) ByteString(okio.ByteString) IOException(java.io.IOException) IOException(java.io.IOException) ProtocolException(java.net.ProtocolException)

Example 3 with WebSocket

use of okhttp3.WebSocket in project okhttp by square.

the class MockWebServer method handleWebSocketUpgrade.

private void handleWebSocketUpgrade(Socket socket, BufferedSource source, BufferedSink sink, RecordedRequest request, MockResponse response) throws IOException {
    String key = request.getHeader("Sec-WebSocket-Key");
    response.setHeader("Sec-WebSocket-Accept", WebSocketProtocol.acceptHeader(key));
    writeHttpResponse(socket, sink, response);
    // Adapt the request and response into our Request and Response domain model.
    String scheme = request.getTlsVersion() != null ? "https" : "http";
    // Has host and port.
    String authority = request.getHeader("Host");
    final Request fancyRequest = new Request.Builder().url(scheme + "://" + authority + "/").headers(request.getHeaders()).build();
    final Response fancyResponse = new Response.Builder().code(Integer.parseInt(response.getStatus().split(" ")[1])).message(response.getStatus().split(" ", 3)[2]).headers(response.getHeaders()).request(fancyRequest).protocol(Protocol.HTTP_1_1).build();
    final CountDownLatch connectionClose = new CountDownLatch(1);
    RealWebSocket.Streams streams = new RealWebSocket.Streams(false, source, sink) {

        @Override
        public void close() {
            connectionClose.countDown();
        }
    };
    RealWebSocket webSocket = new RealWebSocket(fancyRequest, response.getWebSocketListener(), new SecureRandom());
    response.getWebSocketListener().onOpen(webSocket, fancyResponse);
    String name = "MockWebServer WebSocket " + request.getPath();
    webSocket.initReaderAndWriter(name, 0, streams);
    try {
        webSocket.loopReader();
        // Even if messages are no longer being read we need to wait for the connection close signal.
        try {
            connectionClose.await();
        } catch (InterruptedException ignored) {
        }
    } catch (IOException e) {
        webSocket.failWebSocket(e, null);
    } finally {
        closeQuietly(sink);
        closeQuietly(source);
    }
}
Also used : Response(okhttp3.Response) RealWebSocket(okhttp3.internal.ws.RealWebSocket) Request(okhttp3.Request) SecureRandom(java.security.SecureRandom) ByteString(okio.ByteString) InterruptedIOException(java.io.InterruptedIOException) IOException(java.io.IOException) CountDownLatch(java.util.concurrent.CountDownLatch)

Example 4 with WebSocket

use of okhttp3.WebSocket in project couchbase-lite-android by couchbase.

the class CBLWebSocket method newRequest.

private Request newRequest() {
    Request.Builder builder = new Request.Builder();
    // Sets the URL target of this request.
    builder.url(uri.toString());
    // Set/update the "Host" header:
    String host = uri.getHost();
    if (uri.getPort() != -1)
        host = String.format(Locale.ENGLISH, "%s:%d", host, uri.getPort());
    builder.header("Host", host);
    // Construct the HTTP request:
    if (options != null) {
        // Extra Headers
        Map<String, Object> extraHeaders = (Map<String, Object>) options.get(kC4ReplicatorOptionExtraHeaders);
        if (extraHeaders != null) {
            for (Map.Entry<String, Object> entry : extraHeaders.entrySet()) {
                builder.header(entry.getKey(), entry.getValue().toString());
            }
        }
        // Cookies:
        String cookieString = (String) options.get(kC4ReplicatorOptionCookies);
        if (cookieString != null)
            builder.addHeader("Cookie", cookieString);
    }
    // Configure WebSocket related headers:
    String protocols = (String) options.get(kC4SocketOptionWSProtocols);
    if (protocols != null) {
        builder.header("Sec-WebSocket-Protocol", protocols);
    }
    return builder.build();
}
Also used : Request(okhttp3.Request) ByteString(okio.ByteString) HashMap(java.util.HashMap) Map(java.util.Map)

Example 5 with WebSocket

use of okhttp3.WebSocket in project syndesis by syndesisio.

the class EventsITCase method wsEventsWithToken.

@Test
public void wsEventsWithToken() throws Exception {
    OkHttpClient client = new OkHttpClient();
    ResponseEntity<EventMessage> r1 = post("/api/v1/event/reservations", null, EventMessage.class);
    assertThat(r1.getBody().getEvent().get()).as("event").isEqualTo("uuid");
    String uuid = (String) r1.getBody().getData().get();
    assertThat(uuid).as("data").isNotNull();
    String uriTemplate = EventBusToWebSocket.DEFAULT_PATH + "/" + uuid;
    String url = resolveURI(uriTemplate).toString().replaceFirst("^http", "ws");
    Request request = new Request.Builder().url(url).addHeader(HttpHeaders.AUTHORIZATION, "Bearer " + tokenRule.validToken()).build();
    // lets setup an event handler that we can inspect events on..
    WebSocketListener listener = recorder(mock(WebSocketListener.class), WebSocketListener.class);
    List<Recordings.Invocation> invocations = recordedInvocations(listener);
    CountDownLatch countDownLatch = resetRecorderLatch(listener, 2);
    WebSocket ws = client.newWebSocket(request, listener);
    // We auto get a message letting us know we connected.
    assertThat(countDownLatch.await(1000, TimeUnit.SECONDS)).isTrue();
    assertThat(invocations.get(0).getMethod().getName()).isEqualTo("onOpen");
    assertThat(invocations.get(1).getMethod().getName()).isEqualTo("onMessage");
    assertThat(invocations.get(1).getArgs()[1]).isEqualTo(EventMessage.of("message", "connected").toJson());
    // ///////////////////////////////////////////////////
    // Test that we get notified of created entities
    // ///////////////////////////////////////////////////
    invocations.clear();
    countDownLatch = resetRecorderLatch(listener, 1);
    Integration integration = new Integration.Builder().id("1002").name("test").build();
    post("/api/v1/integrations", integration, Integration.class);
    assertThat(countDownLatch.await(1000, TimeUnit.SECONDS)).isTrue();
    assertThat(invocations.get(0).getMethod().getName()).isEqualTo("onMessage");
    assertThat(invocations.get(0).getArgs()[1]).isEqualTo(EventMessage.of("change-event", ChangeEvent.of("created", "integration", "1002").toJson()).toJson());
    ws.close(1000, "closing");
}
Also used : WebSocketListener(okhttp3.WebSocketListener) Integration(io.syndesis.common.model.integration.Integration) OkHttpClient(okhttp3.OkHttpClient) Request(okhttp3.Request) CountDownLatch(java.util.concurrent.CountDownLatch) WebSocket(okhttp3.WebSocket) EventMessage(io.syndesis.common.model.EventMessage) Test(org.junit.Test)

Aggregations

WebSocket (okhttp3.WebSocket)41 MockResponse (mockwebserver3.MockResponse)27 Test (org.junit.jupiter.api.Test)27 WebSocketListener (okhttp3.WebSocketListener)24 ByteString (okio.ByteString)19 Request (okhttp3.Request)15 Response (okhttp3.Response)8 OkHttpClient (okhttp3.OkHttpClient)7 IOException (java.io.IOException)4 HashMap (java.util.HashMap)4 Map (java.util.Map)4 CountDownLatch (java.util.concurrent.CountDownLatch)4 Test (org.junit.Test)4 RecordedRequest (mockwebserver3.RecordedRequest)3 InputStream (java.io.InputStream)2 SecureRandom (java.security.SecureRandom)2 Open (api.cobinhood.websocket.models.Open)1 GsonBuilder (com.google.gson.GsonBuilder)1 JsonObject (com.google.gson.JsonObject)1 WatsonServiceUnitTest (com.ibm.watson.developer_cloud.WatsonServiceUnitTest)1