Java Coding Example

Edited by Lim Siong Boon, last dated 22-Sep-2010.

email:    contact->email_siongboon  

website: http://www.siongboon.com



Java Primitive Data Types
Type Contains Default Size Range
boolean true or false false 1 bit n.a.
char Unicode character unsigned \u0000 2 bytes (16 bits) \u0000 to \uFFFF or 0 to 216-1
byte Signed integer 0 1 byte (8 bits) -128 to 127 or (-27 to 27-1)
short Signed integer 0 2 bytes (16 bits) -32768 to 32767 or (-215 to 215-1)
int Signed integer 0 4 bytes (32 bits) -2147483648 to 2147483647 or (-231 to 231-1)
long Signed integer 0 8 bytes (64 bits) -9223372036854775808 to 9223372036854775807 or (-263 to 263-1)
float IEEE 754 floating point single-precision 0.0f 4 bytes (32 bits) 1.4E-45 to 3.4028235E+38
double IEEE 754 floating point double-precision 0.0 8 bytes (64 bits) 439E-324 to 1.7976931348623157E+308


Java Language References


Escape code for Java Regular Expression

http://www.wellho.net/regex/javare.html


Character Escape Codes Description
\n new line (0x0A)
\t tab (0x09)
\b backspace (0x08)
\r carriage return (0x0D)
\f form feed (0x0C)
\\ backslash
\' single quotation mark
\" double quotation mark
\?? octal
\x?? hexadecimal
\u?? unicode character

Java Regular Expressions   java.util.regex

My first encounter with regex happens when I was using String.split() function. The split char is represented by special char used by regex. I thought the function is easy to use but is spending a lot of time figuring why the string cannot be split. I was splitting the IP address which is separated by the '.' dot or period. My colleague drop me some notes from the website, and now I finally know what really happen. Great article I must say.

Class typically use for wild card search in String.

The following are some char keyword in used by the regular expressions class. In order to use the char, use \ followed by the char or insert the printable string between \Q and \E

metacharacters->   ([{\^-$|]})?*+.

There are more about regex than I thought after searching the web.

http://en.wikipedia.org/wiki/Regular_expression



String tx = "Delta values are labeled \"\u0394\" on the chart.";



Java Fundamental References

package sg.com.siongboon.mypackage; //Basic java class structure

public class ClassName
{
  private int myResult;

  static
  {
    //Similar to constructor which will be executed
    //before the object is created.
    //It can be use like a constructor for your static class object,
    //where a constructor is not allowed.
         //static initializer block, it is seldom used (see example on *.dll)
  

  public ClassName()
  //class constructor
  }  

  public methodOne()
  
  }

  final public methodOne()
  //method cannot be overriden by other class extending it
  }

  static public methodOne()
  //method is the only instance. It will be common to all the class object
  }

  public static void main(String args[])
  { //entry point for running this program
  }
}

This is an example of a typical Java coding structure and some Java naming convention for package, class, method, and variable.

//A simple illustration of Java access modifier, Private, Default, Protected, Public

java access modifier

Java access modifier:

public- Variables/methods using public modifier can be access easily by all objects.

protected- Protected members can be accessed by another package through inheritence. Class CC managed to access protected member C through inheritence. Class CC inherited Class AA, therefore member C becomes part of Class CC.

default- If there is no modifier specified, Java will treat it as the default modifier. Default members B gets a bit more difficult to access. Only classes within the same package can access to it. Member B using the default modifier can be access by Class BB. Class BB can creates an instance of Class AA or through static variable access to access to member B.

private- is the most restrictive modifier. The private member A can only be access within the class AA itselfs. Class AA being the creator, is able to access all it's members A, B, C and D. It is recommended to start the data/method encapsulation using private modifier. Change the modifier when neccessary. There must be a good reason why private modifier is not use.

 

Future research the meaning on these defination:

public interface ClassName
protected interface ClassName
private interface ClassName
public void MethodName();
protected void MethodName();
private void MethodName();
abstract..

What do these defination really means?

 
   
Byte Manipulation  

//Java do not have unsigned data type
//Representation of the unsigned for a signed data type.
byte temp;
int result;
result=(int)(temp[0]&0xFF);  
//extract the unsigned value

long longNum = 289637082704667748;   //The literal 289637082704667748 of type int is out of range

long longNum = 289637082704667748L; //if the literal value is too big, L is required at the back

int result=(int)((1.26)+0.5);         //rounding off to the nearest integer



//f indicates that 1.5 is of data type float rather than a double.
//(any literal is intepreted as a double and not a float)
float x = 1.5f ;  
double x = 1.5;


//Casting a numeric value to a char
char c3 = (char)87;
char c1 = '\u0057';


//declare & allocate memory for byte & char array
byte remoteIP[] = new byte[4];
byte[] dataByte = new byte[]{(byte) 0xDB, (byte) 0xA1};
char[] dataBuf = new char[100];//declare & allocate memory for byte

//converting a byte array for string use
//Please note that byte data maybe lost after converting to string using this method.  
//The conversion uses a default charsetName; 
//if charset is not able to map the data to a char, it could convert it to the data 0x3F.
String dataStr = new String(dataByte);
String dataStr = new String(dataByte,"US-ASCII");

