Search in sources :

Example 1 with CorsHandler

use of io.vertx.ext.web.handler.CorsHandler in project vertx-swagger by bobxwang.

the class SwaggerApp method configRouter.

private static void configRouter(final Vertx vertx, final Router router, final Environment environment) {
    router.route().handler(BodyHandler.create());
    if (environment.getProperty("server.iscors", "false").contentEquals("true")) {
        CorsHandler corsHandler;
        String value = environment.getProperty("server.allowedoriginpattern");
        if (Strings.isNullOrEmpty(value)) {
            corsHandler = CorsHandler.create("*");
        } else {
            corsHandler = CorsHandler.create(value);
        }
        value = environment.getProperty("server.allowed.method");
        if (Strings.isNullOrEmpty(value)) {
            corsHandler.allowedMethods(Sets.newHashSet(HttpMethod.values()));
        } else {
            if (value.contains(";")) {
                String[] methods = value.split(";");
                for (String m : methods) {
                    configCorsAllowedMethod(corsHandler, m);
                }
            } else {
                configCorsAllowedMethod(corsHandler, value);
            }
        }
        value = environment.getProperty("server.maxageseconds");
        if (!Strings.isNullOrEmpty(value)) {
            try {
                corsHandler.maxAgeSeconds(Integer.valueOf(value));
            } catch (NumberFormatException e) {
                logger.warn("server.maxageseconds值请配置成整数" + e.getMessage(), e);
            }
        }
        router.route().handler(corsHandler);
    }
    router.route("/static/*").handler(StaticHandler.create());
    Router swaggerRouter = Router.router(vertx);
    router.mountSubRouter("/swagger", swaggerRouter);
    swaggerRouter.get("/definition.json").handler(ctx -> {
        ctx.response().putHeader("content-type", "application/json;charset=UTF-8").end(Json.encodePrettily(swagger));
    });
    Router sRouter = Router.router(vertx);
    router.mountSubRouter("/v2", sRouter);
    sRouter.get("/api-docs").handler(ctx -> ctx.response().putHeader("content-type", "application/json;charset=UTF-8").end(Json.encodePrettily(swagger)));
}
Also used : Router(io.vertx.ext.web.Router) BBRouter(com.bob.vertx.swagger.BBRouter) CorsHandler(io.vertx.ext.web.handler.CorsHandler)

Example 2 with CorsHandler

use of io.vertx.ext.web.handler.CorsHandler in project VX-API-Gateway by EliMirren.

the class VxApiApplication method createHttpsServer.

/**
 * 创建https服务器
 *
 * @param createHttp
 */
