Search in sources :

Example 1 with ResourceContext

use of javax.ws.rs.container.ResourceContext in project tomee by apache.

the class Contexts method bind.

/**
 * Using a set ensures we don't set the thread local twice or more,
 * there may be super classes with injection points of identical types
 *
 * Also allows us to get context references from other sources such as interceptors
 *
 * @param exchange Exchange
 * @param types    Collection
 */
public static void bind(final Exchange exchange, final Collection<Class<?>> types) {
    // used in lazy mode by RESTResourceFinder if cdi beans uses @Context, === initThreadLocal
    EXCHANGE.set(exchange);
    CdiAppContextsService.pushRequestReleasable(CleanUpThreadLocal.INSTANCE);
    for (final Class<?> type : types) {
        if (Request.class.equals(type)) {
            final Request binding = JAXRSUtils.createContextValue(exchange.getInMessage(), null, Request.class);
            ThreadLocalContextManager.REQUEST.set(binding);
        } else if (UriInfo.class.equals(type)) {
            final UriInfo binding = JAXRSUtils.createContextValue(exchange.getInMessage(), null, UriInfo.class);
            ThreadLocalContextManager.URI_INFO.set(binding);
        } else if (HttpHeaders.class.equals(type)) {
            final HttpHeaders binding = JAXRSUtils.createContextValue(exchange.getInMessage(), null, HttpHeaders.class);
            ThreadLocalContextManager.HTTP_HEADERS.set(binding);
        } else if (SecurityContext.class.equals(type)) {
            final SecurityContext binding = JAXRSUtils.createContextValue(exchange.getInMessage(), null, SecurityContext.class);
            ThreadLocalContextManager.SECURITY_CONTEXT.set(binding);
        } else if (ContextResolver.class.equals(type)) {
            final ContextResolver<?> binding = JAXRSUtils.createContextValue(exchange.getInMessage(), type, ContextResolver.class);
            ThreadLocalContextManager.CONTEXT_RESOLVER.set(binding);
        } else if (Providers.class.equals(type)) {
            final Providers providers = JAXRSUtils.createContextValue(exchange.getInMessage(), null, Providers.class);
            ThreadLocalContextManager.PROVIDERS.set(providers);
        } else if (ServletRequest.class.equals(type)) {
            ServletRequest servletRequest = JAXRSUtils.createContextValue(exchange.getInMessage(), null, ServletRequest.class);
            if (servletRequest == null) {
                // probably the case with CXF
                servletRequest = JAXRSUtils.createContextValue(exchange.getInMessage(), null, HttpServletRequest.class);
            }
            ThreadLocalContextManager.SERVLET_REQUEST.set(servletRequest);
        } else if (HttpServletRequest.class.equals(type)) {
            final HttpServletRequest httpServletRequest = JAXRSUtils.createContextValue(exchange.getInMessage(), null, HttpServletRequest.class);
            ThreadLocalContextManager.HTTP_SERVLET_REQUEST.set(httpServletRequest);
        } else if (HttpServletResponse.class.equals(type)) {
            final HttpServletResponse httpServletResponse = JAXRSUtils.createContextValue(exchange.getInMessage(), null, HttpServletResponse.class);
            ThreadLocalContextManager.HTTP_SERVLET_RESPONSE.set(httpServletResponse);
        } else if (ServletConfig.class.equals(type)) {
            final ServletConfig servletConfig = JAXRSUtils.createContextValue(exchange.getInMessage(), null, ServletConfig.class);
            ThreadLocalContextManager.SERVLET_CONFIG.set(servletConfig);
        } else if (Configuration.class.equals(type)) {
            final Configuration config = JAXRSUtils.createContextValue(exchange.getInMessage(), null, Configuration.class);
            ThreadLocalContextManager.CONFIGURATION.set(config);
        } else if (ResourceInfo.class.equals(type)) {
            final ResourceInfo config = JAXRSUtils.createContextValue(exchange.getInMessage(), null, ResourceInfo.class);
            ThreadLocalContextManager.RESOURCE_INFO.set(config);
        } else if (ResourceContext.class.equals(type)) {
            final ResourceContext config = JAXRSUtils.createContextValue(exchange.getInMessage(), null, ResourceContext.class);
            ThreadLocalContextManager.RESOURCE_CONTEXT.set(config);
        } else if (Application.class.equals(type)) {
            final Application config = JAXRSUtils.createContextValue(exchange.getInMessage(), null, Application.class);
            ThreadLocalContextManager.APPLICATION.set(config);
        } else {
            final Message message = exchange.getInMessage();
            final ContextProvider<?> provider = ProviderFactory.getInstance(message).createContextProvider(type, message);
            if (provider != null) {
                final Object value = provider.createContext(message);
                Map<String, Object> map = ThreadLocalContextManager.OTHERS.get();
                if (map == null) {
                    map = new HashMap<>();
                    ThreadLocalContextManager.OTHERS.set(map);
                }
                map.put(type.getName(), value);
            }
        }
    }
}
Also used : HttpHeaders(javax.ws.rs.core.HttpHeaders) HttpServletRequest(javax.servlet.http.HttpServletRequest) ServletRequest(javax.servlet.ServletRequest) OperationResourceInfo(org.apache.cxf.jaxrs.model.OperationResourceInfo) ResourceInfo(javax.ws.rs.container.ResourceInfo) ClassResourceInfo(org.apache.cxf.jaxrs.model.ClassResourceInfo) ResourceContext(javax.ws.rs.container.ResourceContext) Configuration(javax.ws.rs.core.Configuration) Message(org.apache.cxf.message.Message) HashMap(java.util.HashMap) HttpServletRequest(javax.servlet.http.HttpServletRequest) ServletRequest(javax.servlet.ServletRequest) Request(javax.ws.rs.core.Request) ServletConfig(javax.servlet.ServletConfig) HttpServletResponse(javax.servlet.http.HttpServletResponse) ContextProvider(org.apache.cxf.jaxrs.ext.ContextProvider) Providers(javax.ws.rs.ext.Providers) HttpServletRequest(javax.servlet.http.HttpServletRequest) SecurityContext(javax.ws.rs.core.SecurityContext) Application(javax.ws.rs.core.Application) HashMap(java.util.HashMap) Map(java.util.Map) UriInfo(javax.ws.rs.core.UriInfo)

Example 2 with ResourceContext

use of javax.ws.rs.container.ResourceContext in project cxf by apache.

the class JAXRSInvoker method invoke.

@SuppressWarnings("unchecked")
public Object invoke(Exchange exchange, Object request, Object resourceObject) {
    final OperationResourceInfo ori = exchange.get(OperationResourceInfo.class);
    final ClassResourceInfo cri = ori.getClassResourceInfo();
    final Message inMessage = exchange.getInMessage();
    final ServerProviderFactory providerFactory = ServerProviderFactory.getInstance(inMessage);
    cri.injectContexts(resourceObject, ori, inMessage);
    if (cri.isRoot()) {
        ProviderInfo<Application> appProvider = providerFactory.getApplicationProvider();
        if (appProvider != null) {
            InjectionUtils.injectContexts(appProvider.getProvider(), appProvider, inMessage);
        }
    }
    Method methodToInvoke = getMethodToInvoke(cri, ori, resourceObject);
    List<Object> params = null;
    if (request instanceof List) {
        params = CastUtils.cast((List<?>) request);
    } else if (request != null) {
        params = new MessageContentsList(request);
    }
    Object result = null;
    ClassLoaderHolder contextLoader = null;
    AsyncResponseImpl asyncResponse = null;
    try {
        if (setServiceLoaderAsContextLoader(inMessage)) {
            contextLoader = ClassLoaderUtils.setThreadContextClassloader(resourceObject.getClass().getClassLoader());
        }
        if (!ori.isSubResourceLocator()) {
            asyncResponse = (AsyncResponseImpl) inMessage.get(AsyncResponse.class);
        }
        result = invoke(exchange, resourceObject, methodToInvoke, params);
        if (asyncResponse == null && !ori.isSubResourceLocator()) {
            asyncResponse = checkFutureResponse(inMessage, checkResultObject(result));
        }
        if (asyncResponse != null) {
            if (!asyncResponse.suspendContinuationIfNeeded()) {
                result = handleAsyncResponse(exchange, asyncResponse);
            } else {
                providerFactory.clearThreadLocalProxies();
            }
        }
    } catch (Fault ex) {
        Object faultResponse;
        if (asyncResponse != null) {
            faultResponse = handleAsyncFault(exchange, asyncResponse, ex.getCause() == null ? ex : ex.getCause());
        } else {
            faultResponse = handleFault(ex, inMessage, cri, methodToInvoke);
        }
        return faultResponse;
    } finally {
        exchange.put(LAST_SERVICE_OBJECT, resourceObject);
        if (contextLoader != null) {
            contextLoader.reset();
        }
    }
    ClassResourceInfo subCri = null;
    if (ori.isSubResourceLocator()) {
        try {
            MultivaluedMap<String, String> values = getTemplateValues(inMessage);
            String subResourcePath = values.getFirst(URITemplate.FINAL_MATCH_GROUP);
            String httpMethod = (String) inMessage.get(Message.HTTP_REQUEST_METHOD);
            String contentType = (String) inMessage.get(Message.CONTENT_TYPE);
            if (contentType == null) {
                contentType = "*/*";
            }
            List<MediaType> acceptContentType = (List<MediaType>) exchange.get(Message.ACCEPT_CONTENT_TYPE);
            result = checkSubResultObject(result, subResourcePath);
            final Class<?> subResponseType;
            if (result.getClass() == Class.class) {
                ResourceContext rc = new ResourceContextImpl(inMessage, ori);
                result = rc.getResource((Class<?>) result);
                subResponseType = InjectionUtils.getActualType(methodToInvoke.getGenericReturnType());
            } else {
                subResponseType = methodToInvoke.getReturnType();
            }
            subCri = cri.getSubResource(subResponseType, ClassHelper.getRealClass(exchange.getBus(), result), result);
            if (subCri == null) {
                org.apache.cxf.common.i18n.Message errorM = new org.apache.cxf.common.i18n.Message("NO_SUBRESOURCE_FOUND", BUNDLE, subResourcePath);
                LOG.severe(errorM.toString());
                throw ExceptionUtils.toNotFoundException(null, null);
            }
            OperationResourceInfo subOri = JAXRSUtils.findTargetMethod(Collections.singletonMap(subCri, values), inMessage, httpMethod, values, contentType, acceptContentType);
            exchange.put(OperationResourceInfo.class, subOri);
            inMessage.put(URITemplate.TEMPLATE_PARAMETERS, values);
            inMessage.put(URITemplate.URI_TEMPLATE, JAXRSUtils.getUriTemplate(inMessage, subCri, ori, subOri));
            if (!subOri.isSubResourceLocator() && JAXRSUtils.runContainerRequestFilters(providerFactory, inMessage, false, subOri.getNameBindings())) {
                return new MessageContentsList(exchange.get(Response.class));
            }
            // work out request parameters for the sub-resource class. Here we
            // presume InputStream has not been consumed yet by the root resource class.
            List<Object> newParams = JAXRSUtils.processParameters(subOri, values, inMessage);
            inMessage.setContent(List.class, newParams);
            return this.invoke(exchange, newParams, result);
        } catch (IOException ex) {
            Response resp = JAXRSUtils.convertFaultToResponse(ex, inMessage);
            if (resp == null) {
                resp = JAXRSUtils.convertFaultToResponse(ex, inMessage);
            }
            return new MessageContentsList(resp);
        } catch (WebApplicationException ex) {
            Response excResponse;
            if (JAXRSUtils.noResourceMethodForOptions(ex.getResponse(), (String) inMessage.get(Message.HTTP_REQUEST_METHOD))) {
                excResponse = JAXRSUtils.createResponse(Collections.singletonList(subCri), null, null, 200, true);
            } else {
                excResponse = JAXRSUtils.convertFaultToResponse(ex, inMessage);
            }
            return new MessageContentsList(excResponse);
        }
    }
    setResponseContentTypeIfNeeded(inMessage, result);
    return result;
}
Also used : ServerProviderFactory(org.apache.cxf.jaxrs.provider.ServerProviderFactory) ResourceContext(javax.ws.rs.container.ResourceContext) Message(org.apache.cxf.message.Message) MessageContentsList(org.apache.cxf.message.MessageContentsList) WebApplicationException(javax.ws.rs.WebApplicationException) ClassLoaderHolder(org.apache.cxf.common.classloader.ClassLoaderUtils.ClassLoaderHolder) Fault(org.apache.cxf.interceptor.Fault) AsyncResponseImpl(org.apache.cxf.jaxrs.impl.AsyncResponseImpl) MediaType(javax.ws.rs.core.MediaType) MessageContentsList(org.apache.cxf.message.MessageContentsList) List(java.util.List) ResourceContextImpl(org.apache.cxf.jaxrs.impl.ResourceContextImpl) ClassResourceInfo(org.apache.cxf.jaxrs.model.ClassResourceInfo) Method(java.lang.reflect.Method) IOException(java.io.IOException) AsyncResponse(javax.ws.rs.container.AsyncResponse) Response(javax.ws.rs.core.Response) OperationResourceInfo(org.apache.cxf.jaxrs.model.OperationResourceInfo) Application(javax.ws.rs.core.Application)

Aggregations

ResourceContext (javax.ws.rs.container.ResourceContext)2 Application (javax.ws.rs.core.Application)2 ClassResourceInfo (org.apache.cxf.jaxrs.model.ClassResourceInfo)2 OperationResourceInfo (org.apache.cxf.jaxrs.model.OperationResourceInfo)2 Message (org.apache.cxf.message.Message)2 IOException (java.io.IOException)1 Method (java.lang.reflect.Method)1 HashMap (java.util.HashMap)1 List (java.util.List)1 Map (java.util.Map)1 ServletConfig (javax.servlet.ServletConfig)1 ServletRequest (javax.servlet.ServletRequest)1 HttpServletRequest (javax.servlet.http.HttpServletRequest)1 HttpServletResponse (javax.servlet.http.HttpServletResponse)1 WebApplicationException (javax.ws.rs.WebApplicationException)1 AsyncResponse (javax.ws.rs.container.AsyncResponse)1 ResourceInfo (javax.ws.rs.container.ResourceInfo)1 Configuration (javax.ws.rs.core.Configuration)1 HttpHeaders (javax.ws.rs.core.HttpHeaders)1 MediaType (javax.ws.rs.core.MediaType)1