Search in sources :

Example 1 with JerseyResourceContext

use of org.glassfish.jersey.server.internal.JerseyResourceContext in project jersey by jersey.

the class ApplicationHandler method initialize.

/**
     * Assumes the configuration field is initialized with a valid ResourceConfig.
     */
private ServerRuntime initialize(Iterable<ComponentProvider> componentProviders) {
    LOGGER.config(LocalizationMessages.INIT_MSG(Version.getBuildId()));
    // Lock original ResourceConfig.
    if (application instanceof ResourceConfig) {
        ((ResourceConfig) application).lock();
    }
    final boolean ignoreValidationErrors = ServerProperties.getValue(runtimeConfig.getProperties(), ServerProperties.RESOURCE_VALIDATION_IGNORE_ERRORS, Boolean.FALSE, Boolean.class);
    final boolean disableValidation = ServerProperties.getValue(runtimeConfig.getProperties(), ServerProperties.RESOURCE_VALIDATION_DISABLE, Boolean.FALSE, Boolean.class);
    final ResourceBag resourceBag;
    final ProcessingProviders processingProviders;
    final ComponentBag componentBag;
    ResourceModel resourceModel;
    CompositeApplicationEventListener compositeListener = null;
    // mark begin of validation phase
    Errors.mark();
    try {
        // AutoDiscoverable.
        if (!CommonProperties.getValue(runtimeConfig.getProperties(), RuntimeType.SERVER, CommonProperties.FEATURE_AUTO_DISCOVERY_DISABLE, Boolean.FALSE, Boolean.class)) {
            runtimeConfig.configureAutoDiscoverableProviders(injectionManager);
        } else {
            runtimeConfig.configureForcedAutoDiscoverableProviders(injectionManager);
        }
        // Configure binders and features.
        runtimeConfig.configureMetaProviders(injectionManager);
        final ResourceBag.Builder resourceBagBuilder = new ResourceBag.Builder();
        // Adding programmatic resource models
        for (final Resource programmaticResource : runtimeConfig.getResources()) {
            resourceBagBuilder.registerProgrammaticResource(programmaticResource);
        }
        // Introspecting classes & instances
        for (final Class<?> c : runtimeConfig.getClasses()) {
            try {
                final Resource resource = Resource.from(c, disableValidation);
                if (resource != null) {
                    resourceBagBuilder.registerResource(c, resource);
                }
            } catch (final IllegalArgumentException ex) {
                LOGGER.warning(ex.getMessage());
            }
        }
        for (final Object o : runtimeConfig.getSingletons()) {
            try {
                final Resource resource = Resource.from(o.getClass(), disableValidation);
                if (resource != null) {
                    resourceBagBuilder.registerResource(o, resource);
                }
            } catch (final IllegalArgumentException ex) {
                LOGGER.warning(ex.getMessage());
            }
        }
        resourceBag = resourceBagBuilder.build();
        runtimeConfig.lock();
        componentBag = runtimeConfig.getComponentBag();
        final Class<ExternalRequestScope>[] extScopes = ServiceFinder.find(ExternalRequestScope.class, true).toClassArray();
        boolean extScopeBound = false;
        if (extScopes.length == 1) {
            for (final ComponentProvider p : componentProviders) {
                if (p.bind(extScopes[0], new HashSet<Class<?>>() {

                    {
                        add(ExternalRequestScope.class);
                    }
                })) {
                    extScopeBound = true;
                    break;
                }
            }
        } else if (extScopes.length > 1) {
            if (LOGGER.isLoggable(Level.WARNING)) {
                final StringBuilder scopeList = new StringBuilder("\n");
                for (final Class<ExternalRequestScope> ers : extScopes) {
                    scopeList.append("   ").append(ers.getTypeParameters()[0]).append('\n');
                }
                LOGGER.warning(LocalizationMessages.WARNING_TOO_MANY_EXTERNAL_REQ_SCOPES(scopeList.toString()));
            }
        }
        if (!extScopeBound) {
            injectionManager.register(new ServerRuntime.NoopExternalRequestScopeBinder());
        }
        bindProvidersAndResources(componentProviders, componentBag, resourceBag.classes, resourceBag.instances);
        for (final ComponentProvider componentProvider : componentProviders) {
            componentProvider.done();
        }
        final Iterable<ApplicationEventListener> appEventListeners = Providers.getAllProviders(injectionManager, ApplicationEventListener.class, new RankedComparator<>());
        if (appEventListeners.iterator().hasNext()) {
            compositeListener = new CompositeApplicationEventListener(appEventListeners);
            compositeListener.onEvent(new ApplicationEventImpl(ApplicationEvent.Type.INITIALIZATION_START, this.runtimeConfig, componentBag.getRegistrations(), resourceBag.classes, resourceBag.instances, null));
        }
        processingProviders = getProcessingProviders(componentBag);
        // initialize processing provider reference
        final GenericType<Ref<ProcessingProviders>> refGenericType = new GenericType<Ref<ProcessingProviders>>() {
        };
        final Ref<ProcessingProviders> refProcessingProvider = injectionManager.getInstance(refGenericType.getType());
        refProcessingProvider.set(processingProviders);
        resourceModel = new ResourceModel.Builder(resourceBag.getRootResources(), false).build();
        resourceModel = processResourceModel(resourceModel);
        if (!disableValidation) {
            final ComponentModelValidator validator = new ComponentModelValidator(injectionManager);
            validator.validate(resourceModel);
        }
        if (Errors.fatalIssuesFound() && !ignoreValidationErrors) {
            throw new ModelValidationException(LocalizationMessages.RESOURCE_MODEL_VALIDATION_FAILED_AT_INIT(), ModelErrors.getErrorsAsResourceModelIssues(true));
        }
    } finally {
        if (ignoreValidationErrors) {
            Errors.logErrors(true);
            // reset errors to the state before validation phase
            Errors.reset();
        } else {
            Errors.unmark();
        }
    }
    bindEnhancingResourceClasses(resourceModel, resourceBag, componentProviders);
    ExecutorProviders.createInjectionBindings(injectionManager);
    // initiate resource model into JerseyResourceContext
    final JerseyResourceContext jerseyResourceContext = injectionManager.getInstance(JerseyResourceContext.class);
    jerseyResourceContext.setResourceModel(resourceModel);
    msgBodyWorkers = injectionManager.getInstance(MessageBodyWorkers.class);
    // assembly request processing chain
    final ReferencesInitializer referencesInitializer = injectionManager.createAndInitialize(ReferencesInitializer.class);
    final ContainerFilteringStage preMatchRequestFilteringStage = new ContainerFilteringStage(processingProviders.getPreMatchFilters(), processingProviders.getGlobalResponseFilters());
    final ChainableStage<RequestProcessingContext> routingStage = Routing.forModel(resourceModel.getRuntimeResourceModel()).beanManager(injectionManager).resourceContext(jerseyResourceContext).configuration(runtimeConfig).entityProviders(msgBodyWorkers).processingProviders(processingProviders).buildStage();
    final ContainerFilteringStage resourceFilteringStage = new ContainerFilteringStage(processingProviders.getGlobalRequestFilters(), null);
    /**
         *  Root linear request acceptor. This is the main entry point for the whole request processing.
         */
    final Stage<RequestProcessingContext> rootStage = Stages.chain(referencesInitializer).to(preMatchRequestFilteringStage).to(routingStage).to(resourceFilteringStage).build(Routing.matchedEndpointExtractor());
    final ServerRuntime serverRuntime = injectionManager.createAndInitialize(ServerRuntime.Builder.class).build(rootStage, compositeListener, processingProviders);
    // Inject instances.
    for (final Object instance : componentBag.getInstances(ComponentBag.excludeMetaProviders(injectionManager))) {
        injectionManager.inject(instance);
    }
    for (final Object instance : resourceBag.instances) {
        injectionManager.inject(instance);
    }
    logApplicationInitConfiguration(injectionManager, resourceBag, processingProviders);
    if (compositeListener != null) {
        final ApplicationEvent initFinishedEvent = new ApplicationEventImpl(ApplicationEvent.Type.INITIALIZATION_APP_FINISHED, runtimeConfig, componentBag.getRegistrations(), resourceBag.classes, resourceBag.instances, resourceModel);
        compositeListener.onEvent(initFinishedEvent);
        final MonitoringContainerListener containerListener = injectionManager.getInstance(MonitoringContainerListener.class);
        containerListener.init(compositeListener, initFinishedEvent);
    }
    return serverRuntime;
}
Also used : JerseyResourceContext(org.glassfish.jersey.server.internal.JerseyResourceContext) ModelValidationException(org.glassfish.jersey.server.model.ModelValidationException) RequestProcessingContext(org.glassfish.jersey.server.internal.process.RequestProcessingContext) ResourceModel(org.glassfish.jersey.server.model.ResourceModel) ComponentModelValidator(org.glassfish.jersey.server.model.ComponentModelValidator) ApplicationEventImpl(org.glassfish.jersey.server.internal.monitoring.ApplicationEventImpl) CompositeApplicationEventListener(org.glassfish.jersey.server.internal.monitoring.CompositeApplicationEventListener) ApplicationEventListener(org.glassfish.jersey.server.monitoring.ApplicationEventListener) CompositeApplicationEventListener(org.glassfish.jersey.server.internal.monitoring.CompositeApplicationEventListener) MessageBodyWorkers(org.glassfish.jersey.message.MessageBodyWorkers) ComponentBag(org.glassfish.jersey.model.internal.ComponentBag) ExternalRequestScope(org.glassfish.jersey.server.spi.ExternalRequestScope) GenericType(javax.ws.rs.core.GenericType) ReferencesInitializer(org.glassfish.jersey.server.internal.process.ReferencesInitializer) MonitoringContainerListener(org.glassfish.jersey.server.internal.monitoring.MonitoringContainerListener) Resource(org.glassfish.jersey.server.model.Resource) ApplicationEvent(org.glassfish.jersey.server.monitoring.ApplicationEvent) Ref(org.glassfish.jersey.internal.util.collection.Ref) ComponentProvider(org.glassfish.jersey.server.spi.ComponentProvider) ProcessingProviders(org.glassfish.jersey.server.internal.ProcessingProviders)

