Java Code Examples for io.vertx.core.http.HttpServerRequest#response()
The following examples show how to use
io.vertx.core.http.HttpServerRequest#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: KnativeHttpConsumer.java From camel-k-runtime with Apache License 2.0 | 6 votes |
private HttpServerResponse toHttpResponse(HttpServerRequest request, Message message) { final HttpServerResponse response = request.response(); final boolean failed = message.getExchange().isFailed(); final int defaultCode = failed ? 500 : 200; final int code = message.getHeader(Exchange.HTTP_RESPONSE_CODE, defaultCode, int.class); final TypeConverter tc = message.getExchange().getContext().getTypeConverter(); response.setStatusCode(code); for (Map.Entry<String, Object> entry : message.getHeaders().entrySet()) { final String key = entry.getKey(); final Object value = entry.getValue(); for (Object it: org.apache.camel.support.ObjectHelper.createIterable(value, null)) { String headerValue = tc.convertTo(String.class, it); if (headerValue == null) { continue; } if (!headerFilterStrategy.applyFilterToCamelHeaders(key, headerValue, message.getExchange())) { response.putHeader(key, headerValue); } } } return response; }
Example 2
Source File: Jukebox.java From vertx-in-action with MIT License | 6 votes |
private void downloadFile(AsyncFile file, HttpServerRequest request) { HttpServerResponse response = request.response(); response.setStatusCode(200) .putHeader("Content-Type", "audio/mpeg") .setChunked(true); file.handler(buffer -> { response.write(buffer); if (response.writeQueueFull()) { file.pause(); response.drainHandler(v -> file.resume()); } }); file.endHandler(v -> response.end()); }
Example 3
Source File: App.java From FrameworkBenchmarks with BSD 3-Clause "New" or "Revised" License | 6 votes |
private void handleDb(HttpServerRequest req) { HttpServerResponse resp = req.response(); client.preparedQuery(SELECT_WORLD, Tuple.of(randomWorld()), res -> { if (res.succeeded()) { PgIterator resultSet = res.result().iterator(); if (!resultSet.hasNext()) { resp.setStatusCode(404).end(); return; } Tuple row = resultSet.next(); resp .putHeader(HttpHeaders.SERVER, SERVER) .putHeader(HttpHeaders.DATE, dateString) .putHeader(HttpHeaders.CONTENT_TYPE, RESPONSE_TYPE_JSON) .end(Json.encode(new World(row.getInteger(0), row.getInteger(1)))); } else { logger.error(res.cause()); resp.setStatusCode(500).end(res.cause().getMessage()); } }); }
Example 4
Source File: Jukebox.java From vertx-in-action with MIT License | 5 votes |
private void downloadFilePipe(AsyncFile file, HttpServerRequest request) { HttpServerResponse response = request.response(); response.setStatusCode(200) .putHeader("Content-Type", "audio/mpeg") .setChunked(true); file.pipeTo(response); }
Example 5
Source File: HttpServer.java From vertx-in-action with MIT License | 5 votes |
private void sse(HttpServerRequest request) { HttpServerResponse response = request.response(); response .putHeader("Content-Type", "text/event-stream") .putHeader("Cache-Control", "no-cache") .setChunked(true); MessageConsumer<JsonObject> consumer = vertx.eventBus().consumer("sensor.updates"); consumer.handler(msg -> { response.write("event: update\n"); response.write("data: " + msg.body().encode() + "\n\n"); }); TimeoutStream ticks = vertx.periodicStream(1000); ticks.handler(id -> { vertx.eventBus().<JsonObject>request("sensor.average", "", reply -> { if (reply.succeeded()) { response.write("event: average\n"); response.write("data: " + reply.result().body().encode() + "\n\n"); } }); }); response.endHandler(v -> { consumer.unregister(); ticks.cancel(); }); }
Example 6
Source File: HttpResponseFactory.java From ethsigner with Apache License 2.0 | 5 votes |
public void create( final HttpServerRequest httpRequest, final int statusCode, final JsonRpcResponse body) { final HttpServerResponse response = httpRequest.response(); response.putHeader("Content", JSON); response.setStatusCode(statusCode); response.setChunked(false); response.end(Json.encodeToBuffer(body)); }
Example 7
Source File: VertxHttpResponse.java From quarkus with Apache License 2.0 | 5 votes |
public VertxHttpResponse(HttpServerRequest request, ResteasyProviderFactory providerFactory, final HttpMethod method, BufferAllocator allocator, VertxOutput output) { outputHeaders = new MultivaluedMapImpl<String, Object>(); this.method = method; os = (method == null || !method.equals(HttpMethod.HEAD)) ? new VertxOutputStream(this, allocator) : null; this.request = request; this.response = request.response(); this.providerFactory = providerFactory; this.output = output; }
Example 8
Source File: HttpPolicyAdapter.java From apiman with Apache License 2.0 | 5 votes |
public HttpPolicyAdapter(HttpServerRequest req, IPolicyFailureWriter policyFailureWriter, IPolicyErrorWriter policyErrorWriter, IEngine engine, boolean isTls) { this.vertxRequest = req; this.policyFailureWriter = policyFailureWriter; this.policyErrorWriter = policyErrorWriter; this.engine = engine; this.isTls = isTls; this.vertxResponse = req.response(); }
Example 9
Source File: App.java From FrameworkBenchmarks with BSD 3-Clause "New" or "Revised" License | 5 votes |
private void handle(HttpServerRequest req) { HttpServerResponse resp = req.response(); final int queries = getQueries(req); for (int i = 0; i < queries; i++) { client.preparedQuery(SELECT_WORLD, Tuple.of(randomWorld()), ar -> { if (!failed) { if (ar.failed()) { failed = true; resp.setStatusCode(500).end(ar.cause().getMessage()); return; } // we need a final reference final Tuple row = ar.result().iterator().next(); worlds.add(new JsonObject().put("id", "" + row.getInteger(0)).put("randomNumber", "" + row.getInteger(1))); // stop condition if (worlds.size() == queries) { resp .putHeader(HttpHeaders.SERVER, SERVER) .putHeader(HttpHeaders.DATE, dateString) .putHeader(HttpHeaders.CONTENT_TYPE, RESPONSE_TYPE_JSON) .end(worlds.encode()); } } }); } }
Example 10
Source File: App.java From FrameworkBenchmarks with BSD 3-Clause "New" or "Revised" License | 5 votes |
private void handleJson(HttpServerRequest request) { HttpServerResponse response = request.response(); MultiMap headers = response.headers(); headers .add(HEADER_CONTENT_TYPE, RESPONSE_TYPE_JSON) .add(HEADER_SERVER, SERVER) .add(HEADER_DATE, dateString); response.end(new Message("Hello, World!").toBuffer()); }
Example 11
Source File: App.java From FrameworkBenchmarks with BSD 3-Clause "New" or "Revised" License | 5 votes |
private void handlePlainText(HttpServerRequest request) { HttpServerResponse response = request.response(); MultiMap headers = response.headers(); for (int i = 0;i < plaintextHeaders.length; i+= 2) { headers.add(plaintextHeaders[i], plaintextHeaders[i + 1]); } response.end(HELLO_WORLD_BUFFER); }
Example 12
Source File: EchoServerVertx.java From apiman with Apache License 2.0 | 4 votes |
private void _handle(HttpServerRequest req) { HttpServerResponse rep = req.response(); if (req.headers().contains("X-Echo-ErrorCode")) { // Check if number, if not then set to 400. int errorCode = Optional.of(req.getHeader("X-Echo-ErrorCode")) .filter(NumberUtils::isNumber) .map(Integer::valueOf) .orElse(400); // Get error message, else set to "" to avoid NPE. String statusMsg = Optional.ofNullable(req.getHeader("X-Echo-ErrorMessage")) .orElse(""); // #end writes and flushes the response. rep.setStatusCode(errorCode) .setStatusMessage(statusMsg) .end(); return; } // If redirect query param set, do a 302. String query = req.query(); if (query != null && query.startsWith("redirectTo=")) { String redirectTo = query.substring(11); rep.putHeader("Location", redirectTo) .setStatusCode(302) .end(); return; } // Determine if explicitly needs XML (else, use JSON). boolean isXml = Optional.of(req.getHeader("Accept")) .filter(accept -> accept.contains("application/xml")) .map(accept -> !(accept.contains("application/json"))) .orElse(false); // Build response EchoResponse echo = new EchoResponse(); echo.setMethod(req.method().toString()); echo.setResource(normaliseResource(req)); echo.setUri(req.path()); req.handler(body -> { sha1.update(body.getBytes()); bodyLength += body.length(); }).endHandler(end -> { // If any body was present, encode digest as Base64. if (bodyLength > 0) { echo.setBodyLength(bodyLength); echo.setBodySha1(Base64.getEncoder().encodeToString(sha1.digest())); } echo.setCounter(++counter); echo.setHeaders(multimapToMap(req.headers())); rep.putHeader("Response-Counter", echo.getCounter().toString()); rep.setChunked(true); if (isXml) { // XML rep.putHeader("Content-Type", "application/xml"); writeXmlAndEnd(rep, echo); } else { // JSON rep.putHeader("Content-Type", "application/json"); writeJsonAndEnd(rep, echo); } }); }
Example 13
Source File: ServerConnectionHandleRequestInterceptor.java From pinpoint with Apache License 2.0 | 4 votes |
@Override public void before(Object target, Object[] args) { if (isDebug) { logger.beforeInterceptor(target, args); } if (traceContext.currentRawTraceObject() != null) { // duplicate trace. return; } try { if (!validate(args)) { // invalid args. return; } final HttpServerRequest request = (HttpServerRequest) args[0]; final HttpServerResponse response = request.response(); if (!(response instanceof AsyncContextAccessor)) { if (isDebug) { logger.debug("Invalid response. Need metadata accessor({}).", AsyncContextAccessor.class.getName()); } return; } // create trace for standalone entry point. final Trace trace = createTrace(request); if (trace == null) { return; } entryScope(trace); this.httpHeaderFilter.filter(request); if (!trace.canSampled()) { return; } final SpanEventRecorder recorder = trace.traceBlockBegin(); recorder.recordServiceType(VertxConstants.VERTX_HTTP_SERVER_INTERNAL); // make asynchronous trace-id final AsyncContext asyncContext = recorder.recordNextAsyncContext(true); ((AsyncContextAccessor) request)._$PINPOINT$_setAsyncContext(asyncContext); ((AsyncContextAccessor) response)._$PINPOINT$_setAsyncContext(asyncContext); if (isDebug) { logger.debug("Set closeable-AsyncContext {}", asyncContext); } } catch (Throwable t) { if (logger.isWarnEnabled()) { logger.warn("BEFORE. Caused:{}", t.getMessage(), t); } } }
Example 14
Source File: VertxHttpServerResponse.java From gravitee-gateway with Apache License 2.0 | 4 votes |
public VertxHttpServerResponse(final HttpServerRequest httpServerRequest, final Metrics metrics) { this.httpServerResponse = httpServerRequest.response(); version = httpServerRequest.version(); this.metrics = metrics; }
Example 15
Source File: VertxHttpServerResponse.java From graviteeio-access-management with Apache License 2.0 | 4 votes |
public VertxHttpServerResponse(final HttpServerRequest httpServerRequest, final Metrics metrics) { this.httpServerResponse = httpServerRequest.response(); version = httpServerRequest.version(); this.metrics = metrics; }
Example 16
Source File: VertxRequestHandler.java From quarkus with Apache License 2.0 | 4 votes |
private void dispatch(RoutingContext routingContext, InputStream is, VertxOutput output) { ManagedContext requestContext = beanContainer.requestContext(); requestContext.activate(); routingContext.remove(QuarkusHttpUser.AUTH_FAILURE_HANDLER); QuarkusHttpUser user = (QuarkusHttpUser) routingContext.user(); if (association != null) { association.setIdentity(QuarkusHttpUser.getSecurityIdentity(routingContext, null)); } currentVertxRequest.setCurrent(routingContext); try { Context ctx = vertx.getOrCreateContext(); HttpServerRequest request = routingContext.request(); ResteasyUriInfo uriInfo = VertxUtil.extractUriInfo(request, rootPath); ResteasyHttpHeaders headers = VertxUtil.extractHttpHeaders(request); HttpServerResponse response = request.response(); VertxHttpResponse vertxResponse = new VertxHttpResponse(request, dispatcher.getProviderFactory(), request.method(), allocator, output); // using a supplier to make the remote Address resolution lazy: often it's not needed and it's not very cheap to create. LazyHostSupplier hostSupplier = new LazyHostSupplier(request); VertxHttpRequest vertxRequest = new VertxHttpRequest(ctx, routingContext, headers, uriInfo, request.rawMethod(), hostSupplier, dispatcher.getDispatcher(), vertxResponse, requestContext); vertxRequest.setInputStream(is); try { ResteasyContext.pushContext(SecurityContext.class, new QuarkusResteasySecurityContext(request, routingContext)); ResteasyContext.pushContext(RoutingContext.class, routingContext); dispatcher.service(ctx, request, response, vertxRequest, vertxResponse, true); } catch (Failure e1) { vertxResponse.setStatus(e1.getErrorCode()); if (e1.isLoggable()) { log.error(e1); } } catch (Throwable ex) { routingContext.fail(ex); } boolean suspended = vertxRequest.getAsyncContext().isSuspended(); boolean requestContextActive = requestContext.isActive(); if (!suspended) { try { if (requestContextActive) { requestContext.terminate(); } } finally { try { vertxResponse.finish(); } catch (IOException e) { log.debug("IOException writing JAX-RS response", e); } } } else { //we need the request context to stick around requestContext.deactivate(); } } catch (Throwable t) { try { routingContext.fail(t); } finally { if (requestContext.isActive()) { requestContext.terminate(); } } } }
Example 17
Source File: ProxyVerticle.java From quarantyne with Apache License 2.0 | 4 votes |
private void proxiedRequestHandler(HttpServerRequest frontReq, @Nullable Buffer frontReqBody) { HttpServerResponse frontRep = frontReq.response(); CaseInsensitiveStringKV frontReqHeaders = new CaseInsensitiveStringKV(frontReq.headers().entries()); // inject quarantyne headers, if any HttpRequest qReq = new HttpRequest( HttpRequestMethod.valueOf(frontReq.method().toString().toUpperCase()), frontReqHeaders, RemoteIpAddressesParser.parse(frontReqHeaders, frontReq.remoteAddress().host()), frontReq.path() ); @Nullable final HttpRequestBody qBody = getBody(qReq.getMethod(), frontReqBody, frontReq.getHeader(HttpHeaders.CONTENT_TYPE)); Set<Label> quarantyneLabels = quarantyneClassifier.classify(qReq, qBody); if (configSupplier.get().isBlocked(quarantyneLabels)) { log.info("blocking request {} because we are blocking {}", qReq.getFingerprint(), quarantyneLabels); bouncer.bounce(frontRep); } else { HttpClientRequest backReq = httpClient.request( frontReq.method(), frontReq.uri() ); backReq.headers().setAll(frontReq.headers()); backReq.headers().set(HttpHeaders.HOST, configArgs.getEgress().getHost()); backReq.headers().addAll(quarantyneCheck(quarantyneLabels)); // -------------------------------- backReq.handler(backRep -> { Buffer body = Buffer.buffer(); backRep.handler(body::appendBuffer); backRep.endHandler(h -> { // callback quarantyne with data to record, if needed quarantyneClassifier.record(new HttpResponse(backRep.statusCode()), qReq, qBody); // -------------------------------- frontRep.setStatusCode(backRep.statusCode()); frontRep.headers().setAll(backRep.headers()); frontRep.end(body); }); }); backReq.exceptionHandler(ex -> { log.error("error while querying downstream service", ex); frontRep.setStatusCode(500); frontRep.end("Internal Server Error. This request cannot be satisfied."); }); if (frontReqBody != null) { backReq.end(frontReqBody); } else { backReq.end(); } } }