Search in sources :

Example 1 with ServerProviderFactory

use of org.apache.cxf.jaxrs.provider.ServerProviderFactory in project tomee by apache.

the class CxfRsHttpListener method deployApplication.

@Override
public void deployApplication(final Application application, final String prefix, final String webContext, final Collection<Object> additionalProviders, final Map<String, EJBRestServiceInfo> restEjbs, final ClassLoader classLoader, final Collection<Injection> injections, final Context context, final WebBeansContext owbCtx, final ServiceConfiguration serviceConfiguration) {
    final ClassLoader oldLoader = Thread.currentThread().getContextClassLoader();
    Thread.currentThread().setContextClassLoader(CxfUtil.initBusLoader());
    try {
        final JAXRSServerFactoryBean factory = newFactory(prefix, createServiceJmxName(classLoader), createEndpointName(application));
        configureFactory(additionalProviders, serviceConfiguration, factory, owbCtx);
        factory.setApplication(application);
        final List<Class<?>> classes = new ArrayList<>();
        for (final Class<?> clazz : application.getClasses()) {
            if (!additionalProviders.contains(clazz) && !clazz.isInterface()) {
                classes.add(clazz);
                final EJBRestServiceInfo restServiceInfo = getEjbRestServiceInfo(restEjbs, clazz);
                if (restServiceInfo != null) {
                    final Object proxy = ProxyEJB.subclassProxy(restServiceInfo.context);
                    factory.setResourceProvider(clazz, new NoopResourceProvider(restServiceInfo.context.getBeanClass(), proxy));
                } else {
                    factory.setResourceProvider(clazz, new OpenEJBPerRequestPojoResourceProvider(classLoader, clazz, injections, context, owbCtx));
                }
            }
        }
        for (final Object o : application.getSingletons()) {
            if (!additionalProviders.contains(o)) {
                final Class<?> clazz = realClass(o.getClass());
                classes.add(clazz);
                final EJBRestServiceInfo restServiceInfo = getEjbRestServiceInfo(restEjbs, clazz);
                if (restServiceInfo != null) {
                    final Object proxy = ProxyEJB.subclassProxy(restServiceInfo.context);
                    factory.setResourceProvider(clazz, new NoopResourceProvider(restServiceInfo.context.getBeanClass(), proxy));
                } else {
                    if (owbCtx != null && owbCtx.getBeanManagerImpl().isInUse()) {
                        final CdiSingletonResourceProvider provider = new CdiSingletonResourceProvider(classLoader, clazz, o, injections, context, owbCtx);
                        singletons.add(provider);
                        factory.setResourceProvider(clazz, provider);
                    } else {
                        factory.setResourceProvider(clazz, new SingletonResourceProvider(o));
                    }
                }
            }
        }
        factory.setResourceClasses(classes);
        factory.setInvoker(new AutoJAXRSInvoker(restEjbs));
        this.context = webContext;
        if (!webContext.startsWith("/")) {
            this.context = "/" + webContext;
        }
        // /webcontext/servlet for event firing
        final Level level = SERVER_IMPL_LOGGER.getLevel();
        try {
            SERVER_IMPL_LOGGER.setLevel(Level.OFF);
        } catch (final UnsupportedOperationException e) {
        // ignore
        }
        try {
            server = factory.create();
            fixProviderIfKnown();
            fireServerCreated(oldLoader);
            final ServerProviderFactory spf = ServerProviderFactory.class.cast(server.getEndpoint().get(ServerProviderFactory.class.getName()));
            LOGGER.info("Using readers:");
            for (final Object provider : List.class.cast(Reflections.get(spf, "messageReaders"))) {
                LOGGER.info("     " + ProviderInfo.class.cast(provider).getProvider());
            }
            LOGGER.info("Using writers:");
            for (final Object provider : List.class.cast(Reflections.get(spf, "messageWriters"))) {
                LOGGER.info("     " + ProviderInfo.class.cast(provider).getProvider());
            }
            LOGGER.info("Using exception mappers:");
            for (final Object provider : List.class.cast(Reflections.get(spf, "exceptionMappers"))) {
                LOGGER.info("     " + ProviderInfo.class.cast(provider).getProvider());
            }
        } finally {
            try {
                SERVER_IMPL_LOGGER.setLevel(level);
            } catch (final UnsupportedOperationException e) {
            // ignore
            }
        }
        final int servletIdx = 1 + this.context.substring(1).indexOf('/');
        if (servletIdx > 0) {
            this.servlet = this.context.substring(servletIdx);
            this.context = this.context.substring(0, servletIdx);
        }
        destination = (HttpDestination) server.getDestination();
        final String base;
        if (prefix.endsWith("/")) {
            base = prefix.substring(0, prefix.length() - 1);
        } else if (prefix.endsWith(wildcard)) {
            base = prefix.substring(0, prefix.length() - wildcard.length());
        } else {
            base = prefix;
        }
        // stack info to log to get nice logs
        logEndpoints(application, prefix, restEjbs, factory, base);
    } finally {
        if (oldLoader != null) {
            CxfUtil.clearBusLoader(oldLoader);
        }
    }
}
Also used : ServerProviderFactory(org.apache.cxf.jaxrs.provider.ServerProviderFactory) JAXRSServerFactoryBean(org.apache.cxf.jaxrs.JAXRSServerFactoryBean) CopyOnWriteArrayList(java.util.concurrent.CopyOnWriteArrayList) ArrayList(java.util.ArrayList) EJBRestServiceInfo(org.apache.openejb.server.rest.EJBRestServiceInfo) SingletonResourceProvider(org.apache.cxf.jaxrs.lifecycle.SingletonResourceProvider) ManagedEndpoint(org.apache.cxf.endpoint.ManagedEndpoint) Endpoint(org.apache.cxf.endpoint.Endpoint) ProviderInfo(org.apache.cxf.jaxrs.model.ProviderInfo) Level(java.util.logging.Level)

