Java Code Examples for javax.ws.rs.core.UriInfo#getPath()

The following examples show how to use javax.ws.rs.core.UriInfo#getPath() . 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: ResourceUtil.java    From secure-data-service with Apache License 2.0 6 votes vote down vote up
/**
 * Extracts the API version from the provided URI info.
 * 
 * @param uriInfo
 *            URI requested by user (version is part of the URI)
 * @return version referenced by UriInfo
 */
public static String getApiVersion(final UriInfo uriInfo) {
    if (uriInfo != null) {
        String uriPath = uriInfo.getPath();
        if (uriPath != null) {
            int indexOfSlash = uriPath.indexOf("/");
            if (indexOfSlash >= 0) {
                String version = uriPath.substring(0, indexOfSlash);
                return version;
            } else {
                return uriPath;
            }
        }
    }

    return null;
}
 
Example 2
Source File: LinksUtils.java    From mobi with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * Creates the Links that will be used to get the next and previous page of results based off of the provided
 * details.
 *
 * @param uriInfo the request URI information.
 * @param size the number of results returned.
 * @param limit the maximum number of results returned.
 * @param offset the offset of the results.
 * @return Links for the provided details.
 */
public static Links buildLinks(UriInfo uriInfo, int size, int totalSize, int limit, int offset) {
    String path = uriInfo.getPath(false);

    Links links = new Links();
    links.setBase(uriInfo.getBaseUri().toString());
    links.setSelf(uriInfo.getAbsolutePath().toString());
    links.setContext(path);

    if (size == limit && totalSize - (offset + limit) > 0) {
        String next = path + "?" + buildQueryString(uriInfo.getQueryParameters(), offset + limit);
        links.setNext(next);
    }

    if (offset != 0) {
        String prev = path + "?" + buildQueryString(uriInfo.getQueryParameters(), offset - limit);
        links.setPrev(prev);
    }

    return links;
}
 
Example 3
Source File: WadlGenerator.java    From cxf with Apache License 2.0 6 votes vote down vote up
public List<ClassResourceInfo> getResourcesList(Message m, UriInfo ui) {
    final String slash = "/";
    String path = ui.getPath();
    if (!path.startsWith(slash)) {
        path = slash + path;
    }
    List<ClassResourceInfo> all = ((JAXRSServiceImpl)m.getExchange().getService())
        .getClassResourceInfos();
    boolean absolutePathSlashOn = checkAbsolutePathSlash && ui.getAbsolutePath().getPath().endsWith(slash);
    if (slash.equals(path) && !absolutePathSlashOn) {
        return all;
    }
    List<ClassResourceInfo> cris = new LinkedList<>();
    for (ClassResourceInfo cri : all) {
        MultivaluedMap<String, String> map = new MetadataMap<>();
        if (cri.getURITemplate().match(path, map)
            && slash.equals(map.getFirst(URITemplate.FINAL_MATCH_GROUP))) {
            cris.add(cri);
        }
    }
    return cris;
}
 
Example 4
Source File: TenantFilter.java    From hawkular-metrics with Apache License 2.0 6 votes vote down vote up
@Override
public void filter(ContainerRequestContext requestContext) throws IOException {
    UriInfo uriInfo = requestContext.getUriInfo();
    String path = uriInfo.getPath();

    if (path.startsWith("/tenants") || path.startsWith(StatusHandler.PATH) || path.equals(BaseHandler.PATH)) {
        // Some handlers do not check the tenant header
        return;
    }

    String tenant = requestContext.getHeaders().getFirst(TENANT_HEADER_NAME);
    if (tenant != null && !tenant.trim().isEmpty()) {
        // We're good already
        return;
    }
    // Fail on missing tenant info
    Response response = Response.status(Status.BAD_REQUEST)
                                .type(APPLICATION_JSON_TYPE)
                                .entity(new ApiError(MISSING_TENANT_MSG))
                                .build();
    requestContext.abortWith(response);
}
 
Example 5
Source File: RequestPreprocessor.java    From cxf with Apache License 2.0 5 votes vote down vote up
private void handleLanguageMappings(Message m, UriInfo uriInfo) {
    if (languageMappings.isEmpty()) {
        return;
    }
    PathSegmentImpl ps = new PathSegmentImpl(uriInfo.getPath(false), false);
    String path = ps.getPath();
    for (Map.Entry<?, ?> entry : languageMappings.entrySet()) {
        if (path.endsWith("." + entry.getKey())) {
            updateAcceptLanguageHeader(m, entry.getValue().toString());
            updatePath(m, path, entry.getKey().toString(), ps.getMatrixString());
            break;
        }
    }
}
 
