io.vertx.ext.web.api.contract.RouterFactoryOptions Java Examples

The following examples show how to use io.vertx.ext.web.api.contract.RouterFactoryOptions. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: OpenAPI3RouterFactoryTest.java    From vertx-web with Apache License 2.0 6 votes vote down vote up
@Test
public void pathResolverShouldNotCreateRegex() throws Exception {
  CountDownLatch latch = new CountDownLatch(1);
  OpenAPI3RouterFactory.create(this.vertx, "src/test/resources/swaggers/produces_consumes_test.yaml",
    openAPI3RouterFactoryAsyncResult -> {
      routerFactory = openAPI3RouterFactoryAsyncResult.result();
      routerFactory.setOptions(new RouterFactoryOptions().setMountNotImplementedHandler(false));

      routerFactory.addHandlerByOperationId("consumesTest", routingContext ->
        routingContext
          .response()
          .setStatusCode(200)
          .setStatusMessage("OK")
      );

      latch.countDown();
    });
  awaitLatch(latch);

  router = routerFactory.getRouter();

  assertTrue(router.getRoutes().stream().map(Route::getPath).anyMatch("/consumesTest"::equals));
}
 
Example #2
Source File: OpenAPI3Examples.java    From vertx-web with Apache License 2.0 6 votes vote down vote up
public void addOperationModelKey(OpenAPI3RouterFactory routerFactory, RouterFactoryOptions options) {
  // Configure the operation model key and set options in router factory
  options.setOperationModelKey("operationPOJO");
  routerFactory.setOptions(options);

  // Add an handler that uses the operation model
  routerFactory.addHandlerByOperationId("listPets", routingContext -> {
    io.swagger.v3.oas.models.Operation operation = routingContext.get("operationPOJO");

    routingContext
      .response()
      .setStatusCode(200)
      .setStatusMessage("OK")
      // Write the response with operation id "listPets"
      .end(operation.getOperationId());
  });
}
 
Example #3
Source File: OpenAPI3RouterFactoryTest.java    From vertx-web with Apache License 2.0 6 votes vote down vote up
@Test
public void producesTest() throws Exception {
  CountDownLatch latch = new CountDownLatch(1);
  OpenAPI3RouterFactory.create(this.vertx, "src/test/resources/swaggers/produces_consumes_test.yaml",
    openAPI3RouterFactoryAsyncResult -> {
      routerFactory = openAPI3RouterFactoryAsyncResult.result();
      routerFactory.setOptions(new RouterFactoryOptions().setMountNotImplementedHandler(false));

      routerFactory.addHandlerByOperationId("producesTest", routingContext -> {
        if (((RequestParameters) routingContext.get("parsedParameters")).queryParameter("fail").getBoolean())
          routingContext.response().putHeader("content-type", "text/plain").setStatusCode(500).end("Hate it");
        else
          routingContext.response().setStatusCode(200).end("{}"); // ResponseContentTypeHandler does the job for me
      });

      latch.countDown();
    });
  awaitLatch(latch);

  startServer();

  List<String> acceptableContentTypes = Stream.of("application/json", "text/plain").collect(Collectors.toList());
  testRequestWithResponseContentTypeCheck(HttpMethod.GET, "/producesTest", 200, "application/json", acceptableContentTypes);
  testRequestWithResponseContentTypeCheck(HttpMethod.GET, "/producesTest?fail=true", 500, "text/plain", acceptableContentTypes);

}
 
Example #4
Source File: OpenAPI3RouterFactoryTest.java    From vertx-web with Apache License 2.0 6 votes vote down vote up
@Test
public void exposeConfigurationTest() throws Exception {
  CountDownLatch latch = new CountDownLatch(1);
  OpenAPI3RouterFactory.create(this.vertx, "src/test/resources/swaggers/router_factory_test.yaml",
    openAPI3RouterFactoryAsyncResult -> {
      routerFactory = openAPI3RouterFactoryAsyncResult.result();
      routerFactory.setOptions(new RouterFactoryOptions().setRequireSecurityHandlers(false).setOperationModelKey("fooBarKey"));

      routerFactory.addHandlerByOperationId("listPets", routingContext -> {
        Operation operation = routingContext.get("fooBarKey");

        routingContext
          .response()
          .setStatusCode(200)
          .setStatusMessage("OK")
          .end(operation.getOperationId());
      });

      latch.countDown();
    });
  awaitLatch(latch);

  startServer();

  testRequest(HttpMethod.GET, "/pets", 200, "OK", "listPets");
}
 
