Friday, May 25, 2012

JDK Timer scheduler example


JDK Timer is a simple scheduler for a specified task for repeated fixed-delay execution. To use this, you have to extends the TimerTask abstract class, override the run() method with your scheduler function.
RunMeTask.java
package com.mkyong.common;
 
import java.util.TimerTask;
 
public class RunMeTask extends TimerTask
{
 @Override
 public void run() {
  System.out.println("Run Me ~");
 }
}
Now, you can schedule it by calling the schedule() method of Timer.
public void schedule(TimerTask task,
                     long delay,
                     long period)
App.java
package com.mkyong.common;
 
import java.util.Timer;
import java.util.TimerTask;
 
public class App 
{
    public static void main( String[] args )
    {
 
     TimerTask task = new RunMeTask();
 
     Timer timer = new Timer();
     timer.schedule(task, 1000,60000);
 
    }
}
In this example, the timer will print the “Run Me ~” message every 60 seconds, with a 1 second delay for the first time of execution.

How to check if Date is within a certain range in Java?


import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
 
public class DateValidator {
 
 public boolean isThisDateWithin3MonthsRange(String dateToValidate,
   String dateFromat) {
 
  SimpleDateFormat sdf = new SimpleDateFormat(dateFromat);
  sdf.setLenient(false);
  try {
 
   // if not valid, it will throw ParseException
   Date date = sdf.parse(dateToValidate);
 
   // current date after 3 months
   Calendar currentDateAfter3Months = Calendar.getInstance();
   currentDateAfter3Months.add(Calendar.MONTH, 3);
 
   // current date before 3 months
   Calendar currentDateBefore3Months = Calendar.getInstance();
   currentDateBefore3Months.add(Calendar.MONTH, -3);
 
   /*************** verbose ***********************/
   System.out.println("\n\ncurrentDate : "
     + Calendar.getInstance().getTime());
   System.out.println("currentDateAfter3Months : "
     + currentDateAfter3Months.getTime());
   System.out.println("currentDateBefore3Months : "
     + currentDateBefore3Months.getTime());
   System.out.println("dateToValidate : " + dateToValidate);
   /************************************************/
 
   if (date.before(currentDateAfter3Months.getTime())
     && date.after(currentDateBefore3Months.getTime())) {
 
    //ok everything is fine, date in range
    return true;
 
   } else {
 
    return false;
 
   }
 
  } catch (ParseException e) {
 
   e.printStackTrace();
   return false;
  }
 
 }
 
}

Convert PNG to JPEG image file in Java


import java.awt.Color;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
 
public class ConvertImageFile {
 
   public static void main(String[] args) {
 
 BufferedImage bufferedImage;
 
 try {
 
   //read image file
   bufferedImage = ImageIO.read(new File("c:\\javanullpointer.png"));
 
   // create a blank, RGB, same width and height, and a white background
   BufferedImage newBufferedImage = new BufferedImage(bufferedImage.getWidth(),
   bufferedImage.getHeight(), BufferedImage.TYPE_INT_RGB);
   newBufferedImage.createGraphics().drawImage(bufferedImage, 0, 0, Color.WHITE, null);
 
   // write to jpeg file
   ImageIO.write(newBufferedImage, "jpg", new File("c:\\javanullpointer.jpg"));
 
   System.out.println("Done");
 
 } catch (IOException e) {
 
   e.printStackTrace();
 
 }
 
   }
 
}

Output

A new jpg file is generated, with white background.
File : javanullpointer.jpg, 9kb

How to assign file content into a variable in Java


Most people will read the file content and assign to StringBuffer or String line by line. Here’s another trick that may interest you – how to assign whole file content into a variable with one Java’s statement, try it :)

Example

In this example, you will use DataInputStreamto convert all the content into bytes, and create a String variable with the converted bytes.
package com.mkyong.io;
 
import java.io.DataInputStream;
import java.io.FileInputStream;
 
public class App{
 
 public static void main (String args[]) {
 
 try{
 
          DataInputStream dis = 
      new DataInputStream (
        new FileInputStream ("c:\\logging.log"));
 
   byte[] datainBytes = new byte[dis.available()];
   dis.readFully(datainBytes);
   dis.close();
 
   String content = new String(datainBytes, 0, datainBytes.length);
 
   System.out.println(content);
 
 }catch(Exception ex){
  ex.printStackTrace();
 }
 
  }
}

