Wednesday, 13 February 2013

Linking JavaFX with Web Application


Today I will talk about embedding JavaFX application into a web page and to link Web Page and Java FX application via Java Script. I will take example of sample music player which I build in JavaFX. I will try to trigger some action in JavaFX application (e.g. adding a song to the Media Player playlist). We need to follow these simple steps in order to accomplish the task.
I will be using NetBeans IDE 7.2.1 for this task because packaging of JavaFX application is very easy in NetBeans IDE i.e. you do not need to bother about any Ant task write-ups.

  1.        First of all you need to Code your JavaFX application. Its tutorials are very easily available.
  2.     Change the Configuration of Project:
     Next step is to change the runtime configuration of your Project. For an instance the name of my music application project is “Music Play”.
                                                        Right click your Project folder in NetBeans > Set Configuration > Run_in_Browser. Clean and Build your project (Right Click project folder > Clean and Build @Run_in_Browser).  Run the project. Your default browser will show the embedded JavaFX application.       

3. Copy the generated Code into your own webpage
    Browse to the generated webpage. By default its name will be same as that of your JavaFX application.  Default path of the generated webpage is                                                                                           C:\path to\your\Documents\NetBeansProjects\MusicPlay\dist  
Open the MyMusic.html with some editor such as Notepad or more suitable DreamWeaver.
Script will be something like this.
                <script>
    function launchApplication(jnlpfile) {
        dtjava.launch(            {
                url : 'MusicPlay.jnlp'
 jnlp_content: 'PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0idXRmLT
giPz4NCjxqbmxwIHNwZWM9IjEuMCIgeG1sbnM6amZ4PSJodHRwOi8vamF2YWZ4
LmNvbSIgaHJlZj0iTXVzaWNQbGF5LmpubHAiPg0KICA8aW5mb3JtYXRpb24+DQ
ogICAgPHRpdGxlPk11c2ljUGxheTwvdGl0bGU+DQogI
CAgPHZlbmRvcj5Nb2hpdDwvdmVuZG9yPg0KICAgIDxkZXNjcmlwdGlvbj5TYW1
wbGUgSmF2YUZYIDIuMCBhcHBsaWNhdGlvbi48L2Rlc2NyaXB0aW9uPg0KICAgI
DxvZmZsaW5lLWFsbG93ZWQvPg0KICA8L2luZm9ybWHBhcmFtIG5hbWU9InJlcX
VpcmVkRlhW
ZXJzaW9uIiB2YWx1ZT0iMi4wKyIvPg0KICA8L2FwcGxldC1kZXNjPg0KICA8am
Z4OmphdmFmeC1kZXNjICB3aWR0aD0iNTAwIiBoZWlnaHQ9IjUwMCIgbWFpbi1j
bGFzcz0
ibXVzaWNwbGF5Lk11c2ljUGxheSIgIG5hbWU9Ik11c2ljUGxheSIgLz4NCiAgP
HVwZGF0ZSBjaGVjaz0iYmFja2dyb3VuZCIvPg0KPC9qbmxwPg0K'
            },
            {
                javafx : '2.0+'
            },
            {}
        );
        return false;
    }
</script>

<script>
    function javafxEmbed() {
        dtjava.embed(
            {
                url : 'MusicPlay.jnlp',
                placeholder : 'javafx-app-placeholder',
                width : 500,
                height : 500,
                jnlp_content : 'PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0idXRmLTgiPz4NCjxqbmxw
IHNwZWM9IjEuMCIgeG1sbnM6amZ4PSJodHRwOi8vamF2YWZ4LmNvbSIgaHJlZ
j0iTXVzaWNQbGF5LmpubHAiPg0KICA8aW5mb3JtYXRpb24+DQogICAgPHRpdG
xlPk11c2ljUGxheTwvdGl0bGU+DQogICAgPHZlbmRv
cj5Nb2hpdDwvdmVuZG9yPg0KICAgIDxkZXNjcmlwdGlvbj5TYW1wbGUgSmF2Y
UZYIDIuMCBhcHBsaWNhdGlvbi48L2Rlc2NyaXB0aW9uPg0KICAgIDxvZmZsaW
5lLWFsbG93ZWQvPg0KICA8L2luZm9ybWF0aW9uPg0KICA8cmVzb3VyY2VzPg0
KICAgIDxqZng6amF2Y
WZ4LXJ1bnRpbWUgdmVyc2lvbj0iMi4wKyIgaHJlZj0iaHR0cDovL2phdmFkbC
5zdW4uY29tL3dlYmFwcHMvZG93bmxvYWQvR2V0RmlsZS9qYXZhZngtbGF0ZXN
0L3dpbmRvd3MtaT
U4Ni9qYXZhZngyLmpubHAiLz4NCiAgPC9yZXNvdXJjZXM+DQogIDxyZXNvdXJ
jZXM+DQogICAgPGoyc2UgdmVyc2lvbj0iMS42KyIgaHJlZj0iaHR0cDovL2ph
dmEuc3VuLmNvbS9wcm
9kdWN0cy9hdXRvZGwvajJzZSIvPg0KICAgIDxqYXIgaHJlZj0iTXVzaWNQbGF
5LmphciIgc2l6ZT0iMzQzNjEiIGRvd25sb2FkPSJlYWdlciIgLz4NCiAgPC9y
ZXNvdXJjZXM+DQogIDxhcHBsZXQtZGVzYyAgd2lkdGg9IjUwMCIgaGVpZ2h0P
SI1MDAiIG1haW4tY2xhc3M9I
mNvbS5qYXZhZngubWFpbi5Ob0phdmFGWEZhbGxiYWNrIiAgbmFtZT0iTXVzaW
NQbGF5IiA+DQogICAgPHBhcmFtIG5hbWU9InJlcXVpcmVkRlhWZXJzaW9uIiB
2YWx1ZT0iMi4wKyIvPg0K
ICA8L2FwcGxldC1kZXNjPg0KICA8amZ4OmphdmFmeC1kZXNjICB3aWR0aD0iN
TAwIiBoZWlnaHQ9IjUwMCIgbWFpbi1jbGFzcz0ibXVzaWNwbGF5Lk11c2ljUG
xheSIgIG5hbWU9Ik11
c2ljUGxheSIgLz4NCiAgPHVwZGF0ZSBjaGVjaz0iYmFja2dyb3VuZCIvPg0KP
C9qbmxwPg0K'
            },
            {
                javafx : '2.0+'
            },
            {}
        );
    }
    <!-- Embed FX application into web page once page is loaded -->
    dtjava.addOnloadCallback(javafxEmbed);
</script>
For proper working your webpage must be in the same directory as is your jnlp and jar files other wise you need to configure url in above script.
It is also recommended to import the script at http://java.com/js/dtjava.js

4.       Here our music application needs to access the directory for reading the mp3 file so we need to provide appropriate rights to your application this can be done as follows.
Run your Notepad with administrator account. Open your Java Policy File. It is found at
C:\Program Files\Java\jre7\lib\security
Filename is java.policy
Append following lines to this file
grant
 {
permission java.util.PropertyPermission "*", "read";
permission java.io.FilePermission "<<ALL FILES>>", "read";
permission java.lang.RuntimePermission "stopThread";
permission java.lang.RuntimePermission "modifyThreadGroup";
permission java.lang.RuntimePermission "modifyThread";
permission java.net.SocketPermission "*", "connect,accept,resolve";
};
You also need to give RuntimePermission to Java so that your application can have permission to access the web pages. So you also need to add
grant
{
                permission java.lang.RuntimePermission "*";
}
5.       Now you need to have an object of  JSObject class in your FX application. It can be done as follows:
JSObject jsObject =  getHostServices().getWebContext();
Now you need to set  a named member of a JavaScript object.
This is done as follows:
jsObject.setMember("java", mediaControl);
Here java is the alias name you will use in your javascript code and mediaControl  is object of class whose public member functions you want to call through java page.
6.       JavaScript Code
Make JavaScript function where you can call public members of registered members. In our case registered member is mediaControl. We call its member method as follows:
<script>
function addSongs()
{
               
                var abc=java.addSong('Jaane Kaise','K.K.','Raqeeb','http://localhost/songs/jaane_kaise.mp3');
               
}
</script>
Now you can use this function anywhere you want.
When this function is called then it will in turn call addSong() method of mediaControl object  in Java FX application. This is how you can link a web page and JavaFX application.
Hope you got what I wanted to convey. All your queries and suggestions are welcome in comments section.

Friday, 26 October 2012

Difference between C++ and Java

This is the 5th post in "Difference between C++ and Java" series.
In this post we will discuss about the array initialization and declaration in two languages.
  1. Array Declaration
Statement
We need to define the size of array in C++ but not in case of Java at the time of array declaration.
When we declare an array in C++, we need to set the size of array in the same statement only.In C++, there is a concept of pointers, therefore we can say that array in C++ is collection of similar data-items(same data-type) stored at contiguous memory locations. But in case of Java, there is no access to pointers or memory addresses, therefore from a programmer's perspective Java arrays are just a collection of similar data-items. Moreover in case of Java, arrays are considered just like objects of any class. Hence, we can initialize them at some later time. Java arrays are just treated as special kind of objects(for simplification,actually they are reference variables explained in later posts), hence we can assign the size at some later stage as shown in the example below.
  • Java
int arr[];
//some other code
arr=new int[2];//size is assigned
//some other code
arr[0]=12;arr[1]=45;//manipulating array values

Similar code in C++ will give a compilation error. In C++, we have only two options, either give the arrays size or intialize the array using curly braces as shown in the example below.

  • C++
int a[4];//assign the array size
//some other code
int b[]={1,2,3};//initialize the array in same line
//some other code
a[3]=12;//manipulate the first array
      Moreover, in Java if we write array size along with object name inside square brackets as we do in C++, then we get a compile time error.
 2.  Default Values in Array 
Statement
Default values in C++ array elements is a garbage value, but in Java all numerical data-elements are initialized to 0 and Objects(reference variables) are initialized to a null value. 
C++ compiler does not take any overhead to initialize the values of array elements by itself. Therefore, initially, a garbage value(unpredictable value) is assigned to each array elements.
Java takes the things differently. In Java, initial value is 0 for integers, 0.0 for double, 0.0f for float, false for boolean and null for objects of the classes.
Following code snippets clarify the same.
  • Java
 int a[]=new int[2];
 for(int i=0;i<a.length;i++)
    System.out.println(a[i]);
 Output for above snippet

0
0
  • C++
int a[4];//assign the array size
for(int i=0;i<4;i++)
{
    cout<<a[i]<<endl;
}
Output for above snippet
4247764
4237328
4261536
163
3. Array Length/Array Size
Statement
In Java , array variable keeps the track of current array size or array length(length attribute) but in C++  we need to consider the change in array size by our variables.   While traversing the array for input or output of the array, often we need to find out the number of loop runs. For finding the number of loop runs we need array size. Programmer needs to keep the track of this value and update this value when we re-initialize array in C++. 
       But in case of Java, as I have already told that array is considered just like an object. In Java 'length' attribute of array variable automatically stores and update the value of array size/ array length. This length variable is always of the int type irrespective of the type of array. Programmer cannot change its value as it is marked final by the JVM. Hence, a lot of programming effort is saved in programs with intense use of arrays. When the array is re-initialized, then the value of the length attribute is automatically changed by the JVM.
4. Jagged Arrays
Statement
We cannot have jagged arrays in C++ but we can have them in Java, hence only the required memory is used. 
 In C++, we have two dimensional arrays. The problem is that we can only have rectangular arrays.
Consider the situation, there is a company with 3 departments and we need to store salaries of the members of these departments. Suppose there are 3,8,2 members respectively in these groups. We can think of storing these values in a two dimensional array with size 8X3. Therefore, we require 8X3=24 integer elements. But we require only 3+8+2=13 elements. Hence we are wasting 24-13=11 elements of memory. C++ does not allow each of the element of a two-D array separately. Java provides Jagged array in such a case. We can have following code snippet for the same example.
  • Java
int salary[][]=new int[3][];
salary[0]=new int[3]; // first department
//store salary of dept 1
 salary[1]=new int[8];// second department
 //store salary of dept 2
 salary[2]=new int[2];// third department
 //store salary of dept 3
We can re-initialize the individual elements, independent of each other.
Thanks all for your time. We will continue with 'Difference between C++ and Java' series in next post. Any queries and suggestions are invited in comments.

Saturday, 20 October 2012

Difference between C++ and Java

This is the 4th post in "Difference between C++ and Java" series.
Use of 'break' and 'continue' statement
Statement
'break' and 'continue' statements in Java can have labels and they can be used to 'break' out or 'continue' with nested loops.
Break statement is normally used, to exit the loop, when certain condition becomes true. Along with the keyword 'break', we can also specify that which loop must a program exit.
Example,
  • Java
int i=0;
System.out.println("Before the loop");
out:
for(i=1;i<=5;i++)
{
if(i==3)
break out;//specify the label of loop
System.out.println("Hello "+i);
}
System.out.println("Out of the loop now");
Output of the above snippet
Before the loop
Hello 1
Hello2
Out of the loop now
This was similar to what we did in C++.

Now,Consider the code
for(int i=1;i<=3;i++)   // outer loop
{
    for(int j=1;j<=3;j++) // inner loop
     {
        System.out.println("Hello "+j);
        break;// want to break out of outer loop
     }
}
 In this case, we are using multiple loops.In C++, we were only able to exit the inner loop by using break statement in inner  loop, but in Java, we can also exit the outer loop using break statement in inner loop. But  we need to mention label for the loop involves. Here label just acts as a bookmark. Now consider the code.


  • Java

int i=0;
System.out.println("Before the outer loop");
out:
for(i=1;i<=5;i++)
{
System.out.println("Inside outer loop");
System.out.println("Before inner loop");
inner:
        for(int j=1;j<=3;j++)
{
if(j==3)
break out;
System.out.println("Hello "+"i="+i+" j="+j);
}
System.out.println("After of inner loop");
}
System.out.println("After  outer loop ");
Output of above code snippet

Before the outer loop
Inside outer loop
Before inner loop
Hello i=1 j=1
Hello i=1 j=2
After  outer loop 
The problem has been eradicated by the use of labels analogous to bookmarks. Inside the inner loop we have used the label outer inside the inner loop to instruct the JVM (run-time environment) that from which loop control should break.
In C++, we can achieve similar effect by the use of flags as shown in the code below.
  • C++
int i=0;
int flag=0;
cout<<"Before the outer loop"<<endl;
for(i=1;i<=5;i++) //Outer Loop
{
cout<<"Inside outer loop"<<endl;
cout<<"Before inner loop"<<endl;
for(int j=1;j<=3;j++) //Inner Loop
{
if(j==3)
{
                  flag=1;
                  break;
                }
cout<<"Hello i="<<i<<" j="<<j<<endl;
}
if(flag==1)
          break;
cout<<"After of inner loop"<<endl;
}
cout<<"After  outer loop "<<endl;
Output of this code is same as above code. Here we have achieve the same effect but this code is obviously inefficient as compared to code in Java. This is because here we are checking the flag each time the body of outer loop is executed.
We use 'continue' statement when we want to make a loop skip rest of its statement for a particular value of loop variable.
By the use of labels in case of 'continue' statement,we make outer loop to skip rest of its statements for current value of loop variable by the use of labels. Following example will make you more clear about the same.
  • Java
int i=0;
out:
for(i=1;i<=3;i++)
{
        inner:
for(int j=1;j<=3;j++)
{
if(i==2)
continue out;
System.out.println("i="+i+" j="+j);
}
}
Output of above snippet
i=1 j=1
i=1 j=2
i=1 j=3
i=3 j=1
i=3 j=2
i=3 j=3
Here we have skipped the execution of loop when value of variable 'i' becomes 2.
Thanks all for your time. We will continue with 'Difference between C++ and Java' series in next post. Any queries and suggestions are invited in comments.



Thursday, 18 October 2012

Difference between C++ and Java

This is the 2nd post in "Difference between C++ and Java" series.In this post I am going to discuss about the differences in C++ and Java in case of conditional statements.
Condition Statement in Loops
Statement
Conditional statement in Java have boolean value i.e. either true or false but same in case of C++ can have any numeric value(integer or  float)
There are 3 types of loops in both the languages namely 'while', 'do-while' and 'for'. The loops are very important in any language. The basic difference in the looping statements of these languages is the condition which is tested every time the loop is iterated. The conditional statement in Java can only boolean type that is it may have the value true or false. But in case of C++, the conditional statement can have any numerical value. Here, any non-zero numeric value refers to true and 0 value refers to false.
  • Java
int i=1;
while(i++<=5)
{
   System.out.println("hey");
}
  • C++
i=5;
while(i)
{
    cout<<"hey";
   i--;
}
Both the code snippets produce same output.We cannot write integer value instead of conditional statement in Java but in case of C++ we can do so.
Thanks all for your time. We will continue with 'Difference between C++ and Java' series in next post. Any queries and suggestions are invited in comments

Difference between C++ and Java

This is the 3rd post in "Difference between C++ and Java" series.Here we are going to continue with our discussion on differences between C++ and Java.
1. Unsigned Right Shift Operator
Statement 
There is an additional shift operator in Java called Unsigned Shift Operator. 
We all know that there are shift operators available in almost every language to shift the bits of integer operands. In C++, we have got two Shift operators namely Right Shift Operator(>>) and Left Shift Operator(<<). These two operators are also present in Java but there is an additional shift operator called Unsigned Right Shift operator. This fills '0's on the left of the argument irrespective of its sign. The no. of '0's filled are specified by second operand.
We will make it more clear with the help of an example.
  • Java
int i=-1;
System.out.println(Integer.toBinaryString(i));
System.out.println("applying unsigned right shift by 31");
i=i>>>31;
System.out.println(Integer.toBinaryString(i)); 
Output is 
11111111111111111111111111111111
applying unsigned right shift by 31
1
Here in above code snippet we have illustrated the use of Unsigned Shift Operator in Java. Initially, the value of  'i' variable is -1 which is represented by a sequence of 32 1's in binary. Then we apply the 'Unsigned Right Shift Operator(>>>)' and specify the no. of bits to be shifted as 31. As a result, 31 '0's are inserted at the left of the operand 'i' and we get 1 as our output.
  2. Operators 
There are a lot of common operators in C++ and Java. These operators have same comparative precedence in both the languages. These operators include increment/decrement operators, arithmetic operators, shift operators, relational operators, equality operators, bit-wise operators, logical operators, conditional operator(ternary operator), assignment operators.
In C++, there are scope resolution operator(::), pointer operator(->), sizeof operator, pointer to member operator(.* and ->*), comma operator(,) which are not present in Java.
In Java, there is a instanceof operator which is not there in C++. This operator returns a boolean value signifying whether the second argument is reference variable to first operand.
Since there is no use of pointers in Java, sizeof operator has no significance and is not used.
Thanks all for your time. We will continue with 'Difference between C++ and Java' series in next post. Any queries and suggestions are invited in comments.

Tuesday, 16 October 2012

Difference between C++ and Java

I think almost every Computer Science Engineer wants to learn programming languages. Most basic high level languages which freshers try to learn are C++ and Java. There are a lot of chances of mixing up of syntax and implementation of a concept in these languages because each of them have their own features. Here is a humble effort from my side to carve out the basic differences in implementation of basic concepts and features of both the languages.
I will be describing few of the differences in my every post. Any suggestions and queries are also invited.
Here is the dose for the day.

  1. Use of % (modulo) operator
As we all know that % is a modulo operator and it is used for getting the remainder after division of its operands. For example, 234%2 is equal to 0 and 233%2 evaluates to 1.
Statement
% can be used only for integers in C++ but in Java it can also be used for floating point numbers.

  • C++
Following code attempts to make use of % for float operands

int  a=65,b=7;
float f=7.7;
cout<<(a%b)<<endl;
cout<<(f%b)<<endl;//error
This code gives error and last line does not compiles.

  • Java
The same code in Java method is as follows
int  a=55,b=7;
float f=54.5f;
System.out.println(a%b);
System.out.println(f%b);
Output is
6
5.5
Thanks all for your time. We will continue with 'Difference between C++ and Java' series in next post. Any queries and suggestions are invited in comments and through e-mails.

Into the world of JAVA

As the title says "Into the world of Java", in this post I will like to take you to the feel of Java. Rather than formally introducing you to Java. I will talk about it in layman's language as I will be going to do in my rest of the posts.
 Java is undoubtedly one of the most widely used high level languages in computer history. It has got wide range of applications from standalone applications to web based applications. Java applets can be embedded in a HTML page. J2ME can be used to develop mobile applications. Also this edition of java can also help you to develop set top box applications.
If you want to make a application for smart cards and other similar devices then in that case Java Card comes to the rescue. Java Card is  used for developing applications for all types of smart cards where one application can run on multiple types just like the case of standard Java where same application can run on multiple systems. ATM is very important example which can be quoted for application of Java Card.
    One of the problems with earlier versions of Java was its monotonous UI abilities. This deficit is also going to be solved using JavaFX. JavaFX is the latest edition of Java which would improve UI and make complex UI development relatively easy. It will also be very helpful in incorporating the media features in your application with minimal code.
  Java is also base for Google's Android OS. Best thing about Java is that Java applications may it be web or may it be standalone are far more secure. Moreover, these applications can run on any machine irrespective of platform. This makes JAVA a WORA (Write Once Run Anywhere) language. Java makes extensive use of OOPs concepts. It has got wide range of API's which can be used by the developers for the use in specific applications. All in all, I can say that we can make almost every type of high level language using Java.

Java vs C++

THis is a basic blog that differentiates features of two of the widely used languages C++ and Java.