javax.ws.rs.core.UriBuilder类的使用及代码示例

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

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

UriBuilder介绍

[英]URI template aware utility class for building URIs from their components. See javax.ws.rs.Path#value for an explanation of URI templates.

Builder methods perform contextual encoding of characters not permitted in the corresponding URI component following the rules of the application/x-www-form-urlencoded media type for query parameters and RFC 3986 for all other components. Note that only characters not permitted in a particular component are subject to encoding so, e.g., a path supplied to one of the pathmethods may contain matrix parameters or multiple path segments since the separators are legal characters and will not be encoded. Percent encoded values are also recognized where allowed and will not be double encoded.

URI templates are allowed in most components of a URI but their value is restricted to a particular component. E.g.
UriBuilder.fromPath("{arg1}").build("foo#bar"); would result in encoding of the '#' such that the resulting URI is "foo%23bar". To create a URI "foo#bar" use UriBuilder.fromPath("{arg1}").fragment("{arg2}").build("foo", "bar") instead. URI template names and delimiters are never encoded but their values are encoded when a URI is built. Template parameter regular expressions are ignored when building a URI, i.e. no validation is performed.
[中]URI模板感知实用程序类,用于从组件构建URI。参见javax。ws。rs.Path#用于解释URI模板的值。
生成器方法执行相应URI组件中不允许的字符的上下文编码,遵循查询参数的{0$}媒体类型和所有其他组件的{1$}规则。注意,只有特定组件中不允许的字符才需要编码,因此,例如,提供给其中一个pathmethods的路径可能包含矩阵参数或多个路径段,因为分隔符是合法字符,不会被编码。在允许的情况下,编码百分比值也会被识别,不会被双重编码。
URI模板在URI的大多数组件中都是允许的,但它们的值仅限于特定组件。例如。
UriBuilder.fromPath("{arg1}").build("foo#bar");将导致对“#”进行编码,从而生成的URI为“foo%23bar”。要创建URI“foo#bar”,请使用UriBuilder.fromPath("{arg1}").fragment("{arg2}").build("foo", "bar")。URI模板名称和分隔符永远不会被编码,但它们的值在构建URI时会被编码。构建URI时忽略模板参数正则表达式,即不执行验证。

代码示例

代码示例来源: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: jersey/jersey

@Override
public void start() {
  if (started.compareAndSet(false, true)) {
    LOGGER.log(Level.FINE, "Starting JdkHttpServerTestContainer...");
    server.start();
    if (baseUri.getPort() == 0) {
      baseUri = UriBuilder.fromUri(baseUri)
          .port(server.getAddress().getPort())
          .build();
      LOGGER.log(Level.INFO, "Started JdkHttpServerTestContainer at the base URI " + baseUri);
    }
  } else {
    LOGGER.log(Level.WARNING, "Ignoring start request - JdkHttpServerTestContainer is already started.");
  }
}

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

private URL getYahooGeocoderUrl(String address) throws IOException {
  UriBuilder uriBuilder = UriBuilder.fromUri("http://where.yahooapis.com/geocode");
  uriBuilder.queryParam("location", address);
  uriBuilder.queryParam("flags", "J");
  uriBuilder.queryParam("appid", appId);
  if (locale != null) {
    uriBuilder.queryParam("locale", locale);
    uriBuilder.queryParam("gflags", "L");
  }
  URI uri = uriBuilder.build();
  return new URL(uri.toString());
}

代码示例来源: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: prestodb/presto

private synchronized URI createNextResultsUri(String scheme, UriInfo uriInfo)
{
  return uriInfo.getBaseUriBuilder()
      .scheme(scheme)
      .replacePath("/v1/statement")
      .path(queryId.toString())
      .path(String.valueOf(resultId.incrementAndGet()))
      .replaceQuery("")
      .build();
}

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

