Tuesday, July 6, 2010

Final Report

MOBILE BASED SOLUTION PROVIDER

Mentor: Kuldeep Singh Meel (goldy.kuldeep@gmail.com)


Participants
:

1. Debashis Bhattacharya (debashis.besu@gmail.com) (IITB)

2. Prasanta Halder (prasanta.etc@gmail.com) (IITKgp)

INTRODUCTION

This project intends to provide a brief description of a keyword enquired by a cell phone. The customers’ mobile (mobile 1) will ask for description of a keyword and send the keyword to a particular no (mobile 2). Mobile 2, which is the solution provider, is connected to a PC. The program would search for the keyword on internet and reply back a brief description to the customer mobile (mobile 1).

The service provider mobile (mobile 2) must have GSM modem in it. Windows-XP Hyper Terminal SMS read and send commands are used in this program for our purpose. A Java code is written using those Hyper Terminal commands to provide solution to the inquired keyword.

System specification

For our project, we used:

i. Standard Java edition from java.sun, Java SE-6 and also javax.comm package (comm.jar) had to install separately

ii. As an editor, we used eclipse Java editor.

iii. We used windows XP environment for our project.

iv. Sony Ericsson W700i mobile with PC Suite is used as service provider (mobile 2)

A guideline to use

This project demands the access of three different persons.

1. Programmer or code modifier

2. Solution provider or code user

3. Ultimate user

A brief guideline is given for the usage of this program

1. Guideline for programmer:

Ø To modify this code, programmer must have comm.jar installed and included in the classpath.

2. Guideline for solution provider:

Ø Solution provider must have internet connection.

Ø Solution provider needs to set proxy settings in Settings.ini file.

Ø If proxy server demands authentication by User Id and Password, these are to be filled up in specified places. Else these two fields are to be kept blank.

Ø SendViaSerial in Settings.ini file enables solution provider to send SMS via mobile or way2sms. To send SMS through mobile, service provider needs to set ‘SendViaSerial=true’. If ‘SendViaSerial=false’, system will send SMS through way2sms.

Ø Before execution of this file programmer needs to know mobile is connected to which com port of the computer.

3. Guideline for ultimate user:

Ø Ultimate user needs to send SMS in a format. This is used to avoid false positive error. Else messages, not sent by any user also would have been replied.

Ø Ultimate user needs to place the word ‘code’ in front of the word he is asking the solution provider to search.

An introductory tour of windows Hyper Terminal commands

From Windows-XP using Hyper Terminal, messages can be read or sent through GSM modem. Specific Hyper Terminal commands are used in this program for our purpose. These commands are listed below:

§ AT+CMGF=0 //sets PDU mode

§ AT+CPMS=”ME” //sets mobile memory as default

§ AT+CMGL=0 //reads unread SMS

§ AT+CMGS=length of PDU string //sends SMS

>SMS code in PDU format

A brief description of PDU format

PDU (Protocol Description Unit) is a standard message encoding technique specified by European Telecommunications Standards Institute (ETSI). A seven bit encoding technique is used to encode higher number of characters in a message (1 character-7 bits).

PDU format of the message also contains information about the number to which message is to be sent and service centre number.

HIGH LEVEL DESCRIPTION

This system runs in service provider’s computer. A mobile with GSM modem is kept with it.

This system starts working with receipt of a SMS. When a SMS is received, it is read by the computer connected to it and the computer sends back its meaning, after searching in Internet.

This program executes an infinite loop. Whenever a new message is received, this program reads that message and starts working according to the desired path.


DESCRIPTION OF MAJOR MODULES/PARTS OF THE CODE

Program consists of four building blocks or 4 classes.

§ MobileServer

§ InternetDefination

§ ProxyAuthenticator

§ SmsFuction

1. MobileServer

MobileServer class is the main class of the program. In this class main method is written.

Ø main: Program first reads proxy address from a file “Settings.ini”. ‘sentviaserial’ is used to select whether message is to be sent through mobile or via way2sms site. If it is false, then program asks for was2sms Id and password and also sets a variable ‘msglen=140’. ‘main’ creates one InternetDefination type object (InetDef) and one SmsFuction type object (smsfcnt) which are used to ‘get definition of the keyword from internet’ and to ‘send and receive message’.

Ø EncodeSMS: Most of the mobiles do not operate in text mode, rather in an encrypted mode, called PDU (Protocol Description Unit) mode. So, before sending an SMS, we need to encode our message from text to PDU mode. EncodeSMS method does it with the help of ‘MakeStringToOctate’ method.

EncodeSMS returns a string ‘message’. This string contains message to be sent in PDU format. This string starts with “001100”. First “00” is SMS centre information. 00 means SMS centre no stored in the mobile will be used for sending SMS. Next “11” (here it represents hex 11 or 0001 0001 bit sequence) sets reply path, data header, etc. Next “00” asks phone to message reference number by itself.

Next two character in that string represents length of the phone number (in Hex). The first character is ‘0’ because number length is less than 16. (In program in the method Integer.toHexString len&0xff is passed. It is for safety. In case value of the integer ‘len’ happens to be more than hexadecimal FF, then this PDU formatting may cause damage.)

