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 params = new HashMap(); // 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 formParams = new ArrayList(); 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 listORG = db.query("select * from system_param where param_key='ORG_CODE'"); List 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 params = new HashMap(); // params.put("systemCode", systemCode); // params.put("orgCode", orgCode); path = getFilePath(); // HttpClientUtil.downFile(path, params, ThreadConfig.getURL(ThreadConfig.UPDATE_THREAD_DOWNUPDATEWAR), "", ""); // Map params = new HashMap(); // params.put("systemCode", systemCode); // params.put("orgCode", orgCode); // params.put("access_token", token); LogUtil.info("开始下载文件,文件下載地址在:" + ThreadConfig.SYSTEM_DOWNLOADPATH + downloadPath); // HttpClientUtil.downFile(path, new HashMap(), , "", ""); 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 params = new HashMap(); // params.put("systemCode", systemCode); //params.put("versionCode", ThreadConfig.SOFT_VERSIONCODE); // params.put("orgCode", orgCode); // String returnString = "true"; try { List 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 params = new HashMap(); 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; } } } }