martes, 27 marzo 2007

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

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

jueves, 22 marzo 2007

Choosing a printer programmatically in Jasper Reports

Jasper Reports is in my opinion by far the best report engine available for Java, even more, it's open source! In the project page there is enough information available to build simple and some advanced reports. If you need more help you can buy some guides at the project's owner commercial page JasperSoft There is also technical support available to be purchased.

Today I'll show you how to choose a printer programmatically.

JasperPrint print = JasperFillManager.fillReport( this.class.getResource("/classpath/yourReport.jasper").getPath(), new HashMap(), new yourReportDataSource());
PrinterJob job = PrinterJob.getPrinterJob();
/* Create an array of PrintServices */
PrintService[] services = PrintServiceLookup.lookupPrintServices(null, null);
int selectedService = 0;
/* Scan found services to see if anyone suits our needs */
for(int i = 0; i < services.length;i++){
if(services[i].getName().toUpperCase().contains("Your printer's name")){
/*If the service is named as what we are querying we select it */
selectedService = i;
}
}
job.setPrintService(services[selectedService]);
PrintRequestAttributeSet printRequestAttributeSet = new HashPrintRequestAttributeSet();
MediaSizeName mediaSizeName = MediaSize.findMedia(4,4,MediaPrintableArea.INCH);
printRequestAttributeSet.add(mediaSizeName);
printRequestAttributeSet.add(new Copies(1));
JRPrintServiceExporter exporter;
exporter = new JRPrintServiceExporter();
exporter.setParameter(JRExporterParameter.JASPER_PRINT, print);
/* We set the selected service and pass it as a paramenter */
exporter.setParameter(JRPrintServiceExporterParameter.PRINT_SERVICE, services[selectedService]);
exporter.setParameter(JRPrintServiceExporterParameter.PRINT_SERVICE_ATTRIBUTE_SET, services[selectedService].getAttributes());
exporter.setParameter(JRPrintServiceExporterParameter.PRINT_REQUEST_ATTRIBUTE_SET, printRequestAttributeSet);
exporter.setParameter(JRPrintServiceExporterParameter.DISPLAY_PAGE_DIALOG, Boolean.FALSE);
exporter.setParameter(JRPrintServiceExporterParameter.DISPLAY_PRINT_DIALOG, Boolean.TRUE);
exporter.exportReport();

In the above code you can see how to accomplish our purpose. The first part of all is generating our JasperPrint, this is common to all methods of report printing. Then comes the important part. First we look for the available printServices in the computer. Second, we scan the found services to see if there is anyone that suits our needs. Finally we set the selected print service in the exporter.

You will also find methods to choose the paper output and the number of copies to print.

Technorati Tags:

Posted by admin at 9:02 AM in Jasper Reports

martes, 20 marzo 2007

JVM for Windows Mobile (J2ME) // PocketPC - PDA

If you've ever tried to run a java program with your windows mobile device you'll be aware its one of the most difficult tasks. Sun doesn't officially support windows mobile devices, so you must go to a third party solution.

Why hasn't Sun released an official JVM for ARM pocket PC's? As you can read in the official Sun forum in the thread Open letter to SUN to produce a JRE for Pocket PC

...Unfortunately, since it's not an officially supported project at Sun (i.e. one that will generate enough revenue based on our projections to cover the costs) it is having problems getting out to the public..."

There is a great FAQ where you can find summarized everything about this issue Java on PocketPC (Unofficial FAQ).

Available JVM's

Java Support on Pocket PC This URL forwards you to an old comparison chart where you can find a summarized list of the java available options for Pocket Pc's.

There are many commercial and non commercial non-official JVM's for pocket pc. Most of them have the common problem of needing too much memory to run and implementing very old java profiles.

IBM WebSphere Everyplace Micro Environment

This is a commercial JVM developed by IBM. You can buy licenses online for about $5. There are also trial versions avaialble at IBM for you to try.

As you can read in the IBM site, the JVM features J2ME support for the Connected, Limited Device Configuration (CLDC 1.0 and 1.1) and Mobile Information Device Profile (MIDP 2.0) and for the Connected Device Configuration (CDC 1.0_01), Foundation Profile, and Personal Profile.

Summarizing, IBM solution is a cheap way to implement java in your pocket pc, and enable it to run smartphone software.

Mysaifu JVM

MySaifu is a GPL'd licensed Java virtual machine which runs on Windows Mobile OS's. Currently you can find compiled versions for:

  • Windows Mobile 5.0

  • Windows Mobile 2003 Second Edition software for Pocket PC (Pocket PC 2003 SE)

  • Windows Mobile 2003 software for Pocket PC (Pocket PC 2003)