Example #5
Source File: OpenAPI3RouterFactoryTest.java    From vertx-web with Apache License 2.0 6 votes vote down vote up
@Test
public void mountWithArrayParameter() throws Exception {
 CountDownLatch latch = new CountDownLatch(1);
   OpenAPI3RouterFactory.create(this.vertx, "src/test/resources/swaggers/scenario_with_array_parameter.yaml",
     openAPI3RouterFactoryAsyncResult -> {
       routerFactory = openAPI3RouterFactoryAsyncResult.result();
       routerFactory.setOptions(new RouterFactoryOptions().setRequireSecurityHandlers(false));

       routerFactory.addHandlerByOperationId("getThings", routingContext -> routingContext
         .response()
         .setStatusCode(200)
         .setStatusMessage("OK")
         .end());

       latch.countDown();
     });
   awaitLatch(latch);

   startServer();

   testRequest(HttpMethod.GET, "/things?filter=[{\"field\":\"size\",\"operator\":\"gt\",\"value\":\"20\"},]", 200, "OK");
}
 
Example #6
Source File: OpenAPI3SchemasTest.java    From vertx-web with Apache License 2.0 6 votes vote down vote up
@Override
public void setUp() throws Exception {
  super.setUp();
  stopServer(); // Have to stop default server of WebTestBase
  startSchemaServer();

  CountDownLatch latch = new CountDownLatch(1);
  OpenAPI3RouterFactory.create(this.vertx, OAS_PATH, openAPI3RouterFactoryAsyncResult -> {
    assertTrue(openAPI3RouterFactoryAsyncResult.succeeded());
    assertNull(openAPI3RouterFactoryAsyncResult.cause());
    routerFactory = openAPI3RouterFactoryAsyncResult.result();
    routerFactory.setOptions(
      new RouterFactoryOptions()
      .setRequireSecurityHandlers(false)
      .setMountValidationFailureHandler(true)
      .setMountNotImplementedHandler(false)
    );
    routerFactory.setValidationFailureHandler(FAILURE_HANDLER);
    latch.countDown();
  });
  awaitLatch(latch);

  client = vertx.createHttpClient(new HttpClientOptions().setDefaultPort(8080));
}
 
Example #7
Source File: OpenAPI3RouterFactoryTest.java    From vertx-web with Apache License 2.0 6 votes vote down vote up
@Test
public void notMountNotImplementedHandler() throws Exception {
  CountDownLatch latch = new CountDownLatch(1);
  OpenAPI3RouterFactory.create(this.vertx, "src/test/resources/swaggers/router_factory_test.yaml",
    openAPI3RouterFactoryAsyncResult -> {
      routerFactory = openAPI3RouterFactoryAsyncResult.result();
      routerFactory.setOptions(
        new RouterFactoryOptions()
          .setMountNotImplementedHandler(false)
      );

      latch.countDown();
    });
  awaitLatch(latch);

  startServer();

  testRequest(HttpMethod.GET, "/pets", 404, "Not Found");
}
 
Example #8
Source File: OpenAPI3RouterFactoryTest.java    From vertx-web with Apache License 2.0 6 votes vote down vote up
@Test
public void mountNotImplementedHandler() throws Exception {
  CountDownLatch latch = new CountDownLatch(1);
  OpenAPI3RouterFactory.create(this.vertx, "src/test/resources/swaggers/router_factory_test.yaml",
    openAPI3RouterFactoryAsyncResult -> {
      routerFactory = openAPI3RouterFactoryAsyncResult.result();
      routerFactory.setOptions(
        new RouterFactoryOptions()
          .setRequireSecurityHandlers(false)
          .setMountNotImplementedHandler(true)
      );

      routerFactory.addHandlerByOperationId("showPetById", RoutingContext::next);

      latch.countDown();
    });
  awaitLatch(latch);

  startServer();

  testRequest(HttpMethod.GET, "/pets", 501, "Not Implemented");
}
 
Example #9
Source File: OpenAPI3RouterFactoryTest.java    From vertx-web with Apache License 2.0 6 votes vote down vote up
@Test
public void notRequireSecurityHandler() throws Exception {
  CountDownLatch latch = new CountDownLatch(1);
  OpenAPI3RouterFactory.create(this.vertx, "src/test/resources/swaggers/router_factory_test.yaml",
    openAPI3RouterFactoryAsyncResult -> {
      routerFactory = openAPI3RouterFactoryAsyncResult.result();
      routerFactory.setOptions(new RouterFactoryOptions().setRequireSecurityHandlers(false));

      routerFactory.addHandlerByOperationId("listPets", routingContext -> routingContext
        .response()
        .setStatusCode(200)
        .setStatusMessage(routingContext.get("message") + "OK")
        .end());

      latch.countDown();
    });
  awaitLatch(latch);

  assertNotThrow(() -> routerFactory.getRouter(), RouterFactoryException.class);
}
 
Example #10
Source File: OpenAPI3RouterFactoryTest.java    From vertx-web with Apache License 2.0 5 votes vote down vote up
@Test
public void notMountValidationFailureHandler() throws Exception {
  CountDownLatch latch = new CountDownLatch(1);
  OpenAPI3RouterFactory.create(this.vertx, "src/test/resources/swaggers/router_factory_test.yaml",
    openAPI3RouterFactoryAsyncResult -> {
      routerFactory = openAPI3RouterFactoryAsyncResult.result();
      routerFactory.setOptions(
        new RouterFactoryOptions()
          .setRequireSecurityHandlers(false)
          .setMountValidationFailureHandler(false)
      );

      routerFactory.addHandlerByOperationId("listPets", routingContext -> routingContext
        .response()
        .setStatusCode(200)
        .setStatusMessage(((RequestParameters) routingContext.get("parsedParameters")).queryParameter("limit").toString())
        .end());

      routerFactory.addFailureHandlerByOperationId("listPets", routingContext -> routingContext
        .response()
        .setStatusCode((routingContext.failure() instanceof ValidationException) ? 400 : 500)
        .setStatusMessage((routingContext.failure() instanceof ValidationException) ? "Very very Bad Request" : "Error")
        .end());

      latch.countDown();
    });
  awaitLatch(latch);

  startServer();

  testRequest(HttpMethod.GET, "/pets?limit=hello", 400, "Very very Bad Request");
  testRequest(HttpMethod.GET, "/pets?limit=10", 200, "10");
}
 
Example #11
Source File: OpenAPI3RouterFactoryTest.java    From vertx-web with Apache License 2.0 5 votes vote down vote up
@Test
public void testJsonEmptyBody() throws Exception {
  CountDownLatch latch = new CountDownLatch(1);
  OpenAPI3RouterFactory.create(this.vertx, "src/test/resources/swaggers/router_factory_test.yaml",
    onSuccess(routerFactory -> {
      this.routerFactory = routerFactory;
      routerFactory.setOptions(new RouterFactoryOptions().setRequireSecurityHandlers(false).setMountNotImplementedHandler(false));

      routerFactory.addHandlerByOperationId("jsonEmptyBody", routingContext -> {
        RequestParameters params = routingContext.get("parsedParameters");
        RequestParameter body = params.body();
        routingContext
          .response()
          .setStatusCode(200)
          .setStatusMessage("OK")
          .putHeader("Content-Type", "application/json")
          .end(new JsonObject().put("bodyEmpty", body == null).toBuffer());
      });

      latch.countDown();
    }));
  awaitLatch(latch);

  startServer();

  CountDownLatch requestLatch = new CountDownLatch(1);
  client
    .send(HttpMethod.POST, 8080, "localhost", "/jsonBody/empty", onSuccess(res -> {
      assertEquals(200, res.statusCode());
      assertEquals("application/json", res.getHeader(HttpHeaders.CONTENT_TYPE));
      res.bodyHandler(buff -> {
        JsonObject result = new JsonObject(normalizeLineEndingsFor(buff));
        assertEquals(new JsonObject().put("bodyEmpty", true), result);
        requestLatch.countDown();
      });
    }));
  awaitLatch(requestLatch);
}
 
Example #12
Source File: OpenAPI3RouterFactoryTest.java    From vertx-web with Apache License 2.0 5 votes vote down vote up
/**
 * Tests that user can supply customised BodyHandler
 *
 * @throws Exception
 */
@Test
public void customBodyHandlerTest() throws Exception {
  try {
    CountDownLatch latch = new CountDownLatch(1);
    OpenAPI3RouterFactory.create(this.vertx, "src/test/resources/swaggers/upload_test.yaml",
      openAPI3RouterFactoryAsyncResult -> {
        try {
          if (openAPI3RouterFactoryAsyncResult.succeeded()) {
            routerFactory = openAPI3RouterFactoryAsyncResult.result();
            routerFactory.setOptions(new RouterFactoryOptions().setRequireSecurityHandlers(false));

            routerFactory.setBodyHandler(BodyHandler.create("my-uploads"));

            routerFactory.addHandlerByOperationId("upload", (h) -> h.response().setStatusCode(201).end());
          } else {
            fail(openAPI3RouterFactoryAsyncResult.cause());
          }
        } finally {
          latch.countDown();
        }
      });
    awaitLatch(latch);

    startServer();

    // We're not uploading a real file, just triggering BodyHandler
    MultiMap form = MultiMap.caseInsensitiveMultiMap();

    assertFalse(Paths.get("./my-uploads").toFile().exists());

    testRequestWithForm(HttpMethod.POST, "/upload", FormType.MULTIPART, form, 201, "Created");

    // BodyHandler should create this custom directory for us
    assertTrue(Paths.get("./my-uploads").toFile().exists());
  } finally {
    Paths.get("./my-uploads").toFile().deleteOnExit();
  }
}
 