Example 6
Source File: AdminEventBuilder.java    From keycloak with Apache License 2.0 5 votes vote down vote up
private String getResourcePath(UriInfo uriInfo) {
    String path = uriInfo.getPath();

    StringBuilder sb = new StringBuilder();
    sb.append("/realms/");
    sb.append(realm.getName());
    sb.append("/");
    String realmRelative = sb.toString();

    return path.substring(path.indexOf(realmRelative) + realmRelative.length());
}
 
Example 7
Source File: OrganizationApplicationNotFoundException.java    From usergrid with Apache License 2.0 5 votes vote down vote up
public OrganizationApplicationNotFoundException( String orgAppName, UriInfo uriInfo,
                                                 ServerEnvironmentProperties properties,
                                                 ManagementService management) {
    super( "Could not find application for " + orgAppName + " from URI: " + uriInfo.getPath() );
    apiResponse = new ApiResponse( properties, management );

    apiResponse.setError( this );
}
 
Example 8
Source File: SwaggerUiServiceFilter.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();
        int uiPathIndex = path.lastIndexOf("api-docs");
        if (uiPathIndex >= 0) {
            String resourcePath = uiPathIndex + 8 < path.length()
                ? path.substring(uiPathIndex + 8) : "";
            rc.abortWith(uiService.getResource(ui, resourcePath));
        }
    }
}
 
Example 9
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 10
Source File: RequestPreprocessor.java    From cxf with Apache License 2.0 5 votes vote down vote up
private void handleExtensionMappings(Message m, UriInfo uriInfo) {
    if (extensionMappings.isEmpty()) {
        return;
    }
    PathSegmentImpl ps = new PathSegmentImpl(uriInfo.getPath(false), false);
    String path = ps.getPath();
    if (PATHS_TO_SKIP.contains(path)) {
        return;
    }
    for (Map.Entry<?, ?> entry : extensionMappings.entrySet()) {
        String key = entry.getKey().toString();
        if (path.endsWith("." + key)) {
            updateAcceptTypeHeader(m, entry.getValue().toString());
            updatePath(m, path, key, ps.getMatrixString());
            if ("wadl".equals(key)) {
                // the path has been updated and Accept was not necessarily set to
                // WADL type (xml or json or html - other options)
                String query = (String)m.get(Message.QUERY_STRING);
                if (StringUtils.isEmpty(query)) {
                    query = "_wadl";
                } else if (!query.contains("_wadl")) {
                    query += "&_wadl";
                }
                m.put(Message.QUERY_STRING, query);
            }
            break;
        }
    }

}
 
Example 11
Source File: AdminStaticResourceController.java    From jweb-cms with GNU Affero General Public License v3.0 5 votes vote down vote up
@Path("/{s:.+}")
@GET
@Consumes
public Response get(@Context UriInfo uriInfo, @Context Request request) throws IOException {
    String path = uriInfo.getPath();
    Optional<ConsoleBundle> consoleBundleOptional = console.findByScriptFile(path);
    Resource resource;
    if (consoleBundleOptional.isPresent()) {
        ConsoleBundle consoleBundle = consoleBundleOptional.get();
        resource = new CombinedResource(path, resourcePaths(consoleBundle), webRoot);
    } else {
        Optional<Resource> optional = webRoot.get(path);
        if (!optional.isPresent()) {
            throw new NotFoundException(String.format("missing resource, path=%s", path));
        }
        resource = optional.get();
    }
    EntityTag eTag = new EntityTag(resource.hash());
    Response.ResponseBuilder builder = request.evaluatePreconditions(eTag);
    if (builder != null) {
        return builder.build();
    }
    builder = Response.ok(resource).type(MediaTypes.getMediaType(Files.getFileExtension(path)));
    builder.tag(eTag);
    CacheControl cacheControl = new CacheControl();
    cacheControl.setMustRevalidate(true);
    builder.cacheControl(cacheControl);
    return builder.build();
}
 
Example 12
Source File: KatharsisFilter.java    From katharsis-framework with Apache License 2.0 5 votes vote down vote up
private String buildPath(UriInfo uriInfo) {
    String basePath = uriInfo.getPath();
    if (webPathPrefix != null && basePath.startsWith(webPathPrefix)) {
        return basePath.substring(webPathPrefix.length());
    } else {
        return basePath;
    }
}
 
