Java Code Examples for org.glassfish.jersey.server.ContainerRequest

The following examples show how to use org.glassfish.jersey.server.ContainerRequest. These examples are extracted from open source projects. 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 Project: hadoop-ozone   Source File: TestVirtualHostStyleFilter.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testIncorrectVirtualHostStyle() throws
    Exception {

  VirtualHostStyleFilter virtualHostStyleFilter =
      new VirtualHostStyleFilter();
  virtualHostStyleFilter.setConfiguration(conf);

  ContainerRequest containerRequest = createContainerRequest("mybucket" +
      "localhost:9878", null, null, true);
  try {
    virtualHostStyleFilter.filter(containerRequest);
    fail("testIncorrectVirtualHostStyle failed");
  } catch (InvalidRequestException ex) {
    GenericTestUtils.assertExceptionContains("invalid format", ex);
  }

}
 
Example 2
public Function<ContainerRequest, Token> getValueProvider(final Parameter parameter) {
    return request -> {
        if (parameter.getRawType().equals(Token.class) && parameter.isAnnotationPresent(FernetToken.class)) {
            final Token xAuthorizationToken = getTokenHeaderUtility().getXAuthorizationToken(request);
            if (xAuthorizationToken != null) {
                return xAuthorizationToken;
            }
            final Token authorizationToken = getTokenHeaderUtility().getAuthorizationToken(request);
            if (authorizationToken != null) {
                return authorizationToken;
            }
            throw new NotAuthorizedException("Bearer error=\"invalid_token\", error_description=\"no token found in Authorization or X-Authorization header\"");
        }
        throw new IllegalStateException("misconfigured annotation");
    };
}
 
Example 3
public Function<ContainerRequest, T> getValueProvider(final Parameter parameter) {
    return request -> {
        if (parameter.isAnnotationPresent(FernetSecret.class)) {
            final Collection<? extends Key> keys = getKeySupplier().get();
            final Token xAuthorizationToken = getHeaderUtility().getXAuthorizationToken(request);
            if (xAuthorizationToken != null) {
                return getValidator().validateAndDecrypt(keys, xAuthorizationToken);
            }
            final Token authorizationToken = getHeaderUtility().getAuthorizationToken(request);
            if (authorizationToken != null) {
                return getValidator().validateAndDecrypt(keys, authorizationToken);
            }
            throw new NotAuthorizedException("Bearer error=\"invalid_token\", error_description=\"no token found in Authorization or X-Authorization header\"");
        }
        throw new IllegalStateException("misconfigured annotation");
    };
}
 
Example 4
Source Project: fernet-java8   Source File: TokenHeaderUtility.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Extract a Fernet token from an RFC6750 Authorization header.
 *
 * @param request a REST request which may or may not include an RFC6750 Authorization header.
 * @return a Fernet token or null if no RFC6750 Authorization header is provided.
 */
@SuppressWarnings("PMD.AvoidLiteralsInIfCondition")
public Token getAuthorizationToken(final ContainerRequest request) {
    String authorizationString = request.getHeaderString("Authorization");
    if (authorizationString != null && !"".equals(authorizationString)) {
        authorizationString = authorizationString.trim();
        final String[] components = authorizationString.split("\\s");
        if (components.length != 2) {
            throw new NotAuthorizedException(authenticationType);
        }
        final String scheme = components[0];
        if (!authenticationType.equalsIgnoreCase(scheme)) {
            throw new NotAuthorizedException(authenticationType);
        }
        final String tokenString = components[1];
        return Token.fromString(tokenString);
    }
    return null;
}
 
Example 5
/**
 * This returns the matched template as defined by a base URL and path expressions.
 *
 * <p>Matched templates are pairs of (resource path, method path) added with
 * {@link org.glassfish.jersey.server.internal.routing.RoutingContext#pushTemplates(UriTemplate,
 * UriTemplate)}. This code skips redundant slashes from either source caused by Path("/") or
 * Path("").
 */
