You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@cxf.apache.org by am...@apache.org on 2018/10/19 16:57:40 UTC

[cxf] 02/02: Issue 7868: Ensure properties are registered via RestClientBuilder

This is an automated email from the ASF dual-hosted git repository.

amccright pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/cxf.git

commit 50ffb78f3742f21822b1dab369f5aacfc0e178da
Author: Andy McCright <j....@gmail.com>
AuthorDate: Tue Oct 16 10:55:42 2018 -0500

    Issue 7868: Ensure properties are registered via RestClientBuilder
    
    This ensures that properties registered via RestClientBuilder are
    honored, and that providers registered via MP Config are honored. It
    also passes the method being invoked to ClientRequestFilters via the
    ClientRequestContext.
---
 rt/rs/microprofile-client/pom.xml                  |   5 +
 .../client/MicroProfileClientFactoryBean.java      |   6 +-
 .../microprofile/client/cdi/RestClientBean.java    |  21 ++--
 .../client/proxy/MicroProfileClientProxyImpl.java  |  23 ++++-
 .../org/apache/cxf/jaxrs/client/WebClientUtil.java |  28 +++++
 .../client/CxfTypeSafeClientBuilderTest.java       |  13 +++
 .../microprofile/client/cdi/RestClientCdiTest.java |  79 ++++++++++++++
 .../client/mock/MockConfigProviderResolver.java    | 113 +++++++++++++++++++++
 ....microprofile.config.spi.ConfigProviderResolver |   1 +
 9 files changed, 274 insertions(+), 15 deletions(-)

diff --git a/rt/rs/microprofile-client/pom.xml b/rt/rs/microprofile-client/pom.xml
index 964266f..d057d91 100644
--- a/rt/rs/microprofile-client/pom.xml
+++ b/rt/rs/microprofile-client/pom.xml
@@ -87,6 +87,11 @@
             <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>
             <version>${project.version}</version>
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 9abee1a..479cabb 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 @@ import org.eclipse.microprofile.rest.client.RestClientBuilder;
 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 @@ public class MicroProfileClientFactoryBean extends JAXRSClientFactoryBean {
                                                 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 9386930..ea503ef 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
@@ -33,6 +33,7 @@ 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;
@@ -51,12 +52,12 @@ import org.eclipse.microprofile.rest.client.RestClientBuilder;
 import org.eclipse.microprofile.rest.client.inject.RestClient;
 
 public class RestClientBean implements Bean<Object>, PassivationCapable {
-    private static final Logger LOG = LogUtils.getL7dLogger(RestClientBean.class);
     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;
@@ -93,8 +94,8 @@ public class RestClientBean implements Bean<Object>, PassivationCapable {
         String baseUri = getBaseUri();
         builder = builder.baseUri(URI.create(baseUri));
         List<Class<?>> providers = getConfiguredProviders();
-        Map<Class<?>,Integer> providerPriorities = getConfiguredProviderPriorities(providers);
-        for (Class<?> providerClass : providers){
+        Map<Class<?>, Integer> providerPriorities = getConfiguredProviderPriorities(providers);
+        for (Class<?> providerClass : providers) {
             builder = builder.register(providerClass, 
                                        providerPriorities.getOrDefault(providerClass, Priorities.USER));
         }
@@ -185,12 +186,12 @@ public class RestClientBean implements Bean<Object>, PassivationCapable {
         }
     }
 
-    private List<Class<?>> getConfiguredProviders() {
+    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++) {
+        for (int i = 0; i < providerClassNames.length; i++) {
             try {
                 providers.add(ClassLoaderUtils.loadClass(providerClassNames[i], RestClientBean.class));
             } catch (ClassNotFoundException e) {
@@ -202,18 +203,24 @@ public class RestClientBean implements Bean<Object>, PassivationCapable {
         return providers;
     }
 
-    private Map<Class<?>, Integer> getConfiguredProviderPriorities(List<Class<?>> 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(Priorities.USER);
+            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 33c57ca..1296cdc 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.CompletionStage;
 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 class MicroProfileClientProxyImpl extends ClientProxyImpl {
 
     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 @@ public class MicroProfileClientProxyImpl extends ClientProxyImpl {
                                     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 0000000..736861e
--- /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 5274acd..b1e8855 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.PathParam;
 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 class CxfTypeSafeClientBuilderTest extends Assert {
         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 0000000..e59e67f
--- /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 0000000..05267a1
--- /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 0000000..60b15b7
--- /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