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

The following examples show how to use javax.ws.rs.container.ContainerRequestContext#getUriInfo() . 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: ResourceAuthFilter.java    From tastjava with MIT License 6 votes vote down vote up
@Override
    public void filter(ContainerRequestContext containerRequestContext) throws IOException {

        UriInfo info = containerRequestContext.getUriInfo();
        if (info.getPath().contains("user/login")) {
            return;
        }

        if (!isAuthTokenValid(containerRequestContext)) {
//            throw new NotAuthorizedException("You Don't Have Permission");
            containerRequestContext.abortWith(Response
                    .seeOther(URI.create("/tastjava/user/login")).build());
        }

        return;

    }
 
Example 2
Source File: SatisfiableResourceFilter.java    From smarthome with Eclipse Public License 2.0 6 votes vote down vote up
@Override
public void filter(ContainerRequestContext ctx) throws IOException {
    UriInfo uriInfo = ctx.getUriInfo();

    if (uriInfo != null) {
        List<Object> matchedResources = uriInfo.getMatchedResources();

        if (matchedResources != null && !matchedResources.isEmpty()) {
            // current resource is always first as per documentation
            Object matchedResource = matchedResources.get(0);

            if (matchedResource instanceof RESTResource && !((RESTResource) matchedResource).isSatisfied()) {
                ctx.abortWith(Response.status(Status.SERVICE_UNAVAILABLE).build());
            }
        }
    }
}
 
Example 3
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 4
Source File: JerseyGuiceModule.java    From soabase with Apache License 2.0 5 votes vote down vote up
@Provides
@RequestScoped
public UriInfo providesUriInfo()
{
    ContainerRequestContext context = filter.getContainerRequestContext();
    return (context != null) ? context.getUriInfo() : null;
}
 
Example 5
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 6
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 7
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 8
Source File: RequestLoggingFilter.java    From pnc with Apache License 2.0 5 votes vote down vote up
@Override
public void filter(ContainerRequestContext requestContext) throws IOException {
    MDCUtils.clear();
    requestContext.setProperty(REQUEST_EXECUTION_START, System.currentTimeMillis());

    String logRequestContext = requestContext.getHeaderString("log-request-context");
    if (logRequestContext == null) {
        logRequestContext = RandomUtils.randString(12);
    }
    MDCUtils.addRequestContext(logRequestContext);

    String logProcessContext = requestContext.getHeaderString("log-process-context");
    if (logProcessContext != null) {
        MDCUtils.addProcessContext(logProcessContext);
    }

    User user = null;
    try {
        user = userService.currentUser();
        if (user != null) {
            Integer userId = user.getId();
            if (userId != null) {
                MDCUtils.addUserId(Integer.toString(userId));
            }
        }
    } catch (Exception e) {
        // user not found, continue ...
    }

    UriInfo uriInfo = requestContext.getUriInfo();
    Request request = requestContext.getRequest();
    logger.info("Requested {} {}.", request.getMethod(), uriInfo.getRequestUri());

    if (logger.isTraceEnabled()) {
        MultivaluedMap<String, String> headers = requestContext.getHeaders();
        logger.trace("Headers: " + MapUtils.toString(headers));
        logger.trace("Entity: {}.", getEntityBody(requestContext));
        logger.trace("User principal name: {}", getUserPrincipalName(requestContext));
    }
}
 
Example 9
Source File: SecurityManagerAssociatingFilter.java    From aries-jax-rs-whiteboard with Apache License 2.0 5 votes vote down vote up
/**
 * Set up the incoming request context
 */
@Override
public void filter(ContainerRequestContext requestContext) throws IOException {
    
    _LOG.debug("Establishing Shiro Security Context");
    
    // Bind the security manager
    ThreadContext.bind(manager);
    
    Cookie cookie = requestContext.getCookies().get(SESSION_COOKIE_NAME);
    
    // If we have a session cookie then use it to prime the session value
    if(cookie != null) {
        _LOG.debug("Found a Shiro Security Context cookie: {}. Establishing user context", cookie);
        
        _LOG.debug("Establishing user context:");
        Subject subject = new Subject.Builder(manager).sessionId(cookie.getValue()).buildSubject();
        ThreadContext.bind(subject);
        if(_LOG.isDebugEnabled()) {
            _LOG.debug("Established user context for: {}", subject.getPrincipal());
        }
    }
    
    UriInfo info = requestContext.getUriInfo();
    
    if("security/authenticate".equals(info.getPath())) {
        requestContext.abortWith(authenticate(info, requestContext.getHeaderString("user"), requestContext.getHeaderString("password")));
    } else if("security/logout".equals(info.getPath())) {
        logout();
    }
}
 
