io.vertx.core.http.HttpMethod Java Examples

The following examples show how to use io.vertx.core.http.HttpMethod. 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: UpdateUserEndpointHandlerTest.java    From graviteeio-access-management with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldInvokeSCIMUpdateUserEndpoint_valid_password() throws Exception {
    router.route("/Users").handler(userEndpoint::update);
    when(passwordValidator.validate(anyString())).thenReturn(true);
    when(userService.update(any(), any(), any())).thenReturn(Single.just(getUser()));

    testRequest(
            HttpMethod.PUT,
            "/Users",
            req -> {
                req.setChunked(true);
                req.write(Json.encode(getUser()));
            },
            200,
            "OK", null);
}
 
Example #2
Source File: OkapiClientTest.java    From okapi with Apache License 2.0 6 votes vote down vote up
@Test
public void testHttpClientLegacy2(TestContext context) {
  Async async = context.async();
  StringBuilder b = new StringBuilder();

  context.assertTrue(server != null);
  HttpClient client = vertx.createHttpClient();
  HttpClientRequest requestAbs = HttpClientLegacy.requestAbs(client,
    HttpMethod.GET, BAD_URL + "/test1", res -> {
      b.append("response");
      async.complete();
    });
  requestAbs.exceptionHandler(res -> {
    b.append("exception");
    async.complete();
  });
  requestAbs.end();
  async.await();
  context.assertEquals("exception", b.toString());
}
 
Example #3
Source File: FacebookBidderTest.java    From prebid-server-java with Apache License 2.0 6 votes vote down vote up
@Test
public void makeHttpRequestsShouldCreateSeparateRequestForEachImpAndSkipInvalidImp() {
    // given
    final BidRequest bidRequest = BidRequest.builder()
            .id("req1")
            .user(User.builder().buyeruid("buid").build())
            .imp(asList(
                    givenImp(identity(), identity()),
                    givenImp(identity(), identity()),
                    givenImp(identity(), extImpFacebook -> ExtImpFacebook.of(null, null))))
            .build();

    // when
    final Result<List<HttpRequest<BidRequest>>> result = facebookBidder.makeHttpRequests(bidRequest);

    // then
    assertThat(result.getErrors()).hasSize(1);
    assertThat(result.getValue()).hasSize(2)
            .extracting(HttpRequest::getUri, HttpRequest::getMethod)
            .containsOnly(tuple(ENDPOINT_URL, HttpMethod.POST));
}
 
Example #4
Source File: RxifiedExamples.java    From vertx-rx with Apache License 2.0 6 votes vote down vote up
public void delayToObservable(HttpServer server) {
  server.requestHandler(request -> {
    if (request.method() == HttpMethod.POST) {

      // Stop receiving buffers
      request.pause();

      checkAuth(res -> {

        // Now we can receive buffers again
        request.resume();

        if (res.succeeded()) {
          Observable<Buffer> observable = request.toObservable();
          observable.subscribe(buff -> {
            // Get buffers
          });
        }
      });
    }
  });
}
 
Example #5
Source File: RouterFactoryIntegrationTest.java    From vertx-web with Apache License 2.0 6 votes vote down vote up
@Test
public void testPathParameter(Vertx vertx, VertxTestContext testContext) {
  Checkpoint checkpoint = testContext.checkpoint(2);
  loadFactoryAndStartServer(vertx, VALIDATION_SPEC, testContext, routerFactory -> {
    routerFactory
      .operation("showPetById")
      .handler(routingContext -> {
        RequestParameters params = routingContext.get("parsedParameters");
        routingContext.response().setStatusMessage(params.pathParameter("petId").toString()).end();
      });
  }).onComplete(h -> {
    testRequest(client, HttpMethod.GET, "/pets/3")
      .expect(statusCode(200), statusMessage("3"))
      .send(testContext, checkpoint);
    testRequest(client, HttpMethod.GET, "/pets/three")
      .expect(statusCode(400))
      .expect(badParameterResponse(ParameterProcessorException.ParameterProcessorErrorType.PARSING_ERROR, "petId", ParameterLocation.PATH))
      .send(testContext, checkpoint);
  });
}
 
Example #6
Source File: AuthorizationEndpointTest.java    From graviteeio-access-management with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldNotInvokeAuthorizationEndpoint_emptyRedirectUri() throws Exception {
    final Client client = new Client();
    client.setId("client-id");
    client.setClientId("client-id");
    client.setScopes(Collections.singletonList("read"));

    AuthorizationRequest authorizationRequest = new AuthorizationRequest();
    authorizationRequest.setApproved(true);
    authorizationRequest.setResponseType(ResponseType.CODE);

    when(clientSyncService.findByClientId("client-id")).thenReturn(Maybe.just(client));

    testRequest(
            HttpMethod.GET,
            "/oauth/authorize?response_type=code&client_id=client-id",
            null,
            resp -> {
                String location = resp.headers().get("location");
                assertNotNull(location);
                assertTrue(location.contains("/test/oauth/error?client_id=client-id&error=invalid_request&error_description=A+redirect_uri+must+be+supplied"));
            },
            HttpStatusCode.FOUND_302, "Found", null);
}
 
Example #7
Source File: AdtelligentBidder.java    From prebid-server-java with Apache License 2.0 6 votes vote down vote up
/**
 * Creates {@link HttpRequest}s. One for each source id. Adds source id as url parameter
 */
private Result<List<HttpRequest<BidRequest>>> createHttpRequests(Map<Integer, List<Imp>> sourceToImps,
                                                                 List<BidderError> errors, BidRequest request) {
    final List<HttpRequest<BidRequest>> httpRequests = new ArrayList<>();
    for (Map.Entry<Integer, List<Imp>> sourceIdToImps : sourceToImps.entrySet()) {
        final String url = String.format("%s?aid=%d", endpointUrl, sourceIdToImps.getKey());
        final BidRequest bidRequest = request.toBuilder().imp(sourceIdToImps.getValue()).build();
        final String bidRequestBody;
        try {
            bidRequestBody = mapper.encode(bidRequest);
        } catch (EncodeException e) {
            errors.add(BidderError.badInput(
                    String.format("error while encoding bidRequest, err: %s", e.getMessage())));
            return Result.of(Collections.emptyList(), errors);
        }
        httpRequests.add(HttpRequest.<BidRequest>builder()
                .method(HttpMethod.POST)
                .uri(url)
                .body(bidRequestBody)
                .headers(headers)
                .payload(bidRequest)
                .build());
    }
    return Result.of(httpRequests, errors);
}
 
Example #8
Source File: RestAPIRxVerticle.java    From vertx-blueprint-microservice with Apache License 2.0 6 votes vote down vote up
protected void enableCorsSupport(Router router) {
  Set<String> allowHeaders = new HashSet<>();
  allowHeaders.add("x-requested-with");
  allowHeaders.add("Access-Control-Allow-Origin");
  allowHeaders.add("origin");
  allowHeaders.add("Content-Type");
  allowHeaders.add("accept");
  router.route().handler(CorsHandler.create("*")
    .allowedHeaders(allowHeaders)
    .allowedMethod(HttpMethod.GET)
    .allowedMethod(HttpMethod.POST)
    .allowedMethod(HttpMethod.PUT)
    .allowedMethod(HttpMethod.DELETE)
    .allowedMethod(HttpMethod.PATCH)
    .allowedMethod(HttpMethod.OPTIONS)
  );
}
 
Example #9
Source File: RESTHandler.java    From vert.x-microservice with Apache License 2.0 6 votes vote down vote up
public void handleRESTPostRegistration(final EventBus eventBus, final String url, final String[] mimes) {
    routeMatcher.matchMethod(HttpMethod.POST, url, request -> {
                request.setExpectMultipart(true);
                request.endHandler(new VoidHandler() {
                    public void handle() {
                        final MultiMap attrs = request.formAttributes();
                        handleRestRequest(eventBus,
                                request,
                                url,
                                getParameterEntity(attrs),
                                Arrays.asList(mimes),
                                defaultServiceTimeout);
                    }
                });
            }
    );
}
 