Example 13
Source File: MetricsEndpoint.java    From javametrics with Apache License 2.0 5 votes vote down vote up
private URI getCollectionIDFromURIInfo(UriInfo uriInfo, int contextId) {
    // remove parameters from url
    String urlPath = uriInfo.getPath();
    UriBuilder builder = UriBuilder.fromPath(urlPath.substring(0,urlPath.indexOf("/")));
    builder.path(Integer.toString(contextId));
    return builder.build();
}
 
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: WadlGenerator.java    From cxf with Apache License 2.0 4 votes vote down vote up
protected void doFilter(ContainerRequestContext context, Message m) {
    if (!"GET".equals(m.get(Message.HTTP_REQUEST_METHOD))) {
        return;
    }

    UriInfo ui = context.getUriInfo();
    if (!ui.getQueryParameters().containsKey(WADL_QUERY)) {
        if (stylesheetReference != null || !docLocationMap.isEmpty()) {
            String path = ui.getPath(false);
            if (path.startsWith("/") && path.length() > 0) {
                path = path.substring(1);
            }
            if (stylesheetReference != null && path.endsWith(".xsl")
                || docLocationMap.containsKey(path)) {
                context.abortWith(getExistingResource(m, ui, path));
            }
        }
        return;
    }

    if (ignoreRequests) {
        context.abortWith(Response.status(404).build());
        return;
    }

    if (whiteList != null && !whiteList.isEmpty()) {
        ServletRequest servletRequest = (ServletRequest)m.getContextualProperty(
            "HTTP.REQUEST");
        String remoteAddress = null;
        if (servletRequest != null) {
            remoteAddress = servletRequest.getRemoteAddr();
        } else {
            remoteAddress = "";
        }
        boolean foundMatch = false;
        for (String addr : whiteList) {
            if (addr.equals(remoteAddress)) {
                foundMatch = true;
                break;
            }
        }
        if (!foundMatch) {
            context.abortWith(Response.status(404).build());
            return;
        }
    }

    HttpHeaders headers = new HttpHeadersImpl(m);
    List<MediaType> accepts = headers.getAcceptableMediaTypes();
    MediaType type = accepts.contains(WADL_TYPE) ? WADL_TYPE : accepts
        .contains(MediaType.APPLICATION_JSON_TYPE) ? MediaType.APPLICATION_JSON_TYPE
            : defaultWadlResponseMediaType;

    Response response = getExistingWadl(m, ui, type);
    if (response != null) {
        context.abortWith(response);
        return;
    }

    boolean isJson = isJson(type);

    StringBuilder sbMain = generateWADL(getBaseURI(m, ui), getResourcesList(m, ui), isJson, m, ui);

    m.getExchange().put(JAXRSUtils.IGNORE_MESSAGE_WRITERS, !isJson && ignoreMessageWriters);
    Response r = Response.ok().type(type).entity(createResponseEntity(m, ui, sbMain.toString(), isJson)).build();
    context.abortWith(r);
}
 
Example 16
Source File: GatewayBaseResource.java    From datacollector with Apache License 2.0 4 votes vote down vote up
private Response proxyRequest(
    String subResources,
    UriInfo uriInfo,
    HttpMethod httpMethod,
    HttpHeaders httpheaders,
    InputStream inputStream
) throws PipelineException {
  String serviceName = subResources.split("/")[0];

  GatewayInfo gatewayInfo = runtimeInfo.getApiGateway(serviceName);
  Utils.checkState(
      gatewayInfo != null,
      Utils.format("No entry found in the gateway registry for the service name: {}", serviceName)
  );

  validateRequest(gatewayInfo);

  String resourceUrl = gatewayInfo.getServiceUrl() + getBaseUrlPath() + uriInfo.getPath();

  WebTarget target = ClientBuilder.newClient().target(resourceUrl);

  // update query parameters
  uriInfo.getQueryParameters().forEach((k, l) -> l.forEach(v -> target.queryParam(k, v)));

  Invocation.Builder request = target.request();

  // update request headers
  httpheaders.getRequestHeaders().forEach((k, l) -> l.forEach(v -> request.header(k, v)));

  // To avoid users calling REST Service URL directly instead of going through gateway URL.
  // We use GATEWAY_SECRET header, and REST Service will process request only if secret matches
  request.header(GATEWAY_SECRET, gatewayInfo.getSecret());

  String contentType = httpheaders.getRequestHeaders().getFirst(HttpHeaders.CONTENT_TYPE);
  if (contentType == null) {
    contentType = MediaType.TEXT_PLAIN;
  }

  // update request cookies
  httpheaders.getCookies().forEach((k, v) -> request.cookie(k, v.getValue()));

  switch (httpMethod) {
    case GET:
      return request.get();
    case POST:
      if (inputStream != null) {
        return request.post(Entity.entity(inputStream, contentType));
      } else {
        return request.method(httpMethod.getLabel());
      }
    case PUT:
      if (inputStream != null) {
        return request.put(Entity.entity(inputStream, contentType));
      } else {
        return request.method(httpMethod.getLabel());
      }
    case DELETE:
      return request.delete();
    case HEAD:
      return request.head();
    default:
      throw new RuntimeException("Unsupported HTTP method: " + httpMethod);
  }
}
 
Example 17
Source File: HelloResource.java    From tastjava with MIT License 4 votes vote down vote up
@GET
@Path("/context/{id}")
public String sayTestContext(@Context UriInfo ui,@PathParam("id") int id) {
    Logger.info(ui.getPathParameters());
    return ui.getPath();
}