Example 10
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 11
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 12
Source File: JsonApiResponseFilter.java    From katharsis-framework with Apache License 2.0 5 votes vote down vote up
/**
 * Creates JSON API responses for custom JAX-RS actions returning Katharsis resources.
 */
@Override
public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext) throws IOException {
	Object response = responseContext.getEntity();
	if (response == null) {
		return;
	}
	
	// only modify responses which contain a single or a list of Katharsis resources
	if (isResourceResponse(response)) {
		KatharsisBoot boot = feature.getBoot();
		ResourceRegistry resourceRegistry = boot.getResourceRegistry();
		DocumentMapper documentMapper = boot.getDocumentMapper();
		
		ServiceUrlProvider serviceUrlProvider = resourceRegistry.getServiceUrlProvider();
		try {
			UriInfo uriInfo = requestContext.getUriInfo();
			if (serviceUrlProvider instanceof UriInfoServiceUrlProvider) {
				((UriInfoServiceUrlProvider) serviceUrlProvider).onRequestStarted(uriInfo);
			}

			JsonApiResponse jsonApiResponse = new JsonApiResponse();
			jsonApiResponse.setEntity(response);
			// use the Katharsis document mapper to create a JSON API response
			responseContext.setEntity(documentMapper.toDocument(jsonApiResponse, null));
			responseContext.getHeaders().put("Content-Type", Arrays.asList((Object)JsonApiMediaType.APPLICATION_JSON_API));
			
		}
		finally {
			if (serviceUrlProvider instanceof UriInfoServiceUrlProvider) {
				((UriInfoServiceUrlProvider) serviceUrlProvider).onRequestFinished();
			}
		}
	}
}
 
Example 13
Source File: JSONPrettyPrintFilter.java    From dremio-oss with Apache License 2.0 5 votes vote down vote up
@Override
public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext)
  throws IOException {
  UriInfo info = requestContext.getUriInfo();
  if (!info.getQueryParameters().containsKey("pretty")) {
    return;
  }

  ObjectWriterInjector.set(new PrettyPrintWriter(ObjectWriterInjector.getAndClear()));
}
 
Example 14
Source File: MediaTypeFilter.java    From dremio-oss with Apache License 2.0 5 votes vote down vote up
@Override
public void filter(ContainerRequestContext requestContext)
    throws IOException {
  final UriInfo info = requestContext.getUriInfo();
  MultivaluedMap<String, String> parameters = info.getQueryParameters();

  String format = parameters.getFirst("format");
  if (format == null) {
    return;
  }
  requestContext.getHeaders().putSingle(HttpHeaders.ACCEPT, format);
}
 
Example 15
Source File: JaxrsRequestContext.java    From crnk-framework with Apache License 2.0 5 votes vote down vote up
JaxrsRequestContext(ContainerRequestContext requestContext, CrnkFeature feature) {
	this.feature = feature;
	this.requestContext = requestContext;

	UriInfo uriInfo = requestContext.getUriInfo();
	this.path = buildPath(uriInfo);
	this.parameters = getParameters(uriInfo);
}
 
Example 16
Source File: PrettyPrintFilter.java    From Alpine with Apache License 2.0 5 votes vote down vote up
@Override
public void filter(ContainerRequestContext reqCtx, ContainerResponseContext respCtx) throws IOException {
    final UriInfo uriInfo = reqCtx.getUriInfo();
    final MultivaluedMap<String, String> queryParameters = uriInfo.getQueryParameters();
    if (queryParameters.containsKey("pretty")) {
        ObjectWriterInjector.set(new IndentingModifier());
    }
}
 
Example 17
Source File: AuthenticationFilter.java    From hugegraph with Apache License 2.0 4 votes vote down vote up
@Override
public void filter(ContainerRequestContext context) throws IOException {
    User user = this.authenticate(context);
    Authorizer authorizer = new Authorizer(user, context.getUriInfo());
    context.setSecurityContext(authorizer);
}
 
Example 18
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 19
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 20
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);
}