Java Code Examples for javax.ws.rs.container.ContainerRequestContext#setRequestUri()

The following examples show how to use javax.ws.rs.container.ContainerRequestContext#setRequestUri() . 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 File: UriBuilderRequestFilter.java    From gravitee-management-rest-api with Apache License 2.0 6 votes vote down vote up
private void processHostHeader(ContainerRequestContext ctx, UriBuilder baseBuilder, UriBuilder requestBuilder) {
    String hostHeaderValue = getFirstHeaderValueOrNull(ctx, HttpHeaders.X_FORWARDED_HOST);
    if (hostHeaderValue != null) {
        if (hostHeaderValue.contains(":")) {
            int lastColonIdx = hostHeaderValue.lastIndexOf(':');
            String host = hostHeaderValue.substring(0, lastColonIdx);
            int port = Integer.parseInt(hostHeaderValue.substring(lastColonIdx + 1));
            baseBuilder.host(host).port(port);
            requestBuilder.host(host).port(port);
        } else {
            baseBuilder.host(hostHeaderValue).port(NO_EXPLICIT_PORT);
            requestBuilder.host(hostHeaderValue).port(NO_EXPLICIT_PORT);
        }

        ctx.setRequestUri(baseBuilder.build(), requestBuilder.build());
    }
}
 
Example 2
Source File: LoadBalancerRequestFilter.java    From ameba with MIT License 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public void filter(ContainerRequestContext ctx) throws IOException {

    String scheme = getValue(ctx.getHeaders(), "x-forwarded-proto");
    String port = getValue(ctx.getHeaders(), "x-forwarded-port");
    if (scheme == null && port == null)
        return;

    UriBuilder baseBuilder = ctx.getUriInfo().getBaseUriBuilder();
    UriBuilder requestBuilder = ctx.getUriInfo().getRequestUriBuilder();
    if (scheme != null) {
        baseBuilder.scheme(scheme);
        requestBuilder.scheme(scheme);
        baseBuilder.port(443);
        requestBuilder.port(443);
    }

    if (port != null) {
        int nPort = Integer.parseInt(port);
        baseBuilder.port(nPort);
        requestBuilder.port(nPort);
    }

    ctx.setRequestUri(baseBuilder.build(), requestBuilder.build());
}
 
Example 3
Source File: UriBuilderRequestFilter.java    From graviteeio-access-management with Apache License 2.0 5 votes vote down vote up
@Override
public void filter( ContainerRequestContext ctx ) throws IOException {
    List<String> schemes = ctx.getHeaders().get(HttpHeaders.X_FORWARDED_PROTO);
    UriBuilder baseBuilder = ctx.getUriInfo().getBaseUriBuilder();
    UriBuilder requestBuilder = ctx.getUriInfo().getRequestUriBuilder();

    if (schemes != null && !schemes.isEmpty()) {
        String scheme = schemes.get(0);
        baseBuilder.scheme(scheme);
        requestBuilder.scheme(scheme);

        ctx.setRequestUri(baseBuilder.build(), requestBuilder.build());
    }

    List<String> hosts = ctx.getHeaders().get(HttpHeaders.X_FORWARDED_HOST);
    if (hosts != null && !hosts.isEmpty()) {
        String host = hosts.get(0);

        if (host.contains(":")) {
            // Forwarded host contains both host and port
            String [] parts = host.split(":");
            baseBuilder.host(parts[0]).port(Integer.parseInt(parts[1]));
            requestBuilder.host(parts[0]).port(Integer.parseInt(parts[1]));
        } else {
            baseBuilder.host(host);
            requestBuilder.host(host);
        }

        ctx.setRequestUri(baseBuilder.build(), requestBuilder.build());
    }
}
 
Example 4
Source File: DynamicProxyBasePathFilter.java    From jrestless with Apache License 2.0 5 votes vote down vote up
@Override
public void filter(ContainerRequestContext requestContext) throws IOException {
	String dynamicApplicationPath = getDynamicBasePath();
	if (dynamicApplicationPath != null && !dynamicApplicationPath.isEmpty()) {
		UriInfo uriInfo = requestContext.getUriInfo();
		URI baseUri = uriInfo.getBaseUriBuilder()
				.path(dynamicApplicationPath)
				.path("/") // baseUri must have a trailing slash
				.build();
		URI requestUri = uriInfo.getRequestUri();
		requestContext.setRequestUri(baseUri, requestUri);
	}
}
 
Example 5
Source File: ApplicationPathFilter.java    From jrestless with Apache License 2.0 5 votes vote down vote up
@Override
public void filter(ContainerRequestContext requestContext) throws IOException {
	String applicationPath = getApplicationPath();
	if (applicationPath != null) {
		UriInfo requestUriInfo = requestContext.getUriInfo();
		UriBuilder baseUriBuilder = requestUriInfo.getBaseUriBuilder();
		baseUriBuilder.path(applicationPath);
		// the base URI must end with a trailing slash
		baseUriBuilder.path("/");
		URI updatedBaseUri = baseUriBuilder.build();
		URI requestUri = requestUriInfo.getRequestUri();
		requestContext.setRequestUri(updatedBaseUri, requestUri);
	}
}
 
Example 6
Source File: UriBuilderRequestFilter.java    From gravitee-management-rest-api with Apache License 2.0 5 votes vote down vote up
@Override
public void filter( ContainerRequestContext ctx ) throws IOException {
    List<String> schemes = ctx.getHeaders().get(HttpHeaders.X_FORWARDED_PROTO);
    UriBuilder baseBuilder = ctx.getUriInfo().getBaseUriBuilder();
    UriBuilder requestBuilder = ctx.getUriInfo().getRequestUriBuilder();

    if (schemes != null && !schemes.isEmpty()) {
        String scheme = schemes.get(0);
        baseBuilder.scheme(scheme);
        requestBuilder.scheme(scheme);

        ctx.setRequestUri(baseBuilder.build(), requestBuilder.build());
    }

    List<String> hosts = ctx.getHeaders().get(HttpHeaders.X_FORWARDED_HOST);
    if (hosts != null && !hosts.isEmpty()) {
        String host = hosts.get(0);

        if (host.contains(":")) {
            // Forwarded host contains both host and port
            String [] parts = host.split(":");
            baseBuilder.host(parts[0]).port(Integer.parseInt(parts[1]));
            requestBuilder.host(parts[0]).port(Integer.parseInt(parts[1]));
        } else {
            baseBuilder.host(host);
            requestBuilder.host(host);
        }

        ctx.setRequestUri(baseBuilder.build(), requestBuilder.build());
    }
}
 
Example 7
Source File: UriBuilderRequestFilter.java    From gravitee-management-rest-api with Apache License 2.0 5 votes vote down vote up
private void processProtocolHeader(ContainerRequestContext ctx, UriBuilder baseBuilder, UriBuilder requestBuilder) {
    String protoHeaderValue = getFirstHeaderValueOrNull(ctx, HttpHeaders.X_FORWARDED_PROTO);
    if (protoHeaderValue != null) {
        baseBuilder.scheme(protoHeaderValue);
        requestBuilder.scheme(protoHeaderValue);
        ctx.setRequestUri(baseBuilder.build(), requestBuilder.build());
    }
}
 
Example 8
Source File: UriBuilderRequestFilter.java    From gravitee-management-rest-api with Apache License 2.0 5 votes vote down vote up
private void processPortHeader(ContainerRequestContext ctx, UriBuilder baseBuilder, UriBuilder requestBuilder) {
    String portHeaderValue = getFirstHeaderValueOrNull(ctx, HttpHeaders.X_FORWARDED_PORT);
    if (portHeaderValue != null) {
        int port = Integer.parseInt(portHeaderValue);
        baseBuilder.port(port);
        requestBuilder.port(port);
        ctx.setRequestUri(baseBuilder.build(), requestBuilder.build());
    }
}
 
Example 9
Source File: CleanupQueryFilter.java    From swellrt with Apache License 2.0 5 votes vote down vote up
@Override
public void filter(ContainerRequestContext requestContext) throws IOException {

  URI uri = requestContext.getUriInfo().getRequestUri();
  String uriStr = uri.toString();
  int separatorAt = uriStr.indexOf(";");
  if (separatorAt != -1) {
    // remove ";tid=...;sid=..." parts from end of URI.
    uriStr = uriStr.substring(0, uriStr.indexOf(";"));
    requestContext.setRequestUri(URI.create(uriStr));
  }

  LOG.finest(requestContext.getUriInfo().getRequestUri().toString());
}
 
Example 10
Source File: SwaggerUiResourceFilter.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Override
public void filter(ContainerRequestContext rc) throws IOException {
    if (HttpMethod.GET.equals(rc.getRequest().getMethod())) {
        UriInfo ui = rc.getUriInfo();
        String path = "/" + ui.getPath();
        if (PATTERN.matcher(path).matches() && locator.exists(path)) {
            rc.setRequestUri(URI.create("api-docs" + path));
        }
    }
}
 
Example 11
Source File: SwaggerToOpenApiConversionFilter.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Override
public void filter(ContainerRequestContext reqCtx) throws IOException {
    String path = reqCtx.getUriInfo().getPath();
    if (path.endsWith(openApiJsonPath)) {
        reqCtx.setRequestUri(URI.create(SWAGGER_PATH));
        reqCtx.setProperty(OPEN_API_PROPERTY, Boolean.TRUE);
    }

}
 
Example 12
Source File: RedirectResourceFilter.java    From nifi with Apache License 2.0 5 votes vote down vote up
/**
 * This method checks path of the incoming request, and
 * redirects following URIs:
 * <li>/controller -> SiteToSiteResource
 * @param requestContext request to be modified
 */
@Override
public void filter(ContainerRequestContext requestContext) throws IOException {
    final UriInfo uriInfo = requestContext.getUriInfo();

    if (uriInfo.getPath().equals("controller")){
        UriBuilder builder = UriBuilder.fromUri(uriInfo.getBaseUri())
                .path(SiteToSiteResource.class)
                .replaceQuery(uriInfo.getRequestUri().getRawQuery());

        URI redirectTo = builder.build();
        requestContext.setRequestUri(uriInfo.getBaseUri(), redirectTo);
    }
}
 
Example 13
Source File: VirtualHostStyleFilter.java    From hadoop-ozone with Apache License 2.0 4 votes vote down vote up
@Override
public void filter(ContainerRequestContext requestContext) throws
    IOException {

  domains = conf.getTrimmedStrings(OZONE_S3G_DOMAIN_NAME);

  if (domains.length == 0) {
    // domains is not configured, might be it is path style.
    // So, do not continue further, just return.
    return;
  }
  //Get the value of the host
  String host = requestContext.getHeaderString(HttpHeaders.HOST);
  host = checkHostWithoutPort(host);
  String domain = getDomainName(host);

  if (domain == null) {
    throw getException("Invalid S3 Gateway request {" + requestContext
        .getUriInfo().getRequestUri().toString() + " }: No matching domain " +
        "{" + Arrays.toString(domains) + "} for the host {" + host  + "}");
  }

  LOG.debug("Http header host name is {}", host);
  LOG.debug("Domain name matched is {}", domain);

  //Check if we have a Virtual Host style request, host length greater than
  // address length means it is virtual host style, we need to convert to
  // path style.
  if (host.length() > domain.length()) {
    String bucketName = host.substring(0, host.length() - domain.length());

    if(!bucketName.endsWith(".")) {
      //Checking this as the virtual host style pattern is http://bucket.host/
      throw getException("Invalid S3 Gateway request {" + requestContext
          .getUriInfo().getRequestUri().toString() +"}:" +" Host: {" + host
          + " is in invalid format");
    } else {
      bucketName = bucketName.substring(0, bucketName.length() - 1);
    }
    LOG.debug("Bucket name is {}", bucketName);

    URI baseURI = requestContext.getUriInfo().getBaseUri();
    String currentPath = requestContext.getUriInfo().getPath();
    String newPath = bucketName;
    if (currentPath != null) {
      newPath += String.format("%s", currentPath);
    }
    MultivaluedMap<String, String> queryParams = requestContext.getUriInfo()
        .getQueryParameters();
    UriBuilder requestAddrBuilder = UriBuilder.fromUri(baseURI).path(newPath);
    queryParams.forEach((k, v) -> requestAddrBuilder.queryParam(k,
        v.toArray()));
    URI requestAddr = requestAddrBuilder.build();
    requestContext.setRequestUri(baseURI, requestAddr);
  }
}
 
Example 14
Source File: BookServer20.java    From cxf with Apache License 2.0 4 votes vote down vote up
@Override
public void filter(ContainerRequestContext context) throws IOException {
    UriInfo ui = context.getUriInfo();
    String path = ui.getPath(false);

    if ("POST".equals(context.getMethod())
        && "bookstore/bookheaders/simple".equals(path) && !context.hasEntity()) {
        byte[] bytes = StringUtils.toBytesUTF8("<Book><name>Book</name><id>126</id></Book>");
        context.getHeaders().putSingle(HttpHeaders.CONTENT_LENGTH, Integer.toString(bytes.length));
        context.getHeaders().putSingle("Content-Type", "application/xml");
        context.getHeaders().putSingle("EmptyRequestStreamDetected", "true");
        context.setEntityStream(new ByteArrayInputStream(bytes));
    }
    if ("true".equals(context.getProperty("DynamicPrematchingFilter"))) {
        throw new RuntimeException();
    }
    context.setProperty("FirstPrematchingFilter", "true");

    if ("wrongpath".equals(path)) {
        context.setRequestUri(URI.create("/bookstore/bookheaders/simple"));
    } else if ("throwException".equals(path)) {
        context.setProperty("filterexception", "prematch");
        throw new InternalServerErrorException(
            Response.status(500).type("text/plain")
                .entity("Prematch filter error").build());
    } else if ("throwExceptionIO".equals(path)) {
        context.setProperty("filterexception", "prematch");
        throw new IOException();
    }

    MediaType mt = context.getMediaType();
    if (mt != null && "text/xml".equals(mt.toString())) {
        String method = context.getMethod();
        if ("PUT".equals(method)) {
            context.setMethod("POST");
        }
        context.getHeaders().putSingle("Content-Type", "application/xml");
    } else {
        String newMt = context.getHeaderString("newmediatype");
        if (newMt != null) {
            context.getHeaders().putSingle("Content-Type", newMt);
        }
    }
    List<MediaType> acceptTypes = context.getAcceptableMediaTypes();
    if (acceptTypes.size() == 1 && "text/mistypedxml".equals(acceptTypes.get(0).toString())) {
        context.getHeaders().putSingle("Accept", "text/xml");
    }
}
 
Example 15
Source File: ClientCodeRequestFilter.java    From cxf with Apache License 2.0 4 votes vote down vote up
@Override
public void filter(ContainerRequestContext rc) throws IOException {
    checkSecurityContextStart(rc);
    UriInfo ui = rc.getUriInfo();
    String absoluteRequestUri = ui.getAbsolutePath().toString();
    boolean sameRedirectUri = false;
    if (completeUri == null) {
        String referer = rc.getHeaderString("Referer");
        if (referer != null && referer.startsWith(authorizationServiceUri)) {
            completeUri = absoluteRequestUri;
            sameRedirectUri = true;
        }
    }

    if (isStartUriMatched(ui, absoluteRequestUri, sameRedirectUri)) {
        ClientTokenContext request = getClientTokenContext(rc);
        if (request != null) {
            setClientCodeRequest(request);
            if (completeUri != null) {
                rc.setRequestUri(URI.create(completeUri));
            }
            // let the request continue if the token context is already available
            return;
        }
        // start the code flow
        Response codeResponse = createCodeResponse(rc, ui);
        rc.abortWith(codeResponse);
        return;
    }
    // complete the code flow if possible
    MultivaluedMap<String, String> requestParams = toRequestState(rc, ui);
    if (codeResponseQueryParamsAvailable(requestParams)
        && (completeUri == null || absoluteRequestUri.endsWith(completeUri))) {
        processCodeResponse(rc, ui, requestParams);
        checkSecurityContextEnd(rc, requestParams);
        // let the request continue
        return;
    }
    // neither the start nor the end of the flow
    rc.abortWith(Response.status(401).build());
}
 
Example 16
Source File: HeaderAdder.java    From incubator-pinot with Apache License 2.0 4 votes vote down vote up
@Override
public void filter(ContainerRequestContext req)
    throws IOException {
  {
    // TODO HACK TO BE REMOVED ONCE CLIENTS HAVE UPGRADED TO NEW THIRD-EYE JAR
    // When a client sends an HTTP request without the leading slash (e.g. "GET tables HTTP/1.1")
    // then jersey seems to not parse it correctly. In these cases, the "incomingBaseUri" turns out as
    // http://localhost:21000/ and the "incomingReqUri" turns out as "http://localhost:21000tables"
    // We want to rewrite the incoming request URI to include the slash, otherwise, "localhost:21000tables" is parsed
    // as the authority.
    //
    // An older version of the http client used by third-eye jar sent http requests without leading slash
    // in the URI, causing jersey APIs to break.
    final String incomingReqUri = req.getUriInfo().getRequestUri().toString();
    final String incomingBaseUri = req.getUriInfo().getBaseUri().toASCIIString();
    try {
      String baseUriWithoutSlash = incomingBaseUri;
      if (incomingBaseUri.endsWith("/")) {
        // Remove the trailing slash
        baseUriWithoutSlash = incomingBaseUri.substring(0, incomingBaseUri.length() - 1);
      }
      if (incomingReqUri.startsWith(baseUriWithoutSlash)) {
        String relativeUri = incomingReqUri.substring(baseUriWithoutSlash.length());
        // In the example described above, relativeUri will be "tables"
        if (!relativeUri.startsWith("/")) {
          URI newReqUri = new URI(baseUriWithoutSlash + "/" + relativeUri);
          LOGGER
              .warn("Rewriting new Request URI {} (incomingBaseUri = {}, incomingReqUri = {})", newReqUri.toString(),
                  incomingBaseUri, incomingReqUri);
          req.setRequestUri(newReqUri);
        }
      }
    } catch (Exception e) {
      LOGGER.error("Exception handling incoming URI {}, base URI {}", incomingReqUri, incomingBaseUri);
    }
  }

  // Add outgoing headers if this is a PUT or a POST
  String path = req.getUriInfo().getPath();
  if ((req.getMethod().equalsIgnoreCase("PUT") || req.getMethod().equalsIgnoreCase("POST"))) {
    String mediaType = modifiedContentType(path);
    if (mediaType != null) {
      req.getHeaders().remove(HttpHeaders.CONTENT_TYPE);
      req.getHeaders().add(HttpHeaders.CONTENT_TYPE, mediaType);
    }
  }
}