Java, commonly used coding examples

(Java Coding Example)

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

email:    contact->email_siongboon  

website: http://www.siongboon.com

Content Summary
#JavaPrimitiveDataTypes
#JavaLanguageReferences
#JavaFundamentalReferences
#ByteManipulation
#IntegerStringManipulation
#StringManipulation
#Javastructuretogetthesingleinstanceofanobjectsingleton
#TimeDateCalendarTimer
#ArrayDataContainer
#Javadebuggingexceptionanderrorhandlingresources
#FileIOPropertiesConfigurationfile
#GetSystemorEnvironmentvariables
#Threadingprocesses
#JavaDestructorMethodShutdownHook
#ImportLoadingDLLtoJavacodeDynamicLinkLibrary
#LaunchingthedefaultapplicationbyopeningafilefromJava
#Executingaexeprogramfromthecommandpromptcommandlineinterpreter
#NetworkTCPIPcommunicationexample
#NetworkUDPcommunicationexampledatagrampacketlistening
#Multimedia
#JavaandSQL
#JavaCommandPattern
#JavaGUIProgramming
#JavaApplet
#JNIJavaNativeInterface
#MyJavaLibrary

 

Open Jar2Html.jar program.

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
\0 0x00 null char

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.";

regex example

String str = "This is a sentence. This is a question, right? Yes! It is.";
String delims = "[ .,?!]+";
String[] tokens = str.split(delims);

String str[] = result.split("HWaddr | \\. |inet addr:| \\. |Bcast:| \\. |Mask:| \\. |UP", 6);
This splits the following chunck of text into

eth0 Link encap:Ethernet HWaddr b8:27:eb:87:9e:02
inet addr:192.168.1.97 Bcast:192.168.1.255 Mask:255.255.255.0
UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1
RX packets:4670 errors:0 dropped:0 overruns:0 frame:0
TX packets:2034 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:1000
RX bytes:526428 (514.0 KiB) TX bytes:257010 (250.9 KiB)

str[0] -> eth0 Link encap:Ethernet
str[1] -> b8:27:eb:87:9e:02
str[2] -> 192.168.1.97
str[3] -> 192.168.1.255
str[4] -> 255.255.255.0
str[5] -> BROADCAST RUNNING MULTICAST MTU:1500 Metric:1
RX packets:4599 errors:0 dropped:0 overruns:0 frame:0
TX packets:1960 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:1000
RX bytes:522426 (510.1 KiB) TX bytes:249420 (243.5 KiB)

 



Java Fundamental References

package sg.com.siongboon.mypackage; //Basic java class structure. Using a domain name as your package, ensures that it will likely to be a unique namespace.

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
  }

  protected void finalize()
  //method gets called when it is about to be delete by the garbage collector.
    //Should not be use as it is imposible to know when the object will get deletes.
  }

  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?

 

//defining a common interface for objects
public interface LiftButton
{
  //define all the methods/interface in the class
  public void openLiftDoor();
  public void closeLiftDoor();
  public void pressLiftFloor(int floorLevel);
  public void alarm();
}

//Interface can extends/inherit many other interfaces.
//This is unlike abstract where only one class can be extend.
public interface LiftButton extends otherInterface, otherInterface2, otherInterface3
{
  //define all the methods/interface in the class
  public void openLiftDoor();
  public void closeLiftDoor();
  public void pressLiftFloor(int floorLevel);
  public void alarm();
}


//Object class implementing the interface. A class can implement many interface.
public class Lift implement LiftButton
{
}

Very often in our physical world, we share a common interface with many different type or brand of system.

Example is our elevator lift. The interface buttons are the same/similar in each brand of lift. The user need not require training in order to use the lift, because the operating procedure is the same as what the user has used before.

The same goes for our computer system. Each computer may be run by various brand/model of CPU/hardware/OS, but the keyboard/mouse interface remains the same.

Defining an interface helps us to define a common standard, such that when it comes a day where we need to swap an object (change CPU model), we can easily change it with minimal or without any effect on the system.

It is mentioned by Jim Waldo, in his book "Java The Good Parts", that passing parameters through the method is evetually going to be of some sort of interface. You can pass parameters using object, but later down the road, there is a high chance that it will be later change to an interface as the coding grows comre sophisticated.

//defining an abstract class. Methods that do not has a body/codes will have to be abstract.
//Abstract methods are like interfaces.

public abstract class LiftButton
{
  abstract public void openLiftDoor();
 
abstract public void closeLiftDoor();
  //if any method is abstract, the class must be an abstract.

  public void pressLiftFloor(int floorLevel)
  {
    //codes that will be shared among those classes who inherit this abstract class.
  }
  public void alarm();
}

//An object class can only inherit/extends one abstract class.
public class MetalLiftButton extends LiftButton
{
}


When to use abstract class and when to use interface?

Use abstract clases and inheritance if you can make the statement "A is a B".
Use interfaces if you can make the statement "A is capable of [doing] as", or also, abstract for what a class is, interface for what a class can do.
For example, we can say a triangle is a polygon but it makes no sense to say a triangle is capable of being a polygon.
The design class could be a combination of abstract and interface. You will need to sort out the methods and variable belonging to the abstract class, and those who belongs to the interface.

Consider using abstract classes if any of these statements apply to your situation.
1) You have a common denominator codes that you want to share among several closely related classes (in a hierarchy). Share state or functionality.
2) Many classes that extend your abstract class have many common methods or variable, or you need to hide (private) from those classes
3) ???You want to declare non-static or non-final fields. This enables you to define methods that can access and modify the state of the object to which they belong.

Consider using interfaces if any of these statements apply to your situation.
1) You expect that unrelated classes would implement your interface.
2) You want to specify the behavior of a particular data type, but not concerned about who implements its behavior.
3) You want to take advantage of multiple inheritance of type.

   
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;

//'l' indicates that 10000000000 is of data type long rather than a int .
//(any literal is intepreted as a int and not a long )
int x = 15 ;  
long x = 10000000000l;


//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

String dataStr = new String(dataByte,"ISO-8859-1");
//converting back to byte array after String manipulation

byte[] dataByte = dataStr.getBytes("ISO-8859-1"));

//Earlier method. (ineffective)
//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.
//In some case, a char 0xC2 may be inserted before a char which is > 0x7F.
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);


for information about charset encoding.

http://www.anyang-window.com.cn/tag/java-encoding/page/3/

 

byte[] dataByte = new byte[]{(byte) 0x01, (byte) 0xA1};
ByteBuffer wrapped = ByteBuffer.wrap(dataByte)// convert 0x01A1 to 417
short num = wrapped.getShort();                 // integer result = 417

byte[] dataByte = new byte[]{(byte) 0xD1, (byte) 0xA1};
ByteBuffer wrapped = ByteBuffer.wrap(dataByte)// convert 0xD1A1 to -11871
short num = wrapped.getShort();                 //
integer result = -11871
Convert 2 bytes array to integer
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 Manipulation  
String str = "Hello";             //correct proper way
String str = new String("Hello"); //creating unneccessary String object again. Waste CPU process.

//inserting octal or hex char into a string
String string = "hello\r\n"
String octal_String = "\150\145\154\154\157\015\012";      //same as "hello\r\n" 
String hex_String = "\u0068\u0065\u006c\u006c\u006f\r\n";    //same as "hello\r\n" (\u000d\u000a don't work) 


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("\\|");


s = s.replaceAll("\\s","");      //remove invisible \r \n char
s = s.trim();                    //remove white space

Removing invisible \r \n char and white space.
//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"

String formatter
Leading or padded zero
https://docs.oracle.com/javase/7/docs/api/java/util/Formatter.html
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"