//converting a string to byte[]
byte[] dataByte = dataStr.getBytes();
//converting a byte to char for string use (convert a byte to char)
char dataChar = (char0xDB;
//converting a byte to string for string use (convert a byte to String)
String str = String.valueOf((char)ch);

//more methods for dealing with bytes 
ByteBuffer byteBuffer = ByteBuffer.allocate(10);
byteBuffer.put(0x01);


int hex = Integer.parseInt(HexString, 16);
String str = Integer.toHexString(79);
byte b = (byteInteger.parseInt("192");

String str = Integer.toBinaryString(79);
//parse hex string. HexString="FFFF", result-> hex=65535
//convert number 79 to a hex string "4f"
//convert the string "192" into a byte 0xC0
//convert number 79 to a binary string "01111001"
//defining byte constant array
private static final byte[] MYCONSTANT = {0x040x04, (byte)0xFF0x64};
//static means that there is only one instance for the variable
//final means that the variable cannot be overriden



//Bitwise Operator
>>>   //right shift without preserving the sign bit
>>    //right shift preserving the sign bit

<<    //left shift preserving the sign bit


   
Integer String Manipulation

int num = Integer.parseInt(String);
int hex = Integer.parseInt(HexString, 16);
String str = Integer.toString(79);
String str = Integer.toBinaryString(79);
String str = Integer.toHexString(79);
byte b = (byteInteger.parseInt("192");
//Example: Convert from string to numerical value
//parse hex string. HexString="FFFF", result-> hex=65535
//convert number 79 to a string "79"
//convert number 79 to a binary string "01111001"
//convert number 79 to a hex string "4f"
//convert the string "192" into a byte 0xC0
String str = "abc]123]XYZ";
String str2 = "abc|123";
String strAr[];
//split str "abc]123]XYZ" into 3 sub-string
//strAr[0]=="abc", strAr[1]=="123", strAr[1]=="XYZ"
strAr = str.split("]",3);
//split str1 into 2 sub-string
//strAr[0]=="abc", strAr[1]=="123"
strAr = str2.split("\\|");


   
//compare & match string
String str = "This is my String."
boolean b = str.matches(regex);
int i = str.compareTo("my");
 
 

//formatting a string like printf or sprintf
String str = String.format("Number=%2d, %f", 5, 1.56); //result>"Number= 5, 1.56"

String str = String.format("Leading Zero=%04d", 5); //result>"Leading Zero=0005"
String str = String.format("Hex value=0x%04x", 79 ); //result>"Hex value=0x004F"

Leading or padded zero
String strDecimalFormat formatV = new DecimalFormat("#.##");
String str = String str = formatV.format(1.246f)//result>"1.25"
special numerical formatting
DecimalFormat formatV = new DecimalFormat("###0.00");    //floating value to 2 decimal place
String str = String.format("%6s",formatV.format(value));  //right align
//value =  0.91, result -> "  0.91"
//value = 21.91, result -> " 21.91"
//value = 12   , result -> " 12.00"
Right align a 2 decimal place floating number
String subStr = Integer.toBinaryString(str.charAt(x));
res = res + inBetween + String.format("%8s", subStr).replace(' ', '0');
//convert char/int to 8 bit binary
//to check/compare the data/object type of a unknown java object
boolean x = aAnimal instanceof Fish


private enum BonjourService
{    
  //use enum if there is a fix defined number of constant
  //enum can help to restrict the number input choice for
  //the programmer to feed it into the method
        CAMERA, HTTP, PRINTER, IPP, PDL_DATASTREAM
}

private String getServiceProtocolName(BonjourService service)
{
  String servStr;
        if(service==BonjourService.CAMERA)
            servStr = "_camera._tcp";
        else if(service==BonjourService.HTTP)
            servStr = "_http._tcp";
        else if(service==BonjourService.PRINTER)
            servStr = "_printer._tcp";
        else if(service==BonjourService.IPP)
            servStr = "_ipp._tcp";
        else if(service==BonjourService.PDL_DATASTREAM)
            servStr = "_pdl-datastream";       
}

String str = "(" + BonjourService.CAMERA + ")";
String str = "(" + BonjourService.CAMERA.toString() + ")";
//str="(CAMERA)", enum variables can also be used as String object.


public enum BonjourService
{
  CAMERA("camera"), HTTP("http"), PRINTER("printer");

  //constructor cannot be public
  //constructor allows multiple parameters, so that
  //the enum can represent more than 1 parameter.
  private BonjourService(String name)
  {
    this.name = name;
  }
  
  private final String name;
  public String toString()
  {
    return name;
  }
}

You should use enum types any time you need to represent a fixed set of constants. That includes natural enum types such as the planets in our solar system and data sets where you know all possible values at compile time—for example, the choices on a menu, command line flags, and so on.

Toolkit.getDefaultToolkit().beep(); //error beep tone

 

 

Java structure to get the single instance of an object (singleton)  
AutoScheduleManager myAsm = AutoScheduleManager.getInstance();

public class 
AutoScheduleManager implements AxisObserver
{
    
protected static transient final Log logger = LogFactory.getLog(PcAdminService.class);

    
AutoSchedule autoSche;
    
PcAdminService pcA;
       
    
private static AutoScheduleManager ass = null;   
   
    
public static AutoScheduleManager getInstance(PcAdminService pcA)
    
//object can only create once. constructor method is private
        
if(ass == null)           
            
ass = new AutoScheduleManager(pcA);
        
return(ass);
    
}

    
private AutoScheduleManager(PcAdminService pcA)
    
{
        
this.pcA = pcA;
        
startScheduledShutdown(); //enable scheduled shutdown service when the service started.
    }
}

This singleton structure will ensure that the class object can only be created once. Constructor has to be defined as private while the class variable & getInstance method is static so that they can be access with the object being created.

This is the first question that I ask myself when designing a new class object even since I learned about it; whether it can be created with multiple instance or only a single static instance of the object. In some application, especially when working with hardware devices, single instance is the only proper way to built your class. It can helps you to prevent mis-written codes, resulting in less bugs/crush program when the class is used by another programmer.


Time, Date, Calendar, Timer

//Delay/sleep function
try{Thread.sleep(1000);}catch(InterruptedException e){}


//System time counting in millisecond. Measuring the cpu time to execute certain task
long sysMiliSecCount = System.currentTimeMillis( );
//do the task
long taskTime = System.currentTimeMillis( ) - sysMiliSecCount;


//Calendar, Date, Time (data & formatting function)
Calendar cal;
cal = Calendar.getInstance();
int hourday = cal.get(Calendar.HOUR_OF_DAY);  //24 hour format
int hour = cal.get(Calendar.HOUR);            //12 hour format
int am_pm = cal.get(Calendar.AM_PM);          //
int minute = cal.get(Calendar.MINUTE);
int sec = cal.get(Calendar.SECOND);
int msec = cal.get(Calendar.MILLISECOND);

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MMM-dd (EEE)");
SimpleDateFormat sdf2 = new SimpleDateFormat("hh:mm:ss aaa");
String data = sdf.format(cal.getTime());
String time = sdf2.format(cal.getTime());



//set periodic timer, Class need to implement Runnable
    
Timer RFIDscanTimer = new Timer("RFID Sort");
    
RFIDtagSort rfidTagSorting = new RFIDtagSort();
    
logger.info("Scan Period :  " + RFIDscanPeriod);
    
RFIDscanTimer.schedule(rfidTagSorting, 100, RFIDscanPeriod);
   
    
private class RFIDtagSort extends TimerTask
    
{
        
public RFIDtagSort()
        
{
        
}

        
@Override
        
public final void run()
        
{ //Run function will be executed every RFIDscanPeriod interval
            
logger.info("timer routine.");
        
}
    
}
Use the TimerTask for scheduling a periodic routine to execute .
//timeout implementation
int x = 0;
int timeoutSec = 3;    //set 3 seconds timeout
while(true)
{
  //stop and wait for ip & port number to be resolved           
  try{Thread.sleep(100);}catch(InterruptedException e){}
  x++;
  if(x==timeoutSec*10)
  {
    throw new TimeoutException("timeout occured");
  }
}
 
 



Array, Data Container
//Arraylist container example
ArrayList<String> a;
a.add(new String("Hello"));
Iterator<String> itr = a.iterator();
while(itr.hasNext())
{
    System.out.println(itr.next());
}


HashMap<Integer, Computer> map;
map.put(45,comp);
//Iterator using the HashMap's key

//Iterator<Integer> i=map.keySet().iterator();
//Iterator using the HashMap's value

Iterator<Computer> i=map.values().iterator();
while(i.hasNext())
{
    Computer c = (Computer)i.next();
    c.setSubnet(netInfo.getSubnetMaskAddr());
}


//Example: Ensure that the Array data container object is synchronized
ArrayList<objectName> myArrayList = new ArrayList();
List<objectName> mySyncList;
//Get the list that is synchronized from ArrayList

mySyncList = Collections.synchronizedList(arrayList);

//Another synchronized example for Map container
TreeMap<object1,object2> myMap = new TreeMap<object1,object2>();
Map<object1,object2> mySyncMap;
//Get the list that is synchronized from ArrayList

mySyncMap = Collections.synchronizedMap(myMap);
//Java ArrayList is NOT synchronized, meaning it is possible that any two process can access the un-sychronized data at the same time, causing runtime error. Two process may try to write data to the same memory location.

//Access the ArrayList through mySyncList object to ensure that there are no two or more simultaneously process accessing to the same ArrayList object. This is also applicable to other container objects. The mySyncList List object can be cast back to ArrayList, since it is originate from ArrayList.





Java debugging, exception and error handling resources

log4j
Example: FactoryLog for logging info, error, debug, etc messages.

Similar to System.out.println();

Save to project folder /lib /lib (factory logger).zip

Save to project folder /resource /resource (factory logger).zip

(Details of log file setup can be found in the file "log4j.properties".

Includes a 2nd example to config Log4j for logging in Tomcat.)

Log4j references:
http://logging.apache.org/log4j/1.2/manual.html
http://juliusdavies.ca/logging.html
http://www.laliluna.de/articles/log4j-tutorial.html



//Using LogFactory for debugging & logging example.
//Remember to include the path to "lib" & "resources" in the classpath
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

protected static transient final Log logger = LogFactory.getLog(YourClassName.class);

logger.error("");
logger.debug("Class name:<" + getClass().getSimpleName() + ">");
logger.info("Class name:<" + this.getClass().getName() + ">");  //print out the class name

//print out the method name
logger.info("Method name:<" + new Exception().getStackTrace()[0].getMethodName() + ">");

How to add *.jar library?Encountered the following errors?log4j:WARN No appenders could be found for logger (javax.swing.JApplet).
log4j:WARN Please initialize the log4j system properly.

Remember to add in the libraries in your project classpath. For Eclipse IDE the classpath is indicated in the .classpath in the project root directory.Alternative you can add the lib as follows in Eclipse:1) Right click on your project name (under "Package Explorer") and click "Properties" 2) Select "Java Build Path", and choose tab "Source". Add the folders "lib" & "resource" under your project folder. 3) Choose tab "Libraries". Click "Add JARS..." and add the "commons-logging-1.1.jar" & "log4j-1.2.14" library files. 4) Done.

//Two examples to print out error messages:
e.printStackTrace();
System.out.println("Got an IOException: " + e.getMessage());

logger.error("Got an IOException: ", e);


public KnxSession() throws KnxCommException
{
    try
    {
        int port = getLocalSessionPort();
        udp = new DatagramSocket(port);
        logger.info("\t\topened UDP port: " + port + " (for session)");
    }
    catch(SocketException e)
    {
        logger.error("error while calling setupUdpService()",e);
        //catching a system exeception, and create our own customised exception
        //(error messages) into meaningful message, which will be thrown up again.
        throw new KnxCommException("error message");
    }
    finally
    {
        //contain codes that will be executed after an exception is caught.
        //It is usually used for cleaning up the situation,
        //releasing or closing any resources (example file, network or databse connection.
        //It will be executed with or without exception occurred.
    }
}

public class MyOwnException extends Exception
{
    public MyOwnException(String msg)
    {
        super(msg);
    }

    public MyOwnException(String msg, Throwable t)
    {
        super(msg, t);
    }
}
 
A simple exception class, that accept customised error messages.
//KnxCommExeception Class
package knxEib.knxException;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class KnxCommException extends Exception
{
    protected static transient final Log logger = LogFactory.getLog(KnxCommException.class);

    static private int errorCounter = 0;

    public KnxCommException(String msg)
    {
        super(msg);
        errorCounter++;
        printErrorCount();
    }

    public KnxCommException(String msg, Throwable t)
    {
        super(msg, t);
        errorCounter++;
        printErrorCount();
    }

    private int printErrorCount()
    {
        logger.error("exception history count : " + errorCounter);
        try
        {
            String filename = "resource\\" + getClass().getName() + ".txt";
            BufferedWriter out = new BufferedWriter(new FileWriter(filename));
            out.write(filename + "\r\n");
            out.write("Error Count = " + errorCounter + "\r\n");
            out.close();
        }
        catch(IOException e)
        {
            e.printStackTrace();
        }
        return(errorCounter);
    }
}

A complex exception class that has more functions.



File I/O, Properties/Configuration file

Example: File Write

 

String filename = getClass().getName()+".txt";
try
{
    BufferedWriter out = new BufferedWriter(new FileWriter(filename));
    out.write(previousSessionID);
    out.write("\r\n");
    out.write("Session ID = " + previousSessionID + "\r\n");
    out.close();
}
catch(IOException e)
{
    e.printStackTrace();
}


BufferedReader in = null;
String filename = "resource\\output_mac2ip.txt";

