io.vertx.reactivex.core.http.HttpServerResponse Java Examples

The following examples show how to use io.vertx.reactivex.core.http.HttpServerResponse. 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: TestResource.java    From redpipe with Apache License 2.0 6 votes vote down vote up
@Path("inject")
@GET
public String inject(@Context Vertx vertx,
		@Context RoutingContext routingContext,
		@Context HttpServerRequest request,
		@Context HttpServerResponse response,
		@Context AuthProvider authProvider,
		@Context User user,
		@Context Session session) {
	if(vertx == null
			|| routingContext == null
			|| request == null
			|| response == null
			|| session == null)
		throw new WebApplicationException(Status.INTERNAL_SERVER_ERROR);
	return "ok";
}
 
Example #2
Source File: DynamicClientRegistrationEndpointTest.java    From graviteeio-access-management with Apache License 2.0 6 votes vote down vote up
@Test
public void register_success() {
    //Context
    HttpServerRequest serverRequest = Mockito.mock(HttpServerRequest.class);
    HttpServerResponse serverResponse = Mockito.mock(HttpServerResponse.class);

    when(routingContext.request()).thenReturn(serverRequest);
    when(serverRequest.getHeader(any())).thenReturn(null);
    when(serverRequest.scheme()).thenReturn("https");
    when(serverRequest.host()).thenReturn("host");
    when(routingContext.response()).thenReturn(serverResponse);
    when(serverResponse.putHeader(anyString(),anyString())).thenReturn(serverResponse);
    when(serverResponse.setStatusCode(201)).thenReturn(serverResponse);

    when(dcrService.create(any(),any())).thenReturn(Single.just(new Client()));
    when(clientSyncService.addDynamicClientRegistred(any())).thenReturn(new Client());

    //Test
    endpoint.handle(routingContext);

    //Assertions
    verify(routingContext, times(1)).response();
    verify(serverResponse,times(3)).putHeader(anyString(),anyString());
    verify(serverResponse,times(1)).end(anyString());
}
 
Example #3
Source File: DefaultReactor.java    From graviteeio-access-management with Apache License 2.0 5 votes vote down vote up
private void sendNotFound(HttpServerResponse serverResponse) {
    // Send a NOT_FOUND HTTP status code (404)
    serverResponse.setStatusCode(HttpStatusCode.NOT_FOUND_404);

    String message = environment.getProperty("http.errors[404].message", "No security domain matches the request URI.");
    serverResponse.headers().set(HttpHeaders.CONTENT_LENGTH, Integer.toString(message.length()));
    serverResponse.headers().set(HttpHeaders.CONTENT_TYPE, "text/plain");
    serverResponse.headers().set(HttpHeaders.CONNECTION, HttpHeadersValues.CONNECTION_CLOSE);
    serverResponse.write(Buffer.buffer(message));

    serverResponse.end();
}
 
Example #4
Source File: RestQuoteAPIVerticle.java    From vertx-kubernetes-workshop with Apache License 2.0 5 votes vote down vote up
@Override
public void start(Future<Void> future) throws Exception {
    // Get the stream of messages sent on the "market" address
    vertx.eventBus().<JsonObject>consumer(GeneratorConfigVerticle.ADDRESS).toFlowable()
        // TODO Extract the body of the message using `.map(msg -> {})`
        // ----
        //
        // ----
        // TODO For each message, populate the `quotes` map with the received quote. Use `.doOnNext(json -> {})`
        // Quotes are json objects you can retrieve from the message body
        // The map is structured as follows: name -> quote
        // ----
        //
        // ----
        .subscribe();

    HttpServer server = vertx.createHttpServer();
    server.requestStream().toFlowable()
        .doOnNext(request -> {
            HttpServerResponse response = request.response()
                .putHeader("content-type", "application/json");

            // TODO Handle the HTTP request
            // The request handler returns a specific quote if the `name` parameter is set, or the whole map if none.
            // To write the response use: `response.end(content)`
            // If the name is set but not found, you should return 404 (use response.setStatusCode(404)).
            // To encode a Json object, use the `encorePrettily` method
            // ----

            // Remove this line
            response.end(Json.encodePrettily(quotes));
            
            // ----
        })
    .subscribe();

    server.rxListen(config().getInteger("http.port", 8080))
        .toCompletable()
        .subscribe(CompletableHelper.toObserver(future));
}
 
