Sunday, October 30, 2011

How to send Email through Java


How to send email using java mail api...

Following class will describes how to send email through java


import java.io.IOException;
import java.util.List;
import java.util.Properties;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import org.apache.log4j.Logger;

/**
 * @created by velmurugan pousel
 * @created on Oct 17, 2011
 * @project TestBatch
 */
public class TestEmailUtil {

 private final static Logger logger = Logger.getLogger(TestJobLauncher.class);

 private static  Properties emailProps ;

 /**
  * method to load the email host/port information and construct the email properties to
  * get the session to send mail
  * @throws TestException
  */
 public void init() throws TestException {

  logger.info(" loading the email host information");
  try {
   if (emailProps == null) {
    emailProps = new Properties();
    Properties prop =  new Properties();
    prop.load(getClass().getClassLoader().getResourceAsStream(ExtractULC.Test_EMAIL_CONFIG_FILE_NAME));
    
     //mail.host=Smtp.test.com
    //mail.port=25
    //mail.auth=false
    //mail.auth.userid=
    //mail.auth.password=
    //mail.from=
    //mail.cc=dl-test-Tech_Suport
    emailProps.put("mail.smtp.host", prop.get(ExtractULC.EMAIL_HOST_NAME));
    emailProps.put("mail.smtp.port", prop.get(ExtractULC.EMAIL_HOST_PORT));
    emailProps.put("mail.smtp.auth", prop.get(ExtractULC.EMAIL_AUTH_LEVEL));
    emailProps.put("mail.from", prop.get(ExtractULC.EMAIL_FROM_ADDRESS));
    emailProps.put("mail.cc", prop.get(ExtractULC.EMAIL_CC_ADDRESS));
   } 
  } catch (IOException e) {
   logger.error(" Error during email information loading.."+ e.getMessage());
   throw new TestException(e);
  }
 }
 /**
  * util method to send the email notification
  * @param recipients
  * @param subject
  * @param message
  * @param from
  * @throws MessagingException
  * @throws TestException
  */
 public void postMail(String recipients[], String subject, String message,
   String from) throws MessagingException, TestException {
  logger.info(" entering into the postmail method.....");
  boolean debug = false;
  try {
   init();
   // create some properties and get the default Session
   Session session = Session.getDefaultInstance(emailProps, null);
   session.setDebug(debug);
   // create a message
   Message msg = new MimeMessage(session);
   
   // set the from and to address
   InternetAddress addressFrom = new InternetAddress(emailProps.getProperty(ExtractULC.EMAIL_FROM_ADDRESS));
   msg.setFrom(addressFrom);
     
   // set the cc address incase if its error message
   if (from != null && from.trim().length() > 0){  
    InternetAddress addressCC = new InternetAddress(emailProps.getProperty(ExtractULC.EMAIL_CC_ADDRESS));
    msg.setFrom(addressCC);
   }
      
   InternetAddress[] addressTo = new InternetAddress[recipients.length];
   for (int i = 0; i < recipients.length; i++) {
    addressTo[i] = new InternetAddress(recipients[i]);
   }
   msg.setRecipients(Message.RecipientType.TO, addressTo);
   msg.addHeader("TestHeader", "Test header");
   // Setting the Subject and Content Type
   msg.setSubject(subject);
   msg.setContent(message, "text/plain");
   Transport.send(msg);
   logger.info(" email successfully send...");
  } catch (Throwable e) {
   logger.error(" Error during email send....");
      throw new TestException(e);
  }
 }
 /**
  * method to send the email notification into the internal vendors
  *
  * @param emailIds
  * @param sub - subject to send
  * @param body
  * @return
  * @throws TestException
  */
 public boolean sendMail(List<String> emailIds, String sub, String body, String to)
   throws TestException {
  try {
   //postMail(Collections., sub, body, "");
  } catch (Throwable e) {
   throw new TestException(e);
  }
  return false;
 }
 /**
  * method to send the email notification into the internal vendors
  *
  * @param emailIds
  * @param sub - subject to send
  * @param body
  * @return
  * @throws TestException
  */
 public boolean sendMail(String emailId, String sub, String body)
   throws TestException {
  try {
   postMail(new String[] { emailId }, sub, body, "");
  } catch (Throwable e) {
   throw new TestException(e);
  }
  return false;
 }
 /**
  * method to send the email notification into the internal vendors
  *
  * @param emailIds
  * @param sub - subject to send
  * @param body
  * @return
  * @throws TestException
  */
 public boolean sendMail(String emailId, String sub, String body, boolean addCC)
   throws TestException {
  try {
   postMail(new String[] { emailId }, sub, body, "cc");
  } catch (Throwable e) {
   throw new TestException(e);
  }
  return false;
 }
  
