Java Code Examples for io.vertx.ext.web.RoutingContext#response()
The following examples show how to use
io.vertx.ext.web.RoutingContext#response() .
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: UserApiHandler.java From openapi-generator with Apache License 2.0 | 6 votes |
private void createUsersWithListInput(RoutingContext routingContext) { logger.info("createUsersWithListInput()"); HttpServerResponse response = routingContext.response(); Single.defer( () -> { String jsonString = routingContext.getBodyAsString(); List<User> user = jsonString == null ? null : Json.decodeValue(jsonString, new TypeReference<List<User>>(){}); logger.info("Parameter user is {}", user); return apiImpl.createUsersWithListInput(user); }) .subscribe( apiResponse -> { response.setStatusCode(apiResponse.getStatusCode()) .end(Json.encodePrettily(apiResponse.getData())); }, error -> { if (error instanceof ApiException) { ApiException apiException = (ApiException) error; response.setStatusCode(apiException.getStatusCode()).end(apiException.getMessage()); } else { response.setStatusCode(500).end(error.getMessage()); } }).dispose(); }
Example 2
Source File: TranslateHandler.java From weld-vertx with Apache License 2.0 | 6 votes |
@Override public void handle(RoutingContext ctx) { HttpServerResponse response = ctx.response(); String sentence = ctx.request().getFormAttribute("sentence"); if (sentence != null) { LOGGER.debug("Handle translation: {0}", sentence); // See also Translator#translate() ctx.vertx().eventBus().<JsonArray> send(TRANSLATE, sentence, reply -> { if (reply.succeeded()) { response.putHeader("Content-type", "application/json"); response.setStatusCode(200).end(reply.result().body().encode()); } else { response.setStatusCode(500).end(reply.cause().toString()); } }); } else { response.end("Use \"application/x-www-form-urlencoded\" content type and specify value for name \"sentence\""); } }
Example 3
Source File: TestVertxRestDispatcher.java From servicecomb-java-chassis with Apache License 2.0 | 6 votes |
@Test public void failureHandlerWithNoExceptionAndStatusCodeIsNotSet(@Mocked RoutingContext context) { MockHttpServerResponse response = new MockHttpServerResponse(); new Expectations() { { context.get(RestConst.REST_PRODUCER_INVOCATION); result = null; context.failure(); returns(null, null); context.response(); result = response; context.statusCode(); result = Status.OK.getStatusCode(); } }; Deencapsulation.invoke(dispatcher, "failureHandler", context); Assert.assertThat(response.responseHeader, Matchers.hasEntry(HttpHeaders.CONTENT_TYPE, MediaType.WILDCARD)); Assert.assertThat(response.responseStatusCode, Matchers.is(Status.INTERNAL_SERVER_ERROR.getStatusCode())); Assert.assertThat(response.responseStatusMessage, Matchers.is(Status.INTERNAL_SERVER_ERROR.getReasonPhrase())); Assert.assertThat(response.responseChunk, Matchers.is("{\"message\":\"" + Status.INTERNAL_SERVER_ERROR.getReasonPhrase() + "\"}")); Assert.assertTrue(response.responseEnded); }
Example 4
Source File: ApisManagementEndpoint.java From gravitee-gateway with Apache License 2.0 | 6 votes |
@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 { Collection<ListApiEntity> apis = apiManager.apis().stream().map(api -> { ListApiEntity entity = new ListApiEntity(); entity.setId(api.getId()); entity.setName(api.getName()); entity.setVersion(api.getVersion()); return entity; }).collect(Collectors.toList()); Json.prettyMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); response.write(Json.prettyMapper.writeValueAsString(apis)); } catch (JsonProcessingException jpe) { response.setStatusCode(HttpStatusCode.INTERNAL_SERVER_ERROR_500); LOGGER.error("Unable to transform data object to JSON", jpe); } response.end(); }
Example 5
Source File: StoreApiHandler.java From openapi-generator with Apache License 2.0 | 6 votes |
private void getOrderById(RoutingContext routingContext) { logger.info("getOrderById()"); HttpServerResponse response = routingContext.response(); Single.defer( () -> { Long orderId = ParameterCast.toLong(routingContext.pathParams().get("orderId")); logger.info("Parameter orderId is {}", orderId); return apiImpl.getOrderById(orderId); }) .subscribe( apiResponse -> { response.setStatusCode(apiResponse.getStatusCode()) .end(Json.encodePrettily(apiResponse.getData())); }, error -> { if (error instanceof ApiException) { ApiException apiException = (ApiException) error; response.setStatusCode(apiException.getStatusCode()).end(apiException.getMessage()); } else { response.setStatusCode(500).end(error.getMessage()); } }).dispose(); }
Example 6
Source File: HystrixMetricEventStream.java From vertx-circuit-breaker with Apache License 2.0 | 6 votes |
@Override public void handle(RoutingContext rc) { HttpServerResponse response = rc.response(); response .setChunked(true) .putHeader(HttpHeaders.CONTENT_TYPE, "text/event-stream") .putHeader(HttpHeaders.CACHE_CONTROL, "no-cache") .putHeader(HttpHeaders.CONNECTION, HttpHeaders.KEEP_ALIVE); rc.request().connection() .closeHandler(v -> { connections.remove(response); endQuietly(response); }) .exceptionHandler(t -> { connections.remove(response); rc.fail(t); }); connections.add(response); }
Example 7
Source File: ApiController.java From exonum-java-binding with Apache License 2.0 | 6 votes |
private void failureHandler(RoutingContext rc) { logger.info("An error whilst processing request {}", rc.normalisedPath()); Throwable requestFailure = rc.failure(); if (requestFailure != null) { HttpServerResponse response = rc.response(); if (isBadRequest(requestFailure)) { logger.info("Request error:", requestFailure); response.setStatusCode(HTTP_BAD_REQUEST); } else { logger.error("Internal error", requestFailure); response.setStatusCode(HTTP_INTERNAL_ERROR); } String description = Strings.nullToEmpty(requestFailure.getMessage()); response.putHeader(CONTENT_TYPE, "text/plain") .end(description); } else { int failureStatusCode = rc.statusCode(); rc.response() .setStatusCode(failureStatusCode) .end(); } }
Example 8
Source File: SmallRyeMetricsHandler.java From quarkus with Apache License 2.0 | 6 votes |
@Override public void handle(RoutingContext routingContext) { MetricsRequestHandler internalHandler = CDI.current().select(MetricsRequestHandler.class).get(); HttpServerResponse response = routingContext.response(); HttpServerRequest request = routingContext.request(); Stream<String> acceptHeaders = request.headers().getAll("Accept").stream(); try { internalHandler.handleRequest(request.path(), metricsPath, request.rawMethod(), acceptHeaders, (status, message, headers) -> { response.setStatusCode(status); headers.forEach(response::putHeader); response.end(Buffer.buffer(message)); }); } catch (IOException e) { response.setStatusCode(503); response.end(); LOGGER.error(e); } }
Example 9
Source File: StoreApiHandler.java From openapi-generator with Apache License 2.0 | 6 votes |
private void placeOrder(RoutingContext routingContext) { logger.info("placeOrder()"); HttpServerResponse response = routingContext.response(); Single.defer( () -> { String jsonString = routingContext.getBodyAsString(); Order order = jsonString == null ? null : Json.decodeValue(jsonString, new TypeReference<Order>(){}); logger.info("Parameter order is {}", order); return apiImpl.placeOrder(order); }) .subscribe( apiResponse -> { response.setStatusCode(apiResponse.getStatusCode()) .end(Json.encodePrettily(apiResponse.getData())); }, error -> { if (error instanceof ApiException) { ApiException apiException = (ApiException) error; response.setStatusCode(apiException.getStatusCode()).end(apiException.getMessage()); } else { response.setStatusCode(500).end(error.getMessage()); } }).dispose(); }
Example 10
Source File: AbstractEventBusHttpEndpoint.java From hono with Eclipse Public License 2.0 | 6 votes |
/** * Gets a response handler that implements the default behavior for responding to an HTTP request. * <p> * The default behavior is as follows: * <ol> * <li>Set the status code on the response.</li> * <li>If the status code represents an error condition (i.e. the code is >= 400), * then the JSON object passed in to the returned handler is written to the response body.</li> * <li>Otherwise, if the given filter evaluates to {@code true} for the status code, * the given custom handler is invoked (if not {@code null}), then * the JSON object is written to the response body and </li> * </ol> * * @param ctx The routing context of the request. * @param successfulOutcomeFilter A predicate that evaluates to {@code true} for the status code(s) representing a * successful outcome. * @param customHandler An (optional) handler for post processing the HTTP response, e.g. to set any additional HTTP * headers. The handler <em>must not</em> write to response body. May be {@code null}. * @return The created handler for processing responses. * @throws NullPointerException If routing context or filter is {@code null}. */ protected final BiConsumer<Integer, EventBusMessage> getDefaultResponseHandler( final RoutingContext ctx, final IntPredicate successfulOutcomeFilter, final BiConsumer<HttpServerResponse, EventBusMessage> customHandler) { Objects.requireNonNull(successfulOutcomeFilter); final HttpServerResponse response = ctx.response(); return (status, result) -> { response.setStatusCode(status); if (status >= 400) { HttpUtils.setResponseBody(response, result.getJsonPayload()); } else if (successfulOutcomeFilter.test(status)) { if (customHandler != null) { customHandler.accept(response, result); } HttpUtils.setResponseBody(response, result.getJsonPayload()); } response.end(); }; }
Example 11
Source File: LanAccessSubRouter.java From AlipayWechatPlatform with GNU General Public License v3.0 | 6 votes |
/** * 判断当前请求是否允许,如果不允许,则将状态码设为403并结束响应 * * @return true:禁止访问 false=允许访问 * @author Leibniz.Hu */ protected boolean refuseNonLanAccess(RoutingContext rc) { HttpServerRequest req = rc.request(); HttpServerResponse resp = rc.response(); String realIp = req.getHeader("X-Real-IP"); String xforward = req.getHeader("X-Forwarded-For"); //禁止外网访问 if (realIp != null && !isLanIP(realIp)) { log.warn("检测到非法访问,来自X-Real-IP={}", realIp); resp.setStatusCode(403).end(); return true; } if (xforward != null && !isLanIP(xforward)) { log.warn("检测到非法访问,来自X-Forwarded-For={}", xforward); resp.setStatusCode(403).end(); return true; } return false; }
Example 12
Source File: PgUtil.java From raml-module-builder with Apache License 2.0 | 6 votes |
/** * streamGet that takes CQLWrapper and FacetField List * @param <T> * @param table * @param clazz * @param filter * @param facetList * @param element * @param queryTimeout query timeout in milliseconds, or 0 for no timeout * @param okapiHeaders * @param vertxContext * @param routingContext */ @SuppressWarnings({"unchecked", "squid:S107"}) // Method has >7 parameters public static <T> void streamGet(String table, Class<T> clazz, CQLWrapper filter, List<FacetField> facetList, String element, int queryTimeout, RoutingContext routingContext, Map<String, String> okapiHeaders, Context vertxContext) { HttpServerResponse response = routingContext.response(); PostgresClient postgresClient = PgUtil.postgresClient(vertxContext, okapiHeaders); postgresClient.streamGet(table, clazz, JSON_COLUMN, filter, true, null, facetList, queryTimeout, reply -> { if (reply.failed()) { String message = PgExceptionUtil.badRequestMessage(reply.cause()); if (message == null) { message = reply.cause().getMessage(); } logger.error(message, reply.cause()); response.setStatusCode(400); response.putHeader(HttpHeaders.CONTENT_TYPE, "text/plain"); response.end(message); return; } streamGetResult(reply.result(), element, response); }); }
Example 13
Source File: SmallRyeHealthHandlerBase.java From quarkus with Apache License 2.0 | 5 votes |
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 14
Source File: Main.java From DocBleach with MIT License | 5 votes |
private void sendFile(RoutingContext routingContext, String fileName, File saneFile) { HttpServerResponse response = routingContext.response(); response.putHeader("Content-Description", "File Transfer"); response.putHeader("Content-Type", "application/octet-stream"); response.putHeader( "Content-Disposition", "attachment; filename=" + fileName); // @TODO: don't trust this name? response.putHeader("Content-Transfer-Encoding", "binary"); response.putHeader("Expires", "0"); response.putHeader("Pragma", "Public"); response.putHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0"); response.putHeader("Content-Length", "" + saneFile.length()); response.sendFile(saneFile.getAbsolutePath()); }
Example 15
Source File: ReadHandler.java From nassh-relay with GNU General Public License v2.0 | 5 votes |
@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("rcnt")) { final UUID sid = UUID.fromString(request.params().get("sid")); final LocalMap<String, Session> map = vertx.sharedData().getLocalMap(Constants.SESSIONS); final Session session = map.get(sid.toString()); if (session == null) { logger.warn("could not find valid session for " + sid); response.setStatusCode(410); response.end(); return; } session.setRead_count(Integer.parseInt(request.params().get("rcnt"))); final TransferQueue queue; try { queue = QueueFactory.getQueue(sid.toString()); } catch (NoSuchQueueException ex) { logger.warn(ex, ex.fillInStackTrace()); response.setStatusCode(410); response.end(); return; } final Buffer buffer = queue.poll(); if (buffer == null) { queue.addObserver(new TransferObserver(session, request)); } else { final String encodedBytes = Base64.getUrlEncoder().encodeToString(buffer.getBytes()); response.setStatusCode(200); response.end(encodedBytes); } } else { response.setStatusCode(410); response.end(); } }
Example 16
Source File: HttpResponse.java From okapi with Apache License 2.0 | 5 votes |
/** * Produce HTTP response with status code and application/json header. * @param ctx routing context from where HTTP response is generated * @param code status code * @return HTTP server response */ public static HttpServerResponse responseJson(RoutingContext ctx, int code) { HttpServerResponse res = ctx.response(); if (!res.closed()) { res.setStatusCode(code).putHeader("Content-Type", "application/json"); } return res; }
Example 17
Source File: JsonRpcHttpService.java From besu with Apache License 2.0 | 5 votes |
private void handleJsonRpcUnauthorizedError( final RoutingContext routingContext, final Object id, final JsonRpcError error) { final HttpServerResponse response = routingContext.response(); if (!response.closed()) { response .setStatusCode(HttpResponseStatus.UNAUTHORIZED.code()) .end(Json.encode(new JsonRpcErrorResponse(id, error))); } }
Example 18
Source File: GraphQLHttpService.java From besu with Apache License 2.0 | 5 votes |
private void handleGraphQLError(final RoutingContext routingContext, final Exception ex) { LOG.debug("Error handling GraphQL request", ex); final HttpServerResponse response = routingContext.response(); if (!response.closed()) { response .setStatusCode(HttpResponseStatus.BAD_REQUEST.code()) .end(Json.encode(new GraphQLErrorResponse(ex.getMessage()))); } }
Example 19
Source File: SimpleWebVerticle.java From jkube with Eclipse Public License 2.0 | 4 votes |
private void handleGet(RoutingContext routingContext) { HttpServerResponse response = routingContext.response(); String welcome = routingContext.request().getParam("welcome"); response.end("Reply: " + welcome); }
Example 20
Source File: VertxServerHttpResponse.java From vertx-spring-boot with Apache License 2.0 | 4 votes |
public VertxServerHttpResponse(RoutingContext context, BufferConverter bufferConverter) { super(bufferConverter.getDataBufferFactory(), initHeaders(context.response())); this.context = context; this.delegate = context.response(); this.bufferConverter = bufferConverter; }