You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@camel.apache.org by ff...@apache.org on 2023/01/20 22:08:49 UTC

[camel-spring-boot] branch more-rest-test-new created (now f4c26e12b3f)

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

ffang pushed a change to branch more-rest-test-new
in repository https://gitbox.apache.org/repos/asf/camel-spring-boot.git


      at f4c26e12b3f add CxfRsAsyncProducerSessionTest

This branch includes the following new commits:

     new 01360d8be9c some clean up
     new a8f8f6e5def add CxfRsProducerHeaderTest
     new 9fa07a6c18a add CxfRsSslProducerTest
     new 5ae525d0867 add CxfRsGlobalSslProducerTest
     new acdcd1f5bef add CxfRsSslAsyncProducerTest
     new e1fdba42835 add CxfRsAsyncProducerTest
     new f4c26e12b3f add CxfRsAsyncProducerSessionTest

The 7 revisions listed above as "new" are entirely new to this
repository and will be described in separate emails.  The revisions
listed as "add" were already present in the repository and have only
been added to this reference.



[camel-spring-boot] 07/07: add CxfRsAsyncProducerSessionTest

Posted by ff...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

ffang pushed a commit to branch more-rest-test-new
in repository https://gitbox.apache.org/repos/asf/camel-spring-boot.git

commit f4c26e12b3f7eccc8e700a3a2cc7dd570ac299ba
Author: Freeman Fang <fr...@gmail.com>
AuthorDate: Fri Jan 20 17:07:42 2023 -0500

    add CxfRsAsyncProducerSessionTest
---
 .../springboot/CxfRsAsyncProducerSessionTest.java  | 234 +++++++++++++++++++++
 1 file changed, 234 insertions(+)

diff --git a/components-starter/camel-cxf-rest-starter/src/test/java/org/apache/camel/component/cxf/rest/springboot/CxfRsAsyncProducerSessionTest.java b/components-starter/camel-cxf-rest-starter/src/test/java/org/apache/camel/component/cxf/rest/springboot/CxfRsAsyncProducerSessionTest.java
new file mode 100644
index 00000000000..398fed5c6b0
--- /dev/null
+++ b/components-starter/camel-cxf-rest-starter/src/test/java/org/apache/camel/component/cxf/rest/springboot/CxfRsAsyncProducerSessionTest.java
@@ -0,0 +1,234 @@
+/*
+ * 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.camel.component.cxf.rest.springboot;
+
+
+import java.util.ArrayList;
+import java.util.List;
+
+
+
+import org.apache.camel.Exchange;
+import org.apache.camel.ExchangePattern;
+import org.apache.camel.Message;
+import org.apache.camel.Processor;
+import org.apache.camel.ProducerTemplate;
+import org.apache.camel.builder.RouteBuilder;
+import org.apache.camel.component.cxf.common.CXFTestSupport;
+import org.apache.camel.component.cxf.common.message.CxfConstants;
+import org.apache.camel.component.cxf.spring.jaxrs.SpringJAXRSClientFactoryBean;
+import org.apache.camel.component.cxf.spring.jaxrs.SpringJAXRSServerFactoryBean;
+import org.apache.camel.http.base.cookie.BaseCookieHandler;
+import org.apache.camel.spring.boot.CamelAutoConfiguration;
+import org.apache.camel.spring.xml.CamelEndpointFactoryBean;
+
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.boot.test.context.SpringBootTest;
+import org.springframework.boot.web.embedded.undertow.UndertowServletWebServerFactory;
+import org.springframework.boot.web.servlet.server.ServletWebServerFactory;
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.Configuration;
+import org.springframework.test.annotation.DirtiesContext;
+import org.springframework.test.annotation.DirtiesContext.ClassMode;
+import org.apache.camel.test.spring.junit5.CamelSpringBootTest;
+import org.apache.cxf.endpoint.Server;
+import org.apache.cxf.jaxrs.AbstractJAXRSFactoryBean;
+import org.apache.cxf.jaxrs.JAXRSServerFactoryBean;
+import org.apache.cxf.spring.boot.autoconfigure.CxfAutoConfiguration;
+
+
+
+@DirtiesContext(classMode = ClassMode.AFTER_EACH_TEST_METHOD)
+@CamelSpringBootTest
+@SpringBootTest(
+    classes = {
+        CamelAutoConfiguration.class,
+        CxfRsAsyncProducerSessionTest.class,
+        CxfRsAsyncProducerSessionTest.TestConfiguration.class,
+        CxfAutoConfiguration.class
+    }, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT
+)
+public class CxfRsAsyncProducerSessionTest {
+
+    static int port1 = CXFTestSupport.getPort1();
+    static int port2 = CXFTestSupport.getPort2();
+    
+    private Server server;
+
+    @Autowired
+    private ProducerTemplate template;
+    
+   
+    
+    @BeforeEach
+    public void setUp() throws Exception {
+        JAXRSServerFactoryBean sfb = new SpringJAXRSServerFactoryBean();
+        List<Object> serviceBeans = new ArrayList<Object>();
+        serviceBeans.add(new org.apache.camel.component.cxf.jaxrs.testbean.EchoService());
+        sfb.setServiceBeans(serviceBeans);
+        sfb.setAddress("/CxfRsProducerSessionTest/");
+        sfb.setStaticSubresourceResolution(true);
+        server = sfb.create();
+        server.start();
+    }
+
+    @AfterEach
+    public void shutdown() throws Exception {
+        if (server != null) {
+            server.stop();
+            server.destroy();
+        }
+    }
+    
+    //@Test
+    public void testNoSessionProxy() {
+        String response = sendMessage("direct://proxy", "World", Boolean.FALSE).getMessage().getBody(String.class);
+        assertEquals("New New World", response);
+        response = sendMessage("direct://proxy", "World", Boolean.FALSE).getMessage().getBody(String.class);
+        assertEquals("New New World", response);
+    }
+
+    //@Test
+    public void testExchangeSessionProxy() {
+        String response = sendMessage("direct://proxyexchange", "World", Boolean.FALSE).getMessage().getBody(String.class);
+        assertEquals("Old New World", response);
+        response = sendMessage("direct://proxyexchange", "World", Boolean.FALSE).getMessage().getBody(String.class);
+        assertEquals("Old New World", response);
+    }
+
+    //@Test
+    public void testInstanceSession() {
+        String response = sendMessage("direct://proxyinstance", "World", Boolean.FALSE).getMessage().getBody(String.class);
+        assertEquals("Old New World", response);
+        response = sendMessage("direct://proxyinstance", "World", Boolean.FALSE).getMessage().getBody(String.class);
+        assertEquals("Old Old World", response);
+        // we do the instance tests for proxy and http in one test because order
+        // matters here
+        response = sendMessage("direct://httpinstance", "World", Boolean.TRUE).getMessage().getBody(String.class);
+        assertEquals("Old Old World", response);
+    }
+
+    @Test
+    public void testNoSessionHttp() {
+        String response = sendMessage("direct://http", "World", Boolean.TRUE).getMessage().getBody(String.class);
+        assertEquals("New New World", response);
+        response = sendMessage("direct://http", "World", Boolean.TRUE).getMessage().getBody(String.class);
+        assertEquals("New New World", response);
+    }
+
+    @Test
+    public void testExchangeSessionHttp() {
+        String response = sendMessage("direct://httpexchange", "World", Boolean.TRUE).getMessage().getBody(String.class);
+        assertEquals("Old New World", response);
+        response = sendMessage("direct://httpexchange", "World", Boolean.TRUE).getMessage().getBody(String.class);
+        assertEquals("Old New World", response);
+    }
+
+    private Exchange sendMessage(String endpoint, String body, Boolean httpApi) {
+        Exchange exchange = template.send(endpoint, new Processor() {
+            public void process(Exchange exchange) throws Exception {
+                exchange.setPattern(ExchangePattern.InOut);
+                Message inMessage = exchange.getIn();
+                inMessage.setHeader(CxfConstants.OPERATION_NAME, "echo");
+                inMessage.setHeader(Exchange.HTTP_METHOD, "POST");
+                inMessage.setHeader(Exchange.HTTP_PATH, "/echoservice/echo");
+                inMessage.setHeader(CxfConstants.CAMEL_CXF_RS_USING_HTTP_API, httpApi);
+                inMessage.setHeader(CxfConstants.CAMEL_CXF_RS_RESPONSE_CLASS, String.class);
+                inMessage.setBody(body);
+            }
+        });
+        return exchange;
+    }
+    
+    // *************************************
+    // Config
+    // *************************************
+
+    @Configuration
+    public class TestConfiguration {
+
+        
+        @Bean
+        public ServletWebServerFactory servletWebServerFactory() {
+            return new UndertowServletWebServerFactory(port1);
+        }
+              
+        
+        @Bean 
+        public CamelEndpointFactoryBean fromEndpoint() {
+            CamelEndpointFactoryBean jettyConsumer = new CamelEndpointFactoryBean();
+            jettyConsumer.setUri("jetty://http://localhost:" + port2 + "/CxfRsProducerSessionTest/echoservice");
+            return jettyConsumer;
+        }
+        
+                
+        /*@Bean
+        public AbstractJAXRSFactoryBean rsClientProxy() {
+            SpringJAXRSClientFactoryBean afb = new SpringJAXRSClientFactoryBean();
+            //afb.setBus(BusFactory.getDefaultBus());
+            afb.setAddress("http://localhost:" + port1
+                                   + "/services/CxfRsAsyncProducerTest/");
+            //afb.setServiceClass somehow cause conflict with other test, should be bus conflict
+            afb.setServiceClass(org.apache.camel.component.cxf.jaxrs.testbean.CustomerService.class);
+            afb.setLoggingFeatureEnabled(true);
+            
+            return afb;
+        }*/
+        
+        @Bean
+        public AbstractJAXRSFactoryBean rsClientHttp() {
+            SpringJAXRSClientFactoryBean afb = new SpringJAXRSClientFactoryBean();
+            afb.setAddress("http://localhost:" + port1
+                                   + "/services/CxfRsProducerSessionTest/");
+            return afb;
+        }
+        
+        @Bean
+        public BaseCookieHandler instanceCookieHandler() {
+            return new org.apache.camel.http.base.cookie.InstanceCookieHandler();
+        }
+        
+        @Bean
+        public BaseCookieHandler exchangeCookieHandler() {
+            return new org.apache.camel.http.base.cookie.ExchangeCookieHandler();
+        }
+        
+        @Bean
+        public RouteBuilder routeBuilder() {
+            return new RouteBuilder() {
+                @Override
+                public void configure() {
+                    //from("direct://proxy").to("cxfrs:bean:rsClientProxy");
+                    from("direct://http").to("cxfrs:bean:rsClientHttp")
+                        .convertBodyTo(String.class).to("cxfrs:bean:rsClientHttp");
+                    from("direct://httpinstance").to("cxfrs:bean:rsClientHttp?cookieHandler=#instanceCookieHandler")
+                        .convertBodyTo(String.class).to("cxfrs:bean:rsClientHttp?cookieHandler=#instanceCookieHandler");
+                    from("direct://httpexchange").to("cxfrs:bean:rsClientHttp?cookieHandler=#exchangeCookieHandler")
+                    .convertBodyTo(String.class).to("cxfrs:bean:rsClientHttp?cookieHandler=#exchangeCookieHandler");
+                    
+                }
+            };
+        }
+    }
+    
+}


[camel-spring-boot] 03/07: add CxfRsSslProducerTest

Posted by ff...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

ffang pushed a commit to branch more-rest-test-new
in repository https://gitbox.apache.org/repos/asf/camel-spring-boot.git

commit 9fa07a6c18a3aa7eb3a6ae9b6d615affee08e06e
Author: Freeman Fang <fr...@gmail.com>
AuthorDate: Mon Jan 16 16:33:59 2023 -0500

    add CxfRsSslProducerTest
    
    (cherry picked from commit f3b673399bdd8be6ee103c31f9064c1d9a998b47)
---
 .../cxf/rest/springboot/CxfRsSslProducerTest.java  | 261 +++++++++++++++++++++
 .../cxf/rest/springboot/SslBuilderCustomizer.java  | 247 +++++++++++++++++++
 2 files changed, 508 insertions(+)

