Wednesday, March 16, 2011

Implementing Timer in Java


Implementing Timer and TimerTask in Java
//Real world example of sending SMSes in Fixed interval, interval is defined in a properties file
//For sending an SMS, you need to have an account with third party SMS provider like Unicel, so they 
//will provide an UserId and Password that you have to use while sending SMS.

//Java code
//TestUnicelConnectivity.java

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.Date;
import java.util.Properties;
import java.util.Scanner;
import java.util.Timer;
import java.util.TimerTask;

/**
* @author dmodi
*/
public class TestUnicelConnectivity {
static final Timer t = new Timer();
static int no_sms_sent=1;

//For Unicel testing
private static int intervalForSmsToBeSentInSeconds=30;
private static String unicelURL="";
private static String testingMobileNo="";
private static String testSMSForUnicelConnectivity="";
private static String usernameParam = "uname=******";
private static String passwordParam = "pass=*******";

private static TestUnicelConnectivity automaticConnector=null;
private static Properties props = null;

public TestUnicelConnectivity(String propertiesFilePath) throws Exception{
props=new Properties();
try {
props.load(new FileInputStream(propertiesFilePath));
if(props==null){
throw new IOException("Connectors.properties file not found, please provide path of Connectors.properties correctly");
}
System.out.println("Properties file contents loaded..");
}
catch(IOException e) {
e.printStackTrace();
throw e;
}
}

public static void main(String[] args) {
try {
if(args.length>0) {
automaticConnector=new TestUnicelConnectivity(args[0]);   //Properties file contents is pasted at the end of this blog.

unicelURL = props.getProperty("UnicelURL").trim();
testingMobileNo = props.getProperty("MobileNumber").trim();
testSMSForUnicelConnectivity = props.getProperty("TestSms").trim();
intervalForSmsToBeSentInSeconds=Integer.parseInt(props.getProperty("IntervalForSmsToBeSentInSeconds").trim());

boolean b=automaticConnector.validateSMSParameters(unicelURL,testingMobileNo,testSMSForUnicelConnectivity);
if(b)
automaticConnector.sendRepeatedSMS(intervalForSmsToBeSentInSeconds);
else {
System.out.println("Validation failed for SMS parameters");
System.exit(0);
}
}
else {
System.out.println("Please provide Property file name in command line argument");
System.exit(0);
}
}
catch(Exception e){
System.out.println("Exception occured: "+e.getMessage());
e.printStackTrace();
}
}
private static String formURL() {
String toParam = "****=";
String udhParam = "****=";
String fromParam = "send=*****-T";
String textParam = "msg=";
//String priorityParam = " prty=1";
//String validityPeriodParam = "vp=30";
//String dataCodingSchemeParam = "dcs=";
StringBuffer sb = new StringBuffer();
sb.append(unicelURL).append("?").append(usernameParam + "&").append(passwordParam + "&");
sb.append(toParam).append(testingMobileNo + "&").append(udhParam + "&");
sb.append(fromParam + "&").append(textParam).append(testSMSForUnicelConnectivity);
return sb.toString().replace(" ", "+");
}

public boolean validateSMSParameters(String unicelURL,String mobileNumber,String message){
if (mobileNumber == null || mobileNumber.length() != 12) {
System.out.println("Invalid mobile Number :: Mobile Number must starts with 91. Please check your mobile Number again ...");
return false;
}
Scanner scan = new Scanner(mobileNumber);
if(!scan.hasNextLong())    {
System.out.println("Invalid mobile Number :: Mobile Number must starts with 91. Please check your mobile Number again ...");
return false;
}
if (message == null || "".equalsIgnoreCase(message) || message.length() > 140) {
System.out.println("Invalid message :: Message Exceeds or 140 character or is empty. Please check your message again ...");
return false;
}
if (message == null && message.length() > 140) {
System.out.println("Invalid message :: Message Exceeds or 140 character or is null. Please check your message again ...");
return false;
}
return true;
}

public static void sendSMS() {
try {
System.out.println("URL: "+unicelURL+", SMS Message: "+testSMSForUnicelConnectivity);
String theURL = formURL();
URL url = new URL(theURL);

URLConnection connection = url.openConnection();
connection.setDoOutput(true);
OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream());
out.close();
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String str = null;
String decodedString = null;
//boolean sendFlag = false;
System.out.println("Sending SMS, Count: "+no_sms_sent);
no_sms_sent=no_sms_sent+1;
while ((str = in.readLine()) != null) {
decodedString = str;
System.out.println("Decoded Response String: "+decodedString);
}

in.close();
System.out.println("Message sent successfully to :"+testingMobileNo+"\n");
} catch (MalformedURLException e) {
System.out.println("URL Format Violation, Message sent Failed: "+e.getMessage());
} catch (IOException e) {
System.out.println("IO Exception, Message sent Failed: "+e.getMessage());
}
catch (Throwable e) {
System.out.println("Bigger Exception occured, Message sent Failed: "+e.getMessage());
e.printStackTrace();
}
}

public void sendRepeatedSMS(int interval) {
TimerTask tt = new TimerTask() {
public void run() {
System.out.println("Sending SMS Now :");
sendSMS();
}
};
t.scheduleAtFixedRate(tt, new Date(), interval*1000);
synchronized (TestUnicelConnectivity.class) {
try {
TestUnicelConnectivity.class.wait();
} catch (InterruptedException ie) {
System.out.println("Exception occured in Timer task: "+ie.getMessage());
}
}
}
}


//UnicelConfig.properties
UnicelURL=http://www.unicel.in/SendSMS/sendmsg.php
MobileNumber=919916473353
#Please specify the mobile number with 91 prefix, fortunately this is my number, please don't use this.

TestSms=Welcome to deepakmodi2006.blogspot.in, this is a test SMS for testing sending SMS.
IntervalForSmsToBeSentInSeconds=60
#Means in 60 seconds, it will send 1 sms. If you put 30, means 1 sms in 30 seconds.

//Thats it, now compile it in command prompt, pass the propeties file as command line argument and 
//SMS will be started sending every 60 seconds.

No comments:

Post a Comment