Java Code Examples for io.vertx.ext.web.RoutingContext#getBody()

The following examples show how to use io.vertx.ext.web.RoutingContext#getBody() . 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: KerasDl4jHandler.java    From konduit-serving with Apache License 2.0 6 votes vote down vote up
protected File getTmpFileWithContext(RoutingContext req) {
    File tmpFile = new File(UUID.randomUUID().toString());
    Buffer buff = req.getBody();
    tmpFile.deleteOnExit();
    try {
        ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(buff.getBytes());
        FileOutputStream fileOutputStream = new FileOutputStream(tmpFile);
        IOUtils.copy(byteArrayInputStream, fileOutputStream);
        fileOutputStream.flush();
        fileOutputStream.close();
    } catch (IOException e) {
        tmpFile.delete();
        req.response().setStatusCode(HttpStatus.SC_INTERNAL_SERVER_ERROR);
        req.response().setStatusMessage(e.getMessage());
        return null;
    }

    return tmpFile;
}
 
Example 2
Source File: TensorflowSameDiffHandler.java    From konduit-serving with Apache License 2.0 6 votes vote down vote up
protected File getTmpFileWithContext(RoutingContext req) {
    File tmpFile = new File(UUID.randomUUID().toString());
    Buffer buff = req.getBody();
    tmpFile.deleteOnExit();
    try {
        ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(buff.getBytes());
        FileOutputStream fileOutputStream = new FileOutputStream(tmpFile);
        IOUtils.copy(byteArrayInputStream, fileOutputStream);
        fileOutputStream.flush();
        fileOutputStream.close();
    } catch (IOException e) {
        tmpFile.delete();
        req.response().setStatusCode(HttpStatus.SC_INTERNAL_SERVER_ERROR);
        req.response().setStatusMessage(e.getMessage());
        return null;
    }

    return tmpFile;
}
 
Example 3
Source File: BasePmmlHandler.java    From konduit-serving with Apache License 2.0 6 votes vote down vote up
protected File getTmpFileWithContext(RoutingContext req) {
    File tmpFile = new File(UUID.randomUUID().toString());
    Buffer buff = req.getBody();
    tmpFile.deleteOnExit();
    try {
        ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(buff.getBytes());
        FileOutputStream fileOutputStream = new FileOutputStream(tmpFile);
        IOUtils.copy(byteArrayInputStream, fileOutputStream);
        fileOutputStream.flush();
        fileOutputStream.close();
    } catch (IOException e) {
        tmpFile.delete();
        req.response().setStatusCode(HttpStatus.SC_INTERNAL_SERVER_ERROR);
        req.response().setStatusMessage(e.getMessage());
        return null;
    }

    return tmpFile;
}
 
Example 4
Source File: VtrackHandler.java    From prebid-server-java with Apache License 2.0 6 votes vote down vote up
private List<PutObject> vtrackPuts(RoutingContext context) {
    final Buffer body = context.getBody();
    if (body == null || body.length() == 0) {
        throw new IllegalArgumentException("Incoming request has no body");
    }

    final BidCacheRequest bidCacheRequest;
    try {
        bidCacheRequest = mapper.decodeValue(body, BidCacheRequest.class);
    } catch (DecodeException e) {
        throw new IllegalArgumentException("Failed to parse request body", e);
    }

    final List<PutObject> putObjects = ListUtils.emptyIfNull(bidCacheRequest.getPuts());
    for (PutObject putObject : putObjects) {
        if (StringUtils.isEmpty(putObject.getBidid())) {
            throw new IllegalArgumentException("'bidid' is required field and can't be empty");
        }
        if (StringUtils.isEmpty(putObject.getBidder())) {
            throw new IllegalArgumentException("'bidder' is required field and can't be empty");
        }
    }
    return putObjects;
}
 
Example 5
Source File: SettingsCacheNotificationHandler.java    From prebid-server-java with Apache License 2.0 6 votes vote down vote up
/**
 * Propagates updating settings cache
 */
private void doSave(RoutingContext context) {
    final Buffer body = context.getBody();
    if (body == null) {
        HttpUtil.respondWith(context, HttpResponseStatus.BAD_REQUEST, "Missing update data.");
        return;
    }

    final UpdateSettingsCacheRequest request;
    try {
        request = mapper.decodeValue(body, UpdateSettingsCacheRequest.class);
    } catch (DecodeException e) {
        HttpUtil.respondWith(context, HttpResponseStatus.BAD_REQUEST, "Invalid update.");
        return;
    }

    cacheNotificationListener.save(request.getRequests(), request.getImps());
    HttpUtil.respondWith(context, HttpResponseStatus.OK, null);
}
 
Example 6
Source File: SettingsCacheNotificationHandler.java    From prebid-server-java with Apache License 2.0 6 votes vote down vote up
/**
 * Propagates invalidating settings cache
 */
private void doInvalidate(RoutingContext context) {
    final Buffer body = context.getBody();
    if (body == null) {
        HttpUtil.respondWith(context, HttpResponseStatus.BAD_REQUEST, "Missing invalidation data.");
        return;
    }

    final InvalidateSettingsCacheRequest request;
    try {
        request = mapper.decodeValue(body, InvalidateSettingsCacheRequest.class);
    } catch (DecodeException e) {
        HttpUtil.respondWith(context, HttpResponseStatus.BAD_REQUEST, "Invalid invalidation.");
        return;
    }

    cacheNotificationListener.invalidate(request.getRequests(), request.getImps());
    HttpUtil.respondWith(context, HttpResponseStatus.OK, null);
}
 
Example 7
Source File: GraphQLHandlerImpl.java    From vertx-web with Apache License 2.0 6 votes vote down vote up
@Override
public void handle(RoutingContext rc) {
  HttpMethod method = rc.request().method();
  if (method == GET) {
    handleGet(rc);
  } else if (method == POST) {
    Buffer body = rc.getBody();
    if (body == null) {
      rc.request().bodyHandler(buffer -> handlePost(rc, buffer));
    } else {
      handlePost(rc, body);
    }
  } else {
    rc.fail(405);
  }
}
 
Example 8
Source File: AuctionRequestFactory.java    From prebid-server-java with Apache License 2.0 6 votes vote down vote up
/**
 * Parses request body to {@link BidRequest}.
 * <p>
 * Throws {@link InvalidRequestException} if body is empty, exceeds max request size or couldn't be deserialized.
 */
private BidRequest parseRequest(RoutingContext context) {
    final Buffer body = context.getBody();
    if (body == null) {
        throw new InvalidRequestException("Incoming request has no body");
    }

    if (body.length() > maxRequestSize) {
        throw new InvalidRequestException(
                String.format("Request size exceeded max size of %d bytes.", maxRequestSize));
    }

    try {
        return mapper.decodeValue(body, BidRequest.class);
    } catch (DecodeException e) {
        throw new InvalidRequestException(String.format("Error decoding bidRequest: %s", e.getMessage()));
    }
}
 
Example 9
Source File: VideoRequestFactory.java    From prebid-server-java with Apache License 2.0 6 votes vote down vote up
/**
 * Parses request body to {@link BidRequestVideo}.
 * <p>
 * Throws {@link InvalidRequestException} if body is empty, exceeds max request size or couldn't be deserialized.
 */
private BidRequestVideo parseRequest(RoutingContext context) {
    final Buffer body = context.getBody();
    if (body == null) {
        throw new InvalidRequestException("Incoming request has no body");
    }

    if (body.length() > maxRequestSize) {
        throw new InvalidRequestException(
                String.format("Request size exceeded max size of %d bytes.", maxRequestSize));
    }

    try {
        final BidRequestVideo bidRequestVideo = mapper.decodeValue(body, BidRequestVideo.class);
        return insertDeviceUa(context, bidRequestVideo);
    } catch (DecodeException e) {
        throw new InvalidRequestException(e.getMessage());
    }
}
 
Example 10
Source File: JsonBasedLoraProvider.java    From hono with Eclipse Public License 2.0 6 votes vote down vote up
@Override
public LoraMessage getMessage(final RoutingContext ctx) {
    Objects.requireNonNull(ctx);
    try {
        final Buffer requestBody = ctx.getBody();
        final JsonObject message = requestBody.toJsonObject();
        final LoraMessageType type = getMessageType(message);
        switch (type) {
        case UPLINK:
            return createUplinkMessage(ctx.request(), message);
        default:
            throw new LoraProviderMalformedPayloadException(String.format("unsupported message type [%s]", type));
        }
    } catch (final RuntimeException e) {
        // catch generic exception in order to also cover any (runtime) exceptions
        // thrown by overridden methods
        throw new LoraProviderMalformedPayloadException("failed to decode request body", e);
    }
}
 
Example 11
Source File: XhrTransport.java    From vertx-web with Apache License 2.0 5 votes vote down vote up
private void handleSend(RoutingContext rc, SockJSSession session) {
  Buffer body = rc.getBody();
  if (body != null) {
    handleSendMessage(rc, session, body);
  } else if (rc.request().isEnded()) {
    log.error("Request ended before SockJS handler could read the body. Do you have an asynchronous request "
        + "handler before the SockJS handler? If so, add a BodyHandler before the SockJS handler "
        + "(see the docs).");
    rc.fail(500);
  } else {
    rc.request().bodyHandler(buff -> handleSendMessage(rc, session, buff));
  }
}
 
Example 12
Source File: PassThroughHandler.java    From ethsigner with Apache License 2.0 5 votes vote down vote up
@Override
public void handle(final RoutingContext context) {
  final HttpServerRequest httpServerRequest = context.request();

  final HttpClientRequest proxyRequest =
      ethNodeClient.request(
          httpServerRequest.method(),
          downstreamPathCalculator.calculateDownstreamPath(httpServerRequest.uri()),
          response -> transmitter.handleResponse(context, response));

  final Buffer body = context.getBody();
  transmitter.sendRequest(proxyRequest, body, context);
  logRequest(httpServerRequest, body.toString());
}
 
Example 13
Source File: APIGatewayVerticle.java    From vertx-blueprint-microservice with Apache License 2.0 5 votes vote down vote up
/**
 * Dispatch the request to the downstream REST layers.
 *
 * @param context routing context instance
 * @param path    relative path
 * @param client  relevant HTTP client
 */
private void doDispatch(RoutingContext context, String path, HttpClient client, Future<Object> cbFuture) {
  HttpClientRequest toReq = client
    .request(context.request().method(), path, response -> {
      response.bodyHandler(body -> {
        if (response.statusCode() >= 500) { // api endpoint server error, circuit breaker should fail
          cbFuture.fail(response.statusCode() + ": " + body.toString());
        } else {
          HttpServerResponse toRsp = context.response()
            .setStatusCode(response.statusCode());
          response.headers().forEach(header -> {
            toRsp.putHeader(header.getKey(), header.getValue());
          });
          // send response
          toRsp.end(body);
          cbFuture.complete();
        }
        ServiceDiscovery.releaseServiceObject(discovery, client);
      });
    });
  // set headers
  context.request().headers().forEach(header -> {
    toReq.putHeader(header.getKey(), header.getValue());
  });
  if (context.user() != null) {
    toReq.putHeader("user-principal", context.user().principal().encode());
  }
  // send request
  if (context.getBody() == null) {
    toReq.end();
  } else {
    toReq.end(context.getBody());
  }
}
 
Example 14
Source File: AbstractHttpEndpoint.java    From hono with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Check the Content-Type of the request to be 'application/json' and extract the payload if this check was
 * successful.
 * <p>
 * The payload is parsed to ensure it is valid JSON and is put to the RoutingContext ctx with the key
 * {@link #KEY_REQUEST_BODY}.
 *
 * @param ctx The routing context to retrieve the JSON request body from.
 * @param payloadExtractor The extractor of the payload from the context.
 */
protected final void extractRequiredJson(final RoutingContext ctx, final Function<RoutingContext, Object> payloadExtractor) {

    Objects.requireNonNull(payloadExtractor);

    final MIMEHeader contentType = ctx.parsedHeaders().contentType();
    if (contentType == null) {
        ctx.fail(new ClientErrorException(HttpURLConnection.HTTP_BAD_REQUEST, "Missing Content-Type header"));
    } else if (!HttpUtils.CONTENT_TYPE_JSON.equalsIgnoreCase(contentType.value())) {
        ctx.fail(new ClientErrorException(HttpURLConnection.HTTP_BAD_REQUEST, "Unsupported Content-Type"));
    } else {
        try {
            if (ctx.getBody() != null) {
                final var payload = payloadExtractor.apply(ctx);
                if (payload != null) {
                    ctx.put(KEY_REQUEST_BODY, payload);
                    ctx.next();
                } else {
                    ctx.fail(new ClientErrorException(HttpURLConnection.HTTP_BAD_REQUEST, "Null body"));
                }
            } else {
                ctx.fail(new ClientErrorException(HttpURLConnection.HTTP_BAD_REQUEST, "Empty body"));
            }
        } catch (final DecodeException e) {
            ctx.fail(new ClientErrorException(HttpURLConnection.HTTP_BAD_REQUEST, "Invalid JSON", e));
        }
    }

}
 
Example 15
Source File: SmallRyeGraphQLExecutionHandler.java    From quarkus with Apache License 2.0 5 votes vote down vote up
private void handlePost(HttpServerResponse response, RoutingContext ctx) {
    if (ctx.getBody() != null) {
        byte[] bytes = ctx.getBody().getBytes();
        String postResponse = doRequest(bytes);
        response.setStatusCode(200).setStatusMessage(OK).end(Buffer.buffer(postResponse));
    } else {
        response.setStatusCode(204).end();
    }
}
 
Example 16
Source File: PreBidRequestContextFactory.java    From prebid-server-java with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a new instances of {@link PreBidRequestContext} wrapped into {@link Future} which
 * can be be eventually completed with success or error result.
 */
public Future<PreBidRequestContext> fromRequest(RoutingContext context) {
    final Buffer body = context.getBody();

    if (body == null) {
        return Future.failedFuture(new PreBidException("Incoming request has no body"));
    }

    final PreBidRequest preBidRequest;
    try {
        preBidRequest = mapper.decodeValue(body, PreBidRequest.class);
    } catch (DecodeException e) {
        return Future.failedFuture(new PreBidException(e.getMessage(), e.getCause()));
    }

    final List<AdUnit> adUnits = preBidRequest.getAdUnits();
    if (adUnits == null || adUnits.isEmpty()) {
        return Future.failedFuture(new PreBidException("No ad units specified"));
    }

    final PreBidRequest adjustedRequest = adjustRequestTimeout(preBidRequest);
    final Timeout timeout = timeout(adjustedRequest);

    return extractBidders(adjustedRequest, timeout)
            .map(bidders -> PreBidRequestContext.builder().adapterRequests(bidders))
            .map(builder ->
                    populatePreBidRequestContextBuilder(context, adjustedRequest, context.request(), builder))
            .map(builder -> builder.timeout(timeout))
            .map(PreBidRequestContext.PreBidRequestContextBuilder::build);
}
 
Example 17
Source File: JsonBodyParameterResolver.java    From festival with Apache License 2.0 5 votes vote down vote up
@Override
protected Object doResolve(Parameter parameter, RoutingContext routingContext) {
    Class<?> parameterType = parameter.getType();
    if (parameterType == JsonObject.class) {
        return routingContext.getBodyAsJson();
    }
    if (parameterType == JsonArray.class) {
        return routingContext.getBodyAsJsonArray();
    }
    if (parameterType == String.class) {
        return routingContext.getBodyAsString();
    }
    Buffer buffer = routingContext.getBody();
    return Json.decodeValue(buffer, parameterType);
}
 
Example 18
Source File: VertxServerRequestToHttpServletRequest.java    From servicecomb-java-chassis with Apache License 2.0 4 votes vote down vote up
public VertxServerRequestToHttpServletRequest(RoutingContext context) {
  this.context = context;
  this.vertxRequest = context.request();
  this.socketAddress = this.vertxRequest.remoteAddress();
  super.setBodyBuffer(context.getBody());
}
 
Example 19
Source File: AbstractVertxBasedHttpProtocolAdapter.java    From hono with Eclipse Public License 2.0 4 votes vote down vote up
/**
 * Uploads a command response message to Hono.
 *
 * @param ctx The routing context of the HTTP request.
 * @param tenant The tenant of the device from which the command response was received.
 * @param deviceId The device from which the command response was received.
 * @param commandRequestId The id of the command that the response has been sent in reply to.
 * @param responseStatus The HTTP status code that the device has provided in its request to indicate
 *                       the outcome of processing the command (may be {@code null}).
 * @throws NullPointerException if ctx, tenant or deviceId are {@code null}.
 */
public final void uploadCommandResponseMessage(
        final RoutingContext ctx,
        final String tenant,
        final String deviceId,
        final String commandRequestId,
        final Integer responseStatus) {

    Objects.requireNonNull(ctx);
    Objects.requireNonNull(tenant);
    Objects.requireNonNull(deviceId);

    final Buffer payload = ctx.getBody();
    final String contentType = HttpUtils.getContentType(ctx);

    log.debug("processing response to command [tenantId: {}, deviceId: {}, cmd-req-id: {}, status code: {}]",
            tenant, deviceId, commandRequestId, responseStatus);

    final Device authenticatedDevice = getAuthenticatedDevice(ctx);
    final Span currentSpan = TracingHelper
            .buildChildSpan(tracer, TracingHandler.serverSpanContext(ctx),
                    "upload Command response", getTypeName())
            .withTag(Tags.SPAN_KIND.getKey(), Tags.SPAN_KIND_CLIENT)
            .withTag(TracingHelper.TAG_TENANT_ID, tenant)
            .withTag(TracingHelper.TAG_DEVICE_ID, deviceId)
            .withTag(Constants.HEADER_COMMAND_RESPONSE_STATUS, responseStatus)
            .withTag(Constants.HEADER_COMMAND_REQUEST_ID, commandRequestId)
            .withTag(TracingHelper.TAG_AUTHENTICATED.getKey(), authenticatedDevice != null)
            .start();

    final CommandResponse cmdResponseOrNull = CommandResponse.from(commandRequestId, tenant, deviceId, payload,
            contentType, responseStatus);
    final Future<TenantObject> tenantTracker = getTenantConfiguration(tenant, currentSpan.context());
    final Future<CommandResponse> commandResponseTracker = cmdResponseOrNull != null
            ? Future.succeededFuture(cmdResponseOrNull)
            : Future.failedFuture(new ClientErrorException(HttpURLConnection.HTTP_BAD_REQUEST,
                    String.format("command-request-id [%s] or status code [%s] is missing/invalid",
                            commandRequestId, responseStatus)));

    final int payloadSize = Optional.ofNullable(payload).map(Buffer::length).orElse(0);
    CompositeFuture.all(tenantTracker, commandResponseTracker)
            .compose(commandResponse -> {
                final Future<JsonObject> deviceRegistrationTracker = getRegistrationAssertion(
                        tenant,
                        deviceId,
                        authenticatedDevice,
                        currentSpan.context());
                final Future<Void> tenantValidationTracker = CompositeFuture
                        .all(isAdapterEnabled(tenantTracker.result()),
                                checkMessageLimit(tenantTracker.result(), payloadSize, currentSpan.context()))
                        .map(ok -> null);

                return CompositeFuture.all(tenantValidationTracker, deviceRegistrationTracker)
                        .compose(ok -> sendCommandResponse(tenant, commandResponseTracker.result(),
                                currentSpan.context()))
                        .map(delivery -> {
                            log.trace("delivered command response [command-request-id: {}] to application",
                                    commandRequestId);
                            currentSpan.log("delivered command response to application");
                            currentSpan.finish();
                            metrics.reportCommand(
                                    Direction.RESPONSE,
                                    tenant,
                                    tenantTracker.result(),
                                    ProcessingOutcome.FORWARDED,
                                    payloadSize,
                                    getMicrometerSample(ctx));
                            ctx.response().setStatusCode(HttpURLConnection.HTTP_ACCEPTED);
                            ctx.response().end();
                            return delivery;
                        });
            }).otherwise(t -> {
                log.debug("could not send command response [command-request-id: {}] to application",
                        commandRequestId, t);
                TracingHelper.logError(currentSpan, t);
                currentSpan.finish();
                metrics.reportCommand(
                        Direction.RESPONSE,
                        tenant,
                        tenantTracker.result(),
                        ProcessingOutcome.from(t),
                        payloadSize,
                        getMicrometerSample(ctx));
                ctx.fail(t);
                return null;
            });
}
 
Example 20
Source File: UndertowDeploymentRecorder.java    From quarkus with Apache License 2.0 4 votes vote down vote up
public Handler<RoutingContext> startUndertow(ShutdownContext shutdown, ExecutorService executorService,
        DeploymentManager manager, List<HandlerWrapper> wrappers, HttpConfiguration httpConfiguration,
        ServletRuntimeConfig servletRuntimeConfig) throws Exception {

    shutdown.addShutdownTask(new Runnable() {
        @Override
        public void run() {
            try {
                manager.stop();
            } catch (ServletException e) {
                log.error("Failed to stop deployment", e);
            }
            manager.undeploy();
        }
    });
    HttpHandler main = manager.getDeployment().getHandler();
    for (HandlerWrapper i : wrappers) {
        main = i.wrap(main);
    }
    if (!manager.getDeployment().getDeploymentInfo().getContextPath().equals("/")) {
        PathHandler pathHandler = new PathHandler()
                .addPrefixPath(manager.getDeployment().getDeploymentInfo().getContextPath(), main);
        main = pathHandler;
    }
    currentRoot = main;

    DefaultExchangeHandler defaultHandler = new DefaultExchangeHandler(ROOT_HANDLER);

    UndertowBufferAllocator allocator = new UndertowBufferAllocator(
            servletRuntimeConfig.directBuffers.orElse(DEFAULT_DIRECT_BUFFERS), (int) servletRuntimeConfig.bufferSize
                    .orElse(new MemorySize(BigInteger.valueOf(DEFAULT_BUFFER_SIZE))).asLongValue());
    return new Handler<RoutingContext>() {
        @Override
        public void handle(RoutingContext event) {
            event.request().pause();
            //we handle auth failure directly
            event.remove(QuarkusHttpUser.AUTH_FAILURE_HANDLER);
            VertxHttpExchange exchange = new VertxHttpExchange(event.request(), allocator, executorService, event,
                    event.getBody());
            Optional<MemorySize> maxBodySize = httpConfiguration.limits.maxBodySize;
            if (maxBodySize.isPresent()) {
                exchange.setMaxEntitySize(maxBodySize.get().asLongValue());
            }
            Duration readTimeout = httpConfiguration.readTimeout;
            exchange.setReadTimeout(readTimeout.toMillis());
            //we eagerly dispatch to the exector, as Undertow needs to be blocking anyway
            //its actually possible to be on a different IO thread at this point which confuses Undertow
            //see https://github.com/quarkusio/quarkus/issues/7782
            if (BlockingOperationControl.isBlockingAllowed()) {
                defaultHandler.handle(exchange);
            } else {
                executorService.submit(new Runnable() {
                    @Override
                    public void run() {
                        defaultHandler.handle(exchange);
                    }
                });
            }
        }
    };
}