UpdateThread.java 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393
  1. package com.yihu.ehr.thread;
  2. import com.yihu.ehr.config.ThreadConfig;
  3. import com.yihu.ehr.dbhelper.jdbc.DBHelper;
  4. import com.yihu.ehr.util.Zipper;
  5. import com.yihu.ehr.util.http.HttpClientUtil;
  6. import com.yihu.ehr.util.http.HttpsClientUtil;
  7. import com.yihu.ehr.util.log.LogUtil;
  8. import org.apache.http.NameValuePair;
  9. import org.apache.http.message.BasicNameValuePair;
  10. import org.json.JSONObject;
  11. import org.springframework.util.StringUtils;
  12. import java.io.ByteArrayOutputStream;
  13. import java.io.File;
  14. import java.io.InputStream;
  15. import java.text.SimpleDateFormat;
  16. import java.util.*;
  17. /**
  18. * Created by chenweida on 2016/2/27.
  19. */
  20. public class UpdateThread implements Runnable {
  21. private String orgCode;
  22. private String systemCode;
  23. private int sleepTime = 60 * 1000;
  24. private DBHelper db = new DBHelper();
  25. private String resultString = "";
  26. private String versionName = "";
  27. private String versionCode = "";
  28. private String downloadPath = "";
  29. private String token;
  30. private boolean isStart = false;
  31. @Override
  32. public void run() {
  33. while (ThreadManage.updateIsRunning) {
  34. try {
  35. token = HttpsClientUtil.getToken();
  36. if (!StringUtils.isEmpty(token)) {
  37. //初始化参数
  38. initParam();
  39. LogUtil.info("-----------更新线程开始启动------------token:" + token);
  40. //判断是否需要更新
  41. if (isUpdate()) {
  42. LogUtil.info("有需要更新的任务");
  43. //得到更新的文件包
  44. String filePath = downLoadFile();
  45. LogUtil.info("更新包的路径是:" + filePath);
  46. //解压并且覆盖文件
  47. if (!StringUtils.isEmpty(filePath)) {
  48. //关闭服務
  49. closeService();
  50. //解压
  51. if (zipFile(filePath)) {
  52. //启动服务
  53. startService();
  54. //更新本地版本号
  55. updateVersion();
  56. //判断服务是否启动
  57. String message = "启动服務失败";
  58. if (isStart) {
  59. message = "启动服務成功";
  60. }
  61. //上传结果
  62. upLoagResult(message);
  63. }
  64. }
  65. } else {
  66. LogUtil.info("没有需要更新的任务");
  67. }
  68. }
  69. } catch (Exception e) {
  70. LogUtil.error("-----------更新线程执行失败------------失败原因:" + e.getMessage());
  71. } finally {
  72. //睡眠
  73. try {
  74. sleep();
  75. } catch (Exception e) {
  76. e.printStackTrace();
  77. }
  78. }
  79. }
  80. }
  81. private void updateVersion() {
  82. if (StringUtils.isEmpty(versionCode)) {
  83. versionCode = "1";
  84. }
  85. String sql = "update system_param set param_value='" + versionCode + "' where param_key='VERSION'";//UPDATE 表名称 SET 列名称 = 新值 WHERE 列名称 = 某值
  86. db.execute(sql);
  87. }
  88. private void upLoagResult(String isStart) {
  89. try {
  90. net.sf.json.JSONObject jo = net.sf.json.JSONObject.fromObject(resultString);
  91. // Map<String, Object> params = new HashMap<String, Object>();
  92. // params.put("systemCode", systemCode);
  93. // params.put("orgCode", orgCode);
  94. // params.put("versionName", versionName);
  95. // params.put("versionCode", versionCode);
  96. // params.put("updateDate", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
  97. // HttpClientUtil.doPost(ThreadConfig.SERVICE_URL + ThreadConfig.UPDATE_THREAD_GETUPDATEFLAG, params, ThreadConfig.SERVICE_USERNAME, ThreadConfig.SERVICE_PASSWORD);
  98. List<NameValuePair> formParams = new ArrayList<NameValuePair>();
  99. formParams.add(new BasicNameValuePair("systemCode", systemCode));
  100. formParams.add(new BasicNameValuePair("versionName", versionName));
  101. formParams.add(new BasicNameValuePair("versionCode", versionCode));
  102. formParams.add(new BasicNameValuePair("access_token", token));
  103. formParams.add(new BasicNameValuePair("message", isStart));
  104. formParams.add(new BasicNameValuePair("updateDate", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date())));
  105. formParams.add(new BasicNameValuePair("orgCode", orgCode));
  106. resultString = HttpsClientUtil.post(ThreadConfig.SERVICE_URL + ThreadConfig.UPDATE_THREAD_UPLOADRESULT, formParams, ThreadConfig.SERVICE_USERNAME, ThreadConfig.SERVICE_PASSWORD);
  107. LogUtil.info("上传结果成功");
  108. } catch (Exception e) {
  109. LogUtil.error("上传结果失败:" + e.getMessage());
  110. }
  111. }
  112. private void initParam() {
  113. if (StringUtils.isEmpty(orgCode) || StringUtils.isEmpty(systemCode)) {
  114. try {
  115. List<JSONObject> listORG = db.query("select * from system_param where param_key='ORG_CODE'");
  116. List<JSONObject> listSYSTEM = db.query("select * from system_param where param_key='SYSTEM_CODE'");
  117. if (listORG != null && listORG.size() > 0) {
  118. orgCode = listORG.get(0).getString("param_value");
  119. }
  120. if (listSYSTEM != null && listSYSTEM.size() > 0) {
  121. systemCode = listSYSTEM.get(0).getString("param_value");
  122. } else {
  123. String sql = "insert into system_param (id,param_key,param_value) values " +
  124. "('" + UUID.randomUUID() + "'," +
  125. " 'SYSTEM_CODE' ," +
  126. " '" + ThreadConfig.SYSTEM_CODE + "'" +
  127. ")";
  128. db.execute(sql);
  129. }
  130. } catch (Exception e) {
  131. LogUtil.error("初始化参数失败:" + e.getMessage());
  132. }
  133. }
  134. LogUtil.info("初始化参数成功orgCode:" + orgCode + "---systemCode:" + systemCode);
  135. }
  136. private void closeService() throws Exception {
  137. //C:\Windows\System32\UserAccountControlSettings.exe
  138. LogUtil.info("开始关闭服务");
  139. try {
  140. String system = System.getProperty("os.name").toLowerCase();
  141. if (system.contains("windows")) {
  142. LogUtil.info("关闭windows服务");
  143. //windows
  144. String batPathStop = UpdateThread.class.getResource("/").getPath() + "config/stop.bat";
  145. Process psStop = Runtime.getRuntime().exec(batPathStop);
  146. ByteArrayOutputStream baosStop = new ByteArrayOutputStream();
  147. InputStream osStop = psStop.getInputStream();
  148. byte bStop[] = new byte[256];
  149. while (osStop.read(bStop) > 0) {
  150. baosStop.write(bStop);
  151. }
  152. String sStop = baosStop.toString();
  153. osStop.close();
  154. baosStop.close();
  155. //判断是否服务是否关闭
  156. while (true) {
  157. String batPath = UpdateThread.class.getResource("/").getPath() + "config/serviceAlive.bat";
  158. Process ps = Runtime.getRuntime().exec(batPath);
  159. ByteArrayOutputStream baos = new ByteArrayOutputStream();
  160. InputStream os = ps.getInputStream();
  161. byte b[] = new byte[256];
  162. while (os.read(b) > 0) {
  163. baos.write(b);
  164. }
  165. String s = baos.toString();
  166. os.close();
  167. baos.close();
  168. if (!Boolean.valueOf(s.trim())) {
  169. break;
  170. }
  171. LogUtil.info("服务正在关闭");
  172. }
  173. Thread.sleep(1000L);
  174. } else {
  175. LogUtil.info("重启linux服务");
  176. Runtime.getRuntime().exec("service " + ThreadConfig.TOMCAT_SERVICENAME + " stop");
  177. Thread.sleep(6000L);
  178. }
  179. LogUtil.info("关闭成功");
  180. } catch (Exception e) {
  181. LogUtil.error("关闭失败:" + e.getMessage());
  182. }
  183. }
  184. private void startService() throws Exception {
  185. LogUtil.info("开始启动服务");
  186. try {
  187. String system = System.getProperty("os.name").toLowerCase();
  188. if (system.contains("windows")) {
  189. String batPathStart = UpdateThread.class.getResource("/").getPath() + "config/start.bat";
  190. LogUtil.info("启动windows服务:" + batPathStart);
  191. //windows
  192. Process psStart = Runtime.getRuntime().exec(batPathStart);
  193. ByteArrayOutputStream baosStart = new ByteArrayOutputStream();
  194. InputStream osStart = psStart.getInputStream();
  195. byte bStart[] = new byte[256];
  196. while (osStart.read(bStart) > 0) {
  197. baosStart.write(bStart);
  198. }
  199. osStart.close();
  200. baosStart.close();
  201. int i = 0;
  202. LogUtil.info("开始判断服务是否启动");
  203. while (true) {
  204. String batPath = UpdateThread.class.getResource("/").getPath() + "config/serviceAlive.bat";
  205. Process ps = Runtime.getRuntime().exec(batPath);
  206. ByteArrayOutputStream baos = new ByteArrayOutputStream();
  207. InputStream os = ps.getInputStream();
  208. byte b[] = new byte[256];
  209. while (os.read(b) > 0)
  210. baos.write(b);
  211. String s = baos.toString();
  212. os.close();
  213. baos.close();
  214. LogUtil.info("服务正在启动:" + Boolean.valueOf(s.trim()));
  215. if (Boolean.valueOf(s.trim())) {
  216. i++;
  217. if (i > 3) {
  218. isStart = true;
  219. LogUtil.info("服务启动成功");
  220. break;
  221. }
  222. }
  223. }
  224. } else {
  225. LogUtil.info("启动linux服务");
  226. Runtime.getRuntime().exec("service " + ThreadConfig.TOMCAT_SERVICENAME + " start");
  227. }
  228. LogUtil.info("启动成功");
  229. } catch (Exception e) {
  230. LogUtil.error("启动失败:" + e.getMessage());
  231. }
  232. }
  233. private boolean zipFile(String filePath) {
  234. try {
  235. String home = System.getProperty("catalina.home").replace('\\', '/');
  236. String url = home.substring(0, home.lastIndexOf('/') + 1) + "tomcat8-esb-ds/webapps";
  237. Zipper.unzipFile(new File(filePath.trim()), url);
  238. LogUtil.info("解压成功解压路径:" + url);
  239. return true;
  240. } catch (Exception e) {
  241. LogUtil.error("解压失败:" + e.getMessage());
  242. return false;
  243. }
  244. }
  245. private String downLoadFile() throws Exception {
  246. String path = null;
  247. try {
  248. //Map<String, Object> params = new HashMap<String, Object>();
  249. // params.put("systemCode", systemCode);
  250. // params.put("orgCode", orgCode);
  251. path = getFilePath();
  252. // HttpClientUtil.downFile(path, params, ThreadConfig.getURL(ThreadConfig.UPDATE_THREAD_DOWNUPDATEWAR), "", "");
  253. // Map<String, Object> params = new HashMap<String, Object>();
  254. // params.put("systemCode", systemCode);
  255. // params.put("orgCode", orgCode);
  256. // params.put("access_token", token);
  257. LogUtil.info("开始下载文件,文件下載地址在:" + ThreadConfig.SYSTEM_DOWNLOADPATH + downloadPath);
  258. // HttpClientUtil.downFile(path, new HashMap<String, Object>(), , "", "");
  259. HttpClientUtil.getFile(ThreadConfig.SYSTEM_DOWNLOADPATH + downloadPath, path);
  260. LogUtil.info("下载文件成功,文件保存目录:" + path);
  261. } catch (Exception e) {
  262. e.printStackTrace();
  263. LogUtil.error("下载文件失败:" + path + e.getMessage());
  264. return "";
  265. }
  266. return path;
  267. }
  268. private Boolean isUpdate() throws Exception {
  269. // Map<String, Object> params = new HashMap<String, Object>();
  270. // params.put("systemCode", systemCode);
  271. //params.put("versionCode", ThreadConfig.SOFT_VERSIONCODE);
  272. // params.put("orgCode", orgCode);
  273. // String returnString = "true";
  274. try {
  275. List<JSONObject> listSYSTEM = db.query("select * from system_param where param_key='VERSION'");
  276. if (listSYSTEM != null && listSYSTEM.size() > 0) {
  277. ThreadConfig.SOFT_VERSIONCODE = listSYSTEM.get(0).getString("param_value");
  278. } else {
  279. String sql = "insert into system_param (id,param_key,param_value) values " +
  280. "('" + UUID.randomUUID() + "'," +
  281. " 'VERSION' ," +
  282. " '1'" +
  283. ")";
  284. db.execute(sql);
  285. ThreadConfig.SOFT_VERSIONCODE = "1";
  286. }
  287. // resultString = HttpClientUtil.doPost(ThreadConfig.SERVICE_URL + ThreadConfig.UPDATE_THREAD_GETUPDATEFLAG, params, ThreadConfig.SERVICE_USERNAME, ThreadConfig.SERVICE_PASSWORD);
  288. Map<String, Object> params = new HashMap<String, Object>();
  289. params.put("systemCode", systemCode);
  290. params.put("orgCode", orgCode);
  291. params.put("versionCode", ThreadConfig.SOFT_VERSIONCODE);
  292. params.put("access_token", token);
  293. String path = ThreadConfig.SERVICE_URL + ThreadConfig.UPDATE_THREAD_GETUPDATEFLAG;//192.168.1.1:7070/getisupodate
  294. resultString = HttpsClientUtil.get(path, params, ThreadConfig.SERVICE_USERNAME, ThreadConfig.SERVICE_PASSWORD);
  295. //不需要更新返回空 需要更新返回版本号版本名称
  296. if (!StringUtils.isEmpty(resultString)) {
  297. net.sf.json.JSONObject jo = net.sf.json.JSONObject.fromObject(resultString);
  298. LogUtil.info("判断是否有需要更新的任务返回結果:" + resultString);
  299. versionName = String.valueOf(jo.get("versionName"));
  300. versionCode = String.valueOf(jo.get("versionCode"));
  301. downloadPath = String.valueOf(jo.get("file"));
  302. if (StringUtils.isEmpty(versionName)) {
  303. return false;
  304. }
  305. return true;
  306. } else {
  307. return false;
  308. }
  309. } catch (Exception e) {
  310. LogUtil.error("判断是否有需要更新的任务失败:" + e.getMessage());
  311. return false;
  312. }
  313. }
  314. private void sleep() throws Exception {
  315. LogUtil.info("更新线程开始睡眠,睡眠时间(分钟):" + ThreadConfig.UPDATE_THREAD_SLEEP_TIME);
  316. Thread.sleep(sleepTime * ThreadConfig.UPDATE_THREAD_SLEEP_TIME);
  317. }
  318. private String getFilePath() {
  319. SimpleDateFormat s = new SimpleDateFormat("yyyyMMddHHmmss");
  320. String home = System.getProperty("catalina.home").replace('\\', '/');
  321. //F:/{tomcat_home}/updateWar
  322. String fileName = s.format(new Date()).toString();
  323. // String fileName = "aaa";
  324. String folderPath = home + File.separator + "updateWar/";
  325. File file = new File(folderPath);
  326. //判断文件夹是否存在,如果不存在则创建文件夹
  327. if (!file.exists()) {
  328. file.mkdir();
  329. }
  330. return folderPath + fileName + ".war";
  331. }
  332. public static boolean getProcess() {
  333. boolean flag = false;
  334. try {
  335. Process p = Runtime.getRuntime().exec("cmd /c tasklist ");
  336. ByteArrayOutputStream baos = new ByteArrayOutputStream();
  337. InputStream os = p.getInputStream();
  338. byte b[] = new byte[256];
  339. while (os.read(b) > 0)
  340. baos.write(b);
  341. String s = baos.toString();
  342. if (s.indexOf("smss.exe") >= 0) {
  343. flag = true;
  344. } else {
  345. flag = false;
  346. }
  347. } catch (java.io.IOException ioe) {
  348. }
  349. return flag;
  350. }
  351. public static void main(String[] args) throws Exception {
  352. while (true) {
  353. String batPath = UpdateThread.class.getResource("/").getPath() + "config/serviceAlive.bat";
  354. System.out.println(batPath);
  355. Process ps = Runtime.getRuntime().exec(batPath);
  356. ByteArrayOutputStream baos = new ByteArrayOutputStream();
  357. InputStream os = ps.getInputStream();
  358. byte b[] = new byte[256];
  359. while (os.read(b) > 0)
  360. baos.write(b);
  361. String s = baos.toString();
  362. System.out.println(s);
  363. os.close();
  364. baos.close();
  365. if (Boolean.valueOf(s.trim())) {
  366. break;
  367. }
  368. }
  369. }
  370. }