Example #5
Source File: RestfulApiVerticle.java    From vertx-blueprint-todo-backend with Apache License 2.0 5 votes vote down vote up
/**
 * Resolve an asynchronous status and send back the response.
 * By default, the successful status code is 200 OK.
 *
 * @param context     routing context
 * @param asyncResult asynchronous status with no result
 */
protected void sendResponse(RoutingContext context, Completable asyncResult) {
  HttpServerResponse response = context.response();
  if (asyncResult == null) {
    internalError(context, "invalid_status");
  } else {
    asyncResult.subscribe(response::end, ex -> internalError(context, ex));
  }
}
 
Example #6
Source File: VertxSecurityDomainHandler.java    From graviteeio-access-management with Apache License 2.0 5 votes vote down vote up
private void sendNotFound(RoutingContext context) {
    // Send a NOT_FOUND HTTP status code (404)  if domain's sub url didn't match any route.
    HttpServerResponse serverResponse = context.response();
    serverResponse.setStatusCode(HttpStatusCode.NOT_FOUND_404);

    String message = environment.getProperty("http.domain.errors[404].message", "No endpoint matches the request URI.");
    serverResponse.headers().set(HttpHeaders.CONTENT_LENGTH, Integer.toString(message.length()));
    serverResponse.headers().set(HttpHeaders.CONTENT_TYPE, "text/plain");
    serverResponse.headers().set(HttpHeaders.CONNECTION, HttpHeadersValues.CONNECTION_CLOSE);
    serverResponse.write(Buffer.buffer(message));

    serverResponse.end();
}
 
Example #7
Source File: UserRequestHandler.java    From graviteeio-access-management with Apache License 2.0 4 votes vote down vote up
private void doRedirect(HttpServerResponse response, String url) {
    response.putHeader(HttpHeaders.LOCATION, url).setStatusCode(302).end();
}
 
Example #8
Source File: AuthorizationEndpoint.java    From graviteeio-access-management with Apache License 2.0 4 votes vote down vote up
private void doRedirect(HttpServerResponse response, String url) {
    response.putHeader(HttpHeaders.LOCATION, url).setStatusCode(302).end();
}
 
Example #9
Source File: UserConsentPostEndpoint.java    From graviteeio-access-management with Apache License 2.0 4 votes vote down vote up
private void doRedirect(HttpServerResponse response, String url) {
    response.putHeader(HttpHeaders.LOCATION, url).setStatusCode(302).end();
}
 
Example #10
Source File: AuthorizationRequestFailureHandler.java    From graviteeio-access-management with Apache License 2.0 4 votes vote down vote up
private void doRedirect(HttpServerResponse response, String url) {
    response.putHeader(HttpHeaders.LOCATION, url).setStatusCode(302).end();
}
 
Example #11
Source File: UserConsentFailureHandler.java    From graviteeio-access-management with Apache License 2.0 4 votes vote down vote up
private void doRedirect(HttpServerResponse response, String url) {
    response.putHeader(HttpHeaders.LOCATION, url).setStatusCode(302).end();
}
 
Example #12
Source File: LoginCallbackEndpoint.java    From graviteeio-access-management with Apache License 2.0 4 votes vote down vote up
private void doRedirect(HttpServerResponse response, String url) {
    response.putHeader(HttpHeaders.LOCATION, url).setStatusCode(302).end();
}
 