@Nullable static String route(ContainerRequest request) {
  ExtendedUriInfo uriInfo = request.getUriInfo();
  List<UriTemplate> templates = uriInfo.getMatchedTemplates();
  int templateCount = templates.size();
  if (templateCount == 0) return "";
  StringBuilder builder = null; // don't allocate unless you need it!
  String basePath = uriInfo.getBaseUri().getPath();
  String result = null;
  if (!"/" .equals(basePath)) { // skip empty base paths
    result = basePath;
  }
  for (int i = templateCount - 1; i >= 0; i--) {
    String template = templates.get(i).getTemplate();
    if ("/" .equals(template)) continue; // skip allocation
    if (builder != null) {
      builder.append(template);
    } else if (result != null) {
      builder = new StringBuilder(result).append(template);
      result = null;
    } else {
      result = template;
    }
  }
  return result != null ? result : builder != null ? builder.toString() : "";
}
 
Example 6
Source Project: Alpine   Source File: JwtAuthenticationServiceTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void authenticateShouldReturnNullWhenManagedUserIsSuspended() throws AuthenticationException {
    try (final AlpineQueryManager qm = new AlpineQueryManager()) {
        final ManagedUser managedUser = qm.createManagedUser("username", "passwordHash");
        managedUser.setSuspended(true);
        qm.persist(managedUser);
    }

    final Principal principalMock = mock(Principal.class);
    when(principalMock.getName())
            .thenReturn("username");

    final String token = new JsonWebToken().createToken(principalMock, null, IdentityProvider.LOCAL);

    final ContainerRequest containerRequestMock = mock(ContainerRequest.class);
    when(containerRequestMock.getRequestHeader(eq(HttpHeaders.AUTHORIZATION)))
            .thenReturn(Collections.singletonList("Bearer " + token));

    final JwtAuthenticationService authService = new JwtAuthenticationService(containerRequestMock);

    assertThat(authService.authenticate()).isNull();
}
 
Example 7
@Override public void onEvent(RequestEvent event) {
  // Note: until REQUEST_MATCHED, we don't know metadata such as if the request is async or not
  if (event.getType() != FINISHED) return;
  ContainerRequest request = event.getContainerRequest();
  Object maybeSpan = request.getProperty(SpanCustomizer.class.getName());
  if (!(maybeSpan instanceof SpanCustomizer)) return;

  // Set the HTTP route attribute so that TracingFilter can see it
  request.setProperty("http.route", route(request));

  Throwable error = unwrapError(event);
  // Set the error attribute so that TracingFilter can see it
  if (error != null && request.getProperty("error") == null) request.setProperty("error", error);

  parser.requestMatched(event, (SpanCustomizer) maybeSpan);
}
 
Example 8
Source Project: ameba   Source File: ExceptionMapperUtils.java    License: MIT License 6 votes vote down vote up
/**
 * <p>getResponseType.</p>
 *
 * @param request a {@link org.glassfish.jersey.server.ContainerRequest} object.
 * @param status  a {@link java.lang.Integer} object.
 * @return a {@link javax.ws.rs.core.MediaType} object.
 */
public static MediaType getResponseType(ContainerRequest request, Integer status) {
    if (status != null && status == 406) {
        return MediaType.TEXT_HTML_TYPE;
    }
    List<MediaType> accepts = request.getAcceptableMediaTypes();
    MediaType m;
    if (accepts != null && accepts.size() > 0) {
        m = accepts.get(0);
    } else {
        m = Requests.getMediaType();
    }
    if (m.isWildcardType() || m.equals(LOW_IE_DEFAULT_REQ_TYPE)) {
        m = MediaType.TEXT_HTML_TYPE;
    }
    return m;
}
 
Example 9
Source Project: dremio-oss   Source File: TimingApplicationEventListener.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void onEvent(RequestEvent event) {
  switch (event.getType()) {
  case RESOURCE_METHOD_START:
    callId = ticker.nextId();
    ticker.tick("callRes", callId);
    break;
  case RESOURCE_METHOD_FINISHED:
    ticker.tock("callRes", callId);
    break;
  case FINISHED:
    ticker.tock("req", reqEId);
    ContainerRequest req = event.getContainerRequest();
    String endpoint = req.getMethod() + " " + req.getRequestUri().toString().substring(req.getBaseUri().toString().length());
    ticker.log(reqId, endpoint);
    Timer.release();
    break;
    default: // do nothing
  }
}
 
