/** * Lookup a resource of given <code>resourceType</code> type, either using a suitable {@link ContextResolver} if * <code>providers</code> is not <code>null</code> and a {@link ContextResolver} for given <code>resourceType</code> * is available, or trying to obtain the resource from {@link Context} using given <code>resourceType</code> as * context resource key. * @param <R> Resource type * @param caller Caller class * @param resourceType Resource type to lookup (not null) * @param providers JAX-RS {@link Providers}, if available * @return Resource instance, or an empty optional if not available */ public static <R> Optional<R> lookupResource(Class<?> caller, Class<R> resourceType, Providers providers) { ObjectUtils.argumentNotNull(resourceType, "Resource type must be not null"); R resource = null; // try to use a ContextResolver, if available ContextResolver<R> resolver = providers.getContextResolver(resourceType, null); if (resolver != null) { resource = resolver.getContext(caller); } if (resource == null) { // lookup in context resource = Context.get() .resource(resourceType, (caller != null) ? caller.getClassLoader() : ClassUtils.getDefaultClassLoader()) .orElse(null); } return Optional.ofNullable(resource); }
protected javax.ws.rs.core.Response davPropFind(Long id, UriInfo uriInfo, String depth, Providers providers) throws AuthenticationException, AuthorisationException, ServiceException { final Response folder = new Response(new HRef(uriInfo.getRequestUri()), null, null, null, new PropStat(new Prop(new DisplayName("My Collection"), new CreationDate(new Date()), new GetLastModified(new Date()), COLLECTION), new Status((StatusType) OK))); if (depth.equals(DEPTH_0) || id == null) { return javax.ws.rs.core.Response.status(MULTI_STATUS).entity(new MultiStatus(folder)).build(); } final Collection<Response> responses = new LinkedList<Response>(singletonList(folder)); Iterator<FileOutVO> it = WebUtil.getServiceLocator().getFileService().getFiles(getAuth(), getFileModule(), id, null, null, null).iterator(); if (it != null) { while (it.hasNext()) { FileOutVO out = it.next(); // responses.add(buildResponse(f, uriInfo.getAbsolutePathBuilder().path(format("%s", c.getMatchCode())).build(), providers)); FilePathSplitter filePath = new FilePathSplitter(out.getFileName()); String extension = filePath.getExtension(); if (isTempFile(extension) || isEditableFile(extension)) { responses.add(buildResponse(out, uriInfo.getAbsolutePathBuilder().path(getDavFileName(out)).build(), providers)); } } } return javax.ws.rs.core.Response.status(MULTI_STATUS).entity(new MultiStatus(responses.toArray(new Response[0]))).build(); }
@Test public void testLocateMostRelevantConstructor() { ReflectionProvider rp = instance(ReflectionProvider.class); Providers providers = instance(Providers.class); ProviderFilter providerFilter = instance(ProviderFilter.class); Field f = rp.getField(JaxRsResolverTest.class, "genericField3"); RuntimeDelegate.setInstance(new DefaultRuntimeDelegate()); MessageBodyReader messageBodyReader = providers.getMessageBodyReader(f.getType(), f.getGenericType(), f.getAnnotations(), MediaType.APPLICATION_XML_TYPE); assertNotNull(messageBodyReader); assertEquals(PersonMessageBodyReader.class, messageBodyReader.getClass()); Constructor<?> c = providerFilter.mostRelevantConstructor(messageBodyReader.getClass()); assertEquals(4, c.getParameterCount()); assertEquals("public com.geemvc.jaxrs.PersonMessageBodyReader(javax.ws.rs.core.Application,javax.ws.rs.core.UriInfo,javax.ws.rs.core.HttpHeaders,javax.ws.rs.ext.Providers)", c.toString()); }
@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); } }
/** * Returns the request content as the given type. IF the content is a collection, returns a list of elements of the given type * * @param request * @param type * @return */ public static Object getContent(byte[] raw, Providers providers, HttpHeaders httpHeaders, Class<?> type) { try { return getContent(new ByteArrayInputStream(raw), providers, httpHeaders, type, type, new Annotation[] {}); } catch (MinnalInstrumentationException e) { logger.trace("Failed while getting the content from the request stream", e); Throwable ex = e; while (ex.getCause() != null) { if (ex.getCause() instanceof IOException) { return getContent(new ByteArrayInputStream(raw), providers, httpHeaders, List.class, listType(type).getType(), new Annotation[]{}); } ex = ex.getCause(); } throw e; } }
@Test public void shouldGetContentAsList() throws Exception { List<String> list = Lists.newArrayList("test1", "test2", "test3"); byte[] bytes = new byte[10]; MediaType mediaType = mock(MediaType.class); HttpHeaders httpHeaders = mock(HttpHeaders.class); when(httpHeaders.getMediaType()).thenReturn(mediaType); MessageBodyReader reader = mock(MessageBodyReader.class); when(reader.readFrom(eq(String.class), eq(String.class), eq(new Annotation[]{}), eq(mediaType), isNull(MultivaluedMap.class), any(InputStream.class))).thenThrow(IOException.class); when(reader.readFrom(eq(List.class), any(Type.class), eq(new Annotation[]{}), eq(mediaType), isNull(MultivaluedMap.class), any(InputStream.class))).thenReturn(list); Providers providers = mock(Providers.class); when(providers.getMessageBodyReader(String.class, String.class, new Annotation[]{}, mediaType)).thenReturn(reader); when(providers.getMessageBodyReader(List.class, ResourceUtil.listType(String.class).getType(), new Annotation[]{}, mediaType)).thenReturn(reader); Object content = ResourceUtil.getContent(bytes, providers, httpHeaders, String.class); assertTrue(content instanceof List); assertEquals(content, list); }
@Test public void shouldGetContentAsMap() throws Exception { Map<String, Object> map = new HashMap<String, Object>(); map.put("key1", "value1"); byte[] bytes = new byte[10]; MediaType mediaType = mock(MediaType.class); HttpHeaders httpHeaders = mock(HttpHeaders.class); when(httpHeaders.getMediaType()).thenReturn(mediaType); MessageBodyReader reader = mock(MessageBodyReader.class); when(reader.readFrom(eq(Map.class), eq(Map.class), eq(new Annotation[]{}), eq(mediaType), isNull(MultivaluedMap.class), any(InputStream.class))).thenReturn(map); Providers providers = mock(Providers.class); when(providers.getMessageBodyReader(Map.class, Map.class, new Annotation[]{}, mediaType)).thenReturn(reader); Object content = ResourceUtil.getContent(bytes, providers, httpHeaders, Map.class); assertTrue(content instanceof Map); assertEquals(content, map); }
@Test public void shouldInvokeMethodWithArguments() throws Throwable { Map<String, Object> content = new HashMap<String, Object>(); content.put("value", "test123"); content.put("someNumber", 1L); Map<String, Object> values = new HashMap<String, Object>(); DummyModel model = new DummyModel(); byte[] bytes = new byte[10]; MediaType mediaType = mock(MediaType.class); HttpHeaders httpHeaders = mock(HttpHeaders.class); when(httpHeaders.getMediaType()).thenReturn(mediaType); MessageBodyReader reader = mock(MessageBodyReader.class); when(reader.readFrom(eq(Map.class), eq(Map.class), isNull(Annotation[].class), eq(mediaType), isNull(MultivaluedMap.class), any(InputStream.class))).thenReturn(content); Providers providers = mock(Providers.class); when(providers.getMessageBodyReader(Map.class, Map.class, null, mediaType)).thenReturn(reader); assertEquals(ResourceUtil.invokeAction(model, "dummyActionWithArguments", Lists.newArrayList(new ParameterMetaData("value", "value", String.class), new ParameterMetaData("someNumber", "someNumber", Long.class)), bytes, providers, httpHeaders, values), "dummyActionWithArguments"); }
@Test public void shouldInvokeMethodWithArgumentsAndModel() throws Throwable { Map<String, Object> content = new HashMap<String, Object>(); content.put("value", "test123"); content.put("someNumber", 1L); Map<String, Object> values = new HashMap<String, Object>(); values.put("anotherModel", new DummyModel()); DummyModel model = new DummyModel(); byte[] bytes = new byte[10]; MediaType mediaType = mock(MediaType.class); HttpHeaders httpHeaders = mock(HttpHeaders.class); when(httpHeaders.getMediaType()).thenReturn(mediaType); MessageBodyReader reader = mock(MessageBodyReader.class); when(reader.readFrom(eq(Map.class), eq(Map.class), isNull(Annotation[].class), eq(mediaType), isNull(MultivaluedMap.class), any(InputStream.class))).thenReturn(content); Providers providers = mock(Providers.class); when(providers.getMessageBodyReader(Map.class, Map.class, null, mediaType)).thenReturn(reader); assertEquals(ResourceUtil.invokeAction(model, "dummyActionWithArgumentsAndModel", Lists.newArrayList(new ParameterMetaData("anotherModel", "anotherModel", DummyModel.class), new ParameterMetaData("value", "value", String.class), new ParameterMetaData("someNumber", "someNumber", Long.class)), bytes, providers, httpHeaders, values), "dummyActionWithArgumentsAndModel"); }
@Test(expectedExceptions=MinnalInstrumentationException.class) public void shouldThrowExceptionIfMethodNotFound() throws Throwable { Map<String, Object> values = new HashMap<String, Object>(); DummyModel model = new DummyModel(); byte[] bytes = new byte[10]; MediaType mediaType = mock(MediaType.class); HttpHeaders httpHeaders = mock(HttpHeaders.class); when(httpHeaders.getMediaType()).thenReturn(mediaType); MessageBodyReader reader = mock(MessageBodyReader.class); when(reader.readFrom(eq(Map.class), eq(Map.class), isNull(Annotation[].class), eq(mediaType), isNull(MultivaluedMap.class), any(InputStream.class))).thenReturn(values); Providers providers = mock(Providers.class); when(providers.getMessageBodyReader(Map.class, Map.class, null, mediaType)).thenReturn(reader); ResourceUtil.invokeAction(model, "nonExistingMethod", Lists.newArrayList(new ParameterMetaData("anotherModel", "anotherModel", DummyModel.class)), bytes, providers, httpHeaders, values); }
@Test(expectedExceptions=IllegalStateException.class) public void shouldThrowExceptionIfMethodThrowsAnyException() throws Throwable { Map<String, Object> values = new HashMap<String, Object>(); DummyModel model = new DummyModel(); byte[] bytes = new byte[10]; MediaType mediaType = mock(MediaType.class); HttpHeaders httpHeaders = mock(HttpHeaders.class); when(httpHeaders.getMediaType()).thenReturn(mediaType); MessageBodyReader reader = mock(MessageBodyReader.class); when(reader.readFrom(eq(Map.class), eq(Map.class), isNull(Annotation[].class), eq(mediaType), isNull(MultivaluedMap.class), any(InputStream.class))).thenReturn(values); Providers providers = mock(Providers.class); when(providers.getMessageBodyReader(Map.class, Map.class, null, mediaType)).thenReturn(reader); ResourceUtil.invokeAction(model, "throwsException", new ArrayList<ParameterMetaData>(), bytes, providers, httpHeaders, values); }
private static Set<Class<?>> contextClasses() { final Set<Class<?>> classes = new HashSet<>(); classes.add(UriInfo.class); classes.add(SecurityContext.class); classes.add(HttpHeaders.class); classes.add(ContextResolver.class); classes.add(Providers.class); classes.add(Request.class); /* TODO: when we have jaxrs 2 classes.add(ResourceInfo.class); classes.add(ResourceContext.class); */ classes.add(Application.class); classes.add(HttpServletRequest.class); classes.add(HttpServletResponse.class); classes.add(ServletConfig.class); classes.add(ServletContext.class); classes.add(MessageContext.class); return classes; }
/** * Public ctor. */ public ResourceMocker() { final URI home = URI.create("http://localhost:9999/local"); this.withUriInfo(new UriInfoMocker().withRequestUri(home).mock()); final HttpServletRequest request = Mockito.mock(HttpServletRequest.class); Mockito.doReturn(home.getHost()).when(request).getRemoteAddr(); Mockito.doReturn(home.getPath()).when(request).getRequestURI(); Mockito.doReturn(home.getPath()).when(request).getContextPath(); this.withServletRequest(request); this.withHttpHeaders(new HttpHeadersMocker().mock()); final Providers providers = Mockito.mock(Providers.class); Mockito.doReturn(new XslResolver()) .when(providers) .getContextResolver( Marshaller.class, MediaType.APPLICATION_XML_TYPE ); this.withProviders(providers); final SecurityContext security = Mockito.mock(SecurityContext.class); this.withSecurityContext(security); this.withServletContext(new MkServletContext()); }
/** * BaseResource can set and return context elements. * @throws Exception If there is some problem inside */ @Test public void setsAndReturnsContextElements() throws Exception { final BaseResource res = new BaseResourceTest.FooResource(); final Providers provs = Mockito.mock(Providers.class); res.setProviders(provs); MatcherAssert.assertThat(res.providers(), Matchers.equalTo(provs)); final HttpHeaders headers = Mockito.mock(HttpHeaders.class); res.setHttpHeaders(headers); MatcherAssert.assertThat(res.httpHeaders(), Matchers.equalTo(headers)); final HttpServletRequest req = Mockito.mock(HttpServletRequest.class); res.setHttpServletRequest(req); MatcherAssert.assertThat( res.httpServletRequest(), Matchers.equalTo(req) ); final SecurityContext sctx = Mockito.mock(SecurityContext.class); res.setSecurityContext(sctx); MatcherAssert.assertThat(res.securityContext(), Matchers.equalTo(sctx)); final ServletContext vctx = Mockito.mock(ServletContext.class); res.setServletContext(vctx); MatcherAssert.assertThat(res.servletContext(), Matchers.equalTo(vctx)); }
@SuppressWarnings("unchecked") public static MimeBodyPart createBodyPart(Providers providers, SMIMEOutput out) throws IOException, MessagingException { ByteArrayOutputStream bodyOs = new ByteArrayOutputStream(); MessageBodyWriter writer = providers.getMessageBodyWriter(out.getType(), out.getGenericType(), null, out.getMediaType()); if (writer == null) { throw new RuntimeException("Failed to find writer for type: " + out.getType().getName()); } MultivaluedMap<String, String> bodyHeaders = new MultivaluedHashMap<String, String>(); bodyHeaders.add("Content-Type", out.getMediaType().toString()); writer.writeTo(out.getEntity(), out.getType(), out.getGenericType(), null, out.getMediaType(), bodyHeaders, bodyOs); InternetHeaders ih = new InternetHeaders(); for (Map.Entry<String, List<String>> entry : bodyHeaders.entrySet()) { for (String value : entry.getValue()) { ih.addHeader(entry.getKey(), value); } } return new MimeBodyPart(ih, bodyOs.toByteArray()); }
private static final Prop buildProp(final FileOutVO f, final Providers providers) { return new Prop(new GetETag(String.valueOf(f.getVersion())), new DisplayName(f.getFileName()), // format("%s %s", c.getLastName(), c.getFirstName())), new GetLastModified(f.getModifiedTimestamp()), new GetContentLength(f.getSize()), new GetContentType(f.getContentType().getMimeType())); }
protected javax.ws.rs.core.Response davPropPatch(InputStream body, UriInfo uriInfo, Providers providers, HttpHeaders httpHeaders) throws IOException { final PropertyUpdate propertyUpdate = providers.getMessageBodyReader(PropertyUpdate.class, PropertyUpdate.class, new Annotation[0], APPLICATION_XML_TYPE).readFrom(PropertyUpdate.class, PropertyUpdate.class, new Annotation[0], APPLICATION_XML_TYPE, httpHeaders.getRequestHeaders(), body); // System.out.println("PATCH PROPERTIES: " + propertyUpdate.list()); /* TODO Patch properties in database. */ final Collection<PropStat> propstats = new LinkedList<PropStat>(); for (final RemoveOrSet removeOrSet : propertyUpdate.list()) { propstats.add(new PropStat(removeOrSet.getProp(), new Status((StatusType) FORBIDDEN))); } return javax.ws.rs.core.Response.status(MULTI_STATUS) .entity(new MultiStatus(new Response(new HRef(uriInfo.getRequestUri()), null, null, null, propstats))).build(); }
@Test public void testLocateGensonContextResolver() { Providers providers = instance(Providers.class); RuntimeDelegate.setInstance(new DefaultRuntimeDelegate()); ContextResolver contextResolver = providers.getContextResolver(Genson.class, MediaType.APPLICATION_JSON_TYPE); assertNotNull(contextResolver); assertEquals(TestGensonContextResolver3.class, contextResolver.getClass()); }
@Test public void testLocateObjectContextResolver() { Providers providers = instance(Providers.class); RuntimeDelegate.setInstance(new DefaultRuntimeDelegate()); ContextResolver contextResolver = providers.getContextResolver(Person.class, MediaType.APPLICATION_JSON_TYPE); assertNotNull(contextResolver); assertEquals(TestGensonContextResolver6.class, contextResolver.getClass()); }
@Test public void testLocateApplicationContextResolver() { Providers providers = instance(Providers.class); RuntimeDelegate.setInstance(new DefaultRuntimeDelegate()); ContextResolver contextResolver = providers.getContextResolver(Application.class, MediaType.APPLICATION_JSON_TYPE); assertNotNull(contextResolver); assertEquals(TestApplicationContextResolver.class, contextResolver.getClass()); }
public RestEasyRequestContext(Providers providers, HttpRequest request) { super(providers, new RequestPac4JSecurityContext(ResteasyProviderFactory.getContextData(SecurityContext.class)).context() // if we went through a pac4j security filter .map(sc -> sc.getContext().getRequestContext()) // if not, we create a new ContainerRequestContext .orElse(new PreMatchContainerRequestContext(request))); }
public static <T> T getEntity(ClientMessage msg, Class<T> type, Type genericType, ResteasyProviderFactory factory) { int size = msg.getBodySize(); if (size <= 0) return null; byte[] body = new byte[size]; msg.getBodyBuffer().readBytes(body); String contentType = msg.getStringProperty(HttpHeaderProperty.CONTENT_TYPE); if (contentType == null) { throw new UnknownMediaType("Message did not have a Content-Type header cannot extract entity"); } MediaType ct = MediaType.valueOf(contentType); MessageBodyReader<T> reader = factory.getMessageBodyReader(type, genericType, null, ct); if (reader == null) { throw new UnmarshalException("Unable to find a JAX-RS reader for type " + type.getName() + " and media type " + contentType); } Providers current = ResteasyProviderFactory.getContextData(Providers.class); ResteasyProviderFactory.pushContext(Providers.class, factory); try { return reader.readFrom(type, genericType, null, ct, new Headers<String>(), new ByteArrayInputStream(body)); } catch (IOException e) { throw new RuntimeException(e); } finally { ResteasyProviderFactory.popContextData(Providers.class); if (current != null) ResteasyProviderFactory.pushContext(Providers.class, current); } }
@Inject public ProvidesResource(DaggerContainer daggerContainer, WebApplication webApplication, Providers providers, FeaturesAndProperties featuresAndProperties, MessageBodyWorkers messageBodyWorkers, ExceptionMapperContext exceptionMapperContext, ResourceContext resourceContext) { assertNotNull(daggerContainer); assertNotNull(webApplication); assertNotNull(providers); assertNotNull(featuresAndProperties); assertNotNull(messageBodyWorkers); assertNotNull(exceptionMapperContext); assertNotNull(resourceContext); }
@Override protected void configure() { Provider<Injector> injector = getProvider(Injector.class); bind(ServiceLocator.class).toProvider(new ServiceLocatorProvider(injector, locator)) .in(Singleton.class); Provider<ServiceLocator> provider = getProvider(ServiceLocator.class); bind(Application.class) .toProvider(new JerseyProvider<>(provider, Application.class)); bind(Providers.class) .toProvider(new JerseyProvider<>(provider, Providers.class)); bind(UriInfo.class) .toProvider(new JerseyProvider<>(provider, UriInfo.class)) .in(RequestScoped.class); bind(HttpHeaders.class) .toProvider(new JerseyProvider<>(provider, HttpHeaders.class)) .in(RequestScoped.class); bind(SecurityContext.class) .toProvider(new JerseyProvider<>(provider, SecurityContext.class)) .in(RequestScoped.class); bind(Request.class) .toProvider(new JerseyProvider<>(provider, Request.class)) .in(RequestScoped.class); }
public static SpearalFactory locateFactory(Configuration configuration, Providers providers) { ContextResolver<SpearalFactory> resolver = providers.getContextResolver(SpearalFactory.class, APPLICATION_SPEARAL_TYPE); if (resolver != null) return resolver.getContext(SpearalFactory.class); for (Object instance : configuration.getInstances()) { if (instance instanceof SpearalFactory) return (SpearalFactory)instance; } throw new RuntimeException("Could not locate SpearalFactory in JAX-RS context"); }
@Test public void shouldInvokeMethodWithNoArguments() throws Throwable { Map<String, Object> values = new HashMap<String, Object>(); DummyModel model = new DummyModel(); byte[] bytes = new byte[10]; MediaType mediaType = mock(MediaType.class); HttpHeaders httpHeaders = mock(HttpHeaders.class); when(httpHeaders.getMediaType()).thenReturn(mediaType); MessageBodyReader reader = mock(MessageBodyReader.class); when(reader.readFrom(eq(Map.class), eq(Map.class), isNull(Annotation[].class), eq(mediaType), isNull(MultivaluedMap.class), any(InputStream.class))).thenReturn(values); Providers providers = mock(Providers.class); when(providers.getMessageBodyReader(Map.class, Map.class, null, mediaType)).thenReturn(reader); assertEquals(ResourceUtil.invokeAction(model, "dummyAction", new ArrayList<ParameterMetaData>(), bytes, providers, httpHeaders, values), "dummy"); }
protected GedcomxXmlProvider(Providers ps, MediaType mt, Class<?> instanceClass, QName qName) { super(ps); this.rootClass = Gedcomx.class; this.mt = mt; this.qName = qName; this.instanceClass = instanceClass == null ? this.rootClass : instanceClass; }
public static Object findThreadLocal(final Class<?> type) { if (Request.class.equals(type)) { return REQUEST; } else if (UriInfo.class.equals(type)) { return URI_INFO; } else if (HttpHeaders.class.equals(type)) { return HTTP_HEADERS; } else if (SecurityContext.class.equals(type)) { return SECURITY_CONTEXT; } else if (ContextResolver.class.equals(type)) { return CONTEXT_RESOLVER; } else if (Providers.class.equals(type)) { return PROVIDERS; } else if (ServletRequest.class.equals(type)) { return SERVLET_REQUEST; } else if (HttpServletRequest.class.equals(type)) { return HTTP_SERVLET_REQUEST; } else if (HttpServletResponse.class.equals(type)) { return HTTP_SERVLET_RESPONSE; } else if (ServletConfig.class.equals(type)) { return SERVLET_CONFIG; } else if (ServletContext.class.equals(type)) { return SERVLET_CONTEXT; } else if (ResourceInfo.class.equals(type)) { return RESOURCE_INFO; } else if (ResourceContext.class.equals(type)) { return RESOURCE_CONTEXT; } else if (Application.class.equals(type)) { return APPLICATION; } else if (Configuration.class.equals(type)) { return CONFIGURATION; } return null; }
@Override @NotNull public final Providers providers() { this.assertNotNull( this.iproviders, "%[type]s#providers was never injected by JAX-RS" ); return this.iproviders; }
public static <T> T resolveFromContext(Providers providers, Class<T> clazz, MediaType mediaType, Class<?> type) { ContextResolver<T> contextResolver = providers.getContextResolver(clazz, mediaType); if (contextResolver == null) { throw new RestException("No context resolver found for class " + clazz.getName()); } return contextResolver.getContext(type); }
@Override @SuppressWarnings("unchecked") public T getContext(final Class<?> c) { final MinijaxRequestContext context = MinijaxRequestContext.getThreadLocal(); // 9.2.1 if (c == Application.class) { return (T) context.getApplication(); } // 9.2.2 if (c == UriInfo.class) { return (T) context.getUriInfo(); } // 9.2.3 if (c == HttpHeaders.class) { return (T) context.getHttpHeaders(); } // 9.2.4 if (c == Request.class) { return null; } // 9.2.5 if (c == SecurityContext.class) { return (T) context.getSecurityContext(); } // 9.2.6 if (c == Providers.class) { return (T) context.getApplication().getProviders(); } // 9.2.7 if (c == ResourceContext.class) { return null; } // 9.2.8 if (c == Configuration.class) { return (T) context.getApplication().getConfiguration(); } // 10.1 if (c == ServletConfig.class) { return null; } // 10.1 if (c == ServletContext.class) { return (T) context.getServletRequest().getServletContext(); } // 10.1 if (c == HttpServletRequest.class) { return (T) context.getServletRequest(); } // 10.1 if (c == HttpServletResponse.class) { return (T) context.getServletResponse(); } throw new IllegalArgumentException("Unrecognized @Context parameter: " + c); }
@GET @Path("/providers") public static String getProviders(@Context final Providers providers) { return "ok"; }
private static Response buildResponse(final FileOutVO file, final URI path, final Providers providers) { return new Response(new HRef(path), null, null, null, new PropStat(buildProp(file, providers), new Status((StatusType) OK))); }
protected javax.ws.rs.core.Response davPropFind(Long id, String fileName, UriInfo uriInfo, Providers providers) throws AuthenticationException, AuthorisationException, ServiceException { FileOutVO out = getFileFromDavFileName(id, fileName); return javax.ws.rs.core.Response.status(MULTI_STATUS) .entity(new MultiStatus(buildResponse(out, uriInfo.getAbsolutePathBuilder().build(), providers))).build(); }
@Override public void handle(Result result, RequestContext requestCtx) throws ServletException, IOException { HttpServletResponse response = (HttpServletResponse) requestCtx.getResponse(); if (result.length() > 0) { response.setContentLength((int) result.length()); } if (result.filename() != null) { if (result.attachment()) { response.setHeader("Content-disposition", "attachment; filename=" + result.filename()); } else { response.setHeader("Content-disposition", "filename=" + result.filename()); } } if (result.contentType() != null) { response.setContentType(result.contentType()); } if (result.rangeSupport()) { // TODO: range-support } if (result.result() != null) { RequestHandler requestHandler = requestCtx.requestHandler(); Method handlerMethod = requestHandler.handlerMethod(); if (configuration.isJaxRsEnabled()) { MessageBodyWriter mbw = injector.getInstance(Providers.class).getMessageBodyWriter(handlerMethod.getReturnType(), handlerMethod.getGenericReturnType(), handlerMethod.getAnnotations(), MediaType.valueOf(response.getContentType())); if (mbw != null && mbw.isWriteable(handlerMethod.getReturnType(), handlerMethod.getGenericReturnType(), handlerMethod.getAnnotations(), MediaType.valueOf(response.getContentType()))) { MultivaluedMap<String, Object> httpResponseHeaders = injector.getInstance(MultivaluedMap.class); mbw.writeTo(result.result(), handlerMethod.getReturnType(), handlerMethod.getGenericReturnType(), handlerMethod.getAnnotations(), MediaType.valueOf(response.getContentType()), httpResponseHeaders, response.getOutputStream()); } else { response.sendError(HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE); } } else { log.info("Unable to convert the result object of type '{}' to the media type '{}' as the JAX-RS runtime has been disabled.", () -> result.result().getClass().getName(), () -> response.getContentType()); response.sendError(HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE); } return; } if (result.stream() != null) { IOUtils.copy(result.stream(), response.getOutputStream()); } else if (result.reader() != null) { IOUtils.copy(result.reader(), response.getOutputStream(), result.characterEncoding()); } else if (result.output() != null) { response.getOutputStream().write(result.output().getBytes()); } else { throw new IllegalStateException("You must provide either a stream, a reader or a string output when using Results.stream(). "); } }
@Inject public DefaultJaxRsResponseHandler(Application application, Providers providers) { this.application = application; this.providers = providers; }
protected void configureJaxRSProviders() { if (configuration() == null || configuration().isJaxRsEnabled()) bind(Providers.class).to(DefaultProviders.class); }
public PersonMessageBodyReader(@Context Application application, @Context UriInfo uriInfo, @Context HttpHeaders httpHeaders, @Context Providers providers) { ContextResolver<Genson> gensonResolver = providers.getContextResolver(Genson.class, MediaType.APPLICATION_JSON_TYPE); gensonResolver.getContext(Genson.class); }
public UncheckedExecutionExceptionMapper(@Context Providers providers) { _providers = providers; }
public PartitionForwardingExceptionMapper(@Context Providers providers) { _providers = providers; }