将集合以数据流方式发送给servlet

发送端代码
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import base.GlobalCache;
import base.util.PropertiesTools;
import base.util.SpringFactoryUtils;
import cn.com.pubwin.police.old.po.Netbar;
import cn.com.pubwin.police.service.CacheService;

public class SendNetbarDataScheduler {


private Logger logger = LoggerFactory.getLogger(this.getClass());

private CacheService cacheService=(CacheService)SpringFactoryUtils.getInstance().getBean("cacheService");

private String curAreaCode = PropertiesTools.getConfigProperties("cur_area");

private String center_ip = PropertiesTools.getConfigProperties("center_ip");

public void sendNetbarEveryDay(){
OutputStream outputStream=null;
ObjectOutputStream oos=null;
try {
logger.info("每晚发送网吧数据开始......");
List<Netbar> list = new ArrayList<Netbar>();
List<Netbar> localeList = this.cacheService.getLocaleService().getNetbarListByAreaCode(1,curAreaCode);// 非经
if (!GlobalCache.getFlag()) {
logger.info("每晚同步往市局zk同步场所:网吧非经接收中心为不同库.开始更新网吧数据...");
List<Netbar> netbarList = this.cacheService.getLocaleService().getNetbarListByAreaCode(0,curAreaCode);// 网吧
list.addAll(netbarList);
}
list.addAll(localeList);//得到网吧数据

HttpURLConnection httpURLConnection;
URL gatewayUrl=new URL(center_ip+"/servlet/SyncAndCheckNetbarDataServlet?areaCode="+curAreaCode);
httpURLConnection = (HttpURLConnection)gatewayUrl.openConnection();

httpURLConnection.setDoOutput(true);
httpURLConnection.setRequestMethod("POST");

httpURLConnection.setRequestProperty("Content-Type", "application/octet-stream");
outputStream=httpURLConnection.getOutputStream();
oos=new ObjectOutputStream(outputStream);
oos.writeObject(list);
oos.flush();
oos.close();
outputStream.flush();
outputStream.close();
int responseCode=httpURLConnection.getResponseCode();
if(HttpURLConnection.HTTP_OK==responseCode){
System.out.println("收到市局发送成功回馈");
}
logger.info("每晚发送网吧数据完成!!");
} catch (Exception e) {
logger.error("每晚发送网吧数据失败:",e);
}finally{

}
}
}



接收端代码

import java.io.BufferedWriter;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


import javax.persistence.Column;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


import base.GlobalCache;
import base.util.DateUtil;
import base.util.PropertiesTools;
import base.util.SpringFactoryUtils;
import base.util.StringUtils;
import cn.com.pubwin.police.old.po.Netbar;
import cn.com.pubwin.police.service.NetbarService;


public class SyncAndCheckNetbarDataServlet extends HttpServlet {


private Logger logger = LoggerFactory.getLogger(this.getClass());

public static String netbarLogPath = PropertiesTools.getConfigProperties("netbarLogPath");

private NetbarService netbarService=(NetbarService)SpringFactoryUtils.getInstance().getBean("netbarService");



public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request,response);
}

public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
DataInputStream in=null;
ObjectInputStream ois=null;
BufferedWriter writeOut=null;
try {
// 从流中传上来的场所数据接口
in = new DataInputStream((InputStream) request.getInputStream());
ois = new ObjectInputStream(in);
List<Netbar> list=(List<Netbar>) ois.readObject();
in.close();
ois.close();
Map<String, Netbar> areaNetbarMap = this.getNetbarForMap(list);
// 从流中穿上来的当前区域
String areaCode = request.getParameter("areaCode");
// 从市局的数据库中得到当前区域的场所对象
Map<String, Netbar> netbarMap = this.getNetbarForMap(netbarService.getNetbarByAreaCode(areaCode));// 从数据中得到请求区域的netbar
List<Netbar> insertList = new ArrayList<Netbar>();
Map<String, Map<String, String>> updateMap = new HashMap<String, Map<String, String>>();
List<Netbar> deleteList = new ArrayList<Netbar>();
for (String serviceCode : netbarMap.keySet()) {
Netbar cityNetbar = netbarMap.get(serviceCode);
// 判断市局的场所是否在分局存在,存在比对数据值是否变更
if (areaNetbarMap.containsKey(serviceCode)) {
Map<String, String> map = isequalsNetbar(cityNetbar, areaNetbarMap.get(serviceCode));
// map若不为空,表示此场所,分局有改动,标记为修改场所,放入修改集合中
if (map != null && map.size() > 0) {
updateMap.put(serviceCode, map);
}
// 把市局分局都存在的场所从分局集合中删掉
areaNetbarMap.remove(serviceCode);
} else {
// 不存在,把此对象记录在deleteList中
deleteList.add(cityNetbar);
}
}
// 市局场所map循环完后,分局场所map由于remove,仅剩下市局不存在的场所,即新增场所
insertList.addAll(areaNetbarMap.values());
// TODO 把insert,delete,update集合写入日志文件

if(insertList.size()==0&&updateMap.size()==0&&deleteList.size()==0){
return;
}
String path = netbarLogPath+File.separator;
File file = new File(path);
if (!file.exists()) {
file.mkdirs();
}
file=new File(path+DateUtil.formatDate(new Date(), "yyyy-MM-dd")+".log");
writeOut=new BufferedWriter(new FileWriter(file,true));
writeOut.newLine();
writeOut.newLine();
writeOut.write("*********"+GlobalCache.areaMap.get(areaCode).getAreaName()+"("+areaCode+")需要更新记录如下*********");
writeOut.newLine();
writeOut.newLine();
if(insertList.size()>0){
writeOut.write("需要增加的netbar");
writeOut.newLine();
for (Netbar netbar : i
}
}
if(deleteList.size()>0){
writeOut.newLine();
writeOut.write("需要删除的netbar");
writeOut.newLine();
for(Netbar netbar : deleteList){
writeOut.write("delete from IMC.NETBAR where SERVICE_CODE='"+netbar.getServiceCode()+"'");
writeOut.newLine();
}
}
if(updateMap.size()>0){
writeOut.newLine();
writeOut.write("需要修改的netbar");
writeOut.newLine();
StringBuffer updateStr=new StringBuffer("");
for(String key : updateMap.keySet()){
Map<String, String> update=updateMap.get(key);
updateStr.delete(0, updateStr.length());//清空stringBuffer
for(String keyChild : update.keySet()){
updateStr.append(keyChild+"='"+update.get(keyChild)+"' , ");
}
String updateContent=updateStr.toString().substring(0, updateStr.lastIndexOf(" , "));
writeOut.write("update IMC.NETBAR set "+updateContent+" where SERVICE_CODE='"+key+"'");
writeOut.newLine();
}
}
writeOut.newLine();
writeOut.write("-----------------------------------------------------------------------------------------------");
writeOut.newLine();
writeOut.write("-----------------------------------------------------------------------------------------------");
writeOut.newLine();
writeOut.write("-----------------------------------------------------------------------------------------------");
writeOut.newLine();
writeOut.close();
response.setStatus(200);// 反馈给市局接受成功
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
in.close();
ois.close();
writeOut.close();
}
}

//用到反射机制判断记录是否有修改
private Map<String, String> isequalsNetbar(Netbar netbar1, Netbar netbar2) {
try {
Map<String, String> map = new HashMap<String, String>();
Field[] fieldArr = Netbar.class.getDeclaredFields();
for (Field field : fieldArr) {
String fieldName = field.getName();
if (field.getAnnotation(Column.class) != null) {
String beanid = field.getAnnotation(Column.class).name();
if (!StringUtils.isEmpty(beanid)) {
String meName = "get" + fieldName.substring(0, 1).toUpperCase()
+ fieldName.substring(1, fieldName.length());
if (fieldName.equalsIgnoreCase("ID")) {
continue;
}
Method m = Netbar.class.getDeclaredMethod(meName);
Object cVal1 = m.invoke(netbar1);
Object cVal2 = m.invoke(netbar2);
if (cVal1==null&&cVal2==null) {
continue;
}else if(cVal1==null||cVal2==null){
map.put(beanid, null);
}else if(cVal1.toString().equals(cVal2.toString())){
continue;
} else {
map.put(beanid, cVal2.toString());
}
}
}
}
if (map.size() > 0) {
return map;
}
} catch (Exception e) {
logger.error(e.getMessage(), e);
}
return null;
}

public Map<String, Netbar> getNetbarForMap(List<Netbar> netbarList) {
if (netbarList != null) {
Map<String, Netbar> netbarMap = new HashMap<String, Netbar>();
for (Netbar netbar : netbarList) {
netbarMap.put(netbar.getServiceCode(), netbar);
}
return netbarMap;
} else {
return null;
}
}


}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值