Java Code Examples for io.vertx.core.http.HttpServerResponse#setStatusCode()

The following examples show how to use io.vertx.core.http.HttpServerResponse#setStatusCode() . 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: ApiManagementEndpoint.java    From gravitee-gateway with Apache License 2.0 6 votes vote down vote up
@Override
public void handle(RoutingContext ctx) {
    HttpServerResponse response = ctx.response();

    try {
        String sApi = ctx.request().getParam("apiId");
        Api api = apiManager.get(sApi);

        if (api == null) {
            response.setStatusCode(HttpStatusCode.NOT_FOUND_404);
        } else {
            response.putHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON);
            response.setStatusCode(HttpStatusCode.OK_200);
            response.setChunked(true);

            Json.prettyMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
            response.write(Json.prettyMapper.writeValueAsString(api));
        }
    } catch (JsonProcessingException jpe) {
        response.setStatusCode(HttpStatusCode.INTERNAL_SERVER_ERROR_500);
        LOGGER.error("Unable to transform data object to JSON", jpe);
    }

    response.end();
}
 
Example 2
Source File: SSEHandlerImpl.java    From vertx-sse with Apache License 2.0 6 votes vote down vote up
@Override
public void handle(RoutingContext context) {
	HttpServerRequest request = context.request();
	HttpServerResponse response = context.response();
	response.setChunked(true);
	SSEConnection connection = SSEConnection.create(context);
	String accept = request.getHeader("Accept");
	if (accept != null && !accept.contains("text/event-stream")) {
		connection.reject(406, "Not acceptable");
		return;
	}
	response.closeHandler(aVoid -> {
		closeHandlers.forEach(closeHandler -> closeHandler.handle(connection));
		connection.close();
	});
	response.headers().add("Content-Type", "text/event-stream");
	response.headers().add("Cache-Control", "no-cache");
	response.headers().add("Connection", "keep-alive");
	connectHandlers.forEach(handler -> handler.handle(connection));
	if (!connection.rejected()) {
		response.setStatusCode(200);
		response.setChunked(true);
		response.write(EMPTY_BUFFER);
	}
}
 
Example 3
Source File: NexusHttpProxy.java    From nexus-proxy with Apache License 2.0 6 votes vote down vote up
/**
 * Proxies the specified HTTP request, enriching its headers with authentication information.
 *
 * @param userId  the ID of the user making the request.
 * @param origReq the original request (i.e., {@link RoutingContext#request()}.
 * @param origRes the original response (i.e., {@link RoutingContext#request()}.
 */
public void proxyUserRequest(final String userId,
                             final HttpServerRequest origReq,
                             final HttpServerResponse origRes) {
    final Handler<HttpClientResponse> proxiedResHandler = proxiedRes -> {
        origRes.setChunked(true);
        origRes.setStatusCode(proxiedRes.statusCode());
        origRes.headers().setAll(proxiedRes.headers());
        proxiedRes.handler(origRes::write);
        proxiedRes.endHandler(v -> origRes.end());
    };

    final HttpClientRequest proxiedReq;
    proxiedReq = httpClient.request(origReq.method(), port, host, origReq.uri(), proxiedResHandler);
    if(origReq.method() == HttpMethod.OTHER) {
        proxiedReq.setRawMethod(origReq.rawMethod());
    }
    proxiedReq.setChunked(true);
    proxiedReq.headers().add(X_FORWARDED_PROTO, getHeader(origReq, X_FORWARDED_PROTO, origReq.scheme()));
    proxiedReq.headers().add(X_FORWARDED_FOR, getHeader(origReq, X_FORWARDED_FOR, origReq.remoteAddress().host()));
    proxiedReq.headers().addAll(origReq.headers());
    injectRutHeader(proxiedReq, userId);
    origReq.handler(proxiedReq::write);
    origReq.endHandler(v -> proxiedReq.end());
}
 
Example 4
Source File: ProxyService.java    From okapi with Apache License 2.0 6 votes vote down vote up
private void relayToResponse(HttpServerResponse hres,
                             HttpClientResponse res, ProxyContext pc) {
  if (pc.getHandlerRes() != 0) {
    hres.setStatusCode(pc.getHandlerRes());
    hres.headers().addAll(pc.getHandlerHeaders());
  } else if (pc.getAuthRes() != 0 && (pc.getAuthRes() < 200 || pc.getAuthRes() >= 300)) {
    hres.setStatusCode(pc.getAuthRes());
    hres.headers().addAll(pc.getAuthHeaders());
  } else {
    if (res != null) {
      hres.setStatusCode(res.statusCode());
      hres.headers().addAll(res.headers());
    }
  }
  sanitizeAuthHeaders(hres.headers());
  hres.headers().remove("Content-Length");
  hres.headers().remove("Transfer-Encoding");
  if (hres.getStatusCode() != 204) {
    hres.setChunked(true);
  }
}
 
