import java.io.*;
import java.util.*;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;
import java.net.*;
import com.joomfire.sms.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;
public class SMSGateway implements SmsListenerInterface
{
private static java.util.ResourceBundle res;
private static final String db_name = "test";
static SmsTerminal term = null;
private Connection con = null; //for database connection
private Statement stmt;
private ResultSet rs;
private String msgStatus = "";
private String check = "";
SynchronousQueue<OutMessage> smsQueue = new SynchronousQueue<OutMessage>();
public static void main(String[] args)
{
new SMSGateway();
}
public SMSGateway()
{
String str;
try
{
Class.forName("com.mysql.jdbc.Driver").newInstance();
}
catch (Exception e)
{
System.out.println("Exception in init(): Unable to load JDBC driver");
}
try
{
con = DriverManager.getConnection("jdbc:mysql://localhost:8806/test", "root", "");
System.out.println("conn: "+con);
}
catch (Exception e)
{
System.out.println("Exception in init(): Unable to establish connection to database '" + db_name + "'");
}
try
{
res = Utils.getResources();
}
catch (java.util.MissingResourceException mre)
{
mre.getMessage();
System.exit(1);
}
str = res.getString("samplesmsapp.SampleSmsApp_starting");
System.out.println(str);
String confFileName = "samplesmsapp.conf";
Properties conf = null;
FileInputStream confIn = null;
try
{
File confFile = new File(confFileName);
confIn = new FileInputStream(confFile);
conf = new Properties();
conf.load(confIn);
}
catch (IOException e)
{
System.err.println(res.getString("samplesmsapp.could_not_read_") + confFileName + ": " + e);
System.exit(1);
}
finally
{
try
{
if(confIn!=null)
confIn.close();
}
catch (IOException e) { ; }
}
System.out.println(res.getString("samplesmsapp.-_configuration_read"));
// get configuration parameter values.
String smsTerminalPort = conf.getProperty("smsTerminalPort");
int smsTerminalBitRate = Integer.parseInt(conf.getProperty("smsTerminalBitRate"));
boolean includeSmscInfoLen = new Boolean(conf.getProperty("includeSmscInfoLen")).booleanValue();
String smscAddress = conf.getProperty("smscAddress");
System.err.println(res.getString("samplesmsapp.-_connecting_to_SMS_terminal._please_wait."));
try
{
term = new SmsTerminal(smsTerminalPort, smsTerminalBitRate, this);
term.initialize();
if(includeSmscInfoLen)
{
term.setMsgOutIncludeSmscAddrLen(includeSmscInfoLen);
if(smscAddress != null)
term.setMsgOutSmscAddr(smscAddress);
}
}
catch (Exception e)
{
str=res.getString("samplesmsapp.unable_to_create_a_SmsTerminal");
System.err.println(str);
System.err.println(res.getString("samplesmsapp.msg:_") + e);
System.exit(1);
}
//Create new smsQueue thread here
SMSQueueThread smsQueueThread = new SMSQueueThread("SMS Queue Thread", smsQueue, System.out);
smsQueueThread.start();
str = res.getString("samplesmsapp.-_connected_to_terminal");
System.out.println(str);
try
{
ServerSocket ss = new ServerSocket(4444);
System.out.println("Server started... waiting for Client...");
while(true)
{
Socket connectToClient = ss.accept();
HandleAClient thread = new HandleAClient(connectToClient);
thread.start();
}
}
catch(IOException ex)
{
System.err.println(ex);
}
}
public void receiveSms(int statusCode, String errmsg, SmsMsgIncoming msg)
{
if(statusCode == SmsTerminal.SC_OK)
{
System.out.println(res.getString("samplesmsapp.msg_received:_") + msg.toString());
// Recieved SMS & HP
String rAdm = msg.getMessage();
String rNum = msg.getSenderNumber();
System.out.println("Recieve Message : " + rAdm);
System.out.println("Recieve Number : " + rNum);
// INSERT SMS & HP INTO DATABASE
try {
String xxx;
xxx="";
System.out.println("+65 ooo : " + xxx);
stmt = con.createStatement();
stmt.executeUpdate("INSERT INTO records(sms_id,admission_no,mobile_no,status,datetime) VALUES(null,'"+rAdm+"','"+rNum.substring(3, rNum.length())+"','in', now())");
}
catch (Exception e)
{
System.out.println("Exception in mySQL(): " + e.getMessage() );
}
}
else
{
System.err.println(res.getString("samplesmsapp.error_receiving_SMS_message:_") + errmsg);
}
}
public void destroy()
{
try {
if (con != null)
con.close();
}
catch (SQLException excIgnored){}
} // End destroy()
class HandleAClient extends Thread
{
private Socket connectToClient;
public HandleAClient(Socket socket)
{
this.connectToClient = socket;
}
public void run()
{
synchronized(connectToClient)
{
try
{
BufferedReader fromClient = new BufferedReader(new InputStreamReader(connectToClient.getInputStream()));
PrintWriter toClient = new PrintWriter(connectToClient.getOutputStream(), true);
String selection, outputLine;
while ((selection = fromClient.readLine()) != null)
{
String msg = "";
String num = "";
if(selection.equals("phone"))
{
// RECIEVE NUMBERS AND MSG FROM SERVLET
num = fromClient.readLine();
msg = fromClient.readLine();
System.out.println("Phone = " + num);
System.out.println("Message = " + msg);
try {
smsQueue.offer(new OutMessage(num, msg),10,TimeUnit.SECONDS);
}
catch (InterruptedException ie)
{
ie.printStackTrace();
}
// SendSMS sms = new SendSMS(num, msg);
// sms.start();
}
else
{
// RECIEVE GROUP AND MSG FROM SERVLET
String group = fromClient.readLine();
msg = fromClient.readLine();
System.out.println("Group : "+group);
try
{
stmt = con.createStatement();
rs = stmt.executeQuery("SELECT mobile_no FROM student WHERE course = '"+group+"'");
while(rs.next())
{
num = num + rs.getString(1) + ",";
}
System.out.println("Numbers = " + num);
smsQueue.offer(new OutMessage(num, msg),10,TimeUnit.SECONDS);
// SendSMS sms = new SendSMS(num, msg);
// sms.start();
}
catch (Exception e) {
e.printStackTrace();
}
}
}
}
catch(IOException ex)
{
System.err.println(ex);
}
}
}
}
class SendSMS extends Thread
{
private String num;
private String msg;
public SendSMS(String numbers, String message)
{
num = numbers;
msg = message;
System.out.println("Message = " + message);
}
public void run()
{
// BREAKING NUMBERS INTO TOKENS
StringTokenizer st = new StringTokenizer(num,",");
while (st.hasMoreTokens())
{
String sendNum_65 =st.nextToken().trim();
String sendNum = "65" + sendNum_65;
System.out.println("Phone = " + sendNum);
// SEND INDIVIDUAL TOKENS
try
{
System.err.println(res.getString("samplesmsapp.msg:_'") + sendNum + "', '" + msg + "'");
term.sendMessage(sendNum, msg);
try
{
stmt = con.createStatement();
stmt.executeUpdate("INSERT INTO smsrecords(admission_no,mobile_no,status,datetime) VALUES('"+sendNum_65+"','"+msg+"', now(), 'out')");
}
catch (Exception e)
{
System.out.println("Exception in mySQL(): " + e.getMessage() );
}
Thread.sleep(4800);
}
catch (StringIndexOutOfBoundsException e)
{
System.err.println(res.getString("samplesmsapp.msg_format:_number:message"));
}
catch(Exception ex) { }
}
}
}
public class SMSQueueThread extends Thread
{
private SynchronousQueue smsQueue;
private String consumerName;
private PrintStream printStream;
public SMSQueueThread(String consumerName, SynchronousQueue smsQueue, PrintStream printStream)
{
this.consumerName = consumerName;
this.smsQueue = smsQueue;
this.printStream = printStream;
}
public void run()
{
while (true)
{
try
{
OutMessage poll = (OutMessage)smsQueue.poll(20,TimeUnit.SECONDS);
printStream.println(this.consumerName + ": " + poll.getMsg() + " " + poll.gethpnumbers());
// BREAKING NUMBERS INTO TOKENS
StringTokenizer st = new StringTokenizer(poll.gethpnumbers(),",");
while (st.hasMoreTokens())
{
String sendNum_65 =st.nextToken().trim();
String sendNum = "65" + sendNum_65;
System.out.println("Phone = " + sendNum);
// SEND INDIVIDUAL TOKENS
try
{
System.err.println(res.getString("samplesmsapp.msg:_'") + sendNum + "', '" + poll.getMsg() + "'");
term.sendMessage(sendNum, poll.getMsg());
try
{
stmt = con.createStatement();
stmt.executeUpdate("INSERT INTO records(admission_no,mobile_no,status,datetime) VALUES('"+sendNum_65+"','"+poll.getMsg()+"', now(), 'out')");
}
catch (Exception e)
{
System.out.println("Exception in mySQL(): " + e.getMessage() );
}
Thread.sleep(4800);
}
catch (StringIndexOutOfBoundsException e)
{
System.err.println(res.getString("samplesmsapp.msg_format:_number:message"));
}
catch(Exception ex) {
ex.printStackTrace();
}
}
}
catch (InterruptedException ie)
{
ie.printStackTrace();
}
catch (NullPointerException ne)
{
ne.printStackTrace();
}
}
}
}
}