Example 10
Source Project: development   Source File: RestTriggerResourceTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testAction() throws Exception {
    RestTriggerResource.Action action = new RestTriggerResource()
            .redirectToAction();

    TriggerParameters params = new TriggerParameters();
    params.setId(new Long(1L));

    ContainerRequest request = Mockito.mock(ContainerRequest.class);
    Mockito.when(request.getProperty(Mockito.anyString()))
            .thenReturn(new Integer(CommonParams.VERSION_1));

    Response response = action.getCollection(request, params);
    assertThat(response.getEntity(),
            IsInstanceOf.instanceOf(RepresentationCollection.class));

    assertNull(action.getItem(request, params));
}
 
Example 11
Source Project: dropwizard-guicey   Source File: GuiceBindingsModule.java    License: MIT License 6 votes vote down vote up
@Override
protected void configure() {
    jerseyToGuiceGlobal(MultivaluedParameterExtractorProvider.class);
    jerseyToGuiceGlobal(Application.class);
    jerseyToGuiceGlobal(Providers.class);

    // request scoped objects
    jerseyToGuice(UriInfo.class);
    jerseyToGuice(ResourceInfo.class);
    jerseyToGuice(HttpHeaders.class);
    jerseyToGuice(SecurityContext.class);
    jerseyToGuice(Request.class);
    jerseyToGuice(ContainerRequest.class);
    jerseyToGuice(AsyncContext.class);

    if (!guiceServletSupport) {
        // bind request and response objects when guice servlet module not registered
        // but this will work only for resources
        jerseyToGuice(HttpServletRequest.class);
        jerseyToGuice(HttpServletResponse.class);
    }
}
 
Example 12
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
        throws IOException, ServletException {
    Timer.start("JERSEY_FILTER_DOFILTER");
    // we use a latch to make the processing inside Jersey synchronous
    CountDownLatch jerseyLatch = new CountDownLatch(1);

    ContainerRequest req = servletRequestToContainerRequest(servletRequest);
    req.setWriter(new JerseyServletResponseWriter(servletResponse, jerseyLatch));

    req.setProperty(JERSEY_SERVLET_RESPONSE_PROPERTY, servletResponse);

    jersey.handle(req);
    try {
        jerseyLatch.await();
    } catch (InterruptedException e) {
        log.error("Interrupted while processing request", e);
        throw new InternalServerErrorException(e);
    }
    Timer.stop("JERSEY_FILTER_DOFILTER");
    filterChain.doFilter(servletRequest, servletResponse);
}
 
Example 13
Source Project: jrestless   Source File: ServiceRequestHandler.java    License: Apache License 2.0 6 votes vote down vote up
@Override
protected void extendActualJerseyContainerRequest(ContainerRequest actualContainerRequest,
		JRestlessContainerRequest containerRequest, ServiceRequestAndLambdaContext requestAndLambdaContext) {
	ServiceRequest request = requestAndLambdaContext.getServiceRequest();
	Context lambdaContext = requestAndLambdaContext.getLambdaContext();
	actualContainerRequest.setRequestScopedInitializer(locator -> {
		Ref<ServiceRequest> serviceRequestRef = locator
				.<Ref<ServiceRequest>>getInstance(SERVICE_REQUEST_TYPE);
		if (serviceRequestRef != null) {
			serviceRequestRef.set(request);
		} else {
			LOG.error("ServiceFeature has not been registered. ServiceRequest injection won't work.");
		}
		Ref<Context> contextRef = locator
				.<Ref<Context>>getInstance(AbstractLambdaContextReferencingBinder.LAMBDA_CONTEXT_TYPE);
		if (contextRef != null) {
			contextRef.set(lambdaContext);
		} else {
			LOG.error("AwsFeature has not been registered. Context injection won't work.");
		}
	});
}
 
