org.glassfish.jersey.server.ContainerRequest Java Examples

The following examples show how to use org.glassfish.jersey.server.ContainerRequest. 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: TokenHeaderUtility.java    From fernet-java8 with 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 #2
Source File: SnsRequestHandler.java    From jrestless with 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 #3
Source File: FnRequestHandler.java    From jrestless with 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 #4
Source File: GatewayRequestHandler.java    From jrestless with 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 #5
Source File: SpanCustomizingApplicationEventListener.java    From brave with Apache License 2.0 6 votes vote down vote up
/**
 * 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 File: JRestlessHandlerContainer.java    From jrestless with 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 #7
Source File: ServiceRequestHandlerTest.java    From jrestless with 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 #8
Source File: ServiceRequestHandler.java    From jrestless with 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 #9
Source File: JerseyHandlerFilter.java    From aws-serverless-java-container with Apache License 2.0 6 votes vote down vote up
@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 #10
Source File: FernetSecretValueParamProvider.java    From fernet-java8 with Apache License 2.0 6 votes vote down vote up
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 #11
Source File: FernetTokenValueParamProvider.java    From fernet-java8 with Apache License 2.0 6 votes vote down vote up
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 #12
Source File: JwtAuthenticationServiceTest.java    From Alpine with 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 #13
Source File: SpanCustomizingApplicationEventListener.java    From brave with Apache License 2.0 6 votes vote down vote up
@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 #14
Source File: GuiceBindingsModule.java    From dropwizard-guicey with 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 #15
Source File: TestVirtualHostStyleFilter.java    From hadoop-ozone with 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 #16
Source File: RestTriggerResourceTest.java    From development with 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 #17
Source File: TimingApplicationEventListener.java    From dremio-oss with 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 #18
Source File: ExceptionMapperUtils.java    From ameba with 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 #19
Source File: TextFormatGetter.java    From heroic with Apache License 2.0 5 votes vote down vote up
@Nullable
@Override
public String get(final Object o, final String s) {

  final ContainerRequest request = (ContainerRequest) o;
  final List<String> requestHeader = request.getRequestHeader(s);

  if (requestHeader != null && requestHeader.size() > 0) {
    return requestHeader.get(0);
  }

  return null;
}
 
Example #20
Source File: OpenSessionInViewFilter.java    From minnal with Apache License 2.0 5 votes vote down vote up
protected void requestCompleted(ContainerRequest request, ContainerResponse response) {
	if (contextCreated.get() == null) {
		return;
	}
	contextCreated.remove();
	JPAContext context = getContext();
	if (context.isTxnOpen()) {
		context.closeTxn(true);
	}
	context.close();
}
 
Example #21
Source File: RouterTest.java    From minnal with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldCreateContainerRequestFromHttpRequestWithContent() {
	ByteBuf content = mock(ByteBuf.class);
	when(request.content()).thenReturn(content);
	ContainerRequest containerRequest = router.createContainerRequest(context);
	assertTrue(containerRequest.getEntityStream() instanceof ByteBufInputStream);
}
 
Example #22
Source File: TemplateHelper.java    From ameba with MIT License 5 votes vote down vote up
/**
 * Get media types for which the {@link org.glassfish.jersey.server.mvc.spi.ResolvedViewable resolved viewable} could be
 * produced.
 *
 * @param containerRequest request to obtain acceptable media types.
 * @param extendedUriInfo  uri info to obtain resource method from and its producible media types.
 * @param varyHeaderValue  Vary header reference.
 * @return list of producible media types.
 */
public static List<MediaType> getProducibleMediaTypes(final ContainerRequest containerRequest,
                                                      final ExtendedUriInfo extendedUriInfo,
                                                      final Ref<String> varyHeaderValue) {
    final List<MediaType> producedTypes = getResourceMethodProducibleTypes(extendedUriInfo);
    final MediaType[] mediaTypes = producedTypes.toArray(new MediaType[producedTypes.size()]);

    final List<Variant> variants = VariantSelector.selectVariants(containerRequest, Variant.mediaTypes(mediaTypes)
            .build(), varyHeaderValue == null ? Refs.emptyRef() : varyHeaderValue);

    return Lists.transform(variants, variant -> MediaTypes.stripQualityParams(variant.getMediaType()));
}
 
Example #23
Source File: StructuredEventFilterTest.java    From cloudbreak with Apache License 2.0 5 votes vote down vote up
private ContainerRequest createRequestContext(MultivaluedMap<String, String> headersMap) {
    MapPropertiesDelegate propertiesDelegate = new MapPropertiesDelegate();
    ContainerRequest requestContext =
            new ContainerRequest(URI.create("http://localhost"), URI.create("/test/endpoint"), "PUT", securityContext, propertiesDelegate);
    requestContext.headers(headersMap);
    return requestContext;
}
 