Example #13
Source File: MFAEnrollEndpoint.java    From graviteeio-access-management with Apache License 2.0 4 votes vote down vote up
private void doRedirect(HttpServerResponse response, String url) {
    response.putHeader(HttpHeaders.LOCATION, url).setStatusCode(302).end();
}
 
Example #14
Source File: MFAChallengeEndpoint.java    From graviteeio-access-management with Apache License 2.0 4 votes vote down vote up
private void doRedirect(HttpServerResponse response, String url) {
    response.putHeader(HttpHeaders.LOCATION, url).setStatusCode(302).end();
}
 
Example #15
Source File: MyFirstVerticle.java    From introduction-to-eclipse-vertx with Apache License 2.0 4 votes vote down vote up
@Override
public void start(Future<Void> fut) {

    // Create a router object.
    Router router = Router.router(vertx);

    // Bind "/" to our hello message - so we are still compatible.
    router.route("/").handler(routingContext -> {
        HttpServerResponse response = routingContext.response();
        response
            .putHeader("content-type", "text/html")
            .end("<h1>Hello from my first Vert.x 3 application</h1>");
    });

    // Serve static resources from the /assets directory
    router.route("/assets/*").handler(StaticHandler.create("assets"));
    router.get("/api/articles").handler(this::getAll);
    router.get("/api/articles/:id").handler(this::getOne);
    router.route("/api/articles*").handler(BodyHandler.create());
    router.post("/api/articles").handler(this::addOne);
    router.delete("/api/articles/:id").handler(this::deleteOne);
    router.put("/api/articles/:id").handler(this::updateOne);

    ConfigRetriever retriever = ConfigRetriever.create(vertx);

    // Start sequence:
    // 1 - Retrieve the configuration
    //      |- 2 - Create the JDBC client
    //      |- 3 - Connect to the database (retrieve a connection)
    //              |- 4 - Create table if needed
    //                   |- 5 - Add some data if needed
    //                          |- 6 - Close connection when done
    //              |- 7 - Start HTTP server
    //      |- 9 - we are done!

    retriever.rxGetConfig()
        .doOnSuccess(config ->
            jdbc = JDBCClient.createShared(vertx, config, "My-Reading-List"))
        .flatMap(config ->
            connect()
                .flatMap(connection ->
                    this.createTableIfNeeded(connection)
                        .flatMap(this::createSomeDataIfNone)
                        .doAfterTerminate(connection::close)
                )
                .map(x -> config)
        )
        .flatMapCompletable(config -> createHttpServer(config, router))
        .subscribe(CompletableHelper.toObserver(fut));

}
 
Example #16
Source File: LoginCallbackFailureHandler.java    From graviteeio-access-management with Apache License 2.0 4 votes vote down vote up
private void doRedirect(HttpServerResponse response, String url) {
    response.putHeader(HttpHeaders.LOCATION, url).setStatusCode(302).end();
}
 
Example #17
Source File: ErrorHandler.java    From graviteeio-access-management with Apache License 2.0 4 votes vote down vote up
private void doRedirect(HttpServerResponse response, String url) {
    response.putHeader(HttpHeaders.LOCATION, url).setStatusCode(302).end();
}
 
