Friday, June 24, 2011

Time to change Java main method - Paper

Cairo, Egypt On May, 2011

I. Abstract
Main method in Java (which is inherited from C) have the String[] as input parameter to the main method, now it is time to enforce Object Oriented in this method as well, and enable Object passing as a parameters[1]
In the same time, class can't have more than one main method, so we enabled more than one main method and enabled the dynamic selection of it based on the parameter list.
We have tried some approaches to enable passing objects to the main method using the Java language [2].
We will see how we will use the JSON representation of the object in this paper and pass-by-content or pass-by-representation new methodology in passing objects as parameters.
We proposed some of the new signatures to the main method and passing the arguments as (Object[] args) , (CustomClass[] myData) and (CustomClass[] myData, String[] args).

II. Introduction
Java and all command line parametrized languages accept only String array of arguments which make sense as our ability to call using command line gives us the ability to enter text that could be represented by String object in Java or char* in C.
This is how we used to have a method like[3]:

public static void main (String[] args) {
for (String s: args) {

java Echo Drink Hot Java
If we enclosed them with double quotation “, this will result in a single parameter:
java Echo "Drink Hot Java"
Drink Hot Java

If we need to pass integer value, we need to use parsing method to obtain the numeric value from it:
try {
firstArg = Integer.parseInt(args[0]);
} catch (NumberFormatException e) {
System.err.println("Argument must be an integer");

What if we need to pass a whole object as an argument to the class?
There are some solutions for this, including 1) passing the Object fields as a separate parameters then in our main method construct this Object and fill its fields. 2) Use Java serialization and save the object to the file system and pass the filename to it to deserialize it back to an object [4].

// Serialize the original class object
FileOutputStream fo = new FileOutputStream("cde.tmp");
ObjectOutputStream so = new ObjectOutputStream(fo);
// Deserialize in to new class object
FileInputStream fi = new FileInputStream("cde.tmp");
ObjectInputStream si = new ObjectInputStream(fi);
cnew = (CustomDataExample) si.readObject();

Our proposed solution is to use JSON as a passing String represents this object.

JSON (JavaScript Object Notation) is a lightweight data-interchange format. It is easy for humans to read and write. It is easy for machines to parse and generate. It is based on a subset of the JavaScript Programming Language, Standard ECMA-262 3rd Edition - December 1999.[5]
JSON is a text format that is completely language independent but uses conventions that are familiar to programmers of the C-family of languages, including C, C++, C#, Java, JavaScript, Perl, Python, and many others. These properties make JSON an ideal data-interchange language.[5]

JSON is built on two structures:
* A collection of name/value pairs. In various languages, this is realized as an object, record, struct, dictionary, hash table, keyed list, or associative array.
* An ordered list of values. In most languages, this is realized as an array, vector, list, or sequence.
We have selected Google JSON named Gson which is a Java library that can be used to convert Java Objects into their JSON representation.[6]
It can also be used to convert a JSON string to an equivalent Java object. Gson can work with arbitrary Java objects including pre-existing objects that you do not have source-code of.[6]
There are a few open-source projects that can convert Java objects to JSON. However, most of them require that you place Java annotations in your classes something that you can not do if you do not have access to the source-code. Most also do not fully support the use of Java Generics. Gson considers both of these as very important design goals. [6]

This is example of JSON object:
"firstName": "John",
"lastName": "Smith",
"age": 25,
"streetAddress": "21 2nd Street",
"city": "New York",
"state": "NY",
"postalCode": "10021"

III. New main method signature
Now let's see how we can build a new main method signature, our target is to have the main method public static void main(Object[] args) instead of public static void main (String[] args)

public static void main(String[] args) {
if(args!=null && args.length>0){
Vector parametersObjects=new Vector();
for(int i=0;i<args.length;i++){
if(args[i].startsWith("{") && args[i].endsWith("}")){
args[i]=args[i].replaceAll("~", "\"");
Object[] params=null;
We will back to the line (args[i]=args[i].replaceAll("~", "\"");) later on to explain why we have added it.
Our main method will utilize the parameters now as objects:
public static void main(Object[] args) {
if(args!=null && args.length>0){
for(int i=0;i<args.length;i++){
if(args[i] instanceof EmpData){

If we can inject the code in main(String[] args) into the JVM we would only have the ability to code any one of these 2 methods with String[] and Object[] according to our needs.
Now we can call our class and send mixed parameters of String and JSON objects:

java -jar JSON-Param.jar {"id":0,"name":"Osama Oransa","location":"Cairo, Egypt","isSupported":false}

Now we are facing the following problems:
1. Spaces inside the JSON object string representation.
2. Double quotes inside the parameter which will be removed automatically from the arguments
We have fixed this by ensuring no spaces inside the JSON object string representation except inside the literal values of string field(s), this literal values are already surrounded by double quotes so it won't break the parameter so this will fix the 1st issue, 2nd issue will need a special parameter to proceed every double quote, in this research we have used the symbol ~.

java -jar JSON-Param.jar {~"id~":0,~"name~":~"Osama Oransa~",~"location~":~"Cairo, Egypt~",~"isSupported~":false}

This is why we have added this line in the main method to construct our JSON object correctly:
args[i]=args[i].replaceAll("~", "\"");

To construct JSON object representation like what we have modified:
String jSonAsParameter=new Gson().toJson(object).replaceAll("\"","~\"");

Of course this has a drawback of preventing us to use ~ symbol inside the string literal values so we need to search for a better symbol.

Another way to fix this is to add all the parameters into a single String then start to parse it and only respect String if there is no current JSON object is opened (i.e. no matched closing bracket reached yet), this way is simple and granted to work but it need to be implemented from the JVM as it will need complex logic and will consume time in processing.

IV. Pass-by-Content
According to Sebesta in his book Concepts.of.Programing.Languages passing parameters in programming languages take different types like pass-by-value, pass-by-result, pass-by-value-result, pass-by-reference and pass-by-name [7].

If we looked at what we did so far, we have pass the object content itself so this is some sort of pass-by-value but we can name it pass-by-content or pass-by-representation as we didn't pass the object instead we passed a content to a new object that would be created and constructed from this content.

To fully support JSON in Java as content representation we can add a new method toJson() that produce JSON representation of this class object, in the same time we need to add a static method that accept String of JSON representation and return the object that represents these content.

public class EmpData {
private int id;
private String name;
private String location;
private boolean isSupported;
public String toJson(){
return new Gson().toJson(this);
public static EmpData getInstanceFromJson(String jSonString){
return (EmpData)new Gson().fromJson(jSonString, EmpData.class);

......setters and getters of instance variables

V. Many main methods concept
Now we can have one main method to start the Java application regardless of its signature String[], Object[] or mixed String[], Object[] or even direct child of Object like EmpData[] and the JVM is responsible for invoking the correct method or we can have many main methods and one is selected upon parameter types.
This is similar to have more than one door per application and selection of the door is by the keys given.
If we modified our code a little we can have something like this:
public static void main(String[] args) {
if(args!=null && args.length>0){
Vector parametersObjects=new Vector();
Vector<EmpData> parametersEmpData=new Vector<EmpData>();
Vector<String> parametersString=new Vector<String>();
for(int i=0;i<args.length;i++){
if(args[i].startsWith("{") && args[i].endsWith("}")){
args[i]=args[i].replaceAll("~", "\"");
//System.out.println("Param "+i+" ="+args[i]);
EmpData param=EmpData.getInstanceFromJson(args[i]);
EmpData[] empParams=null;
String[] stringParams=null;
Object[] objectParams=null;
empParams=parametersEmpData.toArray(new EmpData[0]);
stringParams=parametersString.toArray(new String[0]);
if(empParams!=null && stringParams!=null){
If no main method can selected, compilation ambiguity exception must be detected.

VI. Future work
Incorporate parameters detection and main method selection into the Java Development Kit (JDK) and Java Virtual Machine (JVM), this will reduce the effort needed by the programmer and will enhance the speed as well.
Adding toJson() and getInstanceFromJson(String jSonString) methods could be added to the Object class to be inherited by all the objects.

VII. References
[1] (Retrieved on 1st of May,2011)
[2] (Retrieved on 1st of May,2011)
[3] on 1st of May,2011)
[4] on 1st of May,2011)
[5] on 1st of May,2011)
[6] (Retrieved on 1st of May,2011)
[7] Sebesta.R.W.Concepts.of.Programing.Languages.7th.ED-ISBN_0321330250

Wednesday, June 22, 2011

Break with some non-technical ideas

Here is some trivial ideas that can be done with no cost:

1) Switch off the car lamps after configurable time with engine switched off , this could be already in some modern cars but we need a small device to attach it in old cars so we don't have run out of batteries in these cars when we forget the car lights.

User must be able to enforce it to open lights again..(reset the timer).

2) Shoes could have shoes enabler with it that have elastic withdraw so one could pull it and wear the shoes then leave it to return by the elasticity power.

3) Mobile should have secret wallet application hold the owner details, and password is given to him after shipping , mobile is activated on particular SIM card after enter this password (or by one item of these details as SIM_ENABLE_PASSWORD), no SIM can work without this info and any OS installation must have this password or mobile OS is not working.

4) Car tires, could be double layered; a nucleus that is connected with one-way valve to the external layer surrounding this nucleus this could reduce the exploded tires accidents.


About Interactive4J :

I have created this open source project aiming to provide simple easy APIs for Java developers to use interactive abilities in their Java Applications like speech recognition, handwriting recognition, use of web cam , sound record/play, decision trees , text to speech and many others, all with very simple APIs without any needed configurations or XML files,...etc. only simple method APIs.

Without further much enhancements to user experience in the standalone applications, users will prefer the web application for the huge features they provide, this open source enrich the user experience in such applications.

In the same time most of the developers will need to implement the typical and direct scenario in most of the supported features , Interactive4J provides this, in few cases developers need to customize the functionality and they will find project source code available so they can manipulate and use it directly as a reference implementation to the needed functionality.

This is to say moving these areas into easy usage will increase the interactivity of the application and the needs/dependency on them; which will push them more and more,so Interactive4J "When the easy way is the best way to do something!"

Features :

* Easy and simple APIs for developer with any experience to use them.
* Aim for Interactivity of Java Applications (for better user experience)
* Used for NextGen Java Application with higher user interactivity, if we didn't go for such enhancements in user experience , desktop application will fade soon in competition with web apps.
* Use some other open source projects and wrap them in a very simple way.
* Have a nice simple demo to show the supported features.
* Each functionality like text to speech , speech recongnition ,etc. have a very straightforward simple methods to use.
* Human abilites is the main purpose of the 1st release as see, hear , talk , translate, listen , recognize and think.
* Move some areas from scientific research into practical usage.
* Enhance the usage of Java in Educational puropose.
* Use the Standards whenever exist.
* Uses Sphinx-4 is a state-of-the-art speech recognition system written entirely in the JavaTM programming language
* Uses FreeTTS library for text to speech.
* Uses the library LTI-CIVIL which is part of FMJ (Freedom for Media in Java) for portability of WebCam usage.
* Uses Languages translation via open source "google-api-translate-java" for most possible interactivity with different users.
* Define a new JTextField component "JITextField" having JTextField + JButton for translation + JButton for text to speech
* Provides Genetic Algorithm and Decision Tree in a very simple and generic way for easy usage.
* Use Google Gson for JSON parsing and constructions.
* Use JMF (Java Media Framework) for creating movies from images and to play audio/video from the supported audio/video formats in JMF, click here to check them.

Releases :
Currently 2 separate releases one needs JMF support and one do not requires JMF support.

SourceForge URL :

How to Use it?

The demo represents some of the existing functionality in Interactive4J where you can simple initialize the feature you need and use it in a simple way..

Here is some of the important functionality in this release version, you must go through the Java-docs for more details about other not-listed features..

1) Text To Speech
The demo represents 2 ways of using this feature..

-Say it: where you pass the string you want the engine to say.
-Read it: where you do further manipulation to read word by word and highlight the current word.

The APIs is very simple : static method that take the string to say..No configuration files or any thing else!


2) Speech Recognition

Pass String[] with the speech recognition words! no thing else!

3 method control speech recognition:
- JHVoiceRecUtils speakUtils = new JHVoiceRecUtils(this,currentConfigPath);
To configure it to start (you should use the current configuration files without modification, but you can still modify them)
This = represents a class that implement the VoiceRecognitionListener where you get the recognized words in a method : setVoiceResult(String recognized)
- speakUtils.StartVoiceRecognition(commands);
Where you start the recongnition , commands here is a string[] contain all the words/letters you'd like to recognize.
- speakUtils.StopVoiceRecognition();
To stop the voice recognition.

3) Handwriting recognition

Construct the hand writing recognition with numbers or letter to be used and no thing else!

- handwriting = new JHHandWritingUtils(jPanel1, this,JHHandWritingUtils.MODE_NUMBERS,currentConfigPath);
You construct the handwriting utils with the panel you want the user to use it and listener of the results, plus mode (either number, capital letters or small letter), and finally the current configuration path (you shouldn't modify the given configurations.
- handwriting.startHandWritint();
To start the handwriting recognition..
- handwriting.stopHandWriting();
-To stop it

*So 3 modes is supported:
2-Capital letters
3-Small letters

4) Record and play sounds/voices
3 methods:
- JHRecordingUtil recordingUtil=new JHRecordingUtil(maxSeconds);
construct the recorder with max seconds allowed.
- recordingUtil.startRecording("/recordSample.wav", 22000);
To start recording in a give file with sampling rate (this is configured being depend on the needed quality and it affect the recorded file size)

To play it : use the method:"/recordSample.wav",1);
1 = one time only.
You have also stop method to stop it.

This is typically adapted for voice chat where you record a snapshot and send it and play the received snap voice and repeat the cycle..

5) Translate Text
One simple method provided to do the translation:
String trans = JHTranslateUtil.doTranslate(jTextArea1.getText(), Language.ENGLISH, Language.ARABIC);

Where you specify the text to translate and source/destination languages.

In the demo click on translate button translate text to Arabic and the 2nd click restore the original text.

6) Screen Capture
Only 1 simple method:

This facilitate creating desktop recording applications, if we conjugate it with voice/sound recording we can do such application in no time.

7) Web Camera Capture

Very easy and simple way encapsulate all complex logic behind to simple call with image file name to store the captured image into!

Simple single method you just need to specify the file name and the listener of this operation CaptureListener ..
webCam=new JHCaptureUtil(this, "/myWebCamPic.jpg");

8) Web Camera Video Capture
This is actually a stream of jpg files displayed as if a video , this is the better approach for video chatting where you can send each picture separately, you can still construct a video file from these files.
webCam=new JHCaptureUtil(this, "/myWebCamPic.jpg");

9) Decision Tree
Use a simple way to design a decision tree and take the response to control whatever you need..
Here we used a game with decision tree to decided the PC movements..

10) Genetic Algorithm
Simple easy way to use the genetic algorithm in search problems in easy efficient way...prepare your problem and do search using 1 method!

