Monday, February 9, 2009
Bluetooth J2ME Server
/*
* 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 = 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
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
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
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
{
Listcommand = new ArrayList ();
command.add(System.getenv("windir") +"\\system32\\"+"tree.com");
command.add("/A");
ProcessBuilder builder = new ProcessBuilder(command);
Mapenviron = 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 associationAny 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
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.