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

The following examples show how to use io.vertx.ext.web.RoutingContext#getBodyAsJson() . 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
Source Project: xyz-hub   File: SpaceApi.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Update a space.
 */
public void patchSpace(final RoutingContext context) {
  JsonObject input;
  try {
    input = context.getBodyAsJson();
  } catch (DecodeException e) {
    context.fail(new HttpException(BAD_REQUEST, "Invalid JSON string"));
    return;
  }
  String pathId = context.pathParam(Path.SPACE_ID);

  if (input.getString("id") == null) {
    input.put("id", pathId);
  }
  if (!input.getString("id").equals(pathId)) {
    context.fail(
        new HttpException(BAD_REQUEST, "The space ID in the body does not match the ID in the resource path."));
    return;
  }

  ModifySpaceOp modifyOp = new ModifySpaceOp(Collections.singletonList(input.getMap()), IfNotExists.ERROR, IfExists.PATCH, true);

  new ConditionalOperation(context, ApiResponseType.SPACE, modifyOp, true)
      .execute(this::sendResponse, this::sendErrorResponseOnEdit);

}
 
Example 2
private void updateOne(RoutingContext routingContext) {
    String id = routingContext.request().getParam("id");
    try {
        Integer idAsInteger = Integer.valueOf(id);
        Article article = readingList.get(idAsInteger);
        if (article == null) {
            // Not found
            routingContext.response().setStatusCode(404).end();
        } else {
            JsonObject body = routingContext.getBodyAsJson();
            article.setTitle(body.getString("title")).setUrl(body.getString("url"));
            readingList.put(idAsInteger, article);
            routingContext.response()
                .setStatusCode(200)
                .putHeader("content-type", "application/json; charset=utf-8")
                .end(Json.encodePrettily(article));
        }
    } catch (NumberFormatException e) {
        routingContext.response().setStatusCode(400).end();
    }

}
 
Example 3
@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 4
private void update(RoutingContext routingContext) {
  String uuid = routingContext.request().getParam("uuid");
  JsonObject json = routingContext.getBodyAsJson();
  Record record = new Record(json);

  if (!uuid.equals(record.getRegistration())) {
    routingContext.fail(400);
    return;
  }

  discovery.update(record, ar -> {
    if (ar.failed()) {
      routingContext.fail(ar.cause());
    } else {
      routingContext.response().setStatusCode(200)
          .putHeader("Content-Type", "application/json")
          .end(ar.result().toJson().toString());
    }
  });
}
 
Example 5
private void updateOne(RoutingContext routingContext) {
  final String id = routingContext.request().getParam("id");
  JsonObject json = routingContext.getBodyAsJson();
  if (id == null || json == null) {
    routingContext.response().setStatusCode(400).end();
  } else {
    mongo.update(COLLECTION,
        new JsonObject().put("_id", id), // Select a unique document
        // The update syntax: {$set, the json object containing the fields to update}
        new JsonObject()
            .put("$set", json),
        v -> {
          if (v.failed()) {
            routingContext.response().setStatusCode(404).end();
          } else {
            routingContext.response()
                .putHeader("content-type", "application/json; charset=utf-8")
                .end(Json.encodePrettily(new Whisky(id, json.getString("name"), json.getString("origin"))));
          }
        });
  }
}
 
Example 6
@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 7
@Override
protected Object doResolve(Parameter parameter, RoutingContext routingContext) {
    Class<?> parameterType = parameter.getType();

    if (parameterType == RoutingContext.class) {
        return routingContext;
    }
    if (parameterType == HttpServerRequest.class) {
        return routingContext.request();
    }
    if (parameterType == HttpServerResponse.class) {
        return routingContext.response();
    }

    if (parameterType == Session.class) {
        return routingContext.session();
    }

    if (parameterType == MultiMap.class) {
        return resolveParams(routingContext);
    }

    if (parameterType == JsonObject.class) {
        JsonObject jsonObject = routingContext.getBodyAsJson();
        return jsonObject == null ? new JsonObject() : jsonObject;
    }

    return null;
}
 
Example 8
Source Project: xyz-hub   File: SpaceApi.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Create a new space.
 */
public void postSpace(final RoutingContext context) {
  JsonObject input;
  try {
    input = context.getBodyAsJson();
  } catch (DecodeException e) {
    context.fail(new HttpException(BAD_REQUEST, "Invalid JSON string"));
    return;
  }
  ModifySpaceOp modifyOp = new ModifySpaceOp(Collections.singletonList(input.getMap()), IfNotExists.CREATE, IfExists.ERROR, true);

  new ConditionalOperation(context, ApiResponseType.SPACE, modifyOp, false)
      .execute(this::sendResponse, this::sendErrorResponseOnEdit);
}
 
Example 9
/**
 * 发送客服消息
 */
private void sendCustomerServiceMessage(RoutingContext rc) {
    if (refuseNonLanAccess(rc)) return;
    JsonObject params = rc.getBodyAsJson();
    String openId = params.getString("openId");
    String content = params.getString("content");
    int eid = params.getInteger("eid");
    vertx.eventBus().<JsonObject>send(ADDR_ACCOUNT_DB.get(), makeMessage(COMMAND_GET_ACCOUNT_BY_ID, eid), ar -> {
        HttpServerResponse response = rc.response();
        if (ar.succeeded()) {
            JsonObject acc = ar.result().body();
            vertx.executeBlocking(future -> {
                future.complete(null);//TODO 支付宝客服消息的实现
            }, res -> {
                if (res.succeeded()) {
                    response.putHeader("content-type", "application/json;charset=UTF-8").end(res.result().toString());
                } else {
                    log.error("向公众号" + acc.getString(NAME) + "的粉丝" + openId + "发送客服消息时抛出异常", res.cause());
                    response.setStatusCode(500).end(res.cause().getMessage());
                }
            });
        } else {
            log.error("EventBus消息响应错误", ar.cause());
            response.setStatusCode(500).end("EventBus error!");
        }
    });
}
 
Example 10
private void handle(RoutingContext rc) {
    @Nullable JsonObject json = rc.getBodyAsJson();
    if (json == null || json.getDouble("amount") == null) {
        System.out.println("No content or no amount");
        rc.fail(400);
        return;
    }

    double amount = json.getDouble("amount");
    String target = json.getString("currency");
    if (target == null) {
        target = "EUR";
    }
    double rate = getRate(target);
    if (rate == -1) {
        System.out.println("Unknown currency: " + target);
        rc.fail(400);
    }
    
    int i = random.nextInt(10);
    if (i < 5) {

        rc.response().end(new JsonObject()
            .put("amount", convert(amount, rate))
            .put("currency", target).encode()
        );
    } else if (i < 8) {
        // Failure
        rc.fail(500);
    }
    // Timeout, we don't write the response.
}
 
Example 11
private void publish(RoutingContext routingContext) {
  JsonObject json = routingContext.getBodyAsJson();
  Record record = new Record(json);
  discovery.publish(record, ar -> {
    if (ar.failed()) {
      routingContext.fail(ar.cause());
    } else {
      routingContext.response().setStatusCode(201)
          .putHeader("Content-Type", "application/json")
          .end(ar.result().toJson().toString());
    }
  });
}
 
Example 12
private void apiAddCartEvent(RoutingContext context, JsonObject principal) {
  String userId = Optional.ofNullable(principal.getString("userId"))
    .orElse(TEST_USER);
  CartEvent cartEvent = new CartEvent(context.getBodyAsJson());
  if (validateEvent(cartEvent, userId)) {
    shoppingCartService.addCartEvent(cartEvent, resultVoidHandler(context, 201));
  } else {
    context.fail(400);
  }
}
 
Example 13
Source Project: kube_vertx_demo   File: VerticleGateway.java    License: Apache License 2.0 4 votes vote down vote up
private void updateUser(RoutingContext ctx) {
    // update the user properties
    JsonObject update = ctx.getBodyAsJson();
    JsonObject message = updateEntity(ctx, update);
    vertx.eventBus().send("/api/users/:id-put", message, (Handler<AsyncResult<Message<String>>>) responseHandler -> defaultResponse(ctx, responseHandler));
}
 
Example 14
Source Project: kube_vertx_demo   File: VerticleGateway.java    License: Apache License 2.0 4 votes vote down vote up
private void postUser(RoutingContext ctx) {
    JsonObject newUser = ctx.getBodyAsJson();
    vertx.eventBus().send("/api/users-post", newUser, (Handler<AsyncResult<Message<String>>>) responseHandler -> defaultResponse(ctx, responseHandler));
}
 
Example 15
private void apiAddUser(RoutingContext context) {
  Account account = new Account(context.getBodyAsJson());
  accountService.addAccount(account, resultVoidHandler(context, 201));
}
 
Example 16
@Override
public void handle(Endpoint<?> endpoint, Handler<?> handler) {
    RoutingContext routingContext = (RoutingContext) endpoint.get();

    JsonObject bodyAsJson = EMPTY_JSON;
    try {
        // check for an empty body
        if (routingContext.getBody().length() != 0) {
            bodyAsJson = routingContext.getBodyAsJson();
        }
        log.debug("[{}] Request: body = {}", routingContext.get("request-id"), bodyAsJson);
    } catch (DecodeException ex) {
        int code = handleError(ex);
        HttpBridgeError error = new HttpBridgeError(
            code,
            ex.getMessage()
        );
        HttpUtils.sendResponse(routingContext, code,
                BridgeContentType.KAFKA_JSON, error.toJson().toBuffer());
        return;
    }

    switch (this.httpBridgeContext.getOpenApiOperation()) {

        case CREATE_CONSUMER:
            doCreateConsumer(routingContext, bodyAsJson, (Handler<SinkBridgeEndpoint<K, V>>) handler);
            break;

        case SUBSCRIBE:
            doSubscribe(routingContext, bodyAsJson);
            break;

        case ASSIGN:
            doAssign(routingContext, bodyAsJson);
            break;

        case POLL:
            doPoll(routingContext);
            break;

        case DELETE_CONSUMER:
            doDeleteConsumer(routingContext);
            break;

        case COMMIT:
            doCommit(routingContext, bodyAsJson);
            break;

        case SEEK:
            doSeek(routingContext, bodyAsJson);
            break;

        case SEEK_TO_BEGINNING:
        case SEEK_TO_END:
            doSeekTo(routingContext, bodyAsJson, this.httpBridgeContext.getOpenApiOperation());
            break;

        case UNSUBSCRIBE:
            doUnsubscribe(routingContext);
            break;
        case LIST_SUBSCRIPTIONS:
            doListSubscriptions(routingContext);
            break;

        default:
            throw new IllegalArgumentException("Unknown Operation: " + this.httpBridgeContext.getOpenApiOperation());
    }
}
 
Example 17
/**
 * This is commonly used utility
 *
 * @param routingContext This is the connect from REST API
 * @param webClient This is vertx non-blocking rest client used for forwarding
 * @param schemaRegistryRestHost Schema Registry Rest Host
 * @param schemaRegistryRestPort Schema Registry Rest Port
 * @param successMsg Message to response when succeeded
 * @param successCode Status code to response when succeeded
 * @param errorMsg Message to response when failed
 * @param errorCode Status code to response when failed
 */
public static void addOneSchemaCommon(RoutingContext routingContext, WebClient webClient,
                                      String schemaRegistryRestHost, int schemaRegistryRestPort,
                                      String successMsg, int successCode, String errorMsg, int errorCode) {

    JsonObject jsonObj = routingContext.getBodyAsJson();
    JsonObject schemaObj = jsonObj.getJsonObject(ConstantApp.SCHEMA_REGISTRY_KEY_SCHEMA);

    if(!jsonObj.containsKey("id") && !jsonObj.containsKey(ConstantApp.SCHEMA_REGISTRY_KEY_SUBJECT))
        LOG.error(DFAPIMessage.logResponseMessage(9040, "Subject of Schema is missing."));

    // get subject from id (web ui assigned) and assign it to subject
    String subject = jsonObj.containsKey("id")? jsonObj.getString("id"):
            jsonObj.getString(ConstantApp.SCHEMA_REGISTRY_KEY_SUBJECT);

    // Set schema name from subject if it does not has name or empty
    if(!schemaObj.containsKey("name") || schemaObj.getString("name").isEmpty()) {
        schemaObj.put("name", subject);
        jsonObj.put(ConstantApp.SCHEMA_REGISTRY_KEY_SCHEMA, schemaObj);
    }

    String compatibility = jsonObj.containsKey(ConstantApp.SCHEMA_REGISTRY_KEY_COMPATIBILITY) ?
            jsonObj.getString(ConstantApp.SCHEMA_REGISTRY_KEY_COMPATIBILITY) : "NONE";

    webClient.post(schemaRegistryRestPort, schemaRegistryRestHost,
            ConstantApp.SR_REST_URL_SUBJECTS + "/" + subject + ConstantApp.SR_REST_URL_VERSIONS)
            .putHeader(ConstantApp.HTTP_HEADER_CONTENT_TYPE, ConstantApp.AVRO_REGISTRY_CONTENT_TYPE)
            .sendJsonObject( new JsonObject()
                            .put(ConstantApp.SCHEMA_REGISTRY_KEY_SCHEMA, schemaObj.toString()),
                    // Must toString above according SR API spec.
                    ar -> {
                        if (ar.succeeded()) {
                            LOG.info(DFAPIMessage.logResponseMessage(successCode, subject + "-SCHEMA"));
                            // Once successful, we will update schema compatibility
                            webClient.put(schemaRegistryRestPort, schemaRegistryRestHost,
                                    ConstantApp.SR_REST_URL_CONFIG + "/" + subject)
                                    .putHeader(ConstantApp.HTTP_HEADER_CONTENT_TYPE,
                                            ConstantApp.AVRO_REGISTRY_CONTENT_TYPE)
                                    .sendJsonObject(new JsonObject()
                                            .put(ConstantApp.SCHEMA_REGISTRY_KEY_COMPATIBILITY, compatibility),
                                            arc -> {
                                                if (arc.succeeded()) {
                                                    HelpFunc.responseCorsHandleAddOn(routingContext.response())
                                                            .setStatusCode(ConstantApp.STATUS_CODE_OK)
                                                            .end(Json.encodePrettily(jsonObj));
                                                    LOG.info(DFAPIMessage.logResponseMessage(1017,
                                                            successMsg + "-COMPATIBILITY"));
                                                } else {
                                                    // If response is failed, repose df ui and still keep the task
                                                    HelpFunc.responseCorsHandleAddOn(routingContext.response())
                                                            .setStatusCode(ConstantApp.STATUS_CODE_BAD_REQUEST)
                                                            .end(DFAPIMessage.getResponseMessage(errorCode,
                                                                    subject, errorMsg + "-COMPATIBILITY"));
                                                    LOG.info(DFAPIMessage.logResponseMessage(errorCode,
                                                            subject + "-COMPATIBILITY"));
                                                }
                                            }
                                    );
                        } else {
                            // If response is failed, repose df ui and still keep the task
                            HelpFunc.responseCorsHandleAddOn(routingContext.response())
                                    .setStatusCode(ConstantApp.STATUS_CODE_BAD_REQUEST)
                                    .end(DFAPIMessage.getResponseMessage(errorCode, subject,
                                            errorMsg + "-SCHEMA"));
                            LOG.info(DFAPIMessage.logResponseMessage(errorCode, subject  + "-SCHEMA"));
                        }
                    }
            );
}
 
Example 18
private void receiveData(RoutingContext rc) {
    if (!enabled.get()) {
        rc.response().setStatusCode(HttpResponseStatus.FORBIDDEN.code())
                .end("UI server remote listening is currently disabled. Use UIServer.getInstance().enableRemoteListener()");
        return;
    }

    if (statsStorage == null) {
        rc.response().setStatusCode(HttpResponseStatus.INTERNAL_SERVER_ERROR.code())
                .end("UI Server remote listener: no StatsStorage instance is set/available to store results");
        return;
    }

    JsonObject jo = rc.getBodyAsJson();
    Map<String,Object> map = jo.getMap();
    String type = (String) map.get("type");
    String dataClass = (String) map.get("class");
    String data = (String) map.get("data");

    if (type == null || dataClass == null || data == null) {
        log.warn("Received incorrectly formatted data from remote listener (has type = " + (type != null)
                        + ", has data class = " + (dataClass != null) + ", has data = " + (data != null) + ")");
        rc.response().setStatusCode(HttpResponseStatus.BAD_REQUEST.code())
                .end("Received incorrectly formatted data");
        return;
    }

    switch (type.toLowerCase()) {
        case "metadata":
            StorageMetaData meta = getMetaData(dataClass, data);
            if (meta != null) {
                statsStorage.putStorageMetaData(meta);
            }
            break;
        case "staticinfo":
            Persistable staticInfo = getPersistable(dataClass, data);
            if (staticInfo != null) {
                statsStorage.putStaticInfo(staticInfo);
            }
            break;
        case "update":
            Persistable update = getPersistable(dataClass, data);
            if (update != null) {
                statsStorage.putUpdate(update);
            }
            break;
        default:

    }

    rc.response().end();
}
 
Example 19
Source Project: df_data_service   File: DFDataProcessor.java    License: Apache License 2.0 3 votes vote down vote up
/** Add one schema to schema registry
 *
 * @api {post} /schema 3.Add a Schema
 * @apiVersion 0.1.1
 * @apiName addOneSchema
 * @apiGroup Schema
 * @apiPermission none
 * @apiDescription This is how we add a new schema to schema registry service
 * @apiParam   {String}  None        Json String of Schema as message body.
 * @apiSuccess (201) {JsonObject[]} connect     The newly added connect task.
 * @apiError    code        The error code.
 * @apiError    message     The error message.
 * @apiErrorExample {json} Error-Response:
 *     HTTP/1.1 409 Conflict
 *     {
 *       "code" : "409",
 *       "message" : "POST Request exception - Conflict"
 *     }
 */
private void addOneSchema(RoutingContext routingContext) {
    ProcessorTopicSchemaRegistry.forwardAddOneSchema(routingContext, wc_schema,
            kafka_server_host, schema_registry_rest_port);

    JsonObject jsonObj = routingContext.getBodyAsJson();
    // Since Vertx kafka admin still need zookeeper, we now use kafka native admin api until vertx version get updated
    KafkaAdminClient.createTopic(kafka_server_host_and_port,
            jsonObj.getString("id"),
            jsonObj.containsKey(ConstantApp.TOPIC_KEY_PARTITIONS)?
                    jsonObj.getInteger(ConstantApp.TOPIC_KEY_PARTITIONS) : 1,
            jsonObj.containsKey(ConstantApp.TOPIC_KEY_REPLICATION_FACTOR)?
                    jsonObj.getInteger(ConstantApp.TOPIC_KEY_REPLICATION_FACTOR) : 1
    );
}