You are viewing a plain text version of this content. The canonical link for it is here.
Posted to dev@cxf.apache.org by GitBox <gi...@apache.org> on 2017/11/15 13:27:56 UTC

[GitHub] reta closed pull request #339: CXF-7544: Support @Context-based injection into proxied CDI beans

reta closed pull request #339: CXF-7544: Support @Context-based injection into proxied CDI beans
URL: https://github.com/apache/cxf/pull/339
 
 
   

This is a PR merged from a forked repository.
As GitHub hides the original diff on merge, it is displayed below for
the sake of provenance:

As this is a foreign pull request (from a fork), the diff is supplied
below (as it won't show otherwise due to GitHub magic):

diff --git a/integration/cdi/src/main/java/org/apache/cxf/cdi/CdiClassUnwrapper.java b/integration/cdi/src/main/java/org/apache/cxf/cdi/CdiClassUnwrapper.java
index c32e6690981..ac54da90535 100644
--- a/integration/cdi/src/main/java/org/apache/cxf/cdi/CdiClassUnwrapper.java
+++ b/integration/cdi/src/main/java/org/apache/cxf/cdi/CdiClassUnwrapper.java
@@ -22,8 +22,18 @@
 
 import org.apache.cxf.common.util.ClassUnwrapper;
 
+/**
+ * Unwraps the CDI proxy classes into real classes.
+ */
 class CdiClassUnwrapper implements ClassUnwrapper {
-    private static final Pattern PROXY_PATTERN = Pattern.compile(".+\\$\\$.+Proxy");
+    /**
+     * Known proxy patterns for OWB and Weld:
+     * 
+     *  Xxx$$OwbNormalScopeProxy0
+     *  Xxx$Proxy$_$$_WeldClientProxy
+     *  
+     */
+    private static final Pattern PROXY_PATTERN = Pattern.compile(".+\\$\\$.+Proxy\\d*");
 
     CdiClassUnwrapper() {
 
diff --git a/integration/cdi/src/main/java/org/apache/cxf/cdi/JAXRSCdiResourceExtension.java b/integration/cdi/src/main/java/org/apache/cxf/cdi/JAXRSCdiResourceExtension.java
index ce23e1a924c..823ae5e8291 100644
--- a/integration/cdi/src/main/java/org/apache/cxf/cdi/JAXRSCdiResourceExtension.java
+++ b/integration/cdi/src/main/java/org/apache/cxf/cdi/JAXRSCdiResourceExtension.java
@@ -27,6 +27,7 @@
 import java.util.ServiceLoader;
 import java.util.Set;
 
+import javax.enterprise.context.ApplicationScoped;
 import javax.enterprise.context.spi.CreationalContext;
 import javax.enterprise.event.Observes;
 import javax.enterprise.inject.spi.AfterBeanDiscovery;
@@ -38,10 +39,13 @@
 import javax.enterprise.inject.spi.Extension;
 import javax.enterprise.inject.spi.InjectionTarget;
 import javax.enterprise.inject.spi.ProcessBean;
+import javax.enterprise.inject.spi.ProcessInjectionTarget;
 import javax.enterprise.inject.spi.ProcessProducerField;
 import javax.enterprise.inject.spi.ProcessProducerMethod;
 import javax.ws.rs.ApplicationPath;
 import javax.ws.rs.Path;
+import javax.ws.rs.container.ContainerRequestFilter;
+import javax.ws.rs.container.ContainerResponseFilter;
 import javax.ws.rs.core.Application;
 import javax.ws.rs.ext.MessageBodyReader;
 import javax.ws.rs.ext.MessageBodyWriter;
@@ -51,6 +55,7 @@
 import org.apache.cxf.bus.extension.ExtensionManagerBus;
 import org.apache.cxf.cdi.event.DisposableCreationalContext;
 import org.apache.cxf.cdi.extension.JAXRSServerFactoryCustomizationExtension;
+import org.apache.cxf.cdi.inject.ContextInjectionTarget;
 import org.apache.cxf.feature.Feature;
 import org.apache.cxf.jaxrs.JAXRSServerFactoryBean;
 import org.apache.cxf.jaxrs.provider.ServerConfigurableFactory;
@@ -122,6 +127,21 @@ public void addResourceProvider(final CdiResourceProvider other) {
         }
     }
     
+    public <X> void processInjectionTarget(@Observes final ProcessInjectionTarget<X> target, 
+            final BeanManager beanManager) {
+        
+        final InjectionTarget<X> injectionTarget = target.getInjectionTarget();
+        final AnnotatedType<X> type = target.getAnnotatedType();
+        
+        // The beans annotated with @ApplicationScoped will be very likely proxified.
+        boolean isApplicationScoped = type.isAnnotationPresent(ApplicationScoped.class);
+        if (isApplicationScoped && isProvider(type)) {
+            // Limit the scope to providers for now
+            final InjectionTarget<X> contextual = new ContextInjectionTarget<>(injectionTarget, type.getJavaClass());
+            target.setInjectionTarget(contextual);
+        }
+    }
+    
     public <T, X> void collect(@Observes final ProcessProducerField< T, X > event) {
         final Type baseType = event.getAnnotatedProducerField().getBaseType();
         processProducer(event, baseType);
@@ -421,4 +441,16 @@ private void customize(final BeanManager beanManager, final JAXRSServerFactoryBe
         }
     }
 
+    /**
+     * Tries to detect of a particular annotated type corresponds to provider
+     * @param type annotated type 
+     * @return "true" if annotated type corresponds to provider, "false" otherwise
+     */
+    private boolean isProvider(final AnnotatedType<?> type) {
+        return type.isAnnotationPresent(Provider.class) 
+            || ContainerRequestFilter.class.isAssignableFrom(type.getJavaClass()) 
+            || ContainerResponseFilter.class.isAssignableFrom(type.getJavaClass()) 
+            || MessageBodyWriter.class.isAssignableFrom(type.getJavaClass()) 
+            || MessageBodyReader.class.isAssignableFrom(type.getJavaClass());
+    }
 }
diff --git a/integration/cdi/src/main/java/org/apache/cxf/cdi/inject/ContextInjectionTarget.java b/integration/cdi/src/main/java/org/apache/cxf/cdi/inject/ContextInjectionTarget.java
new file mode 100644
index 00000000000..ca6ac2c3820
--- /dev/null
+++ b/integration/cdi/src/main/java/org/apache/cxf/cdi/inject/ContextInjectionTarget.java
@@ -0,0 +1,76 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.cxf.cdi.inject;
+
+import java.util.Set;
+
+import javax.enterprise.context.spi.CreationalContext;
+import javax.enterprise.inject.spi.InjectionPoint;
+import javax.enterprise.inject.spi.InjectionTarget;
+
+import org.apache.cxf.jaxrs.provider.ServerProviderFactory;
+import org.apache.cxf.message.Message;
+import org.apache.cxf.phase.PhaseInterceptorChain;
+
+public final class ContextInjectionTarget<X> implements InjectionTarget<X> {
+    private final InjectionTarget<X> delegate;
+    private final Class<?> providerClass;
+    
+    public ContextInjectionTarget(final InjectionTarget<X> delegate, final Class<?> providerClass) {
+        this.delegate = delegate;
+        this.providerClass = providerClass;
+    }
+    
+    @Override
+    public void inject(X instance, CreationalContext<X> ctx) {
+        delegate.inject(instance, ctx);
+        
+        final Message message = PhaseInterceptorChain.getCurrentMessage();
+        if (message != null) {
+            final ServerProviderFactory factory = ServerProviderFactory.getInstance(message);
+            factory.injectContextProxiesIntoProvider(providerClass, instance);
+        }
+    }
+
+    @Override
+    public void postConstruct(X instance) {
+        delegate.postConstruct(instance);
+    }
+
+    @Override
+    public void preDestroy(X instance) {
+        delegate.dispose(instance);
+    }
+
+    @Override
+    public void dispose(X instance) {
+        delegate.dispose(instance);
+    }
+
+    @Override
+    public Set<InjectionPoint> getInjectionPoints() {
+        return delegate.getInjectionPoints();
+    }
+
+    @Override
+    public X produce(CreationalContext<X> ctx) {
+        return delegate.produce(ctx);
+    }
+}
diff --git a/rt/frontend/jaxrs/src/main/java/org/apache/cxf/jaxrs/provider/ServerProviderFactory.java b/rt/frontend/jaxrs/src/main/java/org/apache/cxf/jaxrs/provider/ServerProviderFactory.java
index dda7ee290d3..fff727237fc 100644
--- a/rt/frontend/jaxrs/src/main/java/org/apache/cxf/jaxrs/provider/ServerProviderFactory.java
+++ b/rt/frontend/jaxrs/src/main/java/org/apache/cxf/jaxrs/provider/ServerProviderFactory.java
@@ -24,6 +24,7 @@
 import java.util.Collection;
 import java.util.Collections;
 import java.util.HashMap;
+import java.util.HashSet;
 import java.util.LinkedHashSet;
 import java.util.LinkedList;
 import java.util.List;
@@ -49,6 +50,7 @@
 import org.apache.cxf.Bus;
 import org.apache.cxf.BusFactory;
 import org.apache.cxf.common.util.ClassHelper;
+import org.apache.cxf.common.util.ClassUnwrapper;
 import org.apache.cxf.endpoint.Endpoint;
 import org.apache.cxf.helpers.CastUtils;
 import org.apache.cxf.jaxrs.impl.ConfigurableImpl;
@@ -269,6 +271,32 @@ protected void setProviders(boolean custom, boolean busGlobal, Object... provide
             containerResponseFilters.values());
     }
 