// init population
Individual[] populations = new Individual[popSize];
for (int i = 0; i < popSize; i++) {
populations[i] = new Individual(numberOfGenes);

// construct the evaluation function..
GeneticEvaluator geneticEvaluator = new GeneticEvaluator() {
public int evaluate(Individual individual) {
int fitness = 0;
return fitness;
public int evaluateSecondLevel(Individual individual) {
int fitness = 0;
return fitness;

//do genetic search now to get the best setting the configuration object with all details...
GeneticConfiguration config=new GeneticConfiguration();
Individual bestIndiv = JHGeneticUtil.executeJHGeneticUtil(config);

NOTE: this previous example uses multi-fitness functions where 2nd one is used after 400 iteration , this is not the typical genetic algorithm where you can switch this off by set it to false for the standard genetic algorithm implementation.

11) New Suggested JTextField style
This composed of JTextField plus 2 buttons; one for translation and one for text to speech..

12) JSON Utilities
Here you can convert from JSON into Object and vice versa using easily APIs provided by Google Gson.
Only you call toJson() and fromJson() according to conversion type.

13) Play Video files and Audio files
Built on JMF, play video/audio in the Swing easily by a single method:

JHPlayer createPlayer(JPanel pf, String media, ControllerListener listener)

14) Convert Series of images into movies

