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

The following examples show how to use io.vertx.ext.web.RoutingContext#getBodyAsString() . These examples are extracted from open source projects. 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
@Override
public Object extract(String name, Parameter parameter, RoutingContext context) {
    BodyParameter bodyParam = (BodyParameter) parameter;
    if ("".equals(context.getBodyAsString())) {
        if (bodyParam.getRequired())
            throw new IllegalArgumentException("Missing required parameter: " + name);
        else
            return null;
    }

    try {
        if(bodyParam.getSchema() instanceof ArrayModel) {
            return context.getBodyAsJsonArray();
        } else {
            return context.getBodyAsJson();
        }
    } catch (DecodeException e) {
        return context.getBodyAsString();  
    }
}
 
Example 2
Source Project: nubes   File: RequestBodyParamInjector.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public Object resolve(RoutingContext context, RequestBody annotation, String paramName, Class<?> resultClass) {
  String body = context.getBodyAsString();
  if (resultClass.equals(String.class)) {
    return body;
  }
  String contentType = ContentTypeProcessor.getContentType(context);
  if (contentType == null) {
    LOG.error("No suitable Content-Type found, request body can't be read");
    return null;
  }
  PayloadMarshaller marshaller = marshallers.get(contentType);
  if (marshaller == null) {
    LOG.error("No marshaller found for Content-Type : " + contentType + ", request body can't be read");
    return null;
  }
  try {
    return marshaller.unmarshallPayload(body, resultClass);
  } catch (Exception e) { //NOSONAR
    // not logged, since it could lead to vulnerabilities (generating huge logs + overhead simply by sending bad payloads)
    context.fail(400);
    return null;
  }
}
 
Example 3
Source Project: besu   File: TimeoutHandler.java    License: Apache License 2.0 5 votes vote down vote up
private static void processHandler(
    final RoutingContext ctx,
    final Optional<TimeoutOptions> globalOptions,
    final Map<String, TimeoutOptions> timeoutOptionsByMethod,
    final boolean decodeJSON) {
  try {
    final String bodyAsString = ctx.getBodyAsString();
    if (bodyAsString != null) {
      final String json = ctx.getBodyAsString().trim();
      Optional<TimeoutOptions> methodTimeoutOptions = Optional.empty();
      if (decodeJSON && !json.isEmpty() && json.charAt(0) == '{') {
        final JsonObject requestBodyJsonObject = new JsonObject(json);
        ctx.put(ContextKey.REQUEST_BODY_AS_JSON_OBJECT.name(), requestBodyJsonObject);
        final String method = requestBodyJsonObject.getString("method");
        methodTimeoutOptions = Optional.ofNullable(timeoutOptionsByMethod.get(method));
      }
      methodTimeoutOptions
          .or(() -> globalOptions)
          .ifPresent(
              timeoutOptions -> {
                long tid =
                    ctx.vertx()
                        .setTimer(
                            timeoutOptions.getTimeoutMillis(),
                            t -> {
                              ctx.fail(timeoutOptions.getErrorCode());
                              ctx.response().close();
                            });
                ctx.addBodyEndHandler(v -> ctx.vertx().cancelTimer(tid));
              });
    }
  } finally {
    ctx.next();
  }
}
 
Example 4
@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 5
@Override
protected Object doResolve(Parameter parameter, RoutingContext routingContext) throws Exception {
    Class<?> parameterType = parameter.getType();
    if (parameterType == String.class) {
        return routingContext.getBodyAsString();
    }
    String xml = routingContext.getBodyAsString();
    return XmlUtils.fromXml(xml, parameterType);
}
 
Example 6
private void addRecommendationToBothColumns(RoutingContext ctx) {
    final String recommendation = ctx.getBodyAsString();
    final JsonArray attributes = new JsonArray()
                                        .add(recommendation)
                                        .add(recommendation);
    insert(ctx, "INSERT INTO recommendation(name, movie_name) VALUES (?,?);", attributes);
}
 