//rounding off float double value to 2 decimal place
float unround = (float0.34456;
double roundOff = Math.round(unround*100)/100D;    //rounding off to 2 decimal place
logger.info((float)roundOff);                      //result = 0.34
    
float unround = (float0.34556;
double roundOff = Math.round(unround*100)/100D;    //rounding off to 2 decimal place
logger.info((float)roundOff);               

//convert a float or double to a more precision BigDecimal
BigDecimal precision = new BigDecimal(0.34556);    //try not to use a double or float converting to a BigDecimal. It will result in additional trailing numbers because floating number is never exact. Use String instead to be accurate.
BigDecimal precision2 = new BigDecimal("0.34556");

precision = precision.setScale(2, BigDecimal.ROUND_HALF_UP)//setup BigDecimal to 2 decimal place, and round up.

precision = precision.setScale(2, BigDecimal.ROUND_HALF_EVEN);//Banker's Rounding (rounding to the even if number is in the middle 0.5 or 0.05, etc...)
//example: 0.1265 (3 decimal place) should be round to 0.126
//example: 0.12651 (3 decimal place) should be round to 0.127
//example: 0.1275 (3 decimal place) should be round to 0.128
//example: 0.1285 (3 decimal place) should be round to 0.128

//division, it is always better to specify the precision. Example, 1/3 will result in 0.333... to infinity, which will throw you an exception.
//-> java.lang.ArithmeticException: Non-terminating decimal expansion; no exact representable decimal result.
MathContext mc = new MathContext(32, RoundingMode.HALF_UP)
BigDecimal c = a.divide(b, mc);    //set the division result to 32 decimal place at most.
BigDecimal c = a.divide(b, MathContext.DECIMAL32);   //same


Right align a 2 decimal place floating number.

If encounter floating point error while using a variable of float data type, try changing to the data type double or use int data type instead. If precision is absolutely necessary, use the object BigDecimal.

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 final String name;

  private BonjourService(String name)
  {
    this.name = name;
  }

  public String toString()
  {
    return name;
  }
}

//Iterating through each element in the enum
for(BonjourService d: BonjourService.values())
{
  System.out.println(d);
}

//Get the literal string of the enum
String name =
BonjourService.CAMERA.name();

//Get the enum from a string
BonjourService bonjourServiceEnum = BonjourService.valueOf("CAMERA");

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.
Enum constants can be iterated, which allows you to write codes to scan through the enum defined.
public enum SerialBaudrate
{
    BPS_9600(9600), BPS_19200(19200), BPS_14400(14400);

    private SerialBaudrate(int i)
    {
      this.i = i;
    }
    
    private final int i;
    public int Id()
    {
      return i;
    }
    
    //converting number to a definite enum object
    static public SerialBaudrate getBaudrate(int baud)
    {
      if(baud == SerialBaudrate.BPS_9600.Id())
        return(SerialBaudrate.BPS_9600);
      else if(baud == SerialBaudrate.BPS_19200.Id())
        return(SerialBaudrate.BPS_19200);
      else if(baud == SerialBaudrate.BPS_14400.Id())
        return(SerialBaudrate.BPS_14400);
      else
        return(null);
    }
}
implementing a static method for use to convert the old int convention to enum type object.

Toolkit.getDefaultToolkit().beep(); //error beep tone (sound, bell)

A beep sound from your system buzzer/bell.
Object obj;
obj  = 
null;
Java has a garbage collector mechanism, which ease programmer having to allocate and de-allocate memory like as in C and C++ language. That does not means that your Java program will not have anymemory leak issue, neither does it means that you need not have to manage memory. Any memory reference (object's reference) that still exits in your run time memory will make your garbage collector thinks that the memory allocated is still in use. If you keep on creating such objects, and happen to leave its reference in memory somewhere in your program, the memory resources will run out sooner or later. One way to ensure that the object is no longer in use is to put a null to your object's reference if you no longer use it. Removing the link to the object reference indicates to the garbage collector that the object is no longer in use. The gabage collector will release the memory resource on its own some time later.
long heapsize=Runtime.getRuntime().totalMemory();
long freesize=Runtime.getRuntime().freeMemory();
long maxsize=Runtime.getRuntime().maxMemory();
Checking the heap size of the java. This can helps detect
Error can occur is there is not enough heap space "java.lang.OutOfMemoryError: Java heap space". There are profiler (JProfiler) and heap dump analysis software (Eclipse MAT tool) which can help analyse the use of memory and detect memory leak issue.
Can also use "jconsole" provided under JDK/bin directory. It will give you a view of the memory usage, thread count, classes loaded, etc.

 

Java structure to get the single instance of an object (singleton)  
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

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

  private static Manager mgr = null;

  public static Manager getInstance()
  //object can only create once. constructor method is private
    if(mgr == null)
      mgr = new Manager();
    return(mgr);
  }

  private Manager()
  {
  }

  public static void main(String[] args)
  {
  }
}
Quick template for singleton structure.
Please refer to some explaination in the following.
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.
    }
}

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;


Instant timestamp = Instant.now();	//newer form of Timestamp method. (Java 8)
LocalDateTime timestamp2; //
LocalDate date; //immutable object. Cannot be changed once it is created (Java 8)
LocalTime time; //immutable object. Cannot be changed once it is created (Java 8)

LocalDate date = LocalDate.now();
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy MM dd");//formatter
String text = date.format(formatter); //format date
LocalDate parsedDate = LocalDate.parse(text, formatter); //parse date

//Timestamp string, output string "2010-03-08 14:59:30.252"
java.util.Date date= new java.util.Date();
logger.info(new Timestamp(date.getTime()));

Java 8 timestamp formatting, https://docs.oracle.com/javase/8/docs/api/java/time/format/DateTimeFormatter.html

//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());               //Format string for date, time
String time = sdf2.format(cal.getTime());

DateFormat df = new SimpleDateFormat("yyyy-mm-dd");
Date dataObj = df.parse("2014-02-25");                 //Parse string for date, time



//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());
}

ArrayList provides insertion order. Insertion order means that is an object is inserted (added) first to the list, it will show first in the iteration process.
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());
}

HashMap do not provide insertion order.
If unqiue key (ensure no duplication) and insertion order is needed, use LinkedHashMap collection.


Map do not allow object duplication in the key, but allow duplication in the value.
Set do not allow object duplication, ensure insertion order.
List allow duplication, ensure insertion order.
Collection
Maintain Insertion Order
Allow Duplication
Comments
ArrayList
Yes
Yes

HashMap
No
No (for Key), Yes (for Values)

LinkedHashMap Yes
No (for Key), Yes (for Values)
LinkedHashSet
Yes
No

TreeMap


Maintain order (for key). Data sorting feature. Object to be compared has to implement "Comparable"
Hashtable


is synchronized, in contrast to HashMap.

//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.
String a = "string1";
String b = "string2";
String c = "string3";

ArrayList<String> list = new ArrayList<String>();
list.add(a);
list.add(b);
list.add(c);

//another short form of iterating the list
for (String temp : list)
{
  logger.info(temp);    //print out the list
}

//to delete an element in the list, use iterator object instead of the arraylist
Iterator<String> itr = list.iterator();
while(itr.hasNext())
{
    
String temp = itr.next();
    itr.remove();
    //list.remove(temp) will result in java.util.ConcurrentModificationException error
    //list object should not be access during the iteration process.
}




Java debugging, exception and error handling resources

New log4j2
Library Jar file needed for log4j2
- log4j-api-2.6.1.jar
- log4j-core-2.6.1.jar
- log4j-jcl-2.6.1.jar (for common logger use)
- log4j2.xml

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


***new changes to org.apache.log4j.DailyRollingFileAppender
log4j.appender.WeightSensorLog.DatePattern='.'yyyy-MM-dd-a

//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(ClassName.class);

logger.error("");
if(logger.isDebugEnabled())
    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() + ">");
logger.info("Method name:<" + Thread.currentThread().getStackTrace()[1].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.

//A method to log seperately to two log file from a class
protected static transient final Log logger = LogFactory.getLog(ClassName.class);
protected static transient final Log loggerSpecial = LogFactory.getLog("LogAppenderName");
logger.info("Usual logging to the appender");
logger.infoSpecial("This log will be pushed to the appender name (LogAppenderName).");
How is the log4j.properties file looks like. The appender name can be anything. In this example, it is "LogAppenderName".

log4j.logger.LogAppenderName=INFO,OrderLog
log4j.additivity.OrderServer=false
log4j.appender.OrderLog = org.apache.log4j.DailyRollingFileAppender
log4j.appender.OrderLog.File=${log.dir}/1-Order/Order

//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
    {
        //"finally" section will be executed with or without exception occurred.
        //Contain codes that has to be executed even 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.
    }
}
Must read.
Top 20 Java Exception Handling Best Practices
http://howtodoinjava.com/best-practices/java-exception-handling-best-practices/#1
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();
}

//Example 2 writing to file
String content = "ABCD\n" + "EFG";
File file = new File("resource/");
try
{
    Files.write(file.toPath(), content.getBytes());
}
catch(IOException e)
{
    // TODO Auto-generated catch block
    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 )
{
}

Very often to specify a file path using a string, we need to use double slashes instead of only one in Java string.

C:\\Users\\Harald\\Folder1\\Version1\\Folder2.

This is because a slash '\' is a escape char in a string. In order to indicate a '\' intention, we need to put 2 slashes. This means that it will be quite odd to a typical computer user as we usually uses only one slash.

One method is to use back slash instead of forward slash. The file object classes will automatically treat '/' back slash as the normal '\' slash in Window OS.

Old was of specifiying the path,

processDirectory="D:\\doc\\Expenses Invoice"

A solution of specifying the path,

processDirectory="D:/doc/Expenses Invoice"

This solution, means that the user need not specify double slash, which can be quite confusing.

Path fileToMovePath = f.toPath();
Path targetPath = sentFolder.toPath();                         
try
{
    Files.move(fileToMovePath, targetPath.resolve(fileToMovePath.getFileName()));
    logger.info("move file<" + f.getName() "> to \"" + sentFolder + "\"");                   
}
catch(IOException e)
{
    logger.error("fails to move file<" + f.getName() "> to \"" + sentFolder + "\"");                   
    e.printStackTrace();
}
(new Java7, 2016-05-31) copy file, move file.
Filename manipulation using Path.
Change folder name while the file name remains.

import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;

File file;
Path source = file.toPath();
file = source.resolveSibling("newFilename").toFile();

Rename a file name without changing the directory. (change file name)
Path source = Paths.get("from/path");
Path newdir = Paths.get("to/path");
Files.move(source, newdir.resolve(source.getFileName()),
StandardCopyOption.REPLACE_EXISTING);
Files.copy(source, newdir.resolve(source.getFileName()), StandardCopyOptionREPLACE_EXISTING);
Change the directory path without changing the file name. (change directory path)
file move
file copy
File dir = new File("dir1/dir2/dir3/abc.txt");
logger.info(dir.getParent());                           //get the File's directory and prints out "dir1/dir2/dir3"
logger.info(dir.getParent()+File.separator);    //prints out path appended with the seperator "dir1/dir2/dir3/"
logger.info(File.pathSeparator);                     //prints out pathSeparator ";"
Get File directory. Get directory.
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

public class Test implements Serializable
{
  //A static ID number to identify this object
  private static final long serialVersionUID = 1L;
  
  private int a;
  private int b;

  public Test(int a, int b)
  {
    this.a = a;
    this.b = b;
  }
  
  public void print()
  {
    System.out.print("data a=" + a + ", b=" + b);
  }
  
  public static void main(String args[])
  //entry point for running this program
    System.out.print("File read/write file location.\n");
    
    String fileName = "myObjFile.abc";
    String fileRoot = System.getProperty("user.dir");
    String fileDir = File.separator + "logFile" + File.separator;
    System.out.print("user.dir= \"" + fileRoot + "\"\n");
    File f = new File(fileRoot + fileDir + fileName);
    
    Test t = new Test(12);
    