Build on JMF, , single method to create .mov file!

JHMovieMaker.createMovie(String movieName, int width , int height, Vector images, int frameRate)

For other features and functionality, go through the java-docs of the project.

Possible Applications and usages:

-Interactive Java Applications like Educational applications.
-Translation and multi-lingual applications.
-Book Readers and translators.
-Video chat applications.
-Screen capture software (outcome images or video)
-Command based applications like speech commands & handwriting; Interactive Browser is an example.
-AI applications.
-Monitoring applications like my home monitor application or Hidden parent eye application.

Some of these applications already implemented and you can find direct links @my blog for them.

Friday, June 17, 2011

Mobile Game Wallet

Game Wallet represents the normal incremental development for my previously known "Free Secure Wallet" , this time with more features towards the goal of "Your data is safe and secure"..

It use Java for Mobile , soon it will be available on all mobile platforms - once i have time to do that :)

Here is the old features that already exist in the previous version..

1) Password to access the application.
2) 3-trial then the application closed and you need to re-lunch it to try again.
3) Your entries encrypted against your password.
4) Your login session expire after configurable time of login (default 30 min), so if you forget the application running, no one can use it.
5) Forced password can be set, to be used if you are forced to open the application and application will open without any of your entries.
6) You can sort the entries.
7) You can edit/delete the entries.
8) Support of Arabic/English interface.
9) You can export your entries (with the current password) to the file system, so you can:
-Store them.
-Re-import them in case of mobile crashed or if you got a new mobile with the application installed.

In this version a nice features added:

1.Separate the notes from phones into 2 different lists , where call button appear in case of phone lists.
2.Increase the size of entries fields.
3.Game interface to hide the application behind.
-Game Icon for the application.
-Named "Game Wallet" instead of "Free Secure Wallet".
-After the initial lunch of the application, subsequent lunches display a nice game appear for play, if you want to go to the application you need to press on # or *

Hope you enjoy this version :)

Click here to Download it from Mobango and here to download it from GetJar.

Sunday, June 5, 2011

Secure End-To-End Chat

This open source project utilizes Diffie–Hellman Key exchange between 2 peers (one as server and the 2nd is client).

It uses RMI technology to connect both peers.
It support chat messages , emoticons and file transfer, with nice liquid look and feel.

Key Exchange using Diffie–Hellman can be done per message or per session as needed.
(password fields kept clear while it can be Password fields for clarity.

Click Here to go to the project on SourceForge.

To read about Diffie–Hellman Key exchange click Here.