Example #13
Source File: OpenAPI3RouterFactoryTest.java    From vertx-web with Apache License 2.0 5 votes vote down vote up
@Test
public void mountHandlersOrderTest() throws Exception {
  CountDownLatch latch = new CountDownLatch(1);
  OpenAPI3RouterFactory.create(this.vertx, "src/test/resources/swaggers/test_order_spec.yaml",
    openAPI3RouterFactoryAsyncResult -> {
      assertTrue(openAPI3RouterFactoryAsyncResult.succeeded());
      routerFactory = openAPI3RouterFactoryAsyncResult.result();
      routerFactory.setOptions(new RouterFactoryOptions().setMountNotImplementedHandler(false));

      routerFactory.addHandlerByOperationId("showSpecialProduct", routingContext ->
        routingContext.response().setStatusMessage("special").end()
      );
      routerFactory.addFailureHandlerByOperationId("showSpecialProduct", generateFailureHandler(false));

      routerFactory.addHandlerByOperationId("showProductById", routingContext -> {
        RequestParameters params = routingContext.get("parsedParameters");
        routingContext.response().setStatusMessage(params.pathParameter("id").getInteger().toString()).end();
      });
      routerFactory.addFailureHandlerByOperationId("showProductById", generateFailureHandler(false));

      latch.countDown();
    });
  awaitLatch(latch);

  startServer();

  testRequest(HttpMethod.GET, "/product/special", 200, "special");
  testRequest(HttpMethod.GET, "/product/123", 200, "123");

  stopServer();
}
 
Example #14
Source File: OpenAPI3RouterFactoryTest.java    From vertx-web with Apache License 2.0 5 votes vote down vote up
@Test
public void addGlobalHandlersTest() throws Exception {
  CountDownLatch latch = new CountDownLatch(1);
  OpenAPI3RouterFactory.create(this.vertx, "src/test/resources/swaggers/router_factory_test.yaml",
    openAPI3RouterFactoryAsyncResult -> {
      routerFactory = openAPI3RouterFactoryAsyncResult.result();
      routerFactory.setOptions(new RouterFactoryOptions().setRequireSecurityHandlers(false));

      routerFactory.addGlobalHandler(rc -> {
        rc.response().putHeader("header-from-global-handler", "some dummy data");
        rc.next();
      });
      routerFactory.addGlobalHandler(rc -> {
          rc.response().putHeader("header-from-global-handler", "some more dummy data");
          rc.next();
      });

      routerFactory.addHandlerByOperationId("listPets", routingContext -> routingContext
        .response()
        .setStatusCode(200)
        .setStatusMessage("OK")
        .end());

      latch.countDown();
    });
  awaitLatch(latch);

  startServer();

  testRequest(HttpMethod.GET, "/pets", null,
    response -> assertEquals(response.getHeader("header-from-global-handler"),
      "some more dummy data"), 200, "OK", null);
}
 
Example #15
Source File: OpenAPI3RouterFactoryTest.java    From vertx-web with Apache License 2.0 5 votes vote down vote up
@Test
public void mountCustomNotImplementedHandler() throws Exception {
  CountDownLatch latch = new CountDownLatch(1);
  OpenAPI3RouterFactory.create(this.vertx, "src/test/resources/swaggers/router_factory_test.yaml",
    openAPI3RouterFactoryAsyncResult -> {
      routerFactory = openAPI3RouterFactoryAsyncResult.result();
      routerFactory.setOptions(
        new RouterFactoryOptions()
          .setMountNotImplementedHandler(true)
          .setRequireSecurityHandlers(false)
      );

      routerFactory.setNotImplementedFailureHandler(routingContext ->
        routingContext
          .response()
          .setStatusCode(501)
          .setStatusMessage("We are too lazy to implement this operation")
          .end()
      );

      latch.countDown();
    });
  awaitLatch(latch);

  startServer();

  testRequest(HttpMethod.GET, "/pets", 501, "We are too lazy to implement this operation");
}
 
Example #16
Source File: OpenAPI3RouterFactoryTest.java    From vertx-web with Apache License 2.0 5 votes vote down vote up
@Test
public void mountNotAllowedHandler() throws Exception {
  CountDownLatch latch = new CountDownLatch(1);
  OpenAPI3RouterFactory.create(this.vertx, "src/test/resources/swaggers/router_factory_test.yaml",
    openAPI3RouterFactoryAsyncResult -> {
      routerFactory = openAPI3RouterFactoryAsyncResult.result();
      routerFactory.setOptions(
        new RouterFactoryOptions()
          .setRequireSecurityHandlers(false)
          .setMountNotImplementedHandler(true)
      );

      routerFactory.addHandlerByOperationId("deletePets", RoutingContext::next);
      routerFactory.addHandlerByOperationId("createPets", RoutingContext::next);

      latch.countDown();
    });
  awaitLatch(latch);

  startServer();

  testRequest(HttpMethod.GET, "/pets", null, resp -> {
    assertTrue(
      Stream.of("DELETE", "POST").collect(Collectors.toSet())
        .equals(new HashSet<>(Arrays.asList(resp.getHeader("Allow").split(Pattern.quote(", ")))))
    );
  }, 405, "Method Not Allowed", null);
}
 
Example #17
Source File: XYZHubRESTVerticle.java    From xyz-hub with Apache License 2.0 5 votes vote down vote up
@Override
public void start(Future<Void> fut) {
  OpenAPI3RouterFactory.create(vertx, CONTRACT_LOCATION, ar -> {
    if (ar.succeeded()) {
      //Add the handlers
      final OpenAPI3RouterFactory routerFactory = ar.result();
      routerFactory.setOptions(new RouterFactoryOptions());
      featureApi = new FeatureApi(routerFactory);
      featureQueryApi = new FeatureQueryApi(routerFactory);
      spaceApi = new SpaceApi(routerFactory);

      final AuthHandler jwtHandler = createJWTHandler();
      routerFactory.addSecurityHandler("authToken", jwtHandler);

      final Router router = routerFactory.getRouter();
      //Add additional handler to the router
      router.route().failureHandler(XYZHubRESTVerticle::failureHandler);
      router.route().order(0)
          .handler(this::onRequestReceived)
          .handler(createCorsHandler());

      this.healthApi = new HealthApi(vertx, router);
      this.adminApi = new AdminApi(vertx, router, jwtHandler);

      //OpenAPI resources
      router.route("/hub/static/openapi/*").handler(createCorsHandler()).handler((routingContext -> {
        final HttpServerResponse res = routingContext.response();
        final String path = routingContext.request().path();
        if (path.endsWith("full.yaml")) {
          res.headers().add(CONTENT_LENGTH, String.valueOf(FULL_API.getBytes().length));
          res.write(FULL_API);
        } else if (path.endsWith("stable.yaml")) {
          res.headers().add(CONTENT_LENGTH, String.valueOf(STABLE_API.getBytes().length));
          res.write(STABLE_API);
        } else if (path.endsWith("experimental.yaml")) {
          res.headers().add(CONTENT_LENGTH, String.valueOf(EXPERIMENTAL_API.getBytes().length));
          res.write(EXPERIMENTAL_API);
        } else if (path.endsWith("contract.yaml")) {
          res.headers().add(CONTENT_LENGTH, String.valueOf(CONTRACT_API.getBytes().length));
          res.write(CONTRACT_API);
        } else {
          res.setStatusCode(HttpResponseStatus.NOT_FOUND.code());
        }

        res.end();
      }));

      //Static resources
      router.route("/hub/static/*").handler(StaticHandler.create().setIndexPage("index.html")).handler(createCorsHandler());
      if (Service.configuration.FS_WEB_ROOT != null) {
        logger.debug("Serving extra web-root folder in file-system with location: {}", Service.configuration.FS_WEB_ROOT);
        //noinspection ResultOfMethodCallIgnored
        new File(Service.configuration.FS_WEB_ROOT).mkdirs();
        router.route("/hub/static/*")
            .handler(StaticHandler.create(Service.configuration.FS_WEB_ROOT).setIndexPage("index.html"));
      }

      //Default NotFound handler
      router.route().last().handler(XYZHubRESTVerticle::notFoundHandler);

      vertx.createHttpServer(SERVER_OPTIONS)
          .requestHandler(router)
          .listen(
              Service.configuration.HTTP_PORT, result -> {
                if (result.succeeded()) {
                  createMessageServer(router, fut);
                } else {
                  logger.error("An error occurred, during the initialization of the server.", result.cause());
                  fut.fail(result.cause());
                }
              });
    } else {
      logger.error("An error occurred, during the creation of the router from the Open API specification file.", ar.cause());
    }
  });
}
 
Example #18
Source File: OpenAPI3RouterFactoryTest.java    From vertx-web with Apache License 2.0 5 votes vote down vote up
@Test
public void testGlobalSecurityHandler() throws Exception {
  final Handler<RoutingContext> handler = routingContext -> {
    routingContext
      .response()
      .setStatusCode(200)
      .setStatusMessage(((routingContext.get("message") != null) ? routingContext.get("message") + "-OK" : "OK"))
      .end();
  };

  CountDownLatch latch = new CountDownLatch(1);
  OpenAPI3RouterFactory.create(this.vertx, "src/test/resources/swaggers/global_security_test.yaml",
    openAPI3RouterFactoryAsyncResult -> {
      routerFactory = openAPI3RouterFactoryAsyncResult.result();
      routerFactory.setOptions(new RouterFactoryOptions().setRequireSecurityHandlers(true));

      routerFactory.addHandlerByOperationId("listPetsWithoutSecurity", handler);
      routerFactory.addHandlerByOperationId("listPetsWithOverride", handler);
      routerFactory.addHandlerByOperationId("listPetsWithoutOverride", handler);

      latch.countDown();
    });
  awaitLatch(latch);

  assertThrow(routerFactory::getRouter, RouterFactoryException.class);

  routerFactory.addSecurityHandler("global_api_key",
    routingContext -> routingContext.put("message", "Global").next()
  );

  routerFactory.addSecurityHandler("api_key",
    routingContext -> routingContext.put("message", "Local").next()
  );

  startServer();

  testRequest(HttpMethod.GET, "/petsWithoutSecurity", 200, "OK");
  testRequest(HttpMethod.GET, "/petsWithOverride", 200, "Local-OK");
  testRequest(HttpMethod.GET, "/petsWithoutOverride", 200, "Global-OK");
}
 
