spark.Request类的使用及代码示例

x33g5p2x  于2022-01-28 转载在 其他  
字(12.3k)|赞(0)|评价(0)|浏览(254)

本文整理了Java中spark.Request类的一些代码示例,展示了Request类的具体用法。这些代码示例主要来源于Github/Stackoverflow/Maven等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。Request类的具体详情如下:
包路径:spark.Request
类名称:Request

Request介绍

[英]Provides information about the HTTP request
[中]提供有关HTTP请求的信息

代码示例

代码示例来源:origin: perwendel/spark

@Override
public String body() {
  return delegate.body();
}

代码示例来源:origin: perwendel/spark

@Override
public Map<String, String> params() {
  return delegate.params();
}

代码示例来源:origin: perwendel/spark

/**
 * Gets the query param, or returns default value
 *
 * @param queryParam   the query parameter
 * @param defaultValue the default value
 * @return the value of the provided queryParam, or default if value is null
 * Example: query parameter 'id' from the following request URI: /hello?id=foo
 */
public String queryParamOrDefault(String queryParam, String defaultValue) {
  String value = queryParams(queryParam);
  return value != null ? value : defaultValue;
}

代码示例来源:origin: gocd/gocd

public static RequestContext requestContext(Request req) {
  return new RequestContext(req.scheme(), req.raw().getServerName(), req.port(), req.contextPath());
}

代码示例来源:origin: gocd/gocd

private CaseInsensitiveString getPipelineNameFromRequest(Request request) {
  String pipelineName = request.params("pipeline_name");
  if (StringUtils.isBlank(pipelineName)) {
    pipelineName = request.queryParams("pipeline_name");
  }
  return new CaseInsensitiveString(pipelineName);
}

代码示例来源:origin: gocd/gocd

protected void verifyContentType(Request request, Response response) throws IOException {
  if (!UPDATE_HTTP_METHODS.contains(request.requestMethod().toUpperCase())) {
    return;
  }
  boolean requestHasBody = request.contentLength() >= 1 || request.raw().getInputStream().available() >= 1 || "chunked".equalsIgnoreCase(request.headers("Transfer-Encoding"));
  if (requestHasBody) {
    if (!isJsonContentType(request)) {
      throw haltBecauseJsonContentTypeExpected();
    }
  } else if (request.headers().stream().noneMatch(headerName -> headerName.toLowerCase().equals("x-gocd-confirm"))) {
    throw haltBecauseConfirmHeaderMissing();
  }
}

代码示例来源:origin: bwssytems/ha-bridge

log.debug("HueMulator " + request.requestMethod() + " called on api/* with request <<<" + request.pathInfo() + ">>>, and body <<<" + request.body() + ">>>");
  if(bridgeSettingMaster.getBridgeSecurity().isSecure()) {
    String pathInfo = request.pathInfo();
    if(pathInfo != null && pathInfo.contains(HUE_CONTEXT + "/devices")) {
      User authUser = bridgeSettingMaster.getBridgeSecurity().getAuthenticatedUser(request);
  response.header("Access-Control-Allow-Origin", request.headers("Origin"));
  response.type("application/json");
  response.status(HttpStatus.SC_OK);
  return groupsListHandler(request.params(":userid"),  request.ip());
} , new JsonTransformer());
  response.header("Access-Control-Allow-Origin", request.headers("Origin"));
  return  groupsIdHandler(request.params(":groupid"), request.params(":userid"), request.ip());
} , new JsonTransformer());
  response.header("Access-Control-Allow-Origin", request.headers("Origin"));
  response.header("Access-Control-Allow-Methods", "GET, POST, PUT");
  response.header("Access-Control-Allow-Headers", request.headers("Access-Control-Request-Headers"));
  response.header("Access-Control-Allow-Origin", request.headers("Origin"));
  return addGroup(request.params(":userid"), request.ip(), request.body());
});
  response.header("Access-Control-Allow-Origin", request.headers("Origin"));
  return deleteGroup(request.params(":userid"), request.params(":groupid"), request.ip());

代码示例来源:origin: bwssytems/ha-bridge

