- Code: Select all
import java.io.*;
import java.util.*;
import javax.comm.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.sql.*;
public class Send_SMS
{
public ListenPort listenPort;
/*
* Send_SMS constructor creates an object for Gui class
*/
public Send_SMS()
{
ListenPort lp = new ListenPort();
lp.start();
}
/*
* main method creates an object for Send_SMS class
*/
public static void main(String args[])
{
Send_SMS sms = new Send_SMS();
}
}
/*
* class ListenPort gets the properties of thread and initiates
* the serial port listener to handle the data on serial port using
* its methods
* @version 1.0
* @author Sasi krishna
* @Date 02-02-2007
*/
class ListenPort extends Thread implements SerialPortEventListener {
//static Enumeration portList;
static CommPortIdentifier portId;
static String messageString;
static SerialPort serialPort;
static OutputStream outputStream;
static InputStream inputStream;
static boolean outputBufferEmptyFlag = false;
static Thread readThread;
private javax.swing.Timer timerTimeOut;
private byte[] globalBuffer;
private int MAXLOC=0;
private boolean completeInfo=false;
private int index=0,ACK=0;
private String msg1=new String();
private Vector intSmsBuf,intSmsBuf2;
private RequestSMS reqSMS;
private Connection con;
private ResultSet rs;
private Statement stmt;
private String query;
private int msgType=-1;
private int flag = 0;
Vector newvecs = new Vector();
int rows=0;
public boolean stopflag = false;
/*
* run method
* 1.opens the serial port using openSerialPort
* 2.checks for the messages to send
* 3.receives the messages */
public void run()
{
intSmsBuf=new Vector();
try{
this.sleep(10);}
catch(Exception e)
{
}
globalBuffer=new byte[1024];
// as for initial default case ate 1, the response is ate 0 OK.
// it is set to ate 0 and the response is not considered
//boolean echoFlag=false;
boolean echoFlag=false;
boolean newMsgFlag=false;
boolean textflag = false;
boolean saveflag = false;
boolean defaultflag = false;
con=DBOps.getConnection();
openSerialPort();
// set command echo mode OFF
//set for the default settings
setDefaultSetting();
//getting the result for the default settings
defaultflag = getResDefaultSettings();
/*if(defaultflag == false)
{
JOptionPane.showMessageDialog(null,"Cannot start the application \n Default settings are not configured","Information",JOptionPane.INFORMATION_MESSAGE);
System.exit(1);
}*/
//set the mode for the input text
setTextMode();
//get the response from the modem
textflag = getResponseforText();
/*if(textflag == false)
{
JOptionPane.showMessageDialog(null,"Restart the application \n as the text mode is not configured to the requirement","Information",JOptionPane.INFORMATION_MESSAGE);
System.exit(1);
}*/
/* if(saveflag == false)
{
JOptionPane.showMessageDialog(null,"Cannot start the application \n as the text mode is not saved properly","Information",JOptionPane.INFORMATION_MESSAGE);
System.exit(1);
}*/
// set command echo mode OFF
sendEchoOff();
// receive response for echo command
echoFlag=getEchoResponse();
//getEchoResponse();
// Set the SMS Message Indication Settings
offNewMsgIndication();
// get response for command : offNew MsgIndication
newMsgFlag=getResForNewMsgIndication();
saveTextMode();
//get the save response
saveflag = getSaveResponse();
// these two commands are send as startup commands to
// modem and if it fails to respond to these commands
// display the dialog " to connect the modem properly
// and to restart the application
//System.out.println("value of defaulflag is:"+defaultflag);
if(echoFlag==true && newMsgFlag==true && textflag==true && defaultflag==true && saveflag==true){
while(true){
sendReqForList();
getResForList();
if(newvecs.size() > 0)
{
ReceiveMessage();
}
Delay(4000);
// check wether there are any valid MESSAGE to be delivered from Database
getRecordsDB();
if(rows >0)
{
SendMessage();
}
Delay(4000);
}//end of while
}//end of if where port and database connection
else {
JOptionPane.showMessageDialog(null,"Restart the application \n as there is no response from modem","Information",JOptionPane.INFORMATION_MESSAGE);
System.exit(1);
}
}//end of run
//Delay method for 4 seconds delay
public void Delay(int time)
{
try{
Thread.sleep(time);
}
catch(Exception e)
{}
}
//method of getting records from the DB
public int getRecordsDB()
{
try{
stmt=con.createStatement();
String query9 = "SELECT count(*) from new_sms_send";
ResultSet rs9= stmt.executeQuery(query9);
if(rs9.next())
rows = rs9.getInt(1);
rs9.close();
stmt.close();
}
catch(SQLException e){}
return rows;
}
//Method to send the message from DB
public void SendMessage() {
try{
stmt=con.createStatement();
ResultSet rs1;
String query1 = "SELECT * FROM new_sms_send";
rs1 = stmt.executeQuery(query1);
while(rs1.next()){
int id = Integer.parseInt(rs1.getString(1));
String mobile = rs1.getString(2);
long mobileNum = Long.parseLong(mobile);
String sender = rs1.getString(3);
String sndMsg = rs1.getString(4);
int att = rs1.getInt(5);
String time = rs1.getString(6);
String sndMsgs = sndMsg+"\t\t\n " +"SENDER:\n"+sender;
// boolean flag=true;
if(att==0)
{
sendReply(mobileNum,sndMsgs);
boolean status=rcvSendStatus();
if(status==true)
{
try
{
String query = "INSERT INTO sucessful_send (message_id, cell_number, sender, message, send_time) values ("+id+","+mobileNum+", '"+sender.trim()+"', '"+sndMsg.trim()+"','"+time+"')";
stmt.executeUpdate(query);
String query4 = "DELETE FROM new_sms_send WHERE (message_id = "+id+")";
stmt.executeQuery(query4);
Delay(100);
System.gc();
}
catch(Exception e)
{
}
}//end of if for status
else
{
JOptionPane.showMessageDialog(null,"Unable to send the messages because there is no balance to send.");
System.exit(0);
}
}//end of if(att==0)
else
{
try{
String query10 = "INSERT INTO unsusessful_send (message_id, cell_number, sender, message, send_time) values ("+id+","+mobileNum+", '"+sender.trim()+"', '"+sndMsg.trim()+"','"+time+"')";
stmt.executeUpdate(query10);
String query5 = "DELETE FROM new_sms_send WHERE (message_id = "+id+")";
stmt.executeQuery(query5);
Delay(100);
System.gc();
}
catch(Exception e){
}
JOptionPane.showMessageDialog(null,"The message with message_id "+id+" is not valid because the attempts value is not 0");
}
}//end of while loop
rs1.close();
stmt.close();
}
catch(Exception e){
}//end of while(rs1)
}//End of the send method
//Method to receive message and store it into the DB
public void ReceiveMessage(){
for(int i=0;i<newvecs.size();i++) {
int temp =Integer.parseInt(newvecs.get(i).toString());
sendReqForMsg(temp);
String rcvMsg=getResForMsg();
String rcvMsg1 = rcvMsg.toString();
String[] parMsg=rcvMsg.split(",");
String msg=new String();
boolean unRead=false;
boolean validMsg=false;
// if the msg is not an error msg
if(parMsg.length > 1) {
if(parMsg[0].trim().equals("+CMGR: \"REC READ\"")) {
unRead=true;
}
//msgType=INVALID;
if(unRead==true) {
/* 0 1 2 3 4 5 6 7 8 9
+CMGR: "REC READ","+919866524337",,"05/08/11,19:10:32+08",145,4,0,0,"+9198450870
012345678901234
10 11
01",145,15
this 1234567890
OK */
byte crByte[]=new byte[1];
crByte[0]=13;
String cr=new String(crByte);
String[] msgSubStr=parMsg[11].split(cr);
int msgLen=Integer.parseInt(msgSubStr[0]);
int vlength = 0;
for(int j=0;j<=10;j++)
{
vlength += parMsg[j].length()+1;
}
msg=rcvMsg1.substring(vlength+3,vlength+4+msgLen);
reqSMS=new RequestSMS();
String mobileNo1=parMsg[1];
if(mobileNo1.length()==15 && mobileNo1.startsWith("+",1))
{
mobileNo1 = mobileNo1.substring(4,14);
long mobileNo = Long.parseLong(mobileNo1.trim());
reqSMS.set(mobileNo,msg,parMsg[3]+" "+parMsg[4],false);
intSmsBuf.add(reqSMS);
deleteSMSFromSIM(temp);
Delay(100);
System.gc();
}
else
{
deleteSMSFromSIM(temp);
Delay(100);
System.gc();
}
}
} // if msg.lENGTH>1
}// for < MAXLOC
}//end of receiving
//}//end of while
//setting the default settings
public void setDefaultSetting()
{
try {
String cmd="at&f";
outputStream.flush();
outputStream.write(cmd.getBytes());
// write CR
//System.out.println("command executed"+cmd);
outputStream.write(13);
} catch (IOException e) {}
}
//getting the response from the modem for default settings
public boolean getResDefaultSettings()
{
while(ACK==0) {
}
String strGB=new String();
for(int i=0;i<index;i++) {
if(globalBuffer[i]!=10 && globalBuffer[i]!=13) {
strGB+=(char)globalBuffer[i];
//System.out.println(globalBuffer[i]);
}
}
ACK=0;
if((strGB.trim()).equalsIgnoreCase("OK")) {
return true;
} else {
return false;
}
}
/* send at+cmgl command
forSIM */
public void sendReqForList() {
try {
String cmd="AT+CMGL=\"ALL\"";
outputStream.flush();
outputStream.write(cmd.getBytes());
// write CR
//System.out.println("command executed"+cmd);
outputStream.write(13);
} catch (IOException e) {}
}
/* get response at+cmgl
fromSIM */
// int indexarr[]=new int[40];
public void getResForList() {
while(ACK==0) {
}
String strGB=new String();
for(int i=0;i<index;i++) {
strGB+=(char)globalBuffer[i];
}
//System.out.println("Mu String ::"+strGB);
newvecs = getCMgrVals(strGB);
ACK=0;
}
Vector vec=new Vector();
public Vector getCMgrVals(String str)
{
int strIndx=0;
while(true){
int indx=str.indexOf("+CMGL:",strIndx);
int cmgrLen="+CMGL:".length();
if(indx<0)
break;
int x=0;
strIndx=indx+1;
String aa=str.substring(indx+cmgrLen,indx+cmgrLen+3).trim();
StringTokenizer snt = new StringTokenizer(aa,",");
String aaa = snt.nextToken().toString();
x=Integer.parseInt(aaa.trim());
vec.add(new Integer(x));
}
return vec;
}
/* set the text mode */
public void setTextMode() {
try
{
String cmd="at+csdh=1";
outputStream.flush();
outputStream.write(cmd.getBytes());
//write CR
outputStream.write(0x0D); // ENTER value
// verification of the response from MODEM whether OK or ERROR
}
catch (IOException e)
{}
}
/*get the response for setting text mode*/
public boolean getResponseforText() {
while(ACK==0) {
}
String strGB=new String();
for(int i=0;i<index;i++) {
if(globalBuffer[i]!=10 && globalBuffer[i]!=13) {
strGB+=(char)globalBuffer[i];
//System.out.println(globalBuffer[i]);
}
}
ACK=0;
if((strGB.trim()).equalsIgnoreCase("OK")) {
return true;
} else {
return false;
}
}
/*save the text mode*/
public void saveTextMode() {
try
{
String cmd="at&w";
outputStream.flush();
outputStream.write(cmd.getBytes());
//write CR
outputStream.write(13);
}
catch (IOException e)
{
}
}
/*get the saved response*/
public boolean getSaveResponse() {
while(ACK==0) {
}
String strGB=new String();
for(int i=0;i<index;i++) {
if(globalBuffer[i]!=10 && globalBuffer[i]!=13) {
strGB+=(char)globalBuffer[i];
//System.out.println(globalBuffer[i]);
}
}
ACK=0;
if((strGB.trim()).equalsIgnoreCase("OK")) {
return true;
} else {
return false;
}
}
/* sendEchoOff method */
public void sendEchoOff() {
try {
String cmd="ate 0";
outputStream.flush();
outputStream.write(cmd.getBytes());
// write CR
outputStream.write(13);
} catch (IOException e) {}
}
/* getEchoOffResponse method */
public boolean getEchoResponse() {
while(ACK==0) {
}
String strGB=new String();
for(int i=0;i<index;i++) {
if(globalBuffer[i]!=10 && globalBuffer[i]!=13) {
strGB+=(char)globalBuffer[i];
//System.out.println(globalBuffer[i]);
}
}
ACK=0;
if((strGB.trim()).equalsIgnoreCase("OK")) {
return true;
} else {
return false;
}
}
/* stop receiving the indication of New Message */
public void offNewMsgIndication() {
try {
String cmd="at+cnmi=1,1,0,0";
outputStream.flush();
outputStream.write(cmd.getBytes());
// write CR
outputStream.write(13);
} catch (IOException e) {}
}
/* get response for stopping the NewMessageIndication */
public boolean getResForNewMsgIndication() {
while(ACK==0) {
}
String strGB=new String();
for(int i=0;i<index;i++) {
if(globalBuffer[i]!=10 && globalBuffer[i]!=13) {
strGB+=(char)globalBuffer[i];
}
}
ACK=0;
if((strGB.trim()).equalsIgnoreCase("OK")) {
return true;
} else {
return false;
}
}
/* send request for maximum memory locations
that are supported by SIM */
public void sendReqForMaxLoc() {
try {
String cmd="at+cpms?";
outputStream.flush();
outputStream.write(cmd.getBytes());
// write CR
outputStream.write(13);
} catch (IOException e) {}
}
/* get response for maximum memory locations
that are supported by SIM */
public void getResForMaxLoc() {
while(ACK==0) {
}
String strGB=new String();
for(int i=0;i<index;i++) {
strGB+=(char)globalBuffer[i];
}
String[] s=strGB.split(",");
MAXLOC=Integer.parseInt(s[2]);
ACK=0;
}
/** send request for message at specified
memory location */
public void sendReqForMsg(int msgIndex) {
try {
String cmd="at+cmgr="+msgIndex;
outputStream.flush();
outputStream.write(cmd.getBytes());
// write CR
outputStream.write(13);
// System.out.println("the reding is:"+msgIndex);
} catch (IOException e) {}
}
/* get response for the requested message */
public String getResForMsg() {
while(ACK==0) {
}
String strGB=new String();
for(int i=0;i<index;i++) {
strGB+=(char)globalBuffer[i];
}
ACK=0;
return strGB;
}
/** delete SMS from SIM */
public void deleteSMSFromSIM(int msgIndex) {
try {
String cmd="at+cmgd="+msgIndex;
outputStream.flush();
outputStream.write(cmd.getBytes());
// write CR
outputStream.write(13);
} catch (IOException e) {}
}
/* send reply to the mobile number */
public void sendReply(long mobileNum,String msg) {
try {
String cmd="at+cmgs=\""+mobileNum+"\"";
outputStream.flush();
outputStream.write(cmd.getBytes());
// write CR
outputStream.write(13);
//after receiving '>' , send msg and ctrl+z
while(ACK==0) {
}
ACK=0;
cmd=msg;
outputStream.write(cmd.getBytes());
outputStream.write(26);
} catch (IOException e) {}
}
/** receive the status of the message that is send */
public boolean rcvSendStatus() {
while(ACK==0) {
}
String strGB=new String();
for(int i=0;i<index;i++) {
strGB+=(char)globalBuffer[i];
//System.out.println("buffer value:"+strGB[i]);
}
ACK=0;
// if the response is +CMGS(out of +CMGS: 23 <CR> OK) then send success
// else send failed
if(strGB.substring(2,7).equalsIgnoreCase("+CMGS")) {
return true;
} else {
return false;
}
}
/* *open serial port and set the required parameters */
public void openSerialPort() {
try {
System.out.println("Opening Comm port");
//portId = CommPortIdentifier.getPortIdentifier(ResourceLoader.getString("port"));
portId = CommPortIdentifier.getPortIdentifier("COM1");
} catch(NoSuchPortException nspe) {
JOptionPane.showMessageDialog(null,"Port COM1 Not Found","Information",JOptionPane.INFORMATION_MESSAGE);
System.exit(1);
}
try {
serialPort = (SerialPort) portId.open("ListenPort", 2000);
} catch (PortInUseException e) {
JOptionPane.showMessageDialog(null,"Port In use","Information",JOptionPane.INFORMATION_MESSAGE);
System.exit(1);
//System.out.println("Port in use.");
}
try {
outputStream = serialPort.getOutputStream();
inputStream = serialPort.getInputStream();
} catch (IOException e) {}
try {
serialPort.setSerialPortParams(9600,SerialPort.DATABITS_8,SerialPort.STOPBITS_1,SerialPort.PARITY_NONE);
//serialPort.setSerialPortParams(38400,SerialPort.DATABITS_8,SerialPort.STOPBITS_1,SerialPort.PARITY_NONE);
} catch (UnsupportedCommOperationException e) {}
try {
System.out.println("SMS is in process if you want to stop, press Ctrl+c");
serialPort.addEventListener(this);
} catch (TooManyListenersException e) {}
serialPort.notifyOnDataAvailable(true);
Logging.addToLogFile("Port is connected.");
}
/* Close serial port */
public void closePort() {
Logging.addToLogFile("Closed the port successfully.");
serialPort.close();
System.exit(0);
}
/** serialEvent method takes the events on serial port as input
if data is available on serial port, read the data in to buffer*/
public void serialEvent(SerialPortEvent event) {
switch(event.getEventType()) {
case SerialPortEvent.BI:
System.out.println("BI");
break;
case SerialPortEvent.OE:
System.out.println("OE");
break;
case SerialPortEvent.FE:
System.out.println("FE");
break;
case SerialPortEvent.PE:
System.out.println("PE");
break;
case SerialPortEvent.CD:
System.out.println("CD");
break;
case SerialPortEvent.CTS:
System.out.println("CTS");
break;
case SerialPortEvent.DSR:
System.out.println("DSR");
break;
case SerialPortEvent.RI:
System.out.println("RI");
break;
case SerialPortEvent.OUTPUT_BUFFER_EMPTY:
//System.out.println("OUTPUT_BUFFER_EMPTY");
break;
case SerialPortEvent.DATA_AVAILABLE:
//System.out.println("DATA_AVAILABLE");
byte readBuffer[]=new byte[1024];
int numBytes=0;
try {
this.sleep(1000);
index=0;
while(inputStream.available()>0 ) {
numBytes=inputStream.read(readBuffer);
for(int i=0;i<numBytes;i++) {
globalBuffer[index]=readBuffer[i];
index++;
}
}
} catch(InterruptedException ie) {
} catch(IOException ie) {
}
ACK=1;
break;
}
}
}
/* Database operations */
class DBOps {
public static Connection connection=null;
/* get database connection */
public static Connection getConnection() {
try {
//String driver = "com.microsoft.sqlserver.jdbc.SQLServerDriver";
Class.forName(ResourceLoader.getString("driver"));
connection = DriverManager.getConnection("jdbc:sqlserver://"+ResourceLoader.getString("constring")+";databaseName=sms",ResourceLoader.getString("uname"),ResourceLoader.getString("password"));
Statement stmt = connection.createStatement();
}
catch(SQLException se)
{
JOptionPane.showMessageDialog(null,"Database connection failed\n","Information",JOptionPane.INFORMATION_MESSAGE);
System.exit(1);
}
catch(ClassNotFoundException se)
{
JOptionPane.showMessageDialog(null,"unable to connect Database \n","Information",JOptionPane.INFORMATION_MESSAGE);
System.exit(1);
}
return connection;
}
/* close the database connection */
public static void closeDB() {
if(connection != null) {
try {
connection.close();
} catch(SQLException se) {
JOptionPane.showMessageDialog(null,"Database connection failed:"+se.getMessage(),"Information",JOptionPane.INFORMATION_MESSAGE);
System.exit(1);
}
connection=null;
}
}
}
/** The request send from user is stored in this class object */
/** The newly received msgs are inserted in to new_sms_rcvd if the msg is valid
else the msg is inserted into the rcvd_jnk table.*/
class RequestSMS{
long mobileNum;
String msg;
java.util.Date dateTime;
boolean sentStatus;
Statement stmt ;
/* set the values with the information from the request SMS received */
public void set(long num, String rcvMsg,String date_Time,boolean status) {
mobileNum=num;
msg=rcvMsg;
//"05/08/11,19:10:32+08"
//0123456789012345678901
int year=Integer.parseInt("20"+date_Time.substring(1,3));
int month=Integer.parseInt(date_Time.substring(4,6));
int date=Integer.parseInt(date_Time.substring(7,9));
int hour=Integer.parseInt(date_Time.substring(10,12));
int minutes=Integer.parseInt(date_Time.substring(13,15));
int seconds=Integer.parseInt(date_Time.substring(16,18));
dateTime=new java.util.Date(year,month,date,hour,minutes,seconds);
String time = year+"/"+month+"/"+date+" "+hour+":"+minutes+":"+seconds;
String[] nmsg = msg.trim().split("\\s");
String checktype = nmsg[0];
String real="";
for(int x=1; x<nmsg.length; x++)
{
real = real+" "+nmsg[x].trim()+" ";}
sentStatus=status;
Connection con = null;
try{
con = DBOps.getConnection();
stmt = con.createStatement();
ResultSet rs1;
String query1 = "SELECT msg_hrd FROM msg_header GROUP BY msg_hrd HAVING(COUNT(*) = 1)";
rs1 = stmt.executeQuery(query1);
int flag=0;
while(rs1.next())
{
if(checktype.trim().equalsIgnoreCase(rs1.getString(1).trim()))
{
flag = 1;
}
}
rs1.close();
if(flag ==1)
{
String query = "INSERT INTO new_sms_rcvd (cell_number, msg_header, msg_body, rcvd_time) values ("+mobileNum+", '"+checktype.trim()+"', '"+real.trim()+"','"+time+"')";
stmt.executeUpdate(query);
}
else
{
String checked = checktype.trim()+" "+real.trim()+" ";
String query3 = "INSERT INTO rcvd_junk (cell_number, msg_body, rcvd_time) values ("+mobileNum+", '"+checked.trim()+"','"+time+"')";
stmt.executeUpdate(query3);
}
stmt.close();
DBOps.closeDB();
}//end of while loop
catch(SQLException e)
{
}
}//emthod closing
}//end of class
In order ro run this supporting properties file must be there and the code for preferences.properties file is
//
port = COM1
driver = com.microsoft.sqlserver.jdbc.SQLServerDriver
constring = 192.168.1.36
uname = sa
password =
//
regards
sasi.


