@Override public void start() throws Exception { HttpServer server = vertx.createHttpServer(); server.requestStream().toFlowable().subscribe(req -> { req.response().putHeader("content-type", "application/json").end(new JsonObject().put("time", System.currentTimeMillis()).toString()); }); server.listen(8080); } }
@Override public void start() throws Exception { HttpServer server = vertx.createHttpServer(); server.requestStream().toFlowable().subscribe(req -> { HttpServerResponse resp = req.response(); String contentType = req.getHeader("Content-Type"); if (contentType != null) { resp.putHeader("Content-Type", contentType); } resp.setChunked(true); req.toFlowable().subscribe( resp::write, err -> {}, resp::end ); }); server.listen(8080); } }
@Override public void start() throws Exception { Router router = Router.router(vertx); router.route().handler(BodyHandler.create()); router.route().handler(req -> req.response().putHeader("content-type", "text/html") .end("<html><body><h1>Hello from vert.x!</h1></body></html>")); HttpServer server = vertx.createHttpServer(); server.requestStream() .toFlowable() .map(HttpServerRequest::pause) .onBackpressureDrop(req -> req.response().setStatusCode(503).end()) .observeOn(RxHelper.scheduler(vertx.getDelegate())) .subscribe(req -> { req.resume(); router.accept(req); }); server.rxListen(PORT).subscribe(res -> generateRequests()); }
private void parseGrantTypeParameter(RoutingContext context) { String grantType = context.request().getParam(OAuth2Constants.GRANT_TYPE); if (grantType == null) { throw new InvalidRequestException("Missing parameter: grant_type"); } }
public ClientRequest(HttpServerRequest serverRequest) { this.path = serverRequest.path(); this.method = serverRequest.method(); this.headers = MultiMap.caseInsensitiveMultiMap().setAll(serverRequest.headers()); this.params = UriHelper.getParams(serverRequest.uri()); this.formAttributes = MultiMap.caseInsensitiveMultiMap().setAll(serverRequest.formAttributes()); }
@Override public void handle(HttpServerRequest request) request.bodyHandler(buff -> { Context ctx = vertx.getOrCreateContext(); ResteasyUriInfo uriInfo = VertxUtil.extractUriInfo(request.getDelegate(), servletMappingPrefix); ResteasyHttpHeaders headers = VertxUtil.extractHttpHeaders(request.getDelegate()); HttpServerResponse response = request.response(); VertxHttpResponse vertxResponse = new VertxHttpResponseWithWorkaround(response.getDelegate(), dispatcher.getProviderFactory(), request.method()); VertxHttpRequest vertxRequest = new VertxHttpRequest(ctx.getDelegate(), headers, uriInfo, request.rawMethod(), dispatcher.getDispatcher(), vertxResponse, false); if (buff.length() > 0) dispatcher.service(ctx.getDelegate(), request.getDelegate(), response.getDelegate(), vertxRequest, vertxResponse, true); } catch (Failure e1)
private RoutingContext mockContext(String requestPath, HttpMethod method) { RoutingContext context = Mockito.mock(RoutingContext.class); HttpServerRequest httpRequest = Mockito.mock(HttpServerRequest.class); Mockito.when(context.request()).thenReturn(httpRequest); Mockito.when(httpRequest.path()).thenReturn(requestPath); Mockito.when(httpRequest.method()).thenReturn(method); return context; } }
private String location(HttpServerRequest request) { try { return UriBuilderRequest.resolveProxyRequest(request, request.path(), null); } catch (URISyntaxException e) { logger.error("An error occurs while decoding SCIM Groups location URI", e); return ""; } } }
@Override public void handle(RoutingContext context) { HttpServerRequest req = context.request(); if (req.method() != HttpMethod.POST) { context.fail(405); // Must be a POST } else { if (!req.isExpectMultipart()) { throw new IllegalStateException("Form body not parsed - do you forget to include a BodyHandler?"); } // check required parameters MultiMap params = req.formAttributes(); Optional<String> missingParameter = requiredParams.stream().filter(param -> { String paramValue = params.get(param); if (paramValue == null) { logger.warn("No {} provided in form - did you forget to include a BodyHandler?", param); return true; } return false; }).findFirst(); if (missingParameter.isPresent()) { redirectToPage(context, Collections.singletonMap(ERROR_PARAM, "missing_required_parameters")); } else { context.next(); } } } }
protected Maybe<String> extractAccessTokenFromRequest(RoutingContext context) { //Extract first from Authorization Header final String authorization = context.request().getHeader(HttpHeaders.AUTHORIZATION); if(authorization!=null) { if(!authorization.trim().startsWith(AccessToken.BEARER_TYPE+" ")) { return Maybe.error(new InvalidRequestException("The access token must be sent using the Authorization header with as value \"Bearer xxxx\"")); } return Maybe.just(authorization.replaceFirst(AccessToken.BEARER_TYPE+" ","")); } //Extract from query parameter. final String accessToken = context.request().getParam(AccessToken.ACCESS_TOKEN); if(!Strings.isNullOrEmpty(accessToken)) { return Maybe.just(accessToken); } return Maybe.error(new InvalidRequestException("An access token is required")); } }
@Override public void handle(RoutingContext context) { MultiMap params = context.request().formAttributes(); Map<String, String> queryParams = new HashMap<>(); queryParams.put(CLIENT_ID_PARAM, context.request().getParam(CLIENT_ID_PARAM)); userService.register(convert(params)) .subscribe( user -> { queryParams.put(SUCCESS_PARAM, "registration_succeed"); redirectToPage(context, queryParams); }, error -> { if (error instanceof UserAlreadyExistsException) { queryParams.put(WARNING_PARAM, "user_already_exists"); redirectToPage(context, queryParams); } else { queryParams.put(ERROR_PARAM, "registration_failed"); redirectToPage(context, queryParams, error); } }); }
@Test public void testPost() { int times = 5; waitFor(times); HttpServer server = vertx.createHttpServer(new HttpServerOptions().setPort(8080)); server.requestStream().handler(req -> req.bodyHandler(buff -> { assertEquals("onetwothree", buff.toString()); req.response().end(); })); try { server.listen(ar -> { client = WebClient.wrap(vertx.createHttpClient(new HttpClientOptions())); Observable<Buffer> stream = Observable.just(Buffer.buffer("one"), Buffer.buffer("two"), Buffer.buffer("three")); Single<HttpResponse<Buffer>> single = client .post(8080, "localhost", "/the_uri") .rxSendStream(stream); for (int i = 0; i < times; i++) { single.subscribe(resp -> complete(), this::fail); } }); await(); } finally { server.close(); } }
protected void redirectToPage(RoutingContext context, Map<String, String> params, Throwable... exceptions) { try { if (exceptions != null && exceptions.length > 0) { logger.debug("Error user actions : " + params.get("error"), exceptions[0]); } String uri = UriBuilderRequest.resolveProxyRequest(context.request(), context.request().path(), params); doRedirect(context.response(), uri); } catch (Exception ex) { logger.error("An error occurs while redirecting to {}", context.request().absoluteURI(), ex); context.fail(503); } }
private void parseClaimsParameter(RoutingContext context) { String claims = context.request().getParam(OIDCParameters.CLAIMS); if (claims != null) { try { ClaimsRequest claimsRequest = claimsRequestResolver.resolve(claims); // save claims request as json string value (will be use for id_token and/or UserInfo endpoint) context.request().params().set(OIDCParameters.CLAIMS, Json.encode(claimsRequest)); } catch (ClaimsRequestSyntaxException e) { throw new InvalidRequestException("Invalid parameter: claims"); } } }
String scheme = request.getHeader(HttpHeaders.X_FORWARDED_PROTO); if (scheme != null && !scheme.isEmpty()) { builder.scheme(scheme); } else { builder.scheme(request.scheme()); String host = request.getHeader(HttpHeaders.X_FORWARDED_HOST); if (host != null && !host.isEmpty()) { handleHost(builder, host); } else { handleHost(builder, request.host()); String forwardedPath = request.getHeader(X_FORWARDED_PREFIX); if (forwardedPath != null && !forwardedPath.isEmpty()) {
if (!req.isExpectMultipart()) { throw new IllegalStateException("Form body not parsed - do you forget to include a BodyHandler?"); MultiMap params = req.formAttributes();
@Override public void handle(RoutingContext rc) { MultiMap formAttributes = rc.request().formAttributes();
@Override protected AuthProvider setupAuthenticationRoutes() { AppGlobals globals = AppGlobals.get(); AuthProvider auth = ShiroAuth.create(globals.getVertx(), new ShiroAuthOptions() .setType(ShiroAuthRealmType.PROPERTIES) .setConfig(new JsonObject() .put("properties_path", globals.getConfig().getString("security_definitions")))); globals.getRouter().route().handler(UserSessionHandler.create(auth)); JsonObject keyStoreOptions = new JsonObject().put("keyStore", globals.getConfig().getJsonObject("keystore")); // attempt to load a Key file JWTAuth jwtAuth = JWTAuth.create(globals.getVertx(), new JWTAuthOptions(keyStoreOptions)); JWTAuthHandler jwtAuthHandler = JWTAuthHandler.create(jwtAuth); globals.setGlobal(JWTAuth.class, jwtAuth); globals.getRouter().route().handler(context -> { // only filter if we have a header, otherwise it will try to force auth, regardless if whether // we want auth if(context.request().getHeader(HttpHeaders.AUTHORIZATION) != null) jwtAuthHandler.handle(context); else context.next(); }); return auth; }
/** * Wrap the todo entity with appropriate id and URL. * * @param todo a todo entity * @param context RoutingContext * @return the wrapped todo entity */ private Todo wrapObject(Todo todo, RoutingContext context) { int id = todo.getId(); if (id > Todo.getIncId()) { Todo.setIncIdWith(id); } else if (id == 0) todo.setIncId(); todo.setUrl(context.request().absoluteURI() + "/" + todo.getId()); return todo; } }
private void parseClientIdParameter(RoutingContext context) { String clientId = context.request().getParam(OAuth2Constants.CLIENT_ID); if (clientId == null) { throw new InvalidRequestException("Missing parameter: client_id"); } }