Example #19
Source File: OpenAPI3RouterFactoryTest.java    From vertx-web with Apache License 2.0 5 votes vote down vote up
@Test
public void requireSecurityHandler() throws Exception {
  CountDownLatch latch = new CountDownLatch(1);
  OpenAPI3RouterFactory.create(this.vertx, "src/test/resources/swaggers/router_factory_test.yaml",
    openAPI3RouterFactoryAsyncResult -> {
      routerFactory = openAPI3RouterFactoryAsyncResult.result();
      routerFactory.setOptions(new RouterFactoryOptions().setRequireSecurityHandlers(true));

      routerFactory.addHandlerByOperationId("listPets", routingContext -> routingContext
        .response()
        .setStatusCode(200)
        .setStatusMessage(routingContext.get("message") + "OK")
        .end());

      latch.countDown();
    });
  awaitLatch(latch);

  assertThrow(routerFactory::getRouter, RouterFactoryException.class);

  routerFactory.addSecurityHandler("api_key", RoutingContext::next);

  routerFactory.addSecurityHandler("second_api_key",
    RoutingContext::next
  );

  routerFactory.addSecurityHandler("third_api_key",
    RoutingContext::next
  );

  assertNotThrow(routerFactory::getRouter, RouterFactoryException.class);
}
 
Example #20
Source File: OpenAPI3RouterFactoryTest.java    From vertx-web with Apache License 2.0 5 votes vote down vote up
@Test
public void mountMultipleSecurityHandlers() throws Exception {
  final Handler<RoutingContext> firstHandler = routingContext -> routingContext.put("firstHandler", "OK").next();
  final Handler<RoutingContext> secondHandler = routingContext -> routingContext.put("secondHandler", "OK").next();
  final Handler<RoutingContext> secondApiKey = routingContext -> routingContext.put("secondApiKey", "OK").next();
  final Handler<RoutingContext> thirdApiKey = routingContext -> routingContext.put("thirdApiKey", "OK").next();

  CountDownLatch latch = new CountDownLatch(1);
  OpenAPI3RouterFactory.create(this.vertx, "src/test/resources/swaggers/router_factory_test.yaml",
    openAPI3RouterFactoryAsyncResult -> {
      routerFactory = openAPI3RouterFactoryAsyncResult.result();
      routerFactory.setOptions(new RouterFactoryOptions().setRequireSecurityHandlers(true));

      routerFactory.addHandlerByOperationId("listPetsSecurity", routingContext ->
        routingContext
          .response()
          .setStatusCode(200)
          .setStatusMessage("First handler: " + routingContext.get("firstHandler") + ", Second handler: " + routingContext.get("secondHandler") + ", Second api key: " + routingContext.get("secondApiKey") + ", Third api key: " + routingContext.get("thirdApiKey"))
          .end()
      );

      routerFactory.addSecurityHandler("api_key", firstHandler);
      routerFactory.addSecurityHandler("api_key", secondHandler);
      routerFactory.addSecurityHandler("second_api_key", secondApiKey);
      routerFactory.addSecurityHandler("third_api_key", thirdApiKey);
      latch.countDown();
    });
  awaitLatch(latch);

  startServer();

  testRequest(HttpMethod.GET, "/pets_security_test", 200, "First handler: OK, Second handler: OK, Second api key: OK, Third api key: OK");
}
 
Example #21
Source File: OpenAPI3ParametersUnitTest.java    From vertx-web with Apache License 2.0 5 votes vote down vote up
@Override
public void setUp() throws Exception {
  super.setUp();
  stopServer(); // Have to stop default server of WebTestBase
  apiClient = new io.vertx.ext.web.api.contract.openapi3.ApiClient(webClient);
  routerFactory = new OpenAPI3RouterFactoryImpl(this.vertx, spec, new ResolverCache(spec, null, SPEC_URL));
  routerFactory.setOptions(
    new RouterFactoryOptions()
      .setRequireSecurityHandlers(false)
      .setMountValidationFailureHandler(true)
      .setMountNotImplementedHandler(false)
  );
  routerFactory.setValidationFailureHandler(generateFailureHandler());
}
 
Example #22
Source File: BaseRouterFactory.java    From vertx-web with Apache License 2.0 5 votes vote down vote up
public BaseRouterFactory(Vertx vertx, Specification spec, RouterFactoryOptions options) {
  this.vertx = vertx;
  this.spec = spec;
  this.options = options;

  this.validationFailureHandler = DEFAULT_VALIDATION_FAILURE_HANDLER;
  this.notImplementedFailureHandler = DEFAULT_NOT_IMPLEMENTED_HANDLER;
  this.bodyHandler = BodyHandler.create();
  this.globalHandlers = new ArrayList<>();
  this.extraOperationContextPayloadMapper = DEFAULT_EXTRA_OPERATION_CONTEXT_PAYLOAD_MAPPER;
}
 
