`
log_cd
  • 浏览: 1089835 次
  • 性别: Icon_minigender_1
  • 来自: 成都
社区版块
存档分类
最新评论

WebService之CXF使用Session

阅读更多
一、接口与实现
@WebService
public interface IUserLogin {

	public boolean login(String userId, String password);
	
	public boolean logout(String userId);

	public boolean checkLoginState(String userId);
	
}

@Repository
@WebService(endpointInterface = "net.log_cd.ws.IUserLogin")
public class UserLoginImpl implements IUserLogin{

	@Resource     
	private WebServiceContext wsContext;      
	
	@Override
	public boolean login(String userId, String password) {
		MessageContext msgContext = wsContext.getMessageContext();      
		HttpSession httpSession = ((HttpServletRequest) msgContext.get(MessageContext.SERVLET_REQUEST)).getSession();      
		HttpServletRequest request = (HttpServletRequest)msgContext.get("HTTP.REQUEST"); 
		System.out.println("request from " + request.getRemoteAddr()+", [userId = "+userId+", password="+password);
		
		httpSession.setAttribute("token", httpSession.getId()+"_"+userId);
		//save session into webservice context
		((javax.servlet.ServletContext) msgContext.get(MessageContext.SERVLET_CONTEXT)).setAttribute("session", httpSession);
		return true;
	}

	@Override
	public boolean logout(String userId) {
		MessageContext msgContext = wsContext.getMessageContext();  
		HttpSession httpSession = (HttpSession)((ServletContext) msgContext.get(MessageContext.SERVLET_CONTEXT)).getAttribute("session");
		String token = (String)httpSession.getAttribute("token");
		if(null != userId && null != token && token.equals(httpSession.getId()+"_"+userId)){
			httpSession.removeAttribute("token");
			System.out.println("userId["+userId+"] log out success!");
			return true;
		}else{
			System.out.println("userId["+userId+"] log out fail!");
			return false;
		}
	}

	@Override
	public boolean checkLoginState(String userId){
		MessageContext msgContext = wsContext.getMessageContext();  
		HttpSession httpSession = (HttpSession)((ServletContext) msgContext.get(MessageContext.SERVLET_CONTEXT)).getAttribute("session");
		String token = (String)httpSession.getAttribute("token");
		return (null != userId && null != token && token.equals(httpSession.getId()+"_"+userId));
	}
	
}

@WebService  
public interface IFileTransfer {
	
	void uploadFile(String userId, FileInfo fileInfo);
	
	FileInfo downloadFile(String userId, FileInfo fileInfo);
	
}

@Repository
@WebService(endpointInterface = "net.log_cd.ws.IFileTransfer")
public class FileTransferImpl implements IFileTransfer{

	@Resource     
	private WebServiceContext wsContext;	
	
	@Resource
	private IUserLogin userLogin;	
	
	@Override
	public void uploadFile(String userId, FileInfo fileInfo) {
		if(!userLogin.checkLoginState(userId)){
			System.out.println("illegal operation!");
			return;
		}
		OutputStream os = null;
		try{
			if(fileInfo.getPosition() != 0){
				os = FileUtils.openOutputStream(new File(fileInfo.getServerFilePath()), true);
			}else{
				os = FileUtils.openOutputStream(new File(fileInfo.getServerFilePath()), false);
			}
			os.write(fileInfo.getBytes());
		}catch(Exception e){
			e.printStackTrace();
		}finally{
			IOUtils.closeQuietly(os);
		}
	}

	@Override
	public FileInfo downloadFile(String userId, FileInfo fileInfo) {
		if(!userLogin.checkLoginState(userId)){
			System.out.println("illegal operation!");
			return null;
		}		
		InputStream innputStrean = null;
		try{
			innputStrean = new FileInputStream(fileInfo.getServerFilePath());
			innputStrean.skip(fileInfo.getPosition());
			byte[] bytes = new byte[1024 * 1024];  
			int size = innputStrean.read(bytes);  
			if (size > 0) {
				byte[] fixedBytes = Arrays.copyOfRange(bytes, 0, size);  
				fileInfo.setBytes(fixedBytes);  
			} else {  
				fileInfo.setBytes(new byte[0]);  
			}  
		}catch(Exception e){
			e.printStackTrace();
		}finally{
			IOUtils.closeQuietly(innputStrean);  
		}
		return fileInfo;
	}
	
}

二、相关POJO
public class FileInfo {

	private String clientFilePath;

	private String serverFilePath;

	private long position;

	private byte[] bytes;

	public String getClientFilePath() {
		return clientFilePath;
	}

	public void setClientFilePath(String clientFilePath) {
		this.clientFilePath = clientFilePath;
	}

	public String getServerFilePath() {
		return serverFilePath;
	}

	public void setServerFilePath(String serverFilePath) {
		this.serverFilePath = serverFilePath;
	}

	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;
	}

}

三、发布WebService服务
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:jaxws="http://cxf.apache.org/jaxws"
	xmlns:context="http://www.springframework.org/schema/context"
	xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context-3.0.xsd
    http://cxf.apache.org/jaxws http://cxf.apache.org/schemas/jaxws.xsd">

	<import resource="classpath:META-INF/cxf/cxf.xml" />
	<import resource="classpath:META-INF/cxf/cxf-servlet.xml" />

	<context:component-scan base-package="net.log_cd.ws"/>
	
	<jaxws:endpoint id="userLoginWebService"
		implementor="#userLoginImpl" address="/userLogin" />	

	<jaxws:endpoint id="fileTransferWebService"
		implementor="#fileTransferImpl" address="/fileTransfer" />	
		
</beans>

四、客户端spring配置
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:jaxws="http://cxf.apache.org/jaxws"
	xmlns:context="http://www.springframework.org/schema/context"
	xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context-3.0.xsd
    http://cxf.apache.org/jaxws http://cxf.apache.org/schemas/jaxws.xsd">

	<context:component-scan base-package="com.log_cd.ws" />

	<!-- proxy factory schema -->
	<bean id="userLogin" class="net.log_cd.ws.IUserLogin"
		factory-bean="clientFactory" factory-method="create" />
	<bean id="clientFactory" class="org.apache.cxf.jaxws.JaxWsProxyFactoryBean">
		<property name="serviceClass" value="net.log_cd.ws.IUserLogin" />
		<property name="address"
			value="http://localhost:8080/cxf/ws/userLogin" />
	</bean>
	<!-- proxy factory schema -->

	<bean id="fileTransfer" class="net.log_cd.ws.IFileTransfer"
		factory-bean="clientFactory2" factory-method="create" />
	<bean id="clientFactory2" class="org.apache.cxf.jaxws.JaxWsProxyFactoryBean">
		<property name="serviceClass" value="net.log_cd.ws.IFileTransfer" />
		<property name="address"
			value="http://localhost:8080/cxf/ws/fileTransfer" />
	</bean>

</beans>

五、测试代码
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:cxf-ws-client.xml")
public class CXFWebServiceSessionTest extends AbstractJUnit4SpringContextTests {

	public static final String clientFilePath = "D:/test/test.jpg";
	public static final String serverFilePath = "D:/test/test_cp.jpg";
	public static final String userId = "log_cd";
	
	@Resource
	private IUserLogin userLogin;

	@Resource
	private IFileTransfer fileTransfer;

	@Test
	public void userLogin() {
		boolean bool = userLogin.login(userId, "85139999");
		System.out.println(bool);
		Assert.isTrue(bool);
	}

	@Ignore
	public void uploadFile() {
		InputStream inputStream = null;
		try {
			FileInfo fileInfo = new FileInfo();
			inputStream = new FileInputStream(clientFilePath);
			byte[] bytes = new byte[1024 * 1024];
			while (true) {
				int size = inputStream.read(bytes);
				if (size <= 0) {
					break;
				}
				byte[] fixedBytes = Arrays.copyOfRange(bytes, 0, size);
				fileInfo.setClientFilePath(clientFilePath);
				fileInfo.setServerFilePath(serverFilePath);
				fileInfo.setBytes(fixedBytes);

				fileTransfer.uploadFile(userId, fileInfo);
				fileInfo.setPosition(fileInfo.getPosition() + fixedBytes.length);
			}
		} catch (IOException e) {
			throw new RuntimeException(e.getMessage(), e);
		} finally {
			IOUtils.closeQuietly(inputStream);
		}
	}

	@Test
	public void downloadFile() {
		FileInfo fileInfo = new FileInfo();
		fileInfo.setServerFilePath(serverFilePath);
		long position = 0;
		while (true) {
			fileInfo.setPosition(position);
			fileInfo = fileTransfer.downloadFile(userId, fileInfo);
			if (fileInfo.getBytes().length <= 0) {
				break;
			}
			OutputStream outputStream = null;
			try {
				if (position != 0) {
					outputStream = FileUtils.openOutputStream(new File(clientFilePath),
							true);
				} else {
					outputStream = FileUtils.openOutputStream(new File(clientFilePath),
							false);
				}
				outputStream.write(fileInfo.getBytes());
			} catch (IOException e) {
				throw new RuntimeException(e.getMessage(), e);
			} finally {
				IOUtils.closeQuietly(outputStream);
			}
			position += fileInfo.getBytes().length;
		}
	}

	@Test
	public void userLogout() {
		boolean bool = userLogin.logout(userId);
		System.out.println(bool);
		Assert.isTrue(bool);
	}

}
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics