javax.ws.rs.core.UriBuilder.build()方法的使用及代码示例

x33g5p2x  于2022-01-31 转载在 其他  
字(10.5k)|赞(0)|评价(0)|浏览(193)

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

UriBuilder.build介绍

[英]Build a URI, using the supplied values in order to replace any URI template parameters. Values are converted to String using their toString method and are then encoded to match the rules of the URI component to which they pertain. All '%' characters in the stringified values will be encoded. The state of the builder is unaffected; this method may be called multiple times on the same builder instance.

All instances of the same template parameter will be replaced by the same value that corresponds to the position of the first instance of the template parameter. e.g. the template "{a}/{b}/{a}" with values {"x", "y", "z"} will result in the the URI "x/y/x", not "x/y/z".
[中]使用提供的值构建URI,以替换任何URI模板参数。使用toString方法将值转换为String,然后对其进行编码以匹配它们所属的URI组件的规则。字符串化值中的所有“%”字符都将被编码。建筑商的状态不受影响;在同一个生成器实例上,可以多次调用此方法。
同一模板参数的所有实例都将替换为与模板参数第一个实例的位置对应的相同值。e、 g.模板“{a}/{b}/{a}”的值为{x”,“y”,“z}”将导致URI“x/y/x”,而不是“x/y/z”。

代码示例

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

@Override
public String start() {
  final UriBuilder uriBuilder = UriBuilder.fromUri(authorizationUri);
  for (final Map.Entry<String, String> entry : authorizationProperties.entrySet()) {
    uriBuilder.queryParam(entry.getKey(), entry.getValue());
  }
  return uriBuilder.build().toString();
}

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

@Override
public URI txCommitUri( long id )
{
  return builder( id ).path( "/commit" ).build();
}

代码示例来源:origin: prestodb/presto

private String rewriteUri(UriInfo uriInfo, String uri)
{
  return uriInfo.getAbsolutePathBuilder()
      .replacePath("/v1/proxy")
      .queryParam("uri", uri)
      .queryParam("hmac", hmac.hashString(uri, UTF_8))
      .build()
      .toString();
}

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

private static ThrowingConsumer<HttpServletResponse, IOException> passwordChangeRequired( final String username, final String baseURL )
{
  URI path = UriBuilder.fromUri( baseURL ).path( format( "/user/%s/password", username ) ).build();
  return error( 403,
      map( "errors", singletonList( map(
          "code", Status.Security.Forbidden.code().serialize(),
          "message", "User is required to change their password." ) ), "password_change", path.toString() ) );
}

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

@Path("start")
@POST
public Response post(@DefaultValue("0") @QueryParam("testSources") int testSources, @Context Sse sse) {
  final Process process = new Process(testSources, sse);
  processes.put(process.getId(), process);
  Executors.newSingleThreadExecutor().execute(process);
  final URI processIdUri = UriBuilder.fromResource(DomainResource.class).path("process/{id}").build(process.getId());
  return Response.created(processIdUri).build();
}

代码示例来源:origin: liferay/liferay-portal

private String _constructResourceURL(String uriPrefix) {
  UriBuilder uriBuilder = UriBuilder.fromPath(uriPrefix);
  URI resourceURI = uriBuilder.path(
    uriPrefix.contains("/p/") ? "" : "p"
  ).path(
    "{resource}"
  ).build(
    getValue()
  );
  return resourceURI.toString();
}

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

NettyTestContainer(URI baseUri, DeploymentContext deploymentContext) {
  this.baseUri = UriBuilder.fromUri(baseUri).path(deploymentContext.getContextPath()).build();
  this.deploymentContext = deploymentContext;
}

代码示例来源:origin: Netflix/Priam

/**
 * Creates a new instance with the given parameters
 *
 * @param id the node id
 * @return Response (201) if the instance was created
 */
