Search in sources :

Example 31 with HttpServer

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

the class HostnameResolutionTest method testHttp.

@Test
public void testHttp() throws Exception {
    HttpClient client = vertx.createHttpClient();
    HttpServer server = vertx.createHttpServer().requestHandler(req -> {
        req.response().end("foo");
    });
    try {
        CountDownLatch listenLatch = new CountDownLatch(1);
        server.listen(8080, "vertx.io", onSuccess(s -> {
            listenLatch.countDown();
        }));
        awaitLatch(listenLatch);
        client.request(HttpMethod.GET, 8080, "vertx.io", "/somepath", onSuccess(req -> {
            req.send(onSuccess(resp -> {
                Buffer buffer = Buffer.buffer();
                resp.handler(buffer::appendBuffer);
                resp.endHandler(v -> {
                    assertEquals(Buffer.buffer("foo"), buffer);
                    testComplete();
                });
            }));
        }));
        await();
    } finally {
        client.close();
        server.close();
    }
}
Also used : VertxException(io.vertx.core.VertxException) RecordClass(org.apache.directory.server.dns.messages.RecordClass) java.util(java.util) HttpServer(io.vertx.core.http.HttpServer) CompletableFuture(java.util.concurrent.CompletableFuture) VertxTestBase(io.vertx.test.core.VertxTestBase) AtomicReference(java.util.concurrent.atomic.AtomicReference) Function(java.util.function.Function) InetAddress(java.net.InetAddress) TestUtils(io.vertx.test.core.TestUtils) JsonObject(io.vertx.core.json.JsonObject) FakeDNSServer(io.vertx.test.fakedns.FakeDNSServer) NetClient(io.vertx.core.net.NetClient) ResourceRecord(org.apache.directory.server.dns.messages.ResourceRecord) VertxImpl(io.vertx.core.impl.VertxImpl) VertxInternal(io.vertx.core.impl.VertxInternal) ChannelInitializer(io.netty.channel.ChannelInitializer) AddressResolver(io.vertx.core.impl.AddressResolver) DnsAttribute(org.apache.directory.server.dns.store.DnsAttribute) 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) Buffer(io.vertx.core.buffer.Buffer) NetServer(io.vertx.core.net.NetServer) HttpMethod(io.vertx.core.http.HttpMethod) RecordType(org.apache.directory.server.dns.messages.RecordType) HttpClient(io.vertx.core.http.HttpClient) Buffer(io.vertx.core.buffer.Buffer) HttpClient(io.vertx.core.http.HttpClient) HttpServer(io.vertx.core.http.HttpServer) CountDownLatch(java.util.concurrent.CountDownLatch) Test(org.junit.Test)

Example 32 with HttpServer

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

the class MockForRestServerVerticle method mockRestServerVerticle.

public void mockRestServerVerticle() {
    final HttpServer server = Mockito.mock(HttpServer.class);
    new MockUp<RestServerVerticle>() {

        @Mock
        private void startListen(HttpServer server, IpPort ipPort, Future<Void> startFuture) {
        }

        @Mock
        private HttpServer createHttpServer(boolean isHttp_2) {
            return server;
        }
    };
}
Also used : HttpServer(io.vertx.core.http.HttpServer) Future(io.vertx.core.Future) MockUp(mockit.MockUp) IpPort(org.apache.servicecomb.foundation.common.net.IpPort)

Example 33 with HttpServer

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

the class RestServerVerticle method start.

