andymc12 closed pull request #457: Issue 7868: Ensure providers registered via 
MP Config are honored
URL: https://github.com/apache/cxf/pull/457
 
 
   

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/rt/rs/microprofile-client/pom.xml 
b/rt/rs/microprofile-client/pom.xml
index 359b492276e..3f929b84464 100644
--- a/rt/rs/microprofile-client/pom.xml
+++ b/rt/rs/microprofile-client/pom.xml
@@ -86,6 +86,11 @@
             <artifactId>junit</artifactId>
             <scope>test</scope>
         </dependency>
+        <dependency>
+            <groupId>org.easymock</groupId>
+            <artifactId>easymock</artifactId>
+            <scope>test</scope>
+        </dependency>
         <dependency>
             <groupId>org.apache.cxf</groupId>
             <artifactId>cxf-core</artifactId>
diff --git 
a/rt/rs/microprofile-client/src/main/java/org/apache/cxf/microprofile/client/MicroProfileClientFactoryBean.java
 
b/rt/rs/microprofile-client/src/main/java/org/apache/cxf/microprofile/client/MicroProfileClientFactoryBean.java
index 9abee1a418f..479cabb8a19 100644
--- 
a/rt/rs/microprofile-client/src/main/java/org/apache/cxf/microprofile/client/MicroProfileClientFactoryBean.java
+++ 
b/rt/rs/microprofile-client/src/main/java/org/apache/cxf/microprofile/client/MicroProfileClientFactoryBean.java
@@ -46,7 +46,7 @@
 public class MicroProfileClientFactoryBean extends JAXRSClientFactoryBean {
     private final Comparator<ProviderInfo<?>> comparator;
     private final List<Object> registeredProviders;
-    private Configuration configuration;
+    private final Configuration configuration;
     private ClassLoader proxyLoader;
     private boolean inheritHeaders;
     private ExecutorService executorService;
@@ -99,10 +99,10 @@ protected ClientProxyImpl 
createClientProxy(ClassResourceInfo cri, boolean isRoo
                                                 ClientState actualState, 
Object[] varValues) {
         if (actualState == null) {
             return new MicroProfileClientProxyImpl(URI.create(getAddress()), 
proxyLoader, cri, isRoot,
-                    inheritHeaders, executorService, varValues);
+                    inheritHeaders, executorService, configuration, varValues);
         } else {
             return new MicroProfileClientProxyImpl(actualState, proxyLoader, 
cri, isRoot,
-                    inheritHeaders, executorService, varValues);
+                    inheritHeaders, executorService, configuration, varValues);
         }
     }
 
diff --git 
a/rt/rs/microprofile-client/src/main/java/org/apache/cxf/microprofile/client/cdi/RestClientBean.java
 
b/rt/rs/microprofile-client/src/main/java/org/apache/cxf/microprofile/client/cdi/RestClientBean.java
index d9f47e95a80..ea503ef3570 100644
--- 
a/rt/rs/microprofile-client/src/main/java/org/apache/cxf/microprofile/client/cdi/RestClientBean.java
+++ 
b/rt/rs/microprofile-client/src/main/java/org/apache/cxf/microprofile/client/cdi/RestClientBean.java
@@ -24,11 +24,16 @@
 import java.util.ArrayList;
 import java.util.Arrays;
 import java.util.Collections;
+import java.util.HashMap;
 import java.util.HashSet;
 import java.util.List;
+import java.util.Map;
 import java.util.NoSuchElementException;
 import java.util.Set;
+import java.util.logging.Level;
+import java.util.logging.Logger;
 
+import javax.annotation.Priority;
 import javax.enterprise.context.Dependent;
 import javax.enterprise.context.spi.CreationalContext;
 import javax.enterprise.inject.Default;
@@ -37,16 +42,22 @@
 import javax.enterprise.inject.spi.InjectionPoint;
 import javax.enterprise.inject.spi.PassivationCapable;
 import javax.enterprise.util.AnnotationLiteral;
+import javax.ws.rs.Priorities;
 
 import org.apache.cxf.common.classloader.ClassLoaderUtils;
+import org.apache.cxf.common.logging.LogUtils;
 import org.apache.cxf.microprofile.client.CxfTypeSafeClientBuilder;
 import org.apache.cxf.microprofile.client.config.ConfigFacade;