+    /**
+     * Injects the context proxies into the provider identified by a particular 
+     * provider class, using the provider instance supplied. This method is used when
+     * the instance inside ProviderInfo class is pointing out to proxy, not a real class
+     * instance. In this case the contextual properties are not injected properly
+     * (f.e. in case of CDI).
+     * @param providerClass provider class
+     * @param instance provider instance
+     */
+    public void injectContextProxiesIntoProvider(Class<?> providerClass, Object instance) {
+        final ClassUnwrapper unwrapper = (ClassUnwrapper)getBus().getProperty(ClassUnwrapper.class.getName());
+        
+        final Collection<ProviderInfo<?>> infos = findProviderByClass(unwrapper, providerClass,
+            exceptionMappers, postMatchContainerRequestFilters.values(), 
+                preMatchContainerRequestFilters, containerResponseFilters.values());
+        
+        // We may end up with a multiple providers but we don't know exactly which one
+        // is being referenced by provider class.
+        for (final ProviderInfo<?> info: infos) {
+            if (info.contextsAvailable()) {
+                InjectionUtils.injectContextProxiesAndApplication(info, instance, 
+                    application == null ? null : application.getProvider(), this);
+            }
+        }
+    }
+
     @Override
     protected void injectContextProxiesIntoProvider(ProviderInfo<?> pi) {
         injectContextProxiesIntoProvider(pi, application == null ? null : application.getProvider());
@@ -602,4 +630,28 @@ public int compare(ProviderInfo<?> p1, ProviderInfo<?> p2) {
         }
     }
 