Example #10
Source File: HttpBidderRequesterTest.java    From prebid-server-java with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldReturnFullDebugInfoIfDebugEnabledAndErrorStatus() {
    // given
    given(bidder.makeHttpRequests(any())).willReturn(Result.of(singletonList(
            HttpRequest.<BidRequest>builder()
                    .method(HttpMethod.POST)
                    .uri("uri1")
                    .body("requestBody1")
                    .headers(new CaseInsensitiveHeaders())
                    .build()),
            emptyList()));

    givenHttpClientReturnsResponses(HttpClientResponse.of(500, null, "responseBody1"));

    // when
    final BidderSeatBid bidderSeatBid =
            bidderHttpConnector.requestBids(bidder, BidRequest.builder().build(), timeout, true).result();

    // then
    assertThat(bidderSeatBid.getHttpCalls()).hasSize(1).containsOnly(
            ExtHttpCall.builder().uri("uri1").requestbody("requestBody1").responsebody("responseBody1")
                    .status(500).build());
    assertThat(bidderSeatBid.getErrors()).hasSize(1)
            .extracting(BidderError::getMessage).containsOnly(
            "Unexpected status code: 500. Run with request.test = 1 for more info");
}
 
Example #11
Source File: MultiAuthorizationHandlerTest.java    From vertx-web with Apache License 2.0 6 votes vote down vote up
@Test
public void testJWTAuthenticationWithAuthorization2() throws Exception {
  // we are testing the following:
  // authentication via jwt
  // one authorization provider is registered
  // an authorization is required on the path
  // => the test should succeed
  router.route("/protected/*").handler(JWTAuthHandler.create(authProvider));
  router.route("/protected/*")
      .handler(
          AuthorizationHandler.create(RoleBasedAuthorization.create("role1"))
          .addAuthorizationProvider(createProvider("authzProvider1", RoleBasedAuthorization.create("role1")))
      );

  router.route("/protected/page1").handler(rc -> {
    assertNotNull(rc.user());
    assertEquals("paulo", rc.user().principal().getString("sub"));
    rc.response().end("Welcome");
  });

  // login with correct credentials
  testRequest(HttpMethod.GET, "/protected/page1",
      req -> req.putHeader("Authorization",
          "Bearer " + authProvider.generateToken(new JsonObject().put("sub", "paulo"), new JWTOptions())),
      200, "OK", "Welcome");
}
 
Example #12
Source File: QueryManager.java    From simulacron with Apache License 2.0 6 votes vote down vote up
public void registerWithRouter(Router router) {
  // Priming queries
  router.route(HttpMethod.POST, "/prime/:clusterIdOrName").handler(this::primeQuery);
  router
      .route(HttpMethod.POST, "/prime/:clusterIdOrName/:datacenterIdOrName")
      .handler(this::primeQuery);
  router
      .route(HttpMethod.POST, "/prime/:clusterIdOrName/:datacenterIdOrName/:nodeIdOrName")
      .handler(this::primeQuery);

  // Deleting primed queries
  router.route(HttpMethod.DELETE, "/prime/:clusterIdOrName").handler(this::clearPrimedQueries);
  router
      .route(HttpMethod.DELETE, "/prime/:clusterIdOrName/:datacenterIdOrName")
      .handler(this::clearPrimedQueries);
  router
      .route(HttpMethod.DELETE, "/prime/:clusterIdOrName/:datacenterIdOrName/:nodeIdOrName")
      .handler(this::primeQuery);
}
 
Example #13
Source File: OpenAPI3MultipleFilesValidationTest.java    From vertx-web with Apache License 2.0 6 votes vote down vote up
@Test
public void testDefaultDoubleQueryParameter() throws Exception {
    Operation op = testSpec.getPaths().get("/queryTests/defaultDouble")
            .getGet();
    OpenAPI3RequestValidationHandler validationHandler = new OpenAPI3RequestValidationHandlerImpl(
            op, op.getParameters(), testSpec, refsCache);
    loadHandlers("/queryTests/defaultDouble", HttpMethod.GET, false,
            validationHandler, (routingContext) -> {
                RequestParameters params = routingContext
                        .get("parsedParameters");
                RequestParameter requestParameter = params
                        .queryParameter("parameter");
                assertTrue(requestParameter.isDouble());
                routingContext.response()
                        .setStatusMessage(requestParameter.toString())
                        .end();
            });

    testRequest(HttpMethod.GET, "/queryTests/defaultDouble", 200, "1.0");
}
 
Example #14
Source File: TimeoutHandlerTest.java    From vertx-web with Apache License 2.0 6 votes vote down vote up
@Test
public void testTimeoutWithCustomBodyEndHandler() throws Exception {
  long timeout = 500;

  AtomicBoolean ended = new AtomicBoolean();
  router.route().handler(routingContext -> {
    routingContext.addBodyEndHandler(event -> ended.set(true));
    routingContext.next();
  });

  router.route().handler(TimeoutHandler.create(timeout));
  router.route().handler(rc -> {
    // Don't end it
  });
  testRequest(HttpMethod.GET, "/", 503, "Service Unavailable");

  waitUntil(ended::get);
}
 
Example #15
Source File: ErrorHandlerTest.java    From vertx-web with Apache License 2.0 6 votes vote down vote up
@Test
public void testFailWithException() throws Exception {
  System.setProperty(SYSTEM_PROPERTY_NAME, "dev");
  router
    // clear the previous setup
    .clear()
    // new handler should use development mode
    .route().failureHandler(ErrorHandler.create());
  // unset the system property
  System.setProperty(SYSTEM_PROPERTY_NAME, "test");

  int statusCode = 500;
  String statusMessage = "Something happened!";
  Exception e = new Exception(statusMessage);
  router.route().handler(rc -> {
    rc.response().putHeader(HttpHeaders.CONTENT_TYPE, "text/html");
    rc.fail(e);
  });
  testRequest(HttpMethod.GET, "/", null, resp -> resp.bodyHandler(buff -> {
    checkHtmlResponse(buff, resp, statusCode, statusMessage, e);
    testComplete();
  }), statusCode, statusMessage, null);
  await();
}
 
Example #16
Source File: OpenAPI3MultipleFilesValidationTest.java    From vertx-web with Apache License 2.0 6 votes vote down vote up
@Test
public void testDefaultStringQueryParameter() throws Exception {
    Operation op = testSpec.getPaths().get("/queryTests/defaultString")
            .getGet();
    OpenAPI3RequestValidationHandler validationHandler = new OpenAPI3RequestValidationHandlerImpl(
            op, op.getParameters(), testSpec, refsCache);
    loadHandlers("/queryTests/defaultString", HttpMethod.GET, false,
            validationHandler, (routingContext) -> {
                RequestParameters params = routingContext
                        .get("parsedParameters");
                routingContext
                        .response().setStatusMessage(params
                                .queryParameter("parameter").getString())
                        .end();
            });
    testRequest(HttpMethod.GET, "/queryTests/defaultString", 200,
            "aString");
}
 
Example #17
Source File: ForgotPasswordSubmissionEndpointTest.java    From graviteeio-access-management with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldCompleteWhenUserNotFoundException() throws Exception {
    Client client = new Client();
    client.setId("client-id");
    client.setClientId("client-id");

    router.route().order(-1).handler(routingContext -> {
        routingContext.put("client", client);
        routingContext.next();
    });

    when(userService.forgotPassword(eq("[email protected]"), eq(client), any(User.class))).thenReturn(Completable.error(new UserNotFoundException("[email protected]")));

    testRequest(
            HttpMethod.POST, "/[email protected]",
            null,
            resp -> {
                String location = resp.headers().get("location");
                assertNotNull(location);
                assertTrue(location.endsWith("/forgotPassword?success=forgot_password_completed&client_id=client-id"));
            },
            HttpStatusCode.FOUND_302, "Found", null);
}
 
Example #18
Source File: RouterFactoryIntegrationTest.java    From vertx-web with Apache License 2.0 6 votes vote down vote up
@Test
public void testQueryParameterByteFormat(Vertx vertx, VertxTestContext testContext) {
  loadFactoryAndStartServer(vertx, VALIDATION_SPEC, testContext, routerFactory -> {
    routerFactory
      .operation("byteFormatTest")
      .handler(routingContext ->
        routingContext.response().setStatusMessage(
          "" + ((RequestParameters)routingContext.get("parsedParameters")).queryParameter("parameter").toString()
        ).end()
      );
  }).onComplete(h ->
    testRequest(client, HttpMethod.GET, "/queryTests/byteFormat?parameter=Zm9vYmFyCg==")
      .expect(statusCode(200), statusMessage("Zm9vYmFyCg=="))
      .send(testContext)
  );
}
 
Example #19
Source File: FormAuthenticationMechanism.java    From quarkus with Apache License 2.0 6 votes vote down vote up
@Override
public Uni<SecurityIdentity> authenticate(RoutingContext context,
        IdentityProviderManager identityProviderManager) {

    PersistentLoginManager.RestoreResult result = loginManager.restore(context);
    if (result != null) {
        Uni<SecurityIdentity> ret = identityProviderManager
                .authenticate(new TrustedAuthenticationRequest(result.getPrincipal()));
        return ret.onItem().invoke(new Consumer<SecurityIdentity>() {
            @Override
            public void accept(SecurityIdentity securityIdentity) {
                loginManager.save(securityIdentity, context, result);
            }
        });
    }

    if (context.normalisedPath().endsWith(postLocation) && context.request().method().equals(HttpMethod.POST)) {
        return runFormAuth(context, identityProviderManager);
    } else {
        return Uni.createFrom().optional(Optional.empty());
    }
}
 
Example #20
Source File: UpdateUserEndpointHandlerTest.java    From graviteeio-access-management with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldReturn400WhenInvalidUserException() throws Exception {
    router.route("/Users").handler(userEndpoint::update);
    when(passwordValidator.validate(anyString())).thenReturn(true);
    when(userService.update(any(), any(), anyString())).thenReturn(Single.error(new InvalidUserException("Invalid user infos")));

    testRequest(
            HttpMethod.PUT,
            "/Users",
            req -> {
                req.setChunked(true);
                req.write(Json.encode(getUser()));
            },
            400,
            "Bad Request",
            "{\n" +
                    "  \"status\" : \"400\",\n" +
                    "  \"scimType\" : \"invalidValue\",\n" +
                    "  \"detail\" : \"Invalid user infos\",\n" +
                    "  \"schemas\" : [ \"urn:ietf:params:scim:api:messages:2.0:Error\" ]\n" +
                    "}");
}
 
Example #21
Source File: RouterFactoryIntegrationTest.java    From vertx-web with Apache License 2.0 6 votes vote down vote up
@Test
public void testDefaultIntQueryParameter(Vertx vertx, VertxTestContext testContext) {
  loadFactoryAndStartServer(vertx, VALIDATION_SPEC, testContext, routerFactory -> {
    routerFactory
      .operation("testDefaultInt")
      .handler(routingContext ->
        routingContext.response().setStatusMessage(
          ((RequestParameters)routingContext.get("parsedParameters")).queryParameter("parameter").getInteger().toString()
        ).end()
      );
  }).onComplete(h ->
    testRequest(client, HttpMethod.GET, "/queryTests/defaultInt")
      .expect(statusCode(200), statusMessage("1"))
      .send(testContext)
  );
}
 
