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