public void createHttpsServer(Handler<AsyncResult<Void>> createHttps) {
    this.httpsRouter = Router.router(vertx);
    httpsRouter.route().handler(this::filterBlackIP);
    httpsRouter.route().handler(CookieHandler.create());
    SessionStore sessionStore = null;
    if (vertx.isClustered()) {
        sessionStore = ClusteredSessionStore.create(vertx);
    } else {
        sessionStore = LocalSessionStore.create(vertx);
    }
    SessionHandler sessionHandler = SessionHandler.create(sessionStore);
    sessionHandler.setSessionCookieName(appOption.getSessionCookieName());
    sessionHandler.setSessionTimeout(appOption.getSessionTimeOut());
    httpsRouter.route().handler(sessionHandler);
    httpsRouter.route().handler(BodyHandler.create().setUploadsDirectory("../temp/file-uploads").setBodyLimit(appOption.getContentLength()));
    // 跨域处理
    if (corsOptions != null) {
        CorsHandler corsHandler = CorsHandler.create(corsOptions.getAllowedOrigin());
        corsHandler.allowedHeaders(corsOptions.getAllowedHeaders()).allowCredentials(corsOptions.isAllowCredentials()).exposedHeaders(corsOptions.getExposedHeaders()).allowedMethods(corsOptions.getAllowedMethods()).maxAgeSeconds(corsOptions.getMaxAgeSeconds());
        httpsRouter.route().handler(corsHandler);
    }
    // 创建https服务器
    serverOptions.setSsl(true);
    VxApiCertOptions certOptions = serverOptions.getCertOptions();
    if (certOptions.getCertType().equalsIgnoreCase("pem")) {
        serverOptions.setPemKeyCertOptions(new PemKeyCertOptions().setCertPath(certOptions.getCertPath()).setKeyPath(certOptions.getCertKey()));
    } else if (certOptions.getCertType().equalsIgnoreCase("pfx")) {
        serverOptions.setPfxKeyCertOptions(new PfxOptions().setPath(certOptions.getCertPath()).setPassword(certOptions.getCertKey()));
    } else {
        LOG.error("创建https服务器-->失败:无效的证书类型,只支持pem/pfx格式的证书");
        createHttps.handle(Future.failedFuture("创建https服务器-->失败:无效的证书类型,只支持pem/pfx格式的证书"));
        return;
    }
    Future<Boolean> createFuture = Future.future();
    vertx.fileSystem().exists(certOptions.getCertPath(), createFuture);
    createFuture.setHandler(check -> {
        if (check.succeeded()) {
            if (check.result()) {
                // 404页面
                httpsRouter.route().order(999999).handler(rct -> {
                    HttpServerResponse response = rct.response();
                    if (appOption.getNotFoundContentType() != null) {
                        response.putHeader("Content-Type", appOption.getNotFoundContentType());
                    }
                    response.end(appOption.getNotFoundResult());
                });
                // 如果在linux系统开启epoll
                if (vertx.isNativeTransportEnabled()) {
                    serverOptions.setTcpFastOpen(true).setTcpCork(true).setTcpQuickAck(true).setReusePort(true);
                }
                vertx.createHttpServer(serverOptions).requestHandler(httpsRouter::accept).listen(serverOptions.getHttpsPort(), res -> {
                    if (res.succeeded()) {
                        System.out.println(appOption.getAppName() + " Running on port " + serverOptions.getHttpsPort() + " by HTTPS");
                        createHttps.handle(Future.succeededFuture());
                    } else {
                        System.out.println("create HTTPS Server failed : " + res.cause());
                        createHttps.handle(Future.failedFuture(res.cause()));
                    }
                });
            } else {
                LOG.error("执行创建https服务器-->失败:无效的证书或者错误的路径:如果证书存放在conf/cert中,路径可以从cert/开始,示例:cert/XXX.XXX");
                createHttps.handle(Future.failedFuture("无效的证书或者错误的路径"));
            }
        } else {
            LOG.error("执行创建https服务器-->失败:无效的证书或者错误的路径:如果证书存放在conf/cert中,路径可以从cert/开始,示例:cert/XXX.XXX", check.cause());
            createHttps.handle(Future.failedFuture(check.cause()));
        }
    });
}
Also used : ClusteredSessionStore(io.vertx.ext.web.sstore.ClusteredSessionStore) SessionStore(io.vertx.ext.web.sstore.SessionStore) LocalSessionStore(io.vertx.ext.web.sstore.LocalSessionStore) SessionHandler(io.vertx.ext.web.handler.SessionHandler) PemKeyCertOptions(io.vertx.core.net.PemKeyCertOptions) HttpServerResponse(io.vertx.core.http.HttpServerResponse) CorsHandler(io.vertx.ext.web.handler.CorsHandler) VxApiCertOptions(com.szmirren.vxApi.core.options.VxApiCertOptions) PfxOptions(io.vertx.core.net.PfxOptions)

Example 3 with CorsHandler

use of io.vertx.ext.web.handler.CorsHandler in project java-chassis by ServiceComb.

the class TestRestServerVerticle method testMountCorsHandler.

