Search in sources :

Example 1 with RequestProcessingContext

use of org.glassfish.jersey.server.internal.process.RequestProcessingContext 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 RequestProcessingContext

use of org.glassfish.jersey.server.internal.process.RequestProcessingContext in project jersey by jersey.

the class RoutingStage method apply.

/**
     * {@inheritDoc}
     * <p/>
     * Routing stage navigates through the nested {@link Router routing hierarchy}
     * using a depth-first transformation strategy until a request-to-response
     * inflector is {@link org.glassfish.jersey.process.internal.Inflecting found on
     * a leaf stage node}, in which case the request routing is terminated and an
     * {@link org.glassfish.jersey.process.Inflector inflector} (if found) is pushed
     * to the {@link RoutingContext routing context}.
     */
@Override
public Continuation<RequestProcessingContext> apply(final RequestProcessingContext context) {
    final ContainerRequest request = context.request();
    context.triggerEvent(RequestEvent.Type.MATCHING_START);
    final TracingLogger tracingLogger = TracingLogger.getInstance(request);
    final long timestamp = tracingLogger.timestamp(ServerTraceEvent.MATCH_SUMMARY);
    try {
        final RoutingResult result = _apply(context, routingRoot);
        Stage<RequestProcessingContext> nextStage = null;
        if (result.endpoint != null) {
            context.routingContext().setEndpoint(result.endpoint);
            nextStage = getDefaultNext();
        }
        return Continuation.of(result.context, nextStage);
    } finally {
        tracingLogger.logDuration(ServerTraceEvent.MATCH_SUMMARY, timestamp);
    }
}
Also used : RequestProcessingContext(org.glassfish.jersey.server.internal.process.RequestProcessingContext) ContainerRequest(org.glassfish.jersey.server.ContainerRequest) TracingLogger(org.glassfish.jersey.message.internal.TracingLogger)

Example 3 with RequestProcessingContext

use of org.glassfish.jersey.server.internal.process.RequestProcessingContext in project jersey by jersey.

the class ContainerFilteringStage method apply.

@Override
@SuppressWarnings("unchecked")
public Continuation<RequestProcessingContext> apply(RequestProcessingContext context) {
    Iterable<ContainerRequestFilter> sortedRequestFilters;
    final boolean postMatching = responseFilters == null;
    final ContainerRequest request = context.request();
    final TracingLogger tracingLogger = TracingLogger.getInstance(request);
    if (postMatching) {
        // post-matching
        final ArrayList<Iterable<RankedProvider<ContainerRequestFilter>>> rankedProviders = new ArrayList<>(2);
        rankedProviders.add(requestFilters);
        rankedProviders.add(request.getRequestFilters());
        sortedRequestFilters = Providers.mergeAndSortRankedProviders(new RankedComparator<ContainerRequestFilter>(), rankedProviders);
        context.monitoringEventBuilder().setContainerRequestFilters(sortedRequestFilters);
        context.triggerEvent(RequestEvent.Type.REQUEST_MATCHED);
    } else {
        // pre-matching (response filter stage is pushed in pre-matching phase, so that if pre-matching filter
        // throws exception, response filters get still invoked)
        context.push(new ResponseFilterStage(context, responseFilters, tracingLogger));
        sortedRequestFilters = Providers.sortRankedProviders(new RankedComparator<ContainerRequestFilter>(), requestFilters);
    }
    final TracingLogger.Event summaryEvent = (postMatching ? ServerTraceEvent.REQUEST_FILTER_SUMMARY : ServerTraceEvent.PRE_MATCH_SUMMARY);
    final long timestamp = tracingLogger.timestamp(summaryEvent);
    int processedCount = 0;
    try {
        final TracingLogger.Event filterEvent = (postMatching ? ServerTraceEvent.REQUEST_FILTER : ServerTraceEvent.PRE_MATCH);
        for (ContainerRequestFilter filter : sortedRequestFilters) {
            final long filterTimestamp = tracingLogger.timestamp(filterEvent);
            try {
                filter.filter(request);
            } catch (Exception exception) {
                throw new MappableException(exception);
            } finally {
                processedCount++;
                tracingLogger.logDuration(filterEvent, filterTimestamp, filter);
            }
            final Response abortResponse = request.getAbortResponse();
            if (abortResponse != null) {
                // abort accepting & return response
                return Continuation.of(context, Stages.asStage(new Endpoint() {

                    @Override
                    public ContainerResponse apply(final RequestProcessingContext requestContext) {
                        return new ContainerResponse(requestContext.request(), abortResponse);
                    }
                }));
            }
        }
    } finally {
        if (postMatching) {
            context.triggerEvent(RequestEvent.Type.REQUEST_FILTERED);
        }
        tracingLogger.logDuration(summaryEvent, timestamp, processedCount);
    }
    return Continuation.of(context, getDefaultNext());
}
Also used : MappableException(org.glassfish.jersey.server.internal.process.MappableException) ArrayList(java.util.ArrayList) TracingLogger(org.glassfish.jersey.message.internal.TracingLogger) Endpoint(org.glassfish.jersey.server.internal.process.Endpoint) MappableException(org.glassfish.jersey.server.internal.process.MappableException) RankedComparator(org.glassfish.jersey.model.internal.RankedComparator) Response(javax.ws.rs.core.Response) RequestProcessingContext(org.glassfish.jersey.server.internal.process.RequestProcessingContext) Endpoint(org.glassfish.jersey.server.internal.process.Endpoint) ContainerRequestFilter(javax.ws.rs.container.ContainerRequestFilter)

Example 4 with RequestProcessingContext

use of org.glassfish.jersey.server.internal.process.RequestProcessingContext in project jersey by jersey.

the class ServerRuntime method process.

/**
     * Process a container request.
     *
     * @param request container request to be processed.
     */
public void process(final ContainerRequest request) {
    TracingUtils.initTracingSupport(tracingConfig, tracingThreshold, request);
    TracingUtils.logStart(request);
    final UriRoutingContext routingContext = request.getUriRoutingContext();
    RequestEventBuilder monitoringEventBuilder = EmptyRequestEventBuilder.INSTANCE;
    RequestEventListener monitoringEventListener = null;
    if (applicationEventListener != null) {
        monitoringEventBuilder = new RequestEventImpl.Builder().setContainerRequest(request).setExtendedUriInfo(routingContext);
        monitoringEventListener = applicationEventListener.onRequest(monitoringEventBuilder.build(RequestEvent.Type.START));
    }
    request.setProcessingProviders(processingProviders);
    final RequestProcessingContext context = new RequestProcessingContext(injectionManager, request, routingContext, monitoringEventBuilder, monitoringEventListener);
    request.checkState();
    final Responder responder = new Responder(context, ServerRuntime.this);
    final RequestScope.Instance requestScopeInstance = requestScope.createInstance();
    // TODO: Will we need EXTERNAL_REQUEST_SCOPE after the injection task?
    final AsyncResponderHolder asyncResponderHolder = new AsyncResponderHolder(responder, externalRequestScope, requestScopeInstance, externalRequestScope.open(injectionManager));
    context.initAsyncContext(asyncResponderHolder);
    requestScope.runInScope(requestScopeInstance, new Runnable() {

        @Override
        public void run() {
            try {
                // for later resolving of relative location URIs
                if (!disableLocationHeaderRelativeUriResolution) {
                    final URI uriToUse = rfc7231LocationHeaderRelativeUriResolution ? request.getRequestUri() : request.getBaseUri();
                    OutboundJaxrsResponse.Builder.setBaseUri(uriToUse);
                }
                final Ref<Endpoint> endpointRef = Refs.emptyRef();
                final RequestProcessingContext data = Stages.process(context, requestProcessingRoot, endpointRef);
                final Endpoint endpoint = endpointRef.get();
                if (endpoint == null) {
                    // not found
                    throw new NotFoundException();
                }
                final ContainerResponse response = endpoint.apply(data);
                if (!asyncResponderHolder.isAsync()) {
                    responder.process(response);
                } else {
                    externalRequestScope.suspend(asyncResponderHolder.externalContext, injectionManager);
                }
            } catch (final Throwable throwable) {
                responder.process(throwable);
            } finally {
                asyncResponderHolder.release();
                // clear base URI from the thread
                OutboundJaxrsResponse.Builder.clearBaseUri();
            }
        }
    });
}
Also used : UriRoutingContext(org.glassfish.jersey.server.internal.routing.UriRoutingContext) NotFoundException(javax.ws.rs.NotFoundException) MessageBodyProviderNotFoundException(org.glassfish.jersey.message.internal.MessageBodyProviderNotFoundException) ExternalRequestScope(org.glassfish.jersey.server.spi.ExternalRequestScope) RequestScope(org.glassfish.jersey.process.internal.RequestScope) URI(java.net.URI) RequestProcessingContext(org.glassfish.jersey.server.internal.process.RequestProcessingContext) Ref(org.glassfish.jersey.internal.util.collection.Ref) RequestEventImpl(org.glassfish.jersey.server.internal.monitoring.RequestEventImpl) Endpoint(org.glassfish.jersey.server.internal.process.Endpoint) RequestEventListener(org.glassfish.jersey.server.monitoring.RequestEventListener) RequestEventBuilder(org.glassfish.jersey.server.internal.monitoring.RequestEventBuilder) EmptyRequestEventBuilder(org.glassfish.jersey.server.internal.monitoring.EmptyRequestEventBuilder)

Example 5 with RequestProcessingContext

use of org.glassfish.jersey.server.internal.process.RequestProcessingContext in project jersey by jersey.

the class MethodSelectingRouter method createHeadEnrichedRouter.

private Router createHeadEnrichedRouter() {
    return new Router() {

        @Override
        public Continuation apply(final RequestProcessingContext context) {
            final ContainerRequest request = context.request();
            if (HttpMethod.HEAD.equals(request.getMethod())) {
                request.setMethodWithoutException(HttpMethod.GET);
                context.push(new Function<ContainerResponse, ContainerResponse>() {

                    @Override
                    public ContainerResponse apply(final ContainerResponse responseContext) {
                        responseContext.getRequestContext().setMethodWithoutException(HttpMethod.HEAD);
                        return responseContext;
                    }
                });
            }
            return Continuation.of(context, getMethodRouter(context));
        }
    };
}
Also used : RequestProcessingContext(org.glassfish.jersey.server.internal.process.RequestProcessingContext) ContainerResponse(org.glassfish.jersey.server.ContainerResponse) ContainerRequest(org.glassfish.jersey.server.ContainerRequest)

Aggregations

RequestProcessingContext (org.glassfish.jersey.server.internal.process.RequestProcessingContext)5 Ref (org.glassfish.jersey.internal.util.collection.Ref)2 TracingLogger (org.glassfish.jersey.message.internal.TracingLogger)2 ContainerRequest (org.glassfish.jersey.server.ContainerRequest)2 Endpoint (org.glassfish.jersey.server.internal.process.Endpoint)2 ExternalRequestScope (org.glassfish.jersey.server.spi.ExternalRequestScope)2 URI (java.net.URI)1 ArrayList (java.util.ArrayList)1 NotFoundException (javax.ws.rs.NotFoundException)1 ContainerRequestFilter (javax.ws.rs.container.ContainerRequestFilter)1 GenericType (javax.ws.rs.core.GenericType)1 Response (javax.ws.rs.core.Response)1 MessageBodyWorkers (org.glassfish.jersey.message.MessageBodyWorkers)1 MessageBodyProviderNotFoundException (org.glassfish.jersey.message.internal.MessageBodyProviderNotFoundException)1 ComponentBag (org.glassfish.jersey.model.internal.ComponentBag)1 RankedComparator (org.glassfish.jersey.model.internal.RankedComparator)1 RequestScope (org.glassfish.jersey.process.internal.RequestScope)1 ContainerResponse (org.glassfish.jersey.server.ContainerResponse)1 JerseyResourceContext (org.glassfish.jersey.server.internal.JerseyResourceContext)1 ProcessingProviders (org.glassfish.jersey.server.internal.ProcessingProviders)1