Example 5
Source File: ApiKeysServiceHandler.java    From gravitee-gateway with Apache License 2.0 6 votes vote down vote up
@Override
public void handle(RoutingContext ctx) {
    HttpServerResponse response = ctx.response();
    response.setStatusCode(HttpStatusCode.OK_200);
    response.putHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON);
    response.setChunked(true);

    try {
        Json.prettyMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
        response.write(Json.prettyMapper.writeValueAsString(new ExecutorStatistics()));
    } catch (JsonProcessingException jpe) {
        response.setStatusCode(HttpStatusCode.INTERNAL_SERVER_ERROR_500);
        LOGGER.error("Unable to transform data object to JSON", jpe);
    }

    response.end();
}
 
Example 6
Source File: HttpVerticle.java    From reactive-refarch-cloudformation with Apache License 2.0 5 votes vote down vote up
private void sendResponse(final RoutingContext routingContext, int statusCode, final String message) {
    HttpServerResponse response = routingContext.request().response();
    response.setStatusCode(statusCode);
    response.putHeader("content-type", "application/json");

    if (message != null)
        response.end(message);
    else
        response.end();
}
 
Example 7
Source File: WriteHandler.java    From nassh-relay with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void handle(final RoutingContext context) {
    final HttpServerRequest request = context.request();
    final HttpServerResponse response = context.response();
    response.putHeader("Cache-Control", "no-store, no-cache, must-revalidate, max-age=0");
    response.putHeader("Pragma", "no-cache");
    if (request.params().contains("sid") && request.params().contains("wcnt") && request.params().contains("data")) {
        final UUID sid = UUID.fromString(request.params().get("sid"));
        final byte[] data = Base64.getUrlDecoder().decode(request.params().get("data"));
        response.setStatusCode(200);
        final LocalMap<String, Session> map = vertx.sharedData().getLocalMap(Constants.SESSIONS);
        final Session session = map.get(sid.toString());
        if (session == null) {
            response.setStatusCode(410);
            response.end();
            return;
        }
        session.setWrite_count(Integer.parseInt(request.params().get("wcnt")));
        final Buffer message = Buffer.buffer();
        message.appendBytes(data);
        vertx.eventBus().publish(session.getHandler(), message);
        response.end();
    } else {
        response.setStatusCode(410);
        response.end();
    }
}
 
Example 8
Source File: TestContextRest.java    From rest.vertx with Apache License 2.0 5 votes vote down vote up
@GET
@Path("/login")
public HttpServerResponse login(@Context HttpServerResponse response) {

	response.setStatusCode(201);
	response.putHeader("X-SessionId", "session");
	response.end("Hello world!");
	return response;
}
 
Example 9
Source File: NotFoundResponseWriter.java    From rest.vertx with Apache License 2.0 5 votes vote down vote up
@Override
public void write(Void result, HttpServerRequest request, HttpServerResponse response) {

	// pre-fill 404 for convenience
	response.setStatusCode(Response.Status.NOT_FOUND.getStatusCode());

	// wrapped call to simplify implementation
	write(request, response);
}
 
Example 10
Source File: SwaggerRouter.java    From vertx-swagger with Apache License 2.0 5 votes vote down vote up
private static void manageError( ReplyException cause, HttpServerResponse response) {
    if(isExistingHttStatusCode(cause.failureCode())) {
        response.setStatusCode(cause.failureCode());
        if(StringUtils.isNotEmpty(cause.getMessage())) {
            response.setStatusMessage(cause.getMessage());
        }
    } else {
        response.setStatusCode(HttpResponseStatus.INTERNAL_SERVER_ERROR.code());
    }
    response.end();
}
 
Example 11
Source File: HttpVerticle.java    From reactive-refarch-cloudformation with Apache License 2.0 5 votes vote down vote up
private void purgeCache(final RoutingContext routingContext) {
    eb.send(Constants.REDIS_PURGE_EVENTBUS_ADDRESS, "");
    eb.send(Constants.CACHE_PURGE_EVENTBUS_ADDRESS, "");

    HttpServerResponse response = routingContext.request().response();
    response.setStatusCode(200);
    response.putHeader("content-type", "application/json");
    response.end();
}
 
Example 12
Source File: SmallRyeHealthHandlerBase.java    From quarkus with Apache License 2.0 5 votes vote down vote up
private void doHandle(RoutingContext ctx) {
    SmallRyeHealthReporter reporter = Arc.container().instance(SmallRyeHealthReporter.class).get();
    SmallRyeHealth health = getHealth(reporter, ctx);
    HttpServerResponse resp = ctx.response();
    if (health.isDown()) {
        resp.setStatusCode(503);
    }
    resp.headers().set(HttpHeaders.CONTENT_TYPE, "application/json; charset=UTF-8");
    try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) {
        reporter.reportHealth(outputStream, health);
        resp.end(Buffer.buffer(outputStream.toByteArray()));
    } catch (IOException e) {
        throw new UncheckedIOException(e);
    }
}
 