Output

This will print out all the “logging.log” file content.
10:21:29,425  INFO Version:15 - Hibernate Annotations 3.3.0.GA
10:21:29,441  INFO Environment:509 - Hibernate 3.2.3
10:21:29,441  INFO Environment:542 - hibernate.properties not found
10:21:29,456  INFO Environment:676 - Bytecode provider name : cglib
10:21:29,456  INFO Environment:593 - using JDK 1.4 java.sql.Timestamp handling
............

How to convert XML file into properties file – Java


<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE properties SYSTEM "http://java.sun.com/dtd/properties.dtd">
   <properties>
 <comment>Support Email</comment>
 <entry key="email.support">donot-spam-me@nospam.com</entry>
   </properties>
In this example, we show you how to use loadFromXML() method to load above XML file into a properties object, and get the key “email.support” value via getProperty() method.
package com.mkyong;
 
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
 
public class PropertiesXMLExample
{
    public static void main(String[] args) throws IOException
    { 
     Properties props = new Properties();
 
     InputStream is = new FileInputStream("c:/email-configuration.xml");
     //load the xml file into properties format
     props.loadFromXML(is);
 
     String email = props.getProperty("email.support");
 
     System.out.println(email);
 
    }
}
Output
The above example will print out the value of properties key : “email.support” :
donot-spam-me@nospam.com

How to convert properties file into XML file – Java


import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Properties;
 
public class PropertiesXMLExample
{
    public static void main(String[] args) throws IOException
    { 
     Properties props = new Properties();
     props.setProperty("email.support", "donot-spam-me@nospam.com");
 
     //where to store?
     OutputStream os = new FileOutputStream("c:/email-configuration.xml");
 
     //store the properties detail into a pre-defined XML file
     props.storeToXML(os, "Support Email","UTF-8");
 
     System.out.println("Done");
    }
}
The above example will write the properties detail into a XML file “c:/email-configuration.xml“.
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE properties SYSTEM "http://java.sun.com/dtd/properties.dtd">
 <properties>
  <comment>Support Email</comment>
  <entry key="email.support">donot-spam-me@nospam.com</entry>
 </properties>

Execute java program based on your specified time using Quartz schedular


Quartz is a powerful and advance scheduler framework, as it can specify the exact date and time to run your scheduler job.
Firstly, try to understand the Quartz work sequence… Quartz Task, Job, JobDetail, Trigger, Scheduler
  1. Scheduler Task – Pure Java class, the task you want to schedule.
  2. Scheduler Job – Get the “Scheduler Task” from “JobDetail” via “task name“, and specify which schedule task (method) to run.
  3. Scheduler JobDetail – Define a “task name” and link it with “Scheduler Job”.
  4. Trigger – When will run your “Scheduler JobDetail”.
  5. Scheduler – Link “JobDetail” and “Trigger” together and schedule it.

1. Download Quartz

You can get the Quartz library from official website – http://www.quartz-scheduler.org/download/ or Maven central repository
<dependency>
    <groupId>opensymphony</groupId>
    <artifactId>quartz</artifactId>
    <version>1.6.3</version>
</dependency>
 
<!-- Quartz dependency library-->
<dependency>
    <groupId>commons-collections</groupId>
    <artifactId>commons-collections</artifactId>
    <version>3.2.1</version>
</dependency>

2. Scheduler Task

Create a pure Java class, this is the class you want to schedule.
package com.mkyong.common;
 
public class RunMeTask 
{
 public void printMe() {
  System.out.println("Run Me ~");
 }
}

3. Scheduler Job

Create a ‘job’ to implement the Quartz Job interface, and also the execute() method. Get the scheduler task from Job Details via “task name”, and specify which schedule task (method) to run.
package com.mkyong.common;
 
import java.util.Map;
 
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
 
public class RunMeJob implements Job
{
 public void execute(JobExecutionContext context)
 throws JobExecutionException {
 
  Map dataMap = context.getJobDetail().getJobDataMap();
  RunMeTask task = (RunMeTask)dataMap.get("runMeTask");
  task.printMe();
 }
}

4. Scheduler JobDetail

