Search in sources :

Example 1 with NetClient

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

the class HostnameResolutionTest method testNet.

private void testNet(String hostname) throws Exception {
    NetClient client = vertx.createNetClient();
    NetServer server = vertx.createNetServer().connectHandler(so -> {
        so.handler(buff -> {
            so.write(buff);
            so.close();
        });
    });
    try {
        CountDownLatch listenLatch = new CountDownLatch(1);
        server.listen(1234, hostname, onSuccess(s -> {
            listenLatch.countDown();
        }));
        awaitLatch(listenLatch);
        client.connect(1234, hostname, onSuccess(so -> {
            Buffer buffer = Buffer.buffer();
            so.handler(buffer::appendBuffer);
            so.closeHandler(v -> {
                assertEquals(Buffer.buffer("foo"), buffer);
                testComplete();
            });
            so.write(Buffer.buffer("foo"));
        }));
        await();
    } finally {
        client.close();
        server.close();
    }
}
Also used : NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) VertxException(io.vertx.core.VertxException) Arrays(java.util.Arrays) HttpServer(io.vertx.core.http.HttpServer) HashMap(java.util.HashMap) CompletableFuture(java.util.concurrent.CompletableFuture) AddressResolverOptions(io.vertx.core.dns.AddressResolverOptions) AtomicReference(java.util.concurrent.atomic.AtomicReference) ArrayList(java.util.ArrayList) InetAddress(java.net.InetAddress) Locale(java.util.Locale) Map(java.util.Map) JsonObject(io.vertx.core.json.JsonObject) FakeDNSServer(io.vertx.test.fakedns.FakeDNSServer) NetClient(io.vertx.core.net.NetClient) VertxImpl(io.vertx.core.impl.VertxImpl) VertxInternal(io.vertx.core.impl.VertxInternal) ChannelInitializer(io.netty.channel.ChannelInitializer) AddressResolver(io.vertx.core.impl.AddressResolver) VertxOptions(io.vertx.core.VertxOptions) Test(org.junit.Test) InetSocketAddress(java.net.InetSocketAddress) UnknownHostException(java.net.UnknownHostException) File(java.io.File) ChannelFuture(io.netty.channel.ChannelFuture) Channel(io.netty.channel.Channel) TimeUnit(java.util.concurrent.TimeUnit) Bootstrap(io.netty.bootstrap.Bootstrap) CountDownLatch(java.util.concurrent.CountDownLatch) NetServerOptions(io.vertx.core.net.NetServerOptions) List(java.util.List) Buffer(io.vertx.core.buffer.Buffer) NetServer(io.vertx.core.net.NetServer) Collections(java.util.Collections) HttpClient(io.vertx.core.http.HttpClient) Buffer(io.vertx.core.buffer.Buffer) NetClient(io.vertx.core.net.NetClient) NetServer(io.vertx.core.net.NetServer) CountDownLatch(java.util.concurrent.CountDownLatch)

Example 2 with NetClient

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

the class HttpProxy method start.

/**
   * Start the server.
   * 
   * @param vertx
   *          Vertx instance to use for creating the server and client
   * @param finishedHandler
   *          will be called when the server has started
   */
