Monday, January 10, 2011

How to select file types in a File Chooser window (Java SWING)

The below tutorial explains how to select some particular file formats (like .jpg, .doc, .cer etc.) in the File Chooser window using Java SWING GUI. Detailed code snippets are interspersed along with the explanation.




First of all we need to have a JLabel, JTextField and JButton fields on the screen similar to the below screenshot. The JButton field is the button image with “…” text on it. Once you click the button, a popup window shows up to select the files (similar to the above screenshot). Whatever the User selects on the screen will be captured into the parent window’s JTextField (C:\Program Files\Common Files\Adobe\Updater6\AdobeUpdate.cer in the below example)


//JLabel:
JLabel certificatePath = new JLabel();
certificatePath.setText("Certificate Path");

//JTextField:
JTextField certificateDir = new JTextField(PropertyReader.get("certificateDir"));
certificateDir.setToolTipText("Location of the certificate file");

//JButton:
JButton browseCertificate = new JButton();
                                browseCertificate.setSize(24, 19);
                                browseCertificate.setPreferredSize(new java.awt.Dimension(24,19));
                                browseCertificate.setToolTipText("Browse and select the location of the cer file(ex: C:\\adobe.cer)");
                                browseCertificate.setText("...");
                                browseCertificate.addActionListener(new ActionListener() {
                                                public void actionPerformed(ActionEvent evt) {
                                                                browseCertificateActionPerformed(evt);
                                                }
                                });


In the above code, we added a listener that invokes a method on the click of the JButton. File selection filtering happens in the listener method.

I’m going to give a little explanation of the fields set in the listener method here. You can skip to the code directly if you just need a screen similar to the below image.

Java SWING provides a class called JFileChooser that allows us to set various properties on the ‘File Select’ popup.

  • The dialogTitle property shows the title on the popup window (“Select the certificate file” on the below screen)
  • The acceptAllFileFilterUsed Boolean is used to show the “All Files” value in the “Files of Type” dropdown. If the value is false, “All Files” option will not be shown.  (set to false on the below screen. Only *.cer value is shown)
  • The fileSelectionmode allows us to set the selection values to Files or Directories or both (set to Files only on the below screen)

To filter the files to show only some particular types of file Types, we create a new FileFilter class and override the two methods getDescription and accept.

  1. In the getDescription method, we return a String (something like “*.cer”). This value will be shown in the Files of Type dropdown.
  1. In the accept method, we write the logic to allow some particular file formats. For example, in the below code, we get the extension of the files using a utility method. If the extension equals “cer” we show it to the User. The important thing here is that we have to include the code if(f.isDirectory()){return true;} in the accept method. This will make sure that when we traverse across folders, we show the directories as well as the “cer” files. If we remove the isDirectory() block, we will not be able to traverse across folders.
Code snippets:
private void browseCertificateActionPerformed(ActionEvent evt) {

                JFileChooser fileChooser = new JFileChooser();
                fileChooser.setDialogTitle("Select the Certificate file");
                fileChooser.setAcceptAllFileFilterUsed(Boolean.FALSE);
                fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
               
                fileChooser.setFileFilter(new FileFilter() {
                                                @Override
                                                public String getDescription() {
                                                                return "*.cer";
                                                }
                                               
                                                @Override
                                                public boolean accept(File f) {
                                                                if (f.isDirectory()) {
                                                                                return true;
                                                                    }
                                                                String extension = getExtension(f);
                                                    if (extension != null) {
                                                                if (extension.equals("cer")) {
                                                                        return true;
                                                                } else {
                                                                    return false;
                                                                }
                                                    }

                                                    return false;
                                                }
                                });
               
                int selection = fileChooser.showDialog(null, "Select");
                if(selection == JFileChooser.APPROVE_OPTION) {
                                certificateDir.setText(fileChooser.getSelectedFile().getAbsolutePath());
                }

}//end of browseCertificateActionPerformed method

This is the utility method to find the extension of the file
/*
     * Get the extension of a file.
     */ 
    private static String getExtension(File f) {
        String ext = null;
        String s = f.getName();
        int i = s.lastIndexOf('.');

        if (i > 0 &&  i < s.length() - 1) {
            ext = s.substring(i+1).toLowerCase();
        }
        return ext;
    }

References/Links:
  1. http://download.oracle.com/javase/tutorial/uiswing/components/filechooser.html#filters


Tags: Java SWING File Chooser file formats types JFileChooser Basic tutorial popup running example code GUI

Schedule Jobs in Java using Quartz (Java Job scheduling tutorial)

How to schedule Jobs in Java using Quartz (Java Job scheduling tutorial)


This tutorial is intended for Users who are looking to automate job scheduling in Java using Quartz. For example, if you would like to run a particular Java program at a particular point of time and date (and at regular frequencies) automatically, you can use the Quartz API to achieve this.

I will provide a simple example that covers the basics of the Quartz API to perform the scheduling.

Quartz API has the following basic objects.

SchedulerFactory
Scheduler
JobDetail
Trigger.