+import org.eclipse.microprofile.rest.client.RestClientBuilder;
 import org.eclipse.microprofile.rest.client.inject.RestClient;
 
 public class RestClientBean implements Bean<Object>, PassivationCapable {
     public static final String REST_URL_FORMAT = "%s/mp-rest/url";
     public static final String REST_URI_FORMAT = "%s/mp-rest/uri";
     public static final String REST_SCOPE_FORMAT = "%s/mp-rest/scope";
+    public static final String REST_PROVIDERS_FORMAT = "%s/mp-rest/providers";
+    public static final String REST_PROVIDERS_PRIORITY_FORMAT = 
"%s/mp-rest/providers/%s/priority";
+    private static final Logger LOG = 
LogUtils.getL7dLogger(RestClientBean.class);
     private static final Default DEFAULT_LITERAL = new DefaultLiteral();
     private final Class<?> clientInterface;
     private final Class<? extends Annotation> scope;
@@ -79,9 +90,16 @@ public boolean isNullable() {
 
     @Override
     public Object create(CreationalContext<Object> creationalContext) {
-        CxfTypeSafeClientBuilder builder = new CxfTypeSafeClientBuilder();
+        RestClientBuilder builder = new CxfTypeSafeClientBuilder();
         String baseUri = getBaseUri();
-        return builder.baseUri(URI.create(baseUri)).build(clientInterface);
+        builder = builder.baseUri(URI.create(baseUri));
+        List<Class<?>> providers = getConfiguredProviders();
+        Map<Class<?>, Integer> providerPriorities = 
getConfiguredProviderPriorities(providers);
+        for (Class<?> providerClass : providers) {
+            builder = builder.register(providerClass, 
+                                       
providerPriorities.getOrDefault(providerClass, Priorities.USER));
+        }
+        return builder.build(clientInterface);
     }
 
     @Override
@@ -168,6 +186,41 @@ private String getBaseUri() {
         }
     }
 
+    List<Class<?>> getConfiguredProviders() {
+        String property = String.format(REST_PROVIDERS_FORMAT, 
clientInterface.getName());
+        String providersList = ConfigFacade.getOptionalValue(property, 
String.class).orElse("");
+        String[] providerClassNames = providersList.split(",");
+        List<Class<?>> providers = new ArrayList<>();
+        for (int i = 0; i < providerClassNames.length; i++) {
+            try {
+                
providers.add(ClassLoaderUtils.loadClass(providerClassNames[i], 
RestClientBean.class));
+            } catch (ClassNotFoundException e) {
+                LOG.log(Level.WARNING,
+                        "Could not load provider, {0}, configured for Rest 
Client interface, {1} ",
+                        new Object[]{providerClassNames[i], 
clientInterface.getName()});
+            }
+        }
+        return providers;
+    }
+
+    Map<Class<?>, Integer> getConfiguredProviderPriorities(List<Class<?>> 
providers) {
+        Map<Class<?>, Integer> map = new HashMap<>();
+        for (Class<?> providerClass : providers) {
+            String property = String.format(REST_PROVIDERS_PRIORITY_FORMAT, 
+                                            clientInterface.getName(),
+                                            providerClass.getName());
+            Integer priority = ConfigFacade.getOptionalValue(property, 
Integer.class)
+                                           
.orElse(getPriorityFromClass(providerClass, Priorities.USER));
+            map.put(providerClass, priority);
+        }
+        return map;
+    }
+
+    private static int getPriorityFromClass(Class<?> providerClass, int 
defaultValue) {
+        Priority p = providerClass.getAnnotation(Priority.class);
+        return p != null ? p.value() : defaultValue;
+    }
+
     private static final class DefaultLiteral extends 
AnnotationLiteral<Default> implements Default {
         private static final long serialVersionUID = 1L;
 
diff --git 
a/rt/rs/microprofile-client/src/main/java/org/apache/cxf/microprofile/client/proxy/MicroProfileClientProxyImpl.java
 
b/rt/rs/microprofile-client/src/main/java/org/apache/cxf/microprofile/client/proxy/MicroProfileClientProxyImpl.java
index 33c57ca48bd..1296cdc69af 100644
--- 
a/rt/rs/microprofile-client/src/main/java/org/apache/cxf/microprofile/client/proxy/MicroProfileClientProxyImpl.java
+++ 
b/rt/rs/microprofile-client/src/main/java/org/apache/cxf/microprofile/client/proxy/MicroProfileClientProxyImpl.java
@@ -28,6 +28,7 @@
 import java.util.concurrent.ExecutorService;
 
 import javax.ws.rs.client.InvocationCallback;
+import javax.ws.rs.core.Configuration;
 import javax.ws.rs.core.MultivaluedMap;
 import javax.ws.rs.core.Response;
 
@@ -56,19 +57,23 @@ public void completed(Object o) { }
 
     private final MPAsyncInvocationInterceptorImpl aiiImpl = new 
MPAsyncInvocationInterceptorImpl();
 
+    //CHECKSTYLE:OFF
     public MicroProfileClientProxyImpl(URI baseURI, ClassLoader loader, 
ClassResourceInfo cri,
                                        boolean isRoot, boolean inheritHeaders, 
ExecutorService executorService,
-                                       Object... varValues) {
+                                       Configuration configuration, Object... 
varValues) {
         super(new LocalClientState(baseURI), loader, cri, isRoot, 
inheritHeaders, varValues);
         cfg.getRequestContext().put(EXECUTOR_SERVICE_PROPERTY, 
executorService);
+        cfg.getRequestContext().putAll(configuration.getProperties());
     }
 
     public MicroProfileClientProxyImpl(ClientState initialState, ClassLoader 
loader, ClassResourceInfo cri,
                                        boolean isRoot, boolean inheritHeaders, 
ExecutorService executorService,
-                                       Object... varValues) {
+                                       Configuration configuration, Object... 
varValues) {
         super(initialState, loader, cri, isRoot, inheritHeaders, varValues);
         cfg.getRequestContext().put(EXECUTOR_SERVICE_PROPERTY, 
executorService);
+        cfg.getRequestContext().putAll(configuration.getProperties());
     }
+    //CHECKSTYLE:ON
 
 
 
@@ -151,11 +156,19 @@ protected Message createMessage(Object body,
                                     Exchange exchange,
                                     Map<String, Object> invocationContext,
                                     boolean proxy) {
+
         Method m = ori.getMethodToInvoke();
-        Map<String, Object> filterProps = new HashMap<>();
-        filterProps.put("org.eclipse.microprofile.rest.client.invokedMethod", 
m);
+        
         Message msg = super.createMessage(body, ori, headers, currentURI, 
exchange, invocationContext, proxy);
-        msg.getExchange().put("jaxrs.filter.properties", filterProps);
+        
+        @SuppressWarnings("unchecked")
+        Map<String, Object> filterProps = (Map<String, Object>) 
msg.getExchange()
+                                                                   
.get("jaxrs.filter.properties");
+        if (filterProps == null) {
+            filterProps = new HashMap<>();
+            msg.getExchange().put("jaxrs.filter.properties", filterProps);
+        }
+        filterProps.put("org.eclipse.microprofile.rest.client.invokedMethod", 
m);
         return msg;
     }
 }
diff --git 
a/rt/rs/microprofile-client/src/test/java/org/apache/cxf/jaxrs/client/WebClientUtil.java
 
b/rt/rs/microprofile-client/src/test/java/org/apache/cxf/jaxrs/client/WebClientUtil.java
new file mode 100644
index 00000000000..736861e6b0d
--- /dev/null
+++ 
b/rt/rs/microprofile-client/src/test/java/org/apache/cxf/jaxrs/client/WebClientUtil.java
@@ -0,0 +1,28 @@
+/**
+ * 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.jaxrs.client;
+
+public final class WebClientUtil {
+
+    private WebClientUtil() { }
+
+    public static ClientConfiguration getClientConfigFromProxy(Object proxy) {
+        return WebClient.fromClientObject(proxy).getConfiguration();
+    }
+}
diff --git 
a/rt/rs/microprofile-client/src/test/java/org/apache/cxf/microprofile/client/CxfTypeSafeClientBuilderTest.java
 
b/rt/rs/microprofile-client/src/test/java/org/apache/cxf/microprofile/client/CxfTypeSafeClientBuilderTest.java
index 5274acd92e2..b1e88558127 100644
--- 
a/rt/rs/microprofile-client/src/test/java/org/apache/cxf/microprofile/client/CxfTypeSafeClientBuilderTest.java
+++ 
b/rt/rs/microprofile-client/src/test/java/org/apache/cxf/microprofile/client/CxfTypeSafeClientBuilderTest.java
@@ -25,6 +25,7 @@
 import javax.ws.rs.WebApplicationException;
 import javax.ws.rs.core.Response;
 
+import org.apache.cxf.jaxrs.client.WebClientUtil;
 import org.apache.cxf.microprofile.client.mock.EchoClientReqFilter;
 import org.apache.cxf.microprofile.client.mock.ExceptionMappingClient;
 import org.apache.cxf.microprofile.client.mock.HighPriorityClientReqFilter;
@@ -151,8 +152,20 @@ public void 
testClientRequestFilterCanAccessInvokedMethod() throws Exception {
         assertEquals(String.class.getName(), 
response.getHeaderString("Parm2"));
     }
 
+    @Test
+    public void testClientPropertiesAreSet() throws Exception {
+        InterfaceWithoutProvidersDefined client = 
RestClientBuilder.newBuilder()
+            .register(InvokedMethodClientRequestFilter.class)
+            .property("hello", "world")
+            .baseUri(new URI("http://localhost:8080/neverUsed";))
+            .build(InterfaceWithoutProvidersDefined.class);
+        assertEquals("world",
+            
WebClientUtil.getClientConfigFromProxy(client).getRequestContext().get("hello"));
+    }
+
     private void fail(Response r, String failureMessage) {
         System.out.println(r.getStatus());
         fail(failureMessage);
     }
+
 }
diff --git 
a/rt/rs/microprofile-client/src/test/java/org/apache/cxf/microprofile/client/cdi/RestClientCdiTest.java
 
b/rt/rs/microprofile-client/src/test/java/org/apache/cxf/microprofile/client/cdi/RestClientCdiTest.java
new file mode 100644
index 00000000000..e59e67f4163
--- /dev/null
+++ 
b/rt/rs/microprofile-client/src/test/java/org/apache/cxf/microprofile/client/cdi/RestClientCdiTest.java
@@ -0,0 +1,79 @@
+/**
+ * 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.microprofile.client.cdi;
+
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+import javax.enterprise.inject.spi.BeanManager;
+import javax.ws.rs.Consumes;
+import javax.ws.rs.Path;
+import javax.ws.rs.Priorities;
+import javax.ws.rs.Produces;
+
+import org.apache.cxf.microprofile.client.mock.HighPriorityClientReqFilter;
+import 
org.apache.cxf.microprofile.client.mock.InvokedMethodClientRequestFilter;
+import org.apache.cxf.microprofile.client.mock.LowPriorityClientReqFilter;
+import org.apache.cxf.microprofile.client.mock.MockConfigProviderResolver;
+import org.eclipse.microprofile.config.spi.ConfigProviderResolver;
+import 
org.eclipse.microprofile.rest.client.tck.interfaces.InterfaceWithoutProvidersDefined;
+
+import org.easymock.EasyMock;
+import org.easymock.IMocksControl;
+import org.junit.Assert;
+import org.junit.Test;
+
+public class RestClientCdiTest extends Assert {
+
+    @Test
+    public void testProvidersRegisteredViaMPConfigProperty() throws Exception {
+        Map<String, String> configValues = new HashMap<>();
+        configValues.put(InterfaceWithoutProvidersDefined.class.getName() + 
"/mp-rest/providers",
+                         HighPriorityClientReqFilter.class.getName() + ","
+                         + LowPriorityClientReqFilter.class.getName() + ","
+                         + InvokedMethodClientRequestFilter.class.getName());
+        configValues.put(InterfaceWithoutProvidersDefined.class.getName() + 
"/mp-rest/providers/" 
+                         + LowPriorityClientReqFilter.class.getName() + 
"/priority", "3");
+        
((MockConfigProviderResolver)ConfigProviderResolver.instance()).setConfigValues(configValues);
+
+        IMocksControl control = EasyMock.createNiceControl();
+        BeanManager mockedBeanMgr = control.createMock(BeanManager.class);
+        mockedBeanMgr.isScope(Path.class);
+        EasyMock.expectLastCall().andReturn(false);
+        mockedBeanMgr.isScope(Produces.class);
+        EasyMock.expectLastCall().andReturn(false);
+        mockedBeanMgr.isScope(Consumes.class);
+        EasyMock.expectLastCall().andReturn(false);
+        control.replay();
+
+        RestClientBean bean = new 
RestClientBean(InterfaceWithoutProvidersDefined.class, mockedBeanMgr);
+        List<Class<?>> registeredProviders = bean.getConfiguredProviders();
+        assertEquals(3, registeredProviders.size());
+        
assertTrue(registeredProviders.contains(HighPriorityClientReqFilter.class));
+        
assertTrue(registeredProviders.contains(LowPriorityClientReqFilter.class));
+        
assertTrue(registeredProviders.contains(InvokedMethodClientRequestFilter.class));
+
+        Map<Class<?>, Integer> priorities = 
bean.getConfiguredProviderPriorities(registeredProviders);
+        assertEquals(3, priorities.size());
+        assertEquals(3, (int) 
priorities.get(LowPriorityClientReqFilter.class));
+        assertEquals(10, (int) 
priorities.get(HighPriorityClientReqFilter.class));
+        assertEquals(Priorities.USER, (int) 
priorities.get(InvokedMethodClientRequestFilter.class));
+    }
+}
diff --git 
a/rt/rs/microprofile-client/src/test/java/org/apache/cxf/microprofile/client/mock/MockConfigProviderResolver.java
 
b/rt/rs/microprofile-client/src/test/java/org/apache/cxf/microprofile/client/mock/MockConfigProviderResolver.java
new file mode 100644
index 00000000000..05267a1fc07
--- /dev/null
+++ 
b/rt/rs/microprofile-client/src/test/java/org/apache/cxf/microprofile/client/mock/MockConfigProviderResolver.java
@@ -0,0 +1,113 @@
+/**
+ * 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.microprofile.client.mock;
+
+import java.util.Arrays;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.Optional;
+
+import org.eclipse.microprofile.config.Config;
+import org.eclipse.microprofile.config.spi.ConfigBuilder;
+import org.eclipse.microprofile.config.spi.ConfigProviderResolver;
+import org.eclipse.microprofile.config.spi.ConfigSource;
+
+public class MockConfigProviderResolver extends ConfigProviderResolver {
+
+    private final Map<String, String> configValues;
+    
+    private final Config config = new Config() {
+        @Override
+        public <T> T getValue(String propertyName, Class<T> propertyType) {
+            String value = configValues.get(propertyName);
+            if (value != null) {
+                if (propertyType == String.class) {
+                    return propertyType.cast(value);
+                }
+                if (propertyType == Integer.class) {
+                    return propertyType.cast(Integer.parseInt(value));
+                }
+            }
+            return null;
+        }
+        @Override
+        public <T> Optional<T> getOptionalValue(String propertyName, Class<T> 
propertyType) {
+            return Optional.ofNullable(getValue(propertyName, propertyType));
+        }
+        @Override
+        public Iterable<String> getPropertyNames() {
+            return configValues.keySet();
+        }
+        @Override
+        public Iterable<ConfigSource> getConfigSources() {
+            ConfigSource source = new ConfigSource() {
+                @Override
+                public Map<String, String> getProperties() {
+                    return configValues;
+                }
+                @Override
+                public String getValue(String propertyName) {
+                    return (String) configValues.get(propertyName);
+                }
+                @Override
+                public String getName() {
+                    return "stub";
+                } };
+            return Arrays.asList(source);
+        } };
+
+    public MockConfigProviderResolver() {
+        configValues = new HashMap<>();
+    }
+
+    public MockConfigProviderResolver(Map<String, String> configValues) {
+        System.out.println("MockConfigProviderResolver ctor " + configValues);
+        this.configValues = configValues;
+    }
+
+    public void setConfigValues(Map<String, String> configValues) {
+        this.configValues.putAll(configValues);
+    }
+
+    @Override
+    public Config getConfig() {
+        return config;
+    }
+
+    @Override
+    public Config getConfig(ClassLoader loader) {
+        return config;
+    }
+
+    @Override
+    public ConfigBuilder getBuilder() {
+        throw new UnsupportedOperationException();
+    }
+
+    @Override
+    public void registerConfig(Config newConfig, ClassLoader classLoader) {
+        throw new UnsupportedOperationException();
+    }
+
+    @Override
+    public void releaseConfig(Config newConfig) {
+        configValues.clear();
+    }
+
+}
diff --git 
a/rt/rs/microprofile-client/src/test/resources/META-INF/services/org.eclipse.microprofile.config.spi.ConfigProviderResolver
 
b/rt/rs/microprofile-client/src/test/resources/META-INF/services/org.eclipse.microprofile.config.spi.ConfigProviderResolver
new file mode 100644
index 00000000000..60b15b77abd
--- /dev/null
+++ 
b/rt/rs/microprofile-client/src/test/resources/META-INF/services/org.eclipse.microprofile.config.spi.ConfigProviderResolver
@@ -0,0 +1 @@
+org.apache.cxf.microprofile.client.mock.MockConfigProviderResolver
\ No newline at end of file


 

----------------------------------------------------------------
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:
us...@infra.apache.org


With regards,
Apache Git Services

Reply via email to