Mutil-Thread socket Too many open files - multithreading

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.

Related

RTMP live transcription

I want to transcribe the live rtmp stream using google speech to text.
In the google code mic is the input source of the audio stream but here I want to use the rtmp instead of mic.
I am reading byte array using xuggler and storing in sharedQueue.
But my code is failing with below exception.
io.grpc.StatusRuntimeException: CANCE LLED: Failed to read message.
public class DataLoader2 implements Runnable {
static ArrayList<Byte> data = new ArrayList<Byte>();
static byte[] audioChunk = new byte[1150];
static ByteBuffer buff;
private static void extractAudio(String rtmpSourceUrl) {
IMediaReader mediaReader = ToolFactory.makeReader(rtmpSourceUrl);
mediaReader.addListener(new MediaToolAdapter() {
private IContainer container;
#Override
public void onReadPacket(IReadPacketEvent event) {
event.getPacket().getByteBuffer().get(audioChunk);
try {
SpeechToText.sharedQueue.put(audioChunk);
} catch (InterruptedException e) {
}
}
#Override
public void onOpenCoder(IOpenCoderEvent event) {
buff = ByteBuffer.wrap(audioChunk);
container = event.getSource().getContainer();
}
#Override
public void onAudioSamples(IAudioSamplesEvent event) {
/*
* if (DataLoader2.data.size() < 6400) {
* DataLoader2.data.add(event.getMediaData().getByteBuffer().get()); } else {
*
* for (byte audio : DataLoader2.data) { buff.put(audio); }
*
* byte[] combined = buff.array();
*
* try { SpeechToText.sharedQueue.put(combined); } catch (InterruptedException
* e) { e.printStackTrace(); }
*
* DataLoader2.data.clear(); buff.clear(); buff = ByteBuffer.wrap(audioChunk);
*
* }
*/
// System.out.println("Event:" + event.getMediaData().getByteBuffer().get());
// SpeechToText.sharedQueue.put(event.getMediaData().getByteBuffer().get());
}
#Override
public void onClose(ICloseEvent event) {
}
});
while (mediaReader.readPacket() == null) {
}
}
#Override
public void run() {
String rtmpSourceUrl = "rtmp://localhost:1935/livewowza/xyz";
extractAudio(rtmpSourceUrl);
}
}
public class SpeechToText {
private static final int STREAMING_LIMIT = 10000; // 10 seconds
public static final String RED = "\033[0;31m";
public static final String GREEN = "\033[0;32m";
public static final String YELLOW = "\033[0;33m";
// Creating shared object
public static volatile BlockingQueue<byte[]> sharedQueue = new LinkedBlockingQueue();
private static TargetDataLine targetDataLine;
private static int BYTES_PER_BUFFER = 6400; // buffer size in bytes
private static int restartCounter = 0;
private static ArrayList<ByteString> audioInput = new ArrayList<ByteString>();
private static ArrayList<ByteString> lastAudioInput = new ArrayList<ByteString>();
private static int resultEndTimeInMS = 0;
private static int isFinalEndTime = 0;
private static int finalRequestEndTime = 0;
private static boolean newStream = true;
private static double bridgingOffset = 0;
private static boolean lastTranscriptWasFinal = false;
private static StreamController referenceToStreamController;
private static ByteString tempByteString;
private static void start() {
ResponseObserver<StreamingRecognizeResponse> responseObserver = null;
try (SpeechClient client = SpeechClient.create()) {
ClientStream<StreamingRecognizeRequest> clientStream;
responseObserver = new ResponseObserver<StreamingRecognizeResponse>() {
ArrayList<StreamingRecognizeResponse> responses = new ArrayList<>();
#Override
public void onComplete() {
System.out.println("!!!!!!!!!!!!!!!!!!!!!");
}
#Override
public void onError(Throwable arg0) {
System.out.println(arg0.getMessage());
}
#Override
public void onResponse(StreamingRecognizeResponse response) {
System.out.println("Inside onResponse ------------");
responses.add(response);
StreamingRecognitionResult result = response.getResultsList().get(0);
Duration resultEndTime = result.getResultEndTime();
resultEndTimeInMS = (int) ((resultEndTime.getSeconds() * 1000)
+ (resultEndTime.getNanos() / 1000000));
double correctedTime = resultEndTimeInMS - bridgingOffset + (STREAMING_LIMIT * restartCounter);
DecimalFormat format = new DecimalFormat("0.#");
SpeechRecognitionAlternative alternative = result.getAlternativesList().get(0);
if (result.getIsFinal()) {
System.out.print(GREEN);
System.out.print("\033[2K\r");
System.out.printf("%s: %s\n", format.format(correctedTime), alternative.getTranscript());
isFinalEndTime = resultEndTimeInMS;
lastTranscriptWasFinal = true;
} else {
System.out.print(RED);
System.out.print("\033[2K\r");
System.out.printf("%s: %s", format.format(correctedTime), alternative.getTranscript());
lastTranscriptWasFinal = false;
}
}
#Override
public void onStart(StreamController controller) {
referenceToStreamController = controller;
}
};
clientStream = client.streamingRecognizeCallable().splitCall(responseObserver);
RecognitionConfig recognitionConfig = RecognitionConfig.newBuilder()
.setEncoding(RecognitionConfig.AudioEncoding.LINEAR16).setLanguageCode("en-US")
.setSampleRateHertz(16000)
.build();
StreamingRecognitionConfig streamingRecognitionConfig = StreamingRecognitionConfig.newBuilder()
.setConfig(recognitionConfig).setInterimResults(true).build();
StreamingRecognizeRequest request = StreamingRecognizeRequest.newBuilder()
.setStreamingConfig(streamingRecognitionConfig).build(); // The first request in a streaming call
// has to be a config
clientStream.send(request);
System.out.println("Configuration request sent");
long startTime = System.currentTimeMillis();
while (true) {
Thread.sleep(5000);
long estimatedTime = System.currentTimeMillis() - startTime;
if (estimatedTime >= STREAMING_LIMIT) {
clientStream.closeSend(); referenceToStreamController.cancel(); // remove
if (resultEndTimeInMS > 0) { finalRequestEndTime = isFinalEndTime; }
resultEndTimeInMS = 0;
lastAudioInput = null; lastAudioInput = audioInput; audioInput = new
ArrayList<ByteString>();
restartCounter++;
if (!lastTranscriptWasFinal) { System.out.print('\n'); }
newStream = true;
clientStream =
client.streamingRecognizeCallable().splitCall(responseObserver);
request = StreamingRecognizeRequest.newBuilder().setStreamingConfig(
streamingRecognitionConfig) .build();
System.out.println(YELLOW); System.out.printf("%d: RESTARTING REQUEST\n",
restartCounter * STREAMING_LIMIT);
startTime = System.currentTimeMillis();
} else {
if ((newStream) && (lastAudioInput.size() > 0)) {
// if this is the first audio from a new request
// calculate amount of unfinalized audio from last request
// resend the audio to the speech client before incoming audio
double chunkTime = STREAMING_LIMIT / lastAudioInput.size();
// ms length of each chunk in previous request audio arrayList
if (chunkTime != 0) {
if (bridgingOffset < 0) {
// bridging Offset accounts for time of resent audio
// calculated from last request
bridgingOffset = 0;
}
if (bridgingOffset > finalRequestEndTime) {
bridgingOffset = finalRequestEndTime;
}
int chunksFromMS = (int) Math.floor((finalRequestEndTime - bridgingOffset) / chunkTime);
// chunks from MS is number of chunks to resend
bridgingOffset = (int) Math.floor((lastAudioInput.size() - chunksFromMS) * chunkTime);
// set bridging offset for next request
for (int i = chunksFromMS; i < lastAudioInput.size(); i++) {
request = StreamingRecognizeRequest.newBuilder().setAudioContent(lastAudioInput.get(i))
.build();
clientStream.send(request);
}
}
newStream = false;
}
tempByteString = ByteString.copyFrom(sharedQueue.take());
request = StreamingRecognizeRequest.newBuilder().setAudioContent(tempByteString).build();
audioInput.add(tempByteString);
}
clientStream.send(request);
}
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String args[]) {
DataLoader2 dataLoader = new DataLoader2();
Thread t = new Thread(dataLoader);
t.start();
SpeechToText.start();
}
}
FFmpeg command for pcm encoding.
ffmpeg -i rtmp://localhost:1935/liveapp/abc -c:a pcm_s16le -ac 1 -ar 16000 -f flv rtmp://localhost:1935/livewowza/xyz

how to send data to be printed via bluetooth J2ME

can someone please help. i am trying to send data to a thermal printer using bluetooth. i understand how to discover the devices but not able to connect or know how to send the stream of data to be printed. what do I use here ? there is OBEX and RFComm. which one is appropriate. and can you plz share a sample of code to show how to do it, it would be much appreciated.
Below is a sample code that i have found which uses OBEX to search for near by devices and its actually for image transferring. can you plz point out to me the part that are important and how to change this in order to send a stream of Data rather than picture... plz plz help
public class BluetoothImageSender extends MIDlet implements CommandListener{
public Display display;
public Form discoveryForm;
public Form readyToConnectForm;
public Form dataViewForm;
public ImageItem mainImageItem;
public Image mainImage;
public Image bt_logo;
public TextField addressTextField;
public TextField subjectTextField;
public TextField messageTextField;
public Command selectCommand;
public Command exitCommand;
public Command connectCommand;
public List devicesList;
public Thread btUtility;
public String btConnectionURL;
public boolean readData = false;
public long startTime = 0;
public long endTime = 0;
public BluetoothImageSender() {
startTime = System.currentTimeMillis();
display = Display.getDisplay(this);
discoveryForm = new Form("Image Sender");
try{
mainImage = Image.createImage("/btlogo.png");
bt_logo = Image.createImage("/btlogo.png");
} catch (java.io.IOException e){
e.printStackTrace();
}
mainImageItem = new ImageItem("Bluetooth Image Sender", mainImage, Item.LAYOUT_CENTER, "");
discoveryForm.append(mainImageItem);
discoveryForm.append("\nThis application will scan the area for Bluetooth devices and determine if any are offering OBEX services.\n\n");
/// discoveryForm initialization
exitCommand = new Command("Exit", Command.EXIT, 1);
discoveryForm.addCommand(exitCommand);
discoveryForm.setCommandListener(this);
/// devicesList initialization
devicesList = new List("Select a Bluetooth Device", Choice.IMPLICIT, new String[0], new Image[0]);
selectCommand = new Command("Select", Command.ITEM, 1);
devicesList.addCommand(selectCommand);
devicesList.setCommandListener(this);
devicesList.setSelectedFlags(new boolean[0]);
/// readyToConnectForm initialization
readyToConnectForm = new Form("Ready to Connect");
readyToConnectForm.append("The selected Bluetooth device is currently offering a valid OPP service and is ready to connect. Please click on the 'Connect' button to connect and send the data.");
connectCommand = new Command("Connect", Command.ITEM, 1);
readyToConnectForm.addCommand(connectCommand);
readyToConnectForm.setCommandListener(this);
/// dataViewForm initialization
dataViewForm = new Form("File Sending Progress");
dataViewForm.append("Below is the status of the file sending process:\n\n");
dataViewForm.addCommand(exitCommand);
dataViewForm.setCommandListener(this);
}
public void commandAction(Command command, Displayable d) {
if(command == selectCommand) {
btUtility.start();
}
if(command == exitCommand ) {
readData = false;
destroyApp(true);
}
if(command == connectCommand ) {
Thread filePusherThread = new FilePusher();
filePusherThread.start();
display.setCurrent(dataViewForm);
}
}
public void startApp() {
display.setCurrent(discoveryForm);
btUtility = new BTUtility();
}
public void pauseApp() {
}
public void destroyApp(boolean b) {
notifyDestroyed();
}
////////////////
/**
* This is an inner class that is used for finding
* Bluetooth devices in the vicinity.
*/
class BTUtility extends Thread implements DiscoveryListener {
Vector remoteDevices = new Vector();
Vector deviceNames = new Vector();
DiscoveryAgent discoveryAgent;
// obviously, 0x1105 is the UUID for
// the Object Push Profile
UUID[] uuidSet = {new UUID(0x1105) };
// 0x0100 is the attribute for the service name element
// in the service record
int[] attrSet = {0x0100};
public BTUtility() {
try {
LocalDevice localDevice = LocalDevice.getLocalDevice();
discoveryAgent = localDevice.getDiscoveryAgent();
discoveryForm.append(" Searching for Bluetooth devices in the vicinity...\n");
discoveryAgent.startInquiry(DiscoveryAgent.GIAC, this);
} catch(Exception e) {
e.printStackTrace();
}
}
public void deviceDiscovered(RemoteDevice remoteDevice, DeviceClass cod) {
try{
discoveryForm.append("found: " + remoteDevice.getFriendlyName(true));
} catch(Exception e){
discoveryForm.append("found: " + remoteDevice.getBluetoothAddress());
} finally{
remoteDevices.addElement(remoteDevice);
}
}
public void inquiryCompleted(int discType) {
if (remoteDevices.size() > 0) {
// the discovery process was a success
// so out them in a List and display it to the user
for (int i=0; i<remoteDevices.size(); i++){
try{
devicesList.append(((RemoteDevice)remoteDevices.elementAt(i)).getFriendlyName(true), bt_logo);
} catch (Exception e){
devicesList.append(((RemoteDevice)remoteDevices.elementAt(i)).getBluetoothAddress(), bt_logo);
}
}
display.setCurrent(devicesList);
} else {
// handle this
}
}
public void run(){
try {
RemoteDevice remoteDevice = (RemoteDevice)remoteDevices.elementAt(devicesList.getSelectedIndex());
discoveryAgent.searchServices(attrSet, uuidSet, remoteDevice , this);
} catch(Exception e) {
e.printStackTrace();
}
}
public void servicesDiscovered(int transID, ServiceRecord[] servRecord){
for(int i = 0; i < servRecord.length; i++) {
DataElement serviceNameElement = servRecord[i].getAttributeValue(0x0100);
String _serviceName = (String)serviceNameElement.getValue();
String serviceName = _serviceName.trim();
btConnectionURL = servRecord[i].getConnectionURL(ServiceRecord.NOAUTHENTICATE_NOENCRYPT, false);
System.out.println(btConnectionURL);
}
display.setCurrent(readyToConnectForm);
readyToConnectForm.append("\n\nNote: the connection URL is: " + btConnectionURL);
}
public void serviceSearchCompleted(int transID, int respCode) {
if (respCode == DiscoveryListener.SERVICE_SEARCH_COMPLETED) {
// the service search process was successful
} else {
// the service search process has failed
}
}
}
////////////////
/**
* FilePusher is an inner class that
* now gets the byte[] named file
* to read the bytes of the file, and
* then opens a connection to a remote
* Bluetooth device to send the file.
*/
class FilePusher extends Thread{
FileConnection fileConn = null;
String file_url = "/loginscreen.png";
byte[] file = null;
String file_name = "loginscreen.png";
String mime_type = "image/png";
// this is the connection object to be used for
// bluetooth i/o
Connection connection = null;
public FilePusher(){
}
public void run(){
try{
InputStream is = this.getClass().getResourceAsStream(file_url);
ByteArrayOutputStream os = new ByteArrayOutputStream();
// now read the file in into the byte[]
int singleByte = 0;
while(singleByte != -1){
singleByte = is.read();
os.write(singleByte);
}
System.out.println("file size: " + os.size());
file = new byte[os.size()];
file = os.toByteArray();
dataViewForm.append("File name: " + file_url);
dataViewForm.append("File size: " + file.length + " bytes");
is.close();
os.close();
} catch (Exception e){
e.printStackTrace();
System.out.println("Error processing the file");
}
try{
connection = Connector.open(btConnectionURL);
// connection obtained
// create a session and a headerset objects
ClientSession cs = (ClientSession)connection;
HeaderSet hs = cs.createHeaderSet();
// establish the session
cs.connect(hs);
hs.setHeader(HeaderSet.NAME, file_name);
hs.setHeader(HeaderSet.TYPE, mime_type); // be sure to note that this should be configurable
hs.setHeader(HeaderSet.LENGTH, new Long(file.length));
Operation putOperation = cs.put(hs);
OutputStream outputStream = putOperation.openOutputStream();
outputStream.write(file);
// file push complete
outputStream.close();
putOperation.close();
cs.disconnect(null);
connection.close();
dataViewForm.append("Operation complete. File transferred");
endTime = System.currentTimeMillis();
long diff = (endTime - startTime)/1000;
System.out.println("Time to transfer file: " + diff);
dataViewForm.append("Time to transfer file: " + diff);
} catch (Exception e){
System.out.println("Error sending the file");
System.out.println(e);
e.printStackTrace();
}
}
}
}

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)

ReaderWriter Lock, My code just gives exceptions

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!

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