Search in sources :

Example 21 with SingletonResourceProvider

use of org.apache.cxf.jaxrs.lifecycle.SingletonResourceProvider 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 ApplicationData applicationData = getApplicationData(application, prefix, additionalProviders);
        logApplication(applicationData);
        if (applicationData.getResources().size() == 0) {
            throw new NoResourcesFoundException(applicationData);
        }
        final JAXRSServerFactoryBean factory = newFactory(prefix, createServiceJmxName(classLoader), createEndpointName(application));
        configureFactory(additionalProviders, serviceConfiguration, factory, owbCtx, application);
        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 {
                    if (owbCtx != null) {
                        final BeanManagerImpl bm = owbCtx.getBeanManagerImpl();
                        Bean<?> bean = null;
                        if (bm != null && bm.isInUse()) {
                            try {
                                final Set<Bean<?>> beans = bm.getBeans(clazz);
                                bean = bm.resolve(beans);
                            } catch (final InjectionException ie) {
                                final String msg = "Resource class " + clazz.getName() + " can not be instantiated";
                                LOGGER.warning(msg, ie);
                                throw new WebApplicationException(Response.serverError().entity(msg).build());
                            }
                            if (bean != null && isConsideredSingleton(bean.getScope())) {
                                final Object reference = bm.getReference(bean, bean.getBeanClass(), bm.createCreationalContext(bean));
                                factory.setResourceProvider(clazz, new CdiSingletonResourceProvider(classLoader, clazz, reference, injections, context, owbCtx));
                                continue;
                            }
                        }
                    }
                    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));
        injectApplication(application, factory);
        /*
             * During setApplication CXF will inspect the binding annotations
             * on the Application subclass and apply them to every Resource class
             * definition.  This is how global bindings are supported.  Thus, if
             * setApplication is called before we've called setResourceClasses()
             * binding annotations on the Application subclass will not work.
             *
             * Global binding annotations are tested in:
             * com/sun/ts/tests/jaxrs/spec/filter/globalbinding/JAXRSClient#globalBoundResourceTest_from_standalone
             */
        factory.setApplication(application);
        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 {
            factory.setProvider(new SseContextProvider());
            factory.setProvider(new TomEESseEventSinkContextProvider());
            server = factory.create();
            fixProviders(serviceConfiguration);
            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) WebApplicationException(javax.ws.rs.WebApplicationException) CopyOnWriteArrayList(java.util.concurrent.CopyOnWriteArrayList) ArrayList(java.util.ArrayList) EJBRestServiceInfo(org.apache.openejb.server.rest.EJBRestServiceInfo) SingletonResourceProvider(org.apache.cxf.jaxrs.lifecycle.SingletonResourceProvider) JAXRSServerFactoryBean(org.apache.cxf.jaxrs.JAXRSServerFactoryBean) MBean(org.apache.openejb.api.jmx.MBean) Bean(javax.enterprise.inject.spi.Bean) InjectionException(javax.enterprise.inject.InjectionException) ProviderInfo(org.apache.cxf.jaxrs.model.ProviderInfo) JAXRSServerFactoryBean(org.apache.cxf.jaxrs.JAXRSServerFactoryBean) SseContextProvider(org.apache.cxf.jaxrs.sse.SseContextProvider) TomEESseEventSinkContextProvider(org.apache.openejb.server.cxf.rs.sse.TomEESseEventSinkContextProvider) ManagedEndpoint(org.apache.cxf.endpoint.ManagedEndpoint) Endpoint(org.apache.cxf.endpoint.Endpoint) BeanManagerImpl(org.apache.webbeans.container.BeanManagerImpl) Level(java.util.logging.Level)

Example 22 with SingletonResourceProvider

use of org.apache.cxf.jaxrs.lifecycle.SingletonResourceProvider in project nutch by apache.

the class NutchServer method getResourceProviders.

private List<ResourceProvider> getResourceProviders() {
    List<ResourceProvider> resourceProviders = new ArrayList<>();
    resourceProviders.add(new SingletonResourceProvider(getConfManager()));
    return resourceProviders;
}
Also used : SingletonResourceProvider(org.apache.cxf.jaxrs.lifecycle.SingletonResourceProvider) ResourceProvider(org.apache.cxf.jaxrs.lifecycle.ResourceProvider) ArrayList(java.util.ArrayList) SingletonResourceProvider(org.apache.cxf.jaxrs.lifecycle.SingletonResourceProvider)