Example 7
Source Project: okapi   File: Auth.java    License: Apache License 2.0 5 votes vote down vote up
public void login(RoutingContext ctx) {
  final String json = ctx.getBodyAsString();
  if (json.length() == 0) {
    logger.debug("test-auth: accept OK in login");
    HttpResponse.responseText(ctx, 202).end("Auth accept in /authn/login");
    return;
  }
  LoginParameters p;
  try {
    p = Json.decodeValue(json, LoginParameters.class);
  } catch (DecodeException ex) {
    HttpResponse.responseText(ctx, 400).end("Error in decoding parameters: " + ex);
    return;
  }

  // Simple password validation: "peter" has a password "peter-password", etc.
  String u = p.getUsername();
  String correctpw = u + "-password";
  if (!p.getPassword().equals(correctpw)) {
    logger.warn("test-auth: Bad passwd for '{}'. Got '{}' expected '{}",
        u, p.getPassword(), correctpw);
    HttpResponse.responseText(ctx, 401).end("Wrong username or password");
    return;
  }
  String tok;
  tok = token(p.getTenant(), p.getUsername());
  logger.info("test-auth: Ok login for {}: {}", u, tok);
  HttpResponse.responseJson(ctx, 200).putHeader(XOkapiHeaders.TOKEN, tok).end(json);
}
 
Example 8
Source Project: vertx-kue   File: KueHttpVerticle.java    License: Apache License 2.0 5 votes vote down vote up
private void apiCreateJob(RoutingContext context) {
  try {
    Job job = new Job(new JsonObject(context.getBodyAsString())); // TODO: support json array create
    job.save().setHandler(resultHandler(context, r -> {
      String result = new JsonObject().put("message", "job created")
        .put("id", r.getId())
        .encodePrettily();
      context.response().setStatusCode(201)
        .putHeader("content-type", "application/json")
        .end(result);
    }));
  } catch (DecodeException e) {
    badRequest(context, e);
  }
}
 
Example 9
private void apiAdd(RoutingContext context) {
  try {
    Product product = new Product(new JsonObject(context.getBodyAsString()));
    service.addProduct(product, resultHandler(context, r -> {
      String result = new JsonObject().put("message", "product_added")
        .put("productId", product.getProductId())
        .encodePrettily();
      context.response().setStatusCode(201)
        .putHeader("content-type", "application/json")
        .end(result);
    }));
  } catch (DecodeException e) {
    badRequest(context, e);
  }
}
 
Example 10
private void apiSave(RoutingContext context) {
  Store store = new Store(new JsonObject(context.getBodyAsString()));
  if (store.getSellerId() == null) {
    badRequest(context, new IllegalStateException("Seller id does not exist"));
  } else {
    JsonObject result = new JsonObject().put("message", "store_saved")
      .put("sellerId", store.getSellerId());
    service.saveStore(store, resultVoidHandler(context, result));
  }
}
 
Example 11
Source Project: quarkus   File: GreetingVertx.java    License: Apache License 2.0 4 votes vote down vote up
@Route(path = "/vertx/hello", methods = POST)
void helloPost(RoutingContext context) {
    String name = context.getBodyAsString();
    context.response().headers().set("Content-Type", "text/plain");
    context.response().setStatusCode(200).end("hello " + name);
}
 
Example 12
Source Project: quarkus   File: GreetingVertx.java    License: Apache License 2.0 4 votes vote down vote up
@Route(path = "/vertx/hello", methods = POST)
void helloPost(RoutingContext context) {
    String name = context.getBodyAsString();
    context.response().headers().set("Content-Type", "text/plain");
    context.response().setStatusCode(200).end("hello " + name);
}
 
Example 13
private void addRecommendation(RoutingContext ctx) {
    final String recommendation = ctx.getBodyAsString();
    final JsonArray attributes = new JsonArray().add(recommendation);
    insert(ctx, "INSERT INTO recommendation(name) VALUES (?);", attributes);
}
 
Example 14
private void addRecommendationToNewColumn(RoutingContext ctx) {
    final String recommendation = ctx.getBodyAsString();
    final JsonArray attributes = new JsonArray().add(recommendation);
    insert(ctx, "INSERT INTO recommendation(movie_name) VALUES (?);", attributes);
}