Example #23
Source File: RxWebApiContractExamples.java    From vertx-rx with Apache License 2.0 5 votes vote down vote up
public void mainExample(Vertx vertx, Handler<RoutingContext> myValidationFailureHandler, JWTAuth jwtAuth) {
  OpenAPI3RouterFactory
    .rxCreate(vertx, "src/main/resources/petstore.yaml")
    .flatMap(routerFactory -> {
      // Spec loaded with success. router factory contains OpenAPI3RouterFactory
      // Set router factory options.
      RouterFactoryOptions options = new RouterFactoryOptions().setOperationModelKey("openapi_model");
      // Mount the options
      routerFactory.setOptions(options);
      // Add an handler with operationId
      routerFactory.addHandlerByOperationId("listPets", routingContext -> {
        // Handle listPets operation
        routingContext.response().setStatusMessage("Called listPets").end();
      });

      // Add a security handler
      routerFactory.addSecurityHandler("api_key", JWTAuthHandler.create(jwtAuth));

      // Now you have to generate the router
      Router router = routerFactory.getRouter();

      // Now you can use your Router instance
      HttpServer server = vertx.createHttpServer(new HttpServerOptions().setPort(8080).setHost("localhost"));
      return server.requestHandler(router).rxListen();
    })
    .subscribe(httpServer -> {
      // Server up and running
    }, throwable -> {
      // Error during router factory instantiation or http server start
    });
}
 
Example #24
Source File: HttpServerVerticle.java    From openapi-generator with Apache License 2.0 5 votes vote down vote up
@Override
public void start(Future<Void> fut) {
    
    new PetApiHandler(operationHandlers);
    new StoreApiHandler(operationHandlers);
    new UserApiHandler(operationHandlers);

    OpenAPI3RouterFactory.rxCreate(vertx, specFile)
            .doOnSuccess(factory -> {
                factory.setOptions(new RouterFactoryOptions()
                        .setRequireSecurityHandlers(false)
                        .setMountNotImplementedHandler(false));
                factory.setValidationFailureHandler(this::validationFailureHandler);
                operationHandlers.forEach(factory.getDelegate()::addHandlerByOperationId);
            })
            .map(OpenAPI3RouterFactory::getRouter)
            .doOnSuccess(router -> router.route().last().handler(this::methodNotFoundHandler))
            .map(router ->
                    vertx.createHttpServer(new HttpServerOptions()
                            .setPort(8080)
                            .setHost("localhost"))
                            .requestHandler(router)
                            .listen()
            )
            .subscribe( httpServer -> {
                logger.info("Http verticle deployed successful");
                fut.complete();
            }, error -> {
                logger.info("Http verticle failed to deployed", error);
                fut.fail(error.getCause());
            });
}
 
Example #25
Source File: OpenAPI3RouterFactoryTest.java    From vertx-web with Apache License 2.0 4 votes vote down vote up
@Test
public void mountSecurityHandlers() throws Exception {
  CountDownLatch latch = new CountDownLatch(1);
  OpenAPI3RouterFactory.create(this.vertx, "src/test/resources/swaggers/router_factory_test.yaml",
    openAPI3RouterFactoryAsyncResult -> {
      routerFactory = openAPI3RouterFactoryAsyncResult.result();
      routerFactory.setOptions(new RouterFactoryOptions().setRequireSecurityHandlers(true));

      routerFactory.addHandlerByOperationId("listPetsSecurity", routingContext -> routingContext
        .response()
        .setStatusCode(200)
        .setStatusMessage(routingContext.get("first_level") + "-" +
          routingContext.get("second_level") + "-" + routingContext.get("third_level_one") +
          "-" + routingContext.get("third_level_two") + "-Done")
        .end());

      routerFactory.addSecurityHandler("api_key",
        routingContext -> routingContext.put("first_level", "User").next()
      );

      routerFactory.addSecuritySchemaScopeValidator("second_api_key", "moderator",
        routingContext -> routingContext.put("second_level", "Moderator").next()
      );

      routerFactory.addSecuritySchemaScopeValidator("third_api_key", "admin",
        routingContext -> routingContext.put("third_level_one", "Admin").next()
      );

      routerFactory.addSecuritySchemaScopeValidator("third_api_key", "useless",
        routingContext -> routingContext.put("third_level_one", "Wrong!").next()
      );

      routerFactory.addSecuritySchemaScopeValidator("third_api_key", "super_admin",
        routingContext -> routingContext.put("third_level_two", "SuperAdmin").next()
      );

      latch.countDown();
    });
  awaitLatch(latch);

  startServer();

  testRequest(HttpMethod.GET, "/pets_security_test", 200, "User-Moderator-Admin-SuperAdmin-Done");
}
 
