Apache CXF实战

转载于:http://blog.csdn.net/kongxx/article/details/7525476

 

Apache的CXF现在几乎成了Java领域构建Web Service的首选类库,并且它也确实简单易用,下面就通过几篇系列文章做一下简单介绍。

当然首先想到的当然还是那个Hello World示例。这个系列文章中用到的例子都是基于Maven构建的工程,下面是我的pom.xml文件内容

  1. <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  2. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  3. <modelVersion>4.0.0</modelVersion>
  4. <groupId>com.googlecode.garbagecan.cxfstudy</groupId>
  5. <artifactId>cxfstudy</artifactId>
  6. <packaging>war</packaging>
  7. <version>1.0-SNAPSHOT</version>
  8. <name>cxfstudy Maven Webapp</name>
  9. <url>http://maven.apache.org</url>
  10. <properties>
  11. <cxf.version>2.2.7</cxf.version>
  12. </properties>
  13. <dependencies>
  14. <dependency>
  15. <groupId>org.apache.cxf</groupId>
  16. <artifactId>cxf-rt-frontend-jaxws</artifactId>
  17. <version>${cxf.version}</version>
  18. </dependency>
  19. <dependency>
  20. <groupId>org.apache.cxf</groupId>
  21. <artifactId>cxf-rt-transports-http</artifactId>
  22. <version>${cxf.version}</version>
  23. </dependency>
  24. <dependency>
  25. <groupId>org.apache.cxf</groupId>
  26. <artifactId>cxf-rt-transports-http-jetty</artifactId>
  27. <version>${cxf.version}</version>
  28. </dependency>
  29. <dependency>
  30. <groupId>org.apache.cxf</groupId>
  31. <artifactId>cxf-rt-ws-security</artifactId>
  32. <version>${cxf.version}</version>
  33. </dependency>
  34. <dependency>
  35. <groupId>org.apache.cxf</groupId>
  36. <artifactId>cxf-rt-ws-policy</artifactId>
  37. <version>${cxf.version}</version>
  38. </dependency>
  39. <dependency>
  40. <groupId>org.apache.cxf</groupId>
  41. <artifactId>cxf-bundle-jaxrs</artifactId>
  42. <version>${cxf.version}</version>
  43. </dependency>
  44. <dependency>
  45. <groupId>javax.ws.rs</groupId>
  46. <artifactId>jsr311-api</artifactId>
  47. <version>1.1.1</version>
  48. </dependency>
  49. <dependency>
  50. <groupId>org.slf4j</groupId>
  51. <artifactId>slf4j-api</artifactId>
  52. <version>1.5.8</version>
  53. </dependency>
  54. <dependency>
  55. <groupId>org.slf4j</groupId>
  56. <artifactId>slf4j-jdk14</artifactId>
  57. <version>1.5.8</version>
  58. </dependency>
  59. <dependency>
  60. <groupId>commons-httpclient</groupId>
  61. <artifactId>commons-httpclient</artifactId>
  62. <version>3.0</version>
  63. </dependency>
  64. <dependency>
  65. <groupId>commons-io</groupId>
  66. <artifactId>commons-io</artifactId>
  67. <version>2.3</version>
  68. </dependency>
  69. <dependency>
  70. <groupId>junit</groupId>
  71. <artifactId>junit</artifactId>
  72. <version>4.8.1</version>
  73. <scope>test</scope>
  74. </dependency>
  75. </dependencies>
  76. <build>
  77. <finalName>cxfstudy</finalName>
  78. <resources>
  79. <resource>
  80. <directory>src/main/resources</directory>
  81. </resource>
  82. <resource>
  83. <directory>src/main/java</directory>
  84. <includes>
  85. <include>**</include>
  86. </includes>
  87. <excludes>
  88. <exclude>**/*.java</exclude>
  89. </excludes>
  90. </resource>
  91. </resources>
  92. <plugins>
  93. <plugin>
  94. <groupId>org.mortbay.jetty</groupId>
  95. <artifactId>maven-jetty-plugin</artifactId>
  96. <configuration>
  97. <contextPath>/</contextPath>
  98. <connectors>
  99. <connector implementation="org.mortbay.jetty.nio.SelectChannelConnector">
  100. <port>9000</port>
  101. </connector>
  102. </connectors>
  103. </configuration>
  104. </plugin>
  105. <plugin>
  106. <groupId>org.apache.maven.plugins</groupId>
  107. <artifactId>maven-compiler-plugin</artifactId>
  108. <configuration>
  109. <source>1.5</source>
  110. <target>1.5</target>
  111. </configuration>
  112. </plugin>
  113. </plugins>
  114. </build>
  115. </project>
下面来看看HelloWorld的具体例子。

1.创建HelloWorld 接口类

  1. package com.googlecode.garbagecan.cxfstudy.helloworld;
  2. import javax.jws.WebMethod;
  3. import javax.jws.WebParam;
  4. import javax.jws.WebResult;
  5. import javax.jws.WebService;
  6. @WebService
  7. public interface HelloWorld {
  8. @WebMethod
  9. @WebResult String sayHi(@WebParam String text);
  10. }
2.创建HelloWorld实现类

  1. package com.googlecode.garbagecan.cxfstudy.helloworld;
  2. public class HelloWorldImpl implements HelloWorld {
  3. public String sayHi(String name) {
  4. String msg = "Hello " + name + "!";
  5. return msg;
  6. }
  7. }
3.创建Server端测试类

  1. package com.googlecode.garbagecan.cxfstudy.helloworld;
  2. import org.apache.cxf.jaxws.JaxWsServerFactoryBean;
  3. // http://localhost:9000/HelloWorld?wsdl
  4. public class Server {
  5. public static void main(String[] args) throws Exception {
  6. JaxWsServerFactoryBean factory = new JaxWsServerFactoryBean();
  7. factory.setServiceClass(HelloWorldImpl.class);
  8. factory.setAddress("http://localhost:9000/ws/HelloWorld");
  9. factory.create();
  10. System.out.println("Server start...");
  11. Thread.sleep(60 * 1000);
  12. System.out.println("Server exit...");
  13. System.exit(0);
  14. }
  15. }
4.创建Client端测试类

  1. package com.googlecode.garbagecan.cxfstudy.helloworld;
  2. import org.apache.cxf.jaxws.JaxWsProxyFactoryBean;
  3. public class Client {
  4. public static void main(String[] args) {
  5. JaxWsProxyFactoryBean factory = new JaxWsProxyFactoryBean();
  6. factory.setServiceClass(HelloWorld.class);
  7. factory.setAddress("http://localhost:9000/ws/HelloWorld");
  8. HelloWorld helloworld = (HelloWorld) factory.create();
  9. System.out.println(helloworld.sayHi("kongxx"));
  10. System.exit(0);
  11. }
  12. }
5.测试

首先运行Server类来启动Web Service服务,然后访问http://localhost:9000/ws/HelloWorld?wsdl地址来确定web service启动正确。

运行Client测试类,会在命令行输出Hello kongxx!的message。

 

=====================

 

Apache CXF实战之一 Hello World Web Service

书接上文,下面看看CXF怎样和spring集成。

1.创建HelloWorld 接口类

  1. package com.googlecode.garbagecan.cxfstudy.helloworld;
  2. import javax.jws.WebMethod;
  3. import javax.jws.WebParam;
  4. import javax.jws.WebResult;
  5. import javax.jws.WebService;
  6. @WebService
  7. public interface HelloWorld {
  8. @WebMethod
  9. @WebResult String sayHi(@WebParam String text);
  10. }

2.创建HelloWorld实现类

  1. package com.googlecode.garbagecan.cxfstudy.helloworld;
  2. public class HelloWorldImpl implements HelloWorld {
  3. public String sayHi(String name) {
  4. String msg = "Hello " + name + "!";
  5. return msg;
  6. }
  7. }

3.修改web.xml文件

  1. <!DOCTYPE web-app PUBLIC
  2. "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
  3. "http://java.sun.com/dtd/web-app_2_3.dtd" >
  4. <web-app>
  5. <display-name>cxfstudy</display-name>
  6. <servlet>
  7. <servlet-name>cxf</servlet-name>
  8. <servlet-class>org.apache.cxf.transport.servlet.CXFServlet</servlet-class>
  9. <load-on-startup>1</load-on-startup>
  10. </servlet>
  11. <servlet-mapping>
  12. <servlet-name>cxf</servlet-name>
  13. <url-pattern>/ws/*</url-pattern>
  14. </servlet-mapping>
  15. <listener>
  16. <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  17. </listener>
  18. <context-param>
  19. <param-name>contextConfigLocation</param-name>
  20. <param-value>classpath*:**/spring.xml</param-value>
  21. </context-param>
  22. </web-app>