Example 23 with SingletonResourceProvider

use of org.apache.cxf.jaxrs.lifecycle.SingletonResourceProvider in project cxf by apache.

the class JAXRSUtilsTest method testSingletonContextFields.

@SuppressWarnings("unchecked")
@Test
public void testSingletonContextFields() throws Exception {
    ClassResourceInfo cri = new ClassResourceInfo(Customer.class, true);
    Customer c = new Customer();
    cri.setResourceProvider(new SingletonResourceProvider(c));
    Message m = createMessage();
    m.put(Message.PROTOCOL_HEADERS, new HashMap<String, List<String>>());
    ServletContext servletContextMock = EasyMock.createNiceMock(ServletContext.class);
    m.put(AbstractHTTPDestination.HTTP_CONTEXT, servletContextMock);
    HttpServletRequest httpRequest = EasyMock.createNiceMock(HttpServletRequest.class);
    m.put(AbstractHTTPDestination.HTTP_REQUEST, httpRequest);
    HttpServletResponse httpResponse = EasyMock.createMock(HttpServletResponse.class);
    m.put(AbstractHTTPDestination.HTTP_RESPONSE, httpResponse);
    InjectionUtils.injectContextProxies(cri, cri.getResourceProvider().getInstance(null));
    InjectionUtils.injectContextFields(c, cri, m);
    InjectionUtils.injectContextMethods(c, cri, m);
    assertSame(ThreadLocalUriInfo.class, c.getUriInfo2().getClass());
    assertSame(UriInfoImpl.class, ((ThreadLocalProxy<UriInfo>) c.getUriInfo2()).get().getClass());
    assertSame(HttpHeadersImpl.class, ((ThreadLocalProxy<HttpHeaders>) c.getHeaders()).get().getClass());
    assertSame(RequestImpl.class, ((ThreadLocalProxy<Request>) c.getRequest()).get().getClass());
    assertSame(ResourceInfoImpl.class, ((ThreadLocalProxy<ResourceInfo>) c.getResourceInfo()).get().getClass());
    assertSame(SecurityContextImpl.class, ((ThreadLocalProxy<SecurityContext>) c.getSecurityContext()).get().getClass());
    assertSame(ProvidersImpl.class, ((ThreadLocalProxy<Providers>) c.getBodyWorkers()).get().getClass());
    assertSame(servletContextMock, ((ThreadLocalProxy<ServletContext>) c.getThreadLocalServletContext()).get());
    assertSame(servletContextMock, ((ThreadLocalProxy<ServletContext>) c.getServletContext()).get());
    assertSame(servletContextMock, ((ThreadLocalProxy<ServletContext>) c.getSuperServletContext()).get());
    HttpServletRequest currentReq = ((ThreadLocalProxy<HttpServletRequest>) c.getServletRequest()).get();
    assertSame(httpRequest, ((HttpServletRequestFilter) currentReq).getRequest());
    HttpServletResponseFilter filter = (HttpServletResponseFilter) ((ThreadLocalProxy<HttpServletResponse>) c.getServletResponse()).get();
    assertSame(httpResponse, filter.getResponse());
}
Also used : ThreadLocalHttpServletRequest(org.apache.cxf.jaxrs.impl.tl.ThreadLocalHttpServletRequest) HttpServletRequest(javax.servlet.http.HttpServletRequest) ThreadLocalProxy(org.apache.cxf.jaxrs.impl.tl.ThreadLocalProxy) Message(org.apache.cxf.message.Message) Customer(org.apache.cxf.jaxrs.Customer) ClassResourceInfo(org.apache.cxf.jaxrs.model.ClassResourceInfo) ServletContext(javax.servlet.ServletContext) HttpServletResponse(javax.servlet.http.HttpServletResponse) List(java.util.List) ArrayList(java.util.ArrayList) SingletonResourceProvider(org.apache.cxf.jaxrs.lifecycle.SingletonResourceProvider) HttpServletResponseFilter(org.apache.cxf.jaxrs.impl.HttpServletResponseFilter) Test(org.junit.Test)

