WebService之CXF使用Session

[b]一、接口与实现[/b]

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

}

[b]二、相关POJO[/b]

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

}

[b]三、发布WebService服务[/b]

<?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>

[b]四、客户端spring配置[/b]

<?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>

[b]五、测试代码[/b]

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

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值