try
{
    FileReader file = new FileReader(filename); // Open the file.
    in = new BufferedReader(file); // Tie 'input' to this file.
}
catch(FileNotFoundException x)
// The file may not exist.
    logger.error("File not found: " + filename);
    System.exit(2);
}

String linetext;
while( (linetext = in.readLine()) != null )
{
}


//monitoring new files added or removed from the file directory

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

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class DirMonitor
{
  protected static transient final Log logger = LogFactory.getLog(DirMonitor.class);

  private File dir;
  private Vector<File> filesVector = new Vector<File>();

  public DirMonitor(File dir)
  {
    this.dir = dir;
    MonitorTask task = new MonitorTask();
    Timer timer = new Timer();
    timer.scheduleAtFixedRate(task, 01000);
  }

  private class MonitorTask extends TimerTask
  {
    public void run()
    {
      /* get file list for this pass */
      File[] filesArray = dir.listFiles();
      Vector<File> newVector = new Vector<File>(filesArray.length);
      Collections.addAll(newVector, filesArray);

      /* copy the previous results */
      Vector<File> copyVector = new Vector<File>(filesVector.size());
      copyVector.addAll(filesVector);

      /* find out what files were removed */
      copyVector.removeAll(newVector);
      for(File file:copyVector)
      {
        System.out.println("Deleted file: " + file.getAbsolutePath());
        filesVector.remove(file);
      }

      /* find out what files were added */
      newVector.removeAll(filesVector);
      for(File file:newVector)
      {
        System.out.println("Added file: " + file.getAbsolutePath());
        filesVector.add(file);
      }
    }
  }

  public static void main(String[] args)
  {
    //new DirMonitor(new File(System.getProperty("user.home")));
    new DirMonitor(new File("C:\\Documents and Settings\\Administrator\\Desktop\\onOne software photos"));
  }
}
 
This class monitor new files added or removed from the directory. The class extends TimerTask which execute the run process every seconds.
Detect file modification.pdf  

 

//Reading a data stream with non-blocking mode 
private OutputStream out = null;
private InputStream out = null;
out = new DataOutputStream(sp.getOutputStream());
in = new DataInputStream(sp.getInputStream());
byte byteRead = in.read(); // -1 if there is no data 

Non-blocking mode is easy to write. I found it difficult when I learn that doing non-blocking input reading is so difficult using Java. I finally got the code to do the non-blocking reading of the input. Most Java examples that I saw were using blocking mode for their inputs. I think blocking mode would be better for long term maintenence. You might need to write extra thread just to handle those inputs under blocking mode; it may be more organised.
//convert String into InputStream
String str = "This is a String to be converted to an InputStream object later";
InputStream is = new ByteArrayInputStream(str.getBytes());
 
 
//reading input from a keyboard
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);
while((line = br.readLine()) != null)
{
  logger.info(line);
}
 
Reading from a keyboard is similar to reading from a data stream. Infact data reading is always in the form of stream.

//reading the int data stream from a binary file
import java.io.*;
import java.util.*;

public class BinOutputFileApp
{
  public static void main(String arg[])
  {
    try
    {
      FileInputStream fis = new FileInputStream("binary.dat");
      DataInputStream in = new DataInputStream(new BufferedInputStream(fis));
      int a = in.readInt();
      int b = in.readInt();
      System.out.println(a); //print int "42"
      System.out.println(b); //print int "45"
    }
    catch (IOException e)
    {
      e.printStackTrace();
    }
  }

Project example: reading_int_datastream.zipExample of the data in the binary.dat file:0x00 0x00 0x00 0x2A 0x00 0x00 0x00 0x2DActual int content represented in the binary file above:42 45

 

Other very good reference:- http://www3.ntu.edu.sg/home/ehchua/programming/java/J5b_IO.html (very good NTU website on data stream by Chua Hock Chuan),

Java Input & Output Stream (by Chua Hock Chuan).pdf

 

 

//Example of reading configuration from a property file
private void loadNetworkConfig()
{
    String filename = "/config.properties";
    InputStream is = getClass.getClassLoader().getResourceAsStream(filename);
    Properties myProperty = new Properties();

    try
    {
        myProperty.load(is);
        is.close();
    }
    catch (IOException ioe)
    {   //ensure that the file is in the classpath");
        logger.error("Error reading the properties file.");       
        System.exit(1);
    }

    String str;
    Int x;
    str = myProperty.getProperty("IP"null);
    x = myProperty.getProperty("PORT"null);
}


Note: There is another better generic methods to read *.properties. Read more about "Apache Common configuration". Commons Configuration provides a generic configuration interface which enables a Java application to read configuration data from a variety of sources. Commons Configuration provides typed access to single, and multi-valued configuration parameters.

//Various method of loading file/resources
//The java code should obtain the resource using getClassloader() as the standard
//loading file that is located in the directory as specified in the classpath
InputStream is = getClass.getClassLoader().getResourceAsStream("file.txt");

//same as above (another way of writing the code)
InputStream is = getClass.getResourceAsStream("/file.txt");

//loading file that is located in the same directory as the *class file
//looking for file in the current class package
InputStream is = getClass.getResourceAsStream("file.txt");


//inside the file config.properties
IP=192.168.1.1
PORT=1234





Get System or Environment variables  
String system_variable = System.getProperty("user.name");
//system_variable == "Administrator" 

//Enumerating through System Properties, prints out all the available keys & the corresponding values
Properties p = System.getProperties();
Enumeration e = p.propertyNames();
while (e.hasMoreElements())
{
  String key = (String)e.nextElement();
  System.out.prinln(key + " = " + p.getProperty(key));
}


The string user.name is the string key required to retrieve the system variables string. The following list present the other possible system variable that you can retrieve from System.getProperty(keyString);

Name String Example string result
"user.name" "Administrator"
"user.home" "C:\Documents and Settings\Administrator"
"user.dir" "E:\java projects\DslrCameraBonjour"
"os.name" "Windows XP"
"os.arch" "x86"
"os.version"  
"file.separator" "\"
"path.separator" ";"
"line.separator"  
"java.vendor" "Sun Microsystems Inc."
"java.runtime.name" "Java(TM) SE Runtime Environment"
"java.version" "1.6.0_18"
"java.home" "C:\Program Files\Java\jdk1.6.0_18\jre"
"java.library.path" "C:\Program Files\Java\jdk1.6.0..... . . . "
"java.vendor.url" "http://www.sun.com/"
"java.class.version" "45.3"
"java.class.path"  
"user.language" "en"
"java.vendor.url.bug" "http://java.sun.com/cgi-bin/bugreport..."
"file.encoding" "8859_1"
"user.timezone" "CST"

 

//Java code to get computer name, example "LSB-PC"
String computername = InetAddress.getLocalHost().getHostName();
 
 


Threading processes

//Threading example
public class myThreadClass extends Thread
{
  //flag to control process flow to be in syn with other critical function