 /**
  * method to send the email notification into the internal vendors
  *
  * @param emailIds
  * @param sub - subject to send
  * @param body
  * @return
  * @throws TestException
  */
 public boolean sendMail(String[] emailIds, String sub, String body, boolean addCC)
   throws TestException {
  try {
   postMail(emailIds , sub, body, "cc");
  } catch (Throwable e) {
   throw new TestException(e);
  }
  return false;
 }
      
 /**
  * method to send the email notification into the internal vendors
  * @param emailIds
  * @param sub - subject to send
  * @param body
  * @return
  * @throws TestException
  */
 public boolean sendMail(String[] emailIds, String sub, String body)
  throws TestException {
  try {
   postMail(emailIds, sub, body, "");
  } catch (Throwable e) {
   throw new TestException(e);
  }
  return false;
 } 

 public static void main(String[] args) {
  try {
   String[] mailIds = new String[]{"vels007@gmailcom"};
   new TestEmailUtil().postMail(mailIds, "Test", " Test message", "");
  } catch (Throwable e){
   e.printStackTrace();
  }
 }
}

How to get the Exception StackTrace content in java

How to get the error/exception Stacktrace in Java


/**
 * util method to get the full stacktrace of an exception
 * and return the message as string
 * @param e
 * @return
 */
public String getExceptionStack(Throwable e) {
 String errorMessage ="" ;
 try {
       StringWriter traceWriter = new StringWriter();
       PrintWriter printWriter = new PrintWriter(traceWriter, false);
       e.printStackTrace(printWriter);
       printWriter.close();
       errorMessage = traceWriter.getBuffer().toString();
 } catch (Throwable e1) {
      logger.error(e1.getMessage());
 }
   return errorMessage;
}




Find out Number of Days in Month/Year using java

How to find out number of days in a given month and year

Code snippet to find out the numbe rof days in a month.

...
..
/**
 * util method to find the number of day in the given passed month
 * @param month  
 * @return last days of the month
 */
public int getDaysInMonth(Date dt) {

 if (dt == null) dt = new Date();

 Calendar cal = Calendar.getInstance();
 cal.setTime(dt);

 return cal.getActualMaximum(cal.DAY_OF_MONTH);


/**
 * util method to find the last day of the given  year
 * @param month
 * @param year
 * @return last days of the month
 */
public int getDaysInYear(Date dt) {

 if (dt == null) dt = new Date();

 Calendar cal = Calendar.getInstance();
 cal.setTime(dt);

 return cal.getActualMaximum(cal.DAY_OF_YEAR);
}


Main Method to test this


public static void main(String[] args) {
 try {   
   
  System.out.println(" last day os the month..."+ new ReqDXCommonUtil().getDaysInMonth(new Date()));
 } catch (Throwable e) {
  // TODO Auto-generated catch block
  e.printStackTrace();
 }
}




Monday, August 1, 2011

Customized Object Serialization/De Serialization in Java

Customized Object Serialization/De Serialization in Java

Following describes how to serialize or de serialize the object in java
 its also known as marshalling and un marshalling java object in a customized way

When weuse Serializable interface, ourclass is serialized automatically by default.
But  we can override writeObject() and readObject() two methods to control more complex object serailization process.

When we use Externalizable interface, you have a complete control over your class's serialization process. This interface contains two methods namely readExternal and writeExternal. You should implement these methods and write the logic for customizing the serialization process.

Now am going to show simple way of serializing the java object

Model object : Person.java


/**
 *
 */
package com.vels.test;
import java.io.Serializable;

/**
 * @author velmurugan pousel
 * created on Aug 1, 2011 for test
 */

public class Person implements Serializable {

 private String name;
 private String id;
 private int age;


 public Person(int age, String name, String id){
    this.name = name;
    this.age = age;
    this.id = id;
 }

 /**
  * @return the name
  */
 public String getName() {
  return name;
 }

 /**
  * @param name the name to set
  */
 public void setName(String name) {
  this.name = name;
 }

 /**
  * @return the id
  */
 public String getId() {
  return id;
 }

 /**
  * @param id the id to set
  */
 public void setId(String id) {
  this.id = id;
 }

 /**
  * @return the age
  */
 public int getAge() {
  return age;
 }

 /**
  * @param age the age to set
  */
 public void setAge(int age) {
  this.age = age;
 }

}
Main class :


/**
 *
 */
package com.vels.test;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import com.sun.corba.se.spi.ior.ObjectId;

/**
 * @author velmurugan pousel
 * created on Aug 1, 2011 for test
 */

public class SerializationTest {

 public static void main(String[] args) {

  try {

   String path = "d:/doc/person.txt";
  
   System.out.println(" ######### BEFORE SERIALIZATION ########## ");

   // serialize the Person object
   Person p = new Person(12,"raj","111");
   serializeObject(path, p);

   System.out.println(" #########  SERIALIZATION DONE ########## ");

  
   System.out.println(" ######### BEFORE DE SERIALIZATION ########## ");
   //de serialize the person

   Person p1 = (Person) deSerializeObject(path); 
   System.out.println(" name...." + p1.getName());
   System.out.println(" id...." + p1.getName());
   System.out.println(" ######### DE SERIALIZATION DONE ########## ");
  
  } catch (Throwable e) {
   e.printStackTrace();
  }
 
 }

 /**
  * to serialise the object to the given path
  * @param path- name of the file where the object going to be serialized
  * @param objToSerialize
  */
 public static void serializeObject(String path, Object objToSerialize) {

  try {
   FileOutputStream fos = new FileOutputStream(new File(path));
   ObjectOutputStream obj = new ObjectOutputStream(fos);
   obj.writeObject(objToSerialize);
  
   fos.flush();
   obj.close();
  } catch (Throwable e) {
   e.printStackTrace();
  }

 }

 /**
  * to de serialize the object from the given file where its serialized
  *
  * @param path
  * @return
  */

 public static Object deSerializeObject(String path) {

  Object obj = null;
  try {
   ObjectInputStream in = new ObjectInputStream(new FileInputStream(path));
   obj = in.readObject();
  } catch (Throwable e) {
   e.printStackTrace();
  }
  return obj;
 }

}
Output :

######### BEFORE SERIALIZATION ##########
######### SERIALIZATION DONE ##########
######### BEFORE DE SERIALIZATION ##########
name....raj
id....raj
######### DE SERIALIZATION DONE ##########

Thursday, July 21, 2011

Comparator in Java

Sorting a Collection of object without implementing the Comparator/Comparable 

This java program describes how to sort collection of user defined objects using Comparator as anonymous class(without implementing the Comparator interface)

There are two ways we can sort the List of user defined objects in java

1. Implement the Comparator/Comparable interface by userdefined  class
2. Without  implementing  Comparator interface(using anonymous class)

Now am going to show the example which will sort the userdefined objects using
Comparator interface as anonymous class(ie. without implementing the Comparator interface)

My Model Object : Sample.java

package com.vels.test;

/**
 * @author velmurugan pousel
 * created on Jul 21, 2011 for test
 */

public class Sample {

 public String id;
 public String name;
 public int age;

 Sample(String ID, String nm, int ag){
    this.id = ID;
    this.name = nm;
    this.age = ag;
 }

 /**
  * @return the id
  */
 public String getId() {
  return id;
 }

 /**
  * @param id the id to set
  */
 public void setId(String id) {
  this.id = id;
 }

 /**
  * @return the name
  */
 public String getName() {
  return name;
 }

 /**
  * @param name the name to set
  */
 public void setName(String name) {
  this.name = name;
 }

 /**
  * @return the age
  */
 public int getAge() {
  return age;
 }

 /**
  * @param age the age to set
  */
 public void setAge(int age) {
  this.age = age;
 }

}

Now am going to sort the list of Sample class object based on the ID field.

Here is my main method :


package com.vels.test;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

/**
 * @author velmurugan pousel
 * created on Jul 21, 2011 for test
 */

public class ComparatorTest {

 public static void main(String[] args) {

  List<Sample> list = new ArrayList<Sample>();
 
  Sample s1 = new Sample("1", "amin", 12); 
  list.add(s1);

  s1 = new Sample("5", "ver", 21);
  list.add(s1);
 
  s1 = new Sample("1", "hji", 14);
  list.add(s1);
 
  s1 = new Sample("7", "loli", 24);
  list.add(s1);
 
  s1 = new Sample("3", "zuri", 12);
  list.add(s1);
  s1 = new Sample("1", "zuri", 12);
  list.add(s1);

  for (Sample s : list) {
   System.out.println(" id..." + s.getId() + " name..." + s.getName());
  }

// here is the most important part

  Collections.sort(list, new Comparator<Sample>() {
   //string comparation here ID is the string field
              public int compare(Sample s1, Sample s2) {
                         int result = s1.getId().compareTo(s2.getId());
                         return result;
               }
     }  );

 //After sorting

  for (Sample s : list) {
   System.out.println(" name..." + s.getName());
   System.out.println(" id..." + s.getId());
  }

 } 
 
}

Output : Before Sorting

id...1 name...amin
id...5 name...ver
id...1 name...hji
id...7 name...loli
id...3 name...zuri
id...1 name...zuri

After Sorting :
id...1 name...amin
id...1 name...hji
id...1 name...zuri
id...3 name...zuri
id...5 name...ver
id...7 name...loli
..

To compare the int type

Collections.sort(list, new Comparator<Sample>() {
   //string comparation here ID is the string field
              public int compare(Sample s1, Sample s2) {
                         int result = s1.getAge() - s2.getAge();
                         return result;
               }
     }  );


 

 

Wednesday, July 13, 2011

ZULU Time validation in java

Zulu Time validation in java

Following are the zulu based time format
HH:mm:ss.SSS'Z'
HH:mm:ss'Z'
HH:mm:ss
..
...
// we can pass the pattern whatever we want

String format = "HH:mm:ss.SSS'Z'";

SimpleDateFormat zuluFmt = new SimpleDateFormat(format);
zuluFmt.setTimeZone(TimeZone.getTimeZone("UTC"));
System.out.println(" checkind time" + zuluFmt.parse("14:45:50.234Z"));
....

JAXB Namespacing - including xmlns:xsi and xsi:schemalocation in namespace

How to include xmlns:xsi and xsi:schemalocation into the namespace while marshalling

1. Add the xmlns:xsi attributes in @XmlSchema in packge-info.java

  @java.xml.bind.annataion.XmlSchema (
       xmlns={ @javax.xml.bind.annataion.XMlNs(prefix="xsi" 
       namespaceURIU=http://www.vels.com/schemadef },
       namespace=http://ww.vels.com/2/,
      elementFormDefault = javax.xml.bind.annatation.XmlForm.QUALIFIED)
  package com.vels.test.schema;

2.Add the schmalocation uri JAXB_SCHEMA_LOCATION_URI in "marshallingproperties " of Jaxb2Marshaller class in spring-ws-servlet.xml

<bean id="marshaller" calss="org.springframework.oxm.jaxb.Jaxb2Marshaller">
     <property names="classesToBound">
             <list>
                    <value> com.vels.test.Sample.java </value>
              </list>
  </property>
//since its a static field property we need to use util:constant from spring dtd
 <property name="marshallingProperties">
         <map>
               <entry>
                      <key><util:constant static-field="javax.xml.bind.helpers.AbstractMarshallerImpl.JAXB_SCHEMA_LOCATION" /> </key>
<value> http://vels.com/vel.xsd </value>
</map>
...

your output xml looks like
<out xmlns="asdsd" xmlns:xsi="sdsdf" xsi:schemalocation=http://vels.com/vels.xsd>
....
</out>

Wednesday, June 8, 2011

GMT/IST convertor in java


How to Convert GMT time into IST time using java

 

package com.vels.test;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;


/**
 * @author velmurugan pousel
 * created on Jun 8, 2011 for GMT Convertor
 */


public class GMTConvertor {

 public static void main(String args[]) {

  Calendar cal = Calendar.getInstance();
  cal.set(2011, 06, 8, 12, 0);//year,month,day,hour,minute format


  System.out.println(" IST time" + convertIST(cal.getTime()));


  System.out.println("current GMT time" + convertGMT(new Date()));

 }

 /**
  *  method to covert IST time to GMT
  * @param date is in IST format
  * @return
  */
 public static String convertGMT(Date date) {


 DateFormat gmtFormat = new SimpleDateFormat();
   TimeZone gmtTime = TimeZone.getTimeZone("GMT");
   gmtFormat.setTimeZone(gmtTime);

   return gmtFormat.format(date);

 }

 /**
  * method to convert GMT to IST time
  * @param date is GMT format
  * @return
  */
 public static String convertIST(Date date) {

   DateFormat istFormat = new SimpleDateFormat();
   TimeZone istTime = TimeZone.getTimeZone("Asia/Kolkata");
   istFormat.setTimeZone(istTime);

   return istFormat.format(date);

 }

}
 
 

Wednesday, February 16, 2011

How to Extract ZIP/JAR/WAR/TAR/RAR file Using Java

Extracting ZIP/JAR/WAR/TAR/RAR file using java

Using ZipEntry and ZipInputstream classes we can extract the zip/jar/war/tar files.

here is the code snippet....


 public static void extractZipFiles(String filename) {
   try {
             // destination folder to extract the contents         
             String destinationname = "d:\\temp\\testZip\\";          

             byte[] buf = new byte[1024];
             ZipInputStream zipinputstream = null;
             ZipEntry zipentry;
             zipinputstream = new ZipInputStream(new FileInputStream(filename));
            zipentry = zipinputstream.getNextEntry();
 
           while (zipentry != null) {

                 // for each entry to be extracted
                 String entryName = zipentry.getName();
    
                 int n;
                FileOutputStream fileoutputstream;
                File newFile = new File(entryName);

              String directory = newFile.getParent();

              // to creating the parent directories
              if (directory == null) {
                   if (newFile.isDirectory()){
                         break;
                      }
             } else {
                 new File(destinationname+directory).mkdirs();
              }
    

            if(!zipentry.isDirectory()){
                       System.out.println("File to be extracted....."+ entryName);
                       fileoutputstream = new FileOutputStream(destinationname  + entryName);
                      while ((n = zipinputstream.read(buf, 0, 1024)) > -1){
                              fileoutputstream.write(buf, 0, n);
                       }
                      fileoutputstream.close();
            }
             
           zipinputstream.closeEntry();
           zipentry = zipinputstream.getNextEntry();
          }// while
  
     zipinputstream.close();
   } catch (Exception e) {
    e.printStackTrace();
   }
  }

...

Tuesday, February 15, 2011

ClassFinder in java

How to find out a class file in a JAR/WAR/ZIP files using java

ClassFinder program to findout "simulator.class" in a dwr.jar file
 
package com.vels.sms.action;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
 /**
 * @author velmurugan pousel
 * @project SMS
 * created on Feb 14, 2011
 */
public class ClassNameFinder {
 

 public static List<String> findClass(String srcJarPath, String srcJar) throws IOException{
  List<String> nameList = new ArrayList<String>();

  ZipFile zip = new ZipFile(srcJarPath);  
  // Process the zip file. Close it when the block is exited.
  try {
      
    String searchFileC = srcJar+".class";
    String searchFileJ = srcJar+".java";
  
   // Loop through the zip entries and print the name of each one.

   for (Enumeration list = zip.entries(); list.hasMoreElements();) {
         ZipEntry entry = (ZipEntry) list.nextElement();
        String srcFile = entry.getName();

    // filters only .class and java files..avoids unnecesaary checking

       if (srcFile.endsWith(".class") || srcFile.endsWith(".java")) {
                   int c = srcFile.lastIndexOf("/");
                  String fName = srcFile.substring(c + 1);
                 if (searchFileC.equalsIgnoreCase(fName) || searchFileJ.equalsIgnoreCase(fName)) {     
                     nameList.add(srcFile);
                  }
        }
   }

//   if(!fileFound){
//    System.out.println(" File" + srcJar +"  not found on the "+ srcJarPath);
//   }
        
  } catch (Throwable e) {
            e.printStackTrace();
  } finally {
            zip.close();
  }
            return nameList;
 }

 public static void main(String[] args) {
  try {
          String srcPath = "D:\\bak\\dwr.war";
          String searchFile = "simulator";
  
         List<String> classList = findClass(srcPath, searchFile);
  
        if (classList.size()>0){
            System.out.println(" Class Find..."+ classList);
       } else {
            System.out.println(" File" + srcPath +"  not found on the "+ searchFile);
       }
     
  } catch (Throwable e){
       e.printStackTrace();
  }
  
 }

}

.....
....

Tuesday, February 8, 2011

Writing A text/xml file into a Tomcat WEB-INF folder

How to write a file(text or xml) file into a TOMCAT WEB-INF folder


code snippet  for writing a text file into the Tomcat WEB-INF folder:

...
...
String realPath = getServletContext().getRealPath("/WEB-INF/log");
// it returns  D:\apps\apache-tomcat-6.0.24\webapps\CodeAnalyser\WEB-INF\log  as realPath value

File curFile = File.createTempFile("SopOut", ".txt", new File(realPath));

// it will creat a file SopOUt.txt in to the  D:\apps\apache-tomcat-6.0.24\webapps\CodeAnalyser\WEB-INF\log  folder

// write to file
FileWriter fw = new FileWriter(curFile);

try {
      fw.write(sb); // sb contains the content to be written into the file
} finally {
    fw.flush();
    fw.close();
}

...
...

Thursday, February 3, 2011

Hacking a Website using Javascript

How to Hack a website.....
Hack instructions:
1. Go to the website which has more number images like
www.myspace.com,google
2. Wait for the page to fully load
3. In your browser’s address bar, enter the code below (copy and paste all in one line)
4. Hit enter
5. Wait a second and See what happens ...coool

script need to be copied..

javascript:R=0; x1=.1; y1=.05; x2=.25; y2=.24; x3=1.6; y3=.24;x4=300; y4=200; x5=300; y5=200; DI=document.images; DIL=DI.length;function A(){for(i=0; i<dil ; i++){DIS=DI[ i ].style;DIS.position='absolute'; DIS.left=Math.sin(R*x1+i*x2+x3)*x4+x5;DIS.top=Math.cos(R*y1+i*y2+y3)*y4+y5}R++ }setInterval('A()',5); void(0);

................

Wednesday, February 2, 2011

Alarm Clock using Java Schedular

How to implement alarm clock functionality to alarm sound at 7 am on week days and 10 am on weekends using java schedular

Steps to schedule a alarm clock during the week days or week ends

Step1. Write an abstract class wich implements Runnable and has the method to implement the logic to alarm sound.

package com.vels.test;

import java.util.TimerTask;
/**
* @author velmurugan pousel
* @project test
* created on Feb 1, 2011
*/
public abstract class SchedulerTask implements Runnable {

final Object lock = new Object();

int state = VIRGIN;
static final int VIRGIN = 0;
static final int SCHEDULED = 1;
static final int CANCELLED = 2;

TimerTask timerTask;

protected SchedulerTask() {
}

public abstract void run();

public boolean cancel() {
synchronized(lock) {
if (timerTask != null) {
timerTask.cancel();
}
boolean result = (state == SCHEDULED);
state = CANCELLED;
return result;
}
}

public long scheduledExecutionTime() {
synchronized(lock) {
return timerTask == null ? 0 : timerTask.scheduledExecutionTime();
}
}

}
Stpe 2 : Write a schedular to schedule tha alarm clock to sound


package com.vels.test;

import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;
/**
* @author velmurugan pousel
* @project test
* created on Feb 1, 2011
*/
public class Scheduler {

class SchedulerTimerTask extends TimerTask {
private SchedulerTask schedulerTask;
private ScheduleIterator iterator;
public SchedulerTimerTask(SchedulerTask schedulerTask,
ScheduleIterator iterator) {
this.schedulerTask = schedulerTask;
this.iterator = iterator;
}
public void run() {
schedulerTask.run();
reschedule(schedulerTask, iterator);
}
}

private final Timer timer = new Timer();

public Scheduler() {
}

public void cancel() {
timer.cancel();
}

public void schedule(SchedulerTask schedulerTask,
ScheduleIterator iterator) {

Date time = iterator.next();
if (time == null) {
schedulerTask.cancel();
} else {
synchronized(schedulerTask.lock) {
if (schedulerTask.state != SchedulerTask.VIRGIN) {
throw new IllegalStateException("Task already scheduled " + "or cancelled");
}
schedulerTask.state = SchedulerTask.SCHEDULED;
schedulerTask.timerTask =
new SchedulerTimerTask(schedulerTask, iterator);
timer.schedule(schedulerTask.timerTask, time);
}
}
}

private void reschedule(SchedulerTask schedulerTask,
ScheduleIterator iterator) {

Date time = iterator.next();
if (time == null) {
schedulerTask.cancel();
} else {
synchronized(schedulerTask.lock) {
if (schedulerTask.state != SchedulerTask.CANCELLED) {
schedulerTask.timerTask =
new SchedulerTimerTask(schedulerTask, iterator);
timer.schedule(schedulerTask.timerTask, time);
}
}
}
}

}


Step 3 : Write an Schedule iterator


package com.vels.test;

import java.util.Date;
/**
* @author velmurugan pousel
* @project test
* created on Feb 1, 2011
*/
public interface ScheduleIterator {
public Date next();

}

Step 4 : Write a Restricted Daily Iterator - it is restricted to run a job on particular days of the week;


package com.vels.test;

import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;

/**
* @author velmurugan pousel
* @project EmailScheduler
* created on Feb 2, 2011
*/
public class RestrictedDailyIterator implements ScheduleIterator {

private final int hourOfDay;
private final int minute;
private final int second;
private final int[] days;
private final Calendar calendar = Calendar.getInstance();

public RestrictedDailyIterator(int hourOfDay, int minute, int second, int day) {
this(hourOfDay, minute, second, new int[]{day});
}

public RestrictedDailyIterator(int hourOfDay, int minute, int second, int[] days) {
this(hourOfDay, minute, second, days, new Date());
}

public RestrictedDailyIterator(int hourOfDay, int minute, int second, int[] days, Date date) {
this.hourOfDay = hourOfDay;
this.minute = minute;
this.second = second;
this.days = (int[]) days.clone();
Arrays.sort(this.days);

calendar.setTime(date);
calendar.set(Calendar.HOUR_OF_DAY, hourOfDay);
calendar.set(Calendar.MINUTE, minute);
calendar.set(Calendar.SECOND, second);
calendar.set(Calendar.MILLISECOND, 0);
if (!calendar.getTime().before(date)) {
calendar.add(Calendar.DATE, -1);
}
}

public Date next() {
do {
calendar.add(Calendar.DATE, 1);
} while (Arrays.binarySearch(days, calendar.get(Calendar.DAY_OF_WEEK)) < 0);
return calendar.getTime();
}
}

Step 5 : Write Composit iterator class - takes a set of ScheduleIterators and correctly orders the dates into a single schedule.


package com.vels.test;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Date;

/**
* @author velmurugan pousel
* @project EmailScheduler
* created on Feb 2, 2011
*/
public class CompositeIterator implements ScheduleIterator {

private List orderedTimes = new ArrayList();
private List orderedIterators = new ArrayList();

public CompositeIterator(ScheduleIterator[] scheduleIterators) {
for (int i = 0; i < scheduleIterators.length; i++) {
insert(scheduleIterators[i]);
}
}

private void insert(ScheduleIterator scheduleIterator) {
Date time = scheduleIterator.next();
if (time == null) {
return;
}
int index = Collections.binarySearch(orderedTimes, time);
if (index < 0) {
index = -index - 1;
}
orderedTimes.add(index, time);
orderedIterators.add(index, scheduleIterator);
}

public synchronized Date next() {
Date next = null;
while (!orderedTimes.isEmpty() && (next == null || next.equals((Date) orderedTimes.get(0)))) {
next = (Date) orderedTimes.remove(0);
insert((ScheduleIterator) orderedIterators.remove(0));
}
return next;
}
}

Step 6 : Write an alarm clock class - it will alarm sound at 7am on week days and 9 am on weekend


package com.vels.test;

import java.text.SimpleDateFormat;

import java.util.Calendar;
import java.util.Date;


/**
* @author velmurugan pousel
* @project test
* created on Feb 1, 2011
*/
public class AlarmClock {

private final Scheduler scheduler = new Scheduler();
private final SimpleDateFormat dateFormat =
new SimpleDateFormat("dd MMM yyyy HH:mm:ss.SSS");


public AlarmClock() {
}

public void start(ScheduleIterator iterator) {

scheduler.schedule(new SchedulerTask() {
public void run() {
soundAlarm();
}
private void soundAlarm() {
System.out.println("Wake up! " +
"It's " + dateFormat.format(new Date()));
// Start a new thread to sound an alarm...
}
}, iterator);

}

public static void main(String[] args) {

int[] weekdays = new int[] {
Calendar.MONDAY,
Calendar.TUESDAY,
Calendar.WEDNESDAY,
Calendar.THURSDAY,
Calendar.FRIDAY
};
int[] weekend = new int[] {
Calendar.SATURDAY,
Calendar.SUNDAY
};
ScheduleIterator i = new CompositeIterator(
new ScheduleIterator[] {
new RestrictedDailyIterator(7, 0, 0, weekdays),
new RestrictedDailyIterator(9, 0, 0, weekend)
}
);

AlarmClock alarmClock = new AlarmClock();
alarmClock.start(i);
}


}
......


Wake up! It's 02 Feb 2011 12:28:00.011
.....




Reference : http://www.ibm.com/...

Tuesday, February 1, 2011

Job Scheduling in Java

How to Schedule a Job or Task in Java

To schedule a job to occur at a certain time or to be excuted at repeated time interval
we can use TimerTask and Timer class in java to accomplish this.


A TimerTask is “A task that can be scheduled for one-time or repeated execution by a Timer.”
A TimerTask is similar to a Thread. Both classes implement the Runable interface.
Thus both classes need to implement the public void run() method. The code inside the run() method is will be executed by a thread

A Timer is facility to schedule TimerTasks.
"Corresponding to each Timer object is a single background thread that is used to execute all of the timer's tasks, sequentially.
Timer tasks should complete quickly."
The constructor of the Timer class starts the background thread.



package com.vels.test;

import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;
/**
* @author velmurugan pousel
* @project test
* created on Feb 1, 2011
*/
public class EmailTask extends TimerTask {

/**
* method will be called at every scheduled time(ex ..1 minute)
*/
public void run() {
System.out.println(" start to send mail...." + new Date());
sendMail();
System.out.println(" after mail sent...." +
System.currentTimeMillis());
}

public void sendMail() {
System.out.println(" email send.....");
}

public static void main(String[] args) {

int DELAY = 60*1000; // one minute delay

Timer t1 = new Timer();
t1.schedule(new EmailTask(),DELAY, DELAY);
//calls the run method to send mail after one minute and
repeat every one minute.

// task - task to be scheduled.
// delay - delay in milliseconds before task is to be
executed.
// period - time in milliseconds between successive task
executions.
}
}


To cancel the Scheduled task we need to call cancel method of the TimerTask( we can override the cancel method).

Tuesday, January 18, 2011

How To Install and run MySQL

How to install and run the MySQL


Step to install and work on the MySQL Server


Step 1 : Download the MYSQL

Download the MySQL and install the MySQL into C:\mysql.
Extract the ZIP to your C: drive and rename the folder from “mysql- x.x.xx-win32″ to “mysql”. MySQL can be installed anywhere on your
system.

Step 2 : Move the data folder(optional)


I recommend placing the data folder on another drive or
partition to make backups and re-installation easier. For the
purposes of this example, we will create a folder called
D:\MySQLdata and move the contents of C:\mysql\data into it.

You should now have two folders, D:\MySQLdata\mysql and
D:\MySQLdata\test. The original C:\mysql\data folder can be
removed.

Step 3 : Create the configuration file

MySQL provides several configuration methods but, in general, it
is easiest to to create a my.ini file in the mysql folder. There
are hundreds of options to tweak MySQL to your exact
requirements,

but the simplest my.ini file is:

[mysqld]
# installation directory
basedir="C:/mysql/"
# data directory
datadir="C:/MySQLdata/"


Step 4 : Test your MySQL Server

Open the command prompt and run the following command

C:\mysql\bin\mysqld.exe
This will start the MySQL server which listens for requests on
localhost port 3306.
Open another command window and run the following command

cd c:\mysql\bin
mysql –u root

This will show a welcome message and the mysql> prompt.
Enter “show databases;” to view a list of the pre-defined
databases

Step 5: Change the root password

The MySQL root user is an all-powerful account that can create and
destroy databases. If you are on a shared network, it is advisable
to change the default (blank) password. From the mysql> prompt,
enter:

UPDATE mysql.user SET password=PASSWORD("my-new-password") WHERE
User='root';

FLUSH PRIVILEGES;

You will be prompted for the password the next time you start the
MySQL command line.

Enter “exit” at the mysql> prompt to stop the command line client.
You should now shut down MySQL with the following command:

Step 6 : Create Table in database velsDB

First we need to Create a database :

mysql> create database velsDB ;
mysql>use database velsDB;

create table resource_vacation_plan(
employee_id varchar(36) not null,
employee_name varchar(32) not null,
start_date date,
end_date date,
no_of_days integer(3)
);

Commit;

If you are going to use my sql in your code the use the following
to create the DB connection:

String DB_MYSQL_DRIVER_NAME = "com.mysql.jdbc.Driver";
String DB_URL_STRING_MYSQL = "jdbc:mysql://localhost:3306/velsDB";
String DB_URL_MYSQL_USERID = "root";
String DB_URL_MYSQL_PASSWORD = "root";
..................