Example 2 with JerseyResourceContext

use of org.glassfish.jersey.server.internal.JerseyResourceContext in project jersey by jersey.

the class ApplicationHandler method bindProvidersAndResources.

private void bindProvidersAndResources(final Iterable<ComponentProvider> componentProviders, final ComponentBag componentBag, final Collection<Class<?>> resourceClasses, final Collection<Object> resourceInstances) {
    JerseyResourceContext resourceContext = injectionManager.getInstance(JerseyResourceContext.class);
    Set<Class<?>> registeredClasses = runtimeConfig.getRegisteredClasses();
    /*
         * Check the {@code component} whether it is correctly configured for client or server {@link RuntimeType runtime}.
         */
    java.util.function.Predicate<Class<?>> correctlyConfigured = componentClass -> Providers.checkProviderRuntime(componentClass, componentBag.getModel(componentClass), RuntimeType.SERVER, !registeredClasses.contains(componentClass), resourceClasses.contains(componentClass));
    /*
         * Check the {@code resource class} whether it is correctly configured for client or server {@link RuntimeType runtime}.
         */
    BiPredicate<Class<?>, ContractProvider> correctlyConfiguredResource = (resourceClass, model) -> Providers.checkProviderRuntime(resourceClass, model, RuntimeType.SERVER, !registeredClasses.contains(resourceClass), true);
    Set<Class<?>> componentClassses = componentBag.getClasses(ComponentBag.excludeMetaProviders(injectionManager)).stream().filter(correctlyConfigured).collect(Collectors.toSet());
    // Merge programmatic resource classes with component classes.
    Set<Class<?>> classes = Collections.newSetFromMap(new IdentityHashMap<>());
    classes.addAll(componentClassses);
    classes.addAll(resourceClasses);
    // Bind classes.
    for (final Class<?> componentClass : classes) {
        ContractProvider model = componentBag.getModel(componentClass);
        if (bindWithComponentProvider(componentClass, model, componentProviders)) {
            continue;
        }
        if (resourceClasses.contains(componentClass)) {
            if (!Resource.isAcceptable(componentClass)) {
                LOGGER.warning(LocalizationMessages.NON_INSTANTIABLE_COMPONENT(componentClass));
                continue;
            }
            if (model != null && !correctlyConfiguredResource.test(componentClass, model)) {
                model = null;
            }
            resourceContext.unsafeBindResource(componentClass, model, injectionManager);
        } else {
            ProviderBinder.bindProvider(componentClass, model, injectionManager);
        }
    }
    // Merge programmatic resource instances with other component instances.
    Set<Object> instances = componentBag.getInstances(ComponentBag.excludeMetaProviders(injectionManager)).stream().filter(instance -> correctlyConfigured.test(instance.getClass())).collect(Collectors.toSet());
    instances.addAll(resourceInstances);
    // Bind instances.
    for (Object component : instances) {
        ContractProvider model = componentBag.getModel(component.getClass());
        if (resourceInstances.contains(component)) {
            if (model != null && !correctlyConfiguredResource.test(component.getClass(), model)) {
                model = null;
            }
            resourceContext.unsafeBindResource(component, model, injectionManager);
        } else {
            ProviderBinder.bindProvider(component, model, injectionManager);
        }
    }
}
Also used : JerseyResourceContext(org.glassfish.jersey.server.internal.JerseyResourceContext) ComponentBag(org.glassfish.jersey.model.internal.ComponentBag) RankedComparator(org.glassfish.jersey.model.internal.RankedComparator) SecurityContext(javax.ws.rs.core.SecurityContext) Errors(org.glassfish.jersey.internal.Errors) MessageBodyWriter(javax.ws.rs.ext.MessageBodyWriter) ModelProcessor(org.glassfish.jersey.server.model.ModelProcessor) ComponentProvider(org.glassfish.jersey.server.spi.ComponentProvider) Application(javax.ws.rs.core.Application) JerseyResourceContext(org.glassfish.jersey.server.internal.JerseyResourceContext) ContainerLifecycleListener(org.glassfish.jersey.server.spi.ContainerLifecycleListener) ContainerRequestFilter(javax.ws.rs.container.ContainerRequestFilter) InjectionManager(org.glassfish.jersey.internal.inject.InjectionManager) ContainerResponseFilter(javax.ws.rs.container.ContainerResponseFilter) RankedProvider(org.glassfish.jersey.model.internal.RankedProvider) JerseyRequestTimeoutHandler(org.glassfish.jersey.server.internal.JerseyRequestTimeoutHandler) ExecutorProviders(org.glassfish.jersey.process.internal.ExecutorProviders) Stages(org.glassfish.jersey.process.internal.Stages) Future(java.util.concurrent.Future) Ref(org.glassfish.jersey.internal.util.collection.Ref) ReaderInterceptor(javax.ws.rs.ext.ReaderInterceptor) Map(java.util.Map) ProviderBinder(org.glassfish.jersey.internal.inject.ProviderBinder) RequestProcessingContext(org.glassfish.jersey.server.internal.process.RequestProcessingContext) ModelErrors(org.glassfish.jersey.server.model.internal.ModelErrors) ApplicationEvent(org.glassfish.jersey.server.monitoring.ApplicationEvent) Values(org.glassfish.jersey.internal.util.collection.Values) ContainerResponseWriter(org.glassfish.jersey.server.spi.ContainerResponseWriter) LocalizationMessages(org.glassfish.jersey.server.internal.LocalizationMessages) IdentityHashMap(java.util.IdentityHashMap) RuntimeType(javax.ws.rs.RuntimeType) Collection(java.util.Collection) Version(org.glassfish.jersey.internal.Version) MessageBodyWorkers(org.glassfish.jersey.message.MessageBodyWorkers) Container(org.glassfish.jersey.server.spi.Container) Set(java.util.Set) ContractProvider(org.glassfish.jersey.model.ContractProvider) ResourceModel(org.glassfish.jersey.server.model.ResourceModel) Providers(org.glassfish.jersey.internal.inject.Providers) Logger(java.util.logging.Logger) ModelValidationException(org.glassfish.jersey.server.model.ModelValidationException) Collectors(java.util.stream.Collectors) ChainableStage(org.glassfish.jersey.process.internal.ChainableStage) PreMatching(javax.ws.rs.container.PreMatching) GenericType(javax.ws.rs.core.GenericType) DynamicFeature(javax.ws.rs.container.DynamicFeature) List(java.util.List) Principal(java.security.Principal) HttpHeaders(javax.ws.rs.core.HttpHeaders) Type(java.lang.reflect.Type) Annotation(java.lang.annotation.Annotation) MonitoringContainerListener(org.glassfish.jersey.server.internal.monitoring.MonitoringContainerListener) Spliterator(java.util.Spliterator) Resource(org.glassfish.jersey.server.model.Resource) CommonProperties(org.glassfish.jersey.CommonProperties) Configuration(javax.ws.rs.core.Configuration) Order(org.glassfish.jersey.model.internal.RankedComparator.Order) CompletableFuture(java.util.concurrent.CompletableFuture) AbstractBinder(org.glassfish.jersey.internal.inject.AbstractBinder) Singleton(javax.inject.Singleton) Binder(org.glassfish.jersey.internal.inject.Binder) Function(java.util.function.Function) Supplier(java.util.function.Supplier) HttpMethod(javax.ws.rs.HttpMethod) ArrayList(java.util.ArrayList) Level(java.util.logging.Level) HashSet(java.util.HashSet) ApplicationEventListener(org.glassfish.jersey.server.monitoring.ApplicationEventListener) BiPredicate(java.util.function.BiPredicate) ReferencesInitializer(org.glassfish.jersey.server.internal.process.ReferencesInitializer) Value(org.glassfish.jersey.internal.util.collection.Value) ApplicationEventImpl(org.glassfish.jersey.server.internal.monitoring.ApplicationEventImpl) ExternalRequestScope(org.glassfish.jersey.server.spi.ExternalRequestScope) Routing(org.glassfish.jersey.server.internal.routing.Routing) ScheduledExecutorService(java.util.concurrent.ScheduledExecutorService) LazyValue(org.glassfish.jersey.internal.util.collection.LazyValue) StreamSupport(java.util.stream.StreamSupport) WriterInterceptor(javax.ws.rs.ext.WriterInterceptor) Injections(org.glassfish.jersey.internal.inject.Injections) LinkedList(java.util.LinkedList) OutputStream(java.io.OutputStream) CompositeApplicationEventListener(org.glassfish.jersey.server.internal.monitoring.CompositeApplicationEventListener) Iterator(java.util.Iterator) ServiceConfigurationError(org.glassfish.jersey.internal.ServiceConfigurationError) ProcessingProviders(org.glassfish.jersey.server.internal.ProcessingProviders) MultivaluedHashMap(javax.ws.rs.core.MultivaluedHashMap) ReflectionHelper(org.glassfish.jersey.internal.util.ReflectionHelper) TimeUnit(java.util.concurrent.TimeUnit) MultivaluedMap(javax.ws.rs.core.MultivaluedMap) ComponentModelValidator(org.glassfish.jersey.server.model.ComponentModelValidator) NameBinding(javax.ws.rs.NameBinding) CompositeBinder(org.glassfish.jersey.internal.inject.CompositeBinder) Stage(org.glassfish.jersey.process.internal.Stage) ServiceFinder(org.glassfish.jersey.internal.ServiceFinder) NullOutputStream(org.glassfish.jersey.message.internal.NullOutputStream) Collections(java.util.Collections) MessageBodyReader(javax.ws.rs.ext.MessageBodyReader) ContractProvider(org.glassfish.jersey.model.ContractProvider)

Aggregations

GenericType (javax.ws.rs.core.GenericType)2 OutputStream (java.io.OutputStream)1 Annotation (java.lang.annotation.Annotation)1 Type (java.lang.reflect.Type)1 Principal (java.security.Principal)1 ArrayList (java.util.ArrayList)1 Collection (java.util.Collection)1 Collections (java.util.Collections)1 HashSet (java.util.HashSet)1 IdentityHashMap (java.util.IdentityHashMap)1 Iterator (java.util.Iterator)1 LinkedList (java.util.LinkedList)1 List (java.util.List)1 Map (java.util.Map)1 Set (java.util.Set)1 Spliterator (java.util.Spliterator)1 CompletableFuture (java.util.concurrent.CompletableFuture)1 Future (java.util.concurrent.Future)1 ScheduledExecutorService (java.util.concurrent.ScheduledExecutorService)1 TimeUnit (java.util.concurrent.TimeUnit)1