response.status(HttpStatus.SC_OK);
  response.header("Access-Control-Allow-Origin", request.headers("Origin"));
  response.header("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE");
  response.header("Access-Control-Allow-Headers", request.headers("Access-Control-Request-Headers"));
});
post(API_CONTEXT, "application/json", (request, response) -> {
  log.debug("Create a Device(s) - request body: " + request.body());
  DeviceDescriptor devices[];
  if(request.body().substring(0,1).equalsIgnoreCase("[") == true) {
    devices = new Gson().fromJson(request.body(), DeviceDescriptor[].class);
    devices = new Gson().fromJson("[" + request.body() + "]", DeviceDescriptor[].class);
  log.debug("Created a Device(s): " + request.body());
  response.header("Access-Control-Allow-Origin", request.headers("Origin"));
  response.header("Access-Control-Allow-Origin", request.headers("Origin"));
  response.header("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE");
  response.header("Access-Control-Allow-Headers", request.headers("Access-Control-Request-Headers"));
});
put (API_CONTEXT + "/:id", "application/json", (request, response) -> {
  log.debug("Edit a Device - request body: " + request.body());
  DeviceDescriptor device = new Gson().fromJson(request.body(), DeviceDescriptor.class);
  if(deviceRepository.findOne(request.params(":id")) == null){
    log.debug("Could not save an edited device, Device Id not found: " + request.params(":id"));
    response.status(HttpStatus.SC_BAD_REQUEST);

代码示例来源:origin: GoogleCloudPlatform/java-docs-samples

/**
 * Creates a controller that maps requests to actions.
 */
public UserController(final UserService userService) {
 Spark.staticFileLocation("/public");
 get("/api/users", (req, res) -> userService.getAllUsers(), json());
 get("/api/users/:id", (req, res) -> userService.getUser(req.params(":id")), json());
 post("/api/users",
   (req, res) -> userService.createUser(req.queryParams("name"), req.queryParams("email")),
   json());
 put("/api/users/:id", (req, res) -> userService.updateUser(
     req.params(":id"),
     req.queryParams("name"),
     req.queryParams("email")
   ), json());
 delete("/api/users/:id", (req, res) -> userService.deleteUser(req.params(":id")), json());
 after((req, res) -> {
  res.type("application/json");
 });
 exception(IllegalArgumentException.class, (error, req, res) -> {
  res.status(400);
  res.body(toJson(new ResponseError(error)));
 });
}

代码示例来源:origin: gocd/gocd

public String bulkDelete(Request req, Response res) throws Exception {
  BulkUpdateUsersOperationResult result = new BulkUpdateUsersOperationResult();
  JsonReader jsonReader = GsonTransformer.getInstance().jsonReaderFrom(req.body());
  List<String> users = jsonReader.readStringArrayIfPresent("users").orElse(Collections.emptyList());
  userService.deleteUsers(users, result);
  if (!result.isSuccessful()) {
    res.status(result.httpCode());
    return writerForTopLevelObject(req, res, outputWriter -> BulkDeletionFailureResultRepresenter.toJSON(outputWriter, result));
  }
  return renderHTTPOperationResult(result, req, res);
}

代码示例来源:origin: gocd/gocd

public byte[] show(Request request, Response response) {
  String pluginId = request.params("plugin_id");
  String hash = request.params("hash");
  response.raw().setHeader("Cache-Control", "max-age=31557600, public");
  response.status(200);
  response.header("Content-Type", image.getContentType());
  this.setEtagHeader(response, image.getHash());
  if (request.requestMethod().equals("head")) {
    return new byte[0];
  } else {

代码示例来源:origin: awslabs/aws-serverless-java-container

public static void defineResources() {
  before((request, response) -> response.type("application/json"));
    Pet newPet = LambdaContainerHandler.getObjectMapper().readValue(req.body(), Pet.class);
    if (newPet.getName() == null || newPet.getBreed() == null) {
      return Response.status(400).entity(new Error("Invalid name or breed")).build();
    dbPet.setId(UUID.randomUUID().toString());
    res.status(200);
    return dbPet;
  }, new JsonTransformer());
    if (req.queryParams("limit") != null) {
      limit = Integer.parseInt(req.queryParams("limit"));
    res.status(200);
    return outputPets;
  }, new JsonTransformer());

代码示例来源:origin: avaire/avaire

@Override
  public void handle(Exception exception, Request request, Response response) {
    Metrics.log.error(request.requestMethod() + " " + request.pathInfo(), exception);

    response.body(ExceptionUtils.getStackTrace(exception));
    response.type("text/plain");
    response.status(500);
  }
}

代码示例来源:origin: gocd/gocd

public String update(Request request, Response response) {
  String fromCookie = request.cookie(COOKIE_NAME);
  final Long userId = currentUserId(request);
  if (!Objects.equals(pipelineSelectionsService.load(fromCookie, userId).etag(), getIfMatch(request))) {
    throw HaltApiResponses.haltBecauseEtagDoesNotMatch(DATA_IS_OUT_OF_DATE);
  }
  Filters filters;
  try {
    filters = Filters.fromJson(request.body());
  } catch (FilterValidationException | JsonParseException e) {
    throw HaltApiResponses.haltBecauseOfReason(e.getMessage());
  }
  Long recordId = pipelineSelectionsService.save(fromCookie, userId, filters);
  if (!apiAuthenticationHelper.securityEnabled()) {
    response.cookie("/go", COOKIE_NAME, String.valueOf(recordId), ONE_YEAR, systemEnvironment.isSessionCookieSecure(), true);
  }
  response.status(OK);
  return format("{ \"contentHash\": \"%s\" }", pipelineSelectionsService.load(fromCookie, userId).etag());
}

代码示例来源:origin: komoot/photon

@Override
  public String handle(Request request, Response response) {
    R photonRequest = null;
    try {
      photonRequest = photonRequestFactory.create(request);
    } catch (BadRequestException e) {
      JSONObject json = new JSONObject();
      json.put("message", e.getMessage());
      halt(e.getHttpStatus(), json.toString());
    }
    PhotonRequestHandler<R> handler = requestHandlerFactory.createHandler(photonRequest);
    List<JSONObject> results = handler.handle(photonRequest);
    JSONObject geoJsonResults = geoJsonConverter.convert(results);
    response.type("application/json; charset=utf-8");
    response.header("Access-Control-Allow-Origin", "*");
    if (request.queryParams("debug") != null)
      return geoJsonResults.toString(4);

    return geoJsonResults.toString();
  }
}

代码示例来源:origin: gocd/gocd

public String pause(Request req, Response res) throws IOException {
  HttpLocalizedOperationResult result = new HttpLocalizedOperationResult();
  JsonReader requestBody = GsonTransformer.getInstance().jsonReaderFrom(req.body());
  String pipelineName = req.params("pipeline_name");
  String pauseCause = requestBody.optString("pause_cause").orElse(null);
  pipelinePauseService.pause(pipelineName, pauseCause, currentUsername(), result);
  return renderHTTPOperationResult(result, req, res);
}

代码示例来源:origin: gocd/gocd

public String showAnalytics(Request request, Response response) {
  try {
    final AnalyticsData analytics = analyticsExtension.getAnalytics(
        request.params(":plugin_id"),
        request.params(":type"),
        request.params(":id"),
        getQueryParams(request));
    response.type("application/json");
    return GSON.toJson(analytics.toMap());
  } catch (Exception e) {
    LOG.error("Encountered error while fetching analytics", e);
    throw halt(500, format("Error generating analytics from plugin - %s", request.params(":plugin_id")));
  }
}

代码示例来源:origin: xjdr/xio

private static Object setupSparkResponse(String name, Request req, Response res) {
 res.type("application/json");
 Optional<String> echoValue = Optional.ofNullable(req.headers("x-echo"));
 Optional<String> optionalMethod = Optional.ofNullable(req.requestMethod());
 String methodValue = "";
 if (optionalMethod.isPresent()) {
  methodValue = optionalMethod.get();
 }
 Optional<String> tagValue = Optional.ofNullable(name);
 res.header("x-echo", echoValue.orElse("none"));
 res.header("x-method", methodValue);
 res.header("x-tag", tagValue.orElse("no tag"));
 Kraken kraken = new Kraken("Release", "the Kraken");
 return new Gson().toJson(kraken);
}

代码示例来源:origin: avaire/avaire

@Override
  public void handle(Request request, Response response) throws Exception {
    Metrics.log.debug(request.requestMethod() + " " + request.pathInfo());

    response.header("Access-Control-Allow-Origin", "*");
    response.type("application/json");
  }
}

代码示例来源:origin: dessalines/torrenttunes-client

public static void allowAllHeaders(Request req, Response res) {
  String origin = req.headers("Origin");
  res.header("Access-Control-Allow-Credentials", "true");
  res.header("Access-Control-Allow-Origin", origin);
  res.header("Content-Encoding", "gzip");
}

相关文章