Search in sources :

Example 6 with HttpServer

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

the class HttpServerImpl method listen.

public synchronized HttpServer listen(int port, String host, Handler<AsyncResult<HttpServer>> listenHandler) {
    if (requestStream.handler() == null && wsStream.handler() == null) {
        throw new IllegalStateException("Set request or websocket handler first");
    }
    if (listening) {
        throw new IllegalStateException("Already listening");
    }
    listenContext = vertx.getOrCreateContext();
    listening = true;
    serverOrigin = (options.isSsl() ? "https" : "http") + "://" + host + ":" + port;
    List<HttpVersion> applicationProtocols = options.getAlpnVersions();
    if (listenContext.isWorkerContext()) {
        applicationProtocols = applicationProtocols.stream().filter(v -> v != HttpVersion.HTTP_2).collect(Collectors.toList());
    }
    sslHelper.setApplicationProtocols(applicationProtocols);
    synchronized (vertx.sharedHttpServers()) {
        // Will be updated on bind for a wildcard port
        this.actualPort = port;
        id = new ServerID(port, host);
        HttpServerImpl shared = vertx.sharedHttpServers().get(id);
        if (shared == null || port == 0) {
            serverChannelGroup = new DefaultChannelGroup("vertx-acceptor-channels", GlobalEventExecutor.INSTANCE);
            ServerBootstrap bootstrap = new ServerBootstrap();
            bootstrap.group(vertx.getAcceptorEventLoopGroup(), availableWorkers);
            bootstrap.channel(NioServerSocketChannel.class);
            applyConnectionOptions(bootstrap);
            sslHelper.validate(vertx);
            bootstrap.childHandler(new ChannelInitializer<Channel>() {

                @Override
                protected void initChannel(Channel ch) throws Exception {
                    if (requestStream.isPaused() || wsStream.isPaused()) {
                        ch.close();
                        return;
                    }
                    ChannelPipeline pipeline = ch.pipeline();
                    if (sslHelper.isSSL()) {
                        pipeline.addLast("ssl", sslHelper.createSslHandler(vertx));
                        if (options.isUseAlpn()) {
                            pipeline.addLast("alpn", new ApplicationProtocolNegotiationHandler("http/1.1") {

                                @Override
                                protected void configurePipeline(ChannelHandlerContext ctx, String protocol) throws Exception {
                                    if (protocol.equals("http/1.1")) {
                                        configureHttp1(pipeline);
                                    } else {
                                        handleHttp2(ch);
                                    }
                                }
                            });
                        } else {
                            configureHttp1(pipeline);
                        }
                    } else {
                        if (DISABLE_HC2) {
                            configureHttp1(pipeline);
                        } else {
                            pipeline.addLast(new Http1xOrHttp2Handler());
                        }
                    }
                }
            });
            addHandlers(this, listenContext);
            try {
                bindFuture = AsyncResolveConnectHelper.doBind(vertx, port, host, bootstrap);
                bindFuture.addListener(res -> {
                    if (res.failed()) {
                        vertx.sharedHttpServers().remove(id);
                    } else {
                        Channel serverChannel = res.result();
                        HttpServerImpl.this.actualPort = ((InetSocketAddress) serverChannel.localAddress()).getPort();
                        serverChannelGroup.add(serverChannel);
                        metrics = vertx.metricsSPI().createMetrics(this, new SocketAddressImpl(port, host), options);
                    }
                });
            } catch (final Throwable t) {
                // Make sure we send the exception back through the handler (if any)
                if (listenHandler != null) {
                    vertx.runOnContext(v -> listenHandler.handle(Future.failedFuture(t)));
                } else {
                    // No handler - log so user can see failure
                    log.error(t);
                }
                listening = false;
                return this;
            }
            vertx.sharedHttpServers().put(id, this);
            actualServer = this;
        } else {
            // Server already exists with that host/port - we will use that
            actualServer = shared;
            this.actualPort = shared.actualPort;
            addHandlers(actualServer, listenContext);
            metrics = vertx.metricsSPI().createMetrics(this, new SocketAddressImpl(port, host), options);
        }
        actualServer.bindFuture.addListener(future -> {
            if (listenHandler != null) {
                final AsyncResult<HttpServer> res;
                if (future.succeeded()) {
                    res = Future.succeededFuture(HttpServerImpl.this);
                } else {
                    res = Future.failedFuture(future.cause());
                    listening = false;
                }
                listenContext.runOnContext((v) -> listenHandler.handle(res));
            } else if (future.failed()) {
                listening = false;
                log.error(future.cause());
            }
        });
    }
    return this;
}
Also used : DefaultChannelGroup(io.netty.channel.group.DefaultChannelGroup) VertxException(io.vertx.core.VertxException) HandlerManager(io.vertx.core.net.impl.HandlerManager) ServerWebSocket(io.vertx.core.http.ServerWebSocket) HttpHeaders(io.netty.handler.codec.http.HttpHeaders) WebSocketServerHandshakerFactory(io.netty.handler.codec.http.websocketx.WebSocketServerHandshakerFactory) DefaultFullHttpRequest(io.netty.handler.codec.http.DefaultFullHttpRequest) DefaultChannelGroup(io.netty.channel.group.DefaultChannelGroup) ChannelInboundHandlerAdapter(io.netty.channel.ChannelInboundHandlerAdapter) HttpServer(io.vertx.core.http.HttpServer) URISyntaxException(java.net.URISyntaxException) ChunkedWriteHandler(io.netty.handler.stream.ChunkedWriteHandler) Unpooled(io.netty.buffer.Unpooled) GlobalEventExecutor(io.netty.util.concurrent.GlobalEventExecutor) HttpServerMetrics(io.vertx.core.spi.metrics.HttpServerMetrics) HttpVersion(io.vertx.core.http.HttpVersion) Http2Exception(io.netty.handler.codec.http2.Http2Exception) Map(java.util.Map) ApplicationProtocolNegotiationHandler(io.netty.handler.ssl.ApplicationProtocolNegotiationHandler) CharsetUtil(io.netty.util.CharsetUtil) ReadStream(io.vertx.core.streams.ReadStream) WebSocketFrameImpl(io.vertx.core.http.impl.ws.WebSocketFrameImpl) URI(java.net.URI) Logger(io.vertx.core.logging.Logger) ChannelGroup(io.netty.channel.group.ChannelGroup) HttpRequest(io.netty.handler.codec.http.HttpRequest) ChannelInitializer(io.netty.channel.ChannelInitializer) PartialPooledByteBufAllocator(io.vertx.core.net.impl.PartialPooledByteBufAllocator) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) NioServerSocketChannel(io.netty.channel.socket.nio.NioServerSocketChannel) HttpResponseStatus(io.netty.handler.codec.http.HttpResponseStatus) MetricsProvider(io.vertx.core.spi.metrics.MetricsProvider) ChannelPipeline(io.netty.channel.ChannelPipeline) FullHttpRequest(io.netty.handler.codec.http.FullHttpRequest) Future(io.vertx.core.Future) ServerID(io.vertx.core.net.impl.ServerID) InetSocketAddress(java.net.InetSocketAddress) Collectors(java.util.stream.Collectors) Objects(java.util.Objects) List(java.util.List) Buffer(io.vertx.core.buffer.Buffer) SslHandler(io.netty.handler.ssl.SslHandler) HandlerHolder(io.vertx.core.net.impl.HandlerHolder) DefaultFullHttpResponse(io.netty.handler.codec.http.DefaultFullHttpResponse) WebSocketFrameInternal(io.vertx.core.http.impl.ws.WebSocketFrameInternal) VertxEventLoopGroup(io.vertx.core.net.impl.VertxEventLoopGroup) HttpServerRequest(io.vertx.core.http.HttpServerRequest) HttpVersion(io.netty.handler.codec.http.HttpVersion) ChannelOption(io.netty.channel.ChannelOption) LoggingHandler(io.netty.handler.logging.LoggingHandler) ContextImpl(io.vertx.core.impl.ContextImpl) FlashPolicyHandler(io.vertx.core.http.impl.cgbystrom.FlashPolicyHandler) WebSocketHandshakeException(io.netty.handler.codec.http.websocketx.WebSocketHandshakeException) LoggerFactory(io.vertx.core.logging.LoggerFactory) LastHttpContent(io.netty.handler.codec.http.LastHttpContent) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) WebSocketVersion(io.netty.handler.codec.http.websocketx.WebSocketVersion) ByteBuf(io.netty.buffer.ByteBuf) FixedRecvByteBufAllocator(io.netty.channel.FixedRecvByteBufAllocator) ChannelFutureListener(io.netty.channel.ChannelFutureListener) AsyncResult(io.vertx.core.AsyncResult) HttpConnection(io.vertx.core.http.HttpConnection) Metrics(io.vertx.core.spi.metrics.Metrics) HttpContent(io.netty.handler.codec.http.HttpContent) Closeable(io.vertx.core.Closeable) VertxInternal(io.vertx.core.impl.VertxInternal) HttpHeaderValues(io.netty.handler.codec.http.HttpHeaderValues) AsyncResolveConnectHelper(io.vertx.core.net.impl.AsyncResolveConnectHelper) HttpMethod(io.netty.handler.codec.http.HttpMethod) SSLHelper(io.vertx.core.net.impl.SSLHelper) Channel(io.netty.channel.Channel) Http2Settings(io.netty.handler.codec.http2.Http2Settings) FullHttpResponse(io.netty.handler.codec.http.FullHttpResponse) IdleStateHandler(io.netty.handler.timeout.IdleStateHandler) WebSocketServerHandshaker(io.netty.handler.codec.http.websocketx.WebSocketServerHandshaker) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) HttpServerOptions(io.vertx.core.http.HttpServerOptions) ChannelHandler(io.netty.channel.ChannelHandler) ChannelGroupFuture(io.netty.channel.group.ChannelGroupFuture) HttpContentDecompressor(io.netty.handler.codec.http.HttpContentDecompressor) HttpRequestDecoder(io.netty.handler.codec.http.HttpRequestDecoder) HttpHeaderNames(io.netty.handler.codec.http.HttpHeaderNames) Handler(io.vertx.core.Handler) SocketAddressImpl(io.vertx.core.net.impl.SocketAddressImpl) Http2CodecUtil(io.netty.handler.codec.http2.Http2CodecUtil) NioServerSocketChannel(io.netty.channel.socket.nio.NioServerSocketChannel) Channel(io.netty.channel.Channel) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) VertxException(io.vertx.core.VertxException) URISyntaxException(java.net.URISyntaxException) Http2Exception(io.netty.handler.codec.http2.Http2Exception) WebSocketHandshakeException(io.netty.handler.codec.http.websocketx.WebSocketHandshakeException) ChannelPipeline(io.netty.channel.ChannelPipeline) ApplicationProtocolNegotiationHandler(io.netty.handler.ssl.ApplicationProtocolNegotiationHandler) ServerID(io.vertx.core.net.impl.ServerID) HttpServer(io.vertx.core.http.HttpServer) SocketAddressImpl(io.vertx.core.net.impl.SocketAddressImpl) HttpVersion(io.vertx.core.http.HttpVersion) HttpVersion(io.netty.handler.codec.http.HttpVersion)