+    /**
+     * Finds the providers which correspond to a particular provider class. 
+     */
+    protected Collection<ProviderInfo<?>> findProviderByClass(final ClassUnwrapper unwrapper, 
+            final Class<?> providerClass, final Collection<?> ... providerLists) {
+        
+        final Set<ProviderInfo<?>> providers = new HashSet<>();
+        
+        for (final Collection<?> list: providerLists) {
+            final Collection<ProviderInfo<?>> l2 = CastUtils.cast(list);
+            
+            for (final ProviderInfo<?> pi : l2) {
+                final Class<?> clazz = (unwrapper != null) 
+                    ? unwrapper.getRealClass(pi.getProvider())
+                        : pi.getProvider().getClass();
+                    
+                if (providerClass.equals(clazz)) {
+                    providers.add(pi);
+                }
+            }
+        }
+        
+        return providers;
+    }
 }
diff --git a/systests/cdi/base/src/main/java/org/apache/cxf/systests/cdi/base/BookStorePreMatchingRequestFilter.java b/systests/cdi/base/src/main/java/org/apache/cxf/systests/cdi/base/BookStorePreMatchingRequestFilter.java
new file mode 100644
index 00000000000..7f82b284a46
--- /dev/null
+++ b/systests/cdi/base/src/main/java/org/apache/cxf/systests/cdi/base/BookStorePreMatchingRequestFilter.java
@@ -0,0 +1,43 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.cxf.systests.cdi.base;
+
+import java.io.IOException;
+
+import javax.enterprise.context.ApplicationScoped;
+import javax.ws.rs.container.ContainerRequestContext;
+import javax.ws.rs.container.ContainerRequestFilter;
+import javax.ws.rs.container.PreMatching;
+import javax.ws.rs.core.Context;
+import javax.ws.rs.core.Response;
+import javax.ws.rs.core.UriInfo;
+
+@ApplicationScoped @PreMatching
+public class BookStorePreMatchingRequestFilter implements ContainerRequestFilter {
+    @Context private UriInfo uriInfo;
+    
+    @Override
+    public void filter(ContainerRequestContext requestContext) throws IOException {
+        // Contextual instances should be injected independently
+        if (uriInfo == null || uriInfo.getBaseUri() == null) {
+            requestContext.abortWith(Response.serverError().entity("uriInfo is not set").build());
+        }
+    }
+}
diff --git a/systests/cdi/cdi-owb/cdi-producers-owb/src/test/java/org/apache/cxf/systest/jaxrs/cdi/SampleFeature.java b/systests/cdi/cdi-owb/cdi-producers-owb/src/test/java/org/apache/cxf/systest/jaxrs/cdi/SampleFeature.java
index 309a5ea3a99..9aa26384c81 100644
--- a/systests/cdi/cdi-owb/cdi-producers-owb/src/test/java/org/apache/cxf/systest/jaxrs/cdi/SampleFeature.java
+++ b/systests/cdi/cdi-owb/cdi-producers-owb/src/test/java/org/apache/cxf/systest/jaxrs/cdi/SampleFeature.java
@@ -32,6 +32,7 @@ public boolean configure(FeatureContext context) {
         context.register(AtomFeedProvider.class);
         context.register(BookStoreRequestFilter.class);
         context.register(BookStoreResponseFilter.class);
+        context.register(SampleNestedFeature.class);
         return false;
     }
 }
