ReaderWriter Lock, My code just gives exceptions - multithreading

I'm trying to implement the Reader Writer Problem .. I don't know what is wrong with it?
can any one help me figure out why?
...................................................
package readerWriterController;
import java.util.ArrayList;
import java.util.Scanner;
public class Main {
public class ReaderThread extends Thread{
String threadName;
public ReaderThread(String threadName){
super(threadName);
}
public void run(){
System.out.println(getName() + " started reading!");
p();
System.out.println(getName() + " Read : " + Main.buffer);
System.out.println(getName() + " finished reading!");
v();
}
private void p() {
semaphore++;
if(isBlocked){ // if writing
try{
System.out.println(getName() + " is blocked!!");
wait();
}catch (InterruptedException e) {
e.printStackTrace();
}
}
}
private void v() {
--semaphore;
if(semaphore == 0 )notify();
}
}
public class WriterThread extends Thread{
private String text;
public WriterThread(String threadName, String text){
super(threadName);
this.text = text;
}
public void run(){
System.out.println(getName() +" start writing");
if(!isBlocked && semaphore == 0){
isBlocked = true;
synchronized (buffer) {
System.out.println(getName() +" Writing : " + Main.buffer + " " + text);
Main.buffer += text;
System.out.println(getName() +" finished writing!!" );
notify();
}
isBlocked=false;
}else if(isBlocked || semaphore != 0){ // just else !
System.out.println(getName() + " is blocked!");
try{
wait();
}catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public static String buffer;
public static int readerCounter = 0;
public static int semaphore ;
private volatile boolean isBlocked=false;
//public boolean semaphore ;
public static void main(String[] args) {
//System.out.println(readerCounter);
Scanner input = new Scanner(System.in);
System.out.println("Enter the buffer:");
buffer = input.next();
int Nr, Nw;
System.out.println("Enter the number of readers");
Nr = input.nextInt();
semaphore = 0;
System.out.println("Enter the number of writers");
Nw = input.nextInt();
// for the reader threads ...
String name;
ArrayList<Thread> list = new ArrayList<Thread>();
for(int i = 0 ; i < Nr ; i++){
// get reader info.
System.out.println("Enter reader "+ (i+1) + " name :");
name = input.next();
// pass to thread!!
list.add(new Main().new ReaderThread(name));
}
// for the writer thread ...
String text;
for(int i = 0 ; i < Nw ; i++){
// get reader info.
System.out.println("Enter writer "+ (i+1) + " name :");
name = input.next();
System.out.println("Enter the text to be written by this writer:");
text = input.next();
// pass to thread!!
list.add(new Main().new WriterThread(name, text));
}
for(Thread t : list){
t.start();
}
}
}
it just gives me more and more exceptions !!!
is there a problem if I called notify() while there is no thread waiting ?
I think that can not call wait() on constant String's or global objects.!
I have seen this here!

Related

Mutil-Thread socket Too many open files

I am getting
java.net.SocketException: Too many open files.
My code:
public class EchoServer {
public static ExecutorService executorService;
public static final String NEWLINE = "\r\n";
public static long COUNT = 0;
public EchoServer(int port) throws IOException {
ServerSocket serverSocket = new ServerSocket();
serverSocket.bind(new InetSocketAddress("127.0.0.1", port));
System.out.println("Starting echo server on port: " + port);
while (true) {
long start = System.currentTimeMillis();
COUNT++;
Socket socket = serverSocket.accept();
ProcessTask processTask = new ProcessTask(socket, start);
executorService.execute(processTask);
}
}
public static void main(String[] args) throws IOException {
executorService = Executors.newFixedThreadPool(5 * Runtime.getRuntime().availableProcessors());
new EchoServer(9999);
}
public static class ProcessTask implements Runnable {
private Socket socket;
private long startTime;
public ProcessTask(Socket socket, long startTime) {
this.socket = socket;
this.startTime = startTime;
}
public void run() {
BufferedReader br = null;
PrintWriter out = null;
try {
br = getReader(socket);
out = getWriter(socket);
String msg;
while ((msg = br.readLine()) != null) {
String res = "Server Reply : " + msg;
out.println(res);
out.flush();
}
long end = System.currentTimeMillis();
System.out.println("Closing connection with client. 耗时 : " + ((end - startTime)));
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
socket.shutdownInput();
socket.shutdownOutput();
} catch (IOException e) {
e.printStackTrace();
}
}
}
private PrintWriter getWriter(Socket socket) throws IOException {
OutputStream socketOut = socket.getOutputStream();
return new PrintWriter(socketOut, true);
}
private BufferedReader getReader(Socket socket) throws IOException {
InputStream socketIn = socket.getInputStream();
return new BufferedReader(new InputStreamReader(socketIn));
}
}
}
public class EchoClient {
public static final int port = 9999;
public static final String NEWLINE = "\r\n";
public static final long NANOSECONDS_PER_SECOND = 1000 * 1000 * 1000;
public static final long REQUESTS_PER_SECOND = 1000 * 1000;
public static long COUNT = 0;
public static void main(String args[]) {
ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(
50, 50, 3000L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<>());
List<Task> tasks = new ArrayList<>();
for (int i = 0; i < 10000; i++) {
tasks.add(new Task(i, port));
}
boolean flag = false;
while (true) {
tasks.stream().forEach(
task ->
{
threadPoolExecutor.submit(task);
COUNT++;
try {
long sleep_time = NANOSECONDS_PER_SECOND / REQUESTS_PER_SECOND;
TimeUnit.NANOSECONDS.sleep(sleep_time);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
);
if (flag) {
break;
}
}
threadPoolExecutor.shutdown();
}
public static class Task implements Callable<Long> {
private int port;
private int id;
private String taskName;
public Task(int id, int port) {
this.id = id;
this.port = port;
this.taskName = "Client_" + this.id;
}
public Long call() {
long start = -1;
long end = -1;
try {
Socket socket = new Socket("127.0.0.1", port);
start = System.currentTimeMillis();
String msg = "From " + taskName;
msg = msg + NEWLINE;
for (int i = 1; i <= 1; i++) {
OutputStream socketOut = null;
BufferedReader br = null;
try {
socketOut = socket.getOutputStream();
socketOut.write(msg.getBytes());
socketOut.flush();
br = new BufferedReader(new InputStreamReader(
socket.getInputStream()));
String res = br.readLine();
} catch (IOException e) {
e.printStackTrace();
} finally {
socket.shutdownInput();
socket.shutdownOutput();
}
}
end = System.currentTimeMillis();
System.out.println(taskName + " 完成发送数据!" + " 耗时 : " + ((end - start)));
} catch (IOException e) {
e.printStackTrace();
}
return (end - start);
}
}
}
➜ Client git:(2.0-SNAPSHOT) ✗ ulimit -a
-t: cpu time (seconds) unlimited
-f: file size (blocks) unlimited
-d: data seg size (kbytes) unlimited
-s: stack size (kbytes) 8192
-c: core file size (blocks) 0
-v: address space (kbytes) unlimited
-l: locked-in-memory size (kbytes) unlimited
-u: processes 2128
-n: file descriptors 1048600
➜ Client git:(2.0-SNAPSHOT) ✗ sysctl net.inet.ip.portrange
net.inet.ip.portrange.lowfirst: 1023
net.inet.ip.portrange.lowlast: 600
net.inet.ip.portrange.first: 1024
net.inet.ip.portrange.last: 65535
net.inet.ip.portrange.hifirst: 49152
net.inet.ip.portrange.hilast: 65535
➜ Client git:(2.0-SNAPSHOT) ✗
You are leaking FDs because you are never closing the accepted sockets, or the connected ones client-side either. You're shutting them down, but that is neither sufficient nor necessary if you close them.

Displaying null pointer excepetion on second iteration at the time of writing in excel using JXL?

I am trying to set or write the result of execute test cases using JXL in key driven framework. Also, I am able to write or set the result but only in first iteration. At the time of second iteration it shows null pointer exception. I tried but don't understand what the exact problem is?
Main Method:
public class MainClass {
private static final String BROWSER_PATH = "D:\\FF18\\firefox.exe";
private static final String TEST_SUITE_PATH = "D:\\configuration\\GmailTestSuite.xls";
private static final String OBJECT_REPOSITORY_PATH = "D:\\configuration\\objectrepository.xls";
private static final String ADDRESS_TO_TEST = "https://www.gmail.com";
// other constants
private WebDriver driver;
private Properties properties;
/* private WebElement we; */
public MainClass() {
File file = new File(BROWSER_PATH);
FirefoxBinary fb = new FirefoxBinary(file);
driver = new FirefoxDriver(fb, new FirefoxProfile());
driver.get(ADDRESS_TO_TEST);
}
public static void main(String[] args) throws Exception {
MainClass main = new MainClass();
main.handleTestSuite();
}
private void handleTestSuite() throws Exception {
ReadPropertyFile readConfigFile = new ReadPropertyFile();
properties = readConfigFile.loadPropertiess();
ExcelHandler testSuite = new ExcelHandler(TEST_SUITE_PATH, "Suite");
testSuite.columnData();
int rowCount = testSuite.rowCount();
System.out.println("Total Rows=" + rowCount);
for (int i = 1; i < rowCount; i++) {
String executable = testSuite.readCell(
testSuite.getCell("Executable"), i);
System.out.println("Executable=" + executable);
if (executable.equalsIgnoreCase("y")) {
// exe. the process
String scenarioName = testSuite.readCell(
testSuite.getCell("TestScenario"), i);
System.out.println("Scenario Name=" + scenarioName);
handleScenario(scenarioName);
}
}
WritableData writableData= new WritableData(TEST_SUITE_PATH,"Login");
writableData.shSheet("Login", 5, 1, "Pass");
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
writableData.shSheet("Login", 5, 2, "Fail");
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
writableData.shSheet("Login", 5, 3, "N/A");
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
}
private void handleScenario(String scenarioName) throws Exception {
ExcelHandler testScenarios = new ExcelHandler(TEST_SUITE_PATH);
testScenarios.setSheetName("Login");
testScenarios.columnData();
int rowWorkBook1 = testScenarios.rowCount();
for (int j = 1; j < rowWorkBook1; j++) {
String framWork = testScenarios.readCell(
testScenarios.getCell("FrameworkName"), j);
String operation = testScenarios.readCell(
testScenarios.getCell("Operation"), j); // SendKey
String value = testScenarios.readCell(
testScenarios.getCell("Value"), j);
System.out.println("FRMNameKK=" + framWork + ",Operation="
+ operation + ",Value=" + value);
handleObjects(operation, value, framWork);
}
}
private void handleObjects(String operation, String value, String framWork)
throws Exception {
System.out.println("HandleObject--> " + framWork);
ExcelHandler objectRepository = new ExcelHandler(
OBJECT_REPOSITORY_PATH, "OR");
objectRepository.columnData();
int rowCount = objectRepository.rowCount();
System.out.println("Total Rows in hadleObject=" + rowCount);
for (int k = 1; k < rowCount; k++) {
String frameWorkName = objectRepository.readCell(
objectRepository.getCell("FrameworkName"), k);
String ObjectName = objectRepository.readCell(
objectRepository.getCell("ObjectName"), k);
String Locator = objectRepository.readCell(
objectRepository.getCell("Locator"), k); // SendKey
System.out.println("FrameWorkNameV=" + frameWorkName
+ ",ObjectName=" + ObjectName + ",Locator=" + Locator);
if (framWork.equalsIgnoreCase(frameWorkName)) {
operateWebDriver(operation, Locator, value, ObjectName);
}
}
}
private void operateWebDriver(String operation, String Locator,
String value, String objectName) throws Exception {
System.out.println("Operation execution in progress");
WebElement temp = getElement(Locator, objectName);
if (operation.equalsIgnoreCase("SendKey")) {
temp.sendKeys(value);
}
Thread.sleep(1000);
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
if (operation.equalsIgnoreCase("Click")) {
temp.click();
}
if (operation.equalsIgnoreCase("Verify")) {
System.out.println("Verify--->" +temp);
temp.isDisplayed();
}
}
public WebElement getElement(String locator, String objectName)
throws Exception {
WebElement temp = null;
System.out.println("Locator-->" + locator);
if (locator.equalsIgnoreCase("id")) {
temp = driver.findElement(By.id(objectName));
} else if (locator.equalsIgnoreCase("xpath")) {
temp = driver.findElement(By.xpath(objectName));
System.out.println("xpath temp ----->" + temp);
} else if (locator.equalsIgnoreCase("name")) {
temp = driver.findElement(By.name(objectName));
}
return temp;
}
}
WritableData
public class WritableData {
Workbook wbook;
WritableWorkbook wwbCopy;
String ExecutedTestCasesSheet;
WritableSheet shSheet;
public WritableData(String testSuitePath, String OBJECT_REPOSITORY_PATH) throws RowsExceededException, WriteException {
// TODO Auto-generated constructor stub
try { wbook = Workbook.getWorkbook(new File(testSuitePath));
wwbCopy= Workbook.createWorkbook(new File(testSuitePath),wbook);
System.out.println("writable workbookC-->" +wwbCopy);
shSheet=wwbCopy.getSheet("Login");
System.out.println("writable sheetC-->" +shSheet);
//shSheet = wwbCopy.createSheet("Login", 1);
} catch (Exception e) {
// TODO: handle exception
System.out.println("Exception message" + e.getMessage()); e.printStackTrace(); } }
public void shSheet(String strSheetName, int iColumnNumber, int
iRowNumber, String strData) throws WriteException, IOException {
// TODO Auto-generated method stub
System.out.println("strDataCC---->>" +strData);
System.out.println("strSheetName<<>><<>><<>>" +strSheetName);
WritableSheet wshTemp = wwbCopy.getSheet(strSheetName);
shSheet=wwbCopy.getSheet("Login");
WritableFont cellFont = null;
WritableCellFormat cellFormat = null;
if (strData.equalsIgnoreCase("PASS")) {
cellFont = new WritableFont(WritableFont.TIMES, 12);
cellFont.setColour(Colour.GREEN);
cellFont.setBoldStyle(WritableFont.BOLD);
cellFormat = new WritableCellFormat(cellFont);
cellFormat.setBorder(Border.ALL, BorderLineStyle.THIN); }
else if (strData.equalsIgnoreCase("FAIL")) {
cellFont = new WritableFont(WritableFont.TIMES, 12);
cellFont.setColour(Colour.RED);
cellFont.setBoldStyle(WritableFont.BOLD);
cellFormat = new WritableCellFormat(cellFont);
cellFormat.setBorder(Border.ALL, BorderLineStyle.THIN); }
else { cellFont = new WritableFont(WritableFont.TIMES, 12);
cellFont.setColour(Colour.BLACK);
cellFormat = new WritableCellFormat(cellFont);
cellFormat.setBorder(Border.ALL, BorderLineStyle.THIN);
cellFormat.setWrap(true); }
Label labTemp = new Label(iColumnNumber, iRowNumber, strData,
cellFormat);
shSheet.addCell(labTemp);
System.out.println("writableSheet---->"+shSheet);
wwbCopy.write();
wwbCopy.close();
wbook.close();
}
}
Console:
writable sheetC-->jxl.write.biff.WritableSheetImpl#ee1ede
strDataCC---->>Pass
strSheetName<<>><<>><<>>Login
writableSheet---->jxl.write.biff.WritableSheetImpl#ee1ede
strDataCC---->>Fail
strSheetName<<>><<>><<>>Login
writableSheet---->jxl.write.biff.WritableSheetImpl#ee1ede
Exception in thread "main" java.lang.NullPointerException
at jxl.write.biff.File.write(File.java:149)
at jxl.write.biff.WritableWorkbookImpl.write(WritableWorkbookImpl.java:706)
at com.chayan.af.WritableData.shSheet(WritableData.java:86)
at com.chayan.af.MainClass.handleTestSuite(MainClass.java:77)
at com.chayan.af.MainClass.main(MainClass.java:48)

Use of dbms_lock inconsistent using jdbc

Why does the protected Java code execute in more then one thread at a time?
Thread-1 - protected code iteration 0
Thread-0 - protected code iteration 0
Thread-1 - protected code iteration 1
Thread-0 - protected code iteration 1
Thread-0 - protected code iteration 2
Thread-1 - protected code iteration 2
Thread-1 - protected code iteration 3
Thread-0 - protected code iteration 3
Run it enough times it can execute as expected.
public class DbmsLockTest implements Runnable {
Connection con; String key; int timeout;
public DbmsLockTest(Connection con, String key, int timeout) {
this.con = con; this.key = key; this.timeout = timeout;
}
public static void log(String str) {
System.out.println(new Date() + " - "
+ Thread.currentThread().getName() + " - " + str);
}
#Override
public void run() {
lockKey(con, key, timeout);
}
public static void lockKey(Connection con, String key, int timeout) {
log("start lockKey " + " key: " + key);
CallableStatement cStmt = null;
int rc = 0;
try {
StringBuilder sql = new StringBuilder(500);
sql.append("DECLARE");
sql.append(" v_lockhandle VARCHAR2(200);");
sql.append("BEGIN");
sql.append(" dbms_lock.allocate_unique(lockname => ?, lockhandle => v_lockhandle);");
sql.append(" ? := dbms_lock.request(lockhandle => v_lockhandle, lockmode => 6,");
sql.append(" timeout => ?, release_on_commit =>true);");
sql.append(" ? := v_lockhandle;");
sql.append("END;");
String lockKey = "LockKey-" + key;
cStmt = con.prepareCall(sql.toString());
cStmt.setString(1, lockKey);
cStmt.registerOutParameter(2, Types.NUMERIC);
cStmt.setInt(3, timeout);
cStmt.registerOutParameter(4, Types.VARCHAR);
log("executeUpdate start: " + lockKey + "] ");
cStmt.executeUpdate();
log("executeUpdate end: " + lockKey + "] ");
rc = cStmt.getInt(2);
log("return value from request=[" + rc + "] ");
if (rc != 0) {
System.out.println("6001 lock obtained: "
+ Thread.currentThread().getName());
throw new RuntimeException("lock acquisition failed with code=" + rc);
}
log("v_lockhandle=[" + cStmt.getString(4) + "] ");
for (int i = 0; i < 4; i++) {
try {
Thread.sleep(1000 * 1);
} catch (InterruptedException e) {
e.printStackTrace();
}
log("***** protected code iteration ***** " + i);
}
con.commit();
} catch (SQLException e) {
log("int timeout: " + Thread.currentThread().getName());
throw new RuntimeException("SQLException locking balance for user "
+ key, e);
} finally {
try {
if (cStmt != null) {
cStmt.close();
}
if (con != null) {
con.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
log("Exiting=[" + rc + "] ");
}
public static void main(String[] args) throws Exception {
new oracle.jdbc.OracleDriver();
List<Thread> list = new ArrayList<Thread>();
for (int i = 0; i < 2; i++) {
Connection connection = DriverManager
.getConnection("jdbc:oracle:thin:#localhost:1521:xe",
"<username>", "password");
Thread t = new Thread(new DbmsLockTest(connection, "mykey", 10));
list.add(t);
}
for (Thread t : list) {
t.start();
}
}
}

using ANTLR in java cause OOM

I'm trying to parse a big log(30MByte) file with ANTLR.
But it crashed with OOM or became very slow as parser working.
As i knew,
1. Lexer scans text and yeids tokens
2. Parser consume tokens with given rule
Tokens already consumed should be collected by gc, but it seems not.
Can you tell me what is the problem?
(grammar or code)
Minimized grammars and codes are below
LogParser.g
grammar LogParser;
options {
language = Java;
}
rule returns [Line result]
:
stamp WS text NL
{
result = new Line();
result.setStamp(Integer.parseInt($stamp.text));
result.setText($text.text + $NL.text);
}
;
stamp
:
DIGIT+
;
text
:
CHAR+
;
DIGIT
:
'0'..'9'
;
CHAR
:
'A'..'Z'
;
WS
:
' '
;
NL
:
'\r'? '\n'
;
Test.java
import java.io.IOException;
import org.antlr.runtime.ANTLRFileStream;
import org.antlr.runtime.CharStream;
import org.antlr.runtime.CommonTokenStream;
import org.antlr.runtime.RecognitionException;
public class Test {
public static void main(String[] args) {
try {
CharStream input = new ANTLRFileStream("aaa.txt");
LogParserLexer lexer = new LogParserLexer(input);
CommonTokenStream tokenStream = new CommonTokenStream(lexer);
LogParserParser parser = new LogParserParser(tokenStream);
int count = 0;
while (true) {
count++;
parser.rule();
parser.setBacktrackingLevel(0);
if (0 == count % 1000)
System.out.println(count);
}
} catch (IOException e) {
e.printStackTrace();
} catch (RecognitionException e) {
e.printStackTrace();
}
}
}
Line.java
public class Line {
private Integer stamp;
private String text;
public Integer getStamp() {
return stamp;
}
public void setStamp(Integer stamp) {
this.stamp = stamp;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
#Override
public String toString() {
return String.format("%010d %s", stamp, text);
}
}
aaa.txt, randomly generated contents. its size is about 30mega byte.
0925489881 BIWRSAZLQTOGJUAVTRWV
0182726517 WWVNRKGGXPKPYBDIVUII
1188747525 NZONXSYIWHMMOLTVPKVC
1605284429 RRLYHBBQKLFDLTRHWCTK
1842597100 UFQNIADNPHQYTEEJDKQN
0338698771 PLFZMKAGLGWTHZXNNZEU
1971850686 TDGYOCGOMNZUFNGOXLPM
1686341878 NTYUXJSVQYXTBZAFLJJD
0849759139 YRXZSVWSZDBJPSNSWNJH
:
:
:
Sample generator
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Random;
public class EntryPoint {
/**
* #param args
*/
public static void main(String[] args) {
FileWriter fw = null;
try {
int size = 20;
String formatLength = Integer.toString(Integer.MAX_VALUE);
String pattern = "%0" + formatLength.length() + "d ";
Random random = new Random();
File file = new File("aaa.txt");
fw = new FileWriter(file);
while (true) {
int nextInt = random.nextInt(Integer.MAX_VALUE);
StringBuilder sb = new StringBuilder();
sb.append(String.format(pattern, nextInt));
for (int i = 0; i < size; i++) {
sb.append((char) ('A' + random.nextInt(26)));
}
fw.append(sb);
fw.append(System.getProperty("line.separator"));
if (file.length() > 30000000)
break;
}
fw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Result with JavaSE-1.6(jre6), windows 7 64 vmarg "-Xmx256M"
85000
86000
Exception in thread "main" java.lang.OutOfMemoryError: GC overhead limit exceeded
at org.antlr.runtime.Lexer.emit(Lexer.java:160)
at org.antlr.runtime.Lexer.nextToken(Lexer.java:91)
at org.antlr.runtime.BufferedTokenStream.fetch(BufferedTokenStream.java:133)
at org.antlr.runtime.BufferedTokenStream.sync(BufferedTokenStream.java:127)
at org.antlr.runtime.CommonTokenStream.consume(CommonTokenStream.java:67)
at org.antlr.runtime.BaseRecognizer.match(BaseRecognizer.java:106)
at LogParserParser.text(LogParserParser.java:190)
at LogParserParser.rule(LogParserParser.java:65)
at Test.main(Test.java:21)
I believe UnbufferedTokenStream is what you want. Might need to unbuffer the char stream too.

not able to receive sms, Help me correct the code

I don't know what is the problem, but SMS is not received with below code and when I see in the phone memory, app is invalid.
Can anyone correct this code?
I am having a lot of issues with this, it compiles well, but when it is on the real phone, the app says it is invalid,Nokia 2630 supports MIDP 2.0, so not a phone problem.
package Pushtest;
import javax.microedition.midlet.*;
import com.sun.lwuit.*;
import com.sun.lwuit.events.ActionEvent;
import com.sun.lwuit.events.ActionListener;
import com.sun.lwuit.layouts.GridLayout;
import javax.microedition.io.*;
import javax.wireless.messaging.*;
import java.util.Date;
import java.io.*;
/**
* #author test
*/
public class SendApprooval extends MIDlet implements Runnable, ActionListener, MessageListener {
Date todaydate;
private Dialog content, alert;
Thread thread;
String[] connections;
boolean done;
String senderAddress, mess;
MessageConnection smsconn = null, clientConn = null;
Message msg;
// public SendApprooval() {
/*
smsPort = getAppProperty("SMS-Port");
content = new Dialog("");
content.addComponent(new Label("Waiting for Authentication Request"));
content.setDialogType(Dialog.TYPE_INFO);
content.setTimeout(2000);
// exitCommand = new Command("Exit", Command.EXIT, 2);
// content.addCommand(exitCommand)
content.addCommand(exitCommand);
content.addCommandListener(this);
content.show();
} */
public void startApp() {
Display.init(this);
String smsConnection = "sms://:" + 5000;
if (smsconn == null) {
try {
smsconn = (MessageConnection) Connector.open(smsConnection);
smsconn.setMessageListener(this);
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
connections = PushRegistry.listConnections(true);
if ((connections == null) || (connections.length == 0)) {
content.addComponent(new Label("Waiting for Authentication Request"));
}
done = false;
thread = new Thread(this);
thread.start();
// display.setCurrent(resumeScreen);
}
public void run() {
try {
msg = smsconn.receive();
if (msg != null) {
senderAddress = msg.getAddress();
int k, j = 0;
for (k = 0; k <= senderAddress.length() - 1; k++) {
if (senderAddress.charAt(k) == ':') {
j++;
if (j == 2) {
break;
}
}
}
senderAddress = senderAddress.substring(0, k + 1);
content.addComponent(new Label(senderAddress));
senderAddress = senderAddress + 5000;
if (msg instanceof TextMessage) {
mess = ((TextMessage) msg).getPayloadText();
}
else {
StringBuffer buf = new StringBuffer();
byte[] data = ((BinaryMessage) msg).getPayloadData();
for (int i = 0; i < data.length; i++) {
int intData = (int) data[i] & 0xFF;
if (intData < 0x10) {
buf.append("0");
}
buf.append(Integer.toHexString(intData));
buf.append(' ');
}
mess = buf.toString();
}
if (mess.equals("Give me Rights")) {
try {
clientConn = (MessageConnection) Connector.open(senderAddress);
}catch (Exception e) {
alert = new Dialog("Alert");
alert.setLayout(new GridLayout(5, 1));
alert.addComponent(new Label("Unable to connect to Station because of network problem"));
alert.setTimeout(2000);
alert.setDialogType(Dialog.TYPE_INFO);
Display.init(alert);
alert.show();
}
try {
TextMessage textmessage = (TextMessage) clientConn.newMessage(MessageConnection.TEXT_MESSAGE);
textmessage.setAddress(senderAddress);
textmessage.setPayloadText("Approoved");
clientConn.send(textmessage);
} catch (Exception e) {
Dialog alert = new Dialog("");
alert.setLayout(new GridLayout(5, 1));
alert.setDialogType(Dialog.TYPE_INFO);
alert.setTimeout(2000);
alert.addComponent(new Label(e.toString()));
Display.init(alert);
alert.show();
}
}
} else {
}
} catch (IOException e) {
content.addComponent(new Label(e.toString()));
Display.init(content);
}
}
public void pauseApp() {
done = true;
thread = null;
Display.init(this);
}
public void destroyApp(boolean unconditional) {
done = true;
thread = null;
if (smsconn != null) {
try {
smsconn.close();
} catch (IOException e) {
}
notifyDestroyed();
}
}
public void showMessage(String message, Display displayable) {
Dialog alert = new Dialog("");
alert.setLayout(new GridLayout(5, 1));
alert.setTitle("Error");
alert.addComponent(new Label(message));
alert.setDialogType(Dialog.TYPE_ERROR);
alert.setTimeout(5000);
alert.show();
}
public void notifyIncomingMessage(MessageConnection conn) {
if (thread == null) {
content.addComponent(new Label("Waiting for Authentication Request"));
content.setLayout(new GridLayout(5, 1));
content.setDialogType(Dialog.TYPE_INFO);
content.show();
done = false;
thread = new Thread(this);
thread.start();
}
}
public void actionPerformed(ActionEvent ae) {
System.out.println("Event fired" + ae.getCommand().getCommandName());
int id = ae.getCommand().getId();
Command cmd = ae.getCommand();
String cmdName1 = cmd.getCommandName();
try {
msg = smsconn.receive();
if (msg != null) {
senderAddress = msg.getAddress();
int k, j = 0;
for (k = 0; k <= senderAddress.length() - 1; k++) {
if (senderAddress.charAt(k) == ':') {
j++;
if (j == 2) {
break;
}
}
}
senderAddress = senderAddress.substring(0, k + 1);
content.addComponent(new Label(senderAddress));
senderAddress = senderAddress + 5000;
if (msg instanceof TextMessage) {
mess = ((TextMessage) msg).getPayloadText();
}
else {
StringBuffer buf = new StringBuffer();
byte[] data = ((BinaryMessage) msg).getPayloadData();
for (int i = 0; i < data.length; i++) {
int intData = (int) data[i] & 0xFF;
if (intData < 0x10) {
buf.append("0");
}
buf.append(Integer.toHexString(intData));
buf.append(' ');
}
mess = buf.toString();
}
if (mess.equals("Give me Rights")) {
try {
clientConn = (MessageConnection) Connector.open(senderAddress);
}catch (Exception e) {
alert = new Dialog("Alert");
alert.setLayout(new GridLayout(5, 1));
alert.addComponent(new Label("Unable to connect to Station because of network problem"));
alert.setTimeout(2000);
alert.setDialogType(Dialog.TYPE_INFO);
Display.init(alert);
alert.show();
}
try {
TextMessage textmessage = (TextMessage) clientConn.newMessage(MessageConnection.TEXT_MESSAGE);
textmessage.setAddress(senderAddress);
textmessage.setPayloadText("Approoved");
clientConn.send(textmessage);
} catch (Exception e) {
Dialog alert = new Dialog("");
alert.setLayout(new GridLayout(5, 1));
alert.setDialogType(Dialog.TYPE_INFO);
alert.setTimeout(2000);
alert.addComponent(new Label(e.toString()));
Display.init(alert);
alert.show();
}
}
} else {
}
if (("Exit").equals(cmdName1)) {
destroyApp(true);
notifyDestroyed();
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
This may be cause because your sending SMS might not send on the port you defined in your code,
Please look at to this working example.
i found it guys, Thanks for your support, i'm sure i would come back with more queries, i have written a sample receiving sms code with port 5000, It would Help someone in someway,
Before you start,
Right click your application in netbeans and select properties. Now select the application descriptor. select the attribute tab and select the Add button. Give the following in the corresponding fields.
Name : SMS-Port
Value : portno
Now u have registered the port no successfully.
Now again select the push registry tab.
give the following in the corresponding fields.
Class Name : Package name.class name
Sender ip : *
Connection String: sms://:portno
Now u have registered the push registry successfully.
CODE HERE:
public class SMSReceiver extends MIDlet implements ActionListener, MessageListener {
private Form formReceiver;
private TextField tfPort;
private MessageConnection msgConnection;
private MessageListener Listener;
private String port;
protected void destroyApp(boolean unconditional)
throws MIDletStateChangeException {
}
protected void pauseApp() {
}
protected void startApp() {
Display.init(this);
try {
Resources r = Resources.open("/m21.res");
UIManager.getInstance().setThemeProps(
r.getTheme(r.getThemeResourceNames()[0]));
} catch (java.io.IOException e) {
e.printStackTrace();
}
formReceiver = new Form();
formReceiver.setTitle(" ");
formReceiver.setLayout(new GridLayout(4, 2));
formReceiver.setTransitionInAnimator(null);
TextField.setReplaceMenuDefault(false);
Label lblPort = new Label("Port");
tfPort = new TextField();
tfPort.setMaxSize(8);
tfPort.setUseSoftkeys(false);
tfPort.setHeight(10);
tfPort.setConstraint(TextField.DECIMAL);
formReceiver.addComponent(lblPort);
formReceiver.addComponent(tfPort);
formReceiver.addCommand(new Command("Listen"), 0);
formReceiver.addCommand(new Command("Exit"), 0);
formReceiver.addCommandListener(this);
formReceiver.show();
}
public void notifyIncomingMessage(MessageConnection conn) {
Message message;
try {
message = conn.receive();
if (message instanceof TextMessage) {
TextMessage tMessage = (TextMessage)message;
formReceiver.addComponent(new Label("Message received : "+tMessage.getPayloadText()+"\n"));
} else {
formReceiver.addComponent(new Label("Unknown Message received\n"));
}
} catch (InterruptedIOException e) {
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void actionPerformed(ActionEvent ae) {
System.out.println("Event fired" + ae.getCommand().getCommandName());
int idi = ae.getCommand().getId();
Command cmd = ae.getCommand();
String cmdNam = cmd.getCommandName();
if ("Listen".equals(cmdNam)) {
ListenSMS sms = new ListenSMS(tfPort.getSelectCommandText(), this);
sms.start();
}
if ("Exit".equals(cmdNam)) {
notifyDestroyed();
}
}
}
class ListenSMS extends Thread {
private MessageConnection msgConnection;
private MessageListener Listener;
private String port;
public ListenSMS(String port, MessageListener listener) {
this.port = port;
this.Listener = listener;
}
public void run() {
try {
msgConnection = (MessageConnection)Connector.open("sms://:" + 5000);
msgConnection.setMessageListener(Listener);
} catch (IOException e) {
e.printStackTrace();
}
}
}

Resources