Wednesday, January 18, 2012

When to use Java Native Interface (JNI) ?

Programming in Java is totally fun, especially, if you use it for general purposes. The term 'general purposes" is stated here as "the program that needs file, socket, web, gui operations" opposite to a special problem. That is, a special problem may be a scientific one which requires loops, array operations and basic operations. A program like this can be easily written in other languages.

Sometimes, we need other libraries which are not yet implemented for Java or some operations that perform some low level operations which are not handled by the JVM. For instance, a library written in C can not be directly used in Java. You have to either re-write it in Java or use the Java Native Interface (JNI).

But there is something worth to talk about. People generally think that a native function that called from Java must run faster than in Java. But it is not true. Yes, a native function (we use the term native for compiled codes) may run faster and via versa. The important point here is that Java can not directly perform a function call directly, that is, there is some preparation process needed.

To be clear, let me give an example. Suppose that we have a C++ function 'mean' which stands for calculating the arithmetic mean of a double array. We have also a function 'jmean' which is written in Java for the same purpose. Now, suppose that we have a double array with size of 1,000,000 and has values from 0.0 to 999,999.
The processes of passing this array reference to C++ and getting the calculated result costs 112 milliseconds. When I tried the same test for the function written in Java, I got the result of 10-12 milliseconds. It seems there is a significant performance difference between them!

In this example, the biggest amount of time is consumed by the calling preparation, not the calculation mean itself.

We can summarize those results as :
1) Calling a native method for millions times makes a significant performance loss.
2) Use JNI if you have to. Maybe, if it is performing a low level operation or converting the C code to Java is hard. For example accessing to LPT port is not possible in Java and you need to use JNI here.

and I can personally say that:
"An increase on performance depends on the job performed by the native method."

Finally, the old book, Essential JNI - Java Native Interface is a good book if you really interested in JNI. JNI is generally used for calling C/C++ functions from Java and accessing Java objects from C/C++. JNI also stands for "creating JVM's in C/C++" code and that means you can manipulate java programs as acting like the JVM itself.

JNI is in everyday Java life. JCurses library uses JNI for coloured console for the people who got bored using System.out.println. QJambi uses JNI for constructing a bridge between Java and Qt classes. Java's standard libraries such as AWT also bridges between native GUI API's and Java. Charva uses JNI for GUI'd text terminals. And, of cource, there are lots of examples on this.



Friday, January 6, 2012

Lets implement a simple Lisp Interpreter in Java

Edit 2015.03.20 : If you are really interested in implementing a LISP like language in Java, you can visit this, this and this

You are probably programing with C++, Java or .Net thingies but not Lisp. Why? Because it is the most beautiful language that human ever made :) Let me explain.

If you write in a programming language, you have to look and understand the interpreter's or compiler's principals. If you didn't do that yet, let me say, when you look inside an interpreter you will see a picture in which hundreds of objects being copied from one data structure to another called stacks. When you trace the interpreter, you will see nothing except those abstract data structures. The scene you will see is like a casino with hundreds of card dealers...

But when you program in Lisp, the interpreter exactly does what you write. There is no abstraction, no hacking. You will deal the cards in your fully controlled casino. Having knowledge about what the interpreter does is everything.

Lets look at the following Lisp expression

(+ 2 (+ 3 2))

which states that interpreter first will sum 2 and 3 and the gained number will be summed with 2. The result should be 7. How did we do that? Because of our primary school skills. Lets do that with a stupid machine that can only handle basic stack operations as in assembly language.

Suppose that we have a stack object and we are sequentially adding tokens into that stack. A token is defined as an atomic element of this expression. So our tokens are (, +, 2, (, +, 3, 2, ) and ) , respectively.

Now, take the first token and put it into the stack. Our stack is like that:


/


Lets add more elements until we encounter a closing parenthesis.