Example 2 with ServerProviderFactory

use of org.apache.cxf.jaxrs.provider.ServerProviderFactory in project tomee by apache.

the class CxfRsHttpListener method fixProviderIfKnown.

private void fixProviderIfKnown() {
    final ServerProviderFactory spf = ServerProviderFactory.class.cast(server.getEndpoint().get(ServerProviderFactory.class.getName()));
    for (final String field : asList("messageWriters", "messageReaders")) {
        final List<ProviderInfo<?>> values = List.class.cast(Reflections.get(spf, field));
        boolean customJsonProvider = false;
        for (final ProviderInfo<?> o : values) {
            // using getName to not suppose any classloader setup
            final String name = o.getResourceClass().getName();
            if ("org.apache.johnzon.jaxrs.ConfigurableJohnzonProvider".equals(name) || "org.apache.johnzon.jaxrs.jsonb.jaxrs.JsonbJaxrsProvider".equals(name) || // contains in case of proxying
            name.contains("com.fasterxml.jackson.jaxrs.json")) {
                customJsonProvider = true;
                // cause we only handle json for now
                break;
            }
        }
        if (customJsonProvider) {
            // remove JohnzonProvider default versions
            final Iterator<ProviderInfo<?>> it = values.iterator();
            while (it.hasNext()) {
                final String name = it.next().getResourceClass().getName();
                if ("org.apache.johnzon.jaxrs.JohnzonProvider".equals(name) || "org.apache.openejb.server.cxf.rs.CxfRSService$TomEEJohnzonProvider".equals(name)) {
                    it.remove();
                    break;
                }
            }
        }
    }
}
Also used : ServerProviderFactory(org.apache.cxf.jaxrs.provider.ServerProviderFactory) ProviderInfo(org.apache.cxf.jaxrs.model.ProviderInfo)

Example 3 with ServerProviderFactory

use of org.apache.cxf.jaxrs.provider.ServerProviderFactory 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);
    if (cri.isRoot()) {
        cri.injectContexts(resourceObject, ori, inMessage);
        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);
            Class<?> subResponseType = null;
            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);
            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)

Example 4 with ServerProviderFactory

use of org.apache.cxf.jaxrs.provider.ServerProviderFactory in project cxf by apache.

the class JAXRSServerFactoryBean method setupFactory.

protected ServerProviderFactory setupFactory(Endpoint ep) {
    ServerProviderFactory factory = ServerProviderFactory.createInstance(getBus());
    setBeanInfo(factory);
    factory.setApplicationProvider(appProvider);
    super.setupFactory(factory, ep);
    return factory;
}
Also used : ServerProviderFactory(org.apache.cxf.jaxrs.provider.ServerProviderFactory)

Example 5 with ServerProviderFactory

use of org.apache.cxf.jaxrs.provider.ServerProviderFactory in project cxf by apache.

the class SseFeature method initialize.

@Override
public void initialize(Server server, Bus bus) {
    final List<Object> providers = new ArrayList<>();
    providers.add(new SseAtmosphereEventSinkContextProvider());
    providers.add(new SseContextProvider());
    ((ServerProviderFactory) server.getEndpoint().get(ServerProviderFactory.class.getName())).setUserProviders(providers);
}
Also used : ServerProviderFactory(org.apache.cxf.jaxrs.provider.ServerProviderFactory) SseAtmosphereEventSinkContextProvider(org.apache.cxf.jaxrs.sse.atmosphere.SseAtmosphereEventSinkContextProvider) ArrayList(java.util.ArrayList)

Aggregations

ServerProviderFactory (org.apache.cxf.jaxrs.provider.ServerProviderFactory)16 ArrayList (java.util.ArrayList)5 Application (javax.ws.rs.core.Application)4 Test (org.junit.Test)4 ClassResourceInfo (org.apache.cxf.jaxrs.model.ClassResourceInfo)3 Message (org.apache.cxf.message.Message)3 IOException (java.io.IOException)2 HashSet (java.util.HashSet)2 List (java.util.List)2 Properties (java.util.Properties)2 Level (java.util.logging.Level)2 WebApplicationException (javax.ws.rs.WebApplicationException)2 MediaType (javax.ws.rs.core.MediaType)2 Response (javax.ws.rs.core.Response)2 ClassLoaderHolder (org.apache.cxf.common.classloader.ClassLoaderUtils.ClassLoaderHolder)2 Endpoint (org.apache.cxf.endpoint.Endpoint)2 JAXRSServiceFactoryBean (org.apache.cxf.jaxrs.JAXRSServiceFactoryBean)2 RequestPreprocessor (org.apache.cxf.jaxrs.impl.RequestPreprocessor)2 OperationResourceInfo (org.apache.cxf.jaxrs.model.OperationResourceInfo)2 ProviderInfo (org.apache.cxf.jaxrs.model.ProviderInfo)2