- Edited by Lim Siong Boon, last dated 22-Sep-2010.
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
| Java
Language
References |
|||||||||||||||||||||||||||
| Escape
code for
Java
Regular Expression
http://www.wellho.net/regex/javare.html
|
Java
Regular
Expressions
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."; |
| Java
Fundamental
References |
|
|
|
This is an example of a typical Java coding structure and some Java naming convention for package, class, method, and variable. |
|
|
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 abstract..
What do these defination really means? |
|
|
//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.public
abstract class LiftButton { abstract public void openLiftDoor();abstract public void closeLiftDoor(); //if any method is abstract, the class must be an
abstract. //codes that will be shared among those classes who
inherit this abstract class. }//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 | |
|
|
|
|
|
|
//Casting
a numeric value to a charchar c3 = (char)87;char c1 = '\u0057'; |
|
|
|
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 417byte[] dataByte = new byte[]{(byte) 0xD1, (byte) 0xA1};ByteBuffer wrapped = ByteBuffer.wrap(dataByte); // convert 0xD1A1 to -11871integer result = -11871 |
Convert 2 bytes array to integer |
int hex = Integer.parseInt(HexString, 16); String str = Integer.toBinaryString(79); |
//parse hex string. HexString="FFFF",
result-> hex=65535 //convert number
79 to a hex string "4f" //convert
number 79 to a binary string "01111001" |
//defining
byte constant array |
|
//Bitwise
Operator<<
//left shift preserving the sign bit |
|
| Integer
String Manipulation |
|
int num = Integer.parseInt(String); |
//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" |
| String Manipulation | |
String str = "Hello"; //correct
proper wayString str = new String("Hello"); //creating unneccessary String object again. Waste CPU
process.//inserting octal or hex char into a
stringString string = "hello\r\n"
String str = "abc]123]XYZ"; |
|
|
|
Removing invisible \r \n char and white space. |
//compare & match string
|
|
|
|
String formatter Leading or padded zero https://docs.oracle.com/javase/7/docs/api/java/util/Formatter.html |
String strDecimalFormat formatV = new DecimalFormat("#.##"); |
special numerical formatting |
|
//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. |
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)); |
//convert char/int to 8 bit binary |
//to
check/compare the data/object type of a unknown java object |
|
|
//Iterating through each element in the enum//Get the literal string of the enumBonjourService.CAMERA.name()//Get the enum from a stringBonjourService 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 |
implementing a static method for use to convert the old int convention to enum type object. |
|
|
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(); |
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. |
| Time,
Date,
Calendar,
Timer |
|
//Delay/sleep
functiontry{Thread.sleep(1000);}catch(InterruptedException e){} |
|
//System time counting in millisecond.
Measuring the
cpu time to execute certain tasklong sysMiliSecCount = System.currentTimeMillis( ); |
|
Instant timestamp = Instant.now();
|
Java 8 timestamp
formatting, https://docs.oracle.com/javase/8/docs/api/java/time/format/DateTimeFormatter.html |
|
|
|
| //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 |
| 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 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: |
***new changes to
org.apache.log4j.DailyRollingFileAppender log4j.appender.WeightSensorLog.DatePattern=’.’yyyy-MM-dd-a |
|
|
How to add *.jar library?Encountered the following errors?log4j:WARN
No appenders could be found for logger (javax.swing.JApplet). |
//A
method to log seperately to two log file from a classprotected 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,OrderLoglog4j.additivity.OrderServer=false log4j.appender.OrderLog = org.apache.log4j.DailyRollingFileAppender log4j.appender.OrderLog.File=${log.dir}/1-Order/Order |
|
|
|
public KnxSession() throws KnxCommException |
Must read. |
public class MyOwnException extends Exception |
A simple exception class, that accept customised error messages. |
//KnxCommExeception Classpackage knxEib.knxException; |
A complex exception class that has more functions. |
| File I/O,
Properties/Configuration file |
|
|
Example: File Write
String filename = getClass().getName()+".txt"; |
|
BufferedReader in = null; |
Very often to specify a file path
using a string, we need to use double slashes instead of only one in
Java string.
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(); 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; |
Rename a file name without
changing the directory. (change file name) |
Path source = Paths.get("from/path");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; |
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 |
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()
|
Using
the new WatchService
class from Java7 to monitor files and directory. |
|
|
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
|
|
//reading input from a keyboard |
Reading from a keyboard is similar to reading from a data stream. Infact data reading is always in the form of stream. |
try |
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. |
|
|
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; |
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), |
//Example
of reading configuration from a property file.private void loadNetworkConfig() |
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: 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 classpathInputStream 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 packageInputStream 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.propertiesIP=192.168.1.1 |
|
|
|
Create a property file, with its key and value data pair. |
OMElement xml = null; |
XML string/file
decoder, emcoder Using – axiom-api-1.2.18.jar – axiom-dom-1.2.18.jar – axiom-impl-1.2.18.jar |
|
import java.io.BufferedOutputStream; |
Using PDFBox. Download library pdfbox-app-2.0.0.jar |
|
|
|
//Example of using Java to write excel *.xls or calc *.ods file |
| |
package testProcess; |
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"); |
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
|
||||||||||||||||||||||||||||||||||||||||||||
|
Add your own variables to the java environment system variables. java YourProgram -D keyString=”mystring”.
|
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"
|
|||||||||||||||||||||||||||||||||||||||||||||
import java.util.prefs.Preferences; |
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. |
|
|
|
The
coding examples on the left are the various style of using the Java
threading features.
http://download.oracle.com/javase/tutorial/essential/concurrency/syncmeth.html |
//Spinning off a new Thread process without
writing
inside a proper class file } |
|
//Set
a name for your thread, to easily track and debug it.currentThread.setName("Processing-" +
messageId); |
|
|
|
|
| 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.//If the java
program terminate
abnormally, shutdownhook will be activated.private ThreadClassShutdownHook tcShutdownHook = null; //add
this to the thread class variabletcShutdownHook = 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. |
|
|
|
|
|
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 | |
|
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" |
|
| Launching folder
directory, network drive from Java
|
|
| 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//object socket for
storing
IP address & Port InetSocketAddress socketAddr = new InetSocketAddress(inetAddr, port); //data object for socket information (ip:port) |
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...) |
|
|
|
|
//handling
incoming client connection |
| Network UDP communication example (datagram packet listening) | |
//UDP example, from
EIB/KNX communication
program |
|
byte[] data = LantronixDevice.queryFirmwareVer; |
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) |
|
Using Java to send email, using this javax.mail.jar file import java.util.Date;
|
| Multimedia | |
|
Playing *.mp3 and *.wav audio/sound files
|
Download the following
|
| 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.1) download and
install the following software |
|
SQL connection pool:------------------------------------------------4) download the
following jar libraries |
| 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; |
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
try |
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); |
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
ThreadFactory factory = new DefaultThreadFactory("Payment"); |
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
//catching the exception that
happens in the executor thread run.
if(e.getCause() instanceof CmdMonitoringTimeoutException) |
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
references:
|
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
read log4j ndc (log the individual instance of client thread connected to the server) |
Design pattern reference: |
| 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 |
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 |
|
int keyChar = evt.getKeyChar(); |
Create a message dialog box that helps to debug data in hex code. |
|
example to load image file to JPanel. |
| 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. Without
the *.class will also works If
your MyApplet.class is located in the directory /appDir If
the *.class to invoke is located inside a *.jar library archive file |
|
|
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 Problem: Problem: |
Browser test for Java Applet, Note for Java applet, Note for Java Jar file, |
| 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.
|
|
| 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: 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 |
|
|
Step 6) Use the *.so file for the *.java file that you have created initially. This is for the system class loader Myclass |
|
| Step 7) Build and deploy the codes. | |
|
Reference: |
//Config.properties file content |
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[] args) throws IOException |
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 |
|
//example for using the
TcpIpServerService class import java.net.Socket; //Start the server, listening for incoming client
connection. while(true) |
|
| 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 /** |
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; |
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; |
|
//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 // [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.
[9] [10] [11]
[12] [13] [14] [15] [16]
|
These formatted java source codes are generated by java2html_50.zip
