martes, 27 marzo 2007

Java App for PostgreSQL scheduled backups using pg_dump (Windows only)

« Choosing a printer programmatically in Jasper Reports | Main | Displaying a jTable inside another jTable // JTable cellRenderer »

Today I'll show you an easy way to automate your database backup dumps with a java application that runs on the background. This simple app will generate a backup of your database and will name it with today's date. It's not really the java program interacting with the database, but the app interacting with the command line program pg_dump.

The thing is quite simple. First we generate a filename with today's date. Then we check if the file exists. Finally we call the pg_dump with the appropriate parameters and the backup is generated

public void backupPGSQL(){
        try{
    //We initialize some variables that we’ll be using
            Runtime r =Runtime.getRuntime();
    //Path to the place we store our backups
    String rutaCT = "C:\\BAKCUPS\\";
            //PostgreSQL variables
            String IP = "192.168.1.1"”;
            String user = "postgres";
            String dbase =  "yourDataBase";
            String password = "yourPassword";
            Process p;
            ProcessBuilder pb;
            InputStreamReader reader;
            BufferedReader buf_reader;
            String line;
            //We build a string with today’s date (This will be the backup’s filename)
                java.util.TimeZone zonah = java.util.TimeZone.getTimeZone("GMT+1");
                java.util.Calendar Calendario = java.util.GregorianCalendar.getInstance( zonah, new java.util.Locale("es"));
                java.text.SimpleDateFormat df = new java.text.SimpleDateFormat( "yyyyMMdd" );
                StringBuffer date = new StringBuffer();
                date.append(df.format(Calendario.getTime()));
               
            java.io.File file = new java.io.File(rutaCT);
            /*We test if the path to our programs exists*/
            if(file.exists()){
                 /*We then test if the file we’re going to generate exists too. If it exists we will delete it*/
                 StringBuffer fechafile = new StringBuffer();
                    fechafile.append(rutaCT);
                    fechafile.append(date.toString());
                    fechafile.append(".backup");
                 java.io.File ficherofile = new java.io.File(fechafile.toString());
                //Probamos a ver si existe ese Гєltimo dato
                   if(ficherofile.exists()){
                       //Lo Borramos
                       ficherofile.delete();
                   }

                r =Runtime.getRuntime();

                pb = new ProcessBuilder(rutaCT + "pg_dump.exe", "-f", fechafile.toString(), "-F", "c", "-Z", "9", "-v", "-o", "-h",IP, "-U", user, dbase);
                pb.environment().put("PGPASSWORD", password);
                pb.redirectErrorStream(true);
                p = pb.start();
                try{
                       InputStream is = p.getInputStream();
                       InputStreamReader isr = new InputStreamReader(is);
                       BufferedReader br = new BufferedReader(isr);
                       String ll;
                       while ((ll = br.readLine()) != null) {
                         System.out.println(ll);
                      }
                }
                catch (IOException e) {
                  System.out.println (e);
                  log("ERROR "+e.getMessage());
                }
            }
           
            }
        catch(IOException x)
            {
                System.err.println("Could not invoke browser, command=");
                System.err.println("Caught: " + x.getMessage());
            }
    }

To run the above programs you will need to have pg_dump.exe and the necessary dll files in the backups directory. We can also schedule the task to be run once a day so we can have a fresh backup every night.

/* We create a timer task*/
TimerTask bakcupTask = new TimerTask(){
        public void run(){
            backupPGSQL();
        }
};
/* We schedue the task to be run every 24 hours */
Timer time = new Timer();

time.scheduleAtFixedRate(bakcupTask, new Date(),1000*60*60*24);

/* Even better, we can schedule the task to be run every 24 hours at a fixed time. (remember to remove the above line if you prefer this method) */
        Calendar taskTime = Calendar.getInstance();
   /* We want the task to be run at 1 o’clock in the morning */
        taskTime.set(Calendar.HOUR_OF_DAY, 1);
        /* We clear the rest of the values for the calendar */
        taskTime.clear(Calendar.MINUTE);
        taskTime.clear(Calendar.SECOND);
        taskTime.clear(Calendar.MILLISECOND);
    /* If for whatever reason the time has already passed, we add another day to the count, so the task will start tomorrow */
        if(now.after(taskTime)){
            taskTime.add(Calendar.DAY_OF_YEAR, 1);
        }
        Date startingDate = taskTime.getTime();
        time.scheduleAtFixedRate(bakcupTask, startingDate, 1000*60*60*24);

Technorati Tags:

Posted by admin at 9:15 AM in Java

 

[Trackback URL for this entry]

Comment: Araz at mar, 19 ago 8:33 AM

Thank you very much..

Your comment:

(not displayed)
 

SCode

Please enter the code as seen in the image above to post your comment.

 
 

Live Comment Preview:

 
Google
 
« March »
SunMonTueWedThuFriSat
    123
45678910
11121314151617
18192021222324
25262728293031