If you are using Apache Maven,  just add the following dependency in your pom.xml

      
                           org.quartz-scheduler
                           quartz
                           1.8.4
      
If you are not using Maven(or don’t know what Maven is), download the Quartz API from www.quartzscheduler.org and include it in your application’s build path. Btw, I strongly recommend you to start using Maven for your projects if you haven’t already. Off topic, but it is a wonderful dependency management tool (among various other features)

The concept is that you create a Scheduler object using the SchedulerFactory (Factory pattern if you know what I mean. I will show the related code below). And then you create a JobDetail object(by assigning the job a name and a group). Finally, you create a Trigger object that tells the scheduler on when to run the Job.

The trigger schedule can be set using CRON. If you are not sure what CRON is, it is just a expression (which is essentially a string) that tells the second/minute/hour/day of month/month/day of week/year in a regex format. The first 6 fields are mandatory and the last one(year) is optional.

A cron expression is a string comprised of 6 or 7 fields(explained above) separated by white space. Fields can contain any of the allowed values, along with various combinations of the allowed special characters for that field.

Just look at the following expression.

10 * * * * ?

This means that on the 10th second(1st field - 10)of every minute(2nd field - *) of every hour (3rd field - *)of every day(4th field - *)  of every month (5th field - *), the job will be run. The 6th field was marked as ? as there is no specific useful value for that. I mean if we are running the job everyday, there is no point in mentioning it to run on Sun/Mon/Tue etc. Also, if in another CRON expression we want to run on the 15th of every month and we don’t care what day of the week it is (Sun/Mon etc.), we can mark the 6th field as ?. I think you get the idea. The 7th field is the year, which is an optional field, which I haven’t used in the above expression. Another example:

0 0 0 1 1 ? *

On the 0th second of the 0th minute of the 0th hour of the 1st day of the 1st month of each year, do something. Like partying for a new year?

Ok, enough of CRON. There are a lot of other ways to use/customize CRON, which you can read in the related links at the end of the post.  Now back to the Quartz scheduler program.

Create a new Java class named QuartzTesting. This has to implement the Job interface, and thereby the execute method. Once the below program is run, the code in the execute method will be invoked at the regular frequency specified as per the CRON expression.
package com.abc.quartz.testing;

import java.text.ParseException;

import org.quartz.CronTrigger;
import org.quartz.Job;
import org.quartz.JobDetail;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.SchedulerFactory;
import org.quartz.impl.StdSchedulerFactory;

public class QuartzTesting implements Job{

                /** The sched fact. */
                private static SchedulerFactory schedFact = new StdSchedulerFactory();
               
                /** The sched. */
                private static Scheduler sched;
               
                static
                {
                                try {
                                                sched = schedFact.getScheduler();
                                } catch (SchedulerException e) {
                                                System.out.println("Exception in static block of QuartzTesting class, Exiting the program " +e);
                                                System.exit(-1);
                                }
                }

                /**
                 * @param args
                 */
                public static void main(String[] args) {
                               
                                try {
                                                //start the scheduler
                                                sched.start();

                                                //Create the JobDetail object and the CronTrigger
                                                JobDetail jobDetail = new JobDetail("Name",
                                                                                "Group", QuartzTesting.class);

                                                CronTrigger trigger = new CronTrigger("Name", "Group");
                                               
                                                //Set the CRON expression as per the desired frequency
                                                trigger.setCronExpression("*/10 * * * * ?");
                                               
                                                //schedule the job
                                                sched.scheduleJob(jobDetail, trigger);
                                } catch (SchedulerException e) {
                                                e.printStackTrace();
                                                System.exit(-1);
                                } catch (ParseException e) {
                                                e.printStackTrace();
                                                System.exit(-1);
                                }

                }

                public void execute(JobExecutionContext cntxt) throws JobExecutionException {

                                try {
                                                                //insert the code here that needs to be performed at the intervals scheduled using CRON trigger
                                                                //like making a Webservice call or running a report etc.
                                                                System.out.println("Running the code in the execute method");
                                                }
                                                                catch (Exception ex) {
                                                                                System.out.println(
                                                                                                                "Exception occured in execute method " +ex);
                                                                }
                                               
                                                }
}
Now, if you compile and run the above program, you will see a Java process running in your task manager. You should the Sysout at the intervals specified as per CRON (on the 10th  second of each minute in the above example. Please note that you see Sysouts every one minute and not every 10 seconds. If you want Sysouts every 10 seconds change the CRON expression to */10 * * * * ? )

If you were wondering what the name and Group are for the JobDetail/Trigger objects, they are used to identify the jobs if you have multiple jobs/triggers. In those multiple job scenarios, you can refer to the particular jobs using their names. Something like,

      //Delete if the job already exists and then schedule the job
                sched.deleteJob(“Sending Job”, “Send Group”);
References/Useful links:

  1. www.quartzscheduler.org
  2. http://oreilly.com/pub/a/java/archive/quartz.html?page=1
  3. http://www.quartz-scheduler.org/docs/tutorials/crontrigger.html

Tags: Java Job scheduling Quartz CRON trigger frequency timer regular intervals example basic tutorial