diff --git a/components-starter/camel-cxf-rest-starter/src/test/java/org/apache/camel/component/cxf/rest/springboot/CxfRsSslProducerTest.java b/components-starter/camel-cxf-rest-starter/src/test/java/org/apache/camel/component/cxf/rest/springboot/CxfRsSslProducerTest.java
new file mode 100644
index 00000000000..ecd97ec46d9
--- /dev/null
+++ b/components-starter/camel-cxf-rest-starter/src/test/java/org/apache/camel/component/cxf/rest/springboot/CxfRsSslProducerTest.java
@@ -0,0 +1,261 @@
+/*
+ * 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.camel.component.cxf.rest.springboot;
+
+
+import java.net.InetAddress;
+import java.net.UnknownHostException;
+import java.util.ArrayList;
+import java.util.List;
+
+
+
+import org.apache.camel.Exchange;
+import org.apache.camel.ExchangePattern;
+import org.apache.camel.Message;
+import org.apache.camel.Processor;
+import org.apache.camel.ProducerTemplate;
+import org.apache.camel.builder.RouteBuilder;
+import org.apache.camel.component.cxf.common.CXFTestSupport;
+import org.apache.camel.component.cxf.common.message.CxfConstants;
+import org.apache.camel.component.cxf.jaxrs.testbean.Customer;
+import org.apache.camel.component.cxf.spring.jaxrs.SpringJAXRSClientFactoryBean;
+import org.apache.camel.spring.boot.CamelAutoConfiguration;
+import org.apache.camel.support.jsse.KeyStoreParameters;
+import org.apache.camel.support.jsse.SSLContextParameters;
+import org.apache.camel.support.jsse.TrustManagersParameters;
+
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.boot.test.context.SpringBootTest;
+import org.springframework.boot.web.embedded.undertow.UndertowServletWebServerFactory;
+import org.springframework.boot.web.server.CertificateFileSslStoreProvider;
+import org.springframework.boot.web.server.Ssl;
+import org.springframework.boot.web.server.Ssl.ClientAuth;
+import org.springframework.boot.web.servlet.server.ServletWebServerFactory;
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.Configuration;
+import org.springframework.test.annotation.DirtiesContext;
+import org.springframework.test.annotation.DirtiesContext.ClassMode;
+import org.apache.camel.test.spring.junit5.CamelSpringBootTest;
+import org.apache.cxf.endpoint.Server;
+import org.apache.cxf.jaxrs.AbstractJAXRSFactoryBean;
+import org.apache.cxf.jaxrs.JAXRSServerFactoryBean;
+import org.apache.cxf.spring.boot.autoconfigure.CxfAutoConfiguration;
+import org.apache.cxf.transport.https.httpclient.DefaultHostnameVerifier;
+
+
+
+@DirtiesContext(classMode = ClassMode.AFTER_EACH_TEST_METHOD)
+@CamelSpringBootTest
+@SpringBootTest(
+    classes = {
+        CamelAutoConfiguration.class,
+        CxfRsSslProducerTest.class,
+        CxfRsSslProducerTest.TestConfiguration.class,
+        CxfAutoConfiguration.class
+    }, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT
+)
+public class CxfRsSslProducerTest {
+
+    static int port = CXFTestSupport.getSslPort();
+    
+    
+    @Autowired
+    protected ProducerTemplate template;
+    
+    @BeforeEach
+    public void setUp() throws Exception {
+        JAXRSServerFactoryBean sfb = new JAXRSServerFactoryBean();
+        List<Object> serviceBeans = new ArrayList<Object>();
+        serviceBeans.add(new org.apache.camel.component.cxf.jaxrs.testbean.CustomerService());
+        sfb.setServiceBeans(serviceBeans);
+        sfb.setAddress("/CxfRsProducerTest/");
+        sfb.setStaticSubresourceResolution(true);
+        Server server = sfb.create();
+        server.start();
+    }
+
+    
+    protected void setupDestinationURL(Message inMessage) {
+        // do nothing here
+    }
+    
+    @Test
+    public void testCorrectTrustStore() {
+        Exchange exchange = template.send("direct://trust", new MyProcessor());
+
+        // get the response message 
+        Customer response = (Customer) exchange.getMessage().getBody();
+
+        assertNotNull(response, "The response should not be null");
+        assertEquals("123", String.valueOf(response.getId()), "Get a wrong customer id");
+        assertEquals("John", response.getName(), "Get a wrong customer name");
+        assertEquals(200, exchange.getMessage().getHeader(Exchange.HTTP_RESPONSE_CODE), "Get a wrong response code");
+        assertEquals("value", exchange.getMessage().getHeader("key"), "Get a wrong header value");
+    }
+
+    @Test
+    public void testNoTrustStore() {
+        Exchange exchange = template.send("direct://noTrust", new MyProcessor());
+        assertTrue(exchange.isFailed());
+        Exception e = exchange.getException();
+        assertEquals("javax.net.ssl.SSLHandshakeException", e.getCause().getClass().getCanonicalName());
+    }
+
+    @Test
+    public void testWrongTrustStore() {
+        Exchange exchange = template.send("direct://wrongTrust", new MyProcessor());
+        assertTrue(exchange.isFailed());
+        Exception e = exchange.getException();
+        assertEquals("javax.net.ssl.SSLHandshakeException", e.getCause().getClass().getCanonicalName());
+    }
+
+    private class MyProcessor implements Processor {
+
+        @Override
+        public void process(Exchange exchange) throws Exception {
+            exchange.setPattern(ExchangePattern.InOut);
+            Message inMessage = exchange.getIn();
+            setupDestinationURL(inMessage);
+            // using the http central client API
+            inMessage.setHeader(CxfConstants.CAMEL_CXF_RS_USING_HTTP_API, Boolean.TRUE);
+            // set the Http method
+            inMessage.setHeader(Exchange.HTTP_METHOD, "GET");
+            // set the relative path
+            inMessage.setHeader(Exchange.HTTP_PATH, "/customerservice/customers/123");
+            // Specify the response class , cxfrs will use InputStream as the response object type
+            inMessage.setHeader(CxfConstants.CAMEL_CXF_RS_RESPONSE_CLASS, Customer.class);
+            // set a customer header
+            inMessage.setHeader("key", "value");
+            // since we use the Get method, so we don't need to set the message body
+            inMessage.setBody(null);
+        }
+    }
+    
+    // *************************************
+    // Config
+    // *************************************
+
+    @Configuration
+    public class TestConfiguration {
+
+        
+        
+        /*
+         * This is the way how to configure TLS/SSL with Bean 
+         */
+        @Bean
+        public ServletWebServerFactory servletWebServerFactory() throws UnknownHostException {
+            UndertowServletWebServerFactory undertowWebServerFactory 
+                = new UndertowServletWebServerFactory();
+            Ssl ssl = new Ssl();
+            ssl.setClientAuth(ClientAuth.NONE);
+            ssl.setKeyPassword("changeit");
+            ssl.setKeyStoreType("JKS");
+            ssl.setKeyStore("classpath:ssl/keystore-server.jks");
+            ssl.setKeyStorePassword("changeit");
+            SslBuilderCustomizer sslBuilderCustomizer = 
+                new SslBuilderCustomizer(port, InetAddress.getByName("localhost"),
+                                         ssl, CertificateFileSslStoreProvider.from(ssl));
+            undertowWebServerFactory.addBuilderCustomizers(sslBuilderCustomizer);
+            return undertowWebServerFactory;
+        }
+        
+        @Bean
+        DefaultHostnameVerifier defaultHostnameVerifier() {
+            return new DefaultHostnameVerifier();
+        }
+        
+        @Bean
+        SSLContextParameters mySslContext() {
+            SSLContextParameters sslContext = new SSLContextParameters();
+            TrustManagersParameters trustManager = new TrustManagersParameters();
+            KeyStoreParameters keyStore = new KeyStoreParameters();
+            keyStore.setType("JKS");
+            keyStore.setPassword("changeit");
+            keyStore.setResource("/ssl/truststore-client.jks");
+            trustManager.setKeyStore(keyStore);
+            sslContext.setTrustManagers(trustManager);
+            return sslContext;
+        }
+        
+        @Bean
+        SSLContextParameters wrongSslContext() {
+            SSLContextParameters sslContext = new SSLContextParameters();
+            TrustManagersParameters trustManager = new TrustManagersParameters();
+            KeyStoreParameters keyStore = new KeyStoreParameters();
+            keyStore.setType("JKS");
+            keyStore.setPassword("changeit");
+            keyStore.setResource("/ssl/truststore-wrong.jks");
+            trustManager.setKeyStore(keyStore);
+            sslContext.setTrustManagers(trustManager);
+            return sslContext;
+        }
+        
+        
+        @Bean
+        AbstractJAXRSFactoryBean serviceEndpoint(SSLContextParameters mySslContext, DefaultHostnameVerifier defaultHostnameVerifier) {
+            AbstractJAXRSFactoryBean afb = new SpringJAXRSClientFactoryBean();
+            afb.setAddress("https://localhost:" + port 
+                                   + "/services/CxfRsProducerTest/");
+            return afb;
+        }
+        
+        /*@Bean
+        CxfRsEndpoint serviceEndpointWithWrongTrust(SSLContextParameters wrongSslContext, DefaultHostnameVerifier defaultHostnameVerifier) {
+            
+            CxfRsEndpoint cxfEndpoint = new CxfRsEndpoint();
+            cxfEndpoint.setAddress("https://localhost:" + port 
+                                   + "/services/CxfRsProducerTest/");
+            cxfEndpoint.setHostnameVerifier(defaultHostnameVerifier);
+            cxfEndpoint.setSslContextParameters(wrongSslContext);
+            cxfEndpoint.setSynchronous(true);
+            return cxfEndpoint;
+        }
+        
+        @Bean
+        CxfRsEndpoint serviceEndpointWithNoTrust(DefaultHostnameVerifier defaultHostnameVerifier) {
+            
+            CxfRsEndpoint cxfEndpoint = new CxfRsEndpoint();
+            cxfEndpoint.setAddress("https://localhost:" + port 
+                                   + "/services/CxfRsProducerTest/");
+            cxfEndpoint.setHostnameVerifier(defaultHostnameVerifier);
+            cxfEndpoint.setSynchronous(true);
+            return cxfEndpoint;
+        }*/
+        
+        @Bean
+        public RouteBuilder routeBuilder() {
+            return new RouteBuilder() {
+                @Override
+                public void configure() {
+                    from("direct://trust").to("cxfrs:bean:serviceEndpoint?sslContextParameters=#mySslContext&hostnameVerifier=#defaultHostnameVerifier&synchronous=true");
+                    from("direct://wrongTrust").to("cxfrs:bean:serviceEndpoint?sslContextParameters=#wrongSslContext&hostnameVerifier=#defaultHostnameVerifier&synchronous=true");
+                    from("direct://noTrust").to("cxfrs:bean:serviceEndpoint?hostnameVerifier=#defaultHostnameVerifier&synchronous=true");
+                }
+            };
+        }
+    }
+    
+}
diff --git a/components-starter/camel-cxf-rest-starter/src/test/java/org/apache/camel/component/cxf/rest/springboot/SslBuilderCustomizer.java b/components-starter/camel-cxf-rest-starter/src/test/java/org/apache/camel/component/cxf/rest/springboot/SslBuilderCustomizer.java
new file mode 100644
index 00000000000..89c5f56a1be
--- /dev/null
+++ b/components-starter/camel-cxf-rest-starter/src/test/java/org/apache/camel/component/cxf/rest/springboot/SslBuilderCustomizer.java
@@ -0,0 +1,247 @@
+/*
+ * 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.camel.component.cxf.rest.springboot;
+
+import java.io.InputStream;
+import java.net.InetAddress;
+import java.net.Socket;
+import java.net.URL;
+import java.security.KeyManagementException;
+import java.security.KeyStore;
+import java.security.NoSuchAlgorithmException;
+import java.security.Principal;
+import java.security.PrivateKey;
+import java.security.cert.X509Certificate;
+
+import javax.net.ssl.KeyManager;
+import javax.net.ssl.KeyManagerFactory;
+import javax.net.ssl.SSLContext;
+import javax.net.ssl.SSLEngine;
+import javax.net.ssl.TrustManager;
+import javax.net.ssl.TrustManagerFactory;
+import javax.net.ssl.X509ExtendedKeyManager;
+
+import org.springframework.boot.web.embedded.undertow.UndertowBuilderCustomizer;
+import org.springframework.boot.web.server.Ssl;
+import org.springframework.boot.web.server.SslConfigurationValidator;
+import org.springframework.boot.web.server.SslStoreProvider;
+import org.springframework.boot.web.server.WebServerException;
+import org.springframework.util.ResourceUtils;
+import org.xnio.Options;
+import org.xnio.Sequence;
+import org.xnio.SslClientAuthMode;
+
+import io.undertow.Undertow;
+
+public class SslBuilderCustomizer implements UndertowBuilderCustomizer {
+    private final int port;
+
+    private final InetAddress address;
+
+    private final Ssl ssl;
+
+    private final SslStoreProvider sslStoreProvider;
+
+    SslBuilderCustomizer(int port, InetAddress address, Ssl ssl, SslStoreProvider sslStoreProvider) {
+            this.port = port;
+            this.address = address;
+            this.ssl = ssl;
+            this.sslStoreProvider = sslStoreProvider;
+    }
+
+    public void customize(Undertow.Builder builder) {
+            try {
+                    SSLContext sslContext = SSLContext.getInstance(this.ssl.getProtocol());
+                    sslContext.init(getKeyManagers(this.ssl, this.sslStoreProvider),
+                                    getTrustManagers(this.ssl, this.sslStoreProvider), null);
+                    builder.addHttpsListener(this.port, getListenAddress(), sslContext);
+                    builder.setSocketOption(Options.SSL_CLIENT_AUTH_MODE, getSslClientAuthMode(this.ssl));
+                    if (this.ssl.getEnabledProtocols() != null) {
+                            builder.setSocketOption(Options.SSL_ENABLED_PROTOCOLS, Sequence.of(this.ssl.getEnabledProtocols()));
+                    }
+                    if (this.ssl.getCiphers() != null) {
+                            builder.setSocketOption(Options.SSL_ENABLED_CIPHER_SUITES, Sequence.of(this.ssl.getCiphers()));
+                    }
+            }
+            catch (NoSuchAlgorithmException | KeyManagementException ex) {
+                    throw new IllegalStateException(ex);
+            }
+    }
+
+    private String getListenAddress() {
+            if (this.address == null) {
+                    return "0.0.0.0";
+            }
+            return this.address.getHostAddress();
+    }
+
+    private SslClientAuthMode getSslClientAuthMode(Ssl ssl) {
+            if (ssl.getClientAuth() == Ssl.ClientAuth.NEED) {
+                    return SslClientAuthMode.REQUIRED;
+            }
+            if (ssl.getClientAuth() == Ssl.ClientAuth.WANT) {
+                    return SslClientAuthMode.REQUESTED;
+            }
+            return SslClientAuthMode.NOT_REQUESTED;
+    }
+
+    private KeyManager[] getKeyManagers(Ssl ssl, SslStoreProvider sslStoreProvider) {
+            try {
+                    KeyStore keyStore = getKeyStore(ssl, sslStoreProvider);
+                    SslConfigurationValidator.validateKeyAlias(keyStore, ssl.getKeyAlias());
+                    KeyManagerFactory keyManagerFactory = KeyManagerFactory
+                                    .getInstance(KeyManagerFactory.getDefaultAlgorithm());
+                    String keyPassword = (sslStoreProvider != null) ? sslStoreProvider.getKeyPassword() : null;
+                    if (keyPassword == null) {
+                            keyPassword = (ssl.getKeyPassword() != null) ? ssl.getKeyPassword() : ssl.getKeyStorePassword();
+                    }
+                    keyManagerFactory.init(keyStore, (keyPassword != null) ? keyPassword.toCharArray() : null);
+                    if (ssl.getKeyAlias() != null) {
+                            return getConfigurableAliasKeyManagers(ssl, keyManagerFactory.getKeyManagers());
+                    }
+                    return keyManagerFactory.getKeyManagers();
+            }
+            catch (Exception ex) {
+                    throw new IllegalStateException(ex);
+            }
+    }
+
+    private KeyManager[] getConfigurableAliasKeyManagers(Ssl ssl, KeyManager[] keyManagers) {
+            for (int i = 0; i < keyManagers.length; i++) {
+                    if (keyManagers[i] instanceof X509ExtendedKeyManager) {
+                            keyManagers[i] = new ConfigurableAliasKeyManager((X509ExtendedKeyManager) keyManagers[i],
+                                            ssl.getKeyAlias());
+                    }
+            }
+            return keyManagers;
+    }
+
+    private KeyStore getKeyStore(Ssl ssl, SslStoreProvider sslStoreProvider) throws Exception {
+            if (sslStoreProvider != null) {
+                    return sslStoreProvider.getKeyStore();
+            }
+            return loadKeyStore(ssl.getKeyStoreType(), ssl.getKeyStoreProvider(), ssl.getKeyStore(),
+                            ssl.getKeyStorePassword());
+    }
+
+    private TrustManager[] getTrustManagers(Ssl ssl, SslStoreProvider sslStoreProvider) {
+            try {
+                    KeyStore store = getTrustStore(ssl, sslStoreProvider);
+                    TrustManagerFactory trustManagerFactory = TrustManagerFactory
+                                    .getInstance(TrustManagerFactory.getDefaultAlgorithm());
+                    trustManagerFactory.init(store);
+                    return trustManagerFactory.getTrustManagers();
+            }
+            catch (Exception ex) {
+                    throw new IllegalStateException(ex);
+            }
+    }
+
+    private KeyStore getTrustStore(Ssl ssl, SslStoreProvider sslStoreProvider) throws Exception {
+            if (sslStoreProvider != null) {
+                    return sslStoreProvider.getTrustStore();
+            }
+            return loadTrustStore(ssl.getTrustStoreType(), ssl.getTrustStoreProvider(), ssl.getTrustStore(),
+                            ssl.getTrustStorePassword());
+    }
+
+    private KeyStore loadKeyStore(String type, String provider, String resource, String password) throws Exception {
+            return loadStore(type, provider, resource, password);
+    }
+
+    private KeyStore loadTrustStore(String type, String provider, String resource, String password) throws Exception {
+            if (resource == null) {
+                    return null;
+            }
+            return loadStore(type, provider, resource, password);
+    }
+
+    private KeyStore loadStore(String type, String provider, String resource, String password) throws Exception {
+            type = (type != null) ? type : "JKS";
+            KeyStore store = (provider != null) ? KeyStore.getInstance(type, provider) : KeyStore.getInstance(type);
+            try {
+                    URL url = ResourceUtils.getURL(resource);
+                    try (InputStream stream = url.openStream()) {
+                            store.load(stream, (password != null) ? password.toCharArray() : null);
+                    }
+                    return store;
+            }
+            catch (Exception ex) {
+                    throw new WebServerException("Could not load key store '" + resource + "'", ex);
+            }
+    }
+
+    /**
+     * {@link X509ExtendedKeyManager} that supports custom alias configuration.
+     */
+    private static class ConfigurableAliasKeyManager extends X509ExtendedKeyManager {
+
+            private final X509ExtendedKeyManager keyManager;
+
+            private final String alias;
+
+            ConfigurableAliasKeyManager(X509ExtendedKeyManager keyManager, String alias) {
+                    this.keyManager = keyManager;
+                    this.alias = alias;
+            }
+
+            @Override
+            public String chooseEngineClientAlias(String[] strings, Principal[] principals, SSLEngine sslEngine) {
+                    return this.keyManager.chooseEngineClientAlias(strings, principals, sslEngine);
+            }
+
+            @Override
+            public String chooseEngineServerAlias(String s, Principal[] principals, SSLEngine sslEngine) {
+                    if (this.alias == null) {
+                            return this.keyManager.chooseEngineServerAlias(s, principals, sslEngine);
+                    }
+                    return this.alias;
+            }
+
+            @Override
+            public String chooseClientAlias(String[] keyType, Principal[] issuers, Socket socket) {
+                    return this.keyManager.chooseClientAlias(keyType, issuers, socket);
+            }
+
+            @Override
+            public String chooseServerAlias(String keyType, Principal[] issuers, Socket socket) {
+                    return this.keyManager.chooseServerAlias(keyType, issuers, socket);
+            }
+
+            @Override
+            public X509Certificate[] getCertificateChain(String alias) {
+                    return this.keyManager.getCertificateChain(alias);
+            }
+
+            @Override
+            public String[] getClientAliases(String keyType, Principal[] issuers) {
+                    return this.keyManager.getClientAliases(keyType, issuers);
+            }
+
+            @Override
+            public PrivateKey getPrivateKey(String alias) {
+                    return this.keyManager.getPrivateKey(alias);
+            }
+
+            @Override
+            public String[] getServerAliases(String keyType, Principal[] issuers) {
+                    return this.keyManager.getServerAliases(keyType, issuers);
+            }
+
+    }
+
+}