Example #26
Source File: BaseRouterFactory.java    From vertx-web with Apache License 2.0 4 votes vote down vote up
@Override
public RouterFactoryOptions getOptions() {
  return options;
}
 
Example #27
Source File: BaseRouterFactory.java    From vertx-web with Apache License 2.0 4 votes vote down vote up
@Override
public RouterFactory setOptions(RouterFactoryOptions options) {
  this.options = options;
  return this;
}
 
Example #28
Source File: OpenAPI3RouterFactoryTest.java    From vertx-web with Apache License 2.0 4 votes vote down vote up
@Test
public void consumesTest() throws Exception {
  CountDownLatch latch = new CountDownLatch(1);
  OpenAPI3RouterFactory.create(this.vertx, "src/test/resources/swaggers/produces_consumes_test.yaml",
    openAPI3RouterFactoryAsyncResult -> {
      routerFactory = openAPI3RouterFactoryAsyncResult.result();
      routerFactory.setOptions(new RouterFactoryOptions().setMountNotImplementedHandler(false));
      routerFactory.setBodyHandler(BodyHandler.create(tempFolder.getRoot().getAbsolutePath()));

      routerFactory.addHandlerByOperationId("consumesTest", routingContext -> {
        RequestParameters params = routingContext.get("parsedParameters");
        if (params.body() != null && params.body().isJsonObject()) {
          routingContext
            .response()
            .setStatusCode(200)
            .setStatusMessage("OK")
            .putHeader("Content-Type", "application/json")
            .end(params.body().getJsonObject().encode());
        } else {
          routingContext
            .response()
            .setStatusCode(200)
            .setStatusMessage("OK")
            .end();
        }
      });

      latch.countDown();
    });
  awaitLatch(latch);

  startServer();

  // Json consumes test
  JsonObject obj = new JsonObject("{\"name\":\"francesco\"}");
  testRequestWithJSON(HttpMethod.POST, "/consumesTest", obj.toBuffer(), 200, "OK", obj.toBuffer());

  // Form consumes tests
  MultiMap form = MultiMap.caseInsensitiveMultiMap();
  form.add("name", "francesco");
  testRequestWithForm(HttpMethod.POST, "/consumesTest", FormType.FORM_URLENCODED, form, 200, "OK");
  testRequestWithForm(HttpMethod.POST, "/consumesTest", FormType.MULTIPART, form, 415, HttpResponseStatus.UNSUPPORTED_MEDIA_TYPE.reasonPhrase());
}
 
Example #29
Source File: BaseRouterFactory.java    From vertx-web with Apache License 2.0 4 votes vote down vote up
public BaseRouterFactory(Vertx vertx, Specification spec) {
  this(vertx, spec, new RouterFactoryOptions());
}
 
Example #30
Source File: OpenAPI3Examples.java    From vertx-web with Apache License 2.0 4 votes vote down vote up
public void mainExample(Vertx vertx) {
  // Load the api spec. This operation is asynchronous
  OpenAPI3RouterFactory.create(vertx, "src/main/resources/petstore.yaml",
    openAPI3RouterFactoryAsyncResult -> {
    if (openAPI3RouterFactoryAsyncResult.succeeded()) {
      // Spec loaded with success, retrieve the router
      OpenAPI3RouterFactory routerFactory = openAPI3RouterFactoryAsyncResult.result();
      // You can enable or disable different features of router factory through mounting RouterFactoryOptions
      // For example you can enable or disable the default failure handler for ValidationException
      RouterFactoryOptions options = new RouterFactoryOptions()
        .setMountValidationFailureHandler(false);
      // Mount the options
      routerFactory.setOptions(options);
      // Add an handler with operationId
      routerFactory.addHandlerByOperationId("listPets", routingContext -> {
        // Handle listPets operation
        routingContext.response().setStatusMessage("Called listPets").end();
      });
      // Add a failure handler to the same operationId
      routerFactory.addFailureHandlerByOperationId("listPets", routingContext -> {
        // This is the failure handler
        Throwable failure = routingContext.failure();
        if (failure instanceof ValidationException)
          // Handle Validation Exception
          routingContext.response().setStatusCode(400).setStatusMessage("ValidationException thrown! " + (
            (ValidationException) failure).type().name()).end();
      });

      // Add a security handler
      // Handle security here
      routerFactory.addSecurityHandler("api_key", RoutingContext::next);

      // Now you have to generate the router
      Router router = routerFactory.getRouter();

      // Now you can use your Router instance
      HttpServer server = vertx.createHttpServer(new HttpServerOptions().setPort(8080).setHost("localhost"));
      server.requestHandler(router).listen();

    } else {
      // Something went wrong during router factory initialization
      Throwable exception = openAPI3RouterFactoryAsyncResult.cause();
    }
  });
}