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

The following examples show how to use io.vertx.ext.web.RoutingContext#pathParam() . 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 findVehicle(RoutingContext routingContext) {
  // Extract the requested vehicle ID
  var vehicleId = routingContext.pathParam("id");
  // Find it in the registry. The Node#withBlockchainData provides
  // the required context with the current, immutable database state.
  var vehicleOpt = node.withBlockchainData(
      (blockchainData) -> service.findVehicle(vehicleId, blockchainData));
  if (vehicleOpt.isPresent()) {
    // Respond with the vehicle details
    var vehicle = vehicleOpt.get();
    routingContext.response()
        .putHeader("Content-Type", "application/octet-stream")
        .end(Buffer.buffer(vehicle.toByteArray()));
  } else {
    // Respond that the vehicle with such ID is not found
    routingContext.response()
        .setStatusCode(HTTP_NOT_FOUND)
        .end();
  }
}
 
Example 3
Source Project: strimzi-kafka-bridge   File: HttpBridge.java    License: Apache License 2.0 6 votes vote down vote up
private void deleteConsumer(RoutingContext routingContext) {
    this.httpBridgeContext.setOpenApiOperation(HttpOpenApiOperations.DELETE_CONSUMER);
    String groupId = routingContext.pathParam("groupid");
    String instanceId = routingContext.pathParam("name");
    ConsumerInstanceId kafkaConsumerInstanceId = new ConsumerInstanceId(groupId, instanceId);

    SinkBridgeEndpoint<byte[], byte[]> deleteSinkEndpoint = this.httpBridgeContext.getHttpSinkEndpoints().get(kafkaConsumerInstanceId);

    if (deleteSinkEndpoint != null) {
        deleteSinkEndpoint.handle(new HttpEndpoint(routingContext));

        this.httpBridgeContext.getHttpSinkEndpoints().remove(kafkaConsumerInstanceId);
        timestampMap.remove(kafkaConsumerInstanceId);
    } else {
        HttpBridgeError error = new HttpBridgeError(
                HttpResponseStatus.NOT_FOUND.code(),
                "The specified consumer instance was not found."
        );
        HttpUtils.sendResponse(routingContext, HttpResponseStatus.NOT_FOUND.code(),
                BridgeContentType.KAFKA_JSON, error.toJson().toBuffer());
    }
}
 
Example 4
Source Project: strimzi-kafka-bridge   File: HttpBridge.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Process an HTTP request related to the consumer
 * 
 * @param routingContext RoutingContext instance
 */
private void processConsumer(RoutingContext routingContext) {
    String groupId = routingContext.pathParam("groupid");
    String instanceId = routingContext.pathParam("name");
    ConsumerInstanceId kafkaConsumerInstanceId = new ConsumerInstanceId(groupId, instanceId);

    SinkBridgeEndpoint<byte[], byte[]> sinkEndpoint = this.httpBridgeContext.getHttpSinkEndpoints().get(kafkaConsumerInstanceId);

    if (sinkEndpoint != null) {
        timestampMap.replace(kafkaConsumerInstanceId, System.currentTimeMillis());
        sinkEndpoint.handle(new HttpEndpoint(routingContext));
    } else {
        HttpBridgeError error = new HttpBridgeError(
                HttpResponseStatus.NOT_FOUND.code(),
                "The specified consumer instance was not found."
        );
        HttpUtils.sendResponse(routingContext, HttpResponseStatus.NOT_FOUND.code(),
                BridgeContentType.KAFKA_JSON, error.toJson().toBuffer());
    }
}
 
Example 5
Source Project: xyz-hub   File: FeatureTask.java    License: Apache License 2.0 5 votes vote down vote up
private FeatureTask(T event, RoutingContext context, ApiResponseType responseType, boolean skipCache) {
  super(event, context, responseType, skipCache);
  event.setStreamId(getMarker().getName());

  if (context.pathParam(ApiParam.Path.SPACE_ID) != null) {
    event.setSpace(context.pathParam(ApiParam.Path.SPACE_ID));
  }
}
 
Example 6
private void dataHandler(final RoutingContext ctx, final UploadHandler uploadHandler) {

        if (!(ctx.user() instanceof Device)) {
            LOG.warn("Not a device");
            return;
        }

        final Device gatewayDevice = (Device) ctx.user();

        final String deviceTenant = gatewayDevice.getTenantId();
        final String requestTenant = ctx.pathParam(SIGFOX_PARAM_TENANT);

        final String deviceId = ctx.queryParams().get(SIGFOX_PARAM_DEVICE_ID);
        final String strData = ctx.queryParams().get(SIGFOX_PARAM_DATA);
        final Buffer data = decodeData(strData);

        LOG.debug("{} handler - deviceTenant: {}, requestTenant: {}, deviceId: {}, data: {}",
                ctx.request().method(), deviceTenant, requestTenant, deviceId, strData);

        if ( requestTenant == null ) {
            ctx.fail(new ClientErrorException(HttpURLConnection.HTTP_BAD_REQUEST,
                    "missing the tenant information in the request URL"));
            return;
        }

        if (!requestTenant.equals(deviceTenant)) {
            ctx.fail(new ClientErrorException(HttpURLConnection.HTTP_BAD_REQUEST,
                    "tenant information mismatch"));
            return;
        }

        final String contentType = (data != null) ? CONTENT_TYPE_OCTET_STREAM
                : EventConstants.CONTENT_TYPE_EMPTY_NOTIFICATION;

        uploadHandler.upload(ctx, deviceTenant, deviceId, data, contentType);
    }
 