4.创建spring配置文件并放在classpath路径下

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans xmlns="http://www.springframework.org/schema/beans"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:jaxws="http://cxf.apache.org/jaxws"
  4. xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
  5. http://cxf.apache.org/jaxws http://cxf.apache.org/schemas/jaxws.xsd">
  6. <import resource="classpath:META-INF/cxf/cxf.xml" />
  7. <import resource="classpath:META-INF/cxf/cxf-extension-soap.xml" />
  8. <import resource="classpath:META-INF/cxf/cxf-servlet.xml" />
  9. <jaxws:endpoint id="helloworld" implementor="com.googlecode.garbagecan.cxfstudy.helloworld.HelloWorldImpl" address="/HelloWorld" />
  10. <!-- For client test -->
  11. <jaxws:client id="helloworldClient" address="http://localhost:9000/ws/HelloWorld" serviceClass="com.googlecode.garbagecan.cxfstudy.helloworld.HelloWorld" />
  12. </beans>

5.创建测试类

  1. package com.googlecode.garbagecan.cxfstudy.helloworld;
  2. import org.springframework.context.ApplicationContext;
  3. import org.springframework.context.support.ClassPathXmlApplicationContext;
  4. public class SpringClient {
  5. public static void main(String[] args) {
  6. ApplicationContext context = new ClassPathXmlApplicationContext("spring.xml");
  7. HelloWorld helloworld = (HelloWorld)context.getBean("helloworldClient");
  8. System.out.println(helloworld.sayHi("kongxx"));
  9. }
  10. }

6.测试

6.1 首先启动tomcat或者使用maven的jetty,并访问http://localhost:9000/ws/HelloWorld?wsdl来验证web service已经启动并且生效;

6.2 然后运行测试类来验证web service。

 

===================

 

 

前面两篇文章介绍了怎样通过CXF来构建最基本的Web Service,并且其中暴露的接口参数和返回值都是字符串,下面来看看一个稍微复杂一点的例子。

1. 首先是一个普通的pojo对象,用来表示一个实体类

  1. package com.googlecode.garbagecan.cxfstudy.jaxws;
  2. import java.util.Date;
  3. public class Customer {
  4. private String id;
  5. private String name;
  6. private Date birthday;
  7. public String getId() {
  8. return id;
  9. }
  10. public void setId(String id) {
  11. this.id = id;
  12. }
  13. public String getName() {
  14. return name;
  15. }
  16. public void setName(String name) {
  17. this.name = name;
  18. }
  19. public Date getBirthday() {
  20. return birthday;
  21. }
  22. public void setBirthday(Date birthday) {
  23. this.birthday = birthday;
  24. }
  25. @Override
  26. public String toString() {
  27. return org.apache.commons.lang.builder.ToStringBuilder.reflectionToString(this);
  28. }
  29. }

2. 创建Web Service接口类

  1. package com.googlecode.garbagecan.cxfstudy.jaxws;
  2. import javax.jws.WebMethod;
  3. import javax.jws.WebParam;
  4. import javax.jws.WebResult;
  5. import javax.jws.WebService;
  6. @WebService
  7. public interface CustomerService {
  8. @WebMethod
  9. @WebResult Customer findCustomer(@WebParam String id);
  10. }

3. 创建Web Service接口的实现类

  1. package com.googlecode.garbagecan.cxfstudy.jaxws;
  2. import java.util.Calendar;
  3. public class CustomerServiceImpl implements CustomerService {
  4. public Customer findCustomer(String id) {
  5. Customer customer = new Customer();
  6. customer.setId("customer_" + id);
  7. customer.setName("customer_name");
  8. customer.setBirthday(Calendar.getInstance().getTime());
  9. return customer;
  10. }
  11. }

4. 下面是Server端的代码

  1. package com.googlecode.garbagecan.cxfstudy.jaxws;
  2. import javax.xml.ws.Endpoint;
  3. import org.apache.cxf.interceptor.LoggingInInterceptor;
  4. import org.apache.cxf.interceptor.LoggingOutInterceptor;
  5. import org.apache.cxf.jaxws.JaxWsServerFactoryBean;
  6. public class MyServer {
  7. private static final String address = "http://localhost:9000/ws/jaxws/customerService";
  8. public static void main(String[] args) throws Exception {
  9. // http://localhost:9000/ws/jaxws/customerService?wsdl
  10. JaxWsServerFactoryBean factoryBean = new JaxWsServerFactoryBean();
  11. factoryBean.getInInterceptors().add(new LoggingInInterceptor());
  12. factoryBean.getOutInterceptors().add(new LoggingOutInterceptor());
  13. factoryBean.setServiceClass(CustomerServiceImpl.class);
  14. factoryBean.setAddress(address);
  15. factoryBean.create();
  16. }
  17. }

5. 下面是Client端的代码

  1. package com.googlecode.garbagecan.cxfstudy.jaxws;
  2. import java.net.SocketTimeoutException;
  3. import javax.xml.ws.WebServiceException;
  4. import org.apache.cxf.jaxws.JaxWsProxyFactoryBean;
  5. public class MyClient {
  6. public static void main(String[] args) throws Exception {
  7. JaxWsProxyFactoryBean factoryBean = new JaxWsProxyFactoryBean();
  8. factoryBean.setAddress("http://localhost:9000/ws/jaxws/customerService");
  9. factoryBean.setServiceClass(CustomerService.class);
  10. Object obj = factoryBean.create();
  11. CustomerService customerService = (CustomerService) obj;
  12. try {
  13. Customer customer = customerService.findCustomer("123");
  14. System.out.println("Customer: " + customer);
  15. } catch(Exception e) {
  16. if (e instanceof WebServiceException
  17. && e.getCause() instanceof SocketTimeoutException) {
  18. System.err.println("This is timeout exception.");
  19. } else {
  20. e.printStackTrace();
  21. }
  22. }
  23. }
  24. }

6.测试

首先运行MyServer类,然后运行MyClient类来验证Web Service。

 

==============

 

这篇文章介绍一下怎么通过CXF来发布RESTful的Web Service.

1. 首先是实体类,注意其中的@XmlRootElement注解

  1. package com.googlecode.garbagecan.cxfstudy.jaxrs;
  2. import java.util.Date;
  3. import javax.xml.bind.annotation.XmlRootElement;
  4. @XmlRootElement(name="Customer")
  5. public class Customer {
  6. private String id;
  7. private String name;
  8. private Date birthday;
  9. public String getId() {
  10. return id;
  11. }
  12. public void setId(String id) {
  13. this.id = id;
  14. }
  15. public String getName() {
  16. return name;
  17. }
  18. public void setName(String name) {
  19. this.name = name;
  20. }
  21. public Date getBirthday() {
  22. return birthday;
  23. }
  24. public void setBirthday(Date birthday) {
  25. this.birthday = birthday;
  26. }
  27. @Override
  28. public String toString() {
  29. return org.apache.commons.lang.builder.ToStringBuilder.reflectionToString(this);
  30. }
  31. }

2. RESTful Web Service接口类,可以通过修改@Produces注解来声明暴露接口返回的json还是xml数据格式

  1. package com.googlecode.garbagecan.cxfstudy.jaxrs;
  2. import javax.ws.rs.GET;
  3. import javax.ws.rs.Path;
  4. import javax.ws.rs.PathParam;
  5. import javax.ws.rs.Produces;
  6. import javax.ws.rs.QueryParam;
  7. @Path(value = "/customer")
  8. @Produces("*/*")
  9. //@Produces("application/xml")
  10. //@Produces("application/json")
  11. public interface CustomerService {
  12. @GET
  13. @Path(value = "/{id}/info")
  14. Customer findCustomerById(@PathParam("id")String id);
  15. @GET
  16. @Path(value = "/search")
  17. Customer findCustomerByName(@QueryParam("name")String name);
  18. }

3. RESTful Web Service接口实现类

  1. package com.googlecode.garbagecan.cxfstudy.jaxrs;
  2. import java.util.Calendar;
  3. public class CustomerServiceImpl implements CustomerService {
  4. public Customer findCustomerById(String id) {
  5. Customer customer = new Customer();
  6. customer.setId(id);
  7. customer.setName(id);
  8. customer.setBirthday(Calendar.getInstance().getTime());
  9. return customer;
  10. }
  11. public Customer findCustomerByName(String name) {
  12. Customer customer = new Customer();
  13. customer.setId(name);
  14. customer.setName(name);
  15. customer.setBirthday(Calendar.getInstance().getTime());
  16. return customer;
  17. }
  18. }

4. Server端代码

  1. package com.googlecode.garbagecan.cxfstudy.jaxrs;
  2. import org.apache.cxf.interceptor.LoggingInInterceptor;
  3. import org.apache.cxf.interceptor.LoggingOutInterceptor;
  4. import org.apache.cxf.jaxrs.JAXRSServerFactoryBean;
  5. public class MyServer {
  6. public static void main(String[] args) throws Exception {
  7. JAXRSServerFactoryBean factoryBean = new JAXRSServerFactoryBean();
  8. factoryBean.getInInterceptors().add(new LoggingInInterceptor());
  9. factoryBean.getOutInterceptors().add(new LoggingOutInterceptor());
  10. factoryBean.setResourceClasses(CustomerServiceImpl.class);
  11. factoryBean.setAddress("http://localhost:9000/ws/jaxrs");
  12. factoryBean.create();
  13. }
  14. }

5. Client端代码

  1. package com.googlecode.garbagecan.cxfstudy.jaxrs;
  2. import org.apache.commons.httpclient.HttpClient;
  3. import org.apache.commons.httpclient.HttpStatus;
  4. import org.apache.commons.httpclient.methods.GetMethod;
  5. public class MyClient {
  6. public static void main(String[] args) throws Exception {
  7. go("http://localhost:9000/ws/jaxrs/customer/1/info");
  8. go("http://localhost:9000/ws/jaxrs/customer/search?name=abc");
  9. }
  10. private static void go(String url) throws Exception {
  11. HttpClient client = new HttpClient();
  12. GetMethod method = new GetMethod(url);
  13. int statusCode = client.executeMethod(method);
  14. if (statusCode != HttpStatus.SC_OK) {
  15. System.err.println("Method failed: " + method.getStatusLine());
  16. }
  17. byte[] responseBody = method.getResponseBody();
  18. System.out.println(new String(responseBody));
  19. }
  20. }

6.测试

首先运行MyServer类,然后运行MyClient类来验证Web Service。

 

================

 

在现实应用中有些时候会有比较大的数据对象需要传输,或者在一个比较慢的网络环境下发布调用web service,此时可以通过压缩数据流的方式来减小数据包的大小,从而提高web service的性能。下面来看看怎样来做到这一点。

1. 首先模拟一个可以存放大数据的pojo对象,这个对象可以通过构造参数给定的size来模拟一个size大小的字符串。

  1. package com.googlecode.garbagecan.cxfstudy.compress;
  2. public class BigData {
  3. private String name;
  4. private String data;
  5. public BigData() {
  6. }
  7. public BigData(String name, int size) {
  8. this.name = name;
  9. StringBuilder sb = new StringBuilder();
  10. for (int i = 0; i < size; i++) {
  11. sb.append("0");
  12. }
  13. this.data = sb.toString();
  14. }
  15. public String getName() {
  16. return name;
  17. }
  18. public void setName(String name) {
  19. this.name = name;
  20. }
  21. public String getData() {
  22. return data;
  23. }
  24. public void setData(String data) {
  25. this.data = data;
  26. }
  27. }

2. Web Service接口类,和普通的接口定义没有什么区别。

  1. package com.googlecode.garbagecan.cxfstudy.compress;
  2. import javax.jws.WebMethod;
  3. import javax.jws.WebParam;
  4. import javax.jws.WebResult;
  5. import javax.jws.WebService;
  6. @WebService
  7. public interface BigDataService {
  8. @WebMethod
  9. @WebResult BigData getBigData(@WebParam String name, @WebParam int size);
  10. }

3. Web Service实现类

  1. package com.googlecode.garbagecan.cxfstudy.compress;
  2. public class BigDataServiceImpl implements BigDataService {
  3. public BigData getBigData(String name, int size) {
  4. BigData bigData = new BigData(name, size);
  5. return bigData;
  6. }
  7. }

4. 测试类,这片文章使用了JUnit测试类来做测试。setUpBeforeClass方法用来启动Service, testGetBigData方法用来测试web service。

注意setUpBeforeClass方法中的

factoryBean.getInInterceptors().add(new GZIPInInterceptor());

factoryBean.getOutInterceptors().add(new GZIPOutInterceptor());

和testGetBigData方法中的

endpoint.getInInterceptors().add(new GZIPInInterceptor());

endpoint.getOutInterceptors().add(new GZIPOutInterceptor());

上面两段代码就是告诉CXF使用压缩Interceptor来压缩和解压缩数据包。

  1. package com.googlecode.garbagecan.cxfstudy.compress;
  2. import org.apache.cxf.endpoint.Client;
  3. import org.apache.cxf.endpoint.Endpoint;
  4. import org.apache.cxf.frontend.ClientProxy;
  5. import org.apache.cxf.interceptor.LoggingInInterceptor;
  6. import org.apache.cxf.interceptor.LoggingOutInterceptor;
  7. import org.apache.cxf.jaxws.JaxWsProxyFactoryBean;
  8. import org.apache.cxf.jaxws.JaxWsServerFactoryBean;
  9. import org.apache.cxf.transport.http.gzip.GZIPInInterceptor;
  10. import org.apache.cxf.transport.http.gzip.GZIPOutInterceptor;
  11. import org.junit.Assert;
  12. import org.junit.BeforeClass;
  13. import org.junit.Test;
  14. public class BigDataServiceTest {
  15. private static final String address = "http://localhost:9000/ws/compress/bigDataService";
  16. @BeforeClass
  17. public static void setUpBeforeClass() throws Exception {
  18. JaxWsServerFactoryBean factoryBean = new JaxWsServerFactoryBean();
  19. factoryBean.getInInterceptors().add(new LoggingInInterceptor());
  20. factoryBean.getOutInterceptors().add(new LoggingOutInterceptor());
  21. factoryBean.getInInterceptors().add(new GZIPInInterceptor());
  22. factoryBean.getOutInterceptors().add(new GZIPOutInterceptor());
  23. factoryBean.setServiceClass(BigDataServiceImpl.class);
  24. factoryBean.setAddress(address);
  25. factoryBean.create();
  26. }
  27. @Test
  28. public void testGetBigData() {
  29. JaxWsProxyFactoryBean factoryBean = new JaxWsProxyFactoryBean();
  30. factoryBean.setAddress(address);
  31. factoryBean.setServiceClass(BigDataService.class);
  32. Object obj = factoryBean.create();
  33. Client client = ClientProxy.getClient(obj);
  34. Endpoint endpoint = client.getEndpoint();
  35. endpoint.getInInterceptors().add(new GZIPInInterceptor());
  36. endpoint.getOutInterceptors().add(new GZIPOutInterceptor());
  37. BigDataService service = (BigDataService) obj;
  38. Assert.assertNotNull(service);
  39. String name = "my big data";
  40. int size = 1024 * 1024 * 10;
  41. long start = System.currentTimeMillis();
  42. BigData bigData = service.getBigData(name, size);
  43. long stop = System.currentTimeMillis();
  44. System.out.println("Time: " + (stop - start));
  45. Assert.assertNotNull(bigData);
  46. Assert.assertEquals(name, bigData.getName());
  47. Assert.assertEquals(size, bigData.getData().length());
  48. }
  49. }

5. 运行此unit test,可以在日志中看到数据包前后大小和内容。

================

 

我们在使用Web Service的过程中,很多情况是需要对web service请求做认证的,对于运行在web容器里的应用程序来说,可能会比较简单一些,通常可以通过filter来做一些处理,但是其实CXF本身也提供了对web service认证的方式。下面来看一下如何实现

1. 首先是一个简单pojo

  1. package com.googlecode.garbagecan.cxfstudy.security;
  2. public class User {
  3. private String id;
  4. private String name;
  5. private String password;
  6. public String getId() {
  7. return id;
  8. }
  9. public void setId(String id) {
  10. this.id = id;
  11. }
  12. public String getName() {
  13. return name;
  14. }
  15. public void setName(String name) {
  16. this.name = name;
  17. }
  18. public String getPassword() {
  19. return password;
  20. }
  21. public void setPassword(String password) {
  22. this.password = password;
  23. }
  24. }

2. Web Service接口

  1. package com.googlecode.garbagecan.cxfstudy.security;
  2. import java.util.List;
  3. import javax.jws.WebMethod;
  4. import javax.jws.WebResult;
  5. import javax.jws.WebService;
  6. @WebService
  7. public interface UserService {
  8. @WebMethod
  9. @WebResult List<User> list();
  10. }

3. Web Service实现类

  1. package com.googlecode.garbagecan.cxfstudy.security;
  2. import java.util.ArrayList;
  3. import java.util.List;
  4. public class UserServiceImpl implements UserService {
  5. public List<User> list() {
  6. List<User> users = new ArrayList<User>();
  7. for (int i = 0; i < 10; i++) {
  8. User user = new User();
  9. user.setId("" + i);
  10. user.setName("user_" + i);
  11. user.setPassword("password_" + i);
  12. users.add(user);
  13. }
  14. return users;
  15. }
  16. }