Next part of the string is “91” which means phone number is of international format.

Next part is mobile number in octet format followed by “0000AA”. “0000” sets protocol identifier and data coding scheme. “AA” sets validity period.

Next encoded information is message length and message in septet format.

Ø MakeStringToOctate: Mobile number is converted into a semi-octet format. At first it is checked whether the number length is odd or even. If the number length is odd, an ‘F’ is added at the end to convert it into even. Then each 2 characters of the string containing phone number are swapped. Like, if the number is “987654321”, the converted string is “89674523F1”.

Ø MakeStringToSeptets: This method converts message string (string that is to be sent via SMS) to an equivalent representation in septet domain (7 bits a character).

‘bit4mnext’ is used to detect how many bits are coming from earlier character. Each time a new character is read, bit4mnext gets increased (as 7 bit represents a character) and next character is shifted by ‘bit4mnext’ number of bits.

Ø DecodeSMS: This is a reverse process of encoding. When message is read in PDU format, DecodeSMS method converts it into text format and extracts sender’s number from PDU code. Class members ‘Sender_number and ‘User_dataare used to store decoded mobile number and read SMS. Service centre number and time stamp are redundant information in the PDU format, which is not used further.

Ø MakeOctateToString: Like MakeStringToOctate method, it also does ‘2 character swapping’. It decodes sender’s number from PDU strings.

Ø ConvertHextoInteger: This method is called to find sender’s number and SMS length by converting hexadecimal expression of length to decimal number.

Ø MakeSeptetsToString: The reverse of MakeStringToSeptets method, it decodes message from septet string. In a similar way, bit shifting is used to convert 7 bit representation to 8 bit representation.

2. InternetDefination

This class is used to find meaning of a keyword from internet. Google search of the definition of the keyword is used to find its meaning.

Ø InternetDefination: Constructor is used to set proxy settings. ‘Authenticator.setDefault’ method takes ‘Authenticator’ type object and sets authentication with proxy User ID and password.

Ø GetDefination: This public method is called in main method. It takes the code to be searched in net and the number of characters that can be sent via SMS (if way2sms is selected, then number of characters would be 140).

This method creates an URL object passing the string of ‘google search URL’ in its constructor.

An ‘URLConnection’ type object ‘connection’ is used for reading input buffer. The input from buffer is stored in a string ‘totalString’.