Example 24 with SingletonResourceProvider

use of org.apache.cxf.jaxrs.lifecycle.SingletonResourceProvider in project cxf by apache.

the class ClientCacheTest method createClient.

private WebClient createClient(CXFCacheControlFeature feature) {
    Bus bus = BusFactory.newInstance().createBus();
    JAXRSServerFactoryBean sf = new JAXRSServerFactoryBean();
    sf.setBus(bus);
    sf.setResourceClasses(TheServer.class);
    sf.setResourceProvider(TheServer.class, new SingletonResourceProvider(new TheServer(), false));
    sf.setTransportId(LocalTransportFactory.TRANSPORT_ID);
    sf.setAddress(ADDRESS);
    sf.create();
    JAXRSClientFactoryBean bean = new JAXRSClientFactoryBean();
    bean.setBus(bus);
    bean.setAddress(ADDRESS);
    bean.setFeatures(Collections.singletonList(feature));
    bean.setTransportId(LocalTransportFactory.TRANSPORT_ID);
    return bean.createWebClient().accept("text/plain").header(HttpHeaders.CACHE_CONTROL, "public");
}
Also used : Bus(org.apache.cxf.Bus) JAXRSClientFactoryBean(org.apache.cxf.jaxrs.client.JAXRSClientFactoryBean) JAXRSServerFactoryBean(org.apache.cxf.jaxrs.JAXRSServerFactoryBean) SingletonResourceProvider(org.apache.cxf.jaxrs.lifecycle.SingletonResourceProvider)

Example 25 with SingletonResourceProvider

use of org.apache.cxf.jaxrs.lifecycle.SingletonResourceProvider in project cxf by apache.

the class ClientCacheTest method bind.

@BeforeClass
public static void bind() throws Exception {
    final JAXRSServerFactoryBean sf = new JAXRSServerFactoryBean();
    sf.setResourceClasses(TheServer.class);
    sf.setResourceProvider(TheServer.class, new SingletonResourceProvider(new TheServer(), false));
    sf.setTransportId(LocalTransportFactory.TRANSPORT_ID);
    sf.setAddress(ADDRESS);
    server = sf.create();
}
Also used : JAXRSServerFactoryBean(org.apache.cxf.jaxrs.JAXRSServerFactoryBean) SingletonResourceProvider(org.apache.cxf.jaxrs.lifecycle.SingletonResourceProvider) BeforeClass(org.junit.BeforeClass)

Aggregations

SingletonResourceProvider (org.apache.cxf.jaxrs.lifecycle.SingletonResourceProvider)84 JAXRSServerFactoryBean (org.apache.cxf.jaxrs.JAXRSServerFactoryBean)63 Bus (org.apache.cxf.Bus)17 JacksonJsonProvider (com.fasterxml.jackson.jaxrs.json.JacksonJsonProvider)15 ArrayList (java.util.ArrayList)14 LoggingOutInterceptor (org.apache.cxf.ext.logging.LoggingOutInterceptor)14 ResourceProvider (org.apache.cxf.jaxrs.lifecycle.ResourceProvider)9 HashMap (java.util.HashMap)7 Before (org.junit.Before)7 SpringBusFactory (org.apache.cxf.bus.spring.SpringBusFactory)5 ClassResourceInfo (org.apache.cxf.jaxrs.model.ClassResourceInfo)5 Map (java.util.Map)4 ReactiveIOCustomizer (org.apache.cxf.jaxrs.rx3.server.ReactiveIOCustomizer)4 DetectorResource (org.apache.tika.server.resource.DetectorResource)4 MetadataResource (org.apache.tika.server.resource.MetadataResource)4 HttpServletRequest (javax.servlet.http.HttpServletRequest)3 HttpServletResponse (javax.servlet.http.HttpServletResponse)3 Feature (org.apache.cxf.feature.Feature)3 ReactiveIOCustomizer (org.apache.cxf.jaxrs.rx2.server.ReactiveIOCustomizer)3 Message (org.apache.cxf.message.Message)3