4. Server端Handler,其中使用了一个Map来存放用户信息,真是应用中可以使用数据库或者其它方式获取用户和密码

  1. package com.googlecode.garbagecan.cxfstudy.security;
  2. import java.io.IOException;
  3. import java.util.HashMap;
  4. import java.util.Map;
  5. import javax.security.auth.callback.Callback;
  6. import javax.security.auth.callback.CallbackHandler;
  7. import javax.security.auth.callback.UnsupportedCallbackException;
  8. import org.apache.ws.security.WSPasswordCallback;
  9. public class ServerUsernamePasswordHandler implements CallbackHandler {
  10. // key is username, value is password
  11. private Map<String, String> users;
  12. public ServerUsernamePasswordHandler() {
  13. users = new HashMap<String, String>();
  14. users.put("admin", "admin");
  15. }
  16. public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException {
  17. WSPasswordCallback callback = (WSPasswordCallback) callbacks[0];
  18. String id = callback.getIdentifier();
  19. if (users.containsKey(id)) {
  20. if (!callback.getPassword().equals(users.get(id))) {
  21. throw new SecurityException("Incorrect password.");
  22. }
  23. } else {
  24. throw new SecurityException("Invalid user.");
  25. }
  26. }
  27. }

5. Client端Handler,用来设置用户密码,在真实应用中可以根据此类和下面的测试类来修改逻辑设置用户名和密码。

  1. package com.googlecode.garbagecan.cxfstudy.security;
  2. import java.io.IOException;
  3. import javax.security.auth.callback.Callback;
  4. import javax.security.auth.callback.CallbackHandler;
  5. import javax.security.auth.callback.UnsupportedCallbackException;
  6. import org.apache.ws.security.WSPasswordCallback;
  7. public class ClientUsernamePasswordHandler implements CallbackHandler {
  8. public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException {
  9. WSPasswordCallback callback = (WSPasswordCallback) callbacks[0];
  10. int usage = callback.getUsage();
  11. System.out.println("identifier: " + callback.getIdentifier());
  12. System.out.println("usage: " + callback.getUsage());
  13. if (usage == WSPasswordCallback.USERNAME_TOKEN) {
  14. callback.setPassword("admin");
  15. }
  16. }
  17. }

6. 单元测试类,注意在Server端添加了WSS4JInInterceptor到Interceptor列表中,在Client添加了WSS4JOutInterceptor到Interceptor列表中。

  1. package com.googlecode.garbagecan.cxfstudy.security;
  2. import java.net.SocketTimeoutException;
  3. import java.util.HashMap;
  4. import java.util.List;
  5. import java.util.Map;
  6. import javax.xml.ws.WebServiceException;
  7. import junit.framework.Assert;
  8. import org.apache.cxf.endpoint.Client;
  9. import org.apache.cxf.endpoint.Endpoint;
  10. import org.apache.cxf.frontend.ClientProxy;
  11. import org.apache.cxf.interceptor.LoggingInInterceptor;
  12. import org.apache.cxf.interceptor.LoggingOutInterceptor;
  13. import org.apache.cxf.jaxws.JaxWsProxyFactoryBean;
  14. import org.apache.cxf.jaxws.JaxWsServerFactoryBean;
  15. import org.apache.cxf.transport.http.HTTPConduit;
  16. import org.apache.cxf.transports.http.configuration.HTTPClientPolicy;
  17. import org.apache.cxf.ws.security.wss4j.WSS4JInInterceptor;
  18. import org.apache.cxf.ws.security.wss4j.WSS4JOutInterceptor;
  19. import org.apache.ws.security.WSConstants;
  20. import org.apache.ws.security.handler.WSHandlerConstants;
  21. import org.junit.BeforeClass;
  22. import org.junit.Test;
  23. public class UserServiceTest {
  24. private static final String address = "http://localhost:9000/ws/security/userService";
  25. @BeforeClass
  26. public static void setUpBeforeClass() throws Exception {
  27. JaxWsServerFactoryBean factoryBean = new JaxWsServerFactoryBean();
  28. factoryBean.getInInterceptors().add(new LoggingInInterceptor());
  29. factoryBean.getOutInterceptors().add(new LoggingOutInterceptor());
  30. Map<String, Object> props = new HashMap<String, Object>();
  31. props.put("action", "UsernameToken");
  32. props.put("passwordType", "PasswordText");
  33. props.put("passwordCallbackClass", ServerUsernamePasswordHandler.class.getName());
  34. WSS4JInInterceptor wss4JInInterceptor = new WSS4JInInterceptor(props);
  35. factoryBean.getInInterceptors().add(wss4JInInterceptor);
  36. factoryBean.setServiceClass(UserServiceImpl.class);
  37. factoryBean.setAddress(address);
  38. factoryBean.create();
  39. }
  40. @Test
  41. public void testList() {
  42. JaxWsProxyFactoryBean factoryBean = new JaxWsProxyFactoryBean();
  43. factoryBean.setAddress(address);
  44. factoryBean.setServiceClass(UserService.class);
  45. Object obj = factoryBean.create();
  46. Client client = ClientProxy.getClient(obj);
  47. Endpoint endpoint = client.getEndpoint();
  48. Map<String,Object> props = new HashMap<String,Object>();
  49. props.put(WSHandlerConstants.ACTION, WSHandlerConstants.USERNAME_TOKEN);
  50. props.put(WSHandlerConstants.USER, "admin");
  51. props.put(WSHandlerConstants.PASSWORD_TYPE, WSConstants.PW_TEXT);
  52. props.put(WSHandlerConstants.PW_CALLBACK_CLASS, ClientUsernamePasswordHandler.class.getName());
  53. WSS4JOutInterceptor wss4JOutInterceptor = new WSS4JOutInterceptor(props);
  54. endpoint.getOutInterceptors().add(wss4JOutInterceptor);
  55. HTTPConduit conduit = (HTTPConduit) client.getConduit();
  56. HTTPClientPolicy policy = new HTTPClientPolicy();
  57. policy.setConnectionTimeout(5 * 1000);
  58. policy.setReceiveTimeout(5 * 1000);
  59. conduit.setClient(policy);
  60. UserService service = (UserService) obj;
  61. try {
  62. List<User> users = service.list();
  63. Assert.assertNotNull(users);
  64. Assert.assertEquals(10, users.size());
  65. } catch(Exception e) {
  66. if (e instanceof WebServiceException
  67. && e.getCause() instanceof SocketTimeoutException) {
  68. System.err.println("This is timeout exception.");
  69. } else {
  70. e.printStackTrace();
  71. }
  72. }
  73. }
  74. }

