123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393 |
- package com.yihu.ehr.thread;
- import com.yihu.ehr.config.ThreadConfig;
- import com.yihu.ehr.dbhelper.jdbc.DBHelper;
- import com.yihu.ehr.util.Zipper;
- import com.yihu.ehr.util.http.HttpClientUtil;
- import com.yihu.ehr.util.http.HttpsClientUtil;
- import com.yihu.ehr.util.log.LogUtil;
- import org.apache.http.NameValuePair;
- import org.apache.http.message.BasicNameValuePair;
- import org.json.JSONObject;
- import org.springframework.util.StringUtils;
- import java.io.ByteArrayOutputStream;
- import java.io.File;
- import java.io.InputStream;
- import java.text.SimpleDateFormat;
- import java.util.*;
- /**
- * Created by chenweida on 2016/2/27.
- */
- public class UpdateThread implements Runnable {
- private String orgCode;
- private String systemCode;
- private int sleepTime = 60 * 1000;
- private DBHelper db = new DBHelper();
- private String resultString = "";
- private String versionName = "";
- private String versionCode = "";
- private String downloadPath = "";
- private String token;
- private boolean isStart = false;
- @Override
- public void run() {
- while (ThreadManage.updateIsRunning) {
- try {
- token = HttpsClientUtil.getToken();
- if (!StringUtils.isEmpty(token)) {
- //初始化参数
- initParam();
- LogUtil.info("-----------更新线程开始启动------------token:" + token);
- //判断是否需要更新
- if (isUpdate()) {
- LogUtil.info("有需要更新的任务");
- //得到更新的文件包
- String filePath = downLoadFile();
- LogUtil.info("更新包的路径是:" + filePath);
- //解压并且覆盖文件
- if (!StringUtils.isEmpty(filePath)) {
- //关闭服務
- closeService();
- //解压
- if (zipFile(filePath)) {
- //启动服务
- startService();
- //更新本地版本号
- updateVersion();
- //判断服务是否启动
- String message = "启动服務失败";
- if (isStart) {
- message = "启动服務成功";
- }
- //上传结果
- upLoagResult(message);
- }
- }
- } else {
- LogUtil.info("没有需要更新的任务");
- }
- }
- } catch (Exception e) {
- LogUtil.error("-----------更新线程执行失败------------失败原因:" + e.getMessage());
- } finally {
- //睡眠
- try {
- sleep();
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- }
- }
- private void updateVersion() {
- if (StringUtils.isEmpty(versionCode)) {
- versionCode = "1";
- }
- String sql = "update system_param set param_value='" + versionCode + "' where param_key='VERSION'";//UPDATE 表名称 SET 列名称 = 新值 WHERE 列名称 = 某值
- db.execute(sql);
- }
- private void upLoagResult(String isStart) {
- try {
- net.sf.json.JSONObject jo = net.sf.json.JSONObject.fromObject(resultString);
- // Map<String, Object> params = new HashMap<String, Object>();
- // params.put("systemCode", systemCode);
- // params.put("orgCode", orgCode);
- // params.put("versionName", versionName);
- // params.put("versionCode", versionCode);
- // params.put("updateDate", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
- // HttpClientUtil.doPost(ThreadConfig.SERVICE_URL + ThreadConfig.UPDATE_THREAD_GETUPDATEFLAG, params, ThreadConfig.SERVICE_USERNAME, ThreadConfig.SERVICE_PASSWORD);
- List<NameValuePair> formParams = new ArrayList<NameValuePair>();
- formParams.add(new BasicNameValuePair("systemCode", systemCode));
- formParams.add(new BasicNameValuePair("versionName", versionName));
- formParams.add(new BasicNameValuePair("versionCode", versionCode));
- formParams.add(new BasicNameValuePair("access_token", token));
- formParams.add(new BasicNameValuePair("message", isStart));
- formParams.add(new BasicNameValuePair("updateDate", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date())));
- formParams.add(new BasicNameValuePair("orgCode", orgCode));
- resultString = HttpsClientUtil.post(ThreadConfig.SERVICE_URL + ThreadConfig.UPDATE_THREAD_UPLOADRESULT, formParams, ThreadConfig.SERVICE_USERNAME, ThreadConfig.SERVICE_PASSWORD);
- LogUtil.info("上传结果成功");
- } catch (Exception e) {
- LogUtil.error("上传结果失败:" + e.getMessage());
- }
- }
- private void initParam() {
- if (StringUtils.isEmpty(orgCode) || StringUtils.isEmpty(systemCode)) {
- try {
- List<JSONObject> listORG = db.query("select * from system_param where param_key='ORG_CODE'");
- List<JSONObject> listSYSTEM = db.query("select * from system_param where param_key='SYSTEM_CODE'");
- if (listORG != null && listORG.size() > 0) {
- orgCode = listORG.get(0).getString("param_value");
- }
- if (listSYSTEM != null && listSYSTEM.size() > 0) {
- systemCode = listSYSTEM.get(0).getString("param_value");
- } else {
- String sql = "insert into system_param (id,param_key,param_value) values " +
- "('" + UUID.randomUUID() + "'," +
- " 'SYSTEM_CODE' ," +
- " '" + ThreadConfig.SYSTEM_CODE + "'" +
- ")";
- db.execute(sql);
- }
- } catch (Exception e) {
- LogUtil.error("初始化参数失败:" + e.getMessage());
- }
- }
- LogUtil.info("初始化参数成功orgCode:" + orgCode + "---systemCode:" + systemCode);
- }
- private void closeService() throws Exception {
- //C:\Windows\System32\UserAccountControlSettings.exe
- LogUtil.info("开始关闭服务");
- try {
- String system = System.getProperty("os.name").toLowerCase();
- if (system.contains("windows")) {
- LogUtil.info("关闭windows服务");
- //windows
- String batPathStop = UpdateThread.class.getResource("/").getPath() + "config/stop.bat";
- Process psStop = Runtime.getRuntime().exec(batPathStop);
- ByteArrayOutputStream baosStop = new ByteArrayOutputStream();
- InputStream osStop = psStop.getInputStream();
- byte bStop[] = new byte[256];
- while (osStop.read(bStop) > 0) {
- baosStop.write(bStop);
- }
- String sStop = baosStop.toString();
- osStop.close();
- baosStop.close();
- //判断是否服务是否关闭
- while (true) {
- String batPath = UpdateThread.class.getResource("/").getPath() + "config/serviceAlive.bat";
- Process ps = Runtime.getRuntime().exec(batPath);
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
- InputStream os = ps.getInputStream();
- byte b[] = new byte[256];
- while (os.read(b) > 0) {
- baos.write(b);
- }
- String s = baos.toString();
- os.close();
- baos.close();
- if (!Boolean.valueOf(s.trim())) {
- break;
- }
- LogUtil.info("服务正在关闭");
- }
- Thread.sleep(1000L);
- } else {
- LogUtil.info("重启linux服务");
- Runtime.getRuntime().exec("service " + ThreadConfig.TOMCAT_SERVICENAME + " stop");
- Thread.sleep(6000L);
- }
- LogUtil.info("关闭成功");
- } catch (Exception e) {
- LogUtil.error("关闭失败:" + e.getMessage());
- }
- }
- private void startService() throws Exception {
- LogUtil.info("开始启动服务");
- try {
- String system = System.getProperty("os.name").toLowerCase();
- if (system.contains("windows")) {
- String batPathStart = UpdateThread.class.getResource("/").getPath() + "config/start.bat";
- LogUtil.info("启动windows服务:" + batPathStart);
- //windows
- Process psStart = Runtime.getRuntime().exec(batPathStart);
- ByteArrayOutputStream baosStart = new ByteArrayOutputStream();
- InputStream osStart = psStart.getInputStream();
- byte bStart[] = new byte[256];
- while (osStart.read(bStart) > 0) {
- baosStart.write(bStart);
- }
- osStart.close();
- baosStart.close();
- int i = 0;
- LogUtil.info("开始判断服务是否启动");
- while (true) {
- String batPath = UpdateThread.class.getResource("/").getPath() + "config/serviceAlive.bat";
- Process ps = Runtime.getRuntime().exec(batPath);
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
- InputStream os = ps.getInputStream();
- byte b[] = new byte[256];
- while (os.read(b) > 0)
- baos.write(b);
- String s = baos.toString();
- os.close();
- baos.close();
- LogUtil.info("服务正在启动:" + Boolean.valueOf(s.trim()));
- if (Boolean.valueOf(s.trim())) {
- i++;
- if (i > 3) {
- isStart = true;
- LogUtil.info("服务启动成功");
- break;
- }
- }
- }
- } else {
- LogUtil.info("启动linux服务");
- Runtime.getRuntime().exec("service " + ThreadConfig.TOMCAT_SERVICENAME + " start");
- }
- LogUtil.info("启动成功");
- } catch (Exception e) {
- LogUtil.error("启动失败:" + e.getMessage());
- }
- }
- private boolean zipFile(String filePath) {
- try {
- String home = System.getProperty("catalina.home").replace('\\', '/');
- String url = home.substring(0, home.lastIndexOf('/') + 1) + "tomcat8-esb-ds/webapps";
- Zipper.unzipFile(new File(filePath.trim()), url);
- LogUtil.info("解压成功解压路径:" + url);
- return true;
- } catch (Exception e) {
- LogUtil.error("解压失败:" + e.getMessage());
- return false;
- }
- }
- private String downLoadFile() throws Exception {
- String path = null;
- try {
- //Map<String, Object> params = new HashMap<String, Object>();
- // params.put("systemCode", systemCode);
- // params.put("orgCode", orgCode);
- path = getFilePath();
- // HttpClientUtil.downFile(path, params, ThreadConfig.getURL(ThreadConfig.UPDATE_THREAD_DOWNUPDATEWAR), "", "");
- // Map<String, Object> params = new HashMap<String, Object>();
- // params.put("systemCode", systemCode);
- // params.put("orgCode", orgCode);
- // params.put("access_token", token);
- LogUtil.info("开始下载文件,文件下載地址在:" + ThreadConfig.SYSTEM_DOWNLOADPATH + downloadPath);
- // HttpClientUtil.downFile(path, new HashMap<String, Object>(), , "", "");
- HttpClientUtil.getFile(ThreadConfig.SYSTEM_DOWNLOADPATH + downloadPath, path);
- LogUtil.info("下载文件成功,文件保存目录:" + path);
- } catch (Exception e) {
- e.printStackTrace();
- LogUtil.error("下载文件失败:" + path + e.getMessage());
- return "";
- }
- return path;
- }
- private Boolean isUpdate() throws Exception {
- // Map<String, Object> params = new HashMap<String, Object>();
- // params.put("systemCode", systemCode);
- //params.put("versionCode", ThreadConfig.SOFT_VERSIONCODE);
- // params.put("orgCode", orgCode);
- // String returnString = "true";
- try {
- List<JSONObject> listSYSTEM = db.query("select * from system_param where param_key='VERSION'");
- if (listSYSTEM != null && listSYSTEM.size() > 0) {
- ThreadConfig.SOFT_VERSIONCODE = listSYSTEM.get(0).getString("param_value");
- } else {
- String sql = "insert into system_param (id,param_key,param_value) values " +
- "('" + UUID.randomUUID() + "'," +
- " 'VERSION' ," +
- " '1'" +
- ")";
- db.execute(sql);
- ThreadConfig.SOFT_VERSIONCODE = "1";
- }
- // resultString = HttpClientUtil.doPost(ThreadConfig.SERVICE_URL + ThreadConfig.UPDATE_THREAD_GETUPDATEFLAG, params, ThreadConfig.SERVICE_USERNAME, ThreadConfig.SERVICE_PASSWORD);
- Map<String, Object> params = new HashMap<String, Object>();
- params.put("systemCode", systemCode);
- params.put("orgCode", orgCode);
- params.put("versionCode", ThreadConfig.SOFT_VERSIONCODE);
- params.put("access_token", token);
- String path = ThreadConfig.SERVICE_URL + ThreadConfig.UPDATE_THREAD_GETUPDATEFLAG;//192.168.1.1:7070/getisupodate
- resultString = HttpsClientUtil.get(path, params, ThreadConfig.SERVICE_USERNAME, ThreadConfig.SERVICE_PASSWORD);
- //不需要更新返回空 需要更新返回版本号版本名称
- if (!StringUtils.isEmpty(resultString)) {
- net.sf.json.JSONObject jo = net.sf.json.JSONObject.fromObject(resultString);
- LogUtil.info("判断是否有需要更新的任务返回結果:" + resultString);
- versionName = String.valueOf(jo.get("versionName"));
- versionCode = String.valueOf(jo.get("versionCode"));
- downloadPath = String.valueOf(jo.get("file"));
- if (StringUtils.isEmpty(versionName)) {
- return false;
- }
- return true;
- } else {
- return false;
- }
- } catch (Exception e) {
- LogUtil.error("判断是否有需要更新的任务失败:" + e.getMessage());
- return false;
- }
- }
- private void sleep() throws Exception {
- LogUtil.info("更新线程开始睡眠,睡眠时间(分钟):" + ThreadConfig.UPDATE_THREAD_SLEEP_TIME);
- Thread.sleep(sleepTime * ThreadConfig.UPDATE_THREAD_SLEEP_TIME);
- }
- private String getFilePath() {
- SimpleDateFormat s = new SimpleDateFormat("yyyyMMddHHmmss");
- String home = System.getProperty("catalina.home").replace('\\', '/');
- //F:/{tomcat_home}/updateWar
- String fileName = s.format(new Date()).toString();
- // String fileName = "aaa";
- String folderPath = home + File.separator + "updateWar/";
- File file = new File(folderPath);
- //判断文件夹是否存在,如果不存在则创建文件夹
- if (!file.exists()) {
- file.mkdir();
- }
- return folderPath + fileName + ".war";
- }
- public static boolean getProcess() {
- boolean flag = false;
- try {
- Process p = Runtime.getRuntime().exec("cmd /c tasklist ");
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
- InputStream os = p.getInputStream();
- byte b[] = new byte[256];
- while (os.read(b) > 0)
- baos.write(b);
- String s = baos.toString();
- if (s.indexOf("smss.exe") >= 0) {
- flag = true;
- } else {
- flag = false;
- }
- } catch (java.io.IOException ioe) {
- }
- return flag;
- }
- public static void main(String[] args) throws Exception {
- while (true) {
- String batPath = UpdateThread.class.getResource("/").getPath() + "config/serviceAlive.bat";
- System.out.println(batPath);
- Process ps = Runtime.getRuntime().exec(batPath);
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
- InputStream os = ps.getInputStream();
- byte b[] = new byte[256];
- while (os.read(b) > 0)
- baos.write(b);
- String s = baos.toString();
- System.out.println(s);
- os.close();
- baos.close();
- if (Boolean.valueOf(s.trim())) {
- break;
- }
- }
- }
- }
|