Initialize a JobDetail object, link your scheduler job with setJobClass(RunMeJob.class); method, define a task name and put it into Job data map, dataMap.put(“runMeTask”, task);. This “task name” is the only link between your Job and JobDetail.
P.S : job.setName(“runMeJob”) has no special function, just a descriptive name, you can put anything.
        RunMeTask task = new RunMeTask();
 
     //specify your sceduler task details
     JobDetail job = new JobDetail();
     job.setName("runMeJob");
     job.setJobClass(RunMeJob.class);
 
     Map dataMap = job.getJobDataMap();
     dataMap.put("runMeTask", task);

5. Quartz Triggers

Quartz triggers are used to define when the Quartz will run your declared scheduler job. There are two types of Quartz triggers :
  • SimpleTrigger – allows to set start time, end time, repeat interval to run yout job.
  • CronTrigger – allows Unix cron expression to specify the dates and times to run your job.
Code snippet – SimpleTrigger
        SimpleTrigger trigger = new SimpleTrigger();
     trigger.setName("runMeJobTesting");
     trigger.setStartTime(new Date(System.currentTimeMillis() + 1000));
     trigger.setRepeatCount(SimpleTrigger.REPEAT_INDEFINITELY);
     trigger.setRepeatInterval(30000);
Code snippet – CronTrigger
       //configure the scheduler time
     CronTrigger trigger = new CronTrigger();
     trigger.setName("runMeJobTesting");
     trigger.setCronExpression("0/30 * * * * ?");

6. Scheduler

Link the “JobDetail” and “Trigger” together and schedule it.
        //schedule it
     Scheduler scheduler = new StdSchedulerFactory().getScheduler();
     scheduler.start();
     scheduler.scheduleJob(job, trigger);

7. Full Example

Here’s two examples to show how to integrate the JobDetail, Triggers and Scheduler together.
SimpleTrigger example
In this Quartz SimpleTrigger example, it will run the printMe() method, every 30 seconds with a 1 second delay for the first time of execution.
package com.mkyong.common;
 
import java.util.Date;
import java.util.Map;
 
import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.SimpleTrigger;
import org.quartz.impl.StdSchedulerFactory;
 
public class QuartzAppSimpleTrigger 
{
    public static void main( String[] args ) throws Exception
    {
     RunMeTask task = new RunMeTask();
 
     //specify your sceduler task details
     JobDetail job = new JobDetail();
     job.setName("runMeJob");
     job.setJobClass(RunMeJob.class);
 
     Map dataMap = job.getJobDataMap();
     dataMap.put("runMeTask", task);
 
     //configure the scheduler time
     SimpleTrigger trigger = new SimpleTrigger();
     trigger.setName("runMeJobTesting");
     trigger.setStartTime(new Date(System.currentTimeMillis() + 1000));
     trigger.setRepeatCount(SimpleTrigger.REPEAT_INDEFINITELY);
     trigger.setRepeatInterval(30000);
 
     //schedule it
     Scheduler scheduler = new StdSchedulerFactory().getScheduler();
     scheduler.start();
     scheduler.scheduleJob(job, trigger);
 
    }
}
CronTrigger example
In this Quartz CronTrigger example, it will run the printMe() method, every 30 seconds.
package com.mkyong.common;
 
import java.util.Map;
 
import org.quartz.CronTrigger;
import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.impl.StdSchedulerFactory;
 
public class QuartzAppCronTrigger 
{
    public static void main( String[] args ) throws Exception
    {
     RunMeTask task = new RunMeTask();
 
     //specify your sceduler task details
     JobDetail job = new JobDetail();
     job.setName("runMeJob");
     job.setJobClass(RunMeJob.class);
 
     Map dataMap = job.getJobDataMap();
     dataMap.put("runMeTask", task);
 
     //configure the scheduler time
     CronTrigger trigger = new CronTrigger();
     trigger.setName("runMeJobTesting");
     trigger.setCronExpression("0/30 * * * * ?");
 
     //schedule it
     Scheduler scheduler = new StdSchedulerFactory().getScheduler();
     scheduler.start();
     scheduler.scheduleJob(job, trigger);
    }
}
The Unix cron expression is highly flexible and powerful, you can learn and see many advance cron expression examples in following website.
  1. http://en.wikipedia.org/wiki/CRON_expression
  2. http://www.quartz-scheduler.org/docs/examples/Example3.html