Search in sources :

Example 21 with Handler

use of io.vertx.core.Handler in project java-chassis by ServiceComb.

the class TestTcp method testTcpClient.

@Test
public void testTcpClient() throws Exception {
    NetClient oNetClient = new NetClient() {

        @Override
        public boolean isMetricsEnabled() {
            // TODO Auto-generated method stub
            return true;
        }

        @Override
        public NetClient connect(int port, String host, Handler<AsyncResult<NetSocket>> connectHandler) {
            return Mockito.mock(NetClient.class);
        }

        @Override
        public void close() {
        // TODO Auto-generated method stub
        }
    };
    TcpClient oTcpClient = new TcpClient(Mockito.mock(Context.class), oNetClient, "highway://127.2.0.1:8080", new TcpClientConfig());
    oTcpClient.checkTimeout();
    oTcpClient.send(new TcpOutputStream(), 123, Mockito.mock(TcpResonseCallback.class));
    oTcpClient.send(new TcpOutputStream(), 123, Mockito.mock(TcpResonseCallback.class));
    Assert.assertNotEquals(null, oTcpClient.getContext());
    new MockUp<TcpClientPool>() {

        @Mock
        protected void startCheckTimeout(TcpClientConfig clientConfig, Context context) {
        }
    };
    TcpClientConfig config = new TcpClientConfig();
    TcpClientPool oClientPool = new TcpClientPool(config, Vertx.vertx().getOrCreateContext(), oNetClient);
    oClientPool.send("highway://152.2.2.3:8080", new TcpOutputStream(), Mockito.mock(TcpResonseCallback.class));
    oClientPool.send("highway://152.2.2.3:8080", new TcpOutputStream(), Mockito.mock(TcpResonseCallback.class));
    Assert.assertNotNull(oClientPool);
    TcpRequest oTcpRequest = new TcpRequest(1234, Mockito.mock(TcpResonseCallback.class));
    oTcpRequest.isTimeout();
    oTcpRequest.onReply(Buffer.buffer(), Buffer.buffer(("test").getBytes()));
    oTcpRequest.onSendError(new Throwable("test Errorsss"));
    Assert.assertNotNull(oTcpRequest);
    TcpClientVerticle oTcpClientVerticle = new TcpClientVerticle();
    oTcpClientVerticle.init(Vertx.vertx(), Vertx.vertx().getOrCreateContext());
    oTcpClientVerticle.createClientPool();
    oTcpClientVerticle.createClientPool();
    Assert.assertNotNull(oTcpClientVerticle.getVertx());
    NetSocket socket = Mockito.mock(NetSocket.class);
    Throwable e = Mockito.mock(Throwable.class);
    Buffer hBuffer = Mockito.mock(Buffer.class);
    Buffer bBuffer = Mockito.mock(Buffer.class);
    Deencapsulation.invoke(oTcpClient, "connect");
    Deencapsulation.invoke(oTcpClient, "onConnectSuccess", socket);
    Mockito.when(socket.localAddress()).thenReturn(new SocketAddressImpl(0, "127.0.0.1"));
    Deencapsulation.setField(oTcpClient, "netSocket", socket);
    Deencapsulation.invoke(oTcpClient, "onDisconnected", e);
    Deencapsulation.invoke(oTcpClient, "tryLogin");
    Deencapsulation.invoke(oTcpClient, "onLoginSuccess");
    Deencapsulation.invoke(oTcpClient, "onConnectFailed", e);
    long l = 10;
    Deencapsulation.invoke(oTcpClient, "onReply", l, hBuffer, bBuffer);
    oTcpClient.checkTimeout();
    Assert.assertNotNull(oTcpClient);
}
Also used : NetSocket(io.vertx.core.net.NetSocket) Context(io.vertx.core.Context) Buffer(io.vertx.core.buffer.Buffer) TcpClientVerticle(io.servicecomb.foundation.vertx.client.tcp.TcpClientVerticle) TcpClientConfig(io.servicecomb.foundation.vertx.client.tcp.TcpClientConfig) Handler(io.vertx.core.Handler) MockUp(mockit.MockUp) TcpClientPool(io.servicecomb.foundation.vertx.client.tcp.TcpClientPool) TcpResonseCallback(io.servicecomb.foundation.vertx.client.tcp.TcpResonseCallback) NetClient(io.vertx.core.net.NetClient) TcpRequest(io.servicecomb.foundation.vertx.client.tcp.TcpRequest) TcpClient(io.servicecomb.foundation.vertx.client.tcp.TcpClient) SocketAddressImpl(io.vertx.core.net.impl.SocketAddressImpl) TcpOutputStream(io.servicecomb.foundation.vertx.tcp.TcpOutputStream) Test(org.junit.Test)

Example 22 with Handler

use of io.vertx.core.Handler in project java-chassis by ServiceComb.

the class GrpcTransport method send.

@Override
public void send(Invocation invocation, AsyncResponse asyncResp) throws Exception {
    HttpClientWithContext httpClientWithContext = clientMgr.findThreadBindClientPool();
    OperationMeta operationMeta = invocation.getOperationMeta();
    OperationProtobuf operationProtobuf = ProtobufManager.getOrCreateOperation(operationMeta);
    String cseContext = JsonUtils.writeValueAsString(invocation.getContext());
    // 在verticle之外的线程调用
    IpPort ipPort = (IpPort) invocation.getEndpoint().getAddress();
    Buffer requestBuf = GrpcCodec.encodeRequest(invocation, operationProtobuf);
    String url = "/" + invocation.getSchemaId() + "/" + operationMeta.getOperationId();
    Handler<HttpClientResponse> responseHandler = httpResponse -> {
        httpResponse.bodyHandler(responseBuf -> {
            invocation.getResponseExecutor().execute(() -> {
                try {
                    Response response = GrpcCodec.decodeResponse(invocation, operationProtobuf, httpResponse, responseBuf);
                    ResponseMeta responseMeta = operationMeta.findResponseMeta(response.getStatusCode());
                    for (String headerName : responseMeta.getHeaders().keySet()) {
                        for (String value : httpResponse.headers().getAll(headerName)) {
                            response.getHeaders().addHeader(headerName, value);
                        }
                    }
                    asyncResp.complete(response);
                } catch (Exception e) {
                    asyncResp.fail(invocation.getInvocationType(), e);
                }
            });
        });
    };
    // 从业务线程转移到网络线程中去发送
    httpClientWithContext.runOnContext(httpClient -> {
        HttpClientRequest httpClientRequest = httpClient.post(ipPort.getPort(), ipPort.getHostOrIp(), url, responseHandler);
        httpClientRequest.exceptionHandler(e -> {
            asyncResp.fail(invocation.getInvocationType(), e);
        });
        httpClientRequest.setTimeout(AbstractTransport.getRequestTimeout());
        httpClientRequest.putHeader(HEADER_CONTENT_TYPE, "application/grpc").putHeader(HEADER_TE, "trailers").putHeader(HEADER_USER_AGENT, "cse-client/1.0.0").putHeader(Const.CSE_CONTEXT, cseContext).putHeader(Const.DEST_MICROSERVICE, invocation.getMicroserviceName()).end(requestBuf);
    });
}
Also used : Buffer(io.vertx.core.buffer.Buffer) JsonUtils(io.servicecomb.foundation.common.utils.JsonUtils) OperationMeta(io.servicecomb.core.definition.OperationMeta) OperationProtobuf(io.servicecomb.codec.protobuf.definition.OperationProtobuf) IpPort(io.servicecomb.foundation.common.net.IpPort) ResponseMeta(io.servicecomb.swagger.invocation.response.ResponseMeta) ProtobufManager(io.servicecomb.codec.protobuf.definition.ProtobufManager) JksOptions(io.vertx.core.net.JksOptions) HttpClientWithContext(io.servicecomb.foundation.vertx.client.http.HttpClientWithContext) AsyncResponse(io.servicecomb.core.AsyncResponse) Const(io.servicecomb.core.Const) HttpClientRequest(io.vertx.core.http.HttpClientRequest) HttpClientResponse(io.vertx.core.http.HttpClientResponse) Component(org.springframework.stereotype.Component) VertxUtils(io.servicecomb.foundation.vertx.VertxUtils) Buffer(io.vertx.core.buffer.Buffer) DeploymentOptions(io.vertx.core.DeploymentOptions) HttpVersion(io.vertx.core.http.HttpVersion) AbstractTransport(io.servicecomb.core.transport.AbstractTransport) Response(io.servicecomb.core.Response) HttpClientOptions(io.vertx.core.http.HttpClientOptions) Handler(io.vertx.core.Handler) ClientPoolManager(io.servicecomb.foundation.vertx.client.ClientPoolManager) Invocation(io.servicecomb.core.Invocation) IpPort(io.servicecomb.foundation.common.net.IpPort) AsyncResponse(io.servicecomb.core.AsyncResponse) HttpClientResponse(io.vertx.core.http.HttpClientResponse) Response(io.servicecomb.core.Response) HttpClientRequest(io.vertx.core.http.HttpClientRequest) OperationProtobuf(io.servicecomb.codec.protobuf.definition.OperationProtobuf) ResponseMeta(io.servicecomb.swagger.invocation.response.ResponseMeta) HttpClientResponse(io.vertx.core.http.HttpClientResponse) HttpClientWithContext(io.servicecomb.foundation.vertx.client.http.HttpClientWithContext) OperationMeta(io.servicecomb.core.definition.OperationMeta)

Example 23 with Handler

use of io.vertx.core.Handler in project vert.x by eclipse.

the class WebsocketTest method testEndHandlerCalled.

@Test
public void testEndHandlerCalled() {
    String path = "/some/path";
    server = vertx.createHttpServer(new HttpServerOptions().setPort(HttpTestBase.DEFAULT_HTTP_PORT)).websocketHandler(WebSocketBase::close);
    AtomicInteger doneCount = new AtomicInteger();
    server.listen(ar -> {
        assertTrue(ar.succeeded());
        client.websocketStream(HttpTestBase.DEFAULT_HTTP_PORT, HttpTestBase.DEFAULT_HTTP_HOST, path, null).endHandler(done -> doneCount.incrementAndGet()).handler(ws -> {
            assertEquals(0, doneCount.get());
            ws.closeHandler(v -> {
                assertEquals(1, doneCount.get());
                testComplete();
            });
        });
    });
    await();
}
Also used : Arrays(java.util.Arrays) MessageDigest(java.security.MessageDigest) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) Cert(io.vertx.test.core.tls.Cert) WebSocketHandshakeException(io.netty.handler.codec.http.websocketx.WebSocketHandshakeException) Context(io.vertx.core.Context) AtomicReference(java.util.concurrent.atomic.AtomicReference) Function(java.util.function.Function) ArrayList(java.util.ArrayList) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) TestUtils(io.vertx.test.core.TestUtils) Map(java.util.Map) ReadStream(io.vertx.core.streams.ReadStream) AsyncResult(io.vertx.core.AsyncResult) ConcurrentHashSet(io.vertx.core.impl.ConcurrentHashSet) java.util.concurrent(java.util.concurrent) Vertx(io.vertx.core.Vertx) Set(java.util.Set) Test(org.junit.Test) Future(io.vertx.core.Future) io.vertx.core.http(io.vertx.core.http) Consumer(java.util.function.Consumer) Base64(java.util.Base64) List(java.util.List) Buffer(io.vertx.core.buffer.Buffer) DeploymentOptions(io.vertx.core.DeploymentOptions) NetServer(io.vertx.core.net.NetServer) AbstractVerticle(io.vertx.core.AbstractVerticle) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) Handler(io.vertx.core.Handler) UnsupportedEncodingException(java.io.UnsupportedEncodingException) Collections(java.util.Collections) NetSocket(io.vertx.core.net.NetSocket) Trust(io.vertx.test.core.tls.Trust) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Test(org.junit.Test)

Example 24 with Handler

use of io.vertx.core.Handler in project vert.x by eclipse.

the class WebsocketTest method testUpgrade.

private void testUpgrade(boolean delayed) {
    String path = "/some/path";
    server = vertx.createHttpServer(new HttpServerOptions().setPort(HttpTestBase.DEFAULT_HTTP_PORT));
    server.requestHandler(request -> {
        Runnable runner = () -> {
            ServerWebSocket ws = request.upgrade();
            ws.handler(buff -> {
                ws.write(Buffer.buffer("helloworld"));
                ws.close();
            });
        };
        if (delayed) {
            vertx.runOnContext(v -> {
                runner.run();
            });
        } else {
            runner.run();
        }
    });
    server.listen(ar -> {
        assertTrue(ar.succeeded());
        client.websocketStream(HttpTestBase.DEFAULT_HTTP_PORT, HttpTestBase.DEFAULT_HTTP_HOST, path, null).handler(ws -> {
            Buffer buff = Buffer.buffer();
            ws.handler(b -> {
                buff.appendBuffer(b);
            });
            ws.endHandler(v -> {
                assertEquals("helloworld", buff.toString());
                testComplete();
            });
            ws.write(Buffer.buffer("foo"));
        });
    });
    await();
}
Also used : Arrays(java.util.Arrays) MessageDigest(java.security.MessageDigest) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) Cert(io.vertx.test.core.tls.Cert) WebSocketHandshakeException(io.netty.handler.codec.http.websocketx.WebSocketHandshakeException) Context(io.vertx.core.Context) AtomicReference(java.util.concurrent.atomic.AtomicReference) Function(java.util.function.Function) ArrayList(java.util.ArrayList) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) TestUtils(io.vertx.test.core.TestUtils) Map(java.util.Map) ReadStream(io.vertx.core.streams.ReadStream) AsyncResult(io.vertx.core.AsyncResult) ConcurrentHashSet(io.vertx.core.impl.ConcurrentHashSet) java.util.concurrent(java.util.concurrent) Vertx(io.vertx.core.Vertx) Set(java.util.Set) Test(org.junit.Test) Future(io.vertx.core.Future) io.vertx.core.http(io.vertx.core.http) Consumer(java.util.function.Consumer) Base64(java.util.Base64) List(java.util.List) Buffer(io.vertx.core.buffer.Buffer) DeploymentOptions(io.vertx.core.DeploymentOptions) NetServer(io.vertx.core.net.NetServer) AbstractVerticle(io.vertx.core.AbstractVerticle) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) Handler(io.vertx.core.Handler) UnsupportedEncodingException(java.io.UnsupportedEncodingException) Collections(java.util.Collections) NetSocket(io.vertx.core.net.NetSocket) Trust(io.vertx.test.core.tls.Trust) Buffer(io.vertx.core.buffer.Buffer)

Example 25 with Handler

use of io.vertx.core.Handler in project vert.x by eclipse.

the class VertxTest method testCloseHookFailure2.

@Test
public void testCloseHookFailure2() throws Exception {
    AtomicInteger closedCount = new AtomicInteger();
    class Hook implements Closeable {

        @Override
        public void close(Handler<AsyncResult<Void>> completionHandler) {
            if (closedCount.incrementAndGet() == 1) {
                completionHandler.handle(Future.succeededFuture());
                throw new RuntimeException();
            } else {
                completionHandler.handle(Future.succeededFuture());
            }
        }
    }
    VertxInternal vertx = (VertxInternal) Vertx.vertx();
    vertx.addCloseHook(new Hook());
    vertx.addCloseHook(new Hook());
    // Now undeploy
    vertx.close(ar -> {
        assertTrue(ar.succeeded());
        assertEquals(2, closedCount.get());
        testComplete();
    });
    await();
}
Also used : VertxInternal(io.vertx.core.impl.VertxInternal) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Closeable(io.vertx.core.Closeable) Handler(io.vertx.core.Handler) Test(org.junit.Test)

Aggregations

Handler (io.vertx.core.Handler)47 Buffer (io.vertx.core.buffer.Buffer)32 AsyncResult (io.vertx.core.AsyncResult)31 Future (io.vertx.core.Future)31 Test (org.junit.Test)28 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)26 NetSocket (io.vertx.core.net.NetSocket)24 ArrayList (java.util.ArrayList)23 Context (io.vertx.core.Context)22 List (java.util.List)22 Map (java.util.Map)22 Vertx (io.vertx.core.Vertx)21 File (java.io.File)21 Collections (java.util.Collections)21 MultiMap (io.vertx.core.MultiMap)20 HttpMethod (io.vertx.core.http.HttpMethod)20 VertxInternal (io.vertx.core.impl.VertxInternal)20 AtomicBoolean (java.util.concurrent.atomic.AtomicBoolean)20 Function (java.util.function.Function)20 HttpClient (io.vertx.core.http.HttpClient)19