Example #18
Source File: RestQuoteAPIVerticle.java    From vertx-kubernetes-workshop with Apache License 2.0 4 votes vote down vote up
@Override
public void start(Future<Void> future) throws Exception {
    // Get the stream of messages sent on the "market" address
    vertx.eventBus().<JsonObject>consumer(GeneratorConfigVerticle.ADDRESS).toFlowable()
        // TODO Extract the body of the message using `.map(msg -> {})`
        // ----
        .map(Message::body)
        // ----
        // TODO For each message, populate the `quotes` map with the received quote. Use `.doOnNext(json -> {})`
        // Quotes are json objects you can retrieve from the message body
        // The map is structured as follows: name -> quote
        // ----
        .doOnNext(json -> {
            quotes.put(json.getString("name"), json); // 2
        })
        // ----
        .subscribe();

    HttpServer server = vertx.createHttpServer();
    server.requestStream().toFlowable()
        .doOnNext(request -> {
            HttpServerResponse response = request.response()
                .putHeader("content-type", "application/json");

            // TODO Handle the HTTP request
            // The request handler returns a specific quote if the `name` parameter is set, or the whole map if none.
            // To write the response use: `response.end(content)`
            // If the name is set but not found, you should return 404 (use response.setStatusCode(404)).
            // To encode a Json object, use the `encorePrettily` method
            // ----
            
            String company = request.getParam("name");
            if (company == null) {
                String content = Json.encodePrettily(quotes);
                response.end(content);
            } else {
                JsonObject quote = quotes.get(company);
                if (quote == null) {
                    response.setStatusCode(404).end();
                } else {
                    response.end(quote.encodePrettily());
                }
            }
            // ----
        })
        .subscribe();

    server.rxListen(config().getInteger("http.port", 8080))
        .toCompletable()
        .subscribe(CompletableHelper.toObserver(future));
}
 
Example #19
Source File: CrnkVertxHandler.java    From crnk-framework with Apache License 2.0 4 votes vote down vote up
private Mono<HttpServerRequest> processRequest(HttpRequestContext context, HttpServerRequest serverRequest) {
    RequestDispatcher requestDispatcher = boot.getRequestDispatcher();

    long startTime = System.currentTimeMillis();
    LOGGER.debug("setting up request");

    try {
        Optional<Result<HttpResponse>> optResponse = requestDispatcher.process(context);

        if (optResponse.isPresent()) {
            MonoResult<HttpResponse> response = (MonoResult<HttpResponse>) optResponse.get();

            Mono<HttpResponse> mono = response.getMono();


            return mono.map(it -> {
                HttpServerResponse httpResponse = serverRequest.response();
                LOGGER.debug("delivering response {}", httpResponse);
                httpResponse.setStatusCode(it.getStatusCode());
                it.getHeaders().forEach((key, value) -> httpResponse.putHeader(key, value));
                if (it.getBody() != null) {
                    Buffer bodyBuffer = Buffer.newInstance(io.vertx.core.buffer.Buffer.buffer(it.getBody()));
                    httpResponse.end(bodyBuffer);
                } else {
                    httpResponse.end();
                }
                return serverRequest;
            });
        } else {
            serverRequest.response().setStatusCode(HttpStatus.NOT_FOUND_404);
            serverRequest.response().end();
            return Mono.just(serverRequest);
        }

    } catch (IOException e) {
        throw new IllegalStateException(e);
    } finally {
        long endTime = System.currentTimeMillis();
        LOGGER.debug("prepared request in in {}ms", endTime - startTime);
    }
}
 
Example #20
Source File: VertxPluginRequestHandler.java    From redpipe with Apache License 2.0 4 votes vote down vote up
@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)
      {
         ByteBufInputStream in = new ByteBufInputStream(buff.getDelegate().getByteBuf());
         vertxRequest.setInputStream(in);
      }

      try
      {
     	AppGlobals.set(appGlobals);
     	appGlobals.injectGlobals();
         dispatcher.service(ctx.getDelegate(), request.getDelegate(), response.getDelegate(), vertxRequest, vertxResponse, true);
      } catch (Failure e1)
      {
         vertxResponse.setStatus(e1.getErrorCode());
      } catch (Exception ex)
      {
         vertxResponse.setStatus(500);
         LogMessages.LOGGER.error(Messages.MESSAGES.unexpected(), ex);
      }
      finally 
      {
     	 AppGlobals.set(null);
      }
      if (!vertxRequest.getAsyncContext().isSuspended())
      {
         try
         {
            vertxResponse.finish();
         } catch (IOException e)
         {
            e.printStackTrace();
         }
      }
   });
}