@Override
public void start(Promise<Void> startPromise) throws Exception {
    try {
        super.start();
        // 如果本地未配置地址,则表示不必监听,只需要作为客户端使用即可
        if (endpointObject == null) {
            LOGGER.warn("rest listen address is not configured, will not start.");
            startPromise.complete();
            return;
        }
        Router mainRouter = Router.router(vertx);
        mountAccessLogHandler(mainRouter);
        mountCorsHandler(mainRouter);
        initDispatcher(mainRouter);
        mountGlobalRestFailureHandler(mainRouter);
        HttpServer httpServer = createHttpServer();
        httpServer.requestHandler(mainRouter);
        httpServer.connectionHandler(connection -> {
            DefaultHttpServerMetrics serverMetrics = (DefaultHttpServerMetrics) ((ConnectionBase) connection).metrics();
            DefaultServerEndpointMetric endpointMetric = serverMetrics.getEndpointMetric();
            long connectedCount = endpointMetric.getCurrentConnectionCount();
            int connectionLimit = DynamicPropertyFactory.getInstance().getIntProperty("servicecomb.rest.server.connection-limit", Integer.MAX_VALUE).get();
            if (connectedCount > connectionLimit) {
                connection.close();
                endpointMetric.onRejectByConnectionLimit();
            }
        });
        List<HttpServerExceptionHandler> httpServerExceptionHandlers = SPIServiceUtils.getAllService(HttpServerExceptionHandler.class);
        httpServer.exceptionHandler(e -> {
            if (e instanceof ClosedChannelException) {
                // This is quite normal in between browser and ege, so do not print out.
                LOGGER.debug("Unexpected error in server.{}", ExceptionUtils.getExceptionMessageWithoutTrace(e));
            } else {
                LOGGER.error("Unexpected error in server.{}", ExceptionUtils.getExceptionMessageWithoutTrace(e));
            }
            httpServerExceptionHandlers.forEach(httpServerExceptionHandler -> {
                httpServerExceptionHandler.handle(e);
            });
        });
        startListen(httpServer, startPromise);
    } catch (Throwable e) {
        // vert.x got some states that not print error and execute call back in VertexUtils.blockDeploy, we add a log our self.
        LOGGER.error("", e);
        throw e;
    }
}
Also used : ClosedChannelException(java.nio.channels.ClosedChannelException) HttpServer(io.vertx.core.http.HttpServer) Router(io.vertx.ext.web.Router) DefaultHttpServerMetrics(org.apache.servicecomb.foundation.vertx.metrics.DefaultHttpServerMetrics) Endpoint(org.apache.servicecomb.core.Endpoint) DefaultServerEndpointMetric(org.apache.servicecomb.foundation.vertx.metrics.metric.DefaultServerEndpointMetric)

Example 34 with HttpServer

use of io.vertx.core.http.HttpServer in project chuidiang-ejemplos by chuidiang.

the class WebServerVerticle method start.

@Override
public void start() throws Exception {
    HttpServer server = vertx.createHttpServer();
    server.requestHandler(request -> {
        LOG.info("Web request arrived");
        if (request.path().endsWith("index.html")) {
            request.response().putHeader("content-type", "text/html");
            request.response().sendFile("src/main/webroot/index.html");
        } else {
            request.response().setChunked(true);
            request.response().putHeader("content-type", "text/plain");
            request.response().write("No such file!!");
            request.response().setStatusCode(404);
            request.response().end();
        }
    });
    server.listen();
    super.start();
}
Also used : HttpServer(io.vertx.core.http.HttpServer)

Example 35 with HttpServer

use of io.vertx.core.http.HttpServer in project hono by eclipse.

the class AbstractVertxBasedHttpProtocolAdapterTest method getHttpServer.

@SuppressWarnings("unchecked")
private HttpServer getHttpServer(final boolean startupShouldFail) {
    final HttpServer server = mock(HttpServer.class);
    when(server.actualPort()).thenReturn(0, 8080);
    when(server.requestHandler(VertxMockSupport.anyHandler())).thenReturn(server);
    when(server.listen(VertxMockSupport.anyHandler())).then(invocation -> {
        final Handler<AsyncResult<HttpServer>> handler = (Handler<AsyncResult<HttpServer>>) invocation.getArgument(0);
        if (startupShouldFail) {
            handler.handle(Future.failedFuture("http server intentionally failed to start"));
        } else {
            handler.handle(Future.succeededFuture(server));
        }
        return server;
    });
    return server;
}
Also used : HttpServer(io.vertx.core.http.HttpServer) TracingHandler(org.eclipse.hono.service.http.TracingHandler) Handler(io.vertx.core.Handler) AsyncResult(io.vertx.core.AsyncResult)

Aggregations

HttpServer (io.vertx.core.http.HttpServer)81 Router (io.vertx.ext.web.Router)37 HttpServerOptions (io.vertx.core.http.HttpServerOptions)33 Test (org.junit.Test)22 JsonObject (io.vertx.core.json.JsonObject)17 HttpClient (io.vertx.core.http.HttpClient)13 Future (io.vertx.core.Future)12 Vertx (io.vertx.core.Vertx)12 HttpServerResponse (io.vertx.core.http.HttpServerResponse)12 CountDownLatch (java.util.concurrent.CountDownLatch)12 Buffer (io.vertx.core.buffer.Buffer)11 HttpMethod (io.vertx.core.http.HttpMethod)10 Handler (io.vertx.core.Handler)9 VertxOptions (io.vertx.core.VertxOptions)9 AtomicReference (java.util.concurrent.atomic.AtomicReference)9 HttpClientOptions (io.vertx.core.http.HttpClientOptions)8 List (java.util.List)8 AbstractVerticle (io.vertx.core.AbstractVerticle)7 File (java.io.File)7 AsyncResult (io.vertx.core.AsyncResult)6