Search in sources :

Example 16 with Providers

use of javax.ws.rs.ext.Providers in project jersey by eclipse-ee4j.

the class JaxrsProvidersTest method testProviders.

@Test
public void testProviders() throws Exception {
    InjectionManager injectionManager = Injections.createInjectionManager();
    injectionManager.register(new MessagingBinders.MessageBodyProviders(null, RuntimeType.SERVER));
    injectionManager.register(new Binder());
    BootstrapBag bootstrapBag = new BootstrapBag();
    List<BootstrapConfigurator> bootstrapConfigurators = Arrays.asList(new RequestScope.RequestScopeConfigurator(), new TestConfigConfigurator(), new ContextResolverFactory.ContextResolversConfigurator(), new MessageBodyFactory.MessageBodyWorkersConfigurator(), new ExceptionMapperFactory.ExceptionMappersConfigurator(), new JaxrsProviders.ProvidersConfigurator());
    injectionManager.register(new TestBinder());
    TestBinder.initProviders(injectionManager);
    bootstrapConfigurators.forEach(configurator -> configurator.init(injectionManager, bootstrapBag));
    injectionManager.completeRegistration();
    bootstrapConfigurators.forEach(configurator -> configurator.postInit(injectionManager, bootstrapBag));
    RequestScope scope = bootstrapBag.getRequestScope();
    scope.runInScope((Callable<Object>) () -> {
        Providers instance = injectionManager.getInstance(Providers.class);
        assertNotNull(instance);
        assertSame(JaxrsProviders.class, instance.getClass());
        assertNotNull(instance.getExceptionMapper(Throwable.class));
        assertNotNull(instance.getMessageBodyReader(String.class, String.class, new Annotation[0], MediaType.TEXT_PLAIN_TYPE));
        assertNotNull(instance.getMessageBodyWriter(String.class, String.class, new Annotation[0], MediaType.TEXT_PLAIN_TYPE));
        assertNotNull(instance.getContextResolver(String.class, MediaType.TEXT_PLAIN_TYPE));
        return null;
    });
}
Also used : BootstrapConfigurator(org.glassfish.jersey.internal.BootstrapConfigurator) MessagingBinders(org.glassfish.jersey.message.internal.MessagingBinders) BootstrapBag(org.glassfish.jersey.internal.BootstrapBag) JaxrsProviders(org.glassfish.jersey.internal.JaxrsProviders) Providers(javax.ws.rs.ext.Providers) JaxrsProviders(org.glassfish.jersey.internal.JaxrsProviders) RequestScope(org.glassfish.jersey.process.internal.RequestScope) MessageBodyFactory(org.glassfish.jersey.message.internal.MessageBodyFactory) AbstractBinder(org.glassfish.jersey.internal.inject.AbstractBinder) ContextResolverFactory(org.glassfish.jersey.internal.ContextResolverFactory) ExceptionMapperFactory(org.glassfish.jersey.internal.ExceptionMapperFactory) InjectionManager(org.glassfish.jersey.internal.inject.InjectionManager) Test(org.junit.Test)

Example 17 with Providers

use of javax.ws.rs.ext.Providers in project quarkus by quarkusio.

the class ResteasyCommonProcessor method setupProviders.

@BuildStep
JaxrsProvidersToRegisterBuildItem setupProviders(BuildProducer<ReflectiveClassBuildItem> reflectiveClass, CombinedIndexBuildItem indexBuildItem, BeanArchiveIndexBuildItem beanArchiveIndexBuildItem, BuildProducer<UnremovableBeanBuildItem> unremovableBeans, List<ResteasyJaxrsProviderBuildItem> contributedProviderBuildItems, List<RestClientBuildItem> restClients, ResteasyConfigBuildItem resteasyConfig, Capabilities capabilities) throws Exception {
    Set<String> contributedProviders = new HashSet<>();
    for (ResteasyJaxrsProviderBuildItem contributedProviderBuildItem : contributedProviderBuildItems) {
        contributedProviders.add(contributedProviderBuildItem.getName());
    }
    Set<String> annotatedProviders = new HashSet<>();
    for (AnnotationInstance i : indexBuildItem.getIndex().getAnnotations(ResteasyDotNames.PROVIDER)) {
        if (i.target().kind() == AnnotationTarget.Kind.CLASS) {
            annotatedProviders.add(i.target().asClass().name().toString());
        }
        checkProperConfigAccessInProvider(i);
    }
    contributedProviders.addAll(annotatedProviders);
    Set<String> availableProviders = new HashSet<>(ServiceUtil.classNamesNamedIn(getClass().getClassLoader(), "META-INF/services/" + Providers.class.getName()));
    // this one is added manually in RESTEasy's ResteasyDeploymentImpl
    availableProviders.add(ServerFormUrlEncodedProvider.class.getName());
    MediaTypeMap<String> categorizedReaders = new MediaTypeMap<>();
    MediaTypeMap<String> categorizedWriters = new MediaTypeMap<>();
    MediaTypeMap<String> categorizedContextResolvers = new MediaTypeMap<>();
    Set<String> otherProviders = new HashSet<>();
    categorizeProviders(availableProviders, categorizedReaders, categorizedWriters, categorizedContextResolvers, otherProviders);
    // add the other providers detected
    Set<String> providersToRegister = new HashSet<>(otherProviders);
    if (!capabilities.isPresent(Capability.VERTX) && !capabilities.isCapabilityWithPrefixPresent(Capability.RESTEASY_JSON)) {
        boolean needJsonSupport = restJsonSupportNeeded(indexBuildItem, ResteasyDotNames.CONSUMES) || restJsonSupportNeeded(indexBuildItem, ResteasyDotNames.PRODUCES) || restJsonSupportNeeded(indexBuildItem, ResteasyDotNames.RESTEASY_SSE_ELEMENT_TYPE) || restJsonSupportNeeded(indexBuildItem, ResteasyDotNames.RESTEASY_PART_TYPE);
        if (needJsonSupport) {
            LOGGER.warn("Quarkus detected the need of REST JSON support but you have not provided the necessary JSON " + "extension for this. You can visit https://quarkus.io/guides/rest-json for more " + "information on how to set one.");
        }
    }
    if (!capabilities.isPresent(Capability.RESTEASY_MUTINY)) {
        String needsMutinyClasses = mutinySupportNeeded(indexBuildItem);
        if (needsMutinyClasses != null) {
            LOGGER.warn("Quarkus detected the need for Mutiny reactive programming support, however the quarkus-resteasy-mutiny extension " + "was not present. Reactive REST endpoints in your application that return Uni or Multi " + "will not function as you expect until you add this extension. Endpoints that need Mutiny are: " + needsMutinyClasses);
        }
    }
    // we add a couple of default providers
    providersToRegister.add(StringTextStar.class.getName());
    providersToRegister.addAll(categorizedWriters.getPossible(MediaType.APPLICATION_JSON_TYPE));
    IndexView index = indexBuildItem.getIndex();
    IndexView beansIndex = beanArchiveIndexBuildItem.getIndex();
    // find the providers declared in our services
    boolean useBuiltinProviders = collectDeclaredProviders(restClients, resteasyConfig, providersToRegister, categorizedReaders, categorizedWriters, categorizedContextResolvers, index, beansIndex);
    if (useBuiltinProviders) {
        providersToRegister = new HashSet<>(contributedProviders);
        providersToRegister.addAll(availableProviders);
    } else {
        providersToRegister.addAll(contributedProviders);
    }
    if (providersToRegister.contains("org.jboss.resteasy.plugins.providers.jsonb.JsonBindingProvider")) {
        // This abstract one is also accessed directly via reflection
        reflectiveClass.produce(new ReflectiveClassBuildItem(true, true, "org.jboss.resteasy.plugins.providers.jsonb.AbstractJsonBindingProvider"));
    }
    JaxrsProvidersToRegisterBuildItem result = new JaxrsProvidersToRegisterBuildItem(providersToRegister, contributedProviders, annotatedProviders, useBuiltinProviders);
    // Providers that are also beans are unremovable
    unremovableBeans.produce(new UnremovableBeanBuildItem(b -> result.getProviders().contains(b.getBeanClass().toString())));
    return result;
}
Also used : DotNames(io.quarkus.arc.processor.DotNames) ConfigGroup(io.quarkus.runtime.annotations.ConfigGroup) Arrays(java.util.Arrays) Produces(javax.ws.rs.Produces) AcceptEncodingGZIPFilter(org.jboss.resteasy.plugins.interceptors.AcceptEncodingGZIPFilter) UnremovableBeanBuildItem(io.quarkus.arc.deployment.UnremovableBeanBuildItem) MessageBodyWriter(javax.ws.rs.ext.MessageBodyWriter) ResteasyConfigSourceProvider(io.quarkus.resteasy.common.runtime.config.ResteasyConfigSourceProvider) FieldInfo(org.jboss.jandex.FieldInfo) CombinedIndexBuildItem(io.quarkus.deployment.builditem.CombinedIndexBuildItem) BuildProducer(io.quarkus.deployment.annotations.BuildProducer) Capabilities(io.quarkus.deployment.Capabilities) ContextResolver(javax.ws.rs.ext.ContextResolver) MediaType(javax.ws.rs.core.MediaType) MethodInfo(org.jboss.jandex.MethodInfo) ServerFormUrlEncodedProvider(io.quarkus.resteasy.common.runtime.providers.ServerFormUrlEncodedProvider) AdditionalBeanBuildItem(io.quarkus.arc.deployment.AdditionalBeanBuildItem) Consumes(javax.ws.rs.Consumes) ResteasyConfigBuildItem(io.quarkus.resteasy.common.spi.ResteasyConfigBuildItem) AnnotationTarget(org.jboss.jandex.AnnotationTarget) ParameterizedType(org.jboss.jandex.ParameterizedType) AnnotationValue(org.jboss.jandex.AnnotationValue) Consume(io.quarkus.deployment.annotations.Consume) Providers(javax.ws.rs.ext.Providers) STATIC_INIT(io.quarkus.deployment.annotations.ExecutionTime.STATIC_INIT) Collection(java.util.Collection) Set(java.util.Set) Collectors(java.util.stream.Collectors) ServletContextConfigSourceImpl(org.jboss.resteasy.microprofile.config.ServletContextConfigSourceImpl) StringTextStar(org.jboss.resteasy.plugins.providers.StringTextStar) List(java.util.List) MediaTypeMap(org.jboss.resteasy.core.MediaTypeMap) ConfigItem(io.quarkus.runtime.annotations.ConfigItem) AnnotationInstance(org.jboss.jandex.AnnotationInstance) BeanContainerBuildItem(io.quarkus.arc.deployment.BeanContainerBuildItem) ServiceProviderBuildItem(io.quarkus.deployment.builditem.nativeimage.ServiceProviderBuildItem) SseConstants(org.jboss.resteasy.plugins.providers.sse.SseConstants) ServletConfigSourceImpl(org.jboss.resteasy.microprofile.config.ServletConfigSourceImpl) StaticInitConfigSourceProviderBuildItem(io.quarkus.deployment.builditem.StaticInitConfigSourceProviderBuildItem) GZIPDecodingInterceptor(org.jboss.resteasy.plugins.interceptors.GZIPDecodingInterceptor) ReflectiveClassBuildItem(io.quarkus.deployment.builditem.nativeimage.ReflectiveClassBuildItem) Record(io.quarkus.deployment.annotations.Record) MemorySize(io.quarkus.runtime.configuration.MemorySize) Logger(org.jboss.logging.Logger) DotName(org.jboss.jandex.DotName) Type(org.jboss.jandex.Type) FilterConfigSourceImpl(org.jboss.resteasy.microprofile.config.FilterConfigSourceImpl) Function(java.util.function.Function) ResteasyInjectorFactoryRecorder(io.quarkus.resteasy.common.runtime.ResteasyInjectorFactoryRecorder) ArrayList(java.util.ArrayList) ConfigRoot(io.quarkus.runtime.annotations.ConfigRoot) HashSet(java.util.HashSet) BuildStep(io.quarkus.deployment.annotations.BuildStep) GZIPEncodingInterceptor(org.jboss.resteasy.plugins.interceptors.GZIPEncodingInterceptor) ResteasyDotNames(io.quarkus.resteasy.common.spi.ResteasyDotNames) RuntimeValue(io.quarkus.runtime.RuntimeValue) BeanArchiveIndexBuildItem(io.quarkus.arc.deployment.BeanArchiveIndexBuildItem) IndexView(org.jboss.jandex.IndexView) Capability(io.quarkus.deployment.Capability) InjectorFactory(org.jboss.resteasy.spi.InjectorFactory) Kind(org.jboss.jandex.AnnotationValue.Kind) ServiceUtil(io.quarkus.deployment.util.ServiceUtil) ResteasyJaxrsProviderBuildItem(io.quarkus.resteasy.common.spi.ResteasyJaxrsProviderBuildItem) Collections(java.util.Collections) MessageBodyReader(javax.ws.rs.ext.MessageBodyReader) MediaTypeMap(org.jboss.resteasy.core.MediaTypeMap) IndexView(org.jboss.jandex.IndexView) ResteasyJaxrsProviderBuildItem(io.quarkus.resteasy.common.spi.ResteasyJaxrsProviderBuildItem) UnremovableBeanBuildItem(io.quarkus.arc.deployment.UnremovableBeanBuildItem) Providers(javax.ws.rs.ext.Providers) AnnotationInstance(org.jboss.jandex.AnnotationInstance) ServerFormUrlEncodedProvider(io.quarkus.resteasy.common.runtime.providers.ServerFormUrlEncodedProvider) ReflectiveClassBuildItem(io.quarkus.deployment.builditem.nativeimage.ReflectiveClassBuildItem) HashSet(java.util.HashSet) StringTextStar(org.jboss.resteasy.plugins.providers.StringTextStar) BuildStep(io.quarkus.deployment.annotations.BuildStep)

