package com.manage.service.sys; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.manage.util.ConvertUtil; import com.manage.util.Dates; import org.apache.commons.io.FileUtils; import org.joda.time.DateTime; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Service; import org.springframework.util.ClassUtils; import org.springframework.web.multipart.MultipartFile; import org.springframework.web.multipart.MultipartHttpServletRequest; import org.springframework.web.multipart.commons.CommonsMultipartResolver; import javax.servlet.http.HttpServletRequest; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.util.Arrays; import java.util.Comparator; import java.util.Iterator; import java.util.List; import java.util.Map; /** * BackupService * * @author <a href="morse.jiang@foxmail.com">JiangWen</a> * @version 1.0.0, 2019/2/25 0025 13:58 */ @Service public class BackupService { @Value("${spring.datasource.username}") String username; @Value("${spring.datasource.password}") String password; @Value("${spring.datasource.port}") String port; @Value("${spring.datasource.host}") String host; @Value("${spring.datasource.database}") String database; static String backupFolder; static { backupFolder = ClassUtils.getDefaultClassLoader().getResource("").getPath(); int index1 = backupFolder.indexOf("/"); backupFolder = backupFolder.substring(index1); int index2 = backupFolder.indexOf(".jar"); if (index2 != -1) { backupFolder = backupFolder.substring(0, index2); int index3 = backupFolder.lastIndexOf("/"); backupFolder = backupFolder.substring(0, index3 + 1); } backupFolder = backupFolder + "backup"; File file = new File(backupFolder); if (!file.exists()) { file.mkdir(); } System.out.println("备份文件夹:" + backupFolder); } /** * 查看备份文件夹 * * @return */ private File exist() { File file = new File(backupFolder); if (!file.exists()) { file.mkdir(); } return file; } /** * 获取当前备份文件 * * @return */ public List<Map> getBackupFiles() throws Exception { File file = exist(); File[] fs = file.listFiles(); Arrays.sort(fs, new CompratorByLastModified()); List<Map> list = Lists.newArrayList(); for (int i = 0; i < fs.length; i++) { if (i >= 10) { fs[i].delete(); } else { Map<String, String> map = Maps.newHashMap(); map.put("name", fs[i].getName()); map.put("length", fs[i].length() / 1000.0 + "kb"); map.put("time", new DateTime(fs[i].lastModified()).toString(Dates.DATE_TIME_FORMATTER_PATTERN)); list.add(map); } } return list; } /** * 备份 * * @return * * @throws Exception */ public boolean backup() throws Exception { Process process = null; InputStream in = null; InputStreamReader isr = null; BufferedReader br = null; FileOutputStream fout = null; OutputStreamWriter writer = null; try { exist(); String filePath = backupFolder + "/"; String fileName = System.currentTimeMillis() + ".sql"; String cmd = "mysqldump -h " + host + " -P" + port + " -u" + username + " -p" + password + " " + database; process = Runtime.getRuntime().exec(cmd); in = process.getInputStream(); isr = new InputStreamReader(in, "utf-8"); String inStr; StringBuffer sb = new StringBuffer(""); String outStr; br = new BufferedReader(isr); while ((inStr = br.readLine()) != null) { sb.append(inStr + "\r\n"); } outStr = sb.toString(); fout = new FileOutputStream(filePath + fileName); writer = new OutputStreamWriter(fout, "utf-8"); writer.write(outStr); writer.flush(); in.close(); isr.close(); br.close(); writer.close(); fout.close(); return true; } catch (Exception e) { e.printStackTrace(); } finally { if (writer != null) { writer.close(); } if (fout != null) { fout.close(); } if (br != null) { br.close(); } if (isr != null) { isr.close(); } if (in != null) { in.close(); } if (process != null) { process.destroy(); } } return false; } /** * 备份恢复 * * @return * * @throws Exception */ public boolean recovery(Map<String, String> params) throws Exception { Process process = null; OutputStream os = null; BufferedReader br = null; OutputStreamWriter writer = null; try { String name = ConvertUtil.checkNotNull(params, "name", "文件名不能为空", String.class); String filePath = backupFolder + "/" + name; String cmd = "mysql -h " + host + " -P" + port + " -u" + username + " -p" + password + " " + database; process = Runtime.getRuntime().exec(cmd); os = process.getOutputStream(); br = new BufferedReader(new InputStreamReader(new FileInputStream(filePath),"utf-8")); String str = null; StringBuffer sb = new StringBuffer(); while ((str = br.readLine()) != null) { sb.append(str + "\r\n"); } str = sb.toString(); writer = new OutputStreamWriter(os, "utf-8"); writer.write(str); writer.flush(); os.close(); br.close(); writer.close(); return true; } catch (Exception e) { e.printStackTrace(); } finally { if (writer != null) { writer.close(); } if (br != null) { br.close(); } if (os != null) { os.close(); } if (process != null) { process.destroy(); } } return false; } /** * 上传备份文件 * * @throws Exception */ public void upload(HttpServletRequest request) throws Exception { CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext()); //检查form中是否有enctype="multipart/form-data" if (multipartResolver.isMultipart(request)) { MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request; //获取multiRequest 中所有的文件名 Iterator iter = multiRequest.getFileNames(); while (iter.hasNext()) { //一次遍历所有文件 MultipartFile file = multiRequest.getFile(iter.next().toString()); if (file != null) { exist(); String filePath = backupFolder + "/" + file.getOriginalFilename(); //上传 file.transferTo(new File(filePath)); } } } } /** * 下载 * * @param params * * @throws Exception */ public byte[] down(Map<String, String> params) throws Exception { String name = ConvertUtil.checkNotNull(params, "name", "文件名不能为空", String.class); File file = new File(backupFolder + "/" + name); return FileUtils.readFileToByteArray(file); } /** * 删除 * * @param params * * @throws Exception */ public void delete(Map<String, String> params) throws Exception { String name = ConvertUtil.checkNotNull(params, "name", "文件名不能为空", String.class); File file = new File(backupFolder + "/" + name); file.delete(); } /** * 排序 */ class CompratorByLastModified implements Comparator<File> { @Override public int compare(File f1, File f2) { long diff = f1.lastModified() - f2.lastModified(); if (diff > 0) { return -1; } else if (diff == 0) { return 0; } else { return 1; } } @Override public boolean equals(Object obj) { return true; } } }