  private static boolean fIsSynProcess=false;
  //object holding the reference to this thread

  private Thread thisThread = null;

  public myThreadClass()
  {
  }


  public void run()
  { //getting the thread process ID

    this.thisThread = Thread.currentThread();
    
String threadName = getClass().getName() + " : " this.thisThread.getName();
    
logger.info("...thread Started: " + threadName);

    
while((!isStopRequested()))
    
{
        
while((!isSynProcess())) 
        
{
        
}
    
}
    
logger.info("...thread Stopped: " + threadName);

  }

  private synchronized boolean isStopRequested()
  {
    if(thisThread==null)
      return(true);
    return(false);
  }
  
  public void requestStop()
  {
    Thread tempThread = thisThread;
    thisThread = null;
    //interrupt for used to exit from blocking function in the run() method's while loop

    if (tempThread != null)
      tempThread.interrupt();
  }

  private synchronized boolean isSynProcess()
  {
    return(fIsSynProcess);
  }

  private synchronized void holdThreadRun()    //prevent the run thread to terminate
  {
    fIsSynProcess=true;
  }

  private synchronized void releaseThreadRun()    //allow the run thread to terminate
  {
    fIsSynProcess=false;
  }
}

The coding examples on the left are the various style of using the Java threading features.


The thread example also illustrate the use of the keyword "synchronized". The java run time will ensure that those methods which are labelled as synchronized will not be excuted in parallel. This is to prevent two or more processes to access the same variable/memory which will cause data corruption or process locked issue. A program base on threading algorithm is likely to face such problems that can be resolved by implementing "synchronized".For more explaination on synchronized, please refer to the following,

http://download.oracle.com/javase/tutorial/essential/concurrency/syncmeth.html

//Spinning off a new Thread process without writing inside a proper class file
Thread rescan = new Thread(new Runnable()
{
    public void run()
    {
        //ToDo: Place your code that
        //you need to run as another simultaneous process.

    }
});


//Another method of writing thread
Object obj = new Object();
new Thread(obj).start();
Object class must contain a method run();

//Object class must implements Runnable and that contains a method run();


Thread rf_reader = new Thread(rfid_reader);
rf_reader.setDaemon(true);
rf_reader.setName("SmartIDReader task"); //Provide the thread with a threadName
rf_reader.start();

this.setDaemon(true); explains: setting daemon to true, will ensure that this thread is spin off from the main's method thread. When a program execute from main entry point, main itself is actually a thread. If daemon is set to true, the sub-thread spinoff will be under the main thread. When the main thread is terminated, all sub thread will be terminated, shutdownhook can also be activated. If daemon is set to false, the thread spin off as another separated thread by its own. When the main thread is terminated, the sub thread will still exists (with daemon set to false).



Java Destructor Method - ShutdownHook
//This example continue from the previous myThreadClass example.
//ShutdownHook is registered for the myThreadClass thread process.

//If the java program terminate abnormally, shutdownhook will be activated.
//Shutdownhook will activate the ThreadClassShutdownHook which will start a thread
//to stop myThreadClass's thread tc.requestStop().

 private ThreadClassShutdownHook tcShutdownHook = null; //add this to the thread class variable
tcShutdownHook = new ThreadClassShutdownHook(tc);      //add this to the thread class constructor
Similar to C++, the implementation of a ShutdownHook can be like writing a destructor for Java. It can help to ensure that for any abnormal program termination, you can get to clean up and close all the resources in used.

public class ThreadClassShutdownHook extends Thread
{
  protected static transient final Log logger = LogFactory.getLog(ThreadClassShutdownHook.class);

  private myThreadClass tc;
  
  public ThreadClassShutdownHook(myThreadClass tc)
  {
    this.tc = tc;
    logger.info(this.getClass().getName() + " created. ShutdownHook registered.");
    Runtime.getRuntime().addShutdownHook(this);
  }
  
  public void remove()
  {
    Runtime.getRuntime().removeShutdownHook(this);
  }
  