Example 7 with HttpServer

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

the class RestServerVerticle method start.

@Override
public void start(Future<Void> startFuture) throws Exception {
    super.start();
    // 如果本地未配置地址,则表示不必监听,只需要作为客户端使用即可
    if (endpointObject == null) {
        LOGGER.warn("rest listen address is not configured, will not start.");
        startFuture.complete();
        return;
    }
    Router mainRouter = Router.router(vertx);
    mainRouter.route().handler(bodyHandler);
    VertxRestServer vertxRestServer = new VertxRestServer(mainRouter);
    vertxRestServer.setTransport(CseContext.getInstance().getTransportManager().findTransport(Const.RESTFUL));
    HttpServer httpServer = createHttpServer();
    httpServer.requestHandler(mainRouter::accept);
    startListen(httpServer, startFuture);
}
Also used : HttpServer(io.vertx.core.http.HttpServer) Router(io.vertx.ext.web.Router)

Example 8 with HttpServer

use of io.vertx.core.http.HttpServer in project vertx-swagger by bobxwang.

the class SwaggerApp method Run.

public static AnnotationConfigApplicationContext Run(Class<?> clasz) {
    final AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(clasz);
    BeanDefinitionBuilder bdb = BeanDefinitionBuilder.rootBeanDefinition(ApplicationContextHolder.class);
    applicationContext.registerBeanDefinition("applicationContextHolder", bdb.getBeanDefinition());
    // Just For Init
    applicationContext.getBean(ApplicationContextHolder.class);
    final Environment environment = applicationContext.getBean(Environment.class);
    final Vertx vertx = applicationContext.getBean(Vertx.class);
    final SpringVerticleFactory verticleFactory = new SpringVerticleFactory();
    vertx.registerVerticleFactory(verticleFactory);
    try {
        applicationContext.getBean(Router.class);
    } catch (BeansException be) {
        if (be instanceof NoSuchBeanDefinitionException) {
            Router rr = new RouterImpl(vertx);
            applicationContext.getBeanFactory().registerSingleton("router", rr);
        }
    }
    final Router router = applicationContext.getBean(Router.class);
    initSwagger(environment);
    configRouter(vertx, router, environment);
    Map<String, Verticle> maps = applicationContext.getBeansOfType(Verticle.class);
    DeploymentOptions options = new DeploymentOptions().setInstances(1).setWorker(true);
    for (Map.Entry<String, Verticle> temp : maps.entrySet()) {
        Verticle verticle = temp.getValue();
        String name = verticle.getClass().getSimpleName().substring(0, 1).toLowerCase() + verticle.getClass().getSimpleName().substring(1);
        vertx.deployVerticle(verticleFactory.prefix() + ":" + name, options);
        for (Method method : verticle.getClass().getDeclaredMethods()) {
            if (method.isAnnotationPresent(Override.class)) {
                continue;
            }
            if (method.getName().contains("lambda")) {
                continue;
            }
            if (io.swagger.util.ReflectionUtils.isOverriddenMethod(method, verticle.getClass())) {
                continue;
            }
            if (method.isAnnotationPresent(BBRouter.class)) {
                BBRouter bbRouter = io.swagger.util.ReflectionUtils.getAnnotation(method, BBRouter.class);
                Route route = router.route(bbRouter.httpMethod(), bbRouter.path());
                route.handler(ctx -> {
                    ReflectionUtils.makeAccessible(method);
                    ReflectionUtils.invokeMethod(method, verticle, ctx);
                });
            }
        }
    }
    HttpServer httpServer = vertx.createHttpServer(new HttpServerOptions().setSsl(false).setKeyStoreOptions(new JksOptions().setPath("server-keystore.jks").setPassword("secret")));
    httpServer.requestHandler(router::accept);
    int port;
    try {
        port = Integer.valueOf(environment.getProperty("server.port", "8080"));
    } catch (Exception e) {
        throw new RuntimeException("请配置有效端口号");
    }
    httpServer.listen(port, ar -> {
        if (ar.succeeded()) {
            logger.info("Server started on port " + ar.result().actualPort());
        } else {
            logger.error("Cannot start the server: " + ar.cause());
        }
    });
    return applicationContext;
}
Also used : BBRouter(com.bob.vertx.swagger.BBRouter) HttpServerOptions(io.vertx.core.http.HttpServerOptions) RouterImpl(io.vertx.ext.web.impl.RouterImpl) HttpServer(io.vertx.core.http.HttpServer) Route(io.vertx.ext.web.Route) BeansException(org.springframework.beans.BeansException) AnnotationConfigApplicationContext(org.springframework.context.annotation.AnnotationConfigApplicationContext) Router(io.vertx.ext.web.Router) BBRouter(com.bob.vertx.swagger.BBRouter) Method(java.lang.reflect.Method) HttpMethod(io.vertx.core.http.HttpMethod) Vertx(io.vertx.core.Vertx) BeansException(org.springframework.beans.BeansException) NoSuchBeanDefinitionException(org.springframework.beans.factory.NoSuchBeanDefinitionException) BeanDefinitionBuilder(org.springframework.beans.factory.support.BeanDefinitionBuilder) Verticle(io.vertx.core.Verticle) DeploymentOptions(io.vertx.core.DeploymentOptions) JksOptions(io.vertx.core.net.JksOptions) Environment(org.springframework.core.env.Environment) NoSuchBeanDefinitionException(org.springframework.beans.factory.NoSuchBeanDefinitionException) Map(java.util.Map)