diff --git a/systests/cdi/cdi-owb/cdi-producers-owb/src/test/java/org/apache/cxf/systest/jaxrs/cdi/SampleNestedFeature.java b/systests/cdi/cdi-owb/cdi-producers-owb/src/test/java/org/apache/cxf/systest/jaxrs/cdi/SampleNestedFeature.java
new file mode 100644
index 00000000000..4e1e47ce7f6
--- /dev/null
+++ b/systests/cdi/cdi-owb/cdi-producers-owb/src/test/java/org/apache/cxf/systest/jaxrs/cdi/SampleNestedFeature.java
@@ -0,0 +1,33 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.cxf.systest.jaxrs.cdi;
+
+import javax.ws.rs.core.Feature;
+import javax.ws.rs.core.FeatureContext;
+
+import org.apache.cxf.systests.cdi.base.BookStorePreMatchingRequestFilter;
+
+public class SampleNestedFeature implements Feature {
+    @Override
+    public boolean configure(FeatureContext context) {
+        context.register(BookStorePreMatchingRequestFilter.class);
+        return false;
+    }
+}
diff --git a/systests/cdi/cdi-weld/cdi-producers-weld/src/test/java/org/apache/cxf/systest/jaxrs/cdi/SampleFeature.java b/systests/cdi/cdi-weld/cdi-producers-weld/src/test/java/org/apache/cxf/systest/jaxrs/cdi/SampleFeature.java
index 309a5ea3a99..9aa26384c81 100644
--- a/systests/cdi/cdi-weld/cdi-producers-weld/src/test/java/org/apache/cxf/systest/jaxrs/cdi/SampleFeature.java
+++ b/systests/cdi/cdi-weld/cdi-producers-weld/src/test/java/org/apache/cxf/systest/jaxrs/cdi/SampleFeature.java
@@ -32,6 +32,7 @@ public boolean configure(FeatureContext context) {
         context.register(AtomFeedProvider.class);
         context.register(BookStoreRequestFilter.class);
         context.register(BookStoreResponseFilter.class);
+        context.register(SampleNestedFeature.class);
         return false;
     }
 }
diff --git a/systests/cdi/cdi-weld/cdi-producers-weld/src/test/java/org/apache/cxf/systest/jaxrs/cdi/SampleNestedFeature.java b/systests/cdi/cdi-weld/cdi-producers-weld/src/test/java/org/apache/cxf/systest/jaxrs/cdi/SampleNestedFeature.java
new file mode 100644
index 00000000000..4e1e47ce7f6
--- /dev/null
+++ b/systests/cdi/cdi-weld/cdi-producers-weld/src/test/java/org/apache/cxf/systest/jaxrs/cdi/SampleNestedFeature.java
@@ -0,0 +1,33 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.cxf.systest.jaxrs.cdi;
+
+import javax.ws.rs.core.Feature;
+import javax.ws.rs.core.FeatureContext;
+
+import org.apache.cxf.systests.cdi.base.BookStorePreMatchingRequestFilter;
+
+public class SampleNestedFeature implements Feature {
+    @Override
+    public boolean configure(FeatureContext context) {
+        context.register(BookStorePreMatchingRequestFilter.class);
+        return false;
+    }
+}


 

----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on GitHub and use the
URL above to go to the specific comment.
 
For queries about this service, please contact Infrastructure at:
users@infra.apache.org


With regards,
Apache Git Services