Now in ‘totalString’ keyword "Web definitions for "is searched. If this is found then a variable is set by a value index=’position of W’ (in "Web definitions for ") +20(20 is the length of the string "Web definitions for ” including ending space). Using an ‘infinite while loop’ string between ‘<’and ‘>’ is scanned. A file “modifier.dic” is used to reduce the string length by replacing few words by its equivalent words.

First 160/140 characters are extracted to send through message.

3. ProxyAuthenticator

This class extends ‘Authenticator’ class. Constructor takes User ID and password and the method ‘getPasswordAuthentication’ returns a ‘PasswordAuthentication’ type object.

An object of class is passed in ‘InternetDefination’ constructor ‘Authenticator.setDefault’ method.

4. SmsFuction:

SMSfunction class object is used to send and receive SMS.

Ø SmsFuction: constructor of this class sets port for data transfer with mobile. On detection of a port program asks the user (solution provider) whether this is the active port for mobile. If the reply is ‘y’, then serial port parameter vales are set.

Ø CloseConnection: This method is called to close port after operation.

Ø serialEvent: This method checks for availability of data at serial port after every 10 milisecond. When data is available, a Boolean type variable flag is set to true. On unavailability of data, this variable is set to false.

Ø IsConnected: This method returns true if connection is made through serial port. Else it returns false.

Ø RecvSMS: This method called in an infinite loop in main method. After every 1000 millisecond this method is called in main method.

On data availability variable flag is set to true by the method serialEvent. Program tries with “AT+CMGL=0” command whether any unread SMS is available or not. If any unread message is read, this method reads it and sends it to main method.

Ø SendSMS: This message is called in main function. This is used to send SMS by “AT+CMGS” command.

Ø SendSMSViaWay2Sms: This method reads way2sms ID and password and message string (in text format). This method, on call sends SMS through way2sms.

RESULTS

This program reads SMS and reply back directly to the sender’s number. With a few input messages program is checked. These input messages are “code apple”, “code einstein”, “code mossad”. The reply that was obtained was search result of their definition. Search result of “define apple”, “define einstein”, “define mossad” is replied back to the sender’s mobile.

CONCLUSION

The common way of message reading is used in this program. But some mobiles show aberrations. Most of the Nokia sets don’t support this way of reading SMS. User of this program needs to check first from Hyper Terminal whether the commands are working properly or not. The developers have tried to write a generalized code, but available system limitations restrict program’s successful execution.

REFERENCES

For this program, we referred to the following web sources:

http://www.dreamfabric.com/sms/

http://www.developershome.com/sms/howToReceiveSMSUsingPC.asp

CHALLENGES

The challenges that we faced during this project were

§ We first tried with Nokia 7310 supernova set. It supports both text and PDU mode. Through GSM modem message can be sent through set, but it does not support AT+CPMS=”ME” command and hence we couldn’t go further with this mobile. Next we used Sony Ericsson W700i. This time the mobile did not support text mode. So, we continued with PDU mode for any mobile.

§ The next challenge we faced was to set proxy authentication ID password. But web sources helped up to obviate that problem.

CONTRIBUTION OF EACH TEAM MEMBER

Most of the time, we worked together on our project. Instead of sub dividing modules, we tried to face every module together. Discussion on gtalk helped us come up with a solution easily. But still there was a little division of modules:

v Debashis Bhattacharya: Major contributions

o Forming Idea of the project

o Approaching web and coding club for project and updating reports on blog

o Coding for sending and receiving SMS

o Report writing

v Prasanta Halder: Major contributions:

o Coding for searching definition of keyword in internet

o Coding for sending and receiving SMS (few parts)

ACKNOWLEDGEMENTS

I would, first of all, like to thank Web and coding club, IITB for providing us such a nice scope to work on a project decided by ourselves. I thank members of web and coding club for suggesting a way out when I faced problem with importing javax.comm package. I thank my mentor Kuldeep for being patient and encouraging me to work on.

ENTIRE CODE:

1. FILE: Settings.ini

#MobileServer Settings File.If you want to modify the setting of MobileServer you hav to modify it.

#To set Proxy address, use line as below

#Proxy-Address=[Your proxy address]

Proxy-Address=netmon.iitb.ac.in

#To set Proxy port, use line as below

#Proxy-Port=[Your proxy port]

Proxy-Port=80

#To set Proxy Authorization User ID, use line as below

#Proxy-UserID=[Authorization User ID]

Proxy-UserID=debashis

#To set Proxy Authorization Password, use line as below

#Proxy-Password=[Authorization Password]

Proxy-Password=bhattacharya

#To set SMS sending type use this.If you are sending SMS via Serial port write

#SendViaSerial=true

#else if you want to send sms using Way2sms write like below

#SendViaSerial=false/true

SendViaSerial=true

2. FILE: modifier.dic

but bt

can cn

one 1

what wht

because bcz

that dat

" "

' '

and n

3. FILE: MobileServer.java

import java.io.BufferedInputStream;

import java.io.BufferedReader;

import java.io.File;

import java.io.FileInputStream;

import java.io.FileNotFoundException;

import java.io.IOException;

import java.io.InputStreamReader;

public class MobileServer

{

static String User_data=null;

static String Sender_number=null;

public static void main(String args[]) throws IOException

{

String proxyadr=null;

String proxyport=null;

String proxyuid=null;

String proxypass=null;

boolean sentviaserial=true; //0 for way2sms and 1 for serial port

boolean ok2sms=true;

String settingsline;

File fset = new File("settings.ini");

FileInputStream fis = null;

try

{

fis = new FileInputStream(fset);

}

catch (FileNotFoundException e)

{

System.out.println("Cannot load settings. settings.ini file is not found."+e);

}

if(fis!=null)

{

BufferedInputStream bis = new BufferedInputStream(fis);

BufferedReader bufrdr= new BufferedReader(new InputStreamReader(bis));

String command,value;

try

{

while(true)

{

settingsline=bufrdr.readLine();

if(settingsline==null)

break;

if(settingsline.startsWith("#"))

continue;

int index=settingsline.indexOf("=");

if (index<0)

continue;

value=settingsline.substring(index+1);

command=settingsline.substring(0, index);

if(command.equalsIgnoreCase("Proxy-Address"))

proxyadr=value;

if(command.equalsIgnoreCase("Proxy-Port"))

proxyport=value;

if(command.equalsIgnoreCase("Proxy-UserID"))

proxyuid=value;

if(command.equalsIgnoreCase("Proxy-Password"))

proxypass=value;

if(command.equalsIgnoreCase("SendViaSerial"))

{

if(value.equalsIgnoreCase("true"))

sentviaserial=true;

else

sentviaserial=false;

}

}

}

catch(IOException e)

{

System.out.println("Error in settings.ini file."+e);

}

if(fis!=null)

fis.close();

}

//System.out.println(proxyadr+proxyport+proxyuid+proxypass+sentviaserial);

InternetDefination InetDef=new InternetDefination(proxyadr,proxyport,proxyuid,proxypass);

String Inet_Definition=null;

String Way2SMS_uid = null;

String Way2SMS_pswd = null;

if(sentviaserial==false)

{

System.out.println("Give the Way2Sms User ID-");

BufferedReader Way2SMS_br = new BufferedReader(new InputStreamReader(System.in));

Way2SMS_uid=Way2SMS_br.readLine();

System.out.println("Give the Way2Sms Password-");

Way2SMS_pswd = Way2SMS_br.readLine();

}

//initialization of connections

SmsFuction smsfcnt=new SmsFuction();

//Checking is connected or not

if(smsfcnt.IsConnected()==false)

{

System.out.println("Yet not connected with modem.Install modem and restart application.");

return;

}

//Infinite loop to receive sms and send result

String temp;

int tmps,tmpe;

while(true)

{

//Receiving SMS

try

{

String msg=smsfcnt.RecvSMS();

if(msg==null||msg.length()<=0)

{

System.out.println("No new message.Waiting...");

Thread.sleep(1000);

continue;

}

tmps=msg.indexOf("+CMGL:")+1;

if(tmps<0)

{

Thread.sleep(1000);

continue;

}

tmpe=msg.indexOf(',', tmps+6);

temp=msg.substring(tmps+6, tmpe);

System.out.println("Sms location="+temp);

Integer.parseInt(temp);

tmps=msg.indexOf("079");

if(tmps<0)

{

System.out.println("Message arrived.but format is unknown.");

Thread.sleep(1000);

continue;

}

tmpe=msg.indexOf("OK", tmps);

temp=msg.substring(tmps,tmpe);

System.out.println("msg data="+temp);

DecodeSMS(temp);

System.out.println(msg);

}

catch (Exception e)

{

System.out.println("Error in receiving sms procudure: "+e);

continue;

}

User_data=User_data.trim();

if(!User_data.startsWith("code "))

ok2sms=false;

else

User_data.replaceFirst("code ","");

//Getting definition from Internet

if(ok2sms)

System.out.println("\nRequest from "+ Sender_number + " for "+ "defination of \""+User_data+"\"");

int msglen=140;

if(sentviaserial)

msglen=160;

if(ok2sms)

Inet_Definition=InetDef.GetDefination(User_data,msglen);

System.out.println("Sending "+ Sender_number + ": "+Inet_Definition +"\n");

//Sending SMS

try

{

if(sentviaserial)

{

if(Sender_number.length()==10)

Sender_number="91"+Sender_number;

if(Sender_number.length()==11&&Sender_number.startsWith("0"))

Sender_number=Sender_number.replaceFirst("0", "91");

if(Sender_number.startsWith("+"))

Sender_number=Sender_number.replaceFirst("+","");

if(Sender_number.length()!=12)

{

System.out.println("Error:Invalid Mobile number");

ok2sms=false;

//continue;

}

if (ok2sms)

{

String msg=EncodeSMS(Sender_number,Inet_Definition);

System.out.println("Coded message is="+msg);

smsfcnt.SendSMS(msg);

}

}

else

{

SmsFuction.SendSMSViaWay2Sms(Way2SMS_uid,Way2SMS_pswd,Sender_number,Inet_Definition);

}

}

catch (Exception e)

{

System.out.println("Error in sending sms procudure: "+e);

break;

}

}

//Closing modem connection

smsfcnt.CloseConnection();

}

static String EncodeSMS(String mobnum,String body)

{

String message="",tempstr;

int len=mobnum.length();

if(len<16)

message="001100"+"0"+Integer.toHexString(len&0xff)+"91";

else

message="001100"+Integer.toHexString(len&0xff)+"91";

tempstr=MakeStringToOctate(mobnum);

message=message+tempstr+"0000AA";

tempstr=MakeStringToSeptets(body);

len=((tempstr.length()+2)/2)&0xFF;

if(len<16)

message=message+"0"+Integer.toHexString(len)+tempstr;

else

message=message+Integer.toHexString(len)+tempstr;

message=message.toUpperCase();

return message;

}

static String MakeStringToOctate(String msg)

{

String modstr="";

for(int i=0;i

{

if((i+1)==msg.length())

modstr=modstr+'F';

else

modstr=modstr+msg.charAt(i+1);

modstr=modstr+msg.charAt(i);

}

return modstr;

}

static String MakeStringToSeptets(String msg)

{

String sept="";

int bit4mnext=1,shift,frmnext;

int hexlen=msg.length();

for(int i=0;i

{

if(bit4mnext>7)

{

bit4mnext=1;

continue;

}

shift=(8-bit4mnext);

if(bit4mnext!=0)

{

if(i>=(hexlen-1))

frmnext=0;

else

frmnext=((msg.charAt(i+1)&(0xFF>>shift))&0xFF)<

sept=sept+Integer.toHexString(frmnext |((msg.charAt(i)&0x7F)>>(bit4mnext-1)));

}

bit4mnext++;

}

return sept;

}

static void DecodeSMS(String message)

{

int SMSC_length;

String Service_center_number;

int Address_Length;

String Time_stamp;

int User_data_length;

String tmpstr;

tmpstr=message.substring(0, 2);

SMSC_length=ConvertHextoInteger(tmpstr);

tmpstr=message.substring(4,(SMSC_length-1)*2+4);

Service_center_number=MakeOctateToString(tmpstr,SMSC_length-1);

System.out.println("Service_center_number="+Service_center_number);

tmpstr=message.substring((SMSC_length+2)*2,(SMSC_length+2)*2+2);

int temp=ConvertHextoInteger(tmpstr);

Address_Length=temp/2+temp%2;

tmpstr=message.substring((SMSC_length+4)*2, (SMSC_length+Address_Length+4)*2);

Sender_number=MakeOctateToString(tmpstr,Address_Length);

System.out.println("Sender_number="+Sender_number);

tmpstr=message.substring((Address_Length+SMSC_length+6)*2, (Address_Length+SMSC_length+6)*2+14);

//Convert to time

Time_stamp=tmpstr;

System.out.println("Time_stamp= "+Time_stamp);

tmpstr=message.substring((Address_Length+SMSC_length+13)*2,(Address_Length+SMSC_length+13)*2+2);

temp=ConvertHextoInteger(tmpstr)*7;

if(temp%8==0)

User_data_length=temp/8;

else

User_data_length=temp/8+1;

System.out.println("User_data len="+User_data_length);

tmpstr=message.substring((Address_Length+SMSC_length+14)*2,(Address_Length+SMSC_length+14)*2+User_data_length*2);

User_data=MakeSeptetsToString(tmpstr,User_data_length);

System.out.println("body="+message);

}

static String MakeOctateToString(String octate,int len)

{

String modstr="";

for(int i=0;i

{

modstr=modstr+octate.charAt(i+1);

modstr=modstr+octate.charAt(i);

}

return modstr;

}

static int ConvertHextoInteger(String hex)

{

return Integer.valueOf(hex, 16).intValue();

}

static String MakeSeptetsToString(String septect,int hexlen)

{

String msg="";

String tmpstr;

int bitavl4mlast=0,shift,avdata,mval=0;

int[] data=new int[200];

for(int i=0;i

{

tmpstr=septect.substring(i,i+2);

data[mval++]=ConvertHextoInteger(tmpstr);

}

for(int i=0;i

{

if(bitavl4mlast>=7)

{

msg=msg+(char)((data[i-1]&0xFE)>>1);

bitavl4mlast=0;

}

shift=(8-bitavl4mlast);

if(bitavl4mlast!=0)

{

avdata=((data[i-1]&(0xFF<>shift;

msg=msg+(char)(avdata | ((data[i]&(0x7F>>bitavl4mlast))<

}

else

msg=msg+(char)(data[i]&0x7F);

bitavl4mlast++;

}

return msg;

}

/* private static String getstring(String str)

{

int a[]=new int[2];

str=str.trim();

for (int i=0;i<2;i++)

{

while (true)

{

a[0]=0;

a[1]=str.length()-1;

if(str.charAt(a[i])=='\"'||str.charAt(a[i])=='\''||str.charAt(a[i])=='>'||str.charAt(a[i])=='<'||str.charAt(a[i])=='.')

a[i]=a[i]+1-2*i;

else

break;

str=str.substring(a[0],a[1]);

}

}

return str.trim();

}*/

}

4. FILE: InternetDefination.java

import java.io.BufferedInputStream;

import java.io.BufferedReader;

import java.io.DataInputStream;

import java.io.File;

import java.io.FileInputStream;

import java.io.FileNotFoundException;

import java.io.IOException;

import java.io.InputStreamReader;

import java.net.Authenticator;

import java.net.MalformedURLException;

import java.net.URL;

import java.net.URLConnection;

public class InternetDefination

{

public InternetDefination(String proxy,String port,String username,String password)

{

System.setProperty("http.proxyHost", proxy);

System.setProperty("http.proxyPort", port);

Authenticator.setDefault(new ProxyAuthenticator(username,password));

}

public String GetDefination(String searchStr,int msglen)

{

//Get definition from internet

searchStr=searchStr.replaceAll(" ", "+");

//String google="http://www.google.ca/search?q=define+"+ searchStr + "&hl=en&ie=UTF-8&oe=UTF8";

String google="http://www.google.co.in/search?q=define+"+ searchStr + "&hl=en&ie=UTF-8&oe=UTF8";

URL urlObject = null;

String decodedString,totalstring;

try

{

urlObject = new URL(google);

}

catch (MalformedURLException e)

{

decodedString="Fatal error: could not connect to server (" + e + ")";

return decodedString;

}

URLConnection connection;

try

{

connection = urlObject.openConnection();

}

catch (IOException e)

{

decodedString="Fatal error: could not connect to server (" + e+ ")";

return decodedString;

}

connection.setRequestProperty( "User-Agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0)" );

BufferedReader in;

try

{

in = new BufferedReader(new InputStreamReader(connection.getInputStream()));

}

catch (IOException e)

{

decodedString="Fatal error: could not connect to server (" + e+")";

return decodedString;

}

try {

totalstring="";

while ((decodedString = in.readLine()) != null)

{

totalstring=totalstring+decodedString;

}

} catch (IOException e) {

decodedString="Fatal error: could not connect to server (" + e+")";

return decodedString;

}

try

{

in.close();

}

catch (IOException e)

{

decodedString="Fatal error: could not connect to server (" + e+")";

return decodedString;

}

//Now extract the definition from google search

int index=totalstring.indexOf("Web definitions for ");

if(index==-1)

{

decodedString="Sorry : No defination is available";

return decodedString;

}

index=index+20;

decodedString="";

while(true)

{

if(index>=totalstring.length())

break;

if(totalstring.charAt(index++)=='<')

{

while(totalstring.charAt(index++)!='>')

{

if(index>=totalstring.length())

break;

}

}

else

{

int i;

index=index-1;

for (i=index;i

{

if (totalstring.charAt(i)=='<')

break;

}

if(decodedString.length()==0)

{

decodedString=totalstring.substring(index, i);

}

else

{

decodedString=decodedString+':'+totalstring.substring(index, i);

break;

}

index=i;

}

}

//Now replace the modifiers

DataInputStream dis = null;

File f = new File("modifier.dic");

FileInputStream fis = null;

try

{

fis = new FileInputStream(f);

}

catch (FileNotFoundException e)

{

System.out.println("Cannot open modifier file.No modifier is loaded."+e);

}

if(fis!=null)

{

BufferedInputStream bis = new BufferedInputStream(fis);

BufferedReader bufrdr= new BufferedReader(new InputStreamReader(bis));

try

{

while ( true )

{

totalstring=bufrdr.readLine();

if(totalstring==null)

break;

String [] temp = null;

temp = totalstring.split(" ");

decodedString=decodedString.replaceAll(temp[0], temp[1]);

}

}

catch (IOException e)

{

System.out.println("Error in Reading Modifier File "+e);

}

if (dis != null)

{

try

{

dis.close();

}

catch (IOException e)

{

System.out.println("Error in Reading Modifier File "+e);

}

}

try

{

fis.close();

}

catch (IOException e)

{

System.out.println("Error in Reading Modifier File "+e);

}

}

//Now extract msglen(160) character string optimized one

index=decodedString.indexOf("...");

if((index!=-1 && index==(decodedString.length()-3))||decodedString.length()>(msglen-1))

{

index=decodedString.lastIndexOf(";");

if(index==-1)

{

if(decodedString.length()>msglen)

decodedString=decodedString.substring(0, msglen-2);

}

else

{

decodedString=decodedString.substring(0, index);

}

}

decodedString=decodedString.replaceAll("; ", ".");

decodedString=decodedString+'.';

return decodedString;

}

}

5. FILE: ProxyAuthenticator.java

import java.net.Authenticator;

import java.net.PasswordAuthentication;

public class ProxyAuthenticator extends Authenticator

{

private String username,password;

public ProxyAuthenticator(String username,String password)

{

this.username = username;

this.password = password;

}

public PasswordAuthentication getPasswordAuthentication()

{

return new PasswordAuthentication(username,password.toCharArray());

}

}

6. FILE: SmsFuction.java

import java.io.BufferedReader;

import java.io.IOException;

import java.io.InputStream;

import java.io.InputStreamReader;

import java.io.OutputStream;

import java.util.Enumeration;

import java.util.TooManyListenersException;

import javax.comm.CommPortIdentifier;

import javax.comm.PortInUseException;

import javax.comm.SerialPort;

import javax.comm.SerialPortEvent;

import javax.comm.SerialPortEventListener;

import javax.comm.UnsupportedCommOperationException;

import java.io.OutputStreamWriter;

import java.io.PrintWriter;

import java.net.HttpURLConnection;

import java.net.URL;

import java.net.URLEncoder;

import java.util.Iterator;

import java.util.Vector;

public class SmsFuction implements SerialPortEventListener

{

static InputStream inputStream;

static OutputStream outputStream;

static SerialPort serialPort = null;

String output=null;

int numBytes=0;

static boolean flag=false;

//Initialization Constructor

@SuppressWarnings("unchecked")

public SmsFuction()

{

Enumeration portList;

CommPortIdentifier portId = null;

portList = CommPortIdentifier.getPortIdentifiers();

System.out.println("Searching ports...");

while (portList.hasMoreElements())

{

portId = (CommPortIdentifier) portList.nextElement();

if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL)

{

System.out.println("Found Communication Port:"+portId.getName());

System.out.println("Is it the port in which the GSM modem connected? (Press Y/N).");

char c = 0;

try

{

BufferedReader ipbr = new BufferedReader(new InputStreamReader(System.in));

c = (char) ipbr.read();

}

catch (IOException e)

{

System.out.println("Error in Reading Keyboard Input "+e);

}

if(c=='Y'||c=='y')

{

try

{

serialPort = (SerialPort) portId.open("MobileServerApplication", 2000);

System.out.println("Successfully opened : "+serialPort.getName());

}

catch (PortInUseException e)

{

System.out.println("Fatal Error : Port In Use " + e);

}

try

{

outputStream = serialPort.getOutputStream();

inputStream = serialPort.getInputStream();

}

catch (IOException e)

{

System.out.println("Error in reading and/or writing to modem data stream " + e);

}

try

{

serialPort.setSerialPortParams(9600, SerialPort.DATABITS_8,SerialPort.STOPBITS_1,SerialPort.PARITY_NONE);

}

catch (UnsupportedCommOperationException e)

{

System.out.println("Error:Can't set serial port parameters");

}

try

{

serialPort.addEventListener(this);

}

catch (TooManyListenersException e)

{

System.out.println("Exception in Adding Listener" + e);

}

serialPort.notifyOnDataAvailable(true);

serialPort.notifyOnCarrierDetect(false);

serialPort.notifyOnDataAvailable(true);

serialPort.notifyOnBreakInterrupt(false);

serialPort.notifyOnCTS(false);

serialPort.notifyOnDSR(false);

serialPort.notifyOnFramingError(false);

serialPort.notifyOnOutputEmpty(true);

serialPort.notifyOnOverrunError(false);

serialPort.notifyOnParityError(false);

serialPort.notifyOnRingIndicator(false);

break;

}

}

}

if(serialPort==null)

System.out.println("No more port exists.Install modem and restart application.");

}

public void CloseConnection()

{

if(serialPort!=null)

{

serialPort.close();

System.out.println("\nSuccessfully Closed : "+serialPort.getName());

}

}

public void serialEvent(SerialPortEvent event)

{

switch (event.getEventType())

{

case SerialPortEvent.OUTPUT_BUFFER_EMPTY:

// System.out.println("Error while reading Port:Output Buffer Empty");

break;

case SerialPortEvent.DATA_AVAILABLE:

{

flag=false;

output="";

byte[] readBuffer = new byte[50];

try

{

while (inputStream.available() > 0)

{

numBytes = inputStream.read(readBuffer);

if(numBytes>0)

{

String temp=new String(readBuffer);

output=output+temp;

}

Thread.sleep(10);

}

output.replaceAll(" ", "");

output.replaceAll("\r\n", "");

output=output.toUpperCase();

flag=true;

}

catch (IOException e) {

System.out.println("Error while reading Port " + e);

}

catch (InterruptedException e) {

System.out.println("Error while suspending thread " + e);

}

}

break;

}

}

public boolean IsConnected()

{

if(serialPort==null)

{

//System.out.println("Yet not connected with modem.Install modem and restart application.");

return false;

}

return true;

}

public String RecvSMS() throws Exception

{

String command = null;

String msg="";

outputStream.flush();

try

{

command = "AT+CMGF=0\r\n";

outputStream.write(command.getBytes());

flag=false;

while(flag==false)

Thread.sleep(10);

if(output.indexOf("OK")<0)

{

System.out.println("Error:Output after sending AT+CMGF=0 message "+output);

return msg;

}

command = "AT+CPMS=\"ME\"\r\n";

outputStream.write(command.getBytes());

flag=false;

while(flag==false)

Thread.sleep(10);

if(output.indexOf("OK")<0)

{

System.out.println("Error:Output after sending AT+CPMS=\"ME\" message "+output);

return msg;

}

command = "AT+CMGL=0\r\n";

outputStream.write(command.getBytes());

flag=false;

while(flag==false)

Thread.sleep(10);

System.out.println("Error:Output after sending AT+CMGL=0 message "+output);

if(output.indexOf("ERROR")>=0)

{

System.out.println("Error:Output after sending AT+CMGL=0 message "+output);

return msg;

}

else

{

msg=output;

return msg;

}

}

catch (IOException e)

{

System.out.println("Error in Receiving message:" + e);

}

return msg;

}

public void SendSMS(String message) throws Exception

{

String command = null;

int len=(message.length()/2)-1;

if(len%2!=0)

{

message=message+'F';

len=len+1;

}

if ((message == null) || (message.length() == 0))

{

throw new IllegalArgumentException("SMS message should be present.");

}

outputStream.flush();

try

{

command = "AT+CMGF=0\r\n";

outputStream.write(command.getBytes());

flag=false;

while(flag==false)

Thread.sleep(10);

if(output.indexOf("OK")<0)

{

System.out.println("Error:Output after sending AT+CMGF=0 message "+output);

return;

}

command = "AT+CMGS="+len+"\r\n";

outputStream.write(command.getBytes());

flag=false;

Thread.sleep(10);

outputStream.write(message.getBytes());

outputStream.write(26);

outputStream.write("\r\n".getBytes());

flag=false;

while(flag==false)

Thread.sleep(10);

if(output.indexOf("ERROR")>=0)

{

System.out.println("Error:Output after sending "+command+ "message="+output);

return;

}

}

catch (IOException e)

{

System.out.println("Error in sending message:" + e);

return;

}

System.out.println("Successfully sent sms via Serial port");

}

@SuppressWarnings("unchecked")

public static void SendSMSViaWay2Sms(String uid, String pwd, String phone, String msg)throws IOException

{

if ((uid == null) || (uid.length() == 0))

{

throw new IllegalArgumentException("UserID is Missin.");

}

uid = URLEncoder.encode(uid, "UTF-8");

if ((pwd == null) || (pwd.length() == 0))

{

throw new IllegalArgumentException("Password is missing.");

}

pwd = URLEncoder.encode(pwd, "UTF-8");

if ((phone == null) || (phone.length() <>

{

throw new IllegalArgumentException( "At least one phone number should be present.");

}

if ((msg == null) || (msg.length() == 0))

{

throw new IllegalArgumentException("SMS message should be present.");

}

msg = URLEncoder.encode(msg, "UTF-8");

Vector numbers = new Vector();

if (phone.indexOf(59) >= 0)

{

String[] pharr = phone.split(";");

for (String t : pharr)

{

try

{

numbers.add(Long.valueOf(t));

}

catch (NumberFormatException ex)

{

throw new IllegalArgumentException("Give proper phone numbers.");

}

}

}

else

{

try

{

numbers.add(Long.valueOf(phone));

}

catch (NumberFormatException ex)

{

throw new IllegalArgumentException("Give proper phone numbers.");

}

}

if (numbers.size() == 0)

{

throw new IllegalArgumentException("At least one proper phone number should be present to send SMS.");

}

String temp = "";

String content;

URL u ;

HttpURLConnection uc;

PrintWriter pw;

BufferedReader br ;

content = "username=" + uid + "&password=" + pwd+"&Submit=Sign+in";

u = new URL("http://wwwd.way2sms.com/auth.cl");

uc = (HttpURLConnection)u.openConnection();

uc.setDoOutput(true);

uc.setRequestProperty("Host","wwwd.way2sms.com");

uc.setRequestProperty("User-Agent","Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.2.4) Gecko/20100611 Firefox/3.6.4");

uc.setRequestProperty("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");

uc.setRequestProperty("Accept-Language","en-us,en;q=0.5");

uc.setRequestProperty("Accept-Encoding","gzip,deflate");

uc.setRequestProperty("Accept-Charset","ISO-8859-1,utf-8;q=0.7,*;q=0.7");

uc.setRequestProperty("Keep-Alive","115");

uc.setRequestProperty("Proxy-Connection","keep-alive");

uc.setRequestProperty("Referer", "http://wwwd.way2sms.com//entry.jsp");

uc.setRequestMethod("POST");

uc.setInstanceFollowRedirects(false);

pw = new PrintWriter(new OutputStreamWriter(uc.getOutputStream()), true);

pw.print(content);

pw.flush();

pw.close();

br = new BufferedReader(new InputStreamReader(uc.getInputStream()));

while ((temp = br.readLine()) != null)

{

System.out.println(temp);

}

String cookie = uc.getHeaderField("Set-Cookie");

u = null;

uc = null;

for (Iterator localIterator = numbers.iterator(); localIterator.hasNext();)

{

long num = ((Long) localIterator.next()).longValue();

content = "HiddenAction=instantsms&Action=custfrom900000&login=&pass=&custid=undefined&MobNo=" + num + "&textArea=" +msg;

u = new URL("http://wwwd.way2sms.com/FirstServletsms?cusid=");

uc = (HttpURLConnection)u.openConnection();

uc.setDoOutput(true);

uc.setRequestProperty("Host","wwwd.way2sms.com");

uc.setRequestProperty("User-Agent","Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.2.4) Gecko/20100611 Firefox/3.6.4");

uc.setRequestProperty("Content-Length", String.valueOf(content.getBytes().length));

uc.setRequestProperty("Content-Type","application/x-www-form-urlencoded");

uc.setRequestProperty("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");

uc.setRequestProperty("Accept-Language","en-us,en;q=0.5");

uc.setRequestProperty("Accept-Encoding","gzip,deflate");

uc.setRequestProperty("Accept-Charset","ISO-8859-1,utf-8;q=0.7,*;q=0.7");

uc.setRequestProperty("Keep-Alive","115");

uc.setRequestProperty("Proxy-Connection","keep-alive");

uc.setRequestProperty("Cookie",cookie);

uc.setRequestProperty("Referer","http://wwwd.way2sms.com//jsp/InstantSMS.jsp?val=0");

uc.setRequestMethod("POST");

uc.setInstanceFollowRedirects(false);

pw = new PrintWriter(new OutputStreamWriter(uc.getOutputStream()),true);

pw.print(content);

pw.flush();

pw.close();

br = new BufferedReader(new InputStreamReader(uc.getInputStream()));

while ((temp = br.readLine()) != null);

br.close();

u = null;

uc = null;

}

u = new URL("http://wwwd.way2sms.com/chat/logout.cl");

uc = (HttpURLConnection) u.openConnection();

uc.setRequestProperty("Host","wwwd.way2sms.com");

uc.setRequestProperty("User-Agent","Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.2.4) Gecko/20100611 Firefox/3.6.4");

uc.setRequestProperty("Content-Type","application/x-www-form-urlencoded");

uc.setRequestProperty("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");

uc.setRequestProperty("Accept-Language","en-us,en;q=0.5");

uc.setRequestProperty("Accept-Encoding","gzip,deflate");

uc.setRequestProperty("Accept-Charset","ISO-8859-1,utf-8;q=0.7,*;q=0.7");

uc.setRequestProperty("Keep-Alive","115");

uc.setRequestProperty("Proxy-Connection","keep-alive");

uc.setRequestProperty("X-Requested-With","XMLHttpRequest");

uc.setRequestProperty("Content-Type","application/x-www-form-urlencoded; charset=UTF-8");

//uc.setRequestProperty("Referer","http://wwwd.way2sms.com//jsp/Main.jsp?id=87EB07F03456C21E25A8F04B13F009F7.a401");

uc.setRequestProperty("Proxy-Connection","keep-alive");

uc.setRequestProperty("Cookie", cookie);

uc.setRequestMethod("GET");

uc.setInstanceFollowRedirects(false);

br = new BufferedReader(new InputStreamReader(uc.getInputStream()));

while ((temp = br.readLine()) != null);

br.close();

u = null;

uc = null;

System.out.println("Successfully sent sms via Way2sms");

}

}

No comments: