package com.heaven.shopping.engine.impl.impl;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.json.JSONException;
import org.json.JSONObject;
import com.alibaba.fastjson.JSON;
import com.heaven.shopping.ConstantValue;
import com.heaven.shopping.bean.po.HelpPO;
import com.heaven.shopping.bean.vo.Help;
import com.heaven.shopping.dao.HelpDao;
import com.heaven.shopping.engine.HelpEngine;
import com.heaven.shopping.net.HttpClientAdapter;
import com.heaven.shopping.util.BeanFactory;
public class HelpEngineImpl implements HelpEngine {
@Override
public List<Help> getLocalHelp() {
List<Help> result = new ArrayList<Help>();
HelpDao helpDao = BeanFactory.getImpl(HelpDao.class);
List<HelpPO> findAll = helpDao.findAll();
for (HelpPO item : findAll) {
Help object = new Help();
object.setId(item.getId() + "");
object.setTitle(item.getTitle());
result.add(object);
}
return result;
}
@Override
public List<Help> getRemoteHelp() {
String version = "0";
// ①获取到version信息
HelpDao dao = BeanFactory.getImpl(HelpDao.class);
version = dao.getVersion();
// ②发送到服务器端
HttpClientAdapter adapter = new HttpClientAdapter();
Map<String, String> params = new HashMap<String, String>();
params.put("version", version);
String result = adapter.sendPost(ConstantValue.HOST + ConstantValue.HELP, params);
// ③服务器回复结果处理,Json数据解析
try {
JSONObject object = new JSONObject(result);
if (checkError(object)) {
String help = object.getString("help");
String sVersion = object.getString("version");
// ④如果从服务获取到了帮助信息,持久化到本地,开启子线程专门执行数据库的添加操作
List<Help> list = JSON.parseArray(help, Help.class);
for (Help item : list) {
// 如果BeanUtil
HelpPO helpPO = new HelpPO();
helpPO.setId(Long.parseLong(item.getId()));
helpPO.setTitle(item.getTitle());
helpPO.setVersion(sVersion);
dao.insert(helpPO);
}
return list;
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* 每一个请求回来都的判断
*
* @param object
* @return
*/
public boolean checkError(JSONObject object) {
return true;
}
}