@Test
public void testMountCorsHandler() {
    ArchaiusUtils.setProperty("servicecomb.cors.enabled", true);
    ArchaiusUtils.setProperty("servicecomb.cors.allowedMethod", "GET,PUT,POST");
    ArchaiusUtils.setProperty("servicecomb.cors.allowedHeader", "abc,def");
    ArchaiusUtils.setProperty("servicecomb.cors.exposedHeader", "abc2,def2");
    ArchaiusUtils.setProperty("servicecomb.cors.maxAge", 1);
    Set<HttpMethod> methodSet = new HashSet<>(3);
    methodSet.add(HttpMethod.GET);
    methodSet.add(HttpMethod.PUT);
    methodSet.add(HttpMethod.POST);
    AtomicInteger counter = new AtomicInteger(0);
    CorsHandler corsHandler = new MockUp<CorsHandler>() {

        @Mock
        CorsHandler allowCredentials(boolean allow) {
            Assert.assertFalse(allow);
            counter.incrementAndGet();
            return null;
        }

        @Mock
        CorsHandler allowedHeaders(Set<String> headerNames) {
            Assert.assertThat(headerNames, Matchers.containsInAnyOrder("abc", "def"));
            counter.incrementAndGet();
            return null;
        }

        @Mock
        CorsHandler exposedHeaders(Set<String> headerNames) {
            Assert.assertThat(headerNames, Matchers.containsInAnyOrder("abc2", "def2"));
            counter.incrementAndGet();
            return null;
        }

        @Mock
        CorsHandler allowedMethod(HttpMethod method) {
            Assert.assertTrue(methodSet.contains(method));
            counter.incrementAndGet();
            methodSet.remove(method);
            return null;
        }

        @Mock
        CorsHandler maxAgeSeconds(int maxAgeSeconds) {
            Assert.assertEquals(1, maxAgeSeconds);
            counter.incrementAndGet();
            return null;
        }
    }.getMockInstance();
    new MockUp<RestServerVerticle>() {

        @Mock
        CorsHandler getCorsHandler(String corsAllowedOrigin) {
            Assert.assertEquals("*", corsAllowedOrigin);
            return corsHandler;
        }
    };
    Router router = Mockito.mock(Router.class);
    Mockito.when(router.route()).thenReturn(Mockito.mock(Route.class));
    RestServerVerticle server = new RestServerVerticle();
    Deencapsulation.invoke(server, "mountCorsHandler", router);
    Assert.assertEquals(7, counter.get());
}
Also used : Router(io.vertx.ext.web.Router) CorsHandler(io.vertx.ext.web.handler.CorsHandler) MockUp(mockit.MockUp) Mock(mockit.Mock) Endpoint(org.apache.servicecomb.core.Endpoint) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) HttpMethod(io.vertx.core.http.HttpMethod) Route(io.vertx.ext.web.Route) HashSet(java.util.HashSet) Test(org.junit.Test)

Example 4 with CorsHandler

use of io.vertx.ext.web.handler.CorsHandler in project VX-API-Gateway by EliMirren.

the class VxApiApplication method createHttpServer.

/**
 * 创建http服务器
 *
 * @param createHttp
 */
public void createHttpServer(Handler<AsyncResult<Void>> createHttp) {
    this.httpRouter = Router.router(vertx);
    httpRouter.route().handler(this::filterBlackIP);
    httpRouter.route().handler(CookieHandler.create());
    SessionStore sessionStore = null;
    if (vertx.isClustered()) {
        sessionStore = ClusteredSessionStore.create(vertx);
    } else {
        sessionStore = LocalSessionStore.create(vertx);
    }
    SessionHandler sessionHandler = SessionHandler.create(sessionStore);
    sessionHandler.setSessionCookieName(appOption.getSessionCookieName());
    sessionHandler.setSessionTimeout(appOption.getSessionTimeOut());
    httpRouter.route().handler(sessionHandler);
    httpRouter.route().handler(BodyHandler.create().setUploadsDirectory("../temp/file-uploads").setBodyLimit(appOption.getContentLength()));
    // 跨域处理
    if (corsOptions != null) {
        CorsHandler corsHandler = CorsHandler.create(corsOptions.getAllowedOrigin());
        corsHandler.allowedHeaders(corsOptions.getAllowedHeaders()).allowCredentials(corsOptions.isAllowCredentials()).exposedHeaders(corsOptions.getExposedHeaders()).allowedMethods(corsOptions.getAllowedMethods()).maxAgeSeconds(corsOptions.getMaxAgeSeconds());
        httpRouter.route().handler(corsHandler);
    }
    // 如果在linux系统开启epoll
    if (vertx.isNativeTransportEnabled()) {
        serverOptions.setTcpFastOpen(true).setTcpCork(true).setTcpQuickAck(true).setReusePort(true);
    }
    // 404页面
    httpRouter.route().order(999999).handler(rct -> {
        HttpServerResponse response = rct.response();
        if (appOption.getNotFoundContentType() != null) {
            response.putHeader("Content-Type", appOption.getNotFoundContentType());
        }
        response.end(appOption.getNotFoundResult());
    });
    // 创建http服务器
    vertx.createHttpServer(serverOptions).requestHandler(httpRouter::accept).listen(serverOptions.getHttpPort(), res -> {
        if (res.succeeded()) {
            System.out.println(MessageFormat.format("{0} Running on port {1} by HTTP", appOption.getAppName(), Integer.toString(serverOptions.getHttpPort())));
            createHttp.handle(Future.succeededFuture());
        } else {
            System.out.println("create HTTP Server failed : " + res.cause());
            createHttp.handle(Future.failedFuture(res.cause()));
        }
    });
}
Also used : ClusteredSessionStore(io.vertx.ext.web.sstore.ClusteredSessionStore) SessionStore(io.vertx.ext.web.sstore.SessionStore) LocalSessionStore(io.vertx.ext.web.sstore.LocalSessionStore) SessionHandler(io.vertx.ext.web.handler.SessionHandler) HttpServerResponse(io.vertx.core.http.HttpServerResponse) CorsHandler(io.vertx.ext.web.handler.CorsHandler)

Example 5 with CorsHandler

use of io.vertx.ext.web.handler.CorsHandler in project java-chassis by ServiceComb.

the class RestServerVerticle method mountCorsHandler.

/**
 * Support CORS
 */
void mountCorsHandler(Router mainRouter) {
    if (!TransportConfig.isCorsEnabled()) {
        return;
    }
    CorsHandler corsHandler = getCorsHandler(TransportConfig.getCorsAllowedOrigin());
    // Access-Control-Allow-Credentials
    corsHandler.allowCredentials(TransportConfig.isCorsAllowCredentials());
    // Access-Control-Allow-Headers
    corsHandler.allowedHeaders(TransportConfig.getCorsAllowedHeaders());
    // Access-Control-Allow-Methods
    Set<String> allowedMethods = TransportConfig.getCorsAllowedMethods();
    for (String method : allowedMethods) {
        corsHandler.allowedMethod(HttpMethod.valueOf(method));
    }
    // Access-Control-Expose-Headers
    corsHandler.exposedHeaders(TransportConfig.getCorsExposedHeaders());
    // Access-Control-Max-Age
    int maxAge = TransportConfig.getCorsMaxAge();
    if (maxAge >= 0) {
        corsHandler.maxAgeSeconds(maxAge);
    }
    LOGGER.info("mount CorsHandler");
    mainRouter.route().handler(corsHandler);
}
Also used : CorsHandler(io.vertx.ext.web.handler.CorsHandler) Endpoint(org.apache.servicecomb.core.Endpoint)

Aggregations

CorsHandler (io.vertx.ext.web.handler.CorsHandler)5 HttpServerResponse (io.vertx.core.http.HttpServerResponse)2 Router (io.vertx.ext.web.Router)2 SessionHandler (io.vertx.ext.web.handler.SessionHandler)2 ClusteredSessionStore (io.vertx.ext.web.sstore.ClusteredSessionStore)2 LocalSessionStore (io.vertx.ext.web.sstore.LocalSessionStore)2 SessionStore (io.vertx.ext.web.sstore.SessionStore)2 Endpoint (org.apache.servicecomb.core.Endpoint)2 BBRouter (com.bob.vertx.swagger.BBRouter)1 VxApiCertOptions (com.szmirren.vxApi.core.options.VxApiCertOptions)1 HttpMethod (io.vertx.core.http.HttpMethod)1 PemKeyCertOptions (io.vertx.core.net.PemKeyCertOptions)1 PfxOptions (io.vertx.core.net.PfxOptions)1 Route (io.vertx.ext.web.Route)1 HashSet (java.util.HashSet)1 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)1 Mock (mockit.Mock)1 MockUp (mockit.MockUp)1 Test (org.junit.Test)1