Example 7
protected ModelType getTypeFromContext(RoutingContext routingContext) {
    String modelType = routingContext.pathParam(MODEL_TYPE);
    return ModelType.valueOf(modelType.toUpperCase());
}
 
Example 8
Source Project: konduit-serving   File: RPmmlHandler.java    License: Apache License 2.0 4 votes vote down vote up
@Override
public Object[] getExtraArgs(RoutingContext req) {
    String param = req.pathParam(CONVERTER_TYPE);
    return new Object[]{getTmpFileWithContext(req), param};
}
 
Example 9
private void deleteOne(RoutingContext rc) {
    String id = rc.pathParam("id");
    connect()
        .compose(connection -> delete(connection, id))
        .setHandler(noContent(rc));
}
 
Example 10
private void getOne(RoutingContext rc) {
    String id = rc.pathParam("id");
    connect()
        .compose(connection -> queryOne(connection, id))
        .setHandler(ok(rc));
}
 
Example 11
public void doCreateConsumer(RoutingContext routingContext, JsonObject bodyAsJson, Handler<SinkBridgeEndpoint<K, V>> handler) {
    // get the consumer group-id
    this.groupId = routingContext.pathParam("groupid");

    // if no name, a random one is assigned
    this.name = bodyAsJson.getString("name", bridgeConfig.getBridgeID() == null
            ? "kafka-bridge-consumer-" + UUID.randomUUID()
            : bridgeConfig.getBridgeID() + "-" + UUID.randomUUID());

    this.consumerInstanceId = new ConsumerInstanceId(this.groupId, this.name);

    if (this.httpBridgeContext.getHttpSinkEndpoints().containsKey(this.consumerInstanceId)) {
        HttpBridgeError error = new HttpBridgeError(
                HttpResponseStatus.CONFLICT.code(),
                "A consumer instance with the specified name already exists in the Kafka Bridge."
        );
        HttpUtils.sendResponse(routingContext, HttpResponseStatus.CONFLICT.code(),
                BridgeContentType.KAFKA_JSON, error.toJson().toBuffer());
        return;
    }

    // construct base URI for consumer
    String requestUri = this.buildRequestUri(routingContext);
    if (!routingContext.request().path().endsWith("/")) {
        requestUri += "/";
    }
    String consumerBaseUri = requestUri + "instances/" + this.name;

    // get supported consumer configuration parameters
    Properties config = new Properties();
    addConfigParameter(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG,
        bodyAsJson.getString(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, null), config);
    // OpenAPI validation handles boolean and integer, quoted or not as string, in the same way
    // instead of raising a validation error due to this: https://github.com/vert-x3/vertx-web/issues/1375
    Object enableAutoCommit = bodyAsJson.getValue(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG);
    addConfigParameter(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG, 
        enableAutoCommit != null ? String.valueOf(enableAutoCommit) : null, config);
    Object fetchMinBytes = bodyAsJson.getValue(ConsumerConfig.FETCH_MIN_BYTES_CONFIG);
    addConfigParameter(ConsumerConfig.FETCH_MIN_BYTES_CONFIG, 
        fetchMinBytes != null ? String.valueOf(fetchMinBytes) : null, config);
    Object requestTimeoutMs = bodyAsJson.getValue("consumer." + ConsumerConfig.REQUEST_TIMEOUT_MS_CONFIG);
    addConfigParameter(ConsumerConfig.REQUEST_TIMEOUT_MS_CONFIG,
        requestTimeoutMs != null ? String.valueOf(requestTimeoutMs) : null, config);
    addConfigParameter(ConsumerConfig.CLIENT_ID_CONFIG, this.name, config);

    // create the consumer
    this.initConsumer(false, config);

    handler.handle(this);

    log.info("Created consumer {} in group {}", this.name, this.groupId);
    // send consumer instance id(name) and base URI as response
    JsonObject body = new JsonObject()
            .put("instance_id", this.name)
            .put("base_uri", consumerBaseUri);
    HttpUtils.sendResponse(routingContext, HttpResponseStatus.OK.code(),
            BridgeContentType.KAFKA_JSON, body.toBuffer());
}