Example #22
Source File: Main.java    From mewbase with MIT License 6 votes vote down vote up
public static void main(String[] args) {
    String resourceBasename = "example.gettingstarted.projectionrest/configuration.conf";
    final Config config = ConfigFactory.load(resourceBasename);

    // create a Vertx web server
    final Vertx vertx = Vertx.vertx();
    final HttpServerOptions options = new HttpServerOptions().setPort(8080);
    final HttpServer httpServer = vertx.createHttpServer(options);
    final BinderStore binderStore = BinderStore.instance(config);
    final Router router = Router.router(vertx);
    router.route().handler(BodyHandler.create());
    httpServer.requestHandler(router::accept);

    /*
    Expose endpoint to retrieve a document from the binder store
     */
    router.route(HttpMethod.GET, "/summary/:product/:date").handler(routingContext -> {
        final String product = routingContext.pathParams().get("product");
        final String date = routingContext.pathParams().get("date");
        final VertxRestServiceActionVisitor actionVisitor = new VertxRestServiceActionVisitor(routingContext);
        actionVisitor.visit(RestServiceAction.retrieveSingleDocument(binderStore, "sales_summary", product + "_" + date));
    });

    httpServer.listen();
}
 
Example #23
Source File: UserInfoEndpointHandlerTest.java    From graviteeio-access-management with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldInvokeUserEndpoint_claimsRequest() throws Exception {
    JWT jwt = new JWT();
    jwt.setJti("id-token");
    jwt.setAud("client-id");
    jwt.setSub("id-subject");
    jwt.setScope("openid");
    jwt.setClaimsRequestParameter("{\"userinfo\":{\"name\":{\"essential\":true}}}");

    Client client = new Client();
    client.setId("client-id");
    client.setClientId("client-id");

    router.route().order(-1).handler(createOAuth2AuthHandler(oAuth2AuthProvider(jwt, client)));

    User user = createUser();

    when(userService.findById(anyString())).thenReturn(Maybe.just(user));

    testRequest(
            HttpMethod.GET,
            "/userinfo",
            req -> req.putHeader(HttpHeaders.AUTHORIZATION, "Bearer test-token"),
            resp -> resp.bodyHandler(body -> {
                final Map<String, Object> claims = Json.decodeValue(body.toString(), Map.class);
                assertNotNull(claims);
                assertEquals(2, claims.size());
                assertFalse(claims.containsKey(StandardClaims.FAMILY_NAME));
            }),
            HttpStatusCode.OK_200, "OK", null);
}
 
Example #24
Source File: OAuth2ClientTest.java    From vertx-auth with Apache License 2.0 5 votes vote down vote up
@Override
public void setUp() throws Exception {
  super.setUp();
  oauth2 = OAuth2Auth.create(vertx, new OAuth2Options()
    .setFlow(OAuth2FlowType.CLIENT)
    .setClientID("client-id")
    .setClientSecret("client-secret")
    .setSite("http://localhost:8080"));

  final CountDownLatch latch = new CountDownLatch(1);

  server = vertx.createHttpServer().requestHandler(req -> {
    if (req.method() == HttpMethod.POST && "/oauth/token".equals(req.path())) {
      assertEquals("Basic Y2xpZW50LWlkOmNsaWVudC1zZWNyZXQ=", req.getHeader("Authorization"));
      req.setExpectMultipart(true).bodyHandler(buffer -> {
        try {
          assertEquals(config, queryToJSON(buffer.toString()));
        } catch (UnsupportedEncodingException e) {
          fail(e);
        }
        req.response().putHeader("Content-Type", "application/json").end(fixture.encode());
      });
    } else {
      req.response().setStatusCode(400).end();
    }
  }).listen(8080, ready -> {
    if (ready.failed()) {
      throw new RuntimeException(ready.cause());
    }
    // ready
    latch.countDown();
  });

  latch.await();
}
 
