Google

Saturday, February 28, 2009

SRS v012

Student.dat

Records Size (kB)
50 51
100 502
150 771
200 1038
250 1305
300 1571

Tuesday, February 24, 2009

Java Out of Memory Error - Solution

How to fix Java out of Memory Error:

http://wiki.netbeans.org/FaqOutofMemoryOnCompile

You need to increase the memory allocated to the compiler. In order to do this:

  1. Right click on the project node in the Projects window and select Properties
  2. In the project properties dialog, click on Build | Compiling
  3. In the Additional Compiler Options text box, enter the -Xmx and optionally -Xms switches as needed (for example, -J-Xms=128m -J-Xmx=512m). For JDK 6, refer to http://javahowto.blogspot.com/2006/06/6-common-errors-in-setting-java-heap.html.
  4. Click OK in the dialog
  5. Make sure the external javac compiler will be used, by adding the following line to nbproject/project.properties from the Files tab:
build.compiler=extJavac

That should resolve the issue.


http://javahowto.blogspot.com/2006/06/6-common-errors-in-setting-java-heap.html

How to set java heap size in NetBeans?
Exit NetBeans, edit the file netbeans-install/etc/netbeans.conf.

For example,
netbeans_default_options="-J-Xms512m -J-Xmx512m
-J-XX:PermSize=32m -J-XX:MaxPermSize=128m -J-Xverify:none

Sunday, February 22, 2009

SRS: Student Record System Project Launched

To create a Student Record System to supplement COMAS.
Not to replace it.

Problem Statement:

COMAS is unable to calculate GPA and CGPA
(except for ADTP).

Scope:

1. To enter student records only from Jan 2009 onwards. But
COMAS will still be used to enter student records. From Jan 2009,
two systems will be used to manage student records, COMAS and
this new System.

2. Limited only to new Student records from Jan 2009.

3. Limited only to GPA and CGPA calculation.

4. Not intended to replace COMAS, but only to supplement COMAS
solely for purpose of calculating GPA and CGPA.

5. Report printing limited only to GPA and CGPA results.

6. All other modules not listed above are implicitly excluded from this
project. Eg, COMAS is still needed to do Student Application
and Enrolment, to generate fees payable and all other functionalities
that has been done by COMAS all along.

7. This system is only to be used for about 2 semesters - Jan and April, 2009.
Laureate (or other) system is expected to replace COMAS.

Friday, February 20, 2009

SCJP: Generics Type must be declared before use

Consider this code:



Text version:

The strangest thing about generic methods is that you must declare the type
variable BEFORE the return type of the method:

public static <k,v> mangle(Map <k,v> in)

<K,V> is the type you are going to use. But the return type is:
Map<K,V> . Even if you are not going to return anything you still
need to declare the type before use, eg:

public static <K,V> void mangle(Map in)

What happens if you change this line :

out.put(entry.getValue(), entry.getKey())

to

out.put(entry.getKey(), entry.getValue()) ?

There will be a compiler error!
This is because when you declare a new HashMap:

Map <V,K> out = new HashMap <V,K> ();

the new HashMap treats the Key as V and the Value as K,
reversing the values and keys.

It then returns the new object to the reference out which
also expects V, K, in that order.
As such when you call out.put( ), the out object expects
the V to come before the K.


SCJP Quiz A Errata

Q.68 Correct answer should be F

Thursday, February 19, 2009

How to strip HTML Tags





The output is:

Honolulu Tue 5:05 AM
Washington DC Tue 10:05 AM
Oslo Tue 4:05 PM


The important parts:

String stripH = dataH.replaceAll("<.*?>"," ");

The method replaceAll("<.*?>"," ") strips out all HTML tags
by searching for anything with angle brackets ( < > ) and replace it
with a blank space ( " ").

The regular expression <.*?> means match anything within
the angle brackets once. The dot ( . ) means any character.
The quantifier ( * ) means zero or more. The ( ? ) qualifies
the quantifier ( * ) by saying match it once only. The ( *? ) is
also called a 'reluctant' quantifier.

So, it will catch all the following:


and replaces each one with a blank space.


For J2ME, use this:




Assuming :




Call the method as follows:

String stripped = doStripHtml(data);

Note that
you will still need to modify the code before
you can use it in your HTML Parser application. But I
leave that to you to do.

Below is yet another version:


Tuesday, February 17, 2009

Pendrive Virus-launcher Cleaner v006



This version fixed the bug that when a virus launcher is
found and the user chooses not to delete, it gives message
innoculation done.

/*
* Pendrive virus Launcher Cleaner
* by Paul Chin
* version 005 Feb 12, 2009
* version 006 Feb 17, 2009
*/
package pendriveviruslaunchercleaner;

import java.awt.*;
import java.awt.event.*;
import java.io.*;
import javax.swing.*;

public class PendriveVirusLauncherCleaner extends JFrame {

//private JButton btnClean;
//private JButton btnInnoculate;
private JButton btnCleanInnoc;
private JButton btnHelp;
//private JButton btnClearscreen;
private JLabel lbIP;
private JTextArea taOutput;
private JScrollPane jsp;
private JComboBox cbDrive;
String[] slist = {"D", "E", "F", "G", "H", "I", "J", "K", "L", "M"};
String sHelp =
"1. Select your pen drive Letter.\n2. Click Clean and Innoculate.\n" +
"\nA Pendive infection consists of a virus-launcher and the actual virus.\n" +
"The virus-launcher file is autorun.inf whilst, the virus can be of any name.\n" +
"Whenever a user double-clicks on a pendrive icon, the autorun.inf\n" +
"file is triggerred, it will then launch the actual virus.\n" +
"The virus will then infect the PC. By deleting this autorun.inf file,\n" +
"the virus will not be able to launch when a user double-clicks on \n" +
"the pendrive.\n\n" +
"Innoculation means to create a fake autorun.inf folder.\n" +
"This prevents the real autorun.inf virus-launcher from being\n" +
"copied to your pendrive from an infected PC.\n";

public static void main(String[] args) {
PendriveVirusLauncherCleaner pdvlc = new PendriveVirusLauncherCleaner();
pdvlc.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
pdvlc.setSize(500, 400);
pdvlc.setVisible(true);
}

public PendriveVirusLauncherCleaner() {
super("Pendrive Virus-Launcher Cleaner v006");
setLayout(new FlowLayout()); // set frame layout
lbIP = new JLabel("Drive: ");
cbDrive = new JComboBox(slist);

//btnClean = new JButton("Clean");
//btnInnoculate = new JButton("Innoculate");
btnCleanInnoc = new JButton("Clean and Innoculate");
btnHelp = new JButton("Help");
//btnClearscreen = new JButton("ClearScreen");
taOutput = new JTextArea(18, 40);
taOutput.append("1. Select your pen drive Letter.\n2. Click Clean and Innoculate.\n");
jsp = new JScrollPane(taOutput);
add(lbIP);
add(new JScrollPane(cbDrive));
//add(btnClean);
//add(btnInnoculate);
add(btnCleanInnoc);
add(btnHelp);
//add(btnClearscreen);
add(jsp);
ButtonHandler handler = new ButtonHandler();
btnHelp.addActionListener(handler);
//btnClean.addActionListener(handler);
//btnInnoculate.addActionListener(handler);
btnCleanInnoc.addActionListener(handler);
//btnClearscreen.addActionListener(handler);
}

private class ButtonHandler implements ActionListener {

public void actionPerformed(ActionEvent e) {
if (e.getSource() == btnCleanInnoc) {
taOutput.setText("");
boolean isDoInnoc = doScan();
if (isDoInnoc == true) {
doInnoculate();
}
}
//if (e.getSource() == btnInnoculate) {
// doInnoculate();
//}
if (e.getSource() == btnHelp) {
taOutput.setText("");
taOutput.append(sHelp);
}
//if (e.getSource() == btnClearscreen) {
// taOutput.setText("");
//}
}
}

private boolean doScan() {
String drive = cbDrive.getSelectedItem().toString();
File d = new File(drive + ":\\");
if (d.exists() == false) {
taOutput.append("Drive: " + drive + " not found, Please try again.\n");
return false;
}
taOutput.append("Starting scan on Drive: " + drive + "\nPlease wait...\n");
File f = new File(drive + ":\\autorun.inf");
if (f.exists() && f.isFile()) {
taOutput.append("FOUND: \'autorun.inf\' virus-launcher\n");
int response = JOptionPane.showConfirmDialog(null,
"Found: \'autorun.inf\' virus launcher. Shall I delete it?");
if (response == 0) {
try {
f.delete();
taOutput.append("Virus launcher successfully deleted\n\n");
return true;
} catch (Exception x) {
taOutput.append(x.getMessage() + "\n");
JOptionPane.showMessageDialog(null, x.getMessage());
return false;
}
} else {
return false;
}
} else {
if (f.isDirectory() == true) {
taOutput.append("autorun.inf folder found.\nPendrive already innoculated\n");
return false;
} else {
taOutput.append("\'autorun.inf\' virus launcher NOT found\n");
}
}
return true;

}

private void doInnoculate() {
String drive = cbDrive.getSelectedItem().toString();
File d = new File(drive + ":\\autorun.inf");
if (d.exists() == false) {
d.mkdir();
File dummy = new File(d, "DoNotDeleteThisFolder.txt");
try {
dummy.createNewFile();
taOutput.append("Innoculation succeeded. Fake autorun.inf folder created.\n");
taOutput.append("Do not delete this autorun.inf folder, it prevents the real\n");
taOutput.append("autorun.inf virus launcher from infecting your pendrive.\n");
} catch (Exception ex) {
taOutput.append(ex.getMessage() + "\n");
}
} else {
taOutput.append("autorun.inf folder exists. Your pendrive is already innoculated.\n");
}
}
}

Multi-dimensional arrays

Note that the following is all ok:

package practice;

public class Test {

public static void main(String[] args){
int[]one =new int[9];
int[][]two=new int[9][9];
int[][][]three=new int[9][9][9];
int[][][][]bigarray=new int[1][1][1][1];

bigarray[1][1][1][1] = one[2];
bigarray[1][1][1] = one;
bigarray[1][1] = two;
bigarray[1]=three;

bigarray[1][1][1] = two[9];
bigarray[1][1][1] = three[9][9];
}

}


ANALYSIS:

Expecting a single value:

bigarray[1][1][1][1] = ?

so
one[2];

is OK


Expecting a 1-D array:

bigarray[1][1][1] = ?
so
one

is OK

Expecting a 2-D array:

bigarray[1][1] = ?
so
two
is OK

Expecting a 3-D array:

bigarray[1]= ?
so
three
is OK

Expecting a 1-D array:

bigarray[1][1][1] = ?
so
two[9]
is OK

Expecting a 1-D array:

bigarray[1][1][1] = ?
so
three[9][9]
is OK


Saturday, February 14, 2009

Another Jar example

//SayHello.java
public class SayHello{
public void greet(){
System.out.println("Hi");
}
}



//SayBye.java
public class SayBye{
public void greet(){
System.out.println("Bye");
}
}



//SayTest
public class SayTest{

public static void main(String[] args){
SayHello sh = new SayHello();
SayBye sb = new SayBye();
sh.greet();
sb.greet();
}
}


Assuming all are in same directory and you are also
in the same directory.
Build them:

javac SayHello.java
javac SayBye.java
javac SayTest.java

Now, jar them. Still in the same directory.

jar -cf MyApp.jar *.class

Now, run it.

java -cp .;MyApp.jar SayTest

Note all these this will fail:

java -cp .;MyApp.jar MyApp
java -cp ./MyApp.jar SayTest
java -cp ./MyApp.jar MyApp


The only correct way:


java -cp .;MyApp.jar SayTest

or

java -classpath .;MyApp.jar SayTest





Creating and Using Jar files

Use the previous blog's example.

To create a jar file form the classes folder:

jar -cf SayHelloTest.jar SayHelloTest.class com

To use:

java -classpath ./SayHelloTest.jar SayHelloTest

The dot (.) refers to the present folder AFTER uncompressed.
You need to refer to the . folder because that is where the
main class is found. The main class should not be jarred in
a subfolder.

Also the jar name should be the same as the main class name.

If you have only one folde containing all your classes:

SayHello.class
SayHelloTest.class

Then enter the folder, and do:

jar -cf SayHelloTest.jar *.class

The jar file SayHelloTest.jar will be created in the same folder.
You can copy it anywhere and then run it as follows:

jar -classpath ./SayHelloTest.jar SayHelloTest

or

jar -cp ./SayHelloTest.jar SayHelloTest

The . refers to the classpath after uncompression.
The SayHelloTest.jar that comes after the . refers to the jar file that contains
the classpath for the dot (.)

Java Classpath




package com.wickedlysmart;

public class SayHello{
public void greet(){
System.out.println("Hi");
}
}


import com.wickedlysmart.SayHello;

public class SayHelloTest{

public static void main(String[] args){
SayHello sh = new SayHello();
sh.greet();
}
}



C:\JavaPractice\source\com\wickedlysmart\SayHello.java
C:\JavaPractice\source\com\wickedlysmart \TestSayHello.java


To build, from C:\JavaPractice\source:

javac -d ../classes com/wickedlysmart/SayHello.java

Then,

javac -d ../classes -classpath C:\JavaPractice\classes com/wickedlysmart/SayHelloTest.java

You can use -cp instead of -classpath

SayHelloTest.class will be created in the classes folder.
Then copy the SayHelloTest.class anywhere you like.


To execute from anywhere where the TestSayHello.class is in
the same folder as you:

java -classpath C:\JavaPractice\classes;. SayHelloTest

or,

java -cp C:\JavaPractice\classes;. SayHelloTest


Note that ; is the separator for Windows.

Friday, February 13, 2009

Open Command Prompt Here


For vista, Right-click while holding shift key



For WinXP:

1) click on Start -> Run
2) type regedit
3) go to HKEY_CLASSES_ROOT -> Directory -> shell
4) right click 'shell' and select New -> Key
5) name it 'MS DOS prompt' or anything you like
6) right click the key just created and select New -> Key
7) name it 'command'
8) double click 'command' and type 'cmd.exe /K cd %1' in the Data Value field
9) close regedit

Thursday, February 12, 2009

Pendrive Virus-launcher Cleaner v005



/*
* Pendrive virus Launcher Cleaner
* by Paul Chin
* Feb 12, 2009
*/
package pendriveviruslaunchercleaner;

import java.awt.*;
import java.awt.event.*;
import java.io.*;
import javax.swing.*;

public class PendriveVirusLauncherCleaner extends JFrame {

//private JButton btnClean;
//private JButton btnInnoculate;
private JButton btnCleanInnoc;
private JButton btnHelp;
//private JButton btnClearscreen;
private JLabel lbIP;
private JTextArea taOutput;
private JScrollPane jsp;
private JComboBox cbDrive;
String[] slist = {"D", "E", "F", "G", "H", "I", "J", "K", "L", "M"};
String sHelp =
"1. Select your pen drive Letter.\n2. Click Clean and Innoculate.\n" +
"\nA Pendive infection consists of a virus-launcher and the actual virus.\n" +
"The virus-launcher file is autorun.inf whilst, the virus can be of any name.\n" +
"Whenever a user double-clicks on a pendrive icon, the autorun.inf\n" +
"file is triggerred, it will then launch the actual virus.\n" +
"The virus will then infect the PC. By deleting this autorun.inf file,\n" +
"the virus will not be able to launch when a user double-clicks on \n" +
"the pendrive.\n\n" +
"Innoculation means to create a fake autorun.inf folder.\n" +
"This prevents the real autorun.inf virus-launcher from being\n" +
"copied to your pendrive from an infected PC.\n";

public static void main(String[] args) {
PendriveVirusLauncherCleaner pdvlc = new PendriveVirusLauncherCleaner();
pdvlc.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
pdvlc.setSize(500, 400);
pdvlc.setVisible(true);
}

public PendriveVirusLauncherCleaner() {
super("Pendrive Virus-Launcher Cleaner v005");
setLayout(new FlowLayout()); // set frame layout
lbIP = new JLabel("Drive: ");
cbDrive = new JComboBox(slist);

//btnClean = new JButton("Clean");
//btnInnoculate = new JButton("Innoculate");
btnCleanInnoc = new JButton("Clean and Innoculate");
btnHelp = new JButton("Help");
//btnClearscreen = new JButton("ClearScreen");
taOutput = new JTextArea(18, 40);
taOutput.append("1. Select your pen drive Letter.\n2. Click Clean and Innoculate.\n");
jsp = new JScrollPane(taOutput);
add(lbIP);
add(new JScrollPane(cbDrive));
//add(btnClean);
//add(btnInnoculate);
add(btnCleanInnoc);
add(btnHelp);
//add(btnClearscreen);
add(jsp);
ButtonHandler handler = new ButtonHandler();
btnHelp.addActionListener(handler);
//btnClean.addActionListener(handler);
//btnInnoculate.addActionListener(handler);
btnCleanInnoc.addActionListener(handler);
//btnClearscreen.addActionListener(handler);
}

private class ButtonHandler implements ActionListener {

public void actionPerformed(ActionEvent e) {
if (e.getSource() == btnCleanInnoc) {
taOutput.setText("");
doScan();
doInnoculate();
}
//if (e.getSource() == btnInnoculate) {
// doInnoculate();
//}
if (e.getSource() == btnHelp) {
taOutput.setText("");
taOutput.append(sHelp);
}
//if (e.getSource() == btnClearscreen) {
// taOutput.setText("");
//}
}
}

private void doScan() {
String drive = cbDrive.getSelectedItem().toString();
File d = new File(drive + ":\\");
if (d.exists() == false) {
taOutput.append("Drive: " + drive + " not found, Please try again.\n");
return;
}
taOutput.append("Starting scan on Drive: " + drive + "\nPlease wait...\n");
File f = new File(drive + ":\\autorun.inf");
if (f.exists() && f.isFile()) {
taOutput.append("FOUND: \'autorun.inf\' virus-launcher\n");
int response = JOptionPane.showConfirmDialog(null,
"Found: \'autorun.inf\' virus launcher. Shall I delete it?");
if (response == 0) {
try {
f.delete();
taOutput.append("Virus launcher successfully deleted\n\n");
} catch (Exception x) {
taOutput.append(x.getMessage() + "\n");
JOptionPane.showMessageDialog(null, x.getMessage());
}
}
} else {
if (f.isDirectory() == true) {
taOutput.append("autorun.inf folder found.\nPendrive already innoculated\n");
} else {
taOutput.append("\'autorun.inf\' virus launcher NOT found\n");
}
}

}

private void doInnoculate() {
String drive = cbDrive.getSelectedItem().toString();
File d = new File(drive + ":\\autorun.inf");
if (d.exists() == false) {
d.mkdir();
File dummy = new File(d, "DoNotDeleteThisFolder.txt");
try {
dummy.createNewFile();
taOutput.append("Innoculation succeeded. Fake autorun.inf folder created.\n");
taOutput.append("Do not delete this autorun.inf folder, it prevents the real\n");
taOutput.append("autorun.inf virus launcher from infecting your pendrive.\n");
} catch (Exception ex) {
taOutput.append(ex.getMessage() + "\n");
}
} else {
taOutput.append("autorun.inf folder exists. Your pendrive is already innoculated.\n");
}
}
}

