1. 程式人生 > >java—(6)OpenAdaptor:基於webservice傳輸大檔案

java—(6)OpenAdaptor:基於webservice傳輸大檔案

OpenAdaptor支援XFire和CXF開發的webservice,所以開發CXF webservice,基於myeclipse開發比較容易。參照網上webrvice傳輸大檔案示例修改 http://blog.csdn.net/kongxx/article/details/7540930

1. 首先是一個封裝了伺服器端檔案路徑,客戶端檔案路徑和要傳輸的位元組陣列的MyFile類。

package com.cattsoft.baseplatform.webservice.fileltransfer;

public class MyFile {

	private String clientFile;

	private String serverFile;
	// 統計總共上傳下載位元組數
	private long position;
	// 每次上傳或下載的位元組陣列
	private byte[] bytes;

	public String getClientFile() {
		return clientFile;
	}

	public void setClientFile(String clientFile) {
		this.clientFile = clientFile;
	}

	public String getServerFile() {
		return serverFile;
	}

	public void setServerFile(String serverFile) {
		this.serverFile = serverFile;
	}

	public long getPosition() {
		return position;
	}

	public void setPosition(long position) {
		this.position = position;
	}

	public byte[] getBytes() {
		return bytes;
	}

	public void setBytes(byte[] bytes) {
		this.bytes = bytes;
	}
}


2. 檔案傳輸的Web Service介面

package com.cattsoft.baseplatform.webservice.fileltransfer;

import javax.jws.WebMethod;
import javax.jws.WebService;

@WebService
public interface FileTransferService {
	@WebMethod
	void uploadFile(String address, String clientFile, String serverFile)
			throws FileTransferException;

	@WebMethod
	void uploadFile1(MyFile myFile, String address) throws FileTransferException;

	@WebMethod
	void uploadFile2(MyFile myFile) throws FileTransferException;

	@WebMethod
	void downloadFile(String address, String clientFile, String serverFile)
			throws FileTransferException;

	@WebMethod
	void downloadFile1(MyFile myFile, String address) throws FileTransferException;

	@WebMethod
	MyFile downloadFile2(MyFile myFile) throws FileTransferException;
}


3. 檔案傳輸的Web Service介面實現類,主要是一些流的操作

package com.cattsoft.baseplatform.webservice.fileltransfer;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Arrays;

import javax.jws.WebService;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.cxf.jaxws.JaxWsProxyFactoryBean;

@WebService(endpointInterface = "com.cattsoft.baseplatform.webservice.fileltransfer.FileTransferService", serviceName = "FileTransferService")
public class FileTransferServiceImpl {
	// 以byte[]傳輸檔案,每次傳輸1024*1024,傳輸完後myFile.setPosition記錄總共傳輸的位元組數
	public void uploadFile(String address, String clientFile, String serverFile)
			throws FileTransferException {
		InputStream is = null;
		try {
			MyFile myFile = new MyFile();
			is = new FileInputStream(clientFile);
			byte[] bytes = new byte[1024 * 1024];
			while (true) {
				int size = is.read(bytes);// 從輸入流讀取資料儲存在緩衝陣列bytes,返回讀取的位元組數,直到檢測到檔案結束。讀取最多等同於read(bytes,
											// 0, bytes.length)
				if (size <= 0) {// 返回-1表示檔案結束
					break;
				}

				byte[] fixedBytes = Arrays.copyOfRange(bytes, 0, size);// 將bytes陣列拷貝到fixedBytes陣列,從0到size
				myFile.setClientFile(clientFile);
				myFile.setServerFile(serverFile);
				myFile.setBytes(fixedBytes);

				uploadFile1(myFile, address);

				myFile.setPosition(myFile.getPosition() + fixedBytes.length);// 總共傳輸的位元組數
			}
		} catch (IOException e) {
			throw new FileTransferException(e.getMessage(), e);
		} finally {
			IOUtils.closeQuietly(is);
		}
	}

	public void uploadFile1(MyFile myFile, String address) throws FileTransferException {
		JaxWsProxyFactoryBean factoryBean = new JaxWsProxyFactoryBean();
		factoryBean.setAddress(address);
		factoryBean.setServiceClass(FileTransferService.class);
		Object obj = factoryBean.create();

		FileTransferService service = (FileTransferService) obj;
		service.uploadFile2(myFile);
	}

	public void uploadFile2(MyFile myFile) throws FileTransferException {
		OutputStream os = null;

		try {
			if (myFile.getPosition() != 0) {
				// 使用Apache commons-io的FileUtils工具類
				// 開啟流,如果不存在建立檔案及其目錄結構,第二個引數表示 檔案流是否是追加方式
				os = FileUtils.openOutputStream(new File(myFile.getServerFile()), true);
			} else {
				os = FileUtils.openOutputStream(new File(myFile.getServerFile()), false);
			}
			os.write(myFile.getBytes());
		} catch (IOException e) {
			throw new FileTransferException(e.getMessage(), e);
		} finally {
			IOUtils.closeQuietly(os);
		}
	}

	public void downloadFile(String address, String clientFile, String serverFile)
			throws FileTransferException {
		MyFile myFile = new MyFile();
		myFile.setServerFile(serverFile);
		long position = 0;
		while (true) {
			myFile.setPosition(position);
			myFile = downloadFile1(myFile, address);
			if (myFile.getBytes().length <= 0) {
				break;
			}

			OutputStream os = null;
			try {
				if (position != 0) {
					os = FileUtils.openOutputStream(new File(clientFile), true);
				} else {
					os = FileUtils.openOutputStream(new File(clientFile), false);
				}
				os.write(myFile.getBytes());
			} catch (IOException e) {
				throw new FileTransferException(e.getMessage(), e);
			} finally {
				IOUtils.closeQuietly(os);
			}

			position += myFile.getBytes().length;
		}
	}

	public MyFile downloadFile1(MyFile myFile, String address) throws FileTransferException {
		JaxWsProxyFactoryBean factoryBean = new JaxWsProxyFactoryBean();
		factoryBean.setAddress(address);
		factoryBean.setServiceClass(FileTransferService.class);
		Object obj = factoryBean.create();

		FileTransferService service = (FileTransferService) obj;
		return service.downloadFile2(myFile);
	}

	public MyFile downloadFile2(MyFile myFile) throws FileTransferException {
		InputStream is = null;

		try {
			is = new FileInputStream(myFile.getServerFile());
			is.skip(myFile.getPosition());
			byte[] bytes = new byte[1024 * 1024];
			int size = is.read(bytes);
			if (size > 0) {
				byte[] fixedBytes = Arrays.copyOfRange(bytes, 0, size);
				myFile.setBytes(fixedBytes);
			} else {
				myFile.setBytes(new byte[0]);
			}
		} catch (IOException e) {
			throw new FileTransferException(e.getMessage(), e);
		} finally {
			IOUtils.closeQuietly(is);
		}
		return myFile;
	}
}


4. 一個簡單的檔案傳輸異常類

package com.cattsoft.baseplatform.webservice.fileltransfer;

public class FileTransferException extends Exception {

	private static final long serialVersionUID = 1L;

	public FileTransferException() {
		super();
	}

	public FileTransferException(String message, Throwable cause) {
		super(message, cause);
	}

	public FileTransferException(String message) {
		super(message);
	}

	public FileTransferException(Throwable cause) {
		super(cause);
	}
}


5. 下面是Server類用來發布web service

package com.cattsoft.baseplatform.webservice.fileltransfer;

import javax.xml.ws.Endpoint;

public class FileTransferServer {

	public static void main(String[] args) throws Exception {
		Endpoint.publish("http://localhost:9000/ws/jaxws/fileTransferService",
				new FileTransferServiceImpl());
		// Endpoint.publish(args[0], new FileTransferServiceImpl());
	}
}


6. 最後是Client類,用來發送檔案上傳和下載請求。

package com.cattsoft.baseplatform.webservice.fileltransfer;

/*
 * uploadFile是從clientFile傳到serverFile
 * downloadFile是從serverFile傳到clientFile
 * 引數args[0], args[1],args[2]依次為address, clientFile, serverFile
 */
public class FileTransferClient {

	private static final String address = "http://192.168.100.169:9000/ws/jaxws/fileTransferService1";
	private static final String clientFile = "F:/ftp/test.txt";
	private static final String serverFile = "D:/share/portal_ESB/ftp/test.txt";

	public static void main(String[] args) throws Exception {
		long start = System.currentTimeMillis();
		FileTransferServiceImpl fts = new FileTransferServiceImpl();
		fts.uploadFile(args[0], args[1], args[2]);
		// downloadFile(args[0], args[1], args[2]);
		long stop = System.currentTimeMillis();
		System.out.println("Time: " + (stop - start));
	}

}


7、配置openAdaptor檔案

<?xml version="1.0" encoding="UTF-8"?>
<!-- 
  $Id: step01.xml 696 2007-06-27 13:04:36Z higginse $
  $HeadURL: https://openadaptor3.openadaptor.org/svn/openadaptor3/tags/3.4.7/example/tutorial/step01.xml $
 -->
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd">
 
  <description><![CDATA[
  Adaptor for step 1 of the tutorial.
  ]]></description>

  <bean id="Adaptor" class="org.openadaptor.core.adaptor.Adaptor">
    <property name="messageProcessor" ref="Router"/>
  </bean>
  
  <bean id="Router" class="org.openadaptor.core.router.Router">
    <property name="processors">
      <list>
        <ref bean="Reader"/>
		<ref bean="BuyWriter"/>
      </list>
    </property>
  </bean>
   
   <bean id="Reader" class="org.openadaptor.auxil.connector.soap.WebServiceCXFReadConnector">
    <property name="wsEndpoint" value="http://localhost:9000/ws/jaxws/fileTransferService1?wsdl"/>
	  <property name="serviceName">
      <bean class="javax.xml.namespace.QName">
        <constructor-arg type="java.lang.String" index="0" value="http://filetransfer.cxfstudy.garbagecan.googlecode.com/"></constructor-arg>
	    <constructor-arg type="java.lang.String" index="1" value="uploadFile"></constructor-arg>
      </bean>
    </property>
	<property name="parameters">
		<list>
			<value type="java.lang.String">http://localhost:9000/ws/jaxws/fileTransferService1</value>
			<value type="java.lang.String">F:/ftp/test.txt</value>
			<value type="java.lang.String">F:/ftp1/test1.txt</value>
		</list>
   </property>
  </bean>

 
  
  <bean id="Writer" class="org.openadaptor.auxil.connector.soap.WebServiceCXFWriteConnector">
    <property name="endpoint" value="http://192.168.223.142:9763/AddService_1.0.0/services/add_service?wsdl"/>
	<property name="methodName" value="add"/>
</bean>

  <bean id="BuyWriter" class="org.openadaptor.auxil.connector.iostream.writer.FileWriteConnector">
   <property name="filename" value="output/1.txt" />
  </bean>
</beans>