Example 9 with HttpServer

use of io.vertx.core.http.HttpServer in project vertx-examples by vert-x3.

the class VertxHttpServer method start.

@Validate
public void start() throws Exception {
    LOGGER.info("Creating vertx HTTP server");
    HttpServer server = executeWithTCCLSwitch(() -> vertx.createHttpServer());
    server.requestHandler((r) -> {
        r.response().end("Hello from OSGi !");
    }).listen(8080);
}
Also used : TcclSwitch.executeWithTCCLSwitch(io.vertx.example.osgi.TcclSwitch.executeWithTCCLSwitch) HttpServer(io.vertx.core.http.HttpServer) Vertx(io.vertx.core.Vertx) Logger(java.util.logging.Logger) org.apache.felix.ipojo.annotations(org.apache.felix.ipojo.annotations) HttpServer(io.vertx.core.http.HttpServer)

Example 10 with HttpServer

use of io.vertx.core.http.HttpServer in project vertx-examples by vert-x3.

the class DashboardVerticle method start.

@Override
public void start() throws Exception {
    Router router = Router.router(vertx);
    // The event bus bridge handler
    BridgeOptions options = new BridgeOptions();
    options.setOutboundPermitted(Collections.singletonList(new PermittedOptions().setAddress("dashboard")));
    router.route("/eventbus/*").handler(SockJSHandler.create(vertx).bridge(options));
    // The web server handler
    router.route().handler(StaticHandler.create().setCachingEnabled(false));
    // Start http server
    HttpServer httpServer = vertx.createHttpServer();
    httpServer.requestHandler(router::accept).listen(8080, ar -> {
        if (ar.succeeded()) {
            System.out.println("Http server started");
        } else {
            ar.cause().printStackTrace();
        }
    });
    // Our dashboard that aggregates metrics from various kafka topics
    JsonObject dashboard = new JsonObject();
    // Publish the dashboard to the browser over the bus
    vertx.setPeriodic(1000, timerID -> {
        vertx.eventBus().publish("dashboard", dashboard);
    });
    // Get the Kafka consumer config
    JsonObject config = config();
    // Create the consumer
    KafkaReadStream<String, JsonObject> consumer = KafkaReadStream.create(vertx, config.getMap(), String.class, JsonObject.class);
    // Aggregates metrics in the dashboard
    consumer.handler(record -> {
        JsonObject obj = record.value();
        dashboard.mergeIn(obj);
    });
    // Subscribe to Kafka
    consumer.subscribe(Collections.singleton("the_topic"));
}
Also used : HttpServer(io.vertx.core.http.HttpServer) Router(io.vertx.ext.web.Router) JsonObject(io.vertx.core.json.JsonObject) BridgeOptions(io.vertx.ext.web.handler.sockjs.BridgeOptions) PermittedOptions(io.vertx.ext.web.handler.sockjs.PermittedOptions)

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