Wednesday, February 11, 2009

IP Scanner 003 - using SwingWorker class (concurrent GUI)



/*
* GUI version of IPScanner
* Scans IP networks using ping
* uses SwingWorker class to
* concurrently update GUI
* by Paul Chin, Feb 11, 2009
*/
package ipscannergui;

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.*;
import javax.swing.*;

public class IPScannerGui extends JFrame {

private JButton btnStart;
private JTextField tfIP;
private JLabel lbIP;
private JTextArea taOutput;
private JScrollPane jsp;
//SwingWorker[] worker = new SwingWorker[100];

public static void main(String[] args) {
IPScannerGui sg = new IPScannerGui(); // create ButtonFrame
sg.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
sg.setSize(500, 400); // set frame size
sg.setVisible(true); // display frame

}

public IPScannerGui() {
super("IP Scanner 003");
setLayout(new FlowLayout()); // set frame layout
lbIP = new JLabel("Enter network (eg 118.100.118)");
tfIP = new JTextField("192.168.1", 20);
btnStart = new JButton("Start");
taOutput = new JTextArea(20, 40);
jsp = new JScrollPane(taOutput);
add(lbIP);
add(tfIP);
add(btnStart);
add(jsp);
ButtonHandler handler = new ButtonHandler();
btnStart.addActionListener(handler);
}

private class ButtonHandler implements ActionListener {

public void actionPerformed(ActionEvent e) {
if (e.getSource() == btnStart) {
try {
for (int i = 1; i < w =" new">() {

public String doInBackground() throws IOException {
String s;
s = doScan(ip);
return s;
}

public void done() {
String t = null;
try {
t = get();
taOutput.append(t);
} catch (Exception x) {
x.printStackTrace();
}
}
};
w.execute();
}

private String doScan(String ip) throws IOException {
String line;
Process p = Runtime.getRuntime().exec("cmd /c ping " + ip + " -n 1");
BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()));
while ((line = input.readLine()) != null) {
if (line.indexOf("Reply") > -1) {
System.out.println(line);
input.close();
return line + "\n";
}
}
return ip + " not found\n";


}
}

IP Scanner 002 - using ExecutorService (concurrent GUI)



/*
* GUI version of IPScanner
* Scans IP networks using ping
* Concurrent GUI update
*/
package ipscannergui;

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.*;
import java.util.concurrent.*;
import javax.swing.*;

public class IPScannerGui extends JFrame {

private JButton btnStart;
private JTextField tfIP;
private JLabel lbIP;
private JTextArea taOutput;
private JScrollPane jsp;

public static void main(String[] args) {
IPScannerGui sg = new IPScannerGui();
sg.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
sg.setSize(500, 400);
sg.setVisible(true);

}

public IPScannerGui() {
super("IP Scanner 002");
setLayout(new FlowLayout()); // set frame layout
lbIP = new JLabel("Enter network (eg 118.100.118)");
tfIP = new JTextField("118.100.118", 20);
btnStart = new JButton("Start");
taOutput = new JTextArea(20, 40);
jsp = new JScrollPane(taOutput);
add(lbIP);
add(tfIP);
add(btnStart);
add(jsp);
ButtonHandler handler = new ButtonHandler();
btnStart.addActionListener(handler);

}

private class ButtonHandler implements ActionListener {

public void actionPerformed(ActionEvent e) {
if (e.getSource() == btnStart) {
IPScanner[] ips = new IPScanner[254];

ExecutorService runner = Executors.newFixedThreadPool(254);
for (int i = 1; i < 20="=" ip =" ipadd;" p =" Runtime.getRuntime().exec(" input =" new" line =" input.readLine())"> -1) {
//System.out.println(line);
final String r = line + "\n";
SwingUtilities.invokeLater(new Runnable() {

public void run() {
taOutput.append(r);
}
});
}
}
} catch (Exception e) {
e.printStackTrace();
}

}
}
}

Monday, February 9, 2009

IP Scanner 001 - Multi-threading but delayed GUI update



/*
* GUI version of IPScanner
* Scans IP networks using ping
* by Paul Chin, Feb 9, 2009
*/
package ipscannergui;

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.*;
import javax.swing.*;

public class IPScannerGui extends JFrame {

private JButton btnStart;
private JTextField tfIP;
private JLabel lbIP;
private JTextArea taOutput;
private JScrollPane jsp;

public static void main(String[] args) {
IPScannerGui sg = new IPScannerGui();
sg.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
sg.setSize(500, 400);
sg.setVisible(true);

}

public IPScannerGui() {
super("IP Scanner 001");
setLayout(new FlowLayout()); // set frame layout
lbIP = new JLabel("Enter network (eg 118.100.118)");
tfIP = new JTextField("118.100.118",20);
btnStart = new JButton("Start");
taOutput = new JTextArea(20, 40);
jsp = new JScrollPane(taOutput);
add(lbIP);
add(tfIP);
add(btnStart);
add(jsp);
ButtonHandler handler = new ButtonHandler();
btnStart.addActionListener(handler);
}

private class ButtonHandler implements ActionListener {

public void actionPerformed(ActionEvent e) {
if (e.getSource() == btnStart) {
try {

doScan();
} catch (Exception x) {
x.printStackTrace();
}
}
}
}

private void doScan() throws InterruptedException {
Thread[] t = new Thread[255];
MyScanner[] ms = new MyScanner[255];
String net= tfIP.getText() + "."; //Construct net addr eg 192.168.1.
for (int i = 1; i < ip =" ip;" taresult =" (JTextArea)" p =" Runtime.getRuntime().exec(" input =" new" line =" input.readLine())"> -1) {
System.out.println(line);
taResult.append(line + "\n");
}
}
input.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}

IP Scanner

/*
* Scans IP networks using ping
* Substitute your target net address in String net
* by Paul Chin, Feb 9, 2009
*/
package ipscanner;

import java.io.BufferedReader;
import java.io.InputStreamReader;

public class IPScanner {

public static void main(String[] args) throws InterruptedException {
IPScanner ips = new IPScanner();
ips.doScan();
}

private void doScan() throws InterruptedException {
Thread[] t = new Thread[255];
MyScanner[] ms = new MyScanner[255];
String net = "118.100.118.";
for (int i = 1; i < 255; i++) {
ms[i] = new MyScanner(net + i);
t[i] = new Thread(ms[i]);
t[i].start();
Thread.sleep(100);
}
}
}

class MyScanner implements Runnable {

String ip;

public MyScanner(String ip) {
this.ip = ip;
}

public void run() {
try {
String line;
Process p = Runtime.getRuntime().exec("cmd /c ping " + ip + " -n 1");
BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()));
while ((line = input.readLine()) != null) {
if (line.indexOf("Reply") > -1) {
System.out.println(line);
}
}
input.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}

Bluetooth J2ME Server, J2SE Server and J2ME Client - How to Use

In the previous 3 posts, I put up the sources for the following:

1. J2ME Server
2. J2ME Client
3. J2SE Server

How to Use:

Every client communicates with a server.
Server should always listen first, then, only start the
Client.

Therefore, you can use the following combinations:

A. J2ME Server <--> J2ME Client (mobile phone to mobile phone)
B. J2SE Server <--> J2ME Client (PC to mobile phone, or vice versa)

Scenario A can be run on PC in emulator mode for both Server and Client, or,
both Server and Client run on Mobile Phone.Both (Server and Client) must be run
on PC Emultor, or, both transferred to Mobile phone and run from two mobile phones.
One Mobile Phone will run the Server whilst the second Mobile Phone run the client.

Scenario B, Server must be run on PC whilst Client must be run on real Mobile phone.
In order to run J2SE server you must install the Bluecove library first. This library enables
you to access your PC's Bluetooth hardware. As such when you run Scenario B, you are
actually using the PC's real Bluetooth hardware to communcate with a real mobile Phone.

Summary:
To communicate between two mobile phones, use Scenario A
To communicate between PC and mobile phone (or vice versa), use Scenario B

Bluetooth J2SE Server

Use this server with the J2ME Client

/*
* J2SE Server - to start listening from for connections from
* Mobile Phones and receive a string and display it
*/
package j2seserver;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import javax.bluetooth.*;
import javax.microedition.io.Connector;
import javax.microedition.io.StreamConnection;
import javax.microedition.io.StreamConnectionNotifier;

public class J2SEServer {

public static void main(String[] ags) throws BluetoothStateException, IOException {
new J2SEServer().startServer();
}

private void startServer() throws BluetoothStateException, IOException {
LocalDevice local = LocalDevice.getLocalDevice();
if (!local.setDiscoverable(DiscoveryAgent.GIAC)) {
System.out.println("Failed to change to the " + "discoverable mode");
}

// Create a server connection object to accept
// a connection from a client
StreamConnectionNotifier notifier =
(StreamConnectionNotifier) Connector.open("btspp://localhost:" +
"86b4d249fb8844d6a756ec265dd1f6a3");

// Accept a connection from the client
StreamConnection conn = notifier.acceptAndOpen();

// Open the input to read data from
InputStream in = conn.openInputStream();
ByteArrayOutputStream out = new ByteArrayOutputStream();

// Read the data sent from the client until
// the end of stream
int data;
while ((data = in.read()) != -1) {
out.write(data);
}

System.out.println(out.toString());
}
}

Bluetooth J2ME Client

Use this client with either J2SE Server OR J2ME Server

/*
* J2ME Client - to sent a string to the J2SE Server
*/
package j2meclient;

import java.io.OutputStream;
import javax.bluetooth.*;
import javax.microedition.io.*;
import javax.microedition.lcdui.*;
import javax.microedition.midlet.*;

public class J2MEClientMidlet extends MIDlet implements CommandListener, Runnable {

Display d;
Command cmExit, cmConnect;
Form f;
Thread t;
String connString;

public J2MEClientMidlet() {
f = new Form("Client");
cmExit = new Command("Exit", Command.EXIT, 1);
cmConnect = new Command("Connect", Command.ITEM, 2);

f.addCommand(cmExit);
f.addCommand(cmConnect);
f.setCommandListener(this);
}

public void startApp() {
if (d == null) {
d = Display.getDisplay(this);
d.setCurrent(f);
t = new Thread(this);
}
}

public void pauseApp() {
}

public void destroyApp(boolean unconditional) {
}

public void commandAction(Command c, Displayable d) {
if (c == cmExit) {
destroyApp(false);
notifyDestroyed();
}
if (c == cmConnect) {
t.start();
}
}

public void run() {
try {
// Retrieve the connection string to connect to
// the server
LocalDevice local =
LocalDevice.getLocalDevice();
DiscoveryAgent agent = local.getDiscoveryAgent();
connString = agent.selectService(
new UUID("86b4d249fb8844d6a756ec265dd1f6a3", false),
ServiceRecord.NOAUTHENTICATE_NOENCRYPT, false);
} catch (Exception e) {
}

if (connString != null) {

try {
// Connect to the server and send 'Hello, World'
StreamConnection conn = (StreamConnection) Connector.open(connString);
OutputStream out = conn.openOutputStream();
Thread.sleep(2000); //2 secs delay necessary to wait for
//Nokia 3120 to open connection
out.write("Hello, World".getBytes());
out.close();
conn.close();
f.append("Message sent correctly");

} catch (Exception ex) {
f.append("IOException: ");
f.append(ex.getMessage());
}
}
else{
f.append("Unable to locate service");
}
}
}

Bluetooth J2ME Server

Use this Server with the J2ME Client

/*
* J2ME Server Midlet to accept incoming connection and a string
* from the J2ME Client counterpart
*/

package j2meserver;

import java.io.*;
import javax.bluetooth.*;
import javax.microedition.io.*;
import javax.microedition.lcdui.*;
import javax.microedition.midlet.*;

public class J2MEServerMidlet extends MIDlet implements CommandListener,Runnable{
Form f;
Command cmExit,cmListen;
Thread t;
Display d;
public J2MEServerMidlet(){
f=new Form("J2ME Server");
cmExit=new Command("Exit",Command.EXIT,1);
cmListen=new Command("Listen",Command.SCREEN,2);
f.addCommand(cmExit);
f.addCommand(cmListen);
f.setCommandListener(this);
}
public void startApp() {
if (d == null) {
d = Display.getDisplay(this);
d.setCurrent(f);
t = new Thread(this);
}
}

public void pauseApp() {
}

public void destroyApp(boolean unconditional) {
}

public void commandAction(Command c, Displayable d) {
if(c==cmExit){
destroyApp(false);
notifyDestroyed();
}
if(c==cmListen){
t.start();
}
}

public void run() {
try {
startServer();
} catch (BluetoothStateException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
}
}

private void startServer() throws BluetoothStateException, IOException {
LocalDevice local = LocalDevice.getLocalDevice();
if (!local.setDiscoverable(DiscoveryAgent.GIAC)) {
System.out.println("Failed to change to the " + "discoverable mode");
}

// Create a server connection object to accept
// a connection from a client
StreamConnectionNotifier notifier =
(StreamConnectionNotifier) Connector.open("btspp://localhost:" +
"86b4d249fb8844d6a756ec265dd1f6a3");

// Accept a connection from the client
StreamConnection conn = notifier.acceptAndOpen();

// Open the input to read data from
InputStream in = conn.openInputStream();
ByteArrayOutputStream out = new ByteArrayOutputStream();

// Read the data sent from the client until
// the end of stream
int data;
while ((data = in.read()) != -1) {
out.write(data);
}
f.append("Received: ");
f.append(out.toString());
}
}

Saturday, February 7, 2009

Bluetooth Acronyms

JABWT Stack:




JABWT = Java API for Bluetooth Wireless Technology
BTSPP = BlueTooth Serial Port Profile, as in btspp://localhost
BCC = Bluetooth Control Centre
OBEX = Object Exchange
SDP = Service Discovery Protocol
SDDB = Service Discovery DataBase
L2CAP = Logical Link Control and Adaptation Protocol
GCF = Generic Connection Framework :

Tuesday, February 3, 2009

Object Serialization and ArrayList

//Human class
import java.io.Serializable;


public class Human implements Serializable{
private String firstname;
private int age;

public void setFirstname(String fn){
firstname=fn;
}
public void setAge(int a){
age=a;
}
public String getFirstname(){
return firstname;
}
public int getAge(){
return age;
}
}


//Main class
import java.io.*;
import java.util.ArrayList;
import java.util.Scanner;

public class Practice {

public static void main(String[] args) throws IOException {
ArrayList hList = new ArrayList();
Human h = null;
FileInputStream fis = null;
ObjectInputStream ois = null;
FileOutputStream fos = null;
ObjectOutputStream oos = null;

Scanner in = new Scanner(System.in);
fos = new FileOutputStream("human.txt");
oos = new ObjectOutputStream(fos);

for (int i = 0; i <>
h=new Human();
System.out.println("Enter firstname:");
h.setFirstname(in.nextLine());
System.out.println("Enter age:");
h.setAge(Integer.parseInt(in.nextLine()));
hList.add(h);
}
for(int i=0;i
oos.writeObject(hList.get(i));
}
oos.close();
fos.close();


fis = new FileInputStream("human.txt");
ois = new ObjectInputStream(fis);
hList.clear();
try {
while (true) {
hList.add((Human) ois.readObject());
}
} catch (Exception e) {

ois.close();
fis.close();
}
for(Human j:hList){
System.out.println(j.getFirstname() + " : " +j.getAge());
}

}
}

How to write Remote Access Tools in Java


I will start another book to cater for students who has no background knowledge in programming. It will be my 5th book.


My proposal is as follows:



HOW TO WRITE YOUR OWN REMOTE ACCESS TOOLS IN JAVA

Abstract

Remote Access Tools also known as RATs are used to remotely control another PC

over the Internet or the Local Area Network.

This book shows you in an easy & simple step-by-step approach to start

writing such a tool from scratch.

RATs are used in network management, remote surveillance, system

administration, classroom teaching system and so on.

In learning how to write RATs you will learn about Java programming,

networking as well as operating systems in a fun and exciting way!

Table of Contents

1 The Tools You Will Need & Networking Essentials

2 Your First Hello World Network Program

3 Running Multiple Commands and Handling Client Disconnections

4 Multitasking : Using Threads to run commands concurrently

5 Two-Way Communication

6 Controlling Hardware Remotely

7 Enabling Unlimited Number of Commands on Server

8 How to Create a Portbinding Shell

9 Portbinding Shell Server Without WIN32 API

10 Reverse Connection Shell

11 Remote Desktop Capture

12 Reverse Remote Desktop Capture Using Remote Method Invocation

13 Executing Commands in a Reverse Connection System - Polling Method

Project Duration

Project duration to complete this book is estimated to be about 6 to 8 months.


Target Audience

Primary Target audience: Existing Inti Students

Secondary Target audience: Bridging Program Students

Monday, February 2, 2009

Execute an external program from Java

http://www.rgagnon.com/javadetails/java-0014.html

This example will capture the output (from stdio) of an external program:

import java.io.*;
public class CmdExec {

public static void main(String argv[]) {
try {
String line;
Process p = Runtime.getRuntime().exec
(System.getenv("windir") +"\\system32\\"+"tree.com /A");
BufferedReader input =
new BufferedReader
(new InputStreamReader(p.getInputStream()));
while ((line = input.readLine()) != null) {
System.out.println(line);
}
input.close();
}
catch (Exception err) {
err.printStackTrace();
}
}



The next example, launch CMD.EXE, grab stdin/stdout and push to stdin command to be
interpreted by the shell:

String line;
OutputStream stdin = null;
InputStream stderr = null;
InputStream stdout = null;

// launch EXE and grab stdin/stdout and stderr
Process process = Runtime.getRuntime ().exec ("/folder/exec.exe");
stdin = process.getOutputStream ();
stderr = process.getErrorStream ();
stdout = process.getInputStream ();

// "write" the parms into stdin
line = "param1" + "\n";
stdin.write(line.getBytes() );
stdin.flush();

line = "param2" + "\n";
stdin.write(line.getBytes() );
stdin.flush();

line = "param3" + "\n";
stdin.write(line.getBytes() );
stdin.flush();

stdin.close();

// clean up if any output in stdout
BufferedReader brCleanUp =
new BufferedReader (new InputStreamReader (stdout));
while ((line = brCleanUp.readLine ()) != null) {
//System.out.println ("[Stdout] " + line);
}
brCleanUp.close();

// clean up if any output in stderr
brCleanUp =
new BufferedReader (new InputStreamReader (stderr));
while ((line = brCleanUp.readLine ()) != null) {
//System.out.println ("[Stderr] " + line);
}

Launch a Windows CMD (or BAT) file and retrieve the errorlevel or exitcode:


/ win xp
import java.io.*;
public class CmdExec {
public static void main(String argv[]) {
try {
String line;
Process p = Runtime.getRuntime().exec("test.cmd");
p.waitFor();
System.out.println(p.exitValue());
}
catch (Exception err) {
err.printStackTrace();
}
}

test.cmd (set the errorlevel manually):

@echo hello world

test.cmd (set the errorlevel 1 (problem detected):

@java -garbage

test.cmd (set the errorlevel 0 (execution Ok):

@java -version

Launch a Unix script:

String[] cmd = {"/bin/sh", "-c", "ls > hello"};
Runtime.getRuntime().exec(cmd);

Using the ProcessBuilder

Since 1.5, the ProcessBuilder class provides more controls overs the process to be started. It's possible to set a starting directory.

 
import java.io.*;
import java.util.*;

public class CmdProcessBuilder {
public static void main(String args[])
throws InterruptedException,IOException
{
List command = new ArrayList();
command.add(System.getenv("windir") +"\\system32\\"+"tree.com");
command.add("/A");

ProcessBuilder builder = new ProcessBuilder(command);
Map environ = builder.environment();
builder.directory(new File(System.getenv("temp")));

System.out.println("Directory : " + System.getenv("temp") );
final Process process = builder.start();
InputStream is = process.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
System.out.println("Program terminated!");
}

Windows rundll32 utility

Windows File association
Any program using the Windows file association mechanism can be started with the rundll32 utility.

/ "file" is the filename of the data file
// ex. myresume.doc
// to start Word if the doc extension is associated with it.
Runtime.getRuntime().exec

See also this HowTo about the new Desktop API, the recommended solution (but you need JDK1.6).
See also this one to open the default browser.

The following example start a Dial-up connection on the Win plateform :


[Dialup.java]
public class Dialup {
public static void main(String[] args) throws Exception {
Process p = Runtime.getRuntime()
.exec("rundll32.exe rnaui.dll,RnaDial MyConnection");
p.waitFor();
System.out.println("Done.");
}
}


The "MyConnection" is the DUN and it's case sensitive.

You still need to press ENTER to CONNECT, there is an option in the Connection properties to connect automatically.

On NT and W2K, rnaui.dll is not available. Use rasdial.exe instead.


rasdial "connection name"
rasdial "connection name" /d to drop
rasdial /? for more options


PDF (Windows only)


public class ShowPDF {
public static void main(String[] args) throws Exception {
Process p =
Runtime.getRuntime()
.exec("rundll32 url.dll,FileProtocolHandler c:/pdf/mypdf.pdf");
p.waitFor();
System.out.println("Done.");
}

More runddl32 examples

Path to executable with spaces in them

You can include a path for the program to be executed. On the Win plateform, you need to put the path in quotes if the path contains spaces.

public class Test {
public static void main(String[] args) throws Exception {
Process p = Runtime.getRuntime().exec(
"\"c:/program files/windows/notepad.exe\"");
p.waitFor();
}


f you need to pass arguments, it's safer to a String array especially if they contain
spaces.

String[] cmd = { "myProgram.exe", "-o=This is an option" };
Runtime.getRuntime().exec(cmd);


If using the start command and the path of the file to be started contains a space then you must specified
a title to the start command.

String fileName = "c:\\Applications\\My Documents\\test.doc";
String[] commands = {"cmd", "/c", "start", "\"DummyTitle\"",fileName};

VBSCRIPT


// Win9x
Runtime.getRuntime().exec("start myscript.vbs");

// WinNT
Runtime.getRuntime().exec("cmd /c start myscript.vbs");

or

// with a visible console
Runtime.getRuntime().exec("cscript myscript.vbs");

// with no visible console

HTML Help (Windows only)


Runtime.getRuntime().exec("hh.exe myhelpfile.chm");

Start Excel


import java.io.IOException;

class StartExcel {
public static void main(String args[])
throws IOException
{
Runtime.getRuntime().exec("cmd /c start excel.exe");
}


To load a worksheet

import java.io.IOException;

class StartExcel {
public static void main(String args[])
throws IOException
{
String fileName = "c:\\temp\\xls\\test2.xls";
String[] commands = {"cmd", "/c", "start", "\"DummyTitle\"",fileName};
Runtime.getRuntime().exec(commands);
}


It's important to pass a dummy title to the Windows start command where there is a possibility
that the filename contains a space. It's a feature.



Start a Windows application under another account

You use the RUNAS command from the command line to start an application under another account (not available with XP Home edition). There are many switches that can enhance the behaviour of RUNAS. Typing "runas /?" from the command prompt gets you all the options.
String  commands [] = new String [] {
"CMD.EXE",
"/C",
"RUNAS /profile /savecred /user:"
+ "administrator"
+ " " + "regedit.exe"
};

Runtime.getRuntime().exec(commands);
}
}
/SaveCred option allows you to save a password for that account and then reuse it later. For example, The command runas /savecred /user:administrator regedit.exe prompts for the password, and then Regedit runs. Next time you use the same command, there is no password prompt.

One potential problem is that when /SaveCred saves the credentials it saves it for whenever RUNAS invokes that user account. This can be a huge security risk so be careful using it!

RUNAS capability can be disabled by editing the Registry or by disabling the RUNAS or Secondary Logon Services. The appropriate registry key is HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\policies\Explorer, create a new DWORD value named HideRunAsVerb and assign it a value of 1 to disable Run as.

RUNAS doesn't work when used from a Windows service.

Windows : execute something in Program Files

We want to execute the textpad editor located in C:\Program Files\TextPad 4 but without hard coding the path since it can be different for a localized version of Windows.

We simply extract to environnment variable called %programfiles% and build the complete path from there.

[JDK1.5]


public class Exec {
static String WIN_PROGRAMFILES = System.getenv("programfiles");
static String FILE_SEPARATOR = System.getProperty("file.separator");

public static void main(String[] args) throws Exception {
String[] commands =
{"cmd.exe",
"/c",
WIN_PROGRAMFILES
+ FILE_SEPARATOR
+ "textpad 4"
+ FILE_SEPARATOR + "textpad.exe"};
Runtime.getRuntime().exec(commands);
}


NOTE :
Prior Vista, System folders were localized on disk like C:\Program Files ->
C:\Archivos de programa
on the Windows with the Spanish localization.
Since Vista, System Folders always exists with the english name BUT when
viewed through Explorer, the localized name is shown.

See http://msmvps.com/blogs/carlosq/archive/2007/02/12/windows-vista-junctions-points-mui-and-localized-folder-names.aspx
}




Command Execution


package practice;

import java.io.*;

public class CommandExecution {

public CommandExecution(String commandline) {
try {
String line;
Process p = Runtime.getRuntime().exec(commandline);
BufferedReader input =
new BufferedReader(new InputStreamReader(p.getInputStream()));
while ((line = input.readLine()) != null) {
System.out.println(line);
}
input.close();
} catch (Exception err) {
err.printStackTrace();
}
}

public static void main(String argv[]) {
new CommandExecution("cmd /c dir");
}
}

Process class in Java

http://java.sun.com/j2se/1.4.2/docs/api/java/lang/Process.html

The Runtime.exec methods create a native process and return an instance of a subclass of Process that can be used to control the process and obtain information about it. The class Process provides methods for performing input from the process, performing output to the process, waiting for the process to complete, checking the exit status of the process, and destroying (killing) the process.

The Runtime.exec methods may not work well for special processes on certain native platforms, such as native windowing processes, daemon processes, Win16/DOS processes on Microsoft Windows, or shell scripts. The created subprocess does not have its own terminal or console. All its standard io (i.e. stdin, stdout, stderr) operations will be redirected to the parent process through three streams (Process.getOutputStream(), Process.getInputStream(), Process.getErrorStream()). The parent process uses these streams to feed input to and get output from the subprocess. Because some native platforms only provide limited buffer size for standard input and output streams, failure to promptly write the input stream or read the output stream of the subprocess may cause the subprocess to block, and even deadlock.

The subprocess is not killed when there are no more references to the Process object, but rather the subprocess continues executing asynchronously.

There is no requirement that a process represented by a Process object execute asynchronously or concurrently with respect to the Java process that owns the Process object.

HTML Parser - Simple

This html parser searches for the string 'Malaysia' from
the website http://www.google.com.my and displays it:

/*
* By Paul Chin
*/
package htmlparser;

import java.io.*;
import javax.microedition.io.*;
import javax.microedition.lcdui.*;
import javax.microedition.midlet.*;

public class HtmlparserMidlet extends MIDlet implements CommandListener, Runnable {

private Display d;
private Form f;
private Command cmExit;

public HtmlparserMidlet() {
cmExit = new Command("Exit", Command.EXIT, 0);
f = new Form("Connecting...");
f.addCommand(cmExit);
f.setCommandListener(this);
}

public void startApp() {
if (d == null) {
d = Display.getDisplay(this);
d.setCurrent(f);

Thread t = new Thread(this);
t.start();
}
}

public void pauseApp() {
}

public void destroyApp(boolean unconditional) {
}

public void commandAction(Command c, Displayable d) {
if (c == cmExit) {
destroyApp(false);
notifyDestroyed();
}
}

public void run() {
HttpConnection hc = null;
DataInputStream in = null;
StringBuffer data = new StringBuffer();

String url = "http://www.google.com.my/index.html";

try {
hc = (HttpConnection) Connector.open(url);
in = new DataInputStream(hc.openInputStream());

int ch;
while (true) {
ch = in.read();
if (ch == -1) {
break;
}
data.append((char) ch);
}

//Search for string "Malaysia"
String s = data.toString();
int index = s.indexOf("Malaysia");
String t = s.substring(index, index + 8);


f.append(t);
f.setTitle("Done");
} catch (Exception e) {
}
}
}

J2ME SMTP Client - This one works

I've modified and corrected the errors in the the earlier
version. The code below works. It sends the message:
'TESTMESSAGE FROM INTI' to your email address.
You need to use nslookup to find the SMTP server
for your email domain first and substitue it in
the appropriate places.


/*
* SMTPClient by Paul Chin
*/
package smtpclient;

import java.io.*;
import java.util.Date;
import javax.microedition.io.*;
import javax.microedition.lcdui.*;
import javax.microedition.midlet.*;

public class SMTPClientMidlet extends MIDlet implements CommandListener, Runnable {

SocketConnection sc;
Display d;
Form f;
Command cmExit, cmSend;
InputStream is = null;
OutputStream os = null;
StringBuffer sb = new StringBuffer();
static final String domain = "intipen.edu.my";
static final String smtpServerAdress = "b.mx.mail.yahoo.com";
static final String from_emailAdress = "justacoder@intipen.edu.my";
static final String to_emailAdress = "javarocks@yahoo.com";
Thread t;

public SMTPClientMidlet() {
cmExit = new Command("Exit", Command.EXIT, 0);
cmSend = new Command("Send", Command.SCREEN, 1);


f = new Form("SMTP Client");


f.addCommand(cmExit);
f.addCommand(cmSend);
f.setCommandListener(this);
}

public void startApp() {
if (d == null) {
d = Display.getDisplay(this);
d.setCurrent(f);

t = new Thread(this);
}
}

public void pauseApp() {
}

public void destroyApp(boolean unconditional) {
}

public void sendEmail() {
int ch;
byte[] b = new byte[2046];
try {
sc = (SocketConnection) Connector.open("socket://" + smtpServerAdress + ":25");
is = new DataInputStream(sc.openInputStream());

os = sc.openOutputStream();

is.read(b);
// Send SMTP-Commands
os.write(("HELO " + domain + "\r\n").getBytes());
is.read(b);


os.write(("MAIL FROM: <" + from_emailAdress + ">\r\n").getBytes());
is.read(b);


os.write(("RCPT TO: <" + to_emailAdress + ">\r\n").getBytes());
is.read(b);


os.write("DATA\r\n".getBytes());
is.read(b);

os.write(("Date: " + new Date() + "\r\n").getBytes());
os.write(("From: " + from_emailAdress + "\r\n").getBytes());
os.write(("To: " + to_emailAdress + "\r\n").getBytes());
os.write(("Subject: INTI TEST\r\n").getBytes());
os.write(("\r\n").getBytes());
os.write(("TESTMESSAGE FROM INTI \r\n").getBytes());
os.write(".\r\n".getBytes());
is.read(b);

os.write("QUIT\r\n".getBytes());
is.read(b);

System.out.println(sb.toString());
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (is != null) {
is.close();
}
if (os != null) {
os.close();
}
if (sc != null) {
sc.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}

}

public void commandAction(Command c, Displayable d) {
if (c == cmExit) {
destroyApp(false);
notifyDestroyed();
}
if (c == cmSend) {
t.start();
}
}

public void run() {
sendEmail();
}
}