This is my personal favorite solution. Apart from being free, it isn't a memory expensive solution and you can run java 1.3 applications, including support for AWT.

MySaifu Sample ScreenShotMySaifu Sample ScreenShot

These are two screenshots of sample applications running on PocketPC using MySaifu JVM. As you can see there is complete support for AWT components which can be easily extended to support better graphic options.

The Rest

As far as I'm concerned the rest of JVM options have been abandoned long ago and are very outdated. Other than that, most of them are commercial versions and much worse than the IBM solution. So if you want to implement java applications in your pocket PC my recommendation is either to use IBM webSphere if what you want is the J2ME standard or MySaifu if you prefer to run J2SE programs.

Technorati Tags:

Posted by admin at 8:01 AM in Java

jueves, 15 marzo 2007

Remove JTable's Enter Key behavior

When you press the Enter key while in a JTable, you'll notice how the row selection changes to the next row or to the first row if the former row selected was the last row in the model. You can change this playing with the traversal key policy, but this is quite complicated.

The easy way is to consume the event if the enter key has been pressed. You can accomplish this doing the following:

JTable jMyTable = new JTable();
jMyTable.addKeyListener(new java.awt.event.KeyAdapter() {
     public void keyPressed(java.awt.event.KeyEvent evt) {
         jMyTableKeyPressed(evt);
     }
});
private void jMyTableKeyPressed(java.awt.event.KeyEvent evt) {
     if(evt.getKeyCode() == evt.VK_ENTER){
         evt.consume();
     }
}

It's very important to consume the event during the keyPressed event and not during the other possible keyEvents not doing so will mean that you will consume the event once it's been triggered, so the Enter key will continue advancing one row.

Technorati Tags:

Posted by admin at 2:38 PM in Java

JTable Alternate Row Background

Java tables are great but complex. The good thing about them is that you can do with them whatever you want. Even more, the view is completely separated from the model so you can even play more.

JTables in brief (bad thing) are just a bunch of components put together. So anything you can de to a Component you can do in a JTable.

To make a JTable render each row in a different color, you just have to extend the JTable's prepareRender method.

JTable table = new JTable(){
    public Component prepareRenderer(TableCellRenderer renderer, int row, int column){
        Component returnComp = super.prepareRenderer(renderer, row, column);
        Color alternateColor = new Color(252,242,206);
        Color whiteColor = Color.WHITE;
        if (!returnComp.getBackground().equals(getSelectionBackground())){
            Color bg = (row % 2 == 0 ? alternateColor : whiteColor);
            returnComp .setBackground(bg);
            bg = null;
        }
        return returnComp;
};

JTableAlteranteRowColor

The above code simply gets the component that was going to be rendered and changes its background so that it fits the user needs. Here we've just set the background using two alternate colors, but there are many more things you can do, just use your imagination. Try using getModel(row, column) to get the values of what the cell contains and make the component behave depending on the values it contains.

Technorati Tags:

Posted by admin at 10:24 AM in Java

miércoles, 14 marzo 2007

Blojsom setup finished

This is my first real post after finishing the blojsom setup.

It wasn't the easiest process but the results are quite good.

Before choosing Blojsom as the weblog engine I looked at the several alternatives such as Apache roller or Pebble. I finally decided to choose Blojsom because it had an easy install and had support for PostgreSQL.

Apache Roller has some more features and is part of the Apache foundation group. But it has a much more complex setup process and has lots of dependencies. Pebble instead is too light weight and doesn't suffice the requirements for this blog.

Blojsom setup Process:

  1. Download Blojsom
  2. Setup the Blojsom database in PostgreSQL (Just need to create the database and the user)
  3. Upload the war file to the webapp server.
  4. Complete the setup process by editing two configuration files and creating the administrator user.
  5. Blog customization. This was the hardest part of all. There's not much documentation available. And the old themes (there are quite a few and very good ones) aren't compatible with blojsom 3.1.

All in all I must say that I'm quite happy with this piece of software.

Posted by admin at 4:39 PM in Blojsom

martes, 13 marzo 2007

Hello World

This is the first and not very original entry in the blog, just for testing purposes.

/** JUST TESTING **/

Posted by admin at 4:00 PM in Uncategorised

Google
 
« March »
SunMonTueWedThuFriSat
    123
45678910
11121314151617
18192021222324
25262728293031