@Override
public void start(Vertx vertx, Handler<Void> finishedHandler) {
    HttpServerOptions options = new HttpServerOptions();
    options.setHost("localhost").setPort(PORT);
    server = vertx.createHttpServer(options);
    server.requestHandler(request -> {
        HttpMethod method = request.method();
        String uri = request.uri();
        if (username != null) {
            String auth = request.getHeader("Proxy-Authorization");
            String expected = "Basic " + Base64.getEncoder().encodeToString((username + ":" + username).getBytes());
            if (auth == null || !auth.equals(expected)) {
                request.response().setStatusCode(407).end("proxy authentication failed");
                return;
            }
        }
        lastRequestHeaders = MultiMap.caseInsensitiveMultiMap().addAll(request.headers());
        if (error != 0) {
            request.response().setStatusCode(error).end("proxy request failed");
        } else if (method == HttpMethod.CONNECT) {
            if (!uri.contains(":")) {
                request.response().setStatusCode(403).end("invalid request");
            } else {
                lastUri = uri;
                if (forceUri != null) {
                    uri = forceUri;
                }
                String[] split = uri.split(":");
                String host = split[0];
                int port;
                try {
                    port = Integer.parseInt(split[1]);
                } catch (NumberFormatException ex) {
                    port = 443;
                }
                if (port == 8080 || port < 1024 && port != 443) {
                    request.response().setStatusCode(403).end("access to port denied");
                    return;
                }
                NetSocket serverSocket = request.netSocket();
                NetClientOptions netOptions = new NetClientOptions();
                NetClient netClient = vertx.createNetClient(netOptions);
                netClient.connect(port, host, result -> {
                    if (result.succeeded()) {
                        NetSocket clientSocket = result.result();
                        serverSocket.write("HTTP/1.0 200 Connection established\n\n");
                        serverSocket.closeHandler(v -> clientSocket.close());
                        clientSocket.closeHandler(v -> serverSocket.close());
                        Pump.pump(serverSocket, clientSocket).start();
                        Pump.pump(clientSocket, serverSocket).start();
                    } else {
                        request.response().setStatusCode(403).end("request failed");
                    }
                });
            }
        } else if (method == HttpMethod.GET) {
            lastUri = request.uri();
            HttpClient client = vertx.createHttpClient();
            HttpClientRequest clientRequest = client.getAbs(request.uri(), resp -> {
                for (String name : resp.headers().names()) {
                    request.response().putHeader(name, resp.headers().getAll(name));
                }
                resp.bodyHandler(body -> {
                    request.response().end(body);
                });
            });
            for (String name : request.headers().names()) {
                if (!name.equals("Proxy-Authorization")) {
                    clientRequest.putHeader(name, request.headers().getAll(name));
                }
            }
            clientRequest.exceptionHandler(e -> {
                log.debug("exception", e);
                int status;
                if (e instanceof UnknownHostException) {
                    status = 504;
                } else {
                    status = 400;
                }
                request.response().setStatusCode(status).end(e.toString() + " on client request");
            });
            clientRequest.end();
        } else {
            request.response().setStatusCode(405).end("method not supported");
        }
    });
    server.listen(server -> {
        finishedHandler.handle(null);
    });
}
Also used : NetSocket(io.vertx.core.net.NetSocket) HttpServer(io.vertx.core.http.HttpServer) MultiMap(io.vertx.core.MultiMap) Vertx(io.vertx.core.Vertx) UnknownHostException(java.net.UnknownHostException) LoggerFactory(io.vertx.core.logging.LoggerFactory) NetClientOptions(io.vertx.core.net.NetClientOptions) HttpClientRequest(io.vertx.core.http.HttpClientRequest) Base64(java.util.Base64) HttpMethod(io.vertx.core.http.HttpMethod) HttpServerOptions(io.vertx.core.http.HttpServerOptions) Pump(io.vertx.core.streams.Pump) Handler(io.vertx.core.Handler) Logger(io.vertx.core.logging.Logger) NetClient(io.vertx.core.net.NetClient) HttpClient(io.vertx.core.http.HttpClient) NetSocket(io.vertx.core.net.NetSocket) NetClientOptions(io.vertx.core.net.NetClientOptions) HttpClientRequest(io.vertx.core.http.HttpClientRequest) NetClient(io.vertx.core.net.NetClient) UnknownHostException(java.net.UnknownHostException) HttpClient(io.vertx.core.http.HttpClient) HttpServerOptions(io.vertx.core.http.HttpServerOptions) HttpMethod(io.vertx.core.http.HttpMethod)

Example 3 with NetClient

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

the class HttpRequestStreamTest method testReadStreamPauseResume.