最后运行上面的测试类来测试结果,也可以修改测试方法中的密码,看看错误结果,这里就不在写错误密码的测试用例了,因为我是一懒人。

 

===============

 

首先声明我知道有个协议叫ftp,也知道有种编程叫sock编程,但我就是碰到了server对外只开放80端口,并且还需要提供文件上传和下载功能的应用,那好吧,开始干活。

1. 首先是一个封装了服务器端文件路径,客户端文件路径和要传输的字节数组的MyFile类。

  1. package com.googlecode.garbagecan.cxfstudy.filetransfer;
  2. public class MyFile {
  3. private String clientFile;
  4. private String serverFile;
  5. private long position;
  6. private byte[] bytes;
  7. public String getClientFile() {
  8. return clientFile;
  9. }
  10. public void setClientFile(String clientFile) {
  11. this.clientFile = clientFile;
  12. }
  13. public String getServerFile() {
  14. return serverFile;
  15. }
  16. public void setServerFile(String serverFile) {
  17. this.serverFile = serverFile;
  18. }
  19. public long getPosition() {
  20. return position;
  21. }
  22. public void setPosition(long position) {
  23. this.position = position;
  24. }
  25. public byte[] getBytes() {
  26. return bytes;
  27. }
  28. public void setBytes(byte[] bytes) {
  29. this.bytes = bytes;
  30. }
  31. }

2. 文件传输的Web Service接口

  1. package com.googlecode.garbagecan.cxfstudy.filetransfer;
  2. import javax.jws.WebMethod;
  3. import javax.jws.WebService;
  4. @WebService
  5. public interface FileTransferService {
  6. @WebMethod
  7. void uploadFile(MyFile myFile) throws FileTransferException;
  8. @WebMethod
  9. MyFile downloadFile(MyFile myFile) throws FileTransferException;
  10. }

3. 文件传输的Web Service接口实现类,主要是一些流的操作

  1. package com.googlecode.garbagecan.cxfstudy.filetransfer;
  2. import java.io.File;
  3. import java.io.FileInputStream;
  4. import java.io.IOException;
  5. import java.io.InputStream;
  6. import java.io.OutputStream;
  7. import java.util.Arrays;
  8. import org.apache.commons.io.FileUtils;
  9. import org.apache.commons.io.IOUtils;
  10. public class FileTransferServiceImpl implements FileTransferService {
  11. public void uploadFile(MyFile myFile) throws FileTransferException {
  12. OutputStream os = null;
  13. try {
  14. if (myFile.getPosition() != 0) {
  15. os = FileUtils.openOutputStream(new File(myFile.getServerFile()), true);
  16. } else {
  17. os = FileUtils.openOutputStream(new File(myFile.getServerFile()), false);
  18. }
  19. os.write(myFile.getBytes());
  20. } catch(IOException e) {
  21. throw new FileTransferException(e.getMessage(), e);
  22. } finally {
  23. IOUtils.closeQuietly(os);
  24. }
  25. }
  26. public MyFile downloadFile(MyFile myFile) throws FileTransferException {
  27. InputStream is = null;
  28. try {
  29. is = new FileInputStream(myFile.getServerFile());
  30. is.skip(myFile.getPosition());
  31. byte[] bytes = new byte[1024 * 1024];
  32. int size = is.read(bytes);
  33. if (size > 0) {
  34. byte[] fixedBytes = Arrays.copyOfRange(bytes, 0, size);
  35. myFile.setBytes(fixedBytes);
  36. } else {
  37. myFile.setBytes(new byte[0]);
  38. }
  39. } catch(IOException e) {
  40. throw new FileTransferException(e.getMessage(), e);
  41. } finally {
  42. IOUtils.closeQuietly(is);
  43. }
  44. return myFile;
  45. }
  46. }