Example #24
Source File: WebActionRequestHandlerTest.java    From jrestless with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
private RequestScopedInitializer getSetRequestScopedInitializer(JsonObject request) {
	ArgumentCaptor<Consumer<ContainerRequest>> containerEnhancerCaptor = ArgumentCaptor.forClass(Consumer.class);
	handler.delegateJsonRequest(request);
	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 #25
Source File: Pac4JValueFactoryProvider.java    From jax-rs-pac4j with Apache License 2.0 5 votes vote down vote up
@Override
protected Function<ContainerRequest, ?> createValueProvider(Parameter parameter) {
    if (parameter.isAnnotationPresent(Pac4JProfileManager.class)) {
        if (ProfileManager.class.isAssignableFrom(parameter.getRawType())) {
            return manager.get();
        }

        throw new IllegalStateException("Cannot inject a Pac4J profile manager into a parameter of type "
            + parameter.getRawType().getName());
    }

    if (parameter.isAnnotationPresent(Pac4JProfile.class)) {
        if (CommonProfile.class.isAssignableFrom(parameter.getRawType())) {
            return profile.get();
        }

        if (Optional.class.isAssignableFrom(parameter.getRawType())) {
            List<ClassTypePair> ctps = ReflectionHelper.getTypeArgumentAndClass(parameter.getRawType());
            ClassTypePair ctp = (ctps.size() == 1) ? ctps.get(0) : null;
            if (ctp == null || CommonProfile.class.isAssignableFrom(ctp.rawClass())) {
                return optProfile.get();
            }
        }

        throw new IllegalStateException(
            "Cannot inject a Pac4J profile into a parameter of type " + parameter.getRawType().getName());
    }

    return null;
}
 
Example #26
Source File: RouterTest.java    From minnal with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldCreateContainerRequestFromHttpRequestWithHeaders() {
	request.headers().add("header1", "value1");
	request.headers().add("header2", Arrays.asList("value2", "value3"));
	ContainerRequest containerRequest = router.createContainerRequest(context);
	assertEquals(containerRequest.getHeaders().getFirst("header1"), "value1");
	assertEquals(containerRequest.getHeaders().get("header2"), Arrays.asList("value2", "value3"));
}
 
Example #27
Source File: SpanCustomizingApplicationEventListenerTest.java    From wingtips with Apache License 2.0 5 votes vote down vote up
@Before
public void beforeMethod() {
    implSpy = spy(SpanCustomizingApplicationEventListener.create());
    requestEventMock = mock(RequestEvent.class);
    requestMock = mock(ContainerRequest.class);
    extendedUriInfoMock = mock(ExtendedUriInfo.class);

    doReturn(RequestEvent.Type.REQUEST_MATCHED).when(requestEventMock).getType();
    doReturn(requestMock).when(requestEventMock).getContainerRequest();
    doReturn(extendedUriInfoMock).when(requestMock).getUriInfo();
}
 
Example #28
Source File: SpanCustomizingApplicationEventListener.java    From wingtips with Apache License 2.0 5 votes vote down vote up
/**
 * 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 RoutingContext#pushTemplates(UriTemplate, UriTemplate)}.
 * This code skips redundant slashes from either source caused by Path("/") or Path("").
 */
protected 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 #29
Source File: TestMediaTypeFilter.java    From dremio-oss with Apache License 2.0 5 votes vote down vote up
@Test
public void testHeaderIsUntouched() throws IOException {
  MediaTypeFilter filter = new MediaTypeFilter();
  ContainerRequest request = ContainerRequestBuilder.from("http://localhost/foo/bar", "GET", null).accept("random/media").build();
  filter.filter(request);

  assertEquals(1, request.getAcceptableMediaTypes().size());
  assertEquals(new AcceptableMediaType("random", "media"), request.getAcceptableMediaTypes().get(0));
}
 
Example #30
Source File: TestMediaTypeFilter.java    From dremio-oss with Apache License 2.0 5 votes vote down vote up
@Test
public void testHeaderChange() throws IOException {
  MediaTypeFilter filter = new MediaTypeFilter();
  ContainerRequest request = ContainerRequestBuilder.from("http://localhost/foo/bar?format=unit/test", "GET", null).accept("random/media").build();
  filter.filter(request);

  assertEquals(1, request.getAcceptableMediaTypes().size());
  assertEquals(new AcceptableMediaType("unit", "test"), request.getAcceptableMediaTypes().get(0));
}