  public void run()
  {
    if(tc != null)    {
      logger.info("ShutdownHook activated for " this.getClass().getName()
      + 
". Thread: " + Thread.currentThread().getName());
      tc.requestStop();
    }
    else
    {
      logger.info("ShutdownHook safely release for " this.getClass().getName()
      + 
". Thread: " + Thread.currentThread().getName());
    }

  }
}

 

 

Import/Loading *.DLL to Java code (Dynamic Link Library)  
public class monitorController
{
  
//A native function in monitorController.dll
  
private native void triggerMonitor(int mode);

  
// ---------------- Load Library -----------------
  
// To load dll file
  
static
  
{
    
try
    
{
      
//get current directory
      
String getPath = System.getProperty("user.dir") + File.separator + "LIB" + File.separator;
      
System.load(getPath + "monitorController.dll");
      
logger.info("monitorContoller.dll loaded..");
    
}
    
catch(Exception ex)
    
{
      
logger.info("Exception while loading monitorController.dll: "+ex);
    
}
  
}
  
// ---------------- onMonitor () -----------------
  
// On Monitor
  
public void onMonitor()
  
{
    
triggerMonitor(1);
  
}
  
// ---------------- offMonitor () -----------------
  
// Off Monitor
  
public void offMonitor()
  
{
    
triggerMonitor(0);
  
}
}
The example shows the loading of *.dll library into a Java code. The example also shows the static initializer block, which is used to load the dll library.

 

Launching the default application by opening a file from Java  

//-----------------------------------------------------------------------------
//Using Desktop class to open file, so that the code will be OS platform independent
//The default application will launch automatically with the file.
//-----------------------------------------------------------------------------
//opening a file on the project root directory
Desktop.getDesktop().open(new File("image.gif"));
//opening a file relative to the project directory
Desktop.getDesktop().open(new File("imageDir\\image.gif"));
//opening a file using absolute file name
Desktop.getDesktop().open(new File("d:\\myproject\\imageDir\\image.gif"));
//opening a pdf file
Desktop.getDesktop().open(new File("d:\\mypdf.pdf"));


//-----------------------------------------------------------------------------
//Non platform independent code. (for Window OS)
//-----------------------------------------------------------------------------
//Open gif image file
Process p1 = Runtime.getRuntime().exec("rundll32 SHELL32.DLL,ShellExec_RunDLL " "d:\\myproject\\imageDir\\image.gif");
//Open pdf file
Process p2 = Runtime.getRuntime().exec("rundll32 url.dll,FileProtocolHandler d:\\mypdf.pdf");

 

 
Executing a *.exe program from the command prompt (command-line interpreter)  
        //Other examples
        
//executing the fing program from the command prompt
        
String cmd = "fing -n 192.168.234.0/24 -r 1 --session scanLog.txt -o table,csv,"+scanResultFileName;
       
        
logger.info("Fing is now scanning the network.");
        
try
        
{
            
Process p2 = Runtime.getRuntime().exec(cmd);
           
            
InputStream is = p2.getInputStream();
            
InputStreamReader isr = new InputStreamReader(is);
            
BufferedReader in = new BufferedReader(isr);
       
            
String str = "";
            
for(int x=0;str != null;x++)
            
{
                
str = in.readLine();
                
if(str==null)    //typically last line is a null. Do not add null string to the list
                    
continue;
                
else if(str.contains("Error"))
                    
logger.error("from Fing.exe: " + str);
                
//logger.debug("Line: " + x + "  \tStr: " + str);
            
}
        
}
        
catch(Exception e)
        
{
            
logger.error("Check if Fing software is installed.");
            
logger.error("Command line \""+ cmd +"\" read error.", e);
      
//halt 10 sec for user to read the error message.
            
try{Thread.sleep(5000);}catch(InterruptedException e1){}
            
System.exit(1);            //terminate the program
        
}
        
logger.info("Fing scanning is completed.");
 


Network TCP/IP communication example  
//how to get proper socket
InetAddress inetAddr = InetAddress.getByName("192.168.1.100");            //check proper internet address by InetAddress
int port = 80;
InetSocketAddress socketAddr = new InetSocketAddress(inetAddr, port);    //data object for socket information (ip:port)
InetAddress ip = socketAddr.getAddress();
int port = socketAddr.getPort();
logger.info("Opening Modem <" this.getClass().getSimpleName() "> at IP<" + ip + "> Port<" + port + ">");
sock = new Socket(ip, port);                    //opening a new socket connection
logger.info("Modem is ready.");

Reference:http://docstore.mik.ua/orelly/java-ent/dist/ch02_01.htm

 

InetAddress i = InetAddress.getLocalHost();  //get IP address of the local machine
 
//Retreive all the network interface available in the system (Ethernet, WiFi, 2nd Ethernet port, etc...)
try
{
  Enumeration<NetworkInterface> n = null;

  //get all the network interface available on the system
  n = NetworkInterface.getNetworkInterfaces();
  while(n.hasMoreElements())
  {
    NetworkInterface ni = n.nextElement();
    String ii = ni.getName();
    System.out.println(ii);    //print all the available network interface name
  }

  //get the network interface from the physical network interface "eth0"
  NetworkInterface ni2 = NetworkInterface.getByName("eth0");
  //get the InetAddress information from the network interface
  Enumeration<InetAddress> eni = ni2.getInetAddresses();
  InetAddress actual_IA=null;

  while(eni.hasMoreElements())
  {
    actual_IA = eni.nextElement();
    String ii = actual_IA.getHostAddress();
    System.out.println(ii);    //print all the IP address
  }

  //opening a network socket
  serverSocket = new ServerSocket(port, 0, actual_IA.getByName(actual_IA.getHostAddress()));
  System.out.println("new serverSocket:"+serverSocket.getLocalSocketAddress());
}
catch (UnknownHostException ex) {}
catch (SocketException ex) {}
catch (IOException ex) {}

 

//Opening TCP/IP server socket
ServerSocket s = null;
try
{
  try
  {
    thisThread = Thread.currentThread();
    String myName = thisThread.getName();
      s = new ServerSocket(getServerListeningPort());
      logger.info("HID RFID Server ...\"START\"...   , Thread: " + myName);
    while((isSynProcess()) || (!isStopRequested()))
    {
      try
      {
        HidRfidReader hid;
        Socket incoming = s.accept();
        hid = new HidRfidReader(incoming);
        hid.setDaemon(true)//set this as a user thread. If startService thread ended, these user thread will end as well.
        hid.start();
      }
      catch(UnAuthorisedDeviceException e)
      //ip address is not reconigze/registered. Print debug message and return to main loop to accept incoming socket connection
        logger.warn("Warning!!! <Unauthorised Access Detected> " + e);
        //detects authorised device access
        //return to check for other incoming connection
      }
    }
  }
  catch(Exception e)
  {
    logger.error("Unhandled Error: " + e, e);
  }
  finally
  {
    s.close();
  }
}
catch(IOException e)
{
  e.printStackTrace();
}
logger.info("HID RFID Server   ...\"STOP\"...");

 
//handling incoming client connection
    thisThread = Thread.currentThread();
    String myName = thisThread.getName();
    logger.info("Door connected    " + getObjectInfo()
            "  ...STARTED thread: " + myName);

    // register shutdownhook for this object
    tcShutdownHook = new HidRfidReaderShutdownHook(this);

    try {
        int byteRead = 0;
        int previousByteRead = 0;
        StringBuffer data = new StringBuffer();
        int testConnectionTimer = 10000// period interval in msec to test the connection
        byte[] checkAlive = new byte[] { '\000' }// byte to test alive

        in = incoming.getInputStream();
        out = incoming.getOutputStream();
        // incoming.setKeepAlive(true);

        // send command to get the current security restrict mode
        byte[] getSecurityMode = new byte[] { '\003', 'G''S''\r''\n' };
        out.write(getSecurityMode)// send the command to get the security mode. The master controller device will reply with the current security restriction mode

        int timeElapse = 0;
        int timeElapseWithoutData = 0;

        while ((isSynProcess()) || (!isStopRequested())) {
            if (in.available() != 0// if data is available to be read. use available() to avoid using read() which is blocking.
            // using blocking mode with timeout exception will work on incoming stream but is will affect the outgoing socket timeout too.
                previousByteRead = byteRead; // therefore use available() is the proper way.
                byteRead = in.read()// in.read() is a blocking function
                timeElapseWithoutData = 0// reset counting the duration since the last incoming byte

                if (byteRead == 0x00// searching for byte sequence 0x6E 0x00
                {
                    if (previousByteRead == 0x6E) {
                        // 2009-11-10 Strange issue detected. The HID RFID reader RW400 kept sending 0x6E 0x00 from each
                        // reader every 13 secs. This issue is not previously seen, therefore I
                        // guess there might be some data command that might have trigger it to happen.
                        // Setting the RW400 device to activate such a data ping.
                        // 2009-11-10 Email from asiasupport@hidcorp.com the 0x6E 0x00 is a reply response from the RW400
                        // device indicating an invalid command is sent to the RW400 device.
                        data.deleteCharAt(data.length() 1);
                        logger.debug("caught data code 0x6E 0x00"
                                ", from " + getObjectInfo());
                    }
                else
                    data.append((charbyteRead)// must cast char else the int will be converted to ascii
            else {
                try {
                    Thread.sleep(getDelayTimeElapse());
                catch (InterruptedException e) {
                }
                timeElapseWithoutData++; // count the time elapsed
                timeElapse++;

                int dataLen = data.length();
                if (dataLen > 0// if there is incoming data
                {
                    if (timeElapseWithoutData >= getMinimumTimeElapseLap())// if time is up
                    {
                        logger.debug("processing incoming data length: " + dataLen + " \"" + byte2AsciiHex(data.toString()true"\"");
                        processData(data);
                        data.delete(0, data.length());
                    }
                }
            }
            // issue: When the client connection drop, the client will attempt to reconnect
            // This results in a multiple thread opened, while the old one is not closed.
            // Server is not aware that the connection has been closed.
            // By sending a test byte over, when the server cannot reaches the connection,
            // it will throw out the SocketException resulting in termination of the current thread.
            if ((timeElapse % (testConnectionTimer / getDelayTimeElapse())) == 0// try detecting the connection once in a while
            {
                // logger.debug("         alive -> " + getObjectInfo());
                out.write(checkAlive);
            }
        }
        // no more incoming data, stop receiving
        incoming.close()// close socket for that particular incoming thread
    catch (SocketException e) {
        logger.error("Lost contact with the client door. "
                + getObjectInfo(), e);
    catch (Exception e) {
        e.printStackTrace();
        logger.error("Exception in " + myName + " " + e, e);
    finally {
        try {
            incoming.close()// close network socket
        catch (IOException e) {
        }
    }
    logger.info("Door disconnected " + getObjectInfo()
            "  ......STOP thread: " + myName);
 


Network UDP communication example (datagram packet listening)  
//UDP example, from EIB/KNX communication program
thisThread = Thread.currentThread();
String thisName = thisThread.getName();

logger.debug("-> started...   " "knxData listener Thread: " + thisName);

byte data[]new byte[100];    //allocate a larger buffer for receiving packet
DatagramPacket packet = new DatagramPacket(data, data.length, getRemoteIp(), getRemotePort());

int timeOut=100;
int debugCounter=0;
int debugAliveCount=(60*1000)/timeOut;

try
{
  udp.setSoTimeout(timeOut);

  while(!isStopRequested())    //while NOT end of transmission, which is terminate by the server side.
  {
    try
    {
      udp.receive(packet);
      debugCounter=0;
      if (logger.isDebugEnabled())
        logger.debug(StringUtil.padLeft("<- KnxDataComms packet received..."35+ HexUtilities.print2Str(packet));
      
      decodePacket(packet);  //Please do not shift this code. Device immediate reply acknowledgement upon receiving data
                  //Ack reply too slow will result in the remote device trying to close the session
                  //thinking that there is a problem in this local computer.
    }
    catch(SocketTimeoutException e)
    {
      //timeout occur
      //do nothing. Just to unblock the receive function blocking mode
      //logger.debug("-> SocketTimeoutException" + getClass());
      debugCounter++;
      if((debugCounter%debugAliveCount)==0) {
        logger.debug("KnxDataComms thread is still alive.");            
      }
    }
  }
}
catch(ClosedByInterruptException e)
{
  logger.error("-> ClosedByInterruptException: " + e.getMessage(), e);
}
catch(IOException e)
{
  logger.error("-> IOException: " + e.getMessage(), e);
}
catch(KnxCommException e)
{
  logger.error("-> KnxCommException: " + e.getMessage(), e);
}
catch(SecurityException e)
{
  //requestStop() invoked Thread.interrupt()
  logger.error("-> SecurityException: " + e.getMessage(), e);
}
catch(Exception e)
{
  logger.error("-> General exception:: " + e.getMessage(), e);
}
finally
{  
    udp.close();
  requestStop();      //internal generated exception. Need to update requestStop variables to allow non thread function to terminate too.
  logger.error("-> stopped...   " "knxData listener Thread: " + thisName);
}
 

byte[] data = LantronixDevice.queryFirmwareVer;
DatagramPacket packet = new DatagramPacket(data, data.length, bc, LantronixDevice.UDP_PORT);
DatagramSocket socket = null;

try
{
socket = new DatagramSocket();
//socket = new DatagramSocket(PORT, IP_ADDRESS); //only for communication to a particaular remote IP & PORT
//socket.setBroadcast(true);
socket.setSoTimeout(timeoutSearch);
socket.send(packet);
}
catch(SocketException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
catch(IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}

UDP is a connectionless communication protocol and does not handle the integrity of the data being send. This does not mean that it cannot be implemented for communication that requires 100% error free communication. It simply means that the lower level protocol will not help you ensure that all your data bytes are being send over, and that your application will need to handle those error checking if you need it.

There are various way to setup your UDP communicates. Two methods are breifly state for your awareness.

- socket define wihtin DatagramSocket

- socket define within DatagramPacket.

For UDP communication to and only to one IP addressed device, you should define your socket in the object DatagramSocket. For packet communication with multiple UDP devices or acting as a listener, you can define your socket within the DatagramPacket object; there will be no restriction to which devices you can communicate within the network. UDP protocol is very flexible to implement.

 

Accessing mySQL using Java:
     When writing programs, there will be time we need to store data permanently. Usually writing data to files would be sufficient. When the data is becoming more and more complex, storing them in database might starts to make sense. SQL provides a standardize data access interface without having your program to manage the complexity of searching and storing the data.For this example, I am using the free database mySQL.

mySQL Software installation setup and library
------------------------------------------------

1) download and install the following software
     SQL1- mysql-essential-5.1.50-win32 (SQL database)
     SQL2- dotNetFx35setup (required for "mysql-workbench" software)
     SQL3- mysql-workbench-gpl-5.2.26-win32 (gui for mySQL)
     SQL4- mysql-connector-java-5.1.13 (sql interface/jar lib for java)
2)import "mysql-connector-java-5.1.13-bin.jar" to your java project
3) use the TestSql example to connect to sql database.


SQL connection pool:
     Why using a SQL connection pool to manage sql database connection. Opening & closing SQL connection takes quite a significant time delay. In order to reduce this delay (especially for high traffic applications), this class object will managed a limited pool of opened connection. When the application request for a SQL connection, this connection pool class will borrow the connection to the requester. When the requester wanted to close the connection, the pool class will retreive it back without actually closing the SQL connection. The pool will manage the SQL connection to provide a faster database access.

SQL connection pool (java library required for SQL connection pool)

------------------------------------------------
4) download the following jar libraries
      SQL5- commons-dbcp-1.4.jar
      SQL6- commons-pool-1.5.4.jar
5) import them to the java project for implementing the sql connection pool

Click here for SQL example


 

Command Pattern: ExecutorServiceexample: ExecutorService_Queue.java, ExecutorService_QueueJob.java Command Pattern: Observerexample1: Observer command pattern.pdfexample2: Observer pattern - Wikipedia, the free encyclopedia.pdfexample3: JavaWorld - October - How-to Java_ Observer and Observable.pdf

 

As you write more and more programs, you will realise the efficiency of re-using the codes. We call them functions. When we write more and more functions, we will realised that more codes can be consolidated; many codes are repeated. Then came the object oriented programming concept. Even when we apply object orientated programming, we can still see similar codes pattern or structure reoccurring. This calls for command pattern. It is a well design coding structures that helps programmer to simplfy commonly use, complex algorithm. When programming complex structure, think about the existing command patterns solutions. Knowing how to apply them can save you days of proramming headache. Many frequently used and efficient algorithms were already being thought of and were simplfied for us for implementation. Study the command patterns, simplfies to keep your coding short and neat. This is the true art of programming.

read log4j ndc (log the individual instance of client thread connected to the server)

Design pattern reference:

- java-design-patterns.pdf


My Java Library

 

 

This utilities.zip contains my frequent/common used Java library, which contains the follow object- HexUtilities.java- ShutdownHook.java, ShutdownHookClass.java

- UtilitiesThread.java

utilities.ziputilities.jar

//example for using the ShutdownHook class 
public class DataComms implements ShutdownHookClass
{
protected static transient final Log logger = LogFactory.getLog(DataComms.class);

private Socket sock = null//network connection socket reference for this object
DataCommsRx dcr = null//object for receiving data handling

ShutdownHook sdh = null//for shutdownhook

protected DataComms(InetSocketAddress socketAddrthrows IOException
{
InetAddress ip = socketAddr.getAddress();
int port = socketAddr.getPort();
logger.info("Opening socket connection at IP<" + ip + "> Port<" + port + ">");
sock = new Socket(ip, port)//opening a new socket connection

//registering shutdown hook for this connection object
sdh = new ShutdownHook(this)//add this to the thread class constructor
}
 
KNX EIB communication for home automation server KNX source code
TjLink TCP/IP communication for network Audio Video AV equipment (AV receiver, Projector) TjLink source code example.
HID RFID door access security program HID RFID source code
Server service to control all computers to wakeup or sleep Wake&Sleep
SMS webservice server SMS server
UDP communication with Xport, MatchPort Java UDP client for XPort




--------------------------




GUI & Event Listener example
- Create window
- Window listener
- Mouse listener
- Keyboard listener


- example interface, inherirt, abstract (pc, network projector project)

- http://www.javamex.com/tutorials/threads/invokelater.shtml
any swing component codes that requires periodically refresh need to apply this invoke function.
http://www3.ntu.edu.sg/home/ehchua/programming/java/J5e_multithreading.html


GUI programming notes:
- GUI programming in java.pdf
- Writing gui applications in java.pdf

int keyChar = evt.getKeyChar();
String debugStr = String.format("%1x", keyChar);
JOptionPane.showMessageDialog(null, debugStr, "Debug", JOptionPane.INFORMATION_MESSAGE);

Create a message dialog box that helps to debug data in hex code.
 

example to load image file to JPanel.
- example- LoadAndShow (example to load image)

 

 

Java Applet  

Inserting applet into html file, where MyApplet.class is the java class to invoke, basecode "./" is the root directory the MyApplet.class is located.
<applet code="MyApplet.class" codebase="./" height="600" width="600"></applet>

Without the *.class will also works
<applet code="MyApplet" codebase="./" height="600" width="600"></applet>

If your MyApplet.class is located in the directory /appDir
html file location -> /index.html
apps file location -> /appDir/MyApplet.class
<applet code="MyApplet.class" codebase="./appDir" height="600" width="600"></applet>

If the *.class to invoke is located inside a *.jar library archive file
<applet code=MyApplet.class archive="JarFileName.jar" codebase="./" width=width height=height> </applet>

 

How to signed a Java Applet for access to communication outside the server the applet reside on?

 

 

 

Applet

- Do not put the main Applet class in a package
- Do not do much coding in the Applet's constructor, other than GUI initialisation. Codes should be place out of the constructor.

Problem:
- Applet hangs in the browser. Need to close the broswer and terminate the browser process to shutdown/restart the Java VM
Solution:
- Applet must use a thread to open new process, especially time consuming process. GUI programming has to be very much thread base.

Problem:
- The applet is able to send out UDP packet from Eclipse applet but not the same applet on the browser.
The browser is able to use the same UDP port to sent data out, but the applet using the same port cannot send the data out.
Solution:
- Remember the applet restrictions that unsigned applets may only access the host they were loaded from, for security purpose. To overcome this security restriction, you will need to signed the applet.

Browser test for Java Applet,
- http://www.javatester.org/enabled.html

Note for Java applet,
- Defining and Using Applet Parameters.pdf
- Call a Applet Java method from Javascript.pdf
- Call Javascript from a Java applet.pdf
- Signed Applet Tutorial.pdf

Note for Java Jar file,
- JAR files revealed.pdf





These formatted java source codes are generated by java2html_50.zip