Sunday, January 9, 2011

Apache Maven Tutorial - Basic setup (Eclipse)

In this post, I will show how to setup Apache Maven in Eclipse and to run a basic program by using Maven.

First of all, what is Maven? In my own words, Maven is a project management, dependency management and build tool. I will explain it further a little bit.
Lets say in your organization, you have various teams and there is a possibility that each team might use the code written by other teams. If the code written for various projects by all the teams follow a particular folder structure/setup, it becomes really easy to build those projects and setup continuous integration etc.
Lets say Team A writes a java application and bundles it as a jar file. Team B writes a JEE application and bundles it as a war/ear file. Team C wants to reuse some methods and classes in Team A's jar file.

Team A sets up its project structure using Maven's standard folder structure. Example would be putting all the java classes in src/main/java folder. It would put all of its properties files under src/main/resources etc. And then there is pom.xml, which is the file that manages the project. This xml is the heart of each project and explains what other jar files are needed for building this project, how to package the code (as a jar/war etc.) and some other details.
In short, Team A creates a Maven project following the standard directory structure and creates a pom.xml. After finishing coding the java classes, there are some commands that can be invoked which read the xml and generate the jar/war file and install them in a repository somewhere.

Now Team C, also creates its own project by following the standard directory structure. Now, instead of writing the Utility classes again, it just adds the Project A's jar file as a dependency in it's(Project C's) pom.xml. So, when the build commands are invoked, Maven download's Project A's jar file from the repository so that Project C can use them(using imports in java classes).

Please note that the above example is just one aspect of Maven.

Ok, enough talk. Lets start with an example.

Im going to use eclipse for this tutorial. You can download eclipse from http://www.eclipse.org/downloads/

Download the latest version of Maven from http://maven.apache.org/download.html. Extract to a folder like C:\Maven

In Eclipse, install the Maven plugin:
Go to Help -> Install New Software and then Click on Add button and enter the following URL for the update site
http://m2eclipse.sonatype.org/installing-m2eclipse.html
Follow the instructions on the screen and finish the plugin installation

After the plugin is installed, in Eclipse, click on File -> New -> Maven -> Maven Project. Click on Next. On this page, select the first checkbox (Create a simple project). Click Next.
Enter the groupId, ArtifactId, Name, Descpription etc. GroupId is something like your organization name(enter abc), ArtifactId is something like a project name(enter Sample). Click Next and click Finish. Voila. You now have your first Maven project setup. The plugin automatically creates a lot of default folder using the standard maven directory structure.
If you look at the Project Explorer for the 'Sample' project, you can see src/main/java, src/main/resources, some other folders and target, pom.xml.
You can open pom.xml and look at the xml file. It contains the details that we provided during the project creation.

Now, let us create a simple java class in this project. In Package explore, right click on src/main/java folder and click on New -> Class. Enter a package name as code and class name as . SampleClass. Check the checkbox to create a main method. Click on Finish.

We now have the SampleClass.java that has the following code.
package code;
public class SampleClass {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated
}
}

Now, lets say in this class we want to do some functionality. Like copying the contents of a directory to another directory. Instead of writing the code to do the copy the contents, we will use Maven's ability to download the jar files that has the code to do the copying. For example, we know that the FileUtils class of the commons-io utility package provides a lot of File Utility functions. So, all we need to do is go to our pom.xml and add the following lines.
 
   org.apache.commons
   commons-io
   1.3.2
  
Add these between <dependencies> tags.

So, the contents of sample/pom.xml should be something like:


 4.0.0
 abc
 sample
 0.0.1-SNAPSHOT
 sample
 Sample project

 
  
   org.apache.commons
   commons-io
   1.3.2
  
 



Click on Project -> Build in Eclipse. On the console, you will see that a lot of jar files are downloaded from some repositories. You can find what all jars are downloaded by going to the location .m2\repository somewhere in your C drive(this default location is specified in settings.xml in your initially downloaded Maven zip file)

That's it! Now, you have the commons-io jar at your disposal !

Go to SampleClass.java and type FileUtils and press Ctrl+Space. This will automatically import the class org.apache.commons.io.FileUtils. Now you can use the methods in the FileUtils class


Add the code so that the java class looks like below:
package code;

import java.io.File;
import java.io.IOException;

import org.apache.commons.io.FileUtils;

public class SampleClass {

/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
try {
File srcDir = new File("C:\\srcDir");
File destDir = new File("C:\\destDir");

FileUtils.copyDirectory(srcDir, destDir);
} catch (IOException e) {
e.printStackTrace();
}

}

}


Save, build and run the Java class using Run -> Run as Java application (You can change the srcDir, destDir paths in the java class to match your folders)

You have used Apache's FileUtils class just by adding the dependency in your pom.xml file.

If I get enough feedback, I will write more tutorials on how to use Maven to install/package your projects and how to use repositories and continuous integrations.

Hopefully, the above simple example will initiate some interest in using Maven for your projects.


References and useful links:

http://maven.apache.org/guides/getting-started/index.html