Example #25
Source File: RoutingContextImplTest.java    From vertx-web with Apache License 2.0 5 votes vote down vote up
@Test
public void test_empty_fails_json_types() throws Exception {
  router.route().handler(event -> {
    assertNull(event.getBodyAsJsonArray());
    assertNull(event.getBodyAsJson());
    event.response().end();
  });
  testRequest(HttpMethod.POST, "/", req -> {
    req.setChunked(true);
    req.write(Buffer.buffer(""));
  }, HttpResponseStatus.INTERNAL_SERVER_ERROR.code(), HttpResponseStatus.INTERNAL_SERVER_ERROR.reasonPhrase(), null);
}
 
Example #26
Source File: OpenAPI3ValidationTest.java    From vertx-web with Apache License 2.0 5 votes vote down vote up
@Test
public void testAllOfQueryParamFailure() throws Exception {
  Operation op = testSpec.getPaths().get("/queryTests/allOfTest").getGet();
  OpenAPI3RequestValidationHandler validationHandler = new OpenAPI3RequestValidationHandlerImpl(op, op.getParameters(), testSpec, refsCache);
  loadHandlers("/queryTests/allOfTest", HttpMethod.GET, true, validationHandler, (routingContext) -> routingContext.response().setStatusMessage("ok").end());

  String a = "5";
  String b = "aString";

  String parameter = "parameter=a," + a + ",b," + b;

  testRequest(HttpMethod.GET, "/queryTests/allOfTest?" + parameter, 400, errorMessage(ValidationException.ErrorType
    .NO_MATCH));
}
 
Example #27
Source File: SettingsCacheNotificationHandlerTest.java    From prebid-server-java with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldReturnBadRequestForUpdateCacheIfRequestHasNoBody() {
    // given
    given(routingContext.request().method()).willReturn(HttpMethod.POST);
    given(routingContext.getBody()).willReturn(null);

    // when
    handler.handle(routingContext);

    // then
    verify(httpResponse).setStatusCode(eq(400));
    verify(httpResponse).end(eq("Missing update data."));
}
 
Example #28
Source File: IntrospectionEndpointTest.java    From graviteeio-access-management with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldReturnInvalidToken_noTokenProvided() throws Exception {
    io.gravitee.am.model.oidc.Client client = new io.gravitee.am.model.oidc.Client();
    client.setClientId("my-client-id");

    router.route().order(-1).handler(routingContext -> {
        routingContext.put("client", client);
        routingContext.next();
    });

    testRequest(
            HttpMethod.POST,
            "/oauth/introspect",
            HttpStatusCode.BAD_REQUEST_400, "Bad Request");
}
 
Example #29
Source File: CorsIT.java    From hono with Eclipse Public License 2.0 5 votes vote down vote up
private static void assertAccessControlHeaders(final MultiMap headers, final HttpMethod expectedAllowedMethod) {

        assertThat(headers.get(HttpHeaders.ACCESS_CONTROL_ALLOW_METHODS)).contains(expectedAllowedMethod.name());
        assertThat(headers.get(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN)).isEqualTo("*");
        assertThat(headers.get(HttpHeaders.ACCESS_CONTROL_ALLOW_HEADERS)).contains(HttpHeaders.AUTHORIZATION);
        assertThat(headers.get(HttpHeaders.ACCESS_CONTROL_ALLOW_HEADERS)).contains(HttpHeaders.CONTENT_TYPE);
    }
 
Example #30
Source File: SessionHandlerTestBase.java    From vertx-web with Apache License 2.0 5 votes vote down vote up
@Test
public void testSessionCookieSecureFlag() throws Exception {
	router.route().handler(SessionHandler.create(store).setCookieSecureFlag(true));
	router.route().handler(rc -> rc.response().end());

	testRequest(HttpMethod.GET, "/", null, resp -> {
		String setCookie = resp.headers().get("set-cookie");

		assertTrue(setCookie.contains("; Secure"));
	}, 200, "OK", null);
}