[camel-spring-boot] 06/07: add CxfRsAsyncProducerTest

Posted by ff...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

ffang pushed a commit to branch more-rest-test-new
in repository https://gitbox.apache.org/repos/asf/camel-spring-boot.git

commit e1fdba4283579c5e739039380354fb5fba298de1
Author: Freeman Fang <fr...@gmail.com>
AuthorDate: Thu Jan 19 11:45:12 2023 -0500

    add CxfRsAsyncProducerTest
    
    (cherry picked from commit d97ee6391e950395e59276fcefba7dbea09d351d)
---
 .../rest/springboot/CxfRsAsyncProducerTest.java    | 640 +++++++++++++++++++++
 .../springboot/CxfRsGlobalSslProducerTest.java     |  13 +-
 .../rest/springboot/CxfRsProducerHeaderTest.java   |  13 +-
 .../rest/springboot/CxfRsSslAsyncProducerTest.java |  13 +-
 .../cxf/rest/springboot/CxfRsSslProducerTest.java  |  13 +-
 5 files changed, 687 insertions(+), 5 deletions(-)

diff --git a/components-starter/camel-cxf-rest-starter/src/test/java/org/apache/camel/component/cxf/rest/springboot/CxfRsAsyncProducerTest.java b/components-starter/camel-cxf-rest-starter/src/test/java/org/apache/camel/component/cxf/rest/springboot/CxfRsAsyncProducerTest.java
new file mode 100644
index 00000000000..34b38c8b2c9
--- /dev/null
+++ b/components-starter/camel-cxf-rest-starter/src/test/java/org/apache/camel/component/cxf/rest/springboot/CxfRsAsyncProducerTest.java
@@ -0,0 +1,640 @@
+/*
+ * 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.camel.component.cxf.rest.springboot;
+
+
+import java.io.InputStream;
+import java.util.ArrayList;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+
+import javax.ws.rs.core.Response;
+
+
+import org.apache.camel.CamelContext;
+import org.apache.camel.Exchange;
+import org.apache.camel.ExchangePattern;
+import org.apache.camel.Message;
+import org.apache.camel.Processor;
+import org.apache.camel.ProducerTemplate;
+import org.apache.camel.builder.RouteBuilder;
+import org.apache.camel.component.cxf.common.CXFTestSupport;
+import org.apache.camel.component.cxf.common.CxfOperationException;
+import org.apache.camel.component.cxf.common.message.CxfConstants;
+import org.apache.camel.component.cxf.jaxrs.testbean.Customer;
+import org.apache.camel.component.cxf.spring.jaxrs.SpringJAXRSClientFactoryBean;
+import org.apache.camel.component.cxf.spring.jaxrs.SpringJAXRSServerFactoryBean;
+import org.apache.camel.spring.boot.CamelAutoConfiguration;
+import org.apache.camel.spring.xml.CamelEndpointFactoryBean;
+
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.boot.test.context.SpringBootTest;
+import org.springframework.boot.web.embedded.undertow.UndertowServletWebServerFactory;
+import org.springframework.boot.web.servlet.server.ServletWebServerFactory;
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.Configuration;
+import org.springframework.test.annotation.DirtiesContext;
+import org.springframework.test.annotation.DirtiesContext.ClassMode;
+import org.apache.camel.test.spring.junit5.CamelSpringBootTest;
+import org.apache.camel.util.CastUtils;
+import org.apache.cxf.Bus;
+import org.apache.cxf.endpoint.Client;
+import org.apache.cxf.endpoint.Server;
+import org.apache.cxf.feature.Feature;
+import org.apache.cxf.interceptor.InterceptorProvider;
+import org.apache.cxf.jaxrs.AbstractJAXRSFactoryBean;
+import org.apache.cxf.jaxrs.JAXRSServerFactoryBean;
+import org.apache.cxf.jaxrs.utils.ParameterizedCollectionType;
+import org.apache.cxf.spring.boot.autoconfigure.CxfAutoConfiguration;
+
+
+
+@DirtiesContext(classMode = ClassMode.AFTER_EACH_TEST_METHOD)
+@CamelSpringBootTest
+@SpringBootTest(
+    classes = {
+        CamelAutoConfiguration.class,
+        CxfRsAsyncProducerTest.class,
+        CxfRsAsyncProducerTest.TestConfiguration.class,
+        CxfAutoConfiguration.class
+    }, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT
+)
+public class CxfRsAsyncProducerTest {
+
+    static int port1 = CXFTestSupport.getPort1();
+    static int port2 = CXFTestSupport.getPort2();
+    
+    private Server server;
+
+    @Autowired
+    private ProducerTemplate template;
+    
+    @Autowired
+    private CamelContext context;
+    
+    
+    
+    @BeforeEach
+    public void setUp() throws Exception {
+        JAXRSServerFactoryBean sfb = new SpringJAXRSServerFactoryBean();
+        List<Object> serviceBeans = new ArrayList<Object>();
+        serviceBeans.add(new org.apache.camel.component.cxf.jaxrs.testbean.CustomerService());
+        sfb.setServiceBeans(serviceBeans);
+        sfb.setAddress("/CxfRsAsyncProducerTest/");
+        sfb.setStaticSubresourceResolution(true);
+        server = sfb.create();
+        server.start();
+    }
+
+    @AfterEach
+    public void shutdown() throws Exception {
+        if (server != null) {
+            server.stop();
+            server.destroy();
+        }
+    }
+    
+    //@Test
+    public void testGetCustomerWithClientProxyAPI() {
+        // START SNIPPET: ProxyExample
+        Exchange exchange = template.send("direct://proxy", new Processor() {
+            public void process(Exchange exchange) throws Exception {
+                exchange.setPattern(ExchangePattern.InOut);
+                Message inMessage = exchange.getIn();
+                // set the operation name 
+                inMessage.setHeader(CxfConstants.OPERATION_NAME, "getCustomer");
+                // using the proxy client API
+                inMessage.setHeader(CxfConstants.CAMEL_CXF_RS_USING_HTTP_API, Boolean.FALSE);
+                // set a customer header
+                inMessage.setHeader("key", "value");
+                // set the parameters , if you just have one parameter 
+                // camel will put this object into an Object[] itself
+                inMessage.setBody("123");
+            }
+        });
+
+        // get the response message 
+        Customer response = (Customer) exchange.getMessage().getBody();
+
+        assertNotNull(response, "The response should not be null");
+        assertEquals(123, response.getId(), "Get a wrong customer id");
+        assertEquals("John", response.getName(), "Get a wrong customer name");
+        assertEquals(200, exchange.getMessage().getHeader(Exchange.HTTP_RESPONSE_CODE), "Get a wrong response code");
+        assertEquals("value", exchange.getMessage().getHeader("key"), "Get a wrong header value");
+        // END SNIPPET: ProxyExample     
+    }
+
+    //@Test
+    public void testGetCustomersWithClientProxyAPI() {
+        Exchange exchange = template.send("direct://proxy", newExchange -> {
+            newExchange.setPattern(ExchangePattern.InOut);
+            Message inMessage = newExchange.getIn();
+            // set the operation name 
+            inMessage.setHeader(CxfConstants.OPERATION_NAME, "getCustomers");
+            // using the proxy client API
+            inMessage.setHeader(CxfConstants.CAMEL_CXF_RS_USING_HTTP_API, Boolean.FALSE);
+            // camel will put this object into an Object[] itself
+            inMessage.setBody(null);
+        });
+
+        // get the response message 
+        List<Customer> response = CastUtils.cast((List<?>) exchange.getMessage().getBody());
+
+        assertNotNull(response, "The response should not be null");
+        assertTrue(response.contains(new Customer(113, "Dan")), "Dan is missing!");
+        assertTrue(response.contains(new Customer(123, "John")), "John is missing!");
+        assertEquals(200, exchange.getMessage().getHeader(Exchange.HTTP_RESPONSE_CODE), "Get a wrong response code");
+    }
+
+    //@Test
+    public void testGetCustomersWithHttpCentralClientAPI() {
+        Exchange exchange = template.send("direct://proxy", newExchange -> {
+            newExchange.setPattern(ExchangePattern.InOut);
+            Message inMessage = newExchange.getIn();
+            // set the Http method
+            inMessage.setHeader(Exchange.HTTP_METHOD, "GET");
+            // set the relative path 
+            inMessage.setHeader(Exchange.HTTP_PATH, "/customerservice/customers/");
+            // using the proxy client API
+            inMessage.setHeader(CxfConstants.CAMEL_CXF_RS_USING_HTTP_API, Boolean.TRUE);
+            // set the headers 
+            inMessage.setHeader(CxfConstants.CAMEL_CXF_RS_RESPONSE_CLASS, List.class);
+            inMessage.setHeader(CxfConstants.CAMEL_CXF_RS_RESPONSE_GENERIC_TYPE,
+                    new ParameterizedCollectionType(Customer.class));
+            // camel will put this object into an Object[] itself
+            inMessage.setBody(null);
+        });
+
+        // get the response message 
+        List<Customer> response = CastUtils.cast((List<?>) exchange.getMessage().getBody());
+
+        assertNotNull(response, "The response should not be null");
+        assertTrue(response.contains(new Customer(113, "Dan")), "Dan is missing!");
+        assertTrue(response.contains(new Customer(123, "John")), "John is missing!");
+        assertEquals(200, exchange.getMessage().getHeader(Exchange.HTTP_RESPONSE_CODE), "Get a wrong response code");
+    }
+
+    @Test
+    public void testGetCustomerWithHttpCentralClientAPI() {
+        Exchange exchange = template.send("direct://http", newExchange -> {
+            newExchange.setPattern(ExchangePattern.InOut);
+            Message inMessage = newExchange.getIn();
+            // using the http central client API
+            inMessage.setHeader(CxfConstants.CAMEL_CXF_RS_USING_HTTP_API, Boolean.TRUE);
+            // set the Http method
+            inMessage.setHeader(Exchange.HTTP_METHOD, "GET");
+            // set the relative path
+            inMessage.setHeader(Exchange.HTTP_PATH, "/customerservice/customers/123");
+            // Specify the response class , cxfrs will use InputStream as the response object type 
+            inMessage.setHeader(CxfConstants.CAMEL_CXF_RS_RESPONSE_CLASS, Customer.class);
+            // set a customer header
+            inMessage.setHeader("key", "value");
+            // since we use the Get method, so we don't need to set the message body
+            inMessage.setBody(null);
+        });
+
+        // get the response message 
+        Customer response = (Customer) exchange.getMessage().getBody();
+
+        assertNotNull(response, "The response should not be null");
+        assertEquals(123, response.getId(), "Get a wrong customer id");
+        assertEquals("John", response.getName(), "Get a wrong customer name");
+        assertEquals(200, exchange.getMessage().getHeader(Exchange.HTTP_RESPONSE_CODE), "Get a wrong response code");
+        assertEquals("value", exchange.getMessage().getHeader("key"), "Get a wrong header value");
+    }
+
+    @Test
+    public void testSuppressGetCustomerExceptionWithCxfRsEndpoint() {
+        Exchange exchange
+                = template.send("cxfrs://http://localhost:" + port1 + "/services/" + getClass().getSimpleName()
+                                + "/?httpClientAPI=true&throwExceptionOnFailure=false",
+                        newExchange -> {
+                            newExchange.setPattern(ExchangePattern.InOut);
+                            Message message = newExchange.getIn();
+                            // set the Http method
+                            message.setHeader(Exchange.HTTP_METHOD, "PUT");
+                            // set the relative path
+                            message.setHeader(Exchange.HTTP_PATH, "/customerservice/customers");
+                            // we just setup the customer with a wrong id
+                            Customer customer = new Customer();
+                            customer.setId(222);
+                            customer.setName("user");
+                            message.setBody(customer);
+                        });
+
+        // we should get the exception here 
+        assertNull(exchange.getException(), "Don't expect the exception here");
+        Message result = exchange.getMessage();
+        assertEquals(406, result.getHeader(Exchange.HTTP_RESPONSE_CODE), "Get a wrong http status code.");
+
+    }
+
+    @Test
+    public void testGetCustomerExceptionWithCxfRsEndpoint() {
+        Exchange exchange
+                = template.send(
+                        "cxfrs://http://localhost:" + port1 + "/services/" + getClass().getSimpleName() + "/?httpClientAPI=true",
+                        newExchange -> {
+                            newExchange.setPattern(ExchangePattern.InOut);
+                            Message message = newExchange.getIn();
+                            // set the Http method
+                            message.setHeader(Exchange.HTTP_METHOD, "PUT");
+                            // set the relative path
+                            message.setHeader(Exchange.HTTP_PATH, "/customerservice/customers");
+                            // we just setup the customer with a wrong id
+                            Customer customer = new Customer();
+                            customer.setId(222);
+                            customer.setName("user");
+                            message.setBody(customer);
+                        });
+
+        // we should get the exception here 
+        assertNotNull(exchange.getException(), "Expect the exception here");
+        CxfOperationException exception = (CxfOperationException) exchange.getException();
+
+        assertEquals("Cannot find the customer!", exception.getResponseBody(), "Get a wrong response body");
+
+    }
+
+    @Test
+    public void testGetCustomerWithCxfRsEndpoint() {
+        Exchange exchange
+                = template.send(
+                        "cxfrs://http://localhost:" + port1 + "/services/" + getClass().getSimpleName() + "/?httpClientAPI=true",
+                        newExchange -> {
+                            newExchange.setPattern(ExchangePattern.InOut);
+                            Message inMessage = newExchange.getIn();
+                            // set the Http method
+                            inMessage.setHeader(Exchange.HTTP_METHOD, "GET");
+                            // set the relative path
+                            inMessage.setHeader(Exchange.HTTP_PATH, "/customerservice/customers/123");
+                            // Specify the response class , cxfrs will use InputStream as the response object type 
+                            inMessage.setHeader(CxfConstants.CAMEL_CXF_RS_RESPONSE_CLASS, Customer.class);
+                            // since we use the Get method, so we don't need to set the message body
+                            inMessage.setBody(null);
+                        });
+
+        // get the response message 
+        Customer response = (Customer) exchange.getMessage().getBody();
+        assertNotNull(response, "The response should not be null");
+        assertEquals(123, response.getId(), "Get a wrong customer id");
+        assertEquals("John", response.getName(), "Get a wrong customer name");
+        assertEquals(200, exchange.getMessage().getHeader(Exchange.HTTP_RESPONSE_CODE), "Get a wrong response code");
+    }
+
+    @Test
+    public void testGetCustomerWithVariableReplacementAndCxfRsEndpoint() {
+        Exchange exchange = template.send(
+                "cxfrs://http://localhost:" + port1 + "/services/" + getClass().getSimpleName() + "/?httpClientAPI=true",
+                newExchange -> {
+                    newExchange.setPattern(ExchangePattern.InOut);
+                    Message inMessage = newExchange.getIn();
+                    // set the Http method
+                    inMessage.setHeader(Exchange.HTTP_METHOD, "GET");
+                    // set the relative path
+                    inMessage.setHeader(Exchange.HTTP_PATH, "/customerservice/customers/{customerId}");
+                    // Set variables for replacement
+                    inMessage.setHeader(CxfConstants.CAMEL_CXF_RS_VAR_VALUES, new String[] { "123" });
+                    // Specify the response class , cxfrs will use InputStream as the response object type
+                    inMessage.setHeader(CxfConstants.CAMEL_CXF_RS_RESPONSE_CLASS, Customer.class);
+                    // since we use the Get method, so we don't need to set the message body
+                    inMessage.setBody(null);
+                });
+
+        // get the response message
+        Customer response = (Customer) exchange.getMessage().getBody();
+        assertNotNull(response, "The response should not be null");
+        assertEquals(123, response.getId(), "Get a wrong customer id");
+        assertEquals("John", response.getName(), "Get a wrong customer name");
+        assertEquals(200, exchange.getMessage().getHeader(Exchange.HTTP_RESPONSE_CODE), "Get a wrong response code");
+    }
+
+    @Test
+    public void testAddCustomerUniqueResponseCodeWithHttpClientAPI() {
+        Exchange exchange
+                = template.send(
+                        "cxfrs://http://localhost:" + port1 + "/services/" + getClass().getSimpleName() + "?httpClientAPI=true",
+                        newExchange -> {
+                            newExchange.setPattern(ExchangePattern.InOut);
+                            Message inMessage = newExchange.getIn();
+                            // set the Http method
+                            inMessage.setHeader(Exchange.HTTP_METHOD, "POST");
+                            // set the relative path
+                            inMessage.setHeader(Exchange.HTTP_PATH, "/customerservice/customersUniqueResponseCode");
+                            // create a new customer object
+                            Customer customer = new Customer();
+                            customer.setId(9999);
+                            customer.setName("HttpClient");
+                            inMessage.setBody(customer);
+                        });
+
+        // get the response message 
+        Response response = (Response) exchange.getMessage().getBody();
+        assertNotNull(response, "The response should not be null");
+        assertNotNull(response.getEntity(), "The response entity should not be null");
+        // check the response code
+        assertEquals(201, response.getStatus(), "Get a wrong response code");
+        // check the response code from message header
+        assertEquals(201, exchange.getMessage().getHeader(Exchange.HTTP_RESPONSE_CODE), "Get a wrong response code");
+    }
+
+    //@Test
+    public void testAddCustomerUniqueResponseCodeWithProxyAPI() {
+        Exchange exchange = template.send("direct://proxy", new Processor() {
+            public void process(Exchange exchange) throws Exception {
+                exchange.setPattern(ExchangePattern.InOut);
+                Message inMessage = exchange.getIn();
+                // set the operation name 
+                inMessage.setHeader(CxfConstants.OPERATION_NAME, "addCustomerUniqueResponseCode");
+                // using the proxy client API
+                inMessage.setHeader(CxfConstants.CAMEL_CXF_RS_USING_HTTP_API, Boolean.FALSE);
+                // set the parameters , if you just have one parameter 
+                // camel will put this object into an Object[] itself
+                Customer customer = new Customer();
+                customer.setId(8888);
+                customer.setName("ProxyAPI");
+                inMessage.setBody(customer);
+            }
+        });
+
+        // get the response message 
+        Response response = (Response) exchange.getMessage().getBody();
+        assertNotNull(response, "The response should not be null");
+        assertNotNull(response.getEntity(), "The response entity should not be null");
+        // check the response code
+        assertEquals(201, response.getStatus(), "Get a wrong response code");
+        // check the response code from message header
+        assertEquals(201, exchange.getMessage().getHeader(Exchange.HTTP_RESPONSE_CODE), "Get a wrong response code");
+    }
+
+    @Test
+    public void testAddCustomerUniqueResponseCode() {
+        Exchange exchange
+                = template.send(
+                        "cxfrs://http://localhost:" + port1 + "/services/" + getClass().getSimpleName() + "?httpClientAPI=true",
+                        new Processor() {
+                            public void process(Exchange exchange) throws Exception {
+                                exchange.setPattern(ExchangePattern.InOut);
+                                Message inMessage = exchange.getIn();
+                                // set the Http method
+                                inMessage.setHeader(Exchange.HTTP_METHOD, "POST");
+                                // set the relative path
+                                inMessage.setHeader(Exchange.HTTP_PATH, "/customerservice/customersUniqueResponseCode");
+                                // put the response's entity into out message body
+                                inMessage.setHeader(CxfConstants.CAMEL_CXF_RS_RESPONSE_CLASS, Customer.class);
+                                // create a new customer object
+                                Customer customer = new Customer();
+                                customer.setId(8888);
+                                customer.setName("Willem");
+                                inMessage.setBody(customer);
+                            }
+                        });
+
+        // get the response message 
+        Customer response = (Customer) exchange.getMessage().getBody();
+        assertNotNull(response, "The response should not be null");
+        assertNotEquals(8888, response.getId(), "Get a wrong customer id");
+        assertEquals("Willem", response.getName(), "Get a wrong customer name");
+        assertEquals(201, exchange.getMessage().getHeader(Exchange.HTTP_RESPONSE_CODE), "Get a wrong response code");
+    }
+
+    @Test
+    public void testProducerWithQueryParameters() {
+        Exchange exchange = template.send("cxfrs://http://localhost:" + port2 + "/" + getClass().getSimpleName()
+                                          + "/testQuery?httpClientAPI=true&q1=12&q2=13",
+                newExchange -> {
+                    newExchange.setPattern(ExchangePattern.InOut);
+                    Message inMessage = newExchange.getIn();
+                    // set the Http method
+                    inMessage.setHeader(Exchange.HTTP_METHOD, "GET");
+                    inMessage.setHeader(CxfConstants.CAMEL_CXF_RS_RESPONSE_CLASS, InputStream.class);
+                    inMessage.setBody(null);
+                });
+
+        // get the response message 
+        String response = exchange.getMessage().getBody(String.class);
+        assertNotNull(response, "The response should not be null");
+        assertEquals("q1=12&q2=13", response, "The response value is wrong");
+    }
+
+    @Test
+    public void testProducerWithQueryParametersHeader() {
+        Exchange exchange = template.send("cxfrs://http://localhost:" + port2 + "/" + getClass().getSimpleName()
+                                          + "/testQuery?httpClientAPI=true&q1=12&q2=13",
+                newExchange -> {
+                    newExchange.setPattern(ExchangePattern.InOut);
+                    Message inMessage = newExchange.getIn();
+                    // set the Http method
+                    inMessage.setHeader(Exchange.HTTP_METHOD, "GET");
+                    inMessage.setHeader(CxfConstants.CAMEL_CXF_RS_RESPONSE_CLASS, InputStream.class);
+                    // override the parameter setting from URI
+                    // START SNIPPET: QueryMapExample
+                    Map<String, String> queryMap = new LinkedHashMap<>();
+                    queryMap.put("q1", "new");
+                    queryMap.put("q2", "world");
+                    inMessage.setHeader(CxfConstants.CAMEL_CXF_RS_QUERY_MAP, queryMap);
+                    // END SNIPPET: QueryMapExample 
+                    inMessage.setBody(null);
+                });
+
+        // get the response message 
+        String response = exchange.getMessage().getBody(String.class);
+        assertNotNull(response, "The response should not be null");
+        assertEquals("q1=new&q2=world", response, "The response value is wrong");
+    }
+
+    @Test
+    public void testRestServerDirectlyGetCustomer() {
+        // we cannot convert directly to Customer as we need camel-jaxb
+        String response = template.requestBodyAndHeader(
+                "cxfrs:http://localhost:" + port1 + "/services/" + getClass().getSimpleName() + "/customerservice/customers/123",
+                null, Exchange.HTTP_METHOD, "GET", String.class);
+
+        assertNotNull(response, "The response should not be null");
+    }
+
+    @Test
+    public void testRestServerDirectlyAddCustomer() {
+        Customer input = new Customer();
+        input.setName("Donald Duck");
+
+        // we cannot convert directly to Customer as we need camel-jaxb
+        String response = template.requestBodyAndHeader(
+                "cxfrs:http://localhost:" + port1 + "/services/" + getClass().getSimpleName() + "/customerservice/customers",
+                input, Exchange.HTTP_METHOD, "POST", String.class);
+
+        assertNotNull(response);
+        assertTrue(response.endsWith("<name>Donald Duck</name></Customer>"));
+    }
+
+    
+    
+    
+    @Test
+    public void testProducerWithFeature() {
+        TestFeature feature = context.getRegistry().lookupByNameAndType("testFeature", TestFeature.class);
+
+        template.requestBodyAndHeader("cxfrs:http://localhost:" + port1 + "/services/" + getClass().getSimpleName()
+                                      + "/customerservice/customers/123?features=#myFeatures",
+                null, Exchange.HTTP_METHOD, "GET", String.class);
+
+        assertTrue(feature.initialized, "The feature should be initialized");
+    }
+
+    @Test
+    public void testProducer422Response() {
+        Exchange exchange = template.send(
+                "cxfrs://http://localhost:" + port1 + "/services/" + getClass().getSimpleName() + "/?httpClientAPI=true",
+                newExchange -> {
+                    newExchange.setPattern(ExchangePattern.InOut);
+                    Message message = newExchange.getIn();
+                    // Try to create a new Customer with an invalid name
+                    message.setHeader(Exchange.HTTP_METHOD, "POST");
+                    message.setHeader(Exchange.HTTP_PATH, "/customerservice/customers");
+                    Customer customer = new Customer();
+                    customer.setId(8888);
+                    customer.setName("");  // will trigger a 422 response (a common REST server validation response code)
+                    message.setBody(customer);
+                });
+
+        assertNotNull(exchange.getException(), "Expect the exception here");
+        assertTrue(exchange.getException() instanceof CxfOperationException, "Exception should be a CxfOperationException");
+
+        CxfOperationException cxfOperationException = CxfOperationException.class.cast(exchange.getException());
+
+        assertEquals(422, cxfOperationException.getStatusCode(), "CXF operation exception has correct response code");
+    }
+    
+    class TestFeature implements Feature {
+        boolean initialized;
+
+        @Override
+        public void initialize(InterceptorProvider interceptorProvider, Bus bus) {
+            initialized = true;
+        }
+
+        @Override
+        public void initialize(Client client, Bus bus) {
+            //Do nothing
+        }
+
+        @Override
+        public void initialize(Server server, Bus bus) {
+            //Do nothing
+        }
+
+        @Override
+        public void initialize(Bus bus) {
+            //Do nothing
+        }
+    }
+    
+    class JettyProcessor implements Processor {
+        @Override
+        public void process(Exchange exchange) throws Exception {
+            // check the query
+            Message inMessage = exchange.getIn();
+            exchange.getMessage().setBody(inMessage.getHeader(Exchange.HTTP_QUERY, String.class));
+        }
+    }
+    
+    // *************************************
+    // Config
+    // *************************************
+
+    @Configuration
+    public class TestConfiguration {
+
+        
+        @Bean
+        public ServletWebServerFactory servletWebServerFactory() {
+            return new UndertowServletWebServerFactory(port1);
+        }
+              
+        
+        @Bean 
+        public CamelEndpointFactoryBean fromEndpoint() {
+            CamelEndpointFactoryBean jettyConsumer = new CamelEndpointFactoryBean();
+            jettyConsumer.setUri("jetty://http://localhost:" + port2 + "/CxfRsAsyncProducerTest/testQuery");
+            return jettyConsumer;
+        }
+        
+        @Bean 
+        public Processor myProcessor() {
+            return new JettyProcessor();
+        }
+        
+        /*@Bean
+        public AbstractJAXRSFactoryBean rsClientProxy() {
+            SpringJAXRSClientFactoryBean afb = new SpringJAXRSClientFactoryBean();
+            //afb.setBus(BusFactory.getDefaultBus());
+            afb.setAddress("http://localhost:" + port1
+                                   + "/services/CxfRsAsyncProducerTest/");
+            //afb.setServiceClass somehow cause conflict with other test, should be bus conflict
+            afb.setServiceClass(org.apache.camel.component.cxf.jaxrs.testbean.CustomerService.class);
+            afb.setLoggingFeatureEnabled(true);
+            
+            return afb;
+        }*/
+        
+        @Bean
+        public AbstractJAXRSFactoryBean rsClientHttp() {
+            SpringJAXRSClientFactoryBean afb = new SpringJAXRSClientFactoryBean();
+            afb.setAddress("http://localhost:" + port1
+                                   + "/services/CxfRsAsyncProducerTest/");
+            return afb;
+        }
+        
+        
+        
+        @Bean
+        public Feature testFeature() {
+            return new TestFeature();
+        }
+        
+        @Bean
+        public List<Feature> myFeatures(Feature testFeature) {
+            List<Feature> features = new ArrayList<Feature>();
+            features.add(testFeature);
+            return features;
+        }
+        
+        @Bean
+        public RouteBuilder routeBuilder() {
+            return new RouteBuilder() {
+                @Override
+                public void configure() {
+                    //from("direct://proxy").to("cxfrs:bean:rsClientProxy");
+                    from("direct://http").to("cxfrs:bean:rsClientHttp");
+                    from("ref:fromEndpoint").process("myProcessor");
+                }
+            };
+        }
+    }
+    
+}
diff --git a/components-starter/camel-cxf-rest-starter/src/test/java/org/apache/camel/component/cxf/rest/springboot/CxfRsGlobalSslProducerTest.java b/components-starter/camel-cxf-rest-starter/src/test/java/org/apache/camel/component/cxf/rest/springboot/CxfRsGlobalSslProducerTest.java
index 3a0e4ff6c04..54f253566ab 100644
--- a/components-starter/camel-cxf-rest-starter/src/test/java/org/apache/camel/component/cxf/rest/springboot/CxfRsGlobalSslProducerTest.java
+++ b/components-starter/camel-cxf-rest-starter/src/test/java/org/apache/camel/component/cxf/rest/springboot/CxfRsGlobalSslProducerTest.java
@@ -40,6 +40,7 @@ import org.apache.camel.support.jsse.KeyStoreParameters;
 import org.apache.camel.support.jsse.SSLContextParameters;
 import org.apache.camel.support.jsse.TrustManagersParameters;
 
