@Override public void filter(ContainerRequestContext requestContext) { if (requestContext instanceof ContainerRequest) { final Principal principal = (Principal) requestContext.getProperty("Principal"); if (principal == null) { requestContext.abortWith(Response.status(Response.Status.UNAUTHORIZED).build()); return; } final PermissionRequired annotation = resourceInfo.getResourceMethod().getDeclaredAnnotation(PermissionRequired.class); try (AlpineQueryManager qm = new AlpineQueryManager()) { if (principal instanceof LdapUser) { final LdapUser user = qm.getLdapUser(((LdapUser) principal).getUsername()); final String[] permissions = annotation.value(); for (String permission: permissions) { // todo check if user has one of these required permissions } } } } }
@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 } }
@POST @Consumes({ MediaType.APPLICATION_JSON }) @Produces(MediaType.TEXT_HTML) public Response newDetectionRule(@Context ContainerRequest request, DetectionRule rule){ OrganizationDAO pd = DAOUtil.getOrganizationDAO(); List<OrganizationProfile> os = pd.getAllActiveOrganizations(); assert(os != null && !os.isEmpty()); rule.setOrganizationId(os.get(0).getId()); DetectionRuleDAO dao = DAOUtil.getDetectionRuleDAO(); try { Integer id = dao.addDetectionRule(rule); String url = request.getUriInfo().getRequestUri().toASCIIString(); return Response.status(Response.Status.CREATED)// 201 .entity("A new detection rule has been created") .header("Location", url + "/" + String.valueOf(id)).build(); } catch (Exception ex) { // TODO: error handling return Response.serverError().build(); //return "Failure"; } }
@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."); } }); }
@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(); }
@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()); }
@SuppressWarnings("unchecked") private RequestScopedInitializer getSetRequestScopedInitializer(Context context, GatewayRequest request) { GatewayRequestAndLambdaContext reqAndContext = new GatewayRequestAndLambdaContext(request, context); ArgumentCaptor<Consumer<ContainerRequest>> containerEnhancerCaptor = ArgumentCaptor.forClass(Consumer.class); gatewayHandler.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(); }
@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."); } }); }
@SuppressWarnings({ "unchecked", "rawtypes" }) private RequestScopedInitializer getSetRequestScopedInitializer(Context context, SNSRecord snsRecord) { SnsRecordAndLambdaContext reqAndContext = new SnsRecordAndLambdaContext(snsRecord, context); ArgumentCaptor<Consumer> containerEnhancerCaptor = ArgumentCaptor.forClass(Consumer.class); snsHandler.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(); }
/** * 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); } }); }
/** * 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; }
@Test public void createContainerRequest_RequestAndContainerResponseWriterAndSecurityContextGiven_ShouldCreateContainerRequestUsingValues() { URI baseUri = URI.create("/"); URI requestUri = URI.create("/entity"); String httpMethod = "POST"; ByteArrayInputStream entityStream = new ByteArrayInputStream(new byte[0]); MultivaluedMap<String, String> headers = new MultivaluedHashMap<>(); headers.add("hk0", "hv0_0"); headers.add("hk0", "hv0_1"); headers.add("hk1", "hv1_0"); JRestlessContainerRequest request = createRequest(baseUri, requestUri, httpMethod, entityStream, headers); ContainerResponseWriter containerResponseWriter = mock(ContainerResponseWriter.class); SecurityContext securityContext = mock(SecurityContext.class); ContainerRequest containerRequest = container.createContainerRequest(request, containerResponseWriter, securityContext); assertEquals(baseUri, containerRequest.getBaseUri()); assertEquals(requestUri, containerRequest.getRequestUri()); assertEquals(httpMethod, containerRequest.getMethod()); assertSame(entityStream, containerRequest.getEntityStream()); assertEquals(headers, containerRequest.getHeaders()); assertSame(containerResponseWriter, containerRequest.getResponseWriter()); assertSame(securityContext, containerRequest.getSecurityContext()); }
@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)); }
@Override public void onEvent(RequestEvent event) { switch (event.getType()) { case RESOURCE_METHOD_START: ExtendedUriInfo uriInfo = event.getUriInfo(); ResourceMethod method = uriInfo.getMatchedResourceMethod(); ContainerRequest containerRequest = event.getContainerRequest(); LOG.info(requestNumber+" Resource method " + method.getHttpMethod() + " started for request " + requestNumber); LOG.info(requestNumber+" Headers: "+ render(containerRequest.getHeaders())); LOG.info(requestNumber+" Path: "+uriInfo.getPath()); LOG.info(requestNumber+" PathParameters: "+ render(uriInfo.getPathParameters())); LOG.info(requestNumber+" QueryParameters: "+ render(uriInfo.getQueryParameters())); LOG.info(requestNumber+" Body: "+getBody(containerRequest)); break; case FINISHED: LOG.info("Request " + requestNumber + " finished. Processing time " + (System.currentTimeMillis() - startTime) + " ms."); break; default: break; } }
public JaxRsRequest createRequestDetails() throws URISyntaxException { //headers headers = new ContainerRequest(new URI(BASEURI), new URI(REQUESTURI), HttpMethod.GET, null, new MapPropertiesDelegate()); //uri info UriInfo uriInfo = mock(UriInfo.class); when(uriInfo.getQueryParameters()).thenReturn(queryParameters); //mocks provider = spy(TestJaxRsDummyPatientProviderDstu3.class); doReturn(uriInfo).when(provider).getUriInfo(); doReturn(BASEURI).when(provider).getBaseForRequest(); doReturn(BASEURI).when(provider).getBaseForServer(); doReturn(headers).when(provider).getHeaders(); return new JaxRsRequest(provider, RESOURCE_STRING, RequestTypeEnum.GET, RestOperationTypeEnum.HISTORY_TYPE); }
public JaxRsRequest createRequestDetails() throws URISyntaxException { //headers headers = new ContainerRequest(new URI(BASEURI), new URI(REQUESTURI), HttpMethod.GET, null, new MapPropertiesDelegate()); //uri info UriInfo uriInfo = mock(UriInfo.class); when(uriInfo.getQueryParameters()).thenReturn(queryParameters); //mocks provider = spy(TestJaxRsDummyPatientProvider.class); doReturn(uriInfo).when(provider).getUriInfo(); doReturn(BASEURI).when(provider).getBaseForRequest(); doReturn(BASEURI).when(provider).getBaseForServer(); doReturn(headers).when(provider).getHeaders(); return new JaxRsRequest(provider, RESOURCE_STRING, RequestTypeEnum.GET, RestOperationTypeEnum.HISTORY_TYPE); }
@Override protected void configure() { jerseyToGuice(MultivaluedParameterExtractorProvider.class); jerseyToGuice(Application.class); jerseyToGuice(Providers.class); // request scoped objects, but hk will control their scope // must be used in guice only with Provider 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); } }
@Test public void testUnregister() throws Exception { Credentials user = AuthenticationEndpointTest.signUpUser(this); PublicKey key = AuthenticationEndpointTest.getPublicKey(this); Response tokenResponse = registerToken(user, key, this); String newAuthToken = tokenResponse.getHeaderString("Authorization"); Response response = target("/push") .request() .header(ContainerRequest.AUTHORIZATION, "CUSTOM " + newAuthToken) .delete(); int statusCode = response.getStatus(); assertEquals(200,statusCode); Collection<TransientObject> list = container.serverDao.get(Query.safeTable(Credentials.class),user.getObjectKey()); TransientObject o = ObjectUtils.get1stOrNull(list); user = TestUtils.convert(o,Credentials.class); assertNotNull(user); assertEquals("", user.getPushMessagingKey()); // check the token was actually saved }
/** * <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; }
@Override public void aroundWriteTo(WriterInterceptorContext context) throws IOException,WebApplicationException { ContainerRequest request = requestProvider.get(); if (request != null) { List<String> aeHeaders = request.getRequestHeader(HttpHeaders.ACCEPT_ENCODING); if (aeHeaders != null && aeHeaders.size() > 0) { String acceptEncodingHeader = aeHeaders.get(0); if (acceptEncodingHeader.contains(GZIP)) { OutputStream outputStream = context.getOutputStream(); context.setOutputStream(new GZIPOutputStream(outputStream)); context.getHeaders().putSingle(HttpHeaders.CONTENT_ENCODING, GZIP); } } } context.proceed(); }
/** * Demonstrates that when the {@link FedoraBaseResource#JMS_BASEURL_PROP fcrepo.jms.baseUrl} system property is not * set, the url used for JMS messages is the same as the base url found in the {@code UriInfo}. * <p> * Implementation note: this test requires a concrete instance of {@link UriInfo}, because it is the interaction of * {@code javax.ws.rs.core.UriBuilder} and {@code FedoraBaseResource} that is being tested. * </p> */ @Test public void testJmsBaseUrlDefault() { // Obtain a concrete instance of UriInfo final URI baseUri = create("http://localhost/fcrepo"); final URI requestUri = create("http://localhost/fcrepo/foo"); final ContainerRequest req = new ContainerRequest(baseUri, requestUri, "GET", mock(SecurityContext.class), mock(PropertiesDelegate.class)); final UriInfo info = spy(req.getUriInfo()); final String expectedBaseUrl = baseUri.toString(); testObj.setUpJMSInfo(info, mockHeaders); verify(mockFedoraSession).addSessionData(BASE_URL, expectedBaseUrl); verify(info, times(0)).getBaseUriBuilder(); verify(info).getBaseUri(); }
/** * Demonstrates that the host supplied by the {@link FedoraBaseResource#JMS_BASEURL_PROP fcrepo.jms.baseUrl} system * property is used as the as the base url for JMS messages, and not the base url found in {@code UriInfo}. * <p> * Note: the path from the request is preserved, the host from the fcrepo.jms.baseUrl is used * </p> * <p> * Implementation note: this test requires a concrete instance of {@link UriInfo}, because it is the interaction of * {@code javax.ws.rs.core.UriBuilder} and {@code FedoraBaseResource} that is being tested. * </p> */ @Test public void testJmsBaseUrlOverrideHost() { // Obtain a concrete implementation of UriInfo final URI baseUri = create("http://localhost/fcrepo"); final URI requestUri = create("http://localhost/fcrepo/foo"); final ContainerRequest req = new ContainerRequest(baseUri, requestUri, "GET", mock(SecurityContext.class), mock(PropertiesDelegate.class)); final UriInfo info = spy(req.getUriInfo()); final String baseUrl = "http://example.org"; final String expectedBaseUrl = baseUrl + baseUri.getPath(); System.setProperty(JMS_BASEURL_PROP, baseUrl); testObj.setUpJMSInfo(info, mockHeaders); verify(mockFedoraSession).addSessionData(BASE_URL, expectedBaseUrl); verify(info).getBaseUriBuilder(); System.clearProperty(JMS_BASEURL_PROP); }
/** * Demonstrates that the host and port supplied by the {@link FedoraBaseResource#JMS_BASEURL_PROP * fcrepo.jms.baseUrl} system property is used as the as the base url for JMS messages, and not the base url found * in {@code UriInfo}. * <p> * Note: the path from the request is preserved, but the host and port from the request is overridden by the values * from fcrepo.jms.baseUrl * </p> * <p> * Implementation note: this test requires a concrete instance of {@link UriInfo}, because it is the interaction of * {@code javax.ws.rs.core.UriBuilder} and {@code FedoraBaseResource} that is being tested. * </p> */ @Test public void testJmsBaseUrlOverrideHostAndPort() { // Obtain a concrete implementation of UriInfo final URI baseUri = create("http://localhost/fcrepo"); final URI requestUri = create("http://localhost/fcrepo/foo"); final ContainerRequest req = new ContainerRequest(baseUri, requestUri, "GET", mock(SecurityContext.class), mock(PropertiesDelegate.class)); final UriInfo info = spy(req.getUriInfo()); final String baseUrl = "http://example.org:9090"; final String expectedBaseUrl = baseUrl + baseUri.getPath(); System.setProperty(JMS_BASEURL_PROP, baseUrl); testObj.setUpJMSInfo(info, mockHeaders); verify(mockFedoraSession).addSessionData(BASE_URL, expectedBaseUrl); verify(info).getBaseUriBuilder(); System.clearProperty(JMS_BASEURL_PROP); }
/** * Demonstrates that the url supplied by the {@link FedoraBaseResource#JMS_BASEURL_PROP fcrepo.jms.baseUrl} system * property is used as the as the base url for JMS messages, and not the base url found in {@code UriInfo}. * <p> * Note: the host and path from the request is overridden by the values from fcrepo.jms.baseUrl * </p> * <p> * Implementation note: this test requires a concrete instance of {@link UriInfo}, because it is the interaction of * {@code javax.ws.rs.core.UriBuilder} and {@code FedoraBaseResource} that is being tested. * </p> */ @Test public void testJmsBaseUrlOverrideUrl() { // Obtain a concrete implementation of UriInfo final URI baseUri = create("http://localhost/fcrepo"); final URI requestUri = create("http://localhost/fcrepo/foo"); final ContainerRequest req = new ContainerRequest(baseUri, requestUri, "GET", mock(SecurityContext.class), mock(PropertiesDelegate.class)); final UriInfo info = spy(req.getUriInfo()); final String expectedBaseUrl = "http://example.org/fcrepo/rest"; System.setProperty(JMS_BASEURL_PROP, expectedBaseUrl); testObj.setUpJMSInfo(info, mockHeaders); verify(mockFedoraSession).addSessionData(BASE_URL, expectedBaseUrl); verify(info).getBaseUriBuilder(); System.clearProperty(JMS_BASEURL_PROP); }
/** * Demonstrates that when the the base url in {@code UriInfo} contains a port number, and the base url defined by * {@link FedoraBaseResource#JMS_BASEURL_PROP fcrepo.jms.baseUrl} does <em>not</em> contain a port number, that the * base url for JMS messages does not contain a port number. * <p> * Note: the host, port, and path from the request is overridden by values from fcrepo.jms.baseUrl * </p> * <p> * Implementation note: this test requires a concrete instance of {@link UriInfo}, because it is the interaction of * {@code javax.ws.rs.core.UriBuilder} and {@code FedoraBaseResource} that is being tested. * </p> */ @Test public void testJmsBaseUrlOverrideRequestUrlWithPort8080() { // Obtain a concrete implementation of UriInfo final URI baseUri = create("http://localhost:8080/fcrepo/rest"); final URI reqUri = create("http://localhost:8080/fcrepo/rest/foo"); final ContainerRequest req = new ContainerRequest(baseUri, reqUri, "GET", mock(SecurityContext.class), mock(PropertiesDelegate.class)); final UriInfo info = spy(req.getUriInfo()); final String expectedBaseUrl = "http://example.org/fcrepo/rest/"; System.setProperty(JMS_BASEURL_PROP, expectedBaseUrl); testObj.setUpJMSInfo(info, mockHeaders); verify(mockFedoraSession).addSessionData(BASE_URL, expectedBaseUrl); verify(info).getBaseUriBuilder(); System.clearProperty(JMS_BASEURL_PROP); }
@Override public void onEvent(RequestEvent event) { ContainerRequest containerRequest = event.getContainerRequest(); Set<Timed> timedAnnotations; switch (event.getType()) { case ON_EXCEPTION: if(!(event.getException() instanceof NotFoundException)) { break; } case REQUEST_MATCHED: timedAnnotations = annotations(event); timedAnnotationsOnRequest.put(containerRequest, timedAnnotations); shortTaskSample.put(containerRequest, Timer.start(registry)); List<LongTaskTimer.Sample> longTaskSamples = longTaskTimers(timedAnnotations, event).stream().map(LongTaskTimer::start).collect(Collectors.toList()); if (!longTaskSamples.isEmpty()) { this.longTaskSamples.put(containerRequest, longTaskSamples); } break; case FINISHED: timedAnnotations = timedAnnotationsOnRequest.remove(containerRequest); Timer.Sample shortSample = shortTaskSample.remove(containerRequest); if (shortSample != null) { for (Timer timer : shortTimers(timedAnnotations, event)) { shortSample.stop(timer); } } Collection<LongTaskTimer.Sample> longSamples = this.longTaskSamples.remove(containerRequest); if (longSamples != null) { for (LongTaskTimer.Sample longSample : longSamples) { longSample.stop(); } } break; } }
private static RequestEvent event(String method, Integer status, Exception exception, String baseUri, String... uriTemplateStrings) { Builder builder = new RequestEventImpl.Builder(); ContainerRequest containerRequest = mock(ContainerRequest.class); when(containerRequest.getMethod()).thenReturn(method); builder.setContainerRequest(containerRequest); ContainerResponse containerResponse = mock(ContainerResponse.class); when(containerResponse.getStatus()).thenReturn(status); builder.setContainerResponse(containerResponse); builder.setException(exception, null); ExtendedUriInfo extendedUriInfo = mock(ExtendedUriInfo.class); when(extendedUriInfo.getBaseUri()).thenReturn( URI.create("http://localhost:8080" + (baseUri == null ? "/" : baseUri))); List<UriTemplate> uriTemplates = uriTemplateStrings == null ? Collections.emptyList() : Arrays.stream(uriTemplateStrings).map(uri -> new UriTemplate(uri)) .collect(Collectors.toList()); // UriTemplate are returned in reverse order Collections.reverse(uriTemplates); when(extendedUriInfo.getMatchedTemplates()).thenReturn(uriTemplates); builder.setExtendedUriInfo(extendedUriInfo); return builder.build(Type.FINISHED); }
@Test public void testJSONGeneratorConfigured() throws IOException { JSONPrettyPrintFilter filter = new JSONPrettyPrintFilter(); ContainerRequest request = ContainerRequestBuilder.from("http://localhost/foo/bar?pretty", "GET").accept("random/media").build(); ContainerResponse response = new ContainerResponse(request, Response.ok().build()); filter.filter(request, response); ObjectWriterModifier modifier = ObjectWriterInjector.get(); assertNotNull(modifier); JsonGenerator g = mock(JsonGenerator.class); modifier.modify(mock(JsonEndpointConfig.class), new MultivaluedHashMap<String, Object>(), new Object(), mock(ObjectWriter.class), g); verify(g).useDefaultPrettyPrinter(); }
@Test public void testJSONGeneratorUntouched() throws IOException { JSONPrettyPrintFilter filter = new JSONPrettyPrintFilter(); ContainerRequest request = ContainerRequestBuilder.from("http://localhost/foo/bar", "GET").accept("random/media").build(); ContainerResponse response = new ContainerResponse(request, Response.ok().build()); filter.filter(request, response); ObjectWriterModifier modifier = ObjectWriterInjector.get(); assertNull(modifier); }
@Test public void testHeaderChange() throws IOException { MediaTypeFilter filter = new MediaTypeFilter(); ContainerRequest request = ContainerRequestBuilder.from("http://localhost/foo/bar?format=unit/test", "GET").accept("random/media").build(); filter.filter(request); assertEquals(1, request.getAcceptableMediaTypes().size()); assertEquals(new AcceptableMediaType("unit", "test"), request.getAcceptableMediaTypes().get(0)); }
@Test public void testHeaderIsUntouched() throws IOException { MediaTypeFilter filter = new MediaTypeFilter(); ContainerRequest request = ContainerRequestBuilder.from("http://localhost/foo/bar", "GET").accept("random/media").build(); filter.filter(request); assertEquals(1, request.getAcceptableMediaTypes().size()); assertEquals(new AcceptableMediaType("random", "media"), request.getAcceptableMediaTypes().get(0)); }
@PUT @Consumes({ MediaType.APPLICATION_JSON }) @Produces(MediaType.TEXT_HTML) @Path("/classification") public Response newEndpointConfiguration(@Context ContainerRequest request, AlertClassification a){ DecisionDAO dao = DAOUtil.getDecisionDAO(); dao.setClassification(a.getAlertId(), a.getClassification()); // return Response.ok().build(); }
/** * Private constructor for a LambdaContainer. Sets the application object, sets the ApplicationHandler, * and initializes the application using the <code>onStartup</code> method. * @param requestReader A request reader instance * @param responseWriter A response writer instance * @param securityContextWriter A security context writer object * @param exceptionHandler An exception handler * @param jaxRsApplication The JaxRs application */ public JerseyLambdaContainerHandler(RequestReader<RequestType, ContainerRequest> requestReader, ResponseWriter<JerseyResponseWriter, ResponseType> responseWriter, SecurityContextWriter<RequestType> securityContextWriter, ExceptionHandler<ResponseType> exceptionHandler, Application jaxRsApplication) { super(requestReader, responseWriter, securityContextWriter, exceptionHandler); this.jaxRsApplication = jaxRsApplication; this.applicationHandler = new ApplicationHandler(jaxRsApplication); applicationHandler.onStartup(this); }
@Override protected void extendActualJerseyContainerRequest(ContainerRequest actualContainerRequest, JRestlessContainerRequest containerRequest, WebActionRequest request) { actualContainerRequest.setRequestScopedInitializer(locator -> { Ref<WebActionRequest> webActionRequestRef = locator .<Ref<WebActionRequest>>getInstance(WEB_ACTION_REQUEST_TYPE); if (webActionRequestRef != null) { webActionRequestRef.set(request); } else { LOG.error("WebActionBinder has not been registered. WebActionRequest injection won't work."); } }); }
@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(); }
/** * Delegates the container request to the application. * * @param request * container request. */ protected void handleRequest(@Nonnull ContainerRequest request) { requireNonNull(request, "request may not be null"); try { appHandler.handle(request); } catch (Exception e) { LOG.error("failed to handle request", e); throw e; } }
@Override public void filter(ContainerRequestContext requestContext) throws IOException { if (webRequest.getSession(false) == null || webRequest.getSession(false).getAttribute(LOGIN_SESSION_KEY)==null ) { if ( !((ContainerRequest) requestContext).getPath(true).equals("login") && !((ContainerRequest) requestContext).getPath(true).equals("locales") && !((ContainerRequest) requestContext).getPath(true).equals("metaData") && !((ContainerRequest) requestContext).getPath(true).equals("views") && !((ContainerRequest) requestContext).getPath(true).equals("guimodel") ) { requestContext.abortWith(Response.status(Response.Status.UNAUTHORIZED).type(MediaType.TEXT_PLAIN_TYPE).entity("User cannot access the resource.").build()); } } }
@Test public void testProcess() throws Exception { RestTriggerResource resource = new RestTriggerResource(); RestTriggerResource.Process process = resource.redirectToProcess(); ProcessBackend backend = new ProcessBackend(); TriggerService service = Mockito.mock(TriggerService.class); backend.setService(service); resource.setProcessBackend(backend); 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)); ProcessRepresentation content = new ProcessRepresentation(); content.setComment("abc"); Response response = process.putApprove(request, params); assertEquals(Response.Status.NO_CONTENT.getStatusCode(), response.getStatus()); response = process.putReject(request, content, params); assertEquals(Response.Status.NO_CONTENT.getStatusCode(), response.getStatus()); }
private static CharSequence getBody(ContainerRequest request) { String body = null; try { body = IOUtils.toString(request.getEntityStream()); // reading the stream consumes it, need to re-create it for the real thing request.setEntityStream(new StringInputStream(body)); } catch (IOException e) { LOG.warn("Couldn't ready body.", e); } return body; }
public Client provide(ContainerRequest request) { Optional<String> possibleClientName = getClientName(request); if (!possibleClientName.isPresent()) { throw new NotAuthorizedException("ClientCert not authorized as a Client"); } String clientName = possibleClientName.get(); try { return authenticator.authenticate(clientName) .orElseThrow(() -> new NotAuthorizedException( format("ClientCert name %s not authorized as a Client", clientName))); } catch (AuthenticationException e) { throw Throwables.propagate(e); } }