    try
    {
      if(!f.exists())
      {
        System.out.print("File not found." "\n");
        try
        {
          //creting a new file
          f.createNewFile();
        }
        catch(IOException e)
        {
          //path directory not found
          System.out.print("Path not found, path= \"" + fileRoot + fileDir + "\"\n");
          System.out.print("Create new path, path= \"" + fileRoot + fileDir + "\"\n");
          f.getParentFile().mkdir();
          f.createNewFile();  //create the file again
        }
        System.out.print("Created a new file \"" + f.getName() "\"\n");
      }
      else
      {
        System.out.print("File exist. file=" + f.getAbsolutePath() "\n");
      }
      
      //write the object to a file
      //can also be use to find out the path that the file will be read
      ObjectOutputStream writeOut = new ObjectOutputStream(new FileOutputStream(f));
      writeOut.writeObject(t);
      
      //read the object back from the file.
      ObjectInputStream readIn = new ObjectInputStream(new FileInputStream(f));
      Test x = (TestreadIn.readObject();
      x.print();
    }
    catch(FileNotFoundException e)
    {
      // TODO Auto-generated catch block      
      e.printStackTrace();
    }
    catch(ClassNotFoundException e)
    {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
    catch(IOException e)
    {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }
}

Writing an class object into a file, and reading the class obj back from the file. This acts as a means to permanently save the state or values store in the object that you have created.

There are also codes written to generate files, so that you can detect where your config files are stored in the user or project directory.



//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.

Check out below (WatchService class) for newer methods of monitoring files and directory.

Detect file modification.pdf  
  protected void runProcess()
  {
    //setup for monitoring the file change
    WatchService watchService = null;
    Path monPath = null;
    try
    {
      monPath = skyXFile.getParent();    //extract the directory containing the file
      watchService = FileSystems.getDefault().newWatchService();
      monPath.register(watchService, StandardWatchEventKinds.ENTRY_MODIFY, StandardWatchEventKinds.ENTRY_CREATE);
    }
    catch(IOException e)
    {
      logger.error("Error setting up file watch service.", e);
    }
    
    logger.info("start monitoring the directory: \"" + monPath.toString() "\"");

    //monitoring file change
    while((!isStopRequested()))
    {
      synProcess()//thread will be blocked here if there is a request to hold the thread.

      try
      {
        key = watchService.take();    //blocking function waiting for file change
      }
      catch(InterruptedException e)
      {
        logger.error("Error in file watch service.", e);
      }  
      
      //get list of events for the watch key
      for(WatchEvent<?> watchEvent:key.pollEvents())
      {

        //get the filename for the event
        @SuppressWarnings("unchecked")
        final WatchEvent<Path> ev = (WatchEvent<Path>watchEvent;
        final Path filename = ev.context();

        //get the kind of event (create, modify, delete)
        final Kind<?> kind = watchEvent.kind();

        //print it out
        logger.info("file event detected <" + kind + "> from file <" + filename + ">");

        if(skyXFile.getFileName().equals(filename))
        {
          TelescopePosition tp = new TelescopePosition(skyXFile, skyX_charset);  //create a new TelescopePosition object
          telescopePositionEvent(tp);      //throw this to the event.
        }        
      }

      //reset the key
      boolean valid = key.reset();

      //exit loop if the key is not valid
      //e.g. if the directory was deleted
      if(!valid)
      {
        break;
      }
    }
    
    logger.info("stop monitoring file: \"" + skyXFile.getFileName() "\"");
  }
Using the new WatchService class from Java7 to monitor files and directory.

 

//Reading a data stream with non-blocking mode 
private OutputStream out = null;
private InputStream in = 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.
try
{
  int a;
  System.in.read(bArray);
  String s = new String(bArray);
  //put to website
  s = s.replaceAll("\\s","");      //remove invisible \r \n char
  s = s.trim();                    //remove white space
  logger.info("-><" + s + ">");
  
  if(s.toLowerCase().compareTo("exit")==0)
  {
    logger.info("Exit command accepted");
  }
}
catch(IOException e)
{
  e.printStackTrace();
}
Another method to get your user data from keyboard. It is just like the scanf (a blocking function) that we have in C/C++ programming. The code scan for input that the user key in from the shell console.

//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

 

InputStream is = null;
try
{
  is = new FileInputStream("resource/idkeydata.xml");
}
catch(FileNotFoundException e1)
{
  e1.printStackTrace();
}

Open an inputstream from a file in the resource folder.

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.

Note:
Class loader resources are often read-only; i.e. held in read-only files / read-only directories.
ClassLoader cl = getClass().getClassLoader();
Unable to obtain classloader using a static class.

Use Java Preferences API instead for configurable preferences.

//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");


More notes about getResource()

from
http://stackoverflow.com/questions/3209901/absolute-path-of-projects-folder-in-

You should really be using getResource() or getResourceAsStream() using your class loader for this sort of thing. In particular, these methods use your ClassLoader to determine the search context for resources within your project.

Specify something like getClass().getResource("lib/txtfile.txt") in order to pick up the text file.

To clarify: instead of thinking about how to get the path of the resource you ought to be thinking about getting the resource -- in this case a file in a directory somewhere (possibly inside your JAR). It's not necessary to know some absolute path in this case, only some URL to get at the file, and the ClassLoader will return this URL for you. If you want to open a stream to the file you can do this directly without messing around with a URL using getResourceAsStream.

The resources you're trying to access through the ClassLoader need to be on the Class-Path (configured in the Manifest of your JAR file). This is critical! The ClassLoader uses the Class-Path to find the resources, so if you don't provide enough context in the Class-Path it won't be able to find anything. If you add . the ClassLoader should resolve anything inside or outside of the JAR depending on how you refer to the resource, though you can certainly be more specific.

Referring to the resource prefixed with a . will cause the ClassLoader to also look for files outside of the JAR, while not prefixing the resource path with a period will direct the ClassLoader to look only inside the JAR file.

That means if you have some file inside the JAR in a directory lib with name foo.txt and you want to get the resource then you'd run getResource("lib/foo.txt");

If the same resource were outside the JAR you'd run getResource("./lib/foo.txt");

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



Properties prop = new Properties();

try
{
  //set the properties value
  prop.setProperty("database""localhost");
  prop.setProperty("dbuser""mkyong");
  prop.setProperty("dbpassword""password");

  //save properties to project root folder
  prop.store(new FileOutputStream("resource/config.properties")null);
}

catch (IOException ex)
{
  ex.printStackTrace();
}
 

Create a property file, with its key and value data pair.

 


OMElement xml = null;
try
{
  xml = AXIOMUtil.stringToOM(data);
}
catch(XMLStreamException e)
{
  throw new XmlDataFormatException("XMLStreamException() occured.");
}
catch (DeferredParsingException e)
{
  throw new XmlDataFormatException("DeferredParsingException() occured.");
}
catch(Exception e)
{
  throw new XmlDataFormatException("Unknown Exception occured parsing data for XML format.");
}


OMElement typeTag = xml.getFirstElement();       

OMElement typeTag = xml.getFirstChildWithName(new QName("tagName"));  

String namespace = xml.getNamespaceURI();
OMElement typeTag = xml.getFirstChildWithName(new QName(namespace, "tagName"));
XML string/file decoder, emcoder
Using
- axiom-api-1.2.18.jar
- axiom-dom-1.2.18.jar
- axiom-impl-1.2.18.jar


//Writing or printing to PDF file.

import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.pdfbox.exceptions.COSVisitorException;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.edit.PDPageContentStream;
import org.apache.pdfbox.pdmodel.font.PDFont;
import org.apache.pdfbox.pdmodel.font.PDType1Font;
import org.apache.pdfbox.util.PDFMergerUtility;

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

  /**
   * create the second sample document from the PDF file format specification.
   
   @param file
   *            The file to write the PDF to.
   @param message
   *            The message to write in the file.
   @param fontfile
   *            The ttf-font file.
   
   @throws IOException
   *             If there is an error writing the data.
   @throws COSVisitorException
   *             If there is an error writing the PDF.
   */
  public void doIt(final String file, final String messagethrows IOException, COSVisitorException
  {
    // the document
    PDDocument doc = null;
    try
    {
      doc = new PDDocument();

      PDPage page = new PDPage();
      doc.addPage(page);
      PDFont font = PDType1Font.HELVETICA_BOLD;

      PDPageContentStream contentStream = new PDPageContentStream(doc, page);
      contentStream.beginText();
      contentStream.setFont(font, 12);
      contentStream.moveTextPositionByAmount(100700);
      contentStream.drawString(message);
      contentStream.endText();
      contentStream.close();

      doc.save(file);

      System.out.println(file + " created!");
    }
    finally
    {
      if(doc != null)
      {
        doc.close();
      }
    }
  }

  /**
   * This will create a hello world PDF document with a ttf-font. <br />
   * see usage() for commandline
   @param args
   *            Command line arguments.
   */
  public static void main(String[] args)
  {
    Test app = new Test();
    Test app2 = new Test();
    try
    {
      app.doIt("D:/here.pdf""hello");
      app2.doIt("D:/here2.pdf""helloagain");
      PDFMergerUtility merger = new PDFMergerUtility();
      merger.addSource("D:/here.pdf");
      merger.addSource("D:/here2.pdf");
      OutputStream bout2 = new BufferedOutputStream(new FileOutputStream("D:/hereisthefinal.pdf"));

      merger.setDestinationStream(bout2);
      merger.mergeDocuments();
    }
    catch(COSVisitorException e)
    {
      e.printStackTrace();
    }
    catch(IOException e)
    {
      e.printStackTrace();
    }
  }
}

Using PDFBox.

Download library pdfbox-app-2.0.0.jar


//Example of using Java to read excel *.xls or calc *.ods file

import org.jopendocument.dom.spreadsheet.MutableCell;
import org.jopendocument.dom.spreadsheet.Sheet;
import org.jopendocument.dom.spreadsheet.SpreadSheet;

//Getting the 0th sheet for manipulation| pass sheet name as string
spreadSheet = SpreadSheet.createFromFile(file).getSheet(0);
          
//Get row count and column count
int nColCount = spreadSheet.getColumnCount();
int nRowCount = spreadSheet.getRowCount();

System.out.println("Rows :" + nRowCount);
System.out.println("Cols :" + nColCount);
//Iterating through each row of the selected sheet
MutableCell cell = null;
for(int nRowIndex = 0;nRowIndex < nRowCount;nRowIndex++)
{
    //Iterating through each column
    int nColIndex = 0;
    for(;nColIndex < nColCount;nColIndex++)
    {
      cell = spreadSheet.getCellAt(nColIndex, nRowIndex);
      System.out.print(cell.getValue() " ");
    }
    System.out.println();
}


 

//Example of using Java to write excel *.xls or calc *.ods file

final Object[][] data = new Object[6][2];
data[0new Object[] { "January"};
data[1new Object[] { "February"};
data[2new Object[] { "March"};
data[3new Object[] { "April"10 };
data[4new Object[] { "May"15 };
data[5new Object[] { "June"18 };

String[] columns = new String[] { "Month""Temp" };

TableModel model = new DefaultTableModel(data, columns);

// Save the data to an ODS file and open it.
final File file = new File("records.ods");
try
{
  SpreadSheet.createEmpty(model).saveAs(file);
  OOUtils.open(file);    //open the spreadsheet
}
catch(FileNotFoundException e)
{
  logger.error(e);
  logger.error("Ensure that the file \"" + file + "\" is not in use by other process.");
}
catch(IOException e)
{
  logger.error("I/O error.", e);
}
 



package testProcess;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

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

/* *
 * The following example provide a means to detect the processes or services currently running in Windows
 * To view the list of processes currently running on your Windows Operating System,
 * Key in "Ctrl"+"Alt"+"Del", then click on "Start Task Manager", then click on the tab "Processes"
 * This is the list of processes that can be detected by the following java program.
 */

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

  public static void main(String[] argsthrows Exception
  {
    String processName = "firefox.exe";
    boolean status = isProcessRunning(processName);
    logger.info("The process <" + processName + "> is " (status?"currently running.":"cannot be found."));    
  }

  public static List<String> getCurProcessTaskList()
  {
    List<String> processes = new ArrayList<String>();
    try
    {
      String line;
      Process p = Runtime.getRuntime().exec("tasklist.exe /fo csv /nh");
      //Alternative sorted result   -> Process p = Runtime.getRuntime().exec("tasklist.exe /FO LIST");
      //Alternative unsorted result -> Process p = Runtime.getRuntime().exec("tasklist.exe");
      BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()));
      while((line = input.readLine()) != null)
      {
        if(!line.trim().equals(""))
        {
          // keep only the process name
          line = line.substring(1);
          processes.add(line.substring(0, line.indexOf("\"")));
        }
      }
      input.close();
    }
    catch(Exception err)
    {
      logger.error("Error encountered in getCurProcessTaskList().",err);
    }
    return processes;
  }

  public static boolean isProcessRunning(String serviceNamethrows Exception
  {
    //grab the list of the current processes, services running in the Windows.
    List<String> processes = getCurProcessTaskList();

    //check if the required service is in the list 
    Iterator<String> it = processes.iterator();
    int i = 0;
    while(it.hasNext())
    {
      String s = it.next();
      //display all the processes currently running in the system now
      //logger.info(s);
      if(serviceName.compareTo(s== 0)
      {
        return(true);
      }
    }
    return(false);
  }
}

This example shows how you can use java to detect the processes running under the Windows Operating System. It can a mean to detect if another Windows application or service or task is currently running.

If can even list out all the currently running processes.

 

 

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"

 

Add your own variables to the java environment system variables.

java YourProgram -D keyString="mystring".


example:
java myJavaProgram -D sg.myhomedir="E:\myJaveProjects\
"

You can also customised your java system variables, by adding the variable when you run the java command.
//Java code to get computer name, example "LSB-PC"
String computername = InetAddress.getLocalHost().getHostName();
 
 


import java.util.prefs.Preferences;

private void saveDirPathToRegistry(String dir)
{
   Preferences prefs = Preferences.userRoot().node(this.getClass().getName());
   prefs.put(REGISTRY_KEY_NAME, dir);
   logger.info("Saved new directory selected \"" + dir + "\"");
}
   
private String getDirPathFromRegistry()
{
   Preferences prefs = Preferences.userRoot().node(this.getClass().getName());
   String path = prefs.get(REGISTRY_KEY_NAME, null);
   if(path != null)
      logger.info("Detects last directory visited \"" + path + "\"");
   return(path);
}
Saving and retreiving Java application data to the operating system registry (example: Win7 registry regedit).

After running this Java program under Windows 7 (64 bits) the following error may be produced,
java.util.prefs.WindowsPreferences <init>
WARNING: Could not open/create prefs root node Software\JavaSoft\Prefs
at root 0x80000002. Windows RegCreateKeyEx(...) returned error code 5.

The error occurs because java.util.prefs.WindowsPreferences is trying to save information in HKEY_LOCAL_MACHINE\Software\JavaSoft\Prefs instead of under HKEY_CURRENT_USER\Software\JavaSoft\Prefs.

The work around is to login as the administrator and create the following key HKEY_LOCAL_MACHINE\Software\JavaSoft\Prefs

or you can use this *.inf script to install/create this key in the WindowsOS registry
Java Prefs registry setup.inf
Download this file. Right click and select "install".
The key "HKEY_LOCAL_MACHINE\Software\JavaSoft\Prefs"
will be create in the Windows OS registry.

userRoot()
systemRoot()

Threading processes
 
//Useful code to track the number of thread running.
logger.info("Active thread count: " + Thread.activeCount());

//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.

    }
});
rescan.start();

//Set a name for your thread, to easily track and debug it.
currentThread.setName("Processing-" + messageId);

//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());
    }

  }
}

 

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

  private myThreadClass tc;
  private Shutdownhook sdh;
  
  public Abc()
  {
    sdh.addShutdownHook(this);
  }

  @Override
  public void shutdownHookActivated()
  {
    close();
  }
  
  public void close()
  {

    if(sdh != null)
    {
      sdh.remove();

      sdh = null;
    }
  }
}

Implementing Shutdownhook using my utilities.jar file. Download the latest version from the section under "My Java Library"

 

 

 

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.
//-----------------------------------------------------------------------------
String fileName = "resource/documentation/operating manual.pdf";
try
{
  Desktop.getDesktop().open(new File(fileName));
}
catch(IOException e)
{
  logger.info("Error opening file " + fileName + ". The default program to open this file may not been set. Please set the default program.");      
}

//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"));
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");

//force close the opened file
p1.destroy();


//-----------------------------------------------------------------------------
//Opening a Openoffice calc template (*.ots) as a calc file (*.ods)
//Using Desktop.getDesktop().open() will open the *.ots template file instead of a *.ods calc file
//-----------------------------------------------------------------------------

String sOfficeExe = "C:/Program Files (x86)/OpenOffice 4/program/soffice.exe";
String calibrationTemplate = "resource/template.ots";
Process p = new ProcessBuilder(sOfficeExe, "-calc", calibrationTemplate).start();  //command line => "C:/Program Files (x86)/OpenOffice 4/program/soffice.exe" -calc "D:/programs/_workspace/macce/resource/Gauge Block Files/Calibration Files/_job no, Calibration Application Form Template.ots"
Machine.getInstance().delay(2000);    //allow some time for Process to execute
p.destroy();
 
Launching folder directory, network drive from Java

//-----------------------------------------------------------------------------
//Using Desktop class to open directory/folder, so that the code will be OS platform independent
//-----------------------------------------------------------------------------
//opening a local directory/folder.
Desktop.getDesktop().open(new File("D:\\programs\\eclipse\\_workspace\\InvoiceDataExtractor"));
//opening a remote network drive using network name/path.
Desktop.getDesktop().open(new File("\\\\BOB-PC\\Bob share folder"));
//opening a remote network drive using IP address.
Desktop.getDesktop().open(new File("\\\\192.168.1.95\\Bob share folder"));


//-----------------------------------------------------------------------------
//Non platform independent code. (for Window OS)
//-----------------------------------------------------------------------------
//open "InvoiceDataExtractor" folder
Process p = new ProcessBuilder("explorer.exe", "D:\\programs\\eclipse\\_workspace\\InvoiceDataExtractor").start();

//open "_workspace" directory and select "InvoiceDataExtractor" folder
Process p = new ProcessBuilder("explorer.exe", "/select,D:\\programs\\eclipse\\_workspace\\InvoiceDataExtractor").start();





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  
//object for storing IP address
InetAddress inetAddr = InetAddress.getByName("192.168.1.100");            //check proper internet address by InetAddress
int port = 80;

//comparing IP address
if(inetAddr.equals(inetAddr2))
{
       logger.info("IP address is the same");
}

//object socket for storing IP address & Port
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.

For UDP broadcasting, use address 255.255.255.255, instead of the local broadcast address. The UDP message to address 255.255.255.255 will typically route to all IP address within the local network (LAN) and will be block by the router. UDP message usually don't propagate beyond the LAN.  

Compute Broadcast address from IP address and network MASK

public String getBroadcastAddress(String ip, String mask)
{
  String broadcastAddr = null;

  String ipArr[] = ip.split("\\."4);
  String maskArr[] = mask.split("\\."4);

  byte ipByte[] new byte[4];
  byte maskByte[] new byte[4];
  byte bcByte[] new byte[4];

  int x = 0;
  for(x = 0;x < 4;x++)
  {
    ipByte[x(byte) (Integer.parseInt(ipArr[x]) 0xFF);//convert a string into a byte maskByte[x] = (byte) (Integer.parseInt(maskArr[x])&0xFF); //convert a string into a byte //ipByte[x] = Byte.parseByte(ipArr[x]); //convert a string into a byte 
    //maskByte[x] = Byte.parseByte(maskArr[x]); //convert a string into a byte
    bcByte[x(byte) (ipByte[x& maskByte[x])//mask out the subnet address
    bcByte[x(byte) (bcByte[x(maskByte[x0xFF))//form the subnet
    broadcastAddr = (((intbcByte[0]) 0xFF"." (((intbcByte[1]) 0xFF"." (((intbcByte[2]) 0xFF"." (((intbcByte[3]) 0xFF);
  }
  return(broadcastAddr);
}
 
Using Java to send email, using this javax.mail.jar file

import java.util.Date;
import java.util.Properties;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

  String host = "siongboon.com";    //smtp host server
  String user = "username";    //smtp host server's user name
  String pass = "??????????";       //smtp host server's user password
  String to = "????@siongboon.com";     //recipient email address
  String from = "????@siongboon.com";    //sender email address
  String subject = "Test subject";     //subject
  String messageText = "Test body";     //email text
  boolean sessionDebug = false
  Properties props = System.getProperties()
  props.setProperty("mail.host", host)
  props.setProperty"mail.transport.protocol""smtps");
  pprops.setProperty("mail.smtps.auth""true")
  props.setProperty("mail.smtps.port""465")
  props.setProperty("mail.smtps.ssl.trust", host)
  Session mailSession = Session.getDefaultInstance(props, null)
  mailSession.setDebug(sessionDebug)
  Message msg = new MimeMessage(mailSession)
  try
  {
    msg.setFrom(new InternetAddress(from));
    InternetAddress[] address = {new InternetAddress(to)}
    msg.setRecipients(Message.RecipientType.TO, address)
    msg.setSubject(subject)
    msg.setSentDate(new Date()); msg.setText(messageText)
    Transport transport = mailSession.getTransport("smtps");
    transport.connect(host, user, pass)
    transport.sendMessage(msg, msg.getAllRecipients())
    transport.close()
  }
  catch(MessagingException e)
  {
    // TODO Auto-generated catch block
    e.printStackTrace();
  

 

 

 

Multimedia  

Playing *.mp3 and *.wav audio/sound files

import java.io.File;
import javax.media.Format;
import javax.media.Manager;
import javax.media.MediaLocator;
import javax.media.Player;
import javax.media.PlugInManager;
import javax.media.format.AudioFormat;


    Format input1 = new AudioFormat(AudioFormat.MPEGLAYER3);
    Format input2 = new AudioFormat(AudioFormat.MPEG);
    Format output = new AudioFormat(AudioFormat.LINEAR);
    PlugInManager.addPlugIn("com.sun.media.codec.audio.mp3.JavaDecoder"new Format[] { input1, input2 }new Format[] { output }, PlugInManager.CODEC);
    try
    {

      String file_location = "d:/mp3dog.mp3";
      System.out.print("start thread mp3 play: " + file_location + "\n");
      Player player = Manager.createPlayer(new MediaLocator(new File(file_location).toURI().toURL()));
      player.start();
      
      file_location = "d:/mp3siren.mp3";
      System.out.print("start thread mp3 play: " + file_location + "\n");
      Player player2 = Manager.createPlayer(new MediaLocator(new File(file_location).toURI().toURL()));
      player2.start();
      
      System.out.print("Two MP3 files playing together.\nNote that the media playing thread is still running.\n");
      
      //delay for 10sec before forcing thread to close
      try{Thread.sleep(10000);}catch(InterruptedException e){}
      
      System.out.print("Ending play thread.\n");
      player.close();
      player2.close();      
    }
    catch(Exception ex)
    {
      ex.printStackTrace();
    }

Download the following
- jmf.jar
- mp3plugin.jar
- mp3siren.mp3
- mp3dog.mp3

 


 

 

 

Java and SQL  
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


 

 

 

Java Command Pattern (or Design Pattern)  

Command Pattern: ExecutorService example: 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.
First create a task object that implements callable<return type>.
Cabllable objects contains a callable method (thread), which will be submitted to the executor service.
This allows the executable (SingleThreadExecutor()) to call this task object in the queue when its turn is up.
There are many type of executor available depending on your application. (example: newFixedThreadPool(3), newCachedThreadPool())

ExecutorService
//for ExecutorService, execute methods in a FIFO queue.

private final ExecutorService pool;       
//Executors object can helps to execute each task in a queuing sequence.
//A brand new pool object will be created here. Remember to shutdown each and every pool generated. Each pool is a thread by itself.
pool = Executors.newSingleThreadExecutor();       

//create an callable object to do the execution for the task in the queue.
//The callable method will be returning a boolean result.
Callable<Boolean> smsJob = new ModemManagerQueueJob(smsModem, smsMsg);   

//send sms to user
//process will stop at this block mode after submit. Once the thread complete its execution, it will return a value
//Loop through the submit to determine if all the jobs (or threads) are completed. (especially for non queue type of executor)
Future<Boolean> executorResult = pool.submit(smsJob);    //(use pool.execute(smsJob) for non blocking and no exception catch required.

//get the return sms result, replied from the mobile user (exception from the callable object can be catch here. e.getCause() to extract the exception)
boolean result = executorResult.get();

//always remember to shutdown executor thread
pool.shutdown();
or
pool.shutdownNow();

return(result);

try
{
  paymentSlip = paymentResult.get()//waiting here for the payment result (payment receipt)
  logger.info("received paymentSlip");
}
catch(InterruptedException e)
{
  logger.warn(e.getClass().getName() "() occurred");
  return;
}
catch(ExecutionException e)
{
  String msg;
  try
  {
    throw e.getCause();
  }
  catch(PaymentTimeoutException ee)
  {
    msg = ee.getMessage();
    logger.warn(ee.getMessage());
  }
  catch(PaymentMachineException ee)
  {
    msg = ee.getMessage();
    logger.error(ee.getMessage());
  }
  catch(UnknownPaymentException ee)
  {
    msg = ee.getMessage();
    logger.error(ee.getMessage());
  }
  catch(Throwable e1)
  {
    msg = e1.getMessage();
    os.sendStatus(OrderErrorCodeEnum.UNKNOWN, msg);
  }
}
catch(CancellationException e)
{
  String msg = "Payment process cancelled.";
  logger.info(msg);
}
Handling interrupt or exception from the running task (thread). Something may happen in the task that is running from the thread generated from the executor service. The left is an example how the exception can be handled.
ExecutorService taskExecutor = Executors.newFixedThreadPool(4);
List<Callable<?>> tasks; // your tasks
// invokeAll() returns when all tasks are complete. Any exeception from the callable object can be detected here
List<Future<?>> futures = taskExecutor.invokeAll(tasks);

ThreadFactory factory = new DefaultThreadFactory("Payment");
pool = Executors.newSingleThreadExecutor(factory)//Executors object can helps to execute each task in a queuing sequence.

//ThreadFactory class written as follows
public class DefaultThreadFactory implements ThreadFactory
{
    static final AtomicInteger poolNumber = new AtomicInteger(1);
    final ThreadGroup group;
    final AtomicInteger threadNumber = new AtomicInteger(1);
    final String namePrefix;

    public DefaultThreadFactory(String name)
    {
        SecurityManager s = System.getSecurityManager();
        group = (s != null? s.getThreadGroup() : Thread.currentThread().getThreadGroup();
        namePrefix = name + poolNumber.getAndIncrement() "-thr-";
    }

    public Thread newThread(Runnable r)
    {
        Thread t = new Thread(group, r, namePrefix + threadNumber.getAndIncrement()0);
        if(t.isDaemon())
            t.setDaemon(false);
        if(t.getPriority() != Thread.NORM_PRIORITY)
            t.setPriority(Thread.NORM_PRIORITY);
        return t;
    }
}
DefaultThreadFactory helps to generate a unique name for the thread from the service executor pool which will be useful for troubleshooting. Using a default factory as shown above will generate a general thread.
//catching the exception that happens in the individual executor thread run.
      try
        {
            //blocking method waits for all cmd jobs to be completed
            logger.info(getId() " starts executing all the <" + numOfTask + "> added tasks");
            futures = executorServ.invokeAll(tasks);       
            logger.info(getId() " completed all <" + numOfTask + "> tasks.");
           
            //check for exception from the list of futures
            for(Future<CmdResponse> f: futures)
            {
                f.get();
            }
        }
        catch(ExecutionException e)
        {
            //catching the exception that happens in the executor thread run.
            if(e.getCause() instanceof CmdMonitoringTimeoutException)
            {
                String errorMsg = e.getCause().getClass().getSimpleName() ": "+ e.getCause().getMessage();
                throw new ControllerCommandException(errorMsg,e);
            }
            if(e.getCause() instanceof ControllerCommandException)
            {
                String errorMsg = e.getCause().getCause().getClass().getSimpleName() ": "+ e.getCause().getCause().getMessage();
                throw new ControllerCommandException(errorMsg,e);
            }           
            else
            {
                e.printStackTrace();
            }
        }

 

Creational Patterns:  
Abstract Factory  
Builder  
Factory  
Prototype  
Singleton Conciously running a single instance of an object. Ensuring that no duplicated instance is possible. This is useful when there is a need to encupsulate a hardware module. There is only one hardware module, making it singleton.
   
Structural Patterns:  
Adapter Add in a middle class so that an old program is able to temperary adapt to a new object method.
Bridge  
Composite  
Decorator  
Facade  
Flyweight  
Proxy  
   
Behavioral Patterns:  
Chain of Responsibility  
Command  
Interpreter Interpreter example use for paser or compiler.
Iterator Going through a list of objects collections
Mediator  
Memento  
Observer  Many other objects wanting to receive update from an object.
State State by state. Lifecycle.
Strategy  
Template Method  
Visitor  
   

references:
http://www.go4expert.com/articles/design-pattern-simple-examples-t5127/


 

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

Design pattern reference:

- java-design-patterns.pdf



Java GUI Programming
 JavaFX programming. Use JavaFX Scene Builder. Config Eclipse plugin and library to supprt JavaFX.  https://www.eclipse.org/efxclipse/install.html
Go to Eclipse>Help>Install New Software...>Add Repository>
Name: e(fx)clipse
Location: http://download.eclipse.org/efxclipse/updates-released/2.3.0/site
Install the plugin from the repository.

Create a *.FXML document.
Eclipse>File>New>Other>New FXML Document
Give this GUI layout file a name.
Right click the new *.FXML file, open it with SceneBuilder.

GUI & Event Listener example
- Create window
- Window listener
- Mouse listener
- Keyboard listener
- Observer (command pattern)

Use Observer command pattern (Observer, Observable) to implement any listener, events with multiple object listening to the same event.
- 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



JNI Java Native Interface

 
Java is a high level secure language. The language do not allow low level hardware device access. Standard device interface like file access, HID mouse/keyboard, imaging, network, PCSC card access, etc... has been written in Java. There are many non standard hardware like RS232, propietary hardware that uses low level code access. Java do not have object that deals with this. The only option is to write the driver/software in low level language C/C++ and create a java native interface to access the low level object. Doing so will also means that you code is no longer portable to other operating system.  

Step 1) Write your normal java class implementing a native method as an abstract.

Myclass
{
  public Myclass()
  {
  }

  public void method1() //normal java method 
  {
  }

  private native void method2()//native method 
}

 
Step 2) Build your java code to generate the Myclass.class from your Myclass.java.  

Step 3) Use the command "javah" to generate a header file from your class file. Go to your generated class directory.

example:
javah Mypackage.Myclass

A header file Mypackage_Myclass.h will be generated.

 
Step 4) Copy/Import the header file to your C project. Use this generated header to help you write your *.c source code. Also #include <jni.h> for your *.c use  

Step 5) Build the C project to generate a *.so library file.

You may encounter an error message
"error: parameter name omitted"
You may have left out the function's (or method's) parameter names which will not be generated in the *.h.
Provide your parametters with a variable name.

 

Step 6) Use the *.so file for the *.java file that you have created initially. This is for the system class loader

Myclass
{
  static
  {
    System.load("full-path-to-NetBeansProjects-dir/JNIDemoCdl/dist/libJNIDemoCdl.so");
  }

  public Myclass()
  {
  }

  public void method1() //normal java method 
  {
  }

  private native void method2()//native method 
}
 
Step 7) Build and deploy the codes.  

Reference:
Java programming with JNI.pdf
Beginning JNI with NetBeans IDE and C_C++ Plugin on Linux.pdf

 

 

 


My Java Library

 
//Config.properties file content
processDirectory="D:\\Incoming doc\\Expenses Invoice"
processDirectory="D:/Incoming doc/Expenses Invoice"

//Using Utilities to retrieve config variables from config.properties file
ConfigFile cf = null;
String configFile = "config.properties";

cf = new ConfigFile(configFile);
String processFolderStr = cf.getPropertyQuote("processDirectory""D:\\");
String archiveFolderStr = cf.getPropertyQuote("archiveDirectory"null);

String prop = cf.getProperty(key, defaultValue);
Boolean bool = cf.getPropertyBoolean(key, defaultValue);
Float f = cf.getPropertyFloat(key, defaultValue);
Integer i = cf.getPropertyInteger(key, defaultValue)

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

- UtilitiesThread.java

utilities.zip

utilities (2011-03-25).jar

utilities (2013-08-11).jar

utilities (2015-04-26).jar
utilities (2015-10-13).jar

nativePeripheral (2015-10-13).jar
nativePeripheral is meant for serial communication use.
public static void main(String[] argsthrows IOException
{
    byte[] b = 0x040x04(byte0xFF0x64 };

    //AsciiHexString ahs = new AsciiHexString("0102");
    AsciiHexString ahs = new AsciiHexString(b);

    //print example
    logger.info("Printing example:");
    String printStr;
      
    logger.info("1) print()");
    ahs.print();
    logger.info("2) original");
    printStr = ahs.toString();
    logger.info("\t\t\"" + printStr + "\"");
    logger.info("3) 0x format");
    printStr = ahs.toString(HexStringDisplayFormat._0X);
    logger.info("\t\t\"" + printStr + "\"");
    logger.info("4) space inbetween");
    printStr = ahs.toString(HexStringDisplayFormat.SPACE);
    logger.info("\t\t\"" + printStr + "\"");
    logger.info("5) bar inbetween");
    printStr = ahs.toString(HexStringDisplayFormat.BAR);
    logger.info("\t\t\"" + printStr + "\"");

    //short, int, long data example (hex/hexString to value)
    logger.info("");
    logger.info("Data type short, int, long example1:");
    try
    {
      byte[] byteA = 0x040x04(byte0xFF0x640x640x640x640x64 };
      byte[] byteB = 0x040x04(byte0xFF0x64 };
      byte[] byteC = { (byte0xFF0x64 };
      AsciiHexString numA = new AsciiHexString(byteA);
      AsciiHexString numB = new AsciiHexString(byteB);
      AsciiHexString numC = new AsciiHexString(byteC);
      
      logger.info("numA = " + numA.toString() "\tLong = " + numA.toLong() "\tanswer should be (long=289637082704667748)");
      logger.info("numB = " + numB.toString() "\t\tInt = " + numB.toInt() "\t\t\tanswer should be (int=67436388)");
      logger.info("numC = " + numC.toString() "\t\tShort = " + numC.toShort() "\t\t\tanswer should be (short=-156)");
      
      logger.info("numB Short = " + numB.toShort());
    }
    catch(HexValueOutOfRangeException e)
    {
      logger.error("numB cannot convert to short. " + e);
    }
    
    //short, int, long data example (value to hex/hexString)
    logger.info("");
    logger.info("Data type short, int, long example2:");
    long valueD = 289637082704667748L;                  
    int valueE = 67436388;
    short valueF = -156;
    AsciiHexString numD = new AsciiHexString(valueD);
    AsciiHexString numE = new AsciiHexString(valueE);
    AsciiHexString numF = new AsciiHexString(valueF);
    
    logger.info("valueD = " + valueD + " converted to hexString = \"" + numD.toString() "\"");
    logger.info("valueE = " + valueE + " converted to hexString = \"" + numE.toString() "\"");
    logger.info("valueF = " + valueF + " converted to hexString = \"" + numF.toString() "\"");
}
Hex String ultilities contains in utilities.jar file
      String data = "03 53 29 00 30 60 29 A0 30";        //text of hex number copied from a software tool
      AsciiHexString ascii = new AsciiHexString(data);   //from a string of hex number
      byte[] byteArray = ascii.toHexByte();              //convert to byte array
Convert a text string copied from most software tool to a byte array for testing use. Very useful conversion of String Hex to byte array.
//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
}
 
//example for using the TcpIpServerService class 
import java.net.Socket;

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

import com.picControl.utilities.communication.TcpIpServerService;

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

  public TestTcpIp(int port)
  {
    super(port);
  }

  @Override
  protected void clientHandler(Socket s)
  {
    logger.info("Client connected. " + s.toString());
    //Usual way of handling this Socket s here.
    //Multiple client may connect into this server.
    //For each and every client connection, this method will be invoked.
    //From here, you can spin off individual thread to handle the connection.
  }

  public static void main(String[] args)
  {
    TestTcpIp t = new TestTcpIp(10001);
    t.start();
   //Start the server, listening for incoming client connection.
    while(true)
    {
         try{Thread.sleep(100);}catch(InterruptedException e){}
    }
  }
}

KNX EIB communication for home automation server KNX source code
Example of a complex communication protocol and behavior handing.
TjLink TCP/IP communication for network Audio Video AV equipment (AV receiver, Projector) TjLink source code example.
Good example for learning Java inheritance ("extends") and interface ("implements")
HID RFID door access security program HID RFID source code
Example of server handling multiple clients
Server service to control all computers to wakeup or sleep Wake&Sleep
Example for Java serlvet, webserver (browser user interface)
SMS webservice server SMS server
Good example of job queue command pattern.
UDP communication with Xport, MatchPort Java UDP client for XPort
Network UDP example
Good java coding practise
JavaDoc
  /**
   * Converts bytes array to string<p>
   * Example if byteArr = 0x01 0x03 0x4A => AsciiHexString = "01034A"<p>
   @param hexByte    array of bytes to be converted to string.
   @return           the converted hex in string format
   */

Java standard of documenting your source code.
Java Serial Com Port Example (RS232), uses RXTXcomm.jar (gnu.io.SerialPort)

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

import com.picControl.nativePeripheral.comm.SerialCom;
import com.picControl.nativePeripheral.comm.serial.SerialBaudrate;
import com.picControl.nativePeripheral.comm.serial.SerialCommException;
import com.picControl.nativePeripheral.comm.serial.SerialCommListener;
import com.picControl.nativePeripheral.comm.serial.SerialDataBit;
import com.picControl.nativePeripheral.comm.serial.SerialHardwareFlow;
import com.picControl.nativePeripheral.comm.serial.SerialParityBit;
import com.picControl.nativePeripheral.comm.serial.SerialStopBit;
import com.picControl.utilities.hexstring.AsciiHexString;
import com.picControl.utilities.hexstring.constant.HexStringDisplayFormat;

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

  private SerialCom serialCom;

  public TestSerialCom()
  {
    try
    {
      serialCom = new SerialCom("COM7", SerialBaudrate.BPS_19200, SerialDataBit.DATA_8, SerialParityBit.NO_PARITY, SerialStopBit.STOP1, SerialHardwareFlow.NO_HARDWARE_FLOW);
      serialCom.registerSerialComEvent(this);
    }
    catch(SerialCommException e)
    {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }

  @Override
  public void serialCom_DataRx(byte[] dataByte)
  {
    AsciiHexString asciiStr = new AsciiHexString(dataByte);
    String dataStr = asciiStr.toString(HexStringDisplayFormat._0X);
    logger.info("(" + dataByte.length + ") " + dataStr);
  }
  
  public void send(byte[] dataBytethrows SerialCommException
  {
    serialCom.send(dataByte);
  }

  public void send(String datathrows SerialCommException
  {
    serialCom.send(data);
  }

  private void close()
  {
    serialCom.close();    
  }

  public static void main(String[] args)
  {
    byte[] outputCmd = new byte[] { '\003', 'O''C''\r''\n' };
    
    logger.info("Test Serial Com START...");
    
    //create a serial com object
    TestSerialCom tsc = new TestSerialCom();
    
    //sending data to serial com
    try
    {
      tsc.send(outputCmd);
    }
    catch(SerialCommException e1)
    {
      // TODO Auto-generated catch block
      e1.printStackTrace();
    }
    
    //listening to incoming data from serial com
    int timerEnd = 30;
    
    timerEnd = timerEnd * 10;
    for(int x=; x < timerEnd ; x++)
      try{Thread.sleep(100);}catch(InterruptedException e){}
    
    tsc.close();
    
    logger.info("Test Serial Com END...");
  }
}
serialComPack (2015-10-13).zip
RXTXcomm.jar
rxtxSerial.dll (64bits)
rxtxSerial.dll (32bits)
nativePeripheral.jar

Setup
---------------------------------------------------------
1) Copy the file "rxtxSerial.dll"
   (for 64bits system) from to folder "c:\windows\system32"
   (for 32bits system) from to folder "c:\windows\SysWOW64"



Click here for Serial Communication Tools


 

Java FFT to transform a time domain into a frequency domain

import edu.emory.mathcs.jtransforms.fft.DoubleFFT_1D;

    double[] input = new double[] { 1, -11, -11, -11, -};
    DoubleFFT_1D fftDo = new DoubleFFT_1D(input.length);
    double[] fft = new double[input.length * 2];
    System.arraycopy(input, 0, fft, 0, input.length);
    fftDo.realForwardFull(fft);

    String data = "";
    for(double d1:input)
    {
      data += d1 + "\t";
    }
    logger.info(data);
    
    data = "";
    for(double d2:fft)
    {
      data += d2 + "\t";
    }
    logger.info(data);

//How to intepret the FFT results?

//time domain signal[8] =>    1.0    -1.0   1.0    -1.0    1.0    -1.0    1.0    -1.0   
//freq domain signal[9] =>    0.0    0.0    0.0    0.0     0.0    -0.0    0.0     0.0    8.0     0.0     0.0     -0.0    0.0     0.0     0.0     -0.0
//                            [0]    [1]    [2]    [3]     [4]     [5]    [6]     [7]    [8]
//Samples = 8, a total of 8 samples in the time domain.
//fs = Sampling Frequency (125Hz)
//[0] - DC component
//[1] - fs/2 * 1/samples    =    fs/(16)
//[2] - fs/2 * 2/samples    =    2fs/(16)
//[3] - fs/2 * 3/samples    =    3fs/(16)
//[4] - fs/2 * 4/samples    =    4fs/(16)
//[5] - fs/2 * 5/samples    =    5fs/(16)
//[6] - fs/2 * 6/samples    =    6fs/(16)
//[7] - fs/2 * 7/samples    =    7fs/(16)
//[8] - fs/2 * 8/samples    =    8fs/(16)
//Comment: no dc component. AC component which is half of the sampling frequency.

//time domain signal[8] =>    1.0   -1.0    4.0   -4.0     1.0    -1.0    4.0    -4.0   
//freq domain signal[9] =>    0.0    0.0    0.0    0.0    -6.0    -6.0    0.0     0.0    20.0    0.0     0.0     -0.0    -6.0    6.0     0.0     -0.0   
//                            [0]    [1]    [2]    [3]     [4]     [5]    [6]     [7]    [8]
//Comment: no dc component. AC component which is half of the sampling frequency, and also 1/4 of the sampling freq.

//time domain signal[16] =>   10.0   0.0    10.0   0.0     10.0    0.0    10.0   0.0     10.0   0.0    10.0   0.0    10.0   0.0    10.0   0.0   
//freq domain signal[17] =>   80.0   0.0    0.0    0.0     0.0     0.0    0.0    0.0     0.0   -0.0    0.0    0.0    0.0    0.0    0.0    0.0    80.0  ...

//                            [0]    [1]    [2]    [3]     [4]     [5]    [6]     [7]    [8]
    [9]    [10]   [11]   [12]   [13]   [14]   [15]   [16]
//Comment: With dc component, because there are no negative numbers. AC component which is half of the sampling frequency.



These formatted java source codes are generated by java2html_50.zip