Example 14
Source Project: jrestless   Source File: ServiceRequestHandlerTest.java    License: Apache License 2.0 6 votes vote down vote up
@SuppressWarnings({ "unchecked", "rawtypes" })
private RequestScopedInitializer getSetRequestScopedInitializer(Context context, ServiceRequest request) {
	ServiceRequestAndLambdaContext reqAndContext = new ServiceRequestAndLambdaContext(request, context);
	ArgumentCaptor<Consumer> containerEnhancerCaptor = ArgumentCaptor.forClass(Consumer.class);
	serviceHandler.delegateRequest(reqAndContext);
	verify(container).handleRequest(any(), any(), any(), containerEnhancerCaptor.capture());

	ContainerRequest containerRequest = mock(ContainerRequest.class);
	containerEnhancerCaptor.getValue().accept(containerRequest);

	ArgumentCaptor<RequestScopedInitializer> requestScopedInitializerCaptor = ArgumentCaptor.forClass(RequestScopedInitializer.class);

	verify(containerRequest).setRequestScopedInitializer(requestScopedInitializerCaptor.capture());

	return requestScopedInitializerCaptor.getValue();
}
 
Example 15
Source Project: jrestless   Source File: GatewayRequestHandler.java    License: Apache License 2.0 6 votes vote down vote up
@Override
protected void extendActualJerseyContainerRequest(ContainerRequest actualContainerRequest,
		JRestlessContainerRequest containerRequest, GatewayRequestAndLambdaContext requestAndLambdaContext) {
	GatewayRequest request = requestAndLambdaContext.getGatewayRequest();
	Context lambdaContext = requestAndLambdaContext.getLambdaContext();
	actualContainerRequest.setRequestScopedInitializer(locator -> {
		Ref<GatewayRequest> gatewayRequestRef = locator
				.<Ref<GatewayRequest>>getInstance(GATEWAY_REQUEST_TYPE);
		if (gatewayRequestRef != null) {
			gatewayRequestRef.set(request);
		} else {
			LOG.error("GatewayFeature has not been registered. GatewayRequest injection won't work.");
		}
		Ref<Context> contextRef = locator
				.<Ref<Context>>getInstance(AbstractLambdaContextReferencingBinder.LAMBDA_CONTEXT_TYPE);
		if (contextRef != null) {
			contextRef.set(lambdaContext);
		} else {
			LOG.error("AwsFeature has not been registered. Context injection won't work.");
		}
	});
	actualContainerRequest.setProperty(GatewayBinaryReadInterceptor.PROPERTY_BASE_64_ENCODED_REQUEST,
			request.isBase64Encoded());
}
 
Example 16
Source Project: jrestless   Source File: SnsRequestHandler.java    License: Apache License 2.0 6 votes vote down vote up
@Override
protected void extendActualJerseyContainerRequest(ContainerRequest actualContainerRequest,
		JRestlessContainerRequest containerRequest, SnsRecordAndLambdaContext snsRecordAndContext) {
	SNSRecord snsRecord = snsRecordAndContext.getSnsRecord();
	Context lambdaContext = snsRecordAndContext.getLambdaContext();
	actualContainerRequest.setRequestScopedInitializer(locator -> {
		Ref<SNSRecord> snsRecordRef = locator.<Ref<SNSRecord>>getInstance(SNS_RECORD_TYPE);
		if (snsRecordRef != null) {
			snsRecordRef.set(snsRecord);
		} else {
			LOG.error("SnsFeature has not been registered. SNSRecord injection won't work.");
		}
		Ref<Context> contextRef = locator
				.<Ref<Context>>getInstance(AbstractLambdaContextReferencingBinder.LAMBDA_CONTEXT_TYPE);
		if (contextRef != null) {
			contextRef.set(lambdaContext);
		} else {
			LOG.error("AwsFeature has not been registered. Context injection won't work.");
		}
	});
}
 
Example 17
Source Project: jrestless   Source File: FnRequestHandler.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Hook that allows you to extend the actual containerRequest passed to the Jersey container.
 */
@Override
protected void extendActualJerseyContainerRequest(ContainerRequest actualContainerRequest,
												JRestlessContainerRequest containerRequest,
												WrappedInput wrappedInput) {
	InputEvent event = wrappedInput.inputEvent;
	actualContainerRequest.setRequestScopedInitializer(locator -> {
		Ref<InputEvent> inputEventRef = locator
				.<Ref<InputEvent>>getInstance(INPUT_EVENT_TYPE);
		if (inputEventRef != null) {
			inputEventRef.set(event);
		}
		Ref<RuntimeContext> contextRef = locator
				.<Ref<RuntimeContext>>getInstance(RUNTIME_CONTEXT_TYPE);
		if (contextRef != null) {
			contextRef.set(rctx);
		}
	});
}
 
Example 18
Source Project: jrestless   Source File: JRestlessHandlerContainer.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Creates a new {@link ContainerRequest} for the given input.
 *
 * @param request
 * @param containerResponseWriter
 * @param securityContext
 * @return
 */
@Nonnull
protected ContainerRequest createContainerRequest(@Nonnull RequestT request,
		@Nonnull ContainerResponseWriter containerResponseWriter, @Nonnull SecurityContext securityContext) {
	requireNonNull(request, "request may not be null");
	URI baseUri = request.getBaseUri();
	URI requestUri = requireNonNull(request.getRequestUri(), "request.getRequestUri() may not be null");
	String httpMethod = requireNonNull(request.getHttpMethod(), "request.getHttpMethod() may not be null");
	InputStream entityStream = requireNonNull(request.getEntityStream(),
			"request.getEntityStream() may not be null");
	Map<String, List<String>> headers = requireNonNull(request.getHeaders(),
			"request.getHeaderParams() may not be null");
	requireNonNull(containerResponseWriter, "containerResponseWriter may not be null");
	requireNonNull(securityContext, "securityContext may not be null");

	ContainerRequest requestContext = new ContainerRequest(baseUri, requestUri, httpMethod, securityContext,
			new MapPropertiesDelegate());
	requestContext.setEntityStream(entityStream);
	requestContext.getHeaders().putAll(headers);
	requestContext.setWriter(containerResponseWriter);

	return requestContext;
}
 
Example 19
Source Project: hadoop-ozone   Source File: TestVirtualHostStyleFilter.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testVirtualHostStyle() throws  Exception {
  VirtualHostStyleFilter virtualHostStyleFilter =
      new VirtualHostStyleFilter();
  virtualHostStyleFilter.setConfiguration(conf);


  ContainerRequest containerRequest = createContainerRequest("mybucket" +
          ".localhost:9878", "/myfile", null, true);
  virtualHostStyleFilter.filter(containerRequest);
  URI expected = new URI("http://" + s3HttpAddr +
      "/mybucket/myfile");
  Assert.assertEquals(expected, containerRequest.getRequestUri());
}
 
Example 20
Source Project: hadoop-ozone   Source File: TestVirtualHostStyleFilter.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testPathStyle() throws Exception {

  VirtualHostStyleFilter virtualHostStyleFilter =
      new VirtualHostStyleFilter();
  virtualHostStyleFilter.setConfiguration(conf);

  ContainerRequest containerRequest = createContainerRequest(s3HttpAddr,
      "/mybucket/myfile", null, false);
  virtualHostStyleFilter.filter(containerRequest);
  URI expected = new URI("http://" + s3HttpAddr +
      "/mybucket/myfile");
  Assert.assertEquals(expected, containerRequest.getRequestUri());

}
 
Example 21
Source Project: soabase   Source File: JerseyGuiceModule.java    License: Apache License 2.0 5 votes vote down vote up
@Provides
@RequestScoped
public HttpHeaders providesHttpHeaders()
{
    ContainerRequestContext context = filter.getContainerRequestContext();
    return (context != null) ? (ContainerRequest)context.getRequest() : null;
}
 
Example 22
Source Project: minnal   Source File: BaseResourceTest.java    License: Apache License 2.0 5 votes vote down vote up
private ContainerRequest createContainerRequest(URI baseUri, URI requestUri, String method, String content, Map<String, String> headers,
                                                SecurityContext securityContext, PropertiesDelegate propertiesDelegate) {
    URI uri = URI.create(baseUri.getPath() + "/");
    ContainerRequest containerRequest = new ContainerRequest(uri, requestUri, method, securityContext, propertiesDelegate);
    containerRequest.setEntityStream(new ByteArrayInputStream(content.getBytes()));
    for (Map.Entry<String, String> headerEntry : headers.entrySet()) {
        containerRequest.getHeaders().add(headerEntry.getKey(), headerEntry.getValue());
    }
    return containerRequest;
}
 
Example 23
@Override
@SuppressWarnings("unchecked")
public void handleRequest(HttpServerExchange exchange) throws Exception {
    try {
        ContainerRequest request = createContainerRequest(exchange);
        request.setWriter(new UndertowResponseWriter(exchange, container));
        container.getApplicationHandler().handle(request);
    } catch (Throwable e) {
        if (exchange.isResponseChannelAvailable()) {
            exchange.setStatusCode(500);
            exchange.getResponseHeaders().add(new HttpString("Content-Type"), "text/plain");
            exchange.getResponseSender().send(Exceptions.stackTrace(e));
        }
    }
}
 
Example 24
@Test
public final void verifyApplyReturnsTokenFromBearerToken() {
    // given
    final ContainerRequest request = mock(ContainerRequest.class);
    doReturn(token).when(tokenHeaderUtility).getAuthorizationToken(request);
    doReturn(null).when(tokenHeaderUtility).getXAuthorizationToken(request);

    // when
    final Token result = function.apply(request);

    // then
    assertEquals(token.serialise(), result.serialise());
}
 
Example 25
@Test
public final void verifyApplyReturnsTokenFromXToken() {
    // given
    final ContainerRequest request = mock(ContainerRequest.class);
    doReturn(null).when(tokenHeaderUtility).getAuthorizationToken(request);
    doReturn(token).when(tokenHeaderUtility).getXAuthorizationToken(request);

    // when
    final Token result = function.apply(request);

    // then
    assertEquals(token.serialise(), result.serialise());
}
 
Example 26
@Test
public final void verifyApplyThrowsNotAuthorized() {
    // given
    final ContainerRequest request = mock(ContainerRequest.class);

    // when / then
    thrown.expect(NotAuthorizedException.class);
    function.apply(request);
}
 
Example 27
@Test
public final void verifyApplyThrowsNotAuthorized() {
    // given
    final ContainerRequest request = mock(ContainerRequest.class);

    // when / then
    thrown.expect(NotAuthorizedException.class);
    function.apply(request);
}
 
Example 28
Source Project: fernet-java8   Source File: TokenHeaderUtilityTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public final void verifyGetAuthorizationTokenDeserialisesBearerToken() {
    // given
    final Key key = Key.generateKey(random);
    final Token token = Token.generate(random, key, "hello");
    final ContainerRequest request = mock(ContainerRequest.class);
    given(request.getHeaderString("Authorization")).willReturn("Bearer " + token.serialise());

    // when
    final Token result = utility.getAuthorizationToken(request);

    // then
    assertEquals(token.serialise(), result.serialise());
}
 
Example 29
Source Project: fernet-java8   Source File: TokenHeaderUtilityTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public final void verifyGetAuthorizationTokenRejectsMalformedHeader() {
    // given
    final ContainerRequest request = mock(ContainerRequest.class);
    given(request.getHeaderString("Authorization")).willReturn("Basic YWxpY2U6cGFzc3dvcmQ= 76bd6d14-0148-43c4-8ea0-8368336ce9f1");

    // when / then
    thrown.expect(NotAuthorizedException.class);
    utility.getAuthorizationToken(request);
}
 
Example 30
Source Project: fernet-java8   Source File: TokenHeaderUtilityTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public final void verifyGetAuthorizationTokenRejectsInvalidScheme() {
    // given
    final ContainerRequest request = mock(ContainerRequest.class);
    given(request.getHeaderString("Authorization")).willReturn("Basic YWxpY2U6cGFzc3dvcmQ=");

    // when / then
    thrown.expect(NotAuthorizedException.class);
    utility.getAuthorizationToken(request);
}