Example 13
Source File: SyncHandler.java    From gravitee-gateway with Apache License 2.0 5 votes vote down vote up
@Override
public void handle(RoutingContext ctx) {
    HttpServerResponse response = ctx.response();
    JsonObject object = new JsonObject()
            .put("counter", syncManager.getCounter())
            .put("lastRefreshAt", syncManager.getLastRefreshAt());

    response.putHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON);
    response.setChunked(true);
    response.write(object.encodePrettily());
    response.setStatusCode(HttpStatusCode.OK_200);
    response.end();
}
 
Example 14
Source File: NoContentResponseWriter.java    From rest.vertx with Apache License 2.0 4 votes vote down vote up
@Override
public void write(Object result, HttpServerRequest request, HttpServerResponse response) {

	response.setStatusCode(204);
}
 
Example 15
Source File: ResponseExecution.java    From vxms with Apache License 2.0 4 votes vote down vote up
private static void updateResponseStatusCode(int httpStatusCode, HttpServerResponse response) {
  if (httpStatusCode != 0) {
    response.setStatusCode(httpStatusCode);
  }
}
 
Example 16
Source File: CookieHandler.java    From nassh-relay with GNU General Public License v2.0 4 votes vote down vote up
@Override
public void handle(final RoutingContext context) {
    logger.debug("got request");
    final HttpServerRequest request = context.request();
    final HttpServerResponse response = context.response();
    response.putHeader("Cache-Control", "no-store, no-cache, must-revalidate, max-age=0");
    response.putHeader("Pragma", "no-cache");
    if (request.params().contains("ext") && request.params().contains("path")) {
        final String ext = request.params().get("ext");
        final String path = request.params().get("path");
        if (!authentication) {
            response.putHeader("location", "chrome-extension://" + ext + "/" + path + "#anonymous@" + RequestHelper.getHost(request));
            response.setStatusCode(302);
            response.end();
            return;
        }
        final AuthSession authSession = WebHelper.validateCookie(context);
        if (authSession != null) {
            final String gplusid = authSession.get("id");
            response.putHeader("location", "chrome-extension://" + ext + "/" + path + "#" + gplusid + "@" + RequestHelper.getHost(request));
            response.setStatusCode(302);
            response.end();
        } else {
            response.setStatusCode(200);
            final String state = new BigInteger(130, new SecureRandom()).toString(32);
            final AuthSession session = AuthSessionManager.createSession(sessionTTL);
            session.put("state", state);
            final Cookie sessionCookie = Cookie
                .cookie(Constants.SESSIONCOOKIE, session.getId().toString())
                .setHttpOnly(true);
            if (secureCookie) {
                sessionCookie
                    .setSameSite(CookieSameSite.NONE)
                    .setSecure(true);
            }
            response.addCookie(sessionCookie);
            final String auth_html = new Scanner(this.getClass().getResourceAsStream(STATIC_FILE), "UTF-8")
                .useDelimiter("\\A").next()
                .replaceAll("[{]{2}\\s*CLIENT_ID\\s*[}]{2}", auth.getString("client-id"))
                .replaceAll("[{]{2}\\s*STATE\\s*[}]{2}", state)
                .replaceAll("[{]{2}\\s*APPLICATION_NAME\\s*[}]{2}", auth.getString("title"));
            response.end(auth_html);
        }
    } else {
        response.setStatusCode(401);
        response.end("unauthorized");
    }
}
 
Example 17
Source File: MyExceptionHandler.java    From rest.vertx with Apache License 2.0 4 votes vote down vote up
@Override
public void write(MyExceptionClass result, HttpServerRequest request, HttpServerResponse response) {

	response.setStatusCode(result.getStatus());
	response.end("Exception: " + result.getError());
}
 
Example 18
Source File: Utils.java    From dfx with Apache License 2.0 4 votes vote down vote up
public static void fireJsonResponse(HttpServerResponse response, int statusCode, Map payload) {
    response.setStatusCode(statusCode);
    JsonObject jsonObject = new JsonObject(payload);
    response.putHeader("content-type", "application/json; charset=utf-8").end(jsonObject.toString());
}
 
Example 19
Source File: MyGlobalExceptionHandler.java    From rest.vertx with Apache License 2.0 4 votes vote down vote up
@Override
public void write(Throwable result, HttpServerRequest request, HttpServerResponse response) {

	response.setStatusCode(400);
	response.end(name + " " + result.getMessage());
}
 
Example 20
Source File: SigfoxProtocolAdapter.java    From hono with Eclipse Public License 2.0 3 votes vote down vote up
@Override
protected void setNonEmptyResponsePayload(final HttpServerResponse response, final CommandContext commandContext,
        final Span currentSpan) {

    currentSpan.log("responding with: payload");

    final Command command = commandContext.getCommand();
    response.setStatusCode(HttpURLConnection.HTTP_OK);
    final Buffer payload = convertToResponsePayload(command);

    LOG.debug("Setting response for ACK: {}", payload);

    HttpUtils.setResponseBody(response, payload, HttpUtils.CONTENT_TYPE_JSON);

}