(+2(+32)

Again, suppose that, whenever we encounter a closing parenthesis, we collect some elements from the stack until we get an opening parenthesis, say that, we have now


(+32)

collected from the stack. Calculate this simple expression and put the result back to our stack. Since result of the sub expression (+ 3 2) is 5, our stack comes to shape of


(+25

We didn't finish reading the tokens yet. We have one more token to push into the stack.


(+25)

We encounter a closing parenthesis again and that means we have to handle the sub expression and put back the result to the stack. Since there is no sub expressions, we have the root expression at hand. Reading until having an opening parenthesis and performing calculations will give the result of 7 after all.

Note that, all we did here spans a 50 lines of Java class. I hope taking a glance at this code will help you to capture the whole story.



package smalllisp;

import java.util.Stack;

public class SmallLisp {

  Stack<String> stack;
  
  public SmallLisp(){
    String[] tokens = new String[]{"(","+","2","(","+","3","2",")",")"};
    stack = new Stack<String>();
    for (int i=0;i<tokens.length;i++){
      stack.push(tokens[i]);
      if(tokens[i].equals(")")) Interprete(); 
    }
  }
  
  public void Interprete(){
    String tok;
    Stack<String> callStack = new Stack<String>();
    tok = stack.pop(); /* This is the ) character */
    while(!(tok=stack.pop()).equals("(")){
      callStack.push(tok);
    }
    Call(callStack);
  }
  
  public void Call(Stack<String> callStack){
    String func = callStack.pop(); /* This is the operator or function */
    if(func.equals("+")) {
      double result = Plus(callStack);
      stack.push(String.valueOf(result));
    }
    //if(func.equals("-")) Minus(callStack);
  }
  
  public double Plus(Stack<String> callStack){
    double a = Double.parseDouble(callStack.pop());
    double b = Double.parseDouble(callStack.pop());
    System.out.println("Answer is "+(a+b));
    return(a+b);
  } 
  
  public static void main(String[] args) {
    new SmallLisp();
  }
}


Todo:
  • Implement the minus function yourself.
  • Implement the product function yourself.
Well done !

A Simple Qt Application Example using Qt Creator

Well, you are programming with C++ and you want to expand your programs with GUI components, Windows, Sockets, Threads, Timers and Processes. Since the standard C++ library does not include classes for those stuff, any C++ program needs external packages to cope with real world problems.

It is almost always a problem to find external libraries that provide platform independency. Java solves this problem with its standard API library which includes classes for threading, file operations, GUI stuff and networking. Qt does nearly the same thing. So, if you want to develop a program using a single framework, Qt is a good choice.

Although programming with Qt make people feel like programming in Java or any other "comfortable" language, do not forget that it is still C++. That means, you can be more relax in memory management but you are still face to face with the machine with your compiled code.

Qt is similar to Java as it is platform independent, that is, you will compile your source code in Windows, Linux and Mac and you will see the same running beautiful program.

If you are familiar with the Qt and you are seeking a framework to use in your C++ project, do not think any more and use it! And stop to read the remaining part of this text. If you don't know how to use it, follow the simplest Qt example in the world... Then have a Qt book and read it. You will feel comfortable with it after a month or two if you have ever programmed with Java or C++.

Yes, let's create a project. Download the Qt Creator from http://qt.nokia.com/products/ and install it. I suppose that you know how to install programs in your operating system. After a big installation progress, run the Qt Creator. You will see a window similar to this:


Then follow the menu "File >> New File or Project" and click it. A new window will be opened:


Select "Qt Widget Project >> Qt Gui Application" using the window then press "Choose".


Give a name for your project.



Select "Desktop" and click next.


Leave the class information as is and click next. When you learn how to program with Qt, you will need more than more window elements but a single one enough for our simple example.


Finally, we have a project which is ready to run. Unfortunately, it does nothing except showing an empty window. See your running empty form by typing CTRL + R key combination or click the menu "Build >> Run".


The panel on the left side shows our project configuration, .h (header), .cpp (C++ source) and gui (forms) files. You can simply activate by clicking on them. Lets click the "Forms >> mainwindow.ui" on the left side panel. 

Now, it seems our empty form is ready for designing. The left side panel now shows other GUI components which can be dragged and dropped on the empty form. Now find the Line Edit component under the "Input Widgets" group and drag & drop to the empty form. You can change its dimensions, name and other properties using the right side panels. But, leave it as is and find the push button component and create one on the form. 

We have now a filled form with a single textbox and a button. Since there is no action defined, when you run your program with the CTRL + R combination, you will see your form but push button does nothing when you click on it. Lets write something on the "text edit" when the push button is clicked. For those, we will add a code to mainwindow.h file. Select the mainwindow.h file and edit it like the following screenshot.


We added the code 

private slots:
    void pushbutton1_click();



in file mainwindow.h so we are able to define an action for the click event of the push button. Not that pushbutton1_click() is a function name which can be also selected as anything else. In Qt, we are controlling the user actions using a signaling mechanism. Every signal sender in Qt, defines SIGNAL 's. A signal catcher must define a SLOT for this. We want our code to catch the "clicking" signals from the push putton, so we defined a slot.

Now, select the mainwindow.cpp, which is the source code of our project and implement the function "pushbutton1_click()" which is defined in the corresponding header file.



void MainWindow::pushbutton1_click(){
    this->ui->lineEdit->setText("Qt Signals are easy");
}

We implemented the pushbutton1_click() in cpp file, which are defined in header file before. Now, we are quite ready because our program will put a "Qt Signals are easy" message on the this->ui->lineEdit object. Note that, lineEdit is the default name for this object and it is changeable by the user. Finally, we have to "link" the button's click action to MainWindow::pushbutton1_click() method. For that, edit the 



MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
}

to 

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    this->connect(this->ui->pushButton, SIGNAL(clicked()), this, SLOT(pushbutton1_click()));
}

So we have just connected the pushbutton's "clicked" signal to our pushbutton1_click() slot. That's all. Run the program.



After the compiling and running progress, click the push button and see the message on the text box.


