Advertisement
tobaJK

AutoDatabaseBackUp

Sep 2nd, 2018
307
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 5.69 KB | None | 0 0
  1. package net.sf.l2j.melron;
  2.  
  3. import java.io.BufferedReader;
  4. import java.io.File;
  5. import java.io.FileInputStream;
  6. import java.io.FileOutputStream;
  7. import java.io.IOException;
  8. import java.io.InputStreamReader;
  9. import java.net.URL;
  10. import java.sql.Connection;
  11. import java.sql.PreparedStatement;
  12. import java.sql.ResultSet;
  13. import java.text.DateFormat;
  14. import java.text.SimpleDateFormat;
  15. import java.util.Date;
  16. import java.util.concurrent.TimeUnit;
  17. import java.util.zip.ZipEntry;
  18. import java.util.zip.ZipOutputStream;
  19.  
  20. import net.sf.l2j.commons.concurrent.ThreadPool;
  21.  
  22. import net.sf.l2j.L2DatabaseFactory;
  23.  
  24. public class BackupDBManager
  25. {
  26.     private static final String database_name = "";
  27.     private static final boolean DEBUG_SYSTEM = true;
  28.     private static final long initializeAfterTime = TimeUnit.MINUTES.toMillis(1);
  29.     private static final long checkEveryTime = TimeUnit.HOURS.toMillis(1);
  30.     private static final DateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy HH-mm-ss");
  31.    
  32.     protected BackupDBManager()
  33.     {
  34.         ThreadPool.scheduleAtFixedRate(() -> BackupDBToSql(), initializeAfterTime, checkEveryTime);
  35.         System.out.println("Database Backup Manager: Loaded. First load in " + TimeUnit.MILLISECONDS.toMinutes(checkEveryTime) + " Minutes. Delay every " + TimeUnit.MILLISECONDS.toHours(checkEveryTime) + " Hours.");
  36.     }
  37.    
  38.     public void BackupDBToSql()
  39.     {
  40.         String pathOfMysql = "\"";
  41.         try (Connection con = L2DatabaseFactory.getInstance().getConnection();
  42.             PreparedStatement st = con.prepareStatement("SELECT@@basedir"))
  43.         {
  44.             final ResultSet rs = st.executeQuery();
  45.             while (rs.next())
  46.             {
  47.                 pathOfMysql += rs.getString(1);
  48.             }
  49.             rs.close();
  50.         }
  51.         catch (Exception e)
  52.         {
  53.             e.printStackTrace();
  54.         }
  55.         if (pathOfMysql.isEmpty())
  56.         {
  57.             System.out.println("Error on backup database. Empty path of mysql.");
  58.             return;
  59.         }
  60.         // Give the specific path (pathOfMysql out = C:\Program Files\MySQL\MySQL Server 5.7\)
  61.         pathOfMysql += "bin\\mysqldump" + "\"";
  62.         if (DEBUG_SYSTEM)
  63.             System.out.println("Path of mysql: " + pathOfMysql);
  64.         try
  65.         {
  66.             final URL applicationRootPathURL = getClass().getProtectionDomain().getCodeSource().getLocation();
  67.             final File applicationRootPath = new File(applicationRootPathURL.getPath());
  68.             final File myFile = new File(applicationRootPath.getParent());
  69.             final File lastMyFile = new File(myFile.getParent());
  70.             final String dbUser = "your-user";
  71.             final String dbPass = "your-pass";
  72.             final String commandOfMysqlDump = " " + database_name + " --single-transaction -u" + dbUser + " -p" + dbPass + " --skip-create-options --skip-comments --disable-keys > ";
  73.             final String folderPath = "backup";
  74.             final File f1 = new File(folderPath);
  75.             f1.mkdir();
  76.             final String pathUntilDirectory = (lastMyFile.getAbsolutePath() + "\\backup\\").replaceAll("%20", " ");
  77.             final String savePath = ("\"" + pathUntilDirectory + "backup.sql\"").replaceAll("%20", " ");
  78.             final String commandToExecute = "cmd /c " + pathOfMysql + commandOfMysqlDump + savePath;
  79.             if (DEBUG_SYSTEM)
  80.             {
  81.                 System.out.println("Save path of sql file: " + savePath);
  82.                 System.out.println("Command To Execute: " + commandToExecute);
  83.             }
  84.             // Execute
  85.             final Process runtimeProcess = Runtime.getRuntime().exec(new String[]
  86.             {
  87.                 "cmd",
  88.                 "/c",
  89.                 commandToExecute
  90.             });
  91.             if (DEBUG_SYSTEM)
  92.             {
  93.                 final BufferedReader stdInput = new BufferedReader(new InputStreamReader(runtimeProcess.getInputStream()));
  94.                 final BufferedReader stdError = new BufferedReader(new InputStreamReader(runtimeProcess.getErrorStream()));
  95.                 System.out.println("Here is the standard output of the command:\n");
  96.                 String s = null;
  97.                 while ((s = stdInput.readLine()) != null)
  98.                 {
  99.                     System.out.println(s);
  100.                 }
  101.                 // read any errors from the attempted command
  102.                 System.out.println("Here is the standard error of the command (if any):\n");
  103.                 while ((s = stdError.readLine()) != null)
  104.                 {
  105.                     System.out.println(s);
  106.                 }
  107.             }
  108.             final int processComplete = runtimeProcess.waitFor();
  109.             /* NOTE: processComplete=0 if correctly executed, will contain other values if not */
  110.             if (processComplete == 0)
  111.             {
  112.                 System.out.println("Backup to SQL Complete");
  113.                 zipAFile(pathUntilDirectory);
  114.                 deleteAFile(savePath.replaceAll("\"", ""));
  115.             }
  116.             else
  117.             {
  118.                 System.out.println("Backup to SQL Failure");
  119.             }
  120.         }
  121.         catch (IOException | InterruptedException ex)
  122.         {
  123.             System.out.println("Error at Backuprestore" + ex.getMessage());
  124.         }
  125.     }
  126.    
  127.     private static void zipAFile(String pathToSave)
  128.     {
  129.         final byte[] buffer = new byte[1024];
  130.         try
  131.         {
  132.             final Date date = new Date();
  133.             final FileOutputStream fos = new FileOutputStream(pathToSave + "Backup_" + dateFormat.format(date) + ".zip");
  134.             final ZipOutputStream zos = new ZipOutputStream(fos);
  135.             final ZipEntry ze = new ZipEntry("backup.sql");
  136.             zos.putNextEntry(ze);
  137.             final FileInputStream in = new FileInputStream(pathToSave + "\\backup.sql");
  138.             int len;
  139.             while ((len = in.read(buffer)) > 0)
  140.             {
  141.                 zos.write(buffer, 0, len);
  142.             }
  143.             in.close();
  144.             zos.closeEntry();
  145.             zos.close();
  146.             System.out.println("Done the zip of backup.");
  147.         }
  148.         catch (IOException ex)
  149.         {
  150.             ex.printStackTrace();
  151.         }
  152.     }
  153.    
  154.     private static void deleteAFile(String path)
  155.     {
  156.         try
  157.         {
  158.             final File file = new File(path);
  159.             System.out.println(file.delete() ? (file.getName() + " is deleted!") : ("Delete operation is failed."));
  160.         }
  161.         catch (Exception e)
  162.         {
  163.             e.printStackTrace();
  164.         }
  165.     }
  166.    
  167.     public static BackupDBManager getInstance()
  168.     {
  169.         return SingletonHolder._instance;
  170.     }
  171.    
  172.     private static class SingletonHolder
  173.     {
  174.         protected static final BackupDBManager _instance = new BackupDBManager();
  175.     }
  176. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement