Making simple SmsSendHub in java
We can receive any alarm data from udp and send them to in-house sms server. Here is an example of using Tibero Database.
SmsSenderHub.java
import java.io.*;
import java.io.File;
import java.io.FileReaer;
import java.io.FileWriter;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketTimeoutException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.sql.*;
import com.tmax.tibero.jdbc.*;
import com.tmax.tibero.jdbc.ext.*;
class SmsSendHub extends Thread {
static String mFileBase = null;
static String mReadFile = null;
static String mWriteFile = null;
static int MSG_LEN = 82 + 1; // Before Msg Field
public static void main(String args[]) {public static void main(String args[]) {
String msg = null;
String line = null;
boolean initRead = true;
int tryCnt = 0;
boolean isRunning = true;
Reader fileReader = null;
BufferedReader input = null;
if (args.length <= 0) {
writeLog(String.format("Parameters are required"));
return;
}
// -----------------------------
// Check config file
// -----------------------------
mFileBase = args[0];
String fname = String.format("$s.%s", mFileBase, new SimpleDateFormat("yyyyMMdd").format(new Date()));
mReadFile = fname;
writeLog(String.format("Args:[%d]", args.length));
writeLog(String.format("Read FileName:[%s]", mReadFile));
// -----------------------------
// Start UDP receive thread
// -----------------------------
Thread thread = new SmsSendHub();
thread.start();
try {
// -----------------------------
// Open File
// -----------------------------
try {
writeLog(String.format("Open ReadFile[%d]:[%s]", tyrCnt, mReadFile));
fileReader = new FileReader(mReadFile);
input = new BufferedReader(fileReader);
} catch (FileNotFoundException e) {
writeLog("FileNotFoundException:" + e.getMessage());
}
// -----------------------------
// Open DB
// -----------------------------
int rslt;
String sender. usrid, usrmsg, callbackno, phoneno, procsect;
Class.forName("com.tmax.tibero.jdbc.TbDriver");
Connection conn = DriverManager.getConnection("jdbc:tibero:thin:@127.0.0.1:8629:SMSDB", "dbusrid", "dbpasswd");
String sqlsmt;
sqlsmt = "insert into SMSTBL(col1, col2, col3, col4) values(?, ?, ?, ?);";
PrepareStatement pstmtsmt = conn.prepareStatement(sqlsmt);
// -----------------------------
// Main Loop
// -----------------------------
while (isRunning) {
fname = String.format("%s.%s", mFileBase, new SimpleDateFormat("yyyyMMdd").format(new Date()));
if (!mReadFile.equals(fname)) {
mReadFile = fname;
input.close();
fileReader.close();
tryCnt++;
writeLog(String.format("DateChangeOpen ReadFile[%d]:[%s]", tryCnt, mReadFile));
fileReader = new FileReader(mReadFile);
input = new BufferedReader(fileReader);
} else {
// Try open repeatedly
try {
if (fileReader == null || input == null) {
tryCnt++;
writeLog(String.format("ReOpen ReadFile[%d]:[%s]", tryCnt, mReadFile));
fileReader = new FileReader(mReadFile);
input = new BufferedReader(fileReader);
}
} catch (FileNotFoundException e) {
writeLog("FileNotFoundException: " + e.getMessage());
Thread.sleep(3000);
continue;
}
}
if (input == null) break;
if ((line = input.readLine()) != null) {
if (initRead != true) {
writeLog("READ : " + line);
if (line.length() >= MSG_LEN)
{
msg = line.substring(0,4);
writeLog(String.format("- MsgLen : [%s]", msg));
msg = line.substring(4,6);
writeLog(String.format("- MsgType : [%s]", msg));
msg = line.substring(6,8);
writeLog(String.format("- JobType : [%s]", msg));
msg = line.substring(8,24); callbackno = msg.trim();
writeLog(String.format("- CallbackNo : [%s]", msg));
msg = line.substring(44,60); sender = msg.trim();
writeLog(String.format("- Sender : [%s]", msg));
// ...
msg = line.substring(82); usrmsg = msg.trim();
writeLog(String.format("- Message : [%s]", msg));
msg = String.format("[%s]%s", sender.trim(), new String(usrmsg.getBytes(), "EUC-KR")); // cf. UTF-8
writeLog(String.format("PARAM:[%s][%s][%s][%s]%s", usrid, callbackno, phoneno, sender, usrmsg));
pstmtsmt.setString(1, usrid);
pstmtsmt.setString(2, msg);
pstmtsmt.setString(3, callbackno);
pstmtsmt.setString(4, phoneno);
rslt = pstmtsmt.executeUpdate(sqlsmt);
if (rslt == 1)
writeLog("INSERT Success");
else
writeLog("INSERT Error");
conn.commit();
} else {
writeLog("SKIP(TOO SHORT) : " + line);
}
} else {
writeLog("SKIP(EXPIRED) : " + line);
}
continue;
} // End of readLine
else {
initRead = false;
}
try {
Thread.sleep(1000L);
} catch (InterruptedException x) {
Thread.currentThread().interrupt();
break;
}
} // End of while
input.close();
pstmtsmt.close();
conn.close();
} catch (FileNotFoundException e) {
writeLog()"FileNotFoundException:" + e.getMessage());
isRunning = false;
} catch (IOException e) {
writeLog()"IOException:" + e.getMessage());
isRunning = false;
} catch (Exception e) {
writeLog()"Exception:" + e.getMessage());
isRunning = false;
}
try {
thread.interrupt();
} catch (Exception e) {
writeLog("Failed to stop thread: " + e.getMessage());
}
writeLog("Stop main process");
}
// -----------------------------
// Run Thread
// -----------------------------
public void run() {
writeLog("Thread is starting...");
initUdpRecv();
writeLog("Thread was ended.");
}
// -----------------------------
// Udp Recv Server
// -----------------------------
public void initUdpRecv() {
int port = 9090;
String fname = null;
FileWriter fw;
BufferedWriter out;
try {
fname = String.format("%s.%s", mFileBase, new SimpleDateFormat("yyyyMMdd").format(new Date()));
mWriteFile = fname;
fw = new FileWriter(mWriteFile, true); // Append mode
int timeout = 10000;
DatagramSocket dsocket = new DatagramSocket(port);
dsocket.setSoTimeout(timeout);
byte[] buffer = new byte[2048];
DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
writeLog(String.format("Listening... Port(%d)", port));
writeLog(String.format("Open WriteFile:[%s]", mWriteFile));
out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(new File(mWriteFile), true), "EUC-KR"));
while (isRunning) {
fname = String.format("%s.%s", mFileBase, new SimpleDateFormat("yyyyMMdd").format(new Date()));
if (!mWriteFile.equals(fname)) {
mWriteFile = fname;
out.close();
writeLog(String.format("DateChangeOpen WriteFile:[%s]", mWriteFile));
out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(new File(mWriteFile), true), "EUC-KR"));
} else {
File file = new File(mWriteFile);
if (!file.exists()) {
writeLog(String.format("ReOpen WriteFile:[%s]", mWriteFile));
out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(new File(mWriteFile), true), "EUC-KR"));
}
}
try {
dsocket.receive(packet);
} catch (SocketTimeoutException e) {
writeLog(String.format("Socket Timeout(%d)", timeout));
continue;
}
String tmp = new String(packet.getData(), 0, packet.getLength());
String msg = new String(packet.getData(), 0, packet.getLength(), "EUC-KR");
tmp = msg.replaceAll("\n", "").replaceAll("\r", "");
msg = msg.replaceAll("\n", "").replaceAll("\r", "");
if (msg.length() >= MSG_LEN) {
out.write(msg);
out.newLine();
out.flush();
writeLog(String.format("RECV:[%s][%s]", packet.getAddress(), tmp));
} else {
writeLog(String.format("RECV SKIP(TOO SHORT):[%s][%s]", packet.getAddress(), tmp));
}
}
out.close();
} catch (Exception e) {
System.err.println(e);
isRunning = false;
}
writeLog("Stop sub(thread) process");
}
// -----------------------------
// Logging
// -----------------------------
static void writeLog(String msg) {
String tm = new SimepleDateFormat("yyyyMMdd HH:mm:ss").format(new Date());
System.out.println(String.format("[%s] %s", tm, msg));
}
}
Compile in linux/unix (compile.sh)
set -x
javac -classpath ../lib/tibero5-jdbc.jar SmsSendHub.java
set +x
cp -pf SmsSendHub.class ../bin/.
ls -altr ../bin/SmsSendHub.class
Run in linux/unix (start_smssendhub.sh)
PGM_NM="SmsSendHub"
USR_ID=`whoami`
CUR_DIR=`pwd`
CHOME=$HOME/java
CDATE=`date +%Y%m%d`
CTIME=`date '+%Y-%m-%d %H:%M:%S'`
cd ${CHOME}/bin
for i in ${CHOME}/lib/*.jar; do
CLASSPATH="$CLASSPATH":"$i"
done
PROC_LIST()
{
ps -ef|grep ${PGM_NM}|grep java|grep classpath|grep -v ${PGM_NM}.java|grep -v grep
}
PROC_CNT()
{
ps -ef|grep ${PGM_NM}|grep java|grep classpath|grep -v ${PGM_NM}.java|grep -v grep|wc -l
}
PROC_PID()
{
ps -ef|grep ${PGM_NM}|grep java|grep classpath|grep -v ${PGM_NM}.java|grep -v grep|awk '{print $2}'
}
if [ $(PROC_CNT) = 0 ]
then
#. ~user/.profile
cd ${CHOME}/bin
(nohup java -classpath $CLASSPATH ${PGM_NM} $CHOME/dat/SmsSend.dat 2>&1) >> $CHOME/log/SmsSendHub.log.`date +%Y%m%d` &
echo "${CTIME} ${PGM_NM} has started"
PROC_LIST
else
echo "-----------------------------------------------------"
echo "${CTIME} ${PGM_NM} is already running."
echo "-----------------------------------------------------"
PROC_LIST
exit
fi
cd ${CUR_DIR}
Leave a comment