private URI buildResourceUri(final String... path) {
  final UriBuilder uriBuilder = uriInfo.getBaseUriBuilder();
  uriBuilder.segment(path);
  URI uri = uriBuilder.build();
  try {
    int uriPort = uri.getPort();
    if (port != null) {
      if (StringUtils.isWhitespace(port)) {
    uri = new URI(
        (StringUtils.isBlank(scheme)) ? uri.getScheme() : scheme,
        uri.getUserInfo(),
        (StringUtils.isBlank(host)) ? uri.getHost() : host,

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

private void addHint(Application wadlApplication) {
  // TODO: this not-null check is here only because of unit tests
  if (uriInfo != null) {
    Doc d = new Doc();
    String message;
    if (detailedWadl) {
      final String uriWithoutQueryParam = UriBuilder.fromUri(uriInfo.getRequestUri()).replaceQuery("").build()
          .toString();
      message = LocalizationMessages.WADL_DOC_EXTENDED_WADL(WadlUtils.DETAILED_WADL_QUERY_PARAM, uriWithoutQueryParam);
    } else {
      final String uriWithQueryParam = UriBuilder.fromUri(uriInfo.getRequestUri())
          .queryParam(WadlUtils.DETAILED_WADL_QUERY_PARAM, "true").build().toString();
      message = LocalizationMessages.WADL_DOC_SIMPLE_WADL(WadlUtils.DETAILED_WADL_QUERY_PARAM, uriWithQueryParam);
    }
    d.getOtherAttributes().put(new QName(WadlApplicationContextImpl.WADL_JERSEY_NAMESPACE, "hint", "jersey"), message);
    wadlApplication.getDoc().add(d);
  }
}

代码示例来源:origin: pentaho/pentaho-kettle

/**
 * Create new instance using existing Client instance, and the URI from which the parameters will be extracted
 * 
 */
public PathIdRevisions( com.sun.jersey.api.client.Client client, URI uri ) {
 _client = client;
 StringBuilder template = new StringBuilder( BASE_URI.toString() );
 if ( template.charAt( ( template.length() - 1 ) ) != '/' ) {
  template.append( "/pur-repository-plugin/api/revision/{pathId : .+}/revisions" );
 } else {
  template.append( "pur-repository-plugin/api/revision/{pathId : .+}/revisions" );
 }
 _uriBuilder = UriBuilder.fromPath( template.toString() );
 _templateAndMatrixParameterValues = new HashMap<String, Object>();
 com.sun.jersey.api.uri.UriTemplate uriTemplate = new com.sun.jersey.api.uri.UriTemplate( template.toString() );
 HashMap<String, String> parameters = new HashMap<String, String>();
 uriTemplate.match( uri.toString(), parameters );
 _templateAndMatrixParameterValues.putAll( parameters );
}

代码示例来源: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

public String start() {
  final Response response = addProperties(client.target(requestTokenUri).request())
      .post(null);
  if (response.getStatus() != 200) {
    throw new RuntimeException(LocalizationMessages.ERROR_REQUEST_REQUEST_TOKEN(response.getStatus()));
  }
  final MultivaluedMap<String, String> formParams = response.readEntity(Form.class).asMap();
  parameters.token(formParams.getFirst(OAuth1Parameters.TOKEN));
  secrets.tokenSecret(formParams.getFirst(OAuth1Parameters.TOKEN_SECRET));
  return UriBuilder.fromUri(authorizationUri).queryParam(OAuth1Parameters.TOKEN, parameters.getToken())
      .build().toString();
}

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

private URI getRedirectBaseUri(URI locationURI) {
    if (locationURI == null) {
      throw new TransportException("Missing Location header in the redirect reply");
    }
    Matcher pathMatcher = REDIRECT_PATH_REGEX.matcher(locationURI.getPath());
    if (pathMatcher.matches()) {
      return UriBuilder.fromUri(locationURI)
          .host(dnsService.resolveIp(locationURI.getHost()))
          .replacePath(pathMatcher.group(1))
          .replaceQuery(null)
          .build();
    }
    logger.warn("Invalid redirect URL {}", locationURI);
    return null;
  }
}

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

@Override
 public void filter(ContainerRequestContext requestContext)
   throws IOException {
  final SecurityContext sc = requestContext.getSecurityContext();
  if (!isUserLoggedIn(sc)) {
   try {
    final String destResource = URLEncoder.encode(
      requestContext.getUriInfo().getRequestUri().toString(), "UTF-8");
    final URI loginURI = requestContext.getUriInfo().getBaseUriBuilder()
      .path(LogInLogOutPages.LOGIN_RESOURCE)
      .queryParam(LogInLogOutPages.REDIRECT_QUERY_PARM, destResource)
      .build();
    requestContext
      .abortWith(Response.temporaryRedirect(loginURI).build());
   } catch (final Exception ex) {
    final String errMsg = String.format(
      "Failed to forward the request to login page: %s",
      ex.getMessage());
    LOG.error(errMsg, ex);
    requestContext
      .abortWith(Response.serverError().entity(errMsg).build());
   }
  }
 }
}

代码示例来源: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: 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: neo4j/neo4j

public static String externalUri( String internalUri, String xForwardedHost, String xForwardedProto )
{
  return externalUri( UriBuilder.fromUri( internalUri ), xForwardedHost, xForwardedProto ).toString();
}

代码示例来源:origin: org.apache.cxf.fediz/fediz-idp-core

@Override
public Response addClaim(UriInfo ui, Claim claim) {
  LOG.info("add Claim config");
  Claim createdClaim = claimDAO.addClaim(claim);
  UriBuilder uriBuilder = UriBuilder.fromUri(ui.getRequestUri());
  uriBuilder.path("{index}");
  URI location = uriBuilder.build(createdClaim.getClaimType().toString());
  return Response.created(location).entity(claim).build();
}

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

private static UriBuilder applyLinkStyle(String template, InjectLink.Style style, UriInfo uriInfo) {
  UriBuilder ub = null;
  switch (style) {
    case ABSOLUTE:
      ub = uriInfo.getBaseUriBuilder().path(template);
      break;
    case ABSOLUTE_PATH:
      String basePath = uriInfo.getBaseUri().getPath();
      ub = UriBuilder.fromPath(basePath).path(template);
      break;
    case RELATIVE_PATH:
      ub = UriBuilder.fromPath(template);
      break;
  }
  return ub;
}

代码示例来源: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: apache/nifi

@POST
@Consumes(MediaType.MULTIPART_FORM_DATA)
@Produces(MediaType.APPLICATION_XML)
@Path("{id}/templates/upload")
    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 UriBuilder uriBuilder = uriInfo.getBaseUriBuilder();
    uriBuilder.segment("process-groups", groupId, "templates", "import");
    final URI importUri = uriBuilder.build();

代码示例来源:origin: apache/activemq-artemis

@POST
  public Response redirectCreation(@Context UriInfo uriInfo) {
   ActiveMQRestLogger.LOGGER.debug("Handling POST request for \"" + uriInfo.getPath() + "\"");

   String id = generateDupId();
   Response.ResponseBuilder res = Response.status(Response.Status.TEMPORARY_REDIRECT.getStatusCode());
   res.location(uriInfo.getAbsolutePathBuilder().path(id).build());
   return res.build();
  }
}

相关文章