@Test
public void testReadStreamPauseResume() {
    String path = "/some/path";
    this.server = vertx.createHttpServer(new HttpServerOptions().setAcceptBacklog(10).setPort(HttpTestBase.DEFAULT_HTTP_PORT));
    ReadStream<HttpServerRequest> httpStream = server.requestStream();
    AtomicBoolean paused = new AtomicBoolean();
    httpStream.handler(req -> {
        assertFalse(paused.get());
        HttpServerResponse response = req.response();
        response.setStatusCode(200).end();
        response.close();
    });
    server.listen(listenAR -> {
        assertTrue(listenAR.succeeded());
        paused.set(true);
        httpStream.pause();
        netClient = vertx.createNetClient(new NetClientOptions().setConnectTimeout(1000));
        netClient.connect(HttpTestBase.DEFAULT_HTTP_PORT, "localhost", socketAR -> {
            assertTrue(socketAR.succeeded());
            NetSocket socket = socketAR.result();
            Buffer buffer = Buffer.buffer();
            socket.handler(buffer::appendBuffer);
            socket.closeHandler(v -> {
                assertEquals(0, buffer.length());
                paused.set(false);
                httpStream.resume();
                client = vertx.createHttpClient(new HttpClientOptions());
                client.request(HttpMethod.GET, HttpTestBase.DEFAULT_HTTP_PORT, "localhost", path, resp -> {
                    assertEquals(200, resp.statusCode());
                    testComplete();
                }).end();
            });
        });
    });
    await();
}
Also used : NetSocket(io.vertx.core.net.NetSocket) Buffer(io.vertx.core.buffer.Buffer) HttpServerRequest(io.vertx.core.http.HttpServerRequest) HttpServer(io.vertx.core.http.HttpServer) Vertx(io.vertx.core.Vertx) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) Test(org.junit.Test) NetClientOptions(io.vertx.core.net.NetClientOptions) CountDownLatch(java.util.concurrent.CountDownLatch) Buffer(io.vertx.core.buffer.Buffer) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) HttpMethod(io.vertx.core.http.HttpMethod) HttpServerResponse(io.vertx.core.http.HttpServerResponse) ReadStream(io.vertx.core.streams.ReadStream) HttpServerOptions(io.vertx.core.http.HttpServerOptions) HttpClientOptions(io.vertx.core.http.HttpClientOptions) NetClient(io.vertx.core.net.NetClient) HttpClient(io.vertx.core.http.HttpClient) NetSocket(io.vertx.core.net.NetSocket) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) NetClientOptions(io.vertx.core.net.NetClientOptions) HttpServerRequest(io.vertx.core.http.HttpServerRequest) HttpServerResponse(io.vertx.core.http.HttpServerResponse) HttpServerOptions(io.vertx.core.http.HttpServerOptions) HttpClientOptions(io.vertx.core.http.HttpClientOptions) Test(org.junit.Test)

Example 4 with NetClient

use of io.vertx.core.net.NetClient 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 5 with NetClient

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

the class TcpClientTest method setUp.

@Before
public void setUp() throws Exception {
    Context context = Mockito.mock(Context.class);
    NetClient netClient = Mockito.mock(NetClient.class);
    InetSocketAddress socketAddress = Mockito.mock(InetSocketAddress.class);
    mockTestCases();
    Mockito.when(NetUtils.parseIpPort("sss").getSocketAddress()).thenReturn(socketAddress);
    instance = new TcpClient(context, netClient, "highway://127.0.0.1:80", new TcpClientConfig());
}
Also used : Context(io.vertx.core.Context) NetClient(io.vertx.core.net.NetClient) InetSocketAddress(java.net.InetSocketAddress) Before(org.junit.Before)

Aggregations

NetClient (io.vertx.core.net.NetClient)52 NetSocket (io.vertx.core.net.NetSocket)35 Test (org.junit.Test)34 NetServerOptions (io.vertx.core.net.NetServerOptions)24 Vertx (io.vertx.core.Vertx)23 JsonObject (io.vertx.core.json.JsonObject)21 Async (io.vertx.ext.unit.Async)20 Handler (io.vertx.core.Handler)19 FrameParser (io.vertx.ext.eventbus.bridge.tcp.impl.protocol.FrameParser)19 AtomicBoolean (java.util.concurrent.atomic.AtomicBoolean)19 NetClientOptions (io.vertx.core.net.NetClientOptions)17 BridgeOptions (io.vertx.ext.bridge.BridgeOptions)16 PermittedOptions (io.vertx.ext.bridge.PermittedOptions)16 Before (org.junit.Before)16 Message (io.vertx.core.eventbus.Message)15 BridgeEventType (io.vertx.ext.bridge.BridgeEventType)15 FrameHelper (io.vertx.ext.eventbus.bridge.tcp.impl.protocol.FrameHelper)15 TestContext (io.vertx.ext.unit.TestContext)15 VertxUnitRunner (io.vertx.ext.unit.junit.VertxUnitRunner)15 After (org.junit.After)15