4. 一个简单的文件传输异常类

  1. package com.googlecode.garbagecan.cxfstudy.filetransfer;
  2. public class FileTransferException extends Exception {
  3. private static final long serialVersionUID = 1L;
  4. public FileTransferException() {
  5. super();
  6. }
  7. public FileTransferException(String message, Throwable cause) {
  8. super(message, cause);
  9. }
  10. public FileTransferException(String message) {
  11. super(message);
  12. }
  13. public FileTransferException(Throwable cause) {
  14. super(cause);
  15. }
  16. }

5. 下面是Server类用来发布web service

  1. package com.googlecode.garbagecan.cxfstudy.filetransfer;
  2. import javax.xml.ws.Endpoint;
  3. public class FileTransferServer {
  4. public static void main(String[] args) throws Exception {
  5. Endpoint.publish("http://localhost:9000/ws/jaxws/fileTransferService", new FileTransferServiceImpl());
  6. }
  7. }

6. 最后是Client类,用来发送文件上传和下载请求。

  1. package com.googlecode.garbagecan.cxfstudy.filetransfer;
  2. import java.io.File;
  3. import java.io.FileInputStream;
  4. import java.io.IOException;
  5. import java.io.InputStream;
  6. import java.io.OutputStream;
  7. import java.util.Arrays;
  8. import org.apache.commons.io.FileUtils;
  9. import org.apache.commons.io.IOUtils;
  10. import org.apache.cxf.jaxws.JaxWsProxyFactoryBean;
  11. public class FileTransferClient {
  12. private static final String address = "http://localhost:9000/ws/jaxws/fileTransferService";
  13. private static final String clientFile = "/home/fkong/temp/client/test.zip";
  14. private static final String serverFile = "/home/fkong/temp/server/test.zip";
  15. public static void main(String[] args) throws Exception {
  16. long start = System.currentTimeMillis();
  17. // uploadFile();
  18. // downloadFile();
  19. long stop = System.currentTimeMillis();
  20. System.out.println("Time: " + (stop - start));
  21. }
  22. private static void uploadFile() throws FileTransferException {
  23. InputStream is = null;
  24. try {
  25. MyFile myFile = new MyFile();
  26. is = new FileInputStream(clientFile);
  27. byte[] bytes = new byte[1024 * 1024];
  28. while (true) {
  29. int size = is.read(bytes);
  30. if (size <= 0) {
  31. break;
  32. }
  33. byte[] fixedBytes = Arrays.copyOfRange(bytes, 0, size);
  34. myFile.setClientFile(clientFile);
  35. myFile.setServerFile(serverFile);
  36. myFile.setBytes(fixedBytes);
  37. uploadFile(myFile);
  38. myFile.setPosition(myFile.getPosition() + fixedBytes.length);
  39. }
  40. } catch(IOException e) {
  41. throw new FileTransferException(e.getMessage(), e);
  42. } finally {
  43. IOUtils.closeQuietly(is);
  44. }
  45. }
  46. private static void uploadFile(MyFile myFile) throws FileTransferException {
  47. JaxWsProxyFactoryBean factoryBean = new JaxWsProxyFactoryBean();
  48. factoryBean.setAddress(address);
  49. factoryBean.setServiceClass(FileTransferService.class);
  50. Object obj = factoryBean.create();
  51. FileTransferService service = (FileTransferService) obj;
  52. service.uploadFile(myFile);
  53. }
  54. private static void downloadFile() throws FileTransferException {
  55. MyFile myFile = new MyFile();
  56. myFile.setServerFile(serverFile);
  57. long position = 0;
  58. while (true) {
  59. myFile.setPosition(position);
  60. myFile = downloadFile(myFile);
  61. if (myFile.getBytes().length <= 0) {
  62. break;
  63. }
  64. OutputStream os = null;
  65. try {
  66. if (position != 0) {
  67. os = FileUtils.openOutputStream(new File(clientFile), true);
  68. } else {
  69. os = FileUtils.openOutputStream(new File(clientFile), false);
  70. }
  71. os.write(myFile.getBytes());
  72. } catch(IOException e) {
  73. throw new FileTransferException(e.getMessage(), e);
  74. } finally {
  75. IOUtils.closeQuietly(os);
  76. }
  77. position += myFile.getBytes().length;
  78. }
  79. }
  80. private static MyFile downloadFile(MyFile myFile) throws FileTransferException {
  81. JaxWsProxyFactoryBean factoryBean = new JaxWsProxyFactoryBean();
  82. factoryBean.setAddress(address);
  83. factoryBean.setServiceClass(FileTransferService.class);
  84. Object obj = factoryBean.create();
  85. FileTransferService service = (FileTransferService) obj;
  86. return service.downloadFile(myFile);
  87. }
  88. }

首先需要准备一个大一点的文件,然后修改代码中的clientFile和serverFile路径,然后分别打开uploadFile和downloadFile注释,运行程序,检查目标文件查看结果。

这个程序还是比较简单的,但基本生完成了文件上传下载功能,如果需要,也可以对这个程序再做点修改使其支持断点续传。

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值