SIGNAL  and SLOT mechanism is the most important thing in the Qt world to learn! Follow these steps to learn much:


  • Put a progress bar on the form. When we clicked to pushbutton, let the progressbar to show value of 50%
  • Create another pushbutton. When somebody clicks to pushbutton, show a message box containing a "Hello world!" text
  • Create a timer. Set the interval of timer to 1000 milliseconds (1 second). In each time the timer activated, show how many times the timer activated on the text box.
Read more books and tutorials and code something is not really meaningful. Qt is really easy to learn, especially, if you learned the SIGNAL & SLOT mechanism.

Good luck in your Qt life!




Sunday, December 4, 2011

Facebook Like Button Example With JQuery

Hi! We all got a Facebook account. As you remember, Facebook's got so much options that we can use, Like button, Chat, TimeLine etc.

In last article, I made mention of Jquery used within Facebook. Today, I'll show you one of'em. That is "like button".

As you know, when our friends share something, we can like it easily. When clicked the like button, data is saved without refresh. Because of this is JQuery&Ajax. Actually this example is not going to be like Facebook Like Button Module exactly, but, may be a good idea to do it for some of us. This things're so easy to do. We all need a database, a PHP page and a coding ajax page with ajax library, where is that complex?

Let's start it!

First, create your MYSQL Table;
CREATE TABLE `jquery_app`.`LikeButton` (
`ID` INT( 11 ) NOT NULL AUTO_INCREMENT PRIMARY KEY ,
`data` VARCHAR( 255 ) NOT NULL
)
You shall need this files:
  1. settings.php //database configurations
  2. jquery.js //your jquery code
  3. jquery library //you must include this file on index.php page
  4. match.php //your php code that you do like something and write database
  5. index.php //default page

index.php

This is facebook like button example. This is what i share! :)
< a href="#" id="like">Like < div id="whathappened"> //We see total clicked like button
< /div>
< div id="whathappening"> //We see what happening now
< /div>

When click the link, sending query to jquery.js page. After that jquery starts ajax method and searchs match.php page for adding +1.

jquery.js
// JavaScript Document
$(document).ready(function() {
 $('#like').click(function() {
  $('#whathappening').fadeIn(1000);
  var wait="Adding..";
  $.ajax({
   cache:false,
   async:false,
   url:'match.php',
   success:function(inc) {
    $('#whathappened').html(inc);
    $('#whathappening').html(wait);
    $('#whathappening').fadeOut(1000);
   }
  });
 });
});

When id=like click, data'll been added to database. If you ask how to add this, you should analyze the page is shown below.

match.php

 include("settings.php");
 //adding data
 $random=rand(0,99999999);
 $ekle=mysql_query("INSERT INTO LikeButton(data) values('$random')");
 //how many data we got
 //with the data we've just added
 $show=mysql_query("select * from LikeButton");
 $total=mysql_num_rows($show); //Getting total liked
 echo "Total: ".$total; //Print total liked.

What you see here, all php code. We include settings.php page for connection database. We get total and add +1 to this.

settings.php

 $conn=mysql_connect("localhost", "username", "password") or die("error1");
 mysql_query("SET NAMES 'utf8'") or die("error2");
 mysql_select_db("jquery_applications",$conn);
 error_reporting(0);
 ini_set('display_errors','Off');
 error_reporting(E_ALL); 

That's it! You've just done Facebook like module. If you want to see how to work this, you can visit the web site for demo.
Module view
When "Like" link click

Saturday, December 3, 2011

Cursed ad-hoc networking problem on Android


It is stil a problem to connect my Samsung Galaxy Tab P-1010 (Wi-fi only) to Internet
through my cell phone. Since Google does not do anything about this, people individually
seek for a solution for this. I have tried many compiled wpa_supplicant.so files on my device,
unfortunately, the only picture that I saw was a tablet computer without wi-fi support.

I have a new idea about this. I know it is not an elegant solution like debugging the source code of wpa_supplicant
and compile it for several devices.  But this is worth to share.

Firstly, suppose that we have an Android device with Wi-fi feature only and call it "Android Device". And suppose that we have a Java installed cell phone (it would be an S6 installed Nokia or Blackberry or an android cell-phone), and we will call it "Cell Phone". The development steps
for my solution are given below:

(Step 1) Implement a tiny http proxy for the Android Device. Suppose that, it listens from the port 8088.
(Step 2) Set the proxy settings on the web browser of Android Device, "localhost" for host and "8088" for port.
(Step 3) Implement a tiny JavaME application, which accepts URL's that sent by (Step 1) through a bluetooth connection, and downloads the
content of the accepted URL's and sends the content using the same bluetooth connection to the http proxy defined in (Step 1).


Now, we can expand those steps for our idea. Suppose that, the http proxy given in (Step 1) is connected to the JavaME application (Step 3) with bluetooth. There are many bluetooth protocols but I think (but I am not really sure about that)
the rfcomm type connection is the common type in both the JavaME and Android.

Whenever the proxy in (Step 1) accepts an URL, it sends this request to the JavaME application using the bluetooth connection.
The application defined in (Step 3) has an internet data plan, so it downloads the content and sends them to the proxy in (Step 1). 

Ok, not the best way, but it seems it would work.

Maybe, somebody wants to implement this.