+import org.junit.jupiter.api.AfterEach;
 import org.junit.jupiter.api.BeforeEach;
 import org.junit.jupiter.api.Test;
 
@@ -85,6 +86,8 @@ public class CxfRsGlobalSslProducerTest {
     @Autowired
     protected ProducerTemplate template;
     
+    private Server server;
+    
     @BeforeEach
     public void setUp() throws Exception {
         JAXRSServerFactoryBean sfb = new JAXRSServerFactoryBean();
@@ -93,9 +96,17 @@ public class CxfRsGlobalSslProducerTest {
         sfb.setServiceBeans(serviceBeans);
         sfb.setAddress("/CxfRsProducerTest/");
         sfb.setStaticSubresourceResolution(true);
-        Server server = sfb.create();
+        server = sfb.create();
         server.start();
     }
+    
+    @AfterEach
+    public void shutdown() throws Exception {
+        if (server != null) {
+            server.stop();
+            server.destroy();
+        }
+    }
 
     
     protected void setupDestinationURL(Message inMessage) {
diff --git a/components-starter/camel-cxf-rest-starter/src/test/java/org/apache/camel/component/cxf/rest/springboot/CxfRsProducerHeaderTest.java b/components-starter/camel-cxf-rest-starter/src/test/java/org/apache/camel/component/cxf/rest/springboot/CxfRsProducerHeaderTest.java
index 47bcf5063c2..347aa19624e 100644
--- a/components-starter/camel-cxf-rest-starter/src/test/java/org/apache/camel/component/cxf/rest/springboot/CxfRsProducerHeaderTest.java
+++ b/components-starter/camel-cxf-rest-starter/src/test/java/org/apache/camel/component/cxf/rest/springboot/CxfRsProducerHeaderTest.java
@@ -36,6 +36,7 @@ import org.apache.camel.component.cxf.util.CxfUtils;
 import org.apache.camel.spring.boot.CamelAutoConfiguration;
 import org.apache.camel.spring.xml.CamelEndpointFactoryBean;
 
+import org.junit.jupiter.api.AfterEach;
 import org.junit.jupiter.api.BeforeEach;
 import org.junit.jupiter.api.Test;
 
@@ -79,6 +80,8 @@ public class CxfRsProducerHeaderTest {
     @Autowired
     protected CamelContext camelContext;
     
+    private Server server;
+    
     @BeforeEach
     public void setUp() throws Exception {
         JAXRSServerFactoryBean sfb = new JAXRSServerFactoryBean();
@@ -87,11 +90,17 @@ public class CxfRsProducerHeaderTest {
         sfb.setServiceBeans(serviceBeans);
         sfb.setAddress("/CxfRsProducerHeaderTest/");
         sfb.setStaticSubresourceResolution(true);
-        Server server = sfb.create();
+        server = sfb.create();
         server.start();
     }
 
-    
+    @AfterEach
+    public void shutdown() throws Exception {
+        if (server != null) {
+            server.stop();
+            server.destroy();
+        }
+    }
 
     @Test
     public void testInvokeThatDoesNotInvolveHeaders() throws Exception {
diff --git a/components-starter/camel-cxf-rest-starter/src/test/java/org/apache/camel/component/cxf/rest/springboot/CxfRsSslAsyncProducerTest.java b/components-starter/camel-cxf-rest-starter/src/test/java/org/apache/camel/component/cxf/rest/springboot/CxfRsSslAsyncProducerTest.java
index dbcf0247d2c..a92d59c7b48 100644
--- a/components-starter/camel-cxf-rest-starter/src/test/java/org/apache/camel/component/cxf/rest/springboot/CxfRsSslAsyncProducerTest.java
+++ b/components-starter/camel-cxf-rest-starter/src/test/java/org/apache/camel/component/cxf/rest/springboot/CxfRsSslAsyncProducerTest.java
@@ -39,6 +39,7 @@ import org.apache.camel.support.jsse.KeyStoreParameters;
 import org.apache.camel.support.jsse.SSLContextParameters;
 import org.apache.camel.support.jsse.TrustManagersParameters;
 
+import org.junit.jupiter.api.AfterEach;
 import org.junit.jupiter.api.BeforeEach;
 import org.junit.jupiter.api.Test;
 
@@ -84,6 +85,8 @@ public class CxfRsSslAsyncProducerTest {
     @Autowired
     protected ProducerTemplate template;
     
+    private Server server;
+    
     @BeforeEach
     public void setUp() throws Exception {
         JAXRSServerFactoryBean sfb = new JAXRSServerFactoryBean();
@@ -92,9 +95,17 @@ public class CxfRsSslAsyncProducerTest {
         sfb.setServiceBeans(serviceBeans);
         sfb.setAddress("/CxfRsProducerTest/");
         sfb.setStaticSubresourceResolution(true);
-        Server server = sfb.create();
+        server = sfb.create();
         server.start();
     }
+    
+    @AfterEach
+    public void shutdown() throws Exception {
+        if (server != null) {
+            server.stop();
+            server.destroy();
+        }
+    }
 
     
     protected void setupDestinationURL(Message inMessage) {
diff --git a/components-starter/camel-cxf-rest-starter/src/test/java/org/apache/camel/component/cxf/rest/springboot/CxfRsSslProducerTest.java b/components-starter/camel-cxf-rest-starter/src/test/java/org/apache/camel/component/cxf/rest/springboot/CxfRsSslProducerTest.java
index ecd97ec46d9..38bed0e8eed 100644
--- a/components-starter/camel-cxf-rest-starter/src/test/java/org/apache/camel/component/cxf/rest/springboot/CxfRsSslProducerTest.java
+++ b/components-starter/camel-cxf-rest-starter/src/test/java/org/apache/camel/component/cxf/rest/springboot/CxfRsSslProducerTest.java
@@ -39,6 +39,7 @@ import org.apache.camel.support.jsse.KeyStoreParameters;
 import org.apache.camel.support.jsse.SSLContextParameters;
 import org.apache.camel.support.jsse.TrustManagersParameters;
 
+import org.junit.jupiter.api.AfterEach;
 import org.junit.jupiter.api.BeforeEach;
 import org.junit.jupiter.api.Test;
 
@@ -84,6 +85,8 @@ public class CxfRsSslProducerTest {
     @Autowired
     protected ProducerTemplate template;
     
+    private Server server;
+    
     @BeforeEach
     public void setUp() throws Exception {
         JAXRSServerFactoryBean sfb = new JAXRSServerFactoryBean();
@@ -92,9 +95,17 @@ public class CxfRsSslProducerTest {
         sfb.setServiceBeans(serviceBeans);
         sfb.setAddress("/CxfRsProducerTest/");
         sfb.setStaticSubresourceResolution(true);
-        Server server = sfb.create();
+        server = sfb.create();
         server.start();
     }
+    
+    @AfterEach
+    public void shutdown() throws Exception {
+        if (server != null) {
+            server.stop();
+            server.destroy();
+        }
+    }
 
     
     protected void setupDestinationURL(Message inMessage) {


[camel-spring-boot] 02/07: add CxfRsProducerHeaderTest

Posted by ff...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

ffang pushed a commit to branch more-rest-test-new
in repository https://gitbox.apache.org/repos/asf/camel-spring-boot.git

commit a8f8f6e5def798139c41ac2bf2b5c713d640d282
Author: Freeman Fang <fr...@gmail.com>
AuthorDate: Wed Jan 11 13:44:01 2023 -0500

    add CxfRsProducerHeaderTest
    
    (cherry picked from commit 95baaf79e0e9c886f6af2ce405506d9200373ca5)
---
 components-starter/camel-cxf-rest-starter/pom.xml  |  16 ++
 .../rest/springboot/CxfRsProducerHeaderTest.java   | 235 +++++++++++++++++++++
 2 files changed, 251 insertions(+)

diff --git a/components-starter/camel-cxf-rest-starter/pom.xml b/components-starter/camel-cxf-rest-starter/pom.xml
index 84d470494c8..f70625763b3 100644
--- a/components-starter/camel-cxf-rest-starter/pom.xml
+++ b/components-starter/camel-cxf-rest-starter/pom.xml
@@ -58,6 +58,12 @@
       <version>${camel-version}</version>
       <scope>test</scope>
     </dependency>
+    <dependency>
+      <groupId>org.apache.camel.springboot</groupId>
+      <artifactId>camel-jetty-starter</artifactId>
+      <version>${camel-version}</version>
+      <scope>test</scope>
+    </dependency>
     <dependency>
       <groupId>cglib</groupId>
       <artifactId>cglib-nodep</artifactId>
@@ -93,4 +99,14 @@
     </dependency>
     <!--END OF GENERATED CODE-->
   </dependencies>
+  <build>
+    <plugins>
+      <plugin>
+        <artifactId>maven-surefire-plugin</artifactId>
+        <configuration>
+          <rerunFailingTestsCount>0</rerunFailingTestsCount>
+        </configuration>
+      </plugin>
+    </plugins>
+  </build>
 </project>
diff --git a/components-starter/camel-cxf-rest-starter/src/test/java/org/apache/camel/component/cxf/rest/springboot/CxfRsProducerHeaderTest.java b/components-starter/camel-cxf-rest-starter/src/test/java/org/apache/camel/component/cxf/rest/springboot/CxfRsProducerHeaderTest.java
new file mode 100644
index 00000000000..47bcf5063c2
--- /dev/null
+++ b/components-starter/camel-cxf-rest-starter/src/test/java/org/apache/camel/component/cxf/rest/springboot/CxfRsProducerHeaderTest.java
@@ -0,0 +1,235 @@
+/*
+ * 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.camel.component.cxf.rest.springboot;
+
+
+import java.io.InputStream;
+import java.util.ArrayList;
+import java.util.List;
+
+import javax.ws.rs.core.Response;
+
+
+import org.apache.camel.CamelContext;
+import org.apache.camel.Exchange;
+import org.apache.camel.ExchangePattern;
+import org.apache.camel.Message;
+import org.apache.camel.Processor;
+import org.apache.camel.builder.RouteBuilder;
+import org.apache.camel.component.cxf.common.CXFTestSupport;
+import org.apache.camel.component.cxf.common.message.CxfConstants;
+import org.apache.camel.component.cxf.util.CxfUtils;
+import org.apache.camel.spring.boot.CamelAutoConfiguration;
+import org.apache.camel.spring.xml.CamelEndpointFactoryBean;
+
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertNull;
+
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.boot.test.context.SpringBootTest;
+import org.springframework.boot.web.embedded.undertow.UndertowServletWebServerFactory;
+import org.springframework.boot.web.servlet.server.ServletWebServerFactory;
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.Configuration;
+import org.springframework.test.annotation.DirtiesContext;
+import org.springframework.test.annotation.DirtiesContext.ClassMode;
+import org.apache.camel.test.spring.junit5.CamelSpringBootTest;
+import org.apache.cxf.endpoint.Server;
+import org.apache.cxf.jaxrs.JAXRSServerFactoryBean;
+import org.apache.cxf.spring.boot.autoconfigure.CxfAutoConfiguration;
+
+
+
+@DirtiesContext(classMode = ClassMode.AFTER_EACH_TEST_METHOD)
+@CamelSpringBootTest
+@SpringBootTest(
+    classes = {
+        CamelAutoConfiguration.class,
+        CxfRsProducerHeaderTest.class,
+        CxfRsProducerHeaderTest.TestConfiguration.class,
+        CxfAutoConfiguration.class
+    }, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT
+)
+public class CxfRsProducerHeaderTest {
+
+    static int port2 = CXFTestSupport.getPort2();
+    static int port3 = CXFTestSupport.getPort("CxfRsProducerHeaderTest.1");
+
+    private static final Object RESPONSE = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>"
+                                           + "<Customer><id>123</id><name>John</name></Customer>";
+
+    @Autowired
+    protected CamelContext camelContext;
+    
+    @BeforeEach
+    public void setUp() throws Exception {
+        JAXRSServerFactoryBean sfb = new JAXRSServerFactoryBean();
+        List<Object> serviceBeans = new ArrayList<Object>();
+        serviceBeans.add(new org.apache.camel.component.cxf.jaxrs.testbean.CustomerService());
+        sfb.setServiceBeans(serviceBeans);
+        sfb.setAddress("/CxfRsProducerHeaderTest/");
+        sfb.setStaticSubresourceResolution(true);
+        Server server = sfb.create();
+        server.start();
+    }
+
+    
+
+    @Test
+    public void testInvokeThatDoesNotInvolveHeaders() throws Exception {
+        Exchange exchange = camelContext.createProducerTemplate().send("direct://http", new Processor() {
+
+            public void process(Exchange exchange) throws Exception {
+                exchange.setPattern(ExchangePattern.InOut);
+                Message inMessage = exchange.getIn();
+                inMessage.setHeader(CxfConstants.CAMEL_CXF_RS_USING_HTTP_API, Boolean.TRUE);
+                inMessage.setHeader(Exchange.HTTP_METHOD, "GET");
+                inMessage.setHeader(Exchange.HTTP_PATH, "/customerservice/customers/123");
+                inMessage.setBody(null);
+            }
+
+        });
+
+        // verify the out message is a Response object by default
+        Response response = (Response) exchange.getMessage().getBody();
+        assertNotNull(response, "The response should not be null");
+        assertEquals(200, response.getStatus());
+
+        // test converter (from Response to InputStream)
+        assertEquals(RESPONSE, CxfUtils.getStringFromInputStream(exchange.getMessage().getBody(InputStream.class)));
+    }
+
+    @Test
+    public void testHeaderFilteringAndPropagation() throws Exception {
+        Exchange exchange = camelContext.createProducerTemplate().send("direct://http2", new Processor() {
+
+            public void process(Exchange exchange) throws Exception {
+                exchange.setPattern(ExchangePattern.InOut);
+                Message inMessage = exchange.getIn();
+                inMessage.setHeader(CxfConstants.CAMEL_CXF_RS_USING_HTTP_API, Boolean.TRUE);
+                inMessage.setHeader(Exchange.HTTP_METHOD, "GET");
+                inMessage.setHeader(Exchange.HTTP_PATH, "/CxfRsProducerHeaderTest/customerservice/customers/123");
+                inMessage.setHeader("Accept", "application/json");
+                inMessage.setHeader("my-user-defined-header", "my-value");
+                inMessage.setBody(null);
+            }
+
+        });
+
+        // get the response message 
+        Response response = (Response) exchange.getMessage().getBody();
+
+        // check the response code on the Response object as set by the "HttpProcess"
+        assertEquals(200, response.getStatus());
+
+        // get out message
+        Message outMessage = exchange.getMessage();
+
+        // verify the content-type header sent by the "HttpProcess"
+        assertEquals("text/xml", outMessage.getHeader(Exchange.CONTENT_TYPE));
+
+        // check the user defined header echoed by the "HttpProcess"
+        assertEquals("my-value", outMessage.getHeader("echo-my-user-defined-header"));
+
+        // check the Accept header echoed by the "HttpProcess"
+        assertEquals("application/json", outMessage.getHeader("echo-accept"));
+
+        // make sure the HttpProcess have not seen CxfConstants.CAMEL_CXF_RS_USING_HTTP_API
+        assertNull(outMessage.getHeader("failed-header-using-http-api"));
+
+        // make sure response code has been set in out header
+        assertEquals(Integer.valueOf(200), outMessage.getHeader(Exchange.HTTP_RESPONSE_CODE, Integer.class));
+    }
+
+    public static class HttpProcessor implements Processor {
+
+        @Override
+        public void process(Exchange exchange) throws Exception {
+            Message in = exchange.getIn();
+            Message out = exchange.getMessage();
+
+            if (in.getHeader(CxfConstants.CAMEL_CXF_RS_USING_HTTP_API) != null) {
+                // this should have been filtered
+                out.setHeader("failed-header-using-http-api", CxfConstants.CAMEL_CXF_RS_USING_HTTP_API);
+            }
+
+            out.setHeader("echo-accept", in.getHeader("Accept"));
+            out.setHeader("echo-my-user-defined-header", in.getHeader("my-user-defined-header"));
+
+            exchange.getMessage().setHeader(Exchange.HTTP_RESPONSE_CODE, 200);
+            exchange.getMessage().setHeader(Exchange.CONTENT_TYPE, "text/xml");
+
+        }
+
+    }
+    
+    // *************************************
+    // Config
+    // *************************************
+
+    @Configuration
+    public class TestConfiguration {
+
+        @Bean
+        public HttpProcessor httpProcessor() {
+            return new HttpProcessor();
+        }
+        
+        @Bean
+        public ServletWebServerFactory servletWebServerFactory() {
+            return new UndertowServletWebServerFactory(port2);
+        }
+        
+        @Bean 
+        public CamelEndpointFactoryBean to1() {
+            CamelEndpointFactoryBean cxfRsProducer = new CamelEndpointFactoryBean();
+            cxfRsProducer.setUri("cxfrs://http://localhost:" + port2 + "/services/CxfRsProducerHeaderTest/");
+            return cxfRsProducer;
+        }
+        
+        @Bean 
+        public CamelEndpointFactoryBean to2() {
+            CamelEndpointFactoryBean cxfRsProducer = new CamelEndpointFactoryBean();
+            cxfRsProducer.setUri("cxfrs://http://localhost:" + port3 + "/CxfRsProducerHeaderTest");
+            return cxfRsProducer;
+        }
+        
+        @Bean 
+        public CamelEndpointFactoryBean from1() {
+            CamelEndpointFactoryBean jettyConsumer = new CamelEndpointFactoryBean();
+            jettyConsumer.setUri("jetty://http://localhost:" + port3 + "/CxfRsProducerHeaderTest?matchOnUriPrefix=true");
+            return jettyConsumer;
+        }
+        
+        @Bean
+        public RouteBuilder routeBuilder() {
+            return new RouteBuilder() {
+                @Override
+                public void configure() {
+                    from("direct://http").to("ref:to1");
+                    from("direct://http2").to("ref:to2");
+                    from("ref:from1").process("httpProcessor");
+                }
+            };
+        }
+    }
+    
+}


[camel-spring-boot] 01/07: some clean up

Posted by ff...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

ffang pushed a commit to branch more-rest-test-new
in repository https://gitbox.apache.org/repos/asf/camel-spring-boot.git

commit 01360d8be9c63717521e3b90b5910e54d11ad0d6
Author: Freeman Fang <fr...@gmail.com>
AuthorDate: Tue Dec 20 16:10:36 2022 -0500

    some clean up
    
    (cherry picked from commit eb628065848af5eca1120d0c0500f5ae2b1b45b1)
---
 components-starter/camel-cxf-rest-starter/pom.xml  |  11 +-
 .../cxf/jaxrs/testbean/CustomException.java        |  27 ----
 .../component/cxf/jaxrs/testbean/Customer.java     |  75 ----------
 .../cxf/jaxrs/testbean/CustomerService.java        | 153 ---------------------
 .../testbean/CustomerServiceNoAnnotations.java     |  25 ----
 .../jaxrs/testbean/CustomerServiceResource.java    |  51 -------
 .../component/cxf/jaxrs/testbean/EchoService.java  |  41 ------
 .../camel/component/cxf/jaxrs/testbean/Order.java  |  67 ---------
 .../component/cxf/jaxrs/testbean/Product.java      |  41 ------
 .../component/cxf/jaxrs/testbean/ServiceUtil.java  |  24 ----
 .../rest/springboot/CxfRsConsumerWithBeanTest.java |  24 ++--
 .../rest/springboot/CxfRsProducerSessionTest.java  |   5 +-
 .../cxf/rest/springboot/CxfRsStreamCacheTest.java  |   7 +-
 .../routes/CxfRsSpringProducerSession.xml          |   4 +-
 14 files changed, 31 insertions(+), 524 deletions(-)

diff --git a/components-starter/camel-cxf-rest-starter/pom.xml b/components-starter/camel-cxf-rest-starter/pom.xml
index a8f6000d351..84d470494c8 100644
--- a/components-starter/camel-cxf-rest-starter/pom.xml
+++ b/components-starter/camel-cxf-rest-starter/pom.xml
@@ -40,16 +40,17 @@
       <version>${camel-version}</version>
     </dependency>
     <dependency>
-      <groupId>org.apache.cxf</groupId>
-      <artifactId>cxf-rt-transports-http-undertow</artifactId>
-      <version>${cxf-version}</version>
-      <scope>test</scope>
+      <groupId>org.apache.camel</groupId>
+      <artifactId>camel-cxf-common</artifactId>
+      <version>${camel-version}</version>
+      <type>test-jar</type>
     </dependency>
     <dependency>
       <groupId>org.apache.camel</groupId>
-      <artifactId>camel-cxf-common</artifactId>
+      <artifactId>camel-cxf-spring-rest</artifactId>
       <version>${camel-version}</version>
       <type>test-jar</type>
+      <scope>test</scope>
     </dependency>
     <dependency>
       <groupId>org.apache.camel</groupId>
diff --git a/components-starter/camel-cxf-rest-starter/src/test/java/org/apache/camel/component/cxf/jaxrs/testbean/CustomException.java b/components-starter/camel-cxf-rest-starter/src/test/java/org/apache/camel/component/cxf/jaxrs/testbean/CustomException.java
deleted file mode 100644
index 1b34d8d6bf5..00000000000
--- a/components-starter/camel-cxf-rest-starter/src/test/java/org/apache/camel/component/cxf/jaxrs/testbean/CustomException.java
+++ /dev/null
@@ -1,27 +0,0 @@
-/*
- * 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.camel.component.cxf.jaxrs.testbean;
-
-public class CustomException extends Exception {
-
-    private static final long serialVersionUID = 1L;
-
-    public CustomException(String message) {
-        super(message);
-    }
-
-}
diff --git a/components-starter/camel-cxf-rest-starter/src/test/java/org/apache/camel/component/cxf/jaxrs/testbean/Customer.java b/components-starter/camel-cxf-rest-starter/src/test/java/org/apache/camel/component/cxf/jaxrs/testbean/Customer.java
deleted file mode 100644
index e0b740c8761..00000000000
--- a/components-starter/camel-cxf-rest-starter/src/test/java/org/apache/camel/component/cxf/jaxrs/testbean/Customer.java
+++ /dev/null
@@ -1,75 +0,0 @@
-/*
- * 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.camel.component.cxf.jaxrs.testbean;
-
-import javax.xml.bind.annotation.XmlRootElement;
-
-import org.apache.camel.util.ObjectHelper;
-
-@XmlRootElement(name = "Customer")
-public class Customer {
-    private long id;
-    private String name;
-
-    public Customer() {
-    }
-
-    public Customer(long id, String name) {
-        setId(id);
-        setName(name);
-    }
-
-    public long getId() {
-        return id;
-    }
-
-    public void setId(long id) {
-        this.id = id;
-    }
-
-    public String getName() {
-        return name;
-    }
-
-    public void setName(String name) {
-        this.name = name;
-    }
-
-    @Override
-    public int hashCode() {
-        final int prime = 31;
-        int result = 1;
-        result = prime * result + (int) (id ^ (id >>> 32));
-        result = prime * result + ((name == null) ? 0 : name.hashCode());
-        return result;
-    }
-
-    @Override
-    public boolean equals(Object obj) {
-        if (!(obj instanceof Customer)) {
-            return false;
-        }
-
-        if (this == obj) {
-            return true;
-        }
-
-        Customer other = (Customer) obj;
-        return id == other.id && ObjectHelper.equal(name, other.name);
-    }
-
-}
diff --git a/components-starter/camel-cxf-rest-starter/src/test/java/org/apache/camel/component/cxf/jaxrs/testbean/CustomerService.java b/components-starter/camel-cxf-rest-starter/src/test/java/org/apache/camel/component/cxf/jaxrs/testbean/CustomerService.java
deleted file mode 100644
index c30fd82dd79..00000000000
--- a/components-starter/camel-cxf-rest-starter/src/test/java/org/apache/camel/component/cxf/jaxrs/testbean/CustomerService.java
+++ /dev/null
@@ -1,153 +0,0 @@
-/*
- * 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.camel.component.cxf.jaxrs.testbean;
-
-import java.util.ArrayList;
-import java.util.List;
-import java.util.Map;
-import java.util.concurrent.ConcurrentHashMap;
-import java.util.concurrent.atomic.AtomicLong;
-
-import javax.ws.rs.DELETE;
-import javax.ws.rs.GET;
-import javax.ws.rs.POST;
-import javax.ws.rs.PUT;
-import javax.ws.rs.Path;
-import javax.ws.rs.PathParam;
-import javax.ws.rs.Produces;
-import javax.ws.rs.QueryParam;
-import javax.ws.rs.core.Response;
-
-import org.apache.cxf.common.util.StringUtils;
-
-@Path("/customerservice/")
-public class CustomerService {
-    private final AtomicLong currentId = new AtomicLong(123L);
-    private final Map<Long, Customer> customers = new ConcurrentHashMap<>();
-    private final Map<Long, Order> orders = new ConcurrentHashMap<>();
-
-    public CustomerService() {
-        init();
-    }
-
-    @GET
-    @Path("/customers/{id}/")
-    public Customer getCustomer(@PathParam("id") String id) {
-        long idNumber = Long.parseLong(id);
-        Customer c = customers.get(idNumber);
-        return c;
-    }
-
-    @GET
-    @Path("/customers")
-    public Customer getCustomerByQueryParam(@QueryParam("id") String id) {
-        long idNumber = Long.parseLong(id);
-        Customer c = customers.get(idNumber);
-        return c;
-    }
-
-    @GET
-    @Path("/customers/")
-    @Produces("application/xml")
-    public List<Customer> getCustomers() {
-        List<Customer> list = new ArrayList<>(customers.values());
-        return list;
-    }
-
-    @PUT
-    @Path("/customers/")
-    public Response updateCustomer(Customer customer) {
-        Customer c = customers.get(customer.getId());
-        Response r;
-        if (c != null) {
-            customers.put(customer.getId(), customer);
-            r = Response.ok().build();
-        } else {
-            r = Response.status(406).entity("Cannot find the customer!").build();
-        }
-
-        return r;
-    }
-
-    @POST
-    @Path("/customers/")
-    public Response addCustomer(Customer customer) {
-        if (StringUtils.isEmpty(customer.getName())) {
-            return Response.status(422).build();
-        }
-
-        customer.setId(currentId.incrementAndGet());
-
-        customers.put(customer.getId(), customer);
-
-        return Response.ok(customer).build();
-    }
-
-    @POST
-    @Path("/customersUniqueResponseCode/")
-    public Response addCustomerUniqueResponseCode(Customer customer) {
-        customer.setId(currentId.incrementAndGet());
-
-        customers.put(customer.getId(), customer);
-
-        return Response.status(201).entity(customer).build();
-    }
-
-    @DELETE
-    @Path("/customers/{id}/")
-    public Response deleteCustomer(@PathParam("id") String id) {
-        long idNumber = Long.parseLong(id);
-        Customer c = customers.get(idNumber);
-
-        Response r;
-        if (c != null) {
-            r = Response.ok().build();
-            customers.remove(idNumber);
-        } else {
-            r = Response.notModified().build();
-        }
-        if (idNumber == currentId.get()) {
-            currentId.decrementAndGet();
-        }
-        return r;
-    }
-
-    @Path("/orders/{orderId}/")
-    public Order getOrder(@PathParam("orderId") String orderId) {
-        long idNumber = Long.parseLong(orderId);
-        Order c = orders.get(idNumber);
-        return c;
-    }
-
-    final void init() {
-        Customer c = new Customer();
-        c.setName("John");
-        c.setId(123);
-        customers.put(c.getId(), c);
-
-        c = new Customer();
-        c.setName("Dan");
-        c.setId(113);
-        customers.put(c.getId(), c);
-
-        Order o = new Order();
-        o.setDescription("order 223");
-        o.setId(223);
-        orders.put(o.getId(), o);
-    }
-
-}
diff --git a/components-starter/camel-cxf-rest-starter/src/test/java/org/apache/camel/component/cxf/jaxrs/testbean/CustomerServiceNoAnnotations.java b/components-starter/camel-cxf-rest-starter/src/test/java/org/apache/camel/component/cxf/jaxrs/testbean/CustomerServiceNoAnnotations.java
deleted file mode 100644
index fa9a395cb96..00000000000
--- a/components-starter/camel-cxf-rest-starter/src/test/java/org/apache/camel/component/cxf/jaxrs/testbean/CustomerServiceNoAnnotations.java
+++ /dev/null
@@ -1,25 +0,0 @@
-/*
- * 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.camel.component.cxf.jaxrs.testbean;
-
-// START SNIPPET: example
-public interface CustomerServiceNoAnnotations {
-
-    Customer getCustomer(String id);
-
-}
-// END SNIPPET: example
diff --git a/components-starter/camel-cxf-rest-starter/src/test/java/org/apache/camel/component/cxf/jaxrs/testbean/CustomerServiceResource.java b/components-starter/camel-cxf-rest-starter/src/test/java/org/apache/camel/component/cxf/jaxrs/testbean/CustomerServiceResource.java
deleted file mode 100644
index e36313746a1..00000000000
--- a/components-starter/camel-cxf-rest-starter/src/test/java/org/apache/camel/component/cxf/jaxrs/testbean/CustomerServiceResource.java
+++ /dev/null
@@ -1,51 +0,0 @@
-/*
- * 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.camel.component.cxf.jaxrs.testbean;
-
-import javax.ws.rs.Consumes;
-import javax.ws.rs.GET;
-import javax.ws.rs.PUT;
-import javax.ws.rs.Path;
-import javax.ws.rs.PathParam;
-import javax.ws.rs.Produces;
-import javax.ws.rs.core.Response;
-
-// START SNIPPET: example
-@Path("/customerservice/")
-public interface CustomerServiceResource {
-
-    @GET
-    @Path("/customers/{id}/")
-    Customer getCustomer(@PathParam("id") String id);
-
-    @PUT
-    @Path("/customers/")
-    Response updateCustomer(Customer customer);
-
-    @Path("/{id}")
-    @PUT()
-    @Consumes({
-            "application/xml", "text/plain",
-            "application/json" })
-    @Produces({
-            "application/xml", "text/plain",
-            "application/json" })
-    Object invoke(
-            @PathParam("id") String id,
-            String payload);
-}
-// END SNIPPET: example
diff --git a/components-starter/camel-cxf-rest-starter/src/test/java/org/apache/camel/component/cxf/jaxrs/testbean/EchoService.java b/components-starter/camel-cxf-rest-starter/src/test/java/org/apache/camel/component/cxf/jaxrs/testbean/EchoService.java
deleted file mode 100644
index abba335cd10..00000000000
--- a/components-starter/camel-cxf-rest-starter/src/test/java/org/apache/camel/component/cxf/jaxrs/testbean/EchoService.java
+++ /dev/null
@@ -1,41 +0,0 @@
-/*
- * 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.camel.component.cxf.jaxrs.testbean;
-
-import javax.ws.rs.POST;
-import javax.ws.rs.Path;
-import javax.ws.rs.core.Context;
-import javax.ws.rs.core.Cookie;
-import javax.ws.rs.core.HttpHeaders;
-import javax.ws.rs.core.NewCookie;
-import javax.ws.rs.core.Response;
-
-@Path("/echoservice/")
-public class EchoService {
-    @Context
-    private HttpHeaders headers;
-
-    @POST
-    @Path("/echo/")
-    public Response echo(String string) {
-        Cookie fooCookie = headers.getCookies().get("foo");
-        if (fooCookie != null && "bar".equals(fooCookie.getValue())) {
-            return Response.ok("Old " + string).build();
-        }
-        return Response.ok("New " + string).cookie(new NewCookie("foo", "bar", "/", null, 1, null, -1, false)).build();
-    }
-}
diff --git a/components-starter/camel-cxf-rest-starter/src/test/java/org/apache/camel/component/cxf/jaxrs/testbean/Order.java b/components-starter/camel-cxf-rest-starter/src/test/java/org/apache/camel/component/cxf/jaxrs/testbean/Order.java
deleted file mode 100644
index 0ac90a8e5bc..00000000000
--- a/components-starter/camel-cxf-rest-starter/src/test/java/org/apache/camel/component/cxf/jaxrs/testbean/Order.java
+++ /dev/null
@@ -1,67 +0,0 @@
-/*
- * 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.camel.component.cxf.jaxrs.testbean;
-
-import java.util.HashMap;
-import java.util.Map;
-
-import javax.ws.rs.GET;
-import javax.ws.rs.Path;
-import javax.ws.rs.PathParam;
-import javax.xml.bind.annotation.XmlRootElement;
-
-@XmlRootElement(name = "Order")
-public class Order {
-    private long id;
-    private String description;
-    private Map<Long, Product> products = new HashMap<>();
-
-    public Order() {
-        init();
-    }
-
-    public long getId() {
-        return id;
-    }
-
-    public void setId(long id) {
-        this.id = id;
-    }
-
-    public String getDescription() {
-        return description;
-    }
-
-    public void setDescription(String d) {
-        this.description = d;
-    }
-
-    @GET
-    @Path("products/{productId}/")
-    public Product getProduct(@PathParam("productId") int productId) {
-        Product p = products.get(Long.valueOf(productId));
-        return p;
-    }
-
-    final void init() {
-        Product p = new Product();
-        p.setId(323);
-        p.setDescription("product 323");
-        products.put(p.getId(), p);
-    }
-
-}
diff --git a/components-starter/camel-cxf-rest-starter/src/test/java/org/apache/camel/component/cxf/jaxrs/testbean/Product.java b/components-starter/camel-cxf-rest-starter/src/test/java/org/apache/camel/component/cxf/jaxrs/testbean/Product.java
deleted file mode 100644
index d363af1055e..00000000000
--- a/components-starter/camel-cxf-rest-starter/src/test/java/org/apache/camel/component/cxf/jaxrs/testbean/Product.java
+++ /dev/null
@@ -1,41 +0,0 @@
-/*
- * 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.camel.component.cxf.jaxrs.testbean;
-
-import javax.xml.bind.annotation.XmlRootElement;
-
-@XmlRootElement(name = "Product")
-public class Product {
-    private long id;
-    private String description;
-
-    public long getId() {
-        return id;
-    }
-
-    public void setId(long id) {
-        this.id = id;
-    }
-
-    public String getDescription() {
-        return description;
-    }
-
-    public void setDescription(String d) {
-        this.description = d;
-    }
-}
diff --git a/components-starter/camel-cxf-rest-starter/src/test/java/org/apache/camel/component/cxf/jaxrs/testbean/ServiceUtil.java b/components-starter/camel-cxf-rest-starter/src/test/java/org/apache/camel/component/cxf/jaxrs/testbean/ServiceUtil.java
deleted file mode 100644
index 0e2a1b85f45..00000000000
--- a/components-starter/camel-cxf-rest-starter/src/test/java/org/apache/camel/component/cxf/jaxrs/testbean/ServiceUtil.java
+++ /dev/null
@@ -1,24 +0,0 @@
-/*
- * 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.camel.component.cxf.jaxrs.testbean;
-
-public class ServiceUtil {
-    public String invoke(String id, String payload) {
-        return id + payload;
-    }
-
-}
diff --git a/components-starter/camel-cxf-rest-starter/src/test/java/org/apache/camel/component/cxf/rest/springboot/CxfRsConsumerWithBeanTest.java b/components-starter/camel-cxf-rest-starter/src/test/java/org/apache/camel/component/cxf/rest/springboot/CxfRsConsumerWithBeanTest.java
index 5fd7a59f3ff..0609dd292a6 100644
--- a/components-starter/camel-cxf-rest-starter/src/test/java/org/apache/camel/component/cxf/rest/springboot/CxfRsConsumerWithBeanTest.java
+++ b/components-starter/camel-cxf-rest-starter/src/test/java/org/apache/camel/component/cxf/rest/springboot/CxfRsConsumerWithBeanTest.java
@@ -18,6 +18,7 @@ package org.apache.camel.component.cxf.rest.springboot;
 
 
 import org.apache.camel.builder.RouteBuilder;
+import org.apache.camel.component.cxf.common.CXFTestSupport;
 import org.apache.camel.component.cxf.jaxrs.testbean.ServiceUtil;
 import org.apache.camel.spring.boot.CamelAutoConfiguration;
 
@@ -55,6 +56,7 @@ import org.apache.http.util.EntityUtils;
 )
 public class CxfRsConsumerWithBeanTest {
 
+    private int port = CXFTestSupport.getPort1();
     private static final String CXT = "/CxfRsConsumerWithBeanTest";
     private static final String CXF_RS_ENDPOINT_URI
             = "cxfrs://" + CXT
@@ -63,20 +65,12 @@ public class CxfRsConsumerWithBeanTest {
             = "cxfrs://" + CXT
               + "/rest2?resourceClasses=org.apache.camel.component.cxf.jaxrs.testbean.CustomerServiceResource";
 
-    @Bean("service")
-    protected ServiceUtil bindToRegistry() {
-        return new ServiceUtil();
-    }
     
-    @Bean
-    public ServletWebServerFactory servletWebServerFactory() {
-        return new UndertowServletWebServerFactory();
-    }
     
     @Test
     public void testPutConsumer() throws Exception {
-        sendPutRequest("http://localhost:8080/services" + CXT + "/rest/customerservice/c20");
-        sendPutRequest("http://localhost:8080/services" + CXT + "/rest2/customerservice/c20");
+        sendPutRequest("http://localhost:" + port + "/services" + CXT + "/rest/customerservice/c20");
+        sendPutRequest("http://localhost:" + port + "/services" + CXT + "/rest2/customerservice/c20");
     }
 
     private void sendPutRequest(String uri) throws Exception {
@@ -102,6 +96,16 @@ public class CxfRsConsumerWithBeanTest {
     @Configuration
     public class TestConfiguration {
 
+        @Bean("service")
+        public ServiceUtil bindToRegistry() {
+            return new ServiceUtil();
+        }
+        
+        @Bean
+        public ServletWebServerFactory servletWebServerFactory() {
+            return new UndertowServletWebServerFactory(port);
+        }
+        
         @Bean
         public RouteBuilder routeBuilder() {
             return new RouteBuilder() {
diff --git a/components-starter/camel-cxf-rest-starter/src/test/java/org/apache/camel/component/cxf/rest/springboot/CxfRsProducerSessionTest.java b/components-starter/camel-cxf-rest-starter/src/test/java/org/apache/camel/component/cxf/rest/springboot/CxfRsProducerSessionTest.java
index e01db825e4b..591b310bb2c 100644
--- a/components-starter/camel-cxf-rest-starter/src/test/java/org/apache/camel/component/cxf/rest/springboot/CxfRsProducerSessionTest.java
+++ b/components-starter/camel-cxf-rest-starter/src/test/java/org/apache/camel/component/cxf/rest/springboot/CxfRsProducerSessionTest.java
@@ -22,6 +22,7 @@ import org.apache.camel.ExchangePattern;
 import org.apache.camel.Message;
 import org.apache.camel.Processor;
 import org.apache.camel.ProducerTemplate;
+import org.apache.camel.component.cxf.common.CXFTestSupport;
 import org.apache.camel.component.cxf.common.message.CxfConstants;
 import org.apache.camel.spring.boot.CamelAutoConfiguration;
 
@@ -56,9 +57,11 @@ import org.apache.cxf.spring.boot.autoconfigure.CxfAutoConfiguration;
 })
 public class CxfRsProducerSessionTest {
 
+    static int port = CXFTestSupport.getPort1();
+    
     @Bean
     public ServletWebServerFactory servletWebServerFactory() {
-        return new UndertowServletWebServerFactory();
+        return new UndertowServletWebServerFactory(port);
     }
     
     @Test
diff --git a/components-starter/camel-cxf-rest-starter/src/test/java/org/apache/camel/component/cxf/rest/springboot/CxfRsStreamCacheTest.java b/components-starter/camel-cxf-rest-starter/src/test/java/org/apache/camel/component/cxf/rest/springboot/CxfRsStreamCacheTest.java
index b0d30fa5fdf..f034b220d69 100644
--- a/components-starter/camel-cxf-rest-starter/src/test/java/org/apache/camel/component/cxf/rest/springboot/CxfRsStreamCacheTest.java
+++ b/components-starter/camel-cxf-rest-starter/src/test/java/org/apache/camel/component/cxf/rest/springboot/CxfRsStreamCacheTest.java
@@ -23,6 +23,7 @@ import org.apache.camel.Exchange;
 import org.apache.camel.ExtendedExchange;
 import org.apache.camel.ProducerTemplate;
 import org.apache.camel.builder.RouteBuilder;
+import org.apache.camel.component.cxf.common.CXFTestSupport;
 import org.apache.camel.component.cxf.jaxrs.testbean.Customer;
 import org.apache.camel.component.mock.MockEndpoint;
 import org.apache.camel.converter.stream.CachedOutputStream;
@@ -65,9 +66,11 @@ import org.apache.http.util.EntityUtils;
 )
 public class CxfRsStreamCacheTest {
 
+    private static int port = CXFTestSupport.getPort1();
+    
     private static final String PUT_REQUEST = "<Customer><name>Mary</name><id>123</id></Customer>";
     private static final String CONTEXT = "/CxfRsStreamCacheTest";
-    private static final String CXT = "8080/services" + CONTEXT;
+    private static final String CXT = port + "/services" + CONTEXT;
     private static final String RESPONSE = "<pong xmlns=\"test/service\"/>";
 
     private String cxfRsEndpointUri = "cxfrs://" + CONTEXT + "?synchronous=" + isSynchronous()
@@ -84,7 +87,7 @@ public class CxfRsStreamCacheTest {
     
     @Bean
     public ServletWebServerFactory servletWebServerFactory() {
-        return new UndertowServletWebServerFactory();
+        return new UndertowServletWebServerFactory(port);
     }
     
     
diff --git a/components-starter/camel-cxf-rest-starter/src/test/resources/routes/CxfRsSpringProducerSession.xml b/components-starter/camel-cxf-rest-starter/src/test/resources/routes/CxfRsSpringProducerSession.xml
index db00a27e1c8..b671b6f6c21 100644
--- a/components-starter/camel-cxf-rest-starter/src/test/resources/routes/CxfRsSpringProducerSession.xml
+++ b/components-starter/camel-cxf-rest-starter/src/test/resources/routes/CxfRsSpringProducerSession.xml
@@ -41,11 +41,11 @@
   
   <bean id="echoService" class="org.apache.camel.component.cxf.jaxrs.testbean.EchoService" />
 
-  <cxf:rsClient id="rsClientProxy" address="http://localhost:8080/services/CxfRsProducerSessionTest/"
+  <cxf:rsClient id="rsClientProxy" address="http://localhost:${CXFTestSupport.port1}/services/CxfRsProducerSessionTest/"
     serviceClass="org.apache.camel.component.cxf.jaxrs.testbean.EchoService"
     loggingFeatureEnabled="true" />
    
-  <cxf:rsClient id="rsClientHttp" address="http://localhost:8080/services/CxfRsProducerSessionTest/"/>
+  <cxf:rsClient id="rsClientHttp" address="http://localhost:${CXFTestSupport.port1}/services/CxfRsProducerSessionTest/"/>
 
 
   <bean id="instanceCookieHandler" class="org.apache.camel.http.base.cookie.InstanceCookieHandler"/>


[camel-spring-boot] 04/07: add CxfRsGlobalSslProducerTest

Posted by ff...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

ffang pushed a commit to branch more-rest-test-new
in repository https://gitbox.apache.org/repos/asf/camel-spring-boot.git

commit 5ae525d086749666bd5701362b938fc130c48c4d
Author: Freeman Fang <fr...@gmail.com>
AuthorDate: Wed Jan 18 15:14:13 2023 -0500

    add CxfRsGlobalSslProducerTest
    
    (cherry picked from commit 43a46af853850b6d32750fb71928073a0c7b8e3e)
---
 .../springboot/CxfRsGlobalSslProducerTest.java     | 257 +++++++++++++++++++++
 1 file changed, 257 insertions(+)

diff --git a/components-starter/camel-cxf-rest-starter/src/test/java/org/apache/camel/component/cxf/rest/springboot/CxfRsGlobalSslProducerTest.java b/components-starter/camel-cxf-rest-starter/src/test/java/org/apache/camel/component/cxf/rest/springboot/CxfRsGlobalSslProducerTest.java
new file mode 100644
index 00000000000..3a0e4ff6c04
--- /dev/null
+++ b/components-starter/camel-cxf-rest-starter/src/test/java/org/apache/camel/component/cxf/rest/springboot/CxfRsGlobalSslProducerTest.java
@@ -0,0 +1,257 @@
+/*
+ * 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.camel.component.cxf.rest.springboot;
+
+
+import java.net.InetAddress;
+import java.net.UnknownHostException;
+import java.util.ArrayList;
+import java.util.List;
+
+import org.apache.camel.CamelContext;
+import org.apache.camel.Exchange;
+import org.apache.camel.ExchangePattern;
+import org.apache.camel.Message;
+import org.apache.camel.Processor;
+import org.apache.camel.ProducerTemplate;
+import org.apache.camel.SSLContextParametersAware;
+import org.apache.camel.builder.RouteBuilder;
+import org.apache.camel.component.cxf.common.CXFTestSupport;
+import org.apache.camel.component.cxf.common.message.CxfConstants;
+import org.apache.camel.component.cxf.jaxrs.testbean.Customer;
+import org.apache.camel.component.cxf.spring.jaxrs.SpringJAXRSClientFactoryBean;
+import org.apache.camel.spring.boot.CamelAutoConfiguration;
+import org.apache.camel.spring.boot.CamelContextConfiguration;
+import org.apache.camel.support.jsse.KeyStoreParameters;
+import org.apache.camel.support.jsse.SSLContextParameters;
+import org.apache.camel.support.jsse.TrustManagersParameters;
+
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.boot.test.context.SpringBootTest;
+import org.springframework.boot.web.embedded.undertow.UndertowServletWebServerFactory;
+import org.springframework.boot.web.server.CertificateFileSslStoreProvider;
+import org.springframework.boot.web.server.Ssl;
+import org.springframework.boot.web.server.Ssl.ClientAuth;
+import org.springframework.boot.web.servlet.server.ServletWebServerFactory;
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.Configuration;
+import org.springframework.test.annotation.DirtiesContext;
+import org.springframework.test.annotation.DirtiesContext.ClassMode;
+import org.apache.camel.test.spring.junit5.CamelSpringBootTest;
+import org.apache.cxf.endpoint.Server;
+import org.apache.cxf.jaxrs.AbstractJAXRSFactoryBean;
+import org.apache.cxf.jaxrs.JAXRSServerFactoryBean;
+import org.apache.cxf.spring.boot.autoconfigure.CxfAutoConfiguration;
+import org.apache.cxf.transport.https.httpclient.DefaultHostnameVerifier;
+
+
+
+@DirtiesContext(classMode = ClassMode.AFTER_EACH_TEST_METHOD)
+@CamelSpringBootTest
+@SpringBootTest(
+    classes = {
+        CamelAutoConfiguration.class,
+        CxfRsGlobalSslProducerTest.class,
+        CxfRsGlobalSslProducerTest.TestConfiguration.class,
+        CxfAutoConfiguration.class
+    }, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT
+)
+public class CxfRsGlobalSslProducerTest {
+
+    static int port = CXFTestSupport.getSslPort();
+    
+    
+    @Autowired
+    protected ProducerTemplate template;
+    
+    @BeforeEach
+    public void setUp() throws Exception {
+        JAXRSServerFactoryBean sfb = new JAXRSServerFactoryBean();
+        List<Object> serviceBeans = new ArrayList<Object>();
+        serviceBeans.add(new org.apache.camel.component.cxf.jaxrs.testbean.CustomerService());
+        sfb.setServiceBeans(serviceBeans);
+        sfb.setAddress("/CxfRsProducerTest/");
+        sfb.setStaticSubresourceResolution(true);
+        Server server = sfb.create();
+        server.start();
+    }
+
+    
+    protected void setupDestinationURL(Message inMessage) {
+        // do nothing here
+    }
+    
+    @Test
+    public void testCorrectTrustStore() {
+        Exchange exchange = template.send("direct://trust", new MyProcessor());
+
+        // get the response message 
+        Customer response = (Customer) exchange.getMessage().getBody();
+
+        assertNotNull(response, "The response should not be null");
+        assertEquals("123", String.valueOf(response.getId()), "Get a wrong customer id");
+        assertEquals("John", response.getName(), "Get a wrong customer name");
+        assertEquals(200, exchange.getMessage().getHeader(Exchange.HTTP_RESPONSE_CODE), "Get a wrong response code");
+        assertEquals("value", exchange.getMessage().getHeader("key"), "Get a wrong header value");
+    }
+
+    @Test
+    public void testNoTrustStore() {
+        Exchange exchange = template.send("direct://noTrust", new MyProcessor());
+        assertTrue(exchange.isFailed());
+        Exception e = exchange.getException();
+        assertEquals("javax.net.ssl.SSLHandshakeException", e.getCause().getClass().getCanonicalName());
+    }
+
+    @Test
+    public void testWrongTrustStore() {
+        Exchange exchange = template.send("direct://wrongTrust", new MyProcessor());
+        assertTrue(exchange.isFailed());
+        Exception e = exchange.getException();
+        assertEquals("javax.net.ssl.SSLHandshakeException", e.getCause().getClass().getCanonicalName());
+    }
+
+    private class MyProcessor implements Processor {
+
+        @Override
+        public void process(Exchange exchange) throws Exception {
+            exchange.setPattern(ExchangePattern.InOut);
+            Message inMessage = exchange.getIn();
+            setupDestinationURL(inMessage);
+            // using the http central client API
+            inMessage.setHeader(CxfConstants.CAMEL_CXF_RS_USING_HTTP_API, Boolean.TRUE);
+            // set the Http method
+            inMessage.setHeader(Exchange.HTTP_METHOD, "GET");
+            // set the relative path
+            inMessage.setHeader(Exchange.HTTP_PATH, "/customerservice/customers/123");
+            // Specify the response class , cxfrs will use InputStream as the response object type
+            inMessage.setHeader(CxfConstants.CAMEL_CXF_RS_RESPONSE_CLASS, Customer.class);
+            // set a customer header
+            inMessage.setHeader("key", "value");
+            // since we use the Get method, so we don't need to set the message body
+            inMessage.setBody(null);
+        }
+    }
+    
+    // *************************************
+    // Config
+    // *************************************
+
+    @Configuration
+    public class TestConfiguration {
+
+        
+        
+        /*
+         * This is the way how to configure TLS/SSL with Bean 
+         */
+        @Bean
+        public ServletWebServerFactory servletWebServerFactory() throws UnknownHostException {
+            UndertowServletWebServerFactory undertowWebServerFactory 
+                = new UndertowServletWebServerFactory();
+            Ssl ssl = new Ssl();
+            ssl.setClientAuth(ClientAuth.NONE);
+            ssl.setKeyPassword("changeit");
+            ssl.setKeyStoreType("JKS");
+            ssl.setKeyStore("classpath:ssl/keystore-server.jks");
+            ssl.setKeyStorePassword("changeit");
+            SslBuilderCustomizer sslBuilderCustomizer = 
+                new SslBuilderCustomizer(port, InetAddress.getByName("localhost"),
+                                         ssl, CertificateFileSslStoreProvider.from(ssl));
+            undertowWebServerFactory.addBuilderCustomizers(sslBuilderCustomizer);
+            return undertowWebServerFactory;
+        }
+        
+        @Bean
+        DefaultHostnameVerifier defaultHostnameVerifier() {
+            return new DefaultHostnameVerifier();
+        }
+        
+        @Bean
+        SSLContextParameters mySslContext() {
+            SSLContextParameters sslContext = new SSLContextParameters();
+            TrustManagersParameters trustManager = new TrustManagersParameters();
+            KeyStoreParameters keyStore = new KeyStoreParameters();
+            keyStore.setType("JKS");
+            keyStore.setPassword("changeit");
+            keyStore.setResource("/ssl/truststore-client.jks");
+            trustManager.setKeyStore(keyStore);
+            sslContext.setTrustManagers(trustManager);
+            return sslContext;
+        }
+        
+        @Bean
+        SSLContextParameters wrongSslContext() {
+            SSLContextParameters sslContext = new SSLContextParameters();
+            TrustManagersParameters trustManager = new TrustManagersParameters();
+            KeyStoreParameters keyStore = new KeyStoreParameters();
+            keyStore.setType("JKS");
+            keyStore.setPassword("changeit");
+            keyStore.setResource("/ssl/truststore-wrong.jks");
+            trustManager.setKeyStore(keyStore);
+            sslContext.setTrustManagers(trustManager);
+            return sslContext;
+        }
+        
+        
+        @Bean
+        AbstractJAXRSFactoryBean serviceEndpoint(SSLContextParameters mySslContext, DefaultHostnameVerifier defaultHostnameVerifier) {
+            AbstractJAXRSFactoryBean afb = new SpringJAXRSClientFactoryBean();
+            afb.setAddress("https://localhost:" + port 
+                                   + "/services/CxfRsProducerTest/");
+            return afb;
+        }
+        
+        @Bean
+        CamelContextConfiguration contextConfiguration() {
+            return new CamelContextConfiguration() {
+                @Override
+                public void beforeApplicationStart(CamelContext context) {
+                    SSLContextParameters parameters = context.getRegistry().lookupByNameAndType("mySslContext", SSLContextParameters.class);
+                    ((SSLContextParametersAware) context.getComponent("cxfrs")).setUseGlobalSslContextParameters(true);
+                    context.setSSLContextParameters(parameters);
+                }
+
+                @Override
+                public void afterApplicationStart(CamelContext camelContext) {
+                    
+
+                }
+            };
+        }
+        
+        @Bean
+        public RouteBuilder routeBuilder() {
+            return new RouteBuilder() {
+                @Override
+                public void configure() {
+                    from("direct://trust").to("cxfrs:bean:serviceEndpoint?hostnameVerifier=#defaultHostnameVerifier&synchronous=true");
+                    from("direct://wrongTrust").to("cxfrs:bean:serviceEndpoint?sslContextParameters=#wrongSslContext&hostnameVerifier=#defaultHostnameVerifier&synchronous=true");
+                    from("direct://noTrust").to("cxfrs:bean:serviceEndpoint?sslContextParameters=#wrongSslContext&hostnameVerifier=#defaultHostnameVerifier&synchronous=true");
+                }
+            };
+        }
+    }
+    
+}


[camel-spring-boot] 05/07: add CxfRsSslAsyncProducerTest

Posted by ff...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

ffang pushed a commit to branch more-rest-test-new
in repository https://gitbox.apache.org/repos/asf/camel-spring-boot.git

commit acdcd1f5bef7c9051c4afadf34647ed67dc99f92
Author: Freeman Fang <fr...@gmail.com>
AuthorDate: Wed Jan 18 16:36:00 2023 -0500

    add CxfRsSslAsyncProducerTest
    
    (cherry picked from commit 1702841dd0774b852a1d3a9aa9281f58639c6eab)
---
 .../rest/springboot/CxfRsSslAsyncProducerTest.java | 261 +++++++++++++++++++++
 1 file changed, 261 insertions(+)

diff --git a/components-starter/camel-cxf-rest-starter/src/test/java/org/apache/camel/component/cxf/rest/springboot/CxfRsSslAsyncProducerTest.java b/components-starter/camel-cxf-rest-starter/src/test/java/org/apache/camel/component/cxf/rest/springboot/CxfRsSslAsyncProducerTest.java
new file mode 100644
index 00000000000..dbcf0247d2c
--- /dev/null
+++ b/components-starter/camel-cxf-rest-starter/src/test/java/org/apache/camel/component/cxf/rest/springboot/CxfRsSslAsyncProducerTest.java
@@ -0,0 +1,261 @@
+/*
+ * 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.camel.component.cxf.rest.springboot;
+
+
+import java.net.InetAddress;
+import java.net.UnknownHostException;
+import java.util.ArrayList;
+import java.util.List;
+
+
+
+import org.apache.camel.Exchange;
+import org.apache.camel.ExchangePattern;
+import org.apache.camel.Message;
+import org.apache.camel.Processor;
+import org.apache.camel.ProducerTemplate;
+import org.apache.camel.builder.RouteBuilder;
+import org.apache.camel.component.cxf.common.CXFTestSupport;
+import org.apache.camel.component.cxf.common.message.CxfConstants;
+import org.apache.camel.component.cxf.jaxrs.testbean.Customer;
+import org.apache.camel.component.cxf.spring.jaxrs.SpringJAXRSClientFactoryBean;
+import org.apache.camel.spring.boot.CamelAutoConfiguration;
+import org.apache.camel.support.jsse.KeyStoreParameters;
+import org.apache.camel.support.jsse.SSLContextParameters;
+import org.apache.camel.support.jsse.TrustManagersParameters;
+
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.boot.test.context.SpringBootTest;
+import org.springframework.boot.web.embedded.undertow.UndertowServletWebServerFactory;
+import org.springframework.boot.web.server.CertificateFileSslStoreProvider;
+import org.springframework.boot.web.server.Ssl;
+import org.springframework.boot.web.server.Ssl.ClientAuth;
+import org.springframework.boot.web.servlet.server.ServletWebServerFactory;
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.Configuration;
+import org.springframework.test.annotation.DirtiesContext;
+import org.springframework.test.annotation.DirtiesContext.ClassMode;
+import org.apache.camel.test.spring.junit5.CamelSpringBootTest;
+import org.apache.cxf.endpoint.Server;
+import org.apache.cxf.jaxrs.AbstractJAXRSFactoryBean;
+import org.apache.cxf.jaxrs.JAXRSServerFactoryBean;
+import org.apache.cxf.spring.boot.autoconfigure.CxfAutoConfiguration;
+import org.apache.cxf.transport.https.httpclient.DefaultHostnameVerifier;
+
+
+
+@DirtiesContext(classMode = ClassMode.AFTER_EACH_TEST_METHOD)
+@CamelSpringBootTest
+@SpringBootTest(
+    classes = {
+        CamelAutoConfiguration.class,
+        CxfRsSslAsyncProducerTest.class,
+        CxfRsSslAsyncProducerTest.TestConfiguration.class,
+        CxfAutoConfiguration.class
+    }, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT
+)
+public class CxfRsSslAsyncProducerTest {
+
+    static int port = CXFTestSupport.getSslPort();
+    
+    
+    @Autowired
+    protected ProducerTemplate template;
+    
+    @BeforeEach
+    public void setUp() throws Exception {
+        JAXRSServerFactoryBean sfb = new JAXRSServerFactoryBean();
+        List<Object> serviceBeans = new ArrayList<Object>();
+        serviceBeans.add(new org.apache.camel.component.cxf.jaxrs.testbean.CustomerService());
+        sfb.setServiceBeans(serviceBeans);
+        sfb.setAddress("/CxfRsProducerTest/");
+        sfb.setStaticSubresourceResolution(true);
+        Server server = sfb.create();
+        server.start();
+    }
+
+    
+    protected void setupDestinationURL(Message inMessage) {
+        // do nothing here
+    }
+    
+    @Test
+    public void testCorrectTrustStore() {
+        Exchange exchange = template.send("direct://trust", new MyProcessor());
+
+        // get the response message 
+        Customer response = (Customer) exchange.getMessage().getBody();
+
+        assertNotNull(response, "The response should not be null");
+        assertEquals("123", String.valueOf(response.getId()), "Get a wrong customer id");
+        assertEquals("John", response.getName(), "Get a wrong customer name");
+        assertEquals(200, exchange.getMessage().getHeader(Exchange.HTTP_RESPONSE_CODE), "Get a wrong response code");
+        assertEquals("value", exchange.getMessage().getHeader("key"), "Get a wrong header value");
+    }
+
+    @Test
+    public void testNoTrustStore() {
+        Exchange exchange = template.send("direct://noTrust", new MyProcessor());
+        assertTrue(exchange.isFailed());
+        Exception e = exchange.getException();
+        assertEquals("javax.net.ssl.SSLHandshakeException", e.getCause().getClass().getCanonicalName());
+    }
+
+    @Test
+    public void testWrongTrustStore() {
+        Exchange exchange = template.send("direct://wrongTrust", new MyProcessor());
+        assertTrue(exchange.isFailed());
+        Exception e = exchange.getException();
+        assertEquals("javax.net.ssl.SSLHandshakeException", e.getCause().getClass().getCanonicalName());
+    }
+
+    private class MyProcessor implements Processor {
+
+        @Override
+        public void process(Exchange exchange) throws Exception {
+            exchange.setPattern(ExchangePattern.InOut);
+            Message inMessage = exchange.getIn();
+            setupDestinationURL(inMessage);
+            // using the http central client API
+            inMessage.setHeader(CxfConstants.CAMEL_CXF_RS_USING_HTTP_API, Boolean.TRUE);
+            // set the Http method
+            inMessage.setHeader(Exchange.HTTP_METHOD, "GET");
+            // set the relative path
+            inMessage.setHeader(Exchange.HTTP_PATH, "/customerservice/customers/123");
+            // Specify the response class , cxfrs will use InputStream as the response object type
+            inMessage.setHeader(CxfConstants.CAMEL_CXF_RS_RESPONSE_CLASS, Customer.class);
+            // set a customer header
+            inMessage.setHeader("key", "value");
+            // since we use the Get method, so we don't need to set the message body
+            inMessage.setBody(null);
+        }
+    }
+    
+    // *************************************
+    // Config
+    // *************************************
+
+    @Configuration
+    public class TestConfiguration {
+
+        
+        
+        /*
+         * This is the way how to configure TLS/SSL with Bean 
+         */
+        @Bean
+        public ServletWebServerFactory servletWebServerFactory() throws UnknownHostException {
+            UndertowServletWebServerFactory undertowWebServerFactory 
+                = new UndertowServletWebServerFactory();
+            Ssl ssl = new Ssl();
+            ssl.setClientAuth(ClientAuth.NONE);
+            ssl.setKeyPassword("changeit");
+            ssl.setKeyStoreType("JKS");
+            ssl.setKeyStore("classpath:ssl/keystore-server.jks");
+            ssl.setKeyStorePassword("changeit");
+            SslBuilderCustomizer sslBuilderCustomizer = 
+                new SslBuilderCustomizer(port, InetAddress.getByName("localhost"),
+                                         ssl, CertificateFileSslStoreProvider.from(ssl));
+            undertowWebServerFactory.addBuilderCustomizers(sslBuilderCustomizer);
+            return undertowWebServerFactory;
+        }
+        
+        @Bean
+        DefaultHostnameVerifier defaultHostnameVerifier() {
+            return new DefaultHostnameVerifier();
+        }
+        
+        @Bean
+        SSLContextParameters mySslContext() {
+            SSLContextParameters sslContext = new SSLContextParameters();
+            TrustManagersParameters trustManager = new TrustManagersParameters();
+            KeyStoreParameters keyStore = new KeyStoreParameters();
+            keyStore.setType("JKS");
+            keyStore.setPassword("changeit");
+            keyStore.setResource("/ssl/truststore-client.jks");
+            trustManager.setKeyStore(keyStore);
+            sslContext.setTrustManagers(trustManager);
+            return sslContext;
+        }
+        
+        @Bean
+        SSLContextParameters wrongSslContext() {
+            SSLContextParameters sslContext = new SSLContextParameters();
+            TrustManagersParameters trustManager = new TrustManagersParameters();
+            KeyStoreParameters keyStore = new KeyStoreParameters();
+            keyStore.setType("JKS");
+            keyStore.setPassword("changeit");
+            keyStore.setResource("/ssl/truststore-wrong.jks");
+            trustManager.setKeyStore(keyStore);
+            sslContext.setTrustManagers(trustManager);
+            return sslContext;
+        }
+        
+        
+        @Bean
+        AbstractJAXRSFactoryBean serviceEndpoint(SSLContextParameters mySslContext, DefaultHostnameVerifier defaultHostnameVerifier) {
+            AbstractJAXRSFactoryBean afb = new SpringJAXRSClientFactoryBean();
+            afb.setAddress("https://localhost:" + port 
+                                   + "/services/CxfRsProducerTest/");
+            return afb;
+        }
+        
+        /*@Bean
+        CxfRsEndpoint serviceEndpointWithWrongTrust(SSLContextParameters wrongSslContext, DefaultHostnameVerifier defaultHostnameVerifier) {
+            
+            CxfRsEndpoint cxfEndpoint = new CxfRsEndpoint();
+            cxfEndpoint.setAddress("https://localhost:" + port 
+                                   + "/services/CxfRsProducerTest/");
+            cxfEndpoint.setHostnameVerifier(defaultHostnameVerifier);
+            cxfEndpoint.setSslContextParameters(wrongSslContext);
+            cxfEndpoint.setSynchronous(true);
+            return cxfEndpoint;
+        }
+        
+        @Bean
+        CxfRsEndpoint serviceEndpointWithNoTrust(DefaultHostnameVerifier defaultHostnameVerifier) {
+            
+            CxfRsEndpoint cxfEndpoint = new CxfRsEndpoint();
+            cxfEndpoint.setAddress("https://localhost:" + port 
+                                   + "/services/CxfRsProducerTest/");
+            cxfEndpoint.setHostnameVerifier(defaultHostnameVerifier);
+            cxfEndpoint.setSynchronous(true);
+            return cxfEndpoint;
+        }*/
+        
+        @Bean
+        public RouteBuilder routeBuilder() {
+            return new RouteBuilder() {
+                @Override
+                public void configure() {
+                    from("direct://trust").to("cxfrs:bean:serviceEndpoint?sslContextParameters=#mySslContext&hostnameVerifier=#defaultHostnameVerifier");
+                    from("direct://wrongTrust").to("cxfrs:bean:serviceEndpoint?sslContextParameters=#wrongSslContext&hostnameVerifier=#defaultHostnameVerifier");
+                    from("direct://noTrust").to("cxfrs:bean:serviceEndpoint?hostnameVerifier=#defaultHostnameVerifier");
+                }
+            };
+        }
+    }
+    
+}