package com.ibatis.struts;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import com.travelsky.newapp.common.log.Log;
import com.travelsky.newapp.common.log.LogFactory;
import com.travelsky.newapp.web.webstart.RetObject;
/**
* @author CFR
*
* TODO 用于对WEBSTART/APPLET返回对象的压缩支持
*/
public class ZipUtil {
static Log logger = LogFactory.getLog(ZipUtil.class);
public ZipUtil() {
super();
}
/**用于对返回对象的压缩输出,只用于前端是WEBSTART/APPLET的情况。
* @author CFR
* @param response response object
* @param obj return object used by swt
*/
public static void WriteGZIP(HttpServletResponse response, RetObject obj) {
response.setContentType("gzip");
byte[] b = writeCompressObject(obj);
try {
ServletOutputStream out = response.getOutputStream();
out.write(b);
out.flush();
out.close();
} catch (IOException e) {
logger.error("WriteZipObject:Error occured when write return object!"
+ e.getMessage(), e);
}
}
/**
* 将可序列化对象写入文件,该方法只供测试使用
* @author CFR
* @param obj 用于返回客户端的对象
*/
public static void WriteObj2File(RetObject obj) {
File f = new File("c:/object.obj");
try {
ByteArrayOutputStream o = new ByteArrayOutputStream();
FileOutputStream fos = new FileOutputStream(f);
ObjectOutputStream out = new ObjectOutputStream(fos);
out.writeObject(obj);
out.flush();
out.close();
} catch (FileNotFoundException e) {
System.out.println("dont write zip file");
e.printStackTrace();
} catch (IOException e) {
System.out.println("dont write zip file");
e.printStackTrace();
}
}
/**
* 将可序列化对象压缩后写入文件,该方法只供测试使用
* @author CFR
* @param obj 用于返回客户端的对象
*/
public static void WriteGZIP2File(RetObject obj)
{
byte[] data = writeCompressObject(obj);
if(data == null)
{
System.out.println("dont write zip file");
return;
}
File f = new File("c:/objectzip.obj");
try {
FileOutputStream fos = new FileOutputStream(f);
fos.write(data);
fos.flush();
fos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 将对象压缩后以二进制形式返回
* @author CFR
* @param obj 待压缩对象
*/
public static byte[] writeCompressObject(Object object_) {
byte[] data_ = null;
try {
// 建立字节数组输出流
ByteArrayOutputStream o = new ByteArrayOutputStream();
// 建立gzip压缩输出流
GZIPOutputStream gzout = new GZIPOutputStream(o);
// 建立对象序列化输出流
ObjectOutputStream out = new ObjectOutputStream(gzout);
out.writeObject(object_);
out.flush();
out.close();
gzout.close();
// 返回压缩字节流
data_ = o.toByteArray();
o.close();
} catch (IOException e) {
e.printStackTrace();
return null;
}
return (data_);
}
/**
* 将压缩二进制还原为对象
* @author CFR
* @param data_ 压缩过的二进制
*/
public static Object readCompressObject(byte[] data_) {
Object object_ = null;
try {
// 建立字节数组输入流
ByteArrayInputStream i = new ByteArrayInputStream(data_);
// 建立gzip解压输入流
GZIPInputStream gzin = new GZIPInputStream(i);
// 建立对象序列化输入流
ObjectInputStream in = new ObjectInputStream(gzin);
// 按制定类型还原对象
object_ = in.readObject();
i.close();
gzin.close();
in.close();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
System.out.println(e);
}
return (object_);
}
}
private void WriteObject(HttpServletRequest request,HttpServletResponse response, RetObject obj) {
/* write to file test*/
if(isNeedZip(request))
{
logger.info("begin write this object by zip:"+request.getRequestURL().toString());
//以下两个方法供测试使用
//ZipUtil.WriteObj2File(obj);
//ZipUtil.WriteGZIP2File(obj);
ZipUtil.WriteGZIP(response, obj);
return;
}
response.setContentType("application/octet-stream");
try {
ObjectOutputStream oos = new ObjectOutputStream(response
.getOutputStream());
oos.writeObject(obj);
oos.close();
} catch (Exception e) {
logger.error("WriteObject:Error occured when write return object!"
+ e.getMessage(), e);
}
}
private boolean isNeedZip(HttpServletRequest request)
{
String url = request.getRequestURL().toString();
int index= url.indexOf(NewappConst.ACTION_GETPSRLIET);
String iszip = GlobalConfig.getConfigNoNull(NewappConst.IS_ZIP);
if((index > 0)&&(iszip.equalsIgnoreCase("true")))
{
return true;
}
return false;
}
客户端:
/**
* @author CFR
* @param data_ 用GZIP压缩后的的二进制流
* @return 解压后重建的对象
*/
public static Object readCompressObject(byte[] data_) {
Object object_ = null;
try {
// 建立字节数组输入流
ByteArrayInputStream i = new ByteArrayInputStream(data_);
// 建立gzip解压输入流
GZIPInputStream gzin = new GZIPInputStream(i);
// 建立对象序列化输入流
ObjectInputStream in = new ObjectInputStream(gzin);
// 按制定类型还原对象
object_ = in.readObject();
i.close();
gzin.close();
in.close();
} catch (ClassNotFoundException e) {
Util.log(e);
return null;
} catch (IOException e) {
Util.log(e);
return null;
}
return (object_);
}
使用:
public static void ShowErrorMessage(String title, String message)
{
MessageBox messageBox = new MessageBox(shell, SWT.OK
| SWT.ERROR_FAILED_EXEC);
messageBox.setText(title);
messageBox.setMessage(message);
messageBox.open();
}
public static Object getObjectFromUrl(String url, String service,
String paramenter) {
String httpUrl = null;
RetObject retObj = null;
long start_t = System.currentTimeMillis();
try {
if (url.trim().length() > 1) {
httpUrl = "http://" + ServerAddr + ":" + String.valueOf(Port)
+ ContextPath + url + "/" + service + ".do?"
+ paramenter;//需要再检查
} else {
httpUrl = "http://" + ServerAddr + ":" + String.valueOf(Port)
+ ContextPath + "/" + service + ".do?" + paramenter;//需要再检查
}
Util.log("httpUrl=" + httpUrl);
//创建到服务器的连接
HttpURLConnection connect = (HttpURLConnection)(new URL(httpUrl)).openConnection();
connect.setUseCaches(false);
//设置会话标志
connect.setRequestProperty("Cookie", "JSESSIONID=" + SessionID);
//打开会话连接
connect.connect();
/*check http status*/
int code = connect.getResponseCode();
if(code >= 400)
{
ShowErrorMessage("http status error","http code:" + code + ","
+ connect.getResponseMessage()+"/nrequest:"+httpUrl);
Util.log("this request use time(failed,ms)" + (System.currentTimeMillis()-start_t));
return null;
}
/*add By CFR,用于对压缩数据的支持*/
String ContentType = connect.getContentType();
if(ContentType.equalsIgnoreCase(HttpUtil.GZIP_CONTENTTYPE))
{
Util.log("gzip content received!");
byte[] b = new byte[1024];
ByteArrayOutputStream o = new ByteArrayOutputStream();
InputStream in = connect.getInputStream();
int num = 0;
while((num = in.read(b,0,b.length)) != -1)
{
o.write(b, 0, num);
}
Util.log("gzip length:"+o.toByteArray().length);
retObj = (RetObject)readCompressObject(o.toByteArray());
Util.log("read zip obj ok!");
}
else
{
ObjectInputStream ois = new ObjectInputStream(connect
.getInputStream());
retObj = (RetObject) ois.readObject();
}
if(retObj == null)
{
ShowErrorMessage("error","error when get remote object!/nrequest:"+httpUrl);
Util.log("this request use time(failed,ms)" + (System.currentTimeMillis()-start_t));
return null;//或者返回一个其他的信息
}
if (retObj.getCode() != 0) {
//Util.log("[" + retObj.getCode() + "]" + retObj.getErrInfo());
ShowErrorMessage("error","[" + retObj.getCode() + "]"
+ retObj.getErrInfo()+"/nrequest:"+httpUrl);
Util.log("this request use time(failed,ms)" + (System.currentTimeMillis()-start_t));
return null;//或者返回一个其他的信息
}
ArrayList retList = retObj.getRetList();
Util.log("this request use time(ms)" + (System.currentTimeMillis()-start_t));
return retList;
} catch (MalformedURLException e2) {
ShowErrorMessage("Exception", e2.getMessage()+"/nrequest:"+httpUrl);
Util.log(e2);
} catch (Exception e1) {
ShowErrorMessage("Exception", e1.getMessage()+"/nrequest:"+httpUrl);
Util.log(e1);
}
Util.log("this request use time(failed,ms)" + (System.currentTimeMillis()-start_t));
return null;
}
public static Object sendMsgToSvr(String url, String service,
String paramenter) {
String httpUrl = null;
long start_t = System.currentTimeMillis();
try {
if (url.trim().length() > 1) {
httpUrl = "http://" + ServerAddr + ":" + String.valueOf(Port)
+ ContextPath + url + "/" + service + ".do?";//需要再检查
} else {
httpUrl = "http://" + ServerAddr + ":" + String.valueOf(Port)
+ ContextPath + "/" + service + ".do?";//需要再检查
}
Util.log("httpUrl=" + httpUrl + "Paramenter:" + paramenter);
//创建到服务器的连接
HttpURLConnection connect = (HttpURLConnection)(new URL(httpUrl)).openConnection();
//设置会话标志
connect.setRequestProperty("Cookie", "JSESSIONID=" + SessionID);
connect.setUseCaches(false);
connect.setDoOutput(true);
connect.setDoInput(true);
OutputStreamWriter out = new OutputStreamWriter(connect
.getOutputStream(), "8859_1");
String par = "xml=" + URIUtil.encodeWithinQuery(paramenter);
out.write(par);
out.flush();
out.close();
/*check http status*/
int code = connect.getResponseCode();
if(code >= 400)
{
ShowErrorMessage("http status error","http code:" + code + ","
+ connect.getResponseMessage()+"/nrequest:"+httpUrl);
Util.log("this request use time(failed,ms)" + (System.currentTimeMillis()-start_t));
return null;
}
//从会话连接中获取数据
ObjectInputStream ois = new ObjectInputStream(connect
.getInputStream());
RetObject retObj = (RetObject) ois.readObject();
if (retObj.getCode() != 0) {
ShowErrorMessage("error","[" + retObj.getCode() + "]"
+ retObj.getErrInfo()+"/nrequest:"+httpUrl);
Util.log("this request use time(failed,ms)" + (System.currentTimeMillis()-start_t));
return null;
}
ArrayList retList = retObj.getRetList();
Util.log("this request use time(ms)" + (System.currentTimeMillis()-start_t));
return retList;
} catch (MalformedURLException e2) {
ShowErrorMessage("Exception", e2.getMessage()+"/nrequest:"+httpUrl);
Util.log(e2);
} catch (Exception e1) {
ShowErrorMessage("Exception", e1.getMessage()+"/nrequest:"+httpUrl);
Util.log(e1);
}
Util.log("this request use time(failed,ms)" + (System.currentTimeMillis()-start_t));
return null;
}