Example 18 with Providers

use of javax.ws.rs.ext.Providers in project jetrs by jetrs.

the class RestApplicationServlet method service.

private void service(final HttpServletRequestImpl httpServletRequest, final HttpServletResponse httpServletResponse) throws IOException, ServletException {
    final ServerContext serverContext = getServerContext();
    final ContainerResponseContextImpl containerResponseContext = new ContainerResponseContextImpl(httpServletRequest, httpServletResponse, serverContext.getWriterInterceptors());
    final HttpHeadersImpl requestHeaders = new HttpHeadersImpl(httpServletRequest);
    final ExecutionContext executionContext = new ExecutionContext(requestHeaders, httpServletResponse, containerResponseContext, serverContext);
    // NOTE: This weird construct is done this way to at least somehow make the two objects cohesive
    final ContainerRequestContextImpl containerRequestContext;
    httpServletRequest.setRequestContext(containerRequestContext = new ContainerRequestContextImpl(httpServletRequest, executionContext, serverContext.getReaderInterceptors()));
    final AnnotationInjector annotationInjector = createAnnotationInjector(containerRequestContext, containerResponseContext, httpServletRequest, httpServletResponse, requestHeaders, serverContext);
    final Providers providers = serverContext.getProviders(annotationInjector);
    ResourceMatch resourceMatch = null;
    Stage stage = null;
    try {
        // (1) Filter Request (Pre-Match)
        stage = Stage.FILTER_REQUEST_PRE_MATCH;
        executionContext.filterPreMatchContainerRequest(containerRequestContext, annotationInjector);
        // (2) Match
        stage = Stage.MATCH;
        resourceMatch = executionContext.filterAndMatch(containerRequestContext, annotationInjector);
        final ResourceManifest resourceManifest = resourceMatch.getManifest();
        annotationInjector.setResourceInfo(resourceManifest);
        // (3) Filter Request
        stage = Stage.FILTER_REQUEST;
        executionContext.filterContainerRequest(containerRequestContext, annotationInjector);
        // (4a) Service
        stage = Stage.SERVICE;
        httpServletRequest.setResourceManifest(resourceManifest);
        executionContext.service(resourceMatch, containerRequestContext, annotationInjector);
        // (5a) Filter Response
        stage = Stage.FILTER_RESPONSE;
        executionContext.filterContainerResponse(containerRequestContext, annotationInjector);
        // (6a) Write Response
        stage = Stage.WRITE_RESPONSE;
        executionContext.writeResponse(annotationInjector, resourceMatch, containerRequestContext, providers);
    } catch (final IOException | RuntimeException | ServletException e) {
        if (!(e instanceof AbortFilterChainException)) {
            // FIXME: Review [JAX-RS 2.1 3.3.4 2,3]
            // (4b) Error
            final Response response;
            try {
                response = executionContext.setErrorResponse(providers, e);
            } catch (final RuntimeException e1) {
                if (!(e1 instanceof WebApplicationException))
                    httpServletResponse.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                e1.addSuppressed(e);
                throw e1;
            }
            if (response == null) {
                httpServletResponse.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                throw e;
            }
        } else if (stage == Stage.FILTER_RESPONSE) {
            throw new IllegalStateException("ContainerRequestContext.abortWith(Response) cannot be called from response filter chain");
        } else {
            executionContext.setAbortResponse((AbortFilterChainException) e);
        }
        try {
            // (5b) Filter Response
            stage = Stage.FILTER_RESPONSE;
            executionContext.filterContainerResponse(containerRequestContext, annotationInjector);
        } catch (final IOException | RuntimeException e1) {
            e.addSuppressed(e1);
        }
        try {
            // (6b) Write Response
            stage = Stage.WRITE_RESPONSE;
            executionContext.writeResponse(annotationInjector, resourceMatch, containerRequestContext, providers);
        } catch (final IOException | RuntimeException e1) {
            if (!(e1 instanceof WebApplicationException))
                httpServletResponse.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            e.addSuppressed(e1);
            throw e;
        }
    } finally {
        // (7) Commit Response
        executionContext.commitResponse(containerRequestContext);
    }
}
Also used : WebApplicationException(javax.ws.rs.WebApplicationException) IOException(java.io.IOException) Providers(javax.ws.rs.ext.Providers) ServletException(javax.servlet.ServletException) HttpServletResponse(javax.servlet.http.HttpServletResponse) Response(javax.ws.rs.core.Response)

Aggregations

Providers (javax.ws.rs.ext.Providers)18 MediaType (javax.ws.rs.core.MediaType)11 ByteArrayInputStream (java.io.ByteArrayInputStream)7 MessageBodyReader (javax.ws.rs.ext.MessageBodyReader)7 IOException (java.io.IOException)6 Test (org.junit.Test)6 WebApplicationException (javax.ws.rs.WebApplicationException)5 ByteArrayOutputStream (java.io.ByteArrayOutputStream)4 Annotation (java.lang.annotation.Annotation)4 Map (java.util.Map)4 Response (javax.ws.rs.core.Response)4 BufferedReader (java.io.BufferedReader)3 InputStream (java.io.InputStream)3 InputStreamReader (java.io.InputStreamReader)3 Type (java.lang.reflect.Type)3 StandardCharsets (java.nio.charset.StandardCharsets)3 ArrayList (java.util.ArrayList)3 Collection (java.util.Collection)3 List (java.util.List)3 Inject (javax.inject.Inject)3