@POST
public Response createInstance(
    @QueryParam("id") int id,
    @QueryParam("instanceID") String instanceID,
    @QueryParam("hostname") String hostname,
    @QueryParam("ip") String ip,
    @QueryParam("rack") String rack,
    @QueryParam("token") String token) {
  log.info(
      "Creating instance [id={}, instanceId={}, hostname={}, ip={}, rack={}, token={}",
      id,
      instanceID,
      hostname,
      ip,
      rack,
      token);
  PriamInstance instance =
      factory.create(
          config.getAppName(), id, instanceID, hostname, ip, rack, null, token);
  URI uri = UriBuilder.fromPath("/{id}").build(instance.getId());
  return Response.created(uri).build();
}

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

private URI getBaseURI(final URI baseUri) {
  String stagingHostName = AccessController.doPrivileged(PropertiesHelper.getSystemProperty(JERSEY_TEST_HOST));
  if (stagingHostName != null) {
    return UriBuilder.fromUri(baseUri).host(stagingHostName).build();
  }
  return baseUri;
}

代码示例来源:origin: apache/nifi

@POST
@Consumes(MediaType.MULTIPART_FORM_DATA)
@Produces(MediaType.APPLICATION_XML)
    logger.warn("An error occurred while parsing a template.", jaxbe);
    String responseXml = String.format("<errorResponse status=\"%s\" statusText=\"The specified template is not in a valid format.\"/>", Response.Status.BAD_REQUEST.getStatusCode());
    return Response.status(Response.Status.OK).entity(responseXml).type("application/xml").build();
  } catch (IllegalArgumentException iae) {
    logger.warn("Unable to import template.", iae);
    String responseXml = String.format("<errorResponse status=\"%s\" statusText=\"%s\"/>", Response.Status.BAD_REQUEST.getStatusCode(), iae.getMessage());
    return Response.status(Response.Status.OK).entity(responseXml).type("application/xml").build();
  } catch (Exception e) {
    logger.warn("An error occurred while importing a template.", e);
    String responseXml = String.format("<errorResponse status=\"%s\" statusText=\"Unable to import the specified template: %s\"/>",
        Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), e.getMessage());
    return Response.status(Response.Status.OK).entity(responseXml).type("application/xml").build();
    final URI importUri = uriBuilder.build();

代码示例来源:origin: Graylog2/graylog2-server

@PUT
@Timed
@Path("/{inputId}")
@ApiOperation(
    value = "Update input on this node",
    response = InputCreated.class
)
@ApiResponses(value = {
    @ApiResponse(code = 404, message = "No such input on this node."),
    @ApiResponse(code = 400, message = "Missing or invalid input configuration.")
})
@AuditEvent(type = AuditEventTypes.MESSAGE_INPUT_UPDATE)
public Response update(@ApiParam(name = "JSON body", required = true) @Valid @NotNull InputCreateRequest lr,
            @ApiParam(name = "inputId", required = true) @PathParam("inputId") String inputId) throws org.graylog2.database.NotFoundException, NoSuchInputTypeException, ConfigurationException, ValidationException {
  checkPermission(RestPermissions.INPUTS_EDIT, inputId);
  final Input input = inputService.find(inputId);
  final Map<String, Object> mergedInput = input.getFields();
  final MessageInput messageInput = messageInputFactory.create(lr, getCurrentUser().getName(), lr.node());
  messageInput.checkConfiguration();
  mergedInput.putAll(messageInput.asMap());
  final Input newInput = inputService.create(input.getId(), mergedInput);
  inputService.update(newInput);
  final URI inputUri = getUriBuilderToSelf().path(InputsResource.class)
      .path("{inputId}")
      .build(input.getId());
  return Response.created(inputUri).entity(InputCreated.create(input.getId())).build();
}

代码示例来源:origin: Graylog2/graylog2-server

@GET
public Response getIndex(@Context ContainerRequest request, @Context HttpHeaders headers) {
  final URI originalLocation = request.getRequestUri();
  if (originalLocation.getPath().endsWith("/")) {
    return get(request, headers, originalLocation.getPath());
  }
  final URI redirect = UriBuilder.fromPath(originalLocation.getPath() + "/").build();
  return Response.temporaryRedirect(redirect).build();
}

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

requestURI = UriBuilder.fromUri(requestURI)
      .replacePath(
          requestURIPath
              .substring(0, requestURIPath.lastIndexOf('/') + 1))
      .build();
    ? UriBuilder.fromPath(root).path("/application.wadl/") : UriBuilder.fromPath("./application.wadl/");
final URI rootURI = root != null ? UriBuilder.fromPath(root).build() : null;
  final URI schemaURI = extendedPath.clone().path(path).build();
  final String schemaPath = rootURI != null ? requestURI.relativize(schemaURI).toString() : schemaURI.toString();

代码示例来源:origin: opentripplanner/OpenTripPlanner

private URL getGeocoderURL(String geocoderBaseUrl, String address) throws MalformedURLException {
  UriBuilder builder = UriBuilder.fromUri(geocoderBaseUrl);
  builder.queryParam("address", address);
  URI uri = builder.build();
  return new URL(uri.toString());
}

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

@Path("start")
@POST
public Response post(@DefaultValue("0") @QueryParam("testSources") int testSources) {
  final Process process = new Process(testSources);
  processes.put(process.getId(), process);
  Executors.newSingleThreadExecutor().execute(process);
  final URI processIdUri = UriBuilder.fromResource(DomainResource.class).path("process/{id}").build(process.getId());
  return Response.created(processIdUri).build();
}

代码示例来源:origin: liferay/liferay-portal

public String getWebSiteURL() {
  UriBuilder uriBuilder = UriBuilder.fromPath(getHost());
  URI webSiteURI = uriBuilder.path(
    "p"
  ).path(
    "commerce-web-site"
  ).path(
    "{webSiteId}"
  ).build(
    getValue()
  );
  return webSiteURI.toString();
}

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

private ExternalTestContainer(final URI baseUri, final DeploymentContext context) {
  final UriBuilder uriBuilder = UriBuilder.fromUri(baseUri).path(context.getContextPath());
  if (context instanceof ServletDeploymentContext) {
    uriBuilder.path(((ServletDeploymentContext) context).getServletPath());
  }
  this.baseUri = uriBuilder.build();
  if (LOGGER.isLoggable(Level.INFO)) {
    LOGGER.info("Creating ExternalTestContainer configured at the base URI " + this.baseUri);
  }
}

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

/**
   * Gets base {@link URI}.
   *
   * @return base {@link URI}.
   */
  public static URI getBaseURI() {
    return UriBuilder.fromUri("http://localhost/").port(getPort(8080)).build();
  }
}

代码示例来源:origin: prestodb/presto

@GET
  public Response redirectIndexHtml(
      @HeaderParam(X_FORWARDED_PROTO) String proto,
      @Context UriInfo uriInfo)
  {
    if (isNullOrEmpty(proto)) {
      proto = uriInfo.getRequestUri().getScheme();
    }

    return Response.status(MOVED_PERMANENTLY)
        .location(uriInfo.getRequestUriBuilder().scheme(proto).path("/ui/").build())
        .build();
  }
}

代码示例来源:origin: apache/hbase

return Response.status(Response.Status.FORBIDDEN)
  .type(MIMETYPE_TEXT).entity("Forbidden" + CRLF)
  .build();
 URI uri = builder.path(id).build();
 servlet.getMetrics().incrementSucessfulPutRequests(1);
 return Response.created(uri).build();
} catch (Exception e) {
 LOG.error("Exception occured while processing " + uriInfo.getAbsolutePath() + " : ", e);
  return Response.status(Response.Status.NOT_FOUND)
   .type(MIMETYPE_TEXT).entity("Not found" + CRLF)
   .build();
 } else if (e instanceof RuntimeException
   || e instanceof JsonMappingException | e instanceof JsonParseException) {

相关文章