Saturday Sep 06, 2008

Guassian Blur Example JavaFX

This is one simulation of Golden Eyes :-D(with an ugly face). I tried to make one use of Gaussian Blur which is applied in the white color of eyes. Adding this spot in the eyes gives a real simulation.

Here is the simple code :

package eyes;

import javafx.application.Frame;
import javafx.application.Stage;
import javafx.scene.geometry.Arc;
import javafx.scene.geometry.\*;
import javafx.scene.paint.Color;
import javafx.scene.paint.\*;
import javafx.scene.effect.\*;

var y: Number = 150;
Frame {
    title: "Golden Eyes"
    width: 500
    height: 500
    closeAction: function() { java.lang.System.exit( 0 ); 
    }
    visible: true

    stage: Stage {
        fill: Color.GRAY;
        content: [  
 
            Circle {
                centerX: 160, centerY: y
                radius: 23
                fill: LinearGradient {
                    startX: 0.0
                    startY: 0.0
                    endX: 1.0
                    endY: 0.0
                    proportional: true
                    stops: [
                        Stop { offset: 0.0 color: Color.GOLD },
                        Stop { offset: 1.0 color: Color.BLACK }
                    ]
                }
                opacity: 0.9
            },
 
            Circle {
                centerX: 160, centerY: y
                radius: 10
                fill: Color.BLACK
            },
            Circle {
                centerX: 166, centerY: y - 5
                radius: 5
                fill: Color.WHITE;
                effect : GaussianBlur {
                    radius: 6
                }
            },
            Circle {
                centerX: 250, centerY: y
                radius: 23
                fill: LinearGradient {
                    startX: 0.0
                    startY: 0.0
                    endX: 1.0
                    endY: 0.0
                    proportional: true
                    stops: [
                        Stop { offset: 0.0 color: Color.BLACK },
                        Stop { offset: 1.0 color: Color.GOLD }
                    ]
                }
                opacity: 0.2
            },
 
 
            Circle {
                centerX: 250, centerY: y
                radius: 10
                fill: Color.BLACK
            },
            Circle {
                centerX: 244, centerY: y - 5
                radius: 5
                fill: Color.WHITE;
                effect : GaussianBlur {
                    radius: 6
                }
            },
            Circle {
                centerX: 200, centerY: 180
                radius: 100
                fill: Color.SIENNA
                opacity: 0.1
 
            },
            Polyline { 
             stroke:Color.BLACK
                points: [
                    200,160, 
                    220.0,220.0,
                    180.0,220.0
                ]
            },
            Path {
               fill: LinearGradient {
                    startX: 0.0
                    startY: 0.0
                    endX: 1.0
                    endY: 0.0
                    proportional: true
                    stops: [
                        Stop { offset: 0.0 color: Color.BLACK },
                        Stop { offset: 1.0 color: Color.RED }
                    ]
                }
                elements: [
                    MoveTo { x: 160 y: 240 },
                    ArcTo { x: 250 y: 240 radiusX: 100 radiusY: 100},
 
                ]
            },
 
       ]
    }
}

Thursday Aug 28, 2008

Next BOJUG meet

We are welcoming all the Java Engineers in Bangalore to join BOJUG. Its Bangalore Open Java Users Group. Before going into the schedule of this time meet, we motivate you to join the BOJUG group at: http://bojug.wikispaces.com/ and http://bojug.dev.java.net. Now, here are the talks of the week: 

The next Bangalore Open Java Users Group (BOJUG) (http://bojug.dev.java.net)  meet has been planned for Saturday August 30, 2008,Time: 11.30 AM .

Venue:

Thoughtworks Bangalore

Tower C, Corporate Block, Diamond District, Airport Road
Landmarks: The first set of buildings after the Indiranagar flyover,
opp to the TJIF restaurant.

Google Maps Location: http://maps.google.com/maps?f=q&hl=en&geocode=&q=thoughtworks,+bangalore&ie=UTF8&filter=0&ll=12.996864,77.651196&spn=0.075603,0.154495&z=13

Time: 11.30 AM
Session Details:

1. Java FX..Its just the beginning-Vaibhav Choudhary

JavaFX Preview SDK
NetBeans Compatibilty
Demo, Demo, Demo, Demo .. and only Demo. How to make timeline, reflection, constraint,easing, shapes, animation, Java AWT/Swing.
Last we will try to see how to use it in applet or any type of web code.

2. Beans Binding and Beans Validation- Sathish Kumar

Short discussion on the above topics

3. Tomcat Internals - Sriram Narayanan

In this talk, Sriram will cover in brief various Tomcat configuration issues (server.xml, how to avoid having to deploy during development
time, etc). He'll next cover interesting topics such as developing custom Tomcat components, and how the component assembly mechanism
works.

Monday Aug 18, 2008

Button Tabs with effects in JavaFX !

It looks good, so I decided to put before the completion of work. I was trying to simulate some fancy effects on button, so that I can embed it somewhere in some site. Here what is the class for Button:

public class Button extends CustomNode {

    public attribute x: Number;
    public attribute y: Number;
    public attribute text: Text;
    public attribute rectangle: Rectangle;
    public attribute content: String;
 
    public function create(): Node {

Now, the buttons will look like: 

 If you move the focus on any of the button, it will shine like this :

 or like this :

This simple 2 line animation is achieved by playing with the opacity code. Though I am not able to fit my text inside the button which currently I am trying to bind out. But simple flashy buttons are easy to achieve. Here is the code:

package flashybutton;

import javafx.scene.CustomNode;
import javafx.scene.Group;
import javafx.scene.Node;
import javafx.scene.text.\*;
import javafx.scene.geometry.\*;
import javafx.scene.paint.Color;
import javafx.application.Frame;
import javafx.application.Stage;
import javafx.ext.swing.TextField;
import javafx.scene.Font;
import javafx.scene.FontStyle;
import javafx.scene.paint.\*;
import javafx.input.MouseEvent;


var x: Number = 100;
var y: Number = 100;
var color: Color;
var buttons:Button[]; 
var text: Text;
var content: String;
var width: Number = 100;
var height: Number = 40;
var arcWidth:Number = 10;
var arcHeight: Number = 10;
var opacity: Number = 0.6;

for( i in [1..5] ) {
    insert Button {
        x:100 + 100 \* i,
        y:100,
        content: "HelloWorld" + i,
        opacity: 0.6
    } into buttons;
}     
Frame {
    title: "MyApplication"
    width: 1000
    height: 200
    closeAction: function() { java.lang.System.exit( 0 ); 
    }
    visible: true

    stage: Stage {
        fill: Color.BLACK
        content: [ 
            buttons
        ]
    }
}

public class Button extends CustomNode {

    public attribute x: Number;
    public attribute y: Number;
    public attribute text: Text;
    public attribute rectangle: Rectangle;
    public attribute content: String;
 
    public function create(): Node {
        return Group {
            content: [
                Rectangle {    
                    x : bind x,
                    y : bind y, 
                    fill: LinearGradient {
                        startX: 0.0
                        startY: 0.0
                        endX: 1.0
                        endY: 0.0
                        proportional: true
                        stops: [
                 //   Stop { offset: 0.0 color: Color.BLACK },
                            Stop { offset: 0.0 color: Color.BLACK },
                            Stop { offset: 0.5 color: Color.GOLD },
                            Stop { offset: 1.0 color: Color.BLACK }
                        ]
                    },
                    width: 100
                    height: 40
                    arcWidth: 10
                    arcHeight: 10
                    opacity: bind opacity
                    onMouseMoved: function( e: MouseEvent ):Void {
                        opacity = 1.0;
                    }
                    onMouseExited: function( e: MouseEvent ):Void {
                        opacity = 0.6;
                    }
                },
                Text {
                    x: bind x + 10,
                    y: bind y + height / 2 + arcHeight / 2;
                    content: bind content
 
 
                }
            ]
        }
    }
}

Motion of Ball Under Gravity - JavaFX

As written in the last blog, now we can use those MotionBall into giving some kind of motion. Here I have tried to give a simple motion of ball under gravity. After every hit there is an energy dissipation and the ball will slow down at end. The colors of balls, initial positions and radius are all random but under a constraint. 

Now, the motion of the balls should get called in timeline. Like this:

 var timeline = Timeline {
    repeatCount: Timeline.INDEFINITE
    keyFrames : [
        KeyFrame {
            time : 16ms
            action: function():Void {
                for(ball in balls) {
                    ball.motion();
                }
            }
        }
    ]
}

Here is the final code. I tried to write the value as generic as possible but pardon me if there is some hardcoded value written somewhere :

import javafx.scene.CustomNode;
import javafx.scene.Group;
import javafx.scene.Node;
import javafx.scene.geometry.\*;
import javafx.animation.Timeline;
import javafx.animation.KeyFrame;
import javafx.scene.paint.\*;
import javafx.application.Frame;
import javafx.application.Stage;
import javafx.scene.effect.\*; 

// Java Legacy
import java.lang.Math;
import java.util.Random;
import java.lang.System;


var balls:GravityBall[];
var gravity:Number= 0.1;
var width:Number = 1200;
var height:Number= 500;
var dampFactor: Number = 0.9;
 
var timeline = Timeline {
    repeatCount: Timeline.INDEFINITE
    keyFrames : [
        KeyFrame {
            time : 16ms
            action: function():Void {
                for(ball in balls) {
                    ball.motion();
                }
            }
        }
    ]
}

var rnd : Random = new Random();

for( i in [1..5] ) {
    insert GravityBall {
        x : rnd.nextInt( 100 ), y :  rnd.nextInt( 300 ), radius : rnd.nextInt( 10 ) + 20
        color : Color.rgb(rnd.nextInt(255),rnd.nextInt(255),rnd.nextInt(255))
        , opacity : 0.9
    } into balls;
}    


var rect = Rectangle {
    x: 0, y: 500
    width: 1200, height: 10
    fill: LinearGradient {
        startX: 0.0
        startY: 0.0
        endX: 1.0
        endY: 0.0
        proportional: true
        stops: [
            Stop { offset: 0.0 color: Color.TRANSPARENT },
            Stop { offset: 1.0 color: Color.WHITESMOKE }
        ]

    }
}
Frame
{
 
    title: "MyApplication"
    width: 1200
    height: 732
    closeAction: function() { java.lang.System.exit( 0 ); 
    }
    visible: true

    stage: Stage {
        fill : Color.BLACK
        content: [
            balls,
            rect
        ]
    }
}

timeline.start();

public class GravityBall extends CustomNode {

    public attribute x : Number;
    public attribute y : Number;
    public attribute radius : Number;
    public attribute color : Color;
    public attribute velocity : Number;
 
    public function motion(): Void {
        velocity += gravity;
        x += 1;
        y += velocity;
 
        if(x + radius > width ) {
            x = width - radius; //for ending at the boundary
        }
        if( y + radius > height ) {
            y = height - radius;
            velocity \*= -dampFactor;
        }
    }
 
    public function create(): Node {
        return Circle {
            centerX : bind x, centerY : bind y, radius : bind radius
            fill: bind color
 
        };
 
    }
} 

This is small output view :


Friday Aug 15, 2008

Insertion trigger in JavaFX

This weekend I have written some physics equation in JavaFX like motion under gravity and collision motion. In all  complex code, we have to write a class of MotionBall, which consist attribute like X position, Y position, Velocity, Mass and Color of Ball like:

public class MotionBall extends CustomNode {

    public attribute x: Number;
    public attribute y: Number;
    public attribute velocityX: Number;
    public attribute velocityY: Number;
    public attribute mass: Number;
    public attribute radius: Number;
    public attribute color: Color;
 
    public function create(): Node {
        return Circle {
            centerX : bind x, centerY : bind y, radius : bind radius
            fill : bind color
 
        };
    }
} 

After this, the important part is to fill these data outside the class. Say, I want to make 5 instance of MotionBall. And I want to give Center X, Center Y, radius and color. Here in this code, I want to put the Balls at the random position with random radius with random color :-). Here goes the insertion trigger in JavaFX:

package insertion;

import javafx.application.Frame;
import javafx.application.Stage;
import javafx.scene.CustomNode;
import javafx.scene.Group;
import javafx.scene.Node;
import javafx.scene.geometry.Circle;
import javafx.scene.paint.Color;
import java.util.Random;


var radius: Number;
var balls: MotionBall[];

var rnd : Random = new Random();

 for( i in [1..5] ) {
                insert MotionBall {
                    x : rnd.nextInt( 170), y :  rnd.nextInt( 170 ), radius : rnd.nextInt( 10 ) + 20
                    color : Color.rgb(rnd.nextInt(255),rnd.nextInt(255),rnd.nextInt(255))
                    , opacity : 0.9
                    } into balls;
                }    
Frame {
    title: "Insertion Example"
    width: 250
    height: 250
    closeAction: function() { java.lang.System.exit( 0 ); 
    }
    visible: true

    stage: Stage {
        fill: Color.BLACK
        content: 
            bind balls
 
    }
}
 
public class MotionBall extends CustomNode {

    public attribute x: Number;
    public attribute y: Number;
    public attribute velocityX: Number;
    public attribute velocityY: Number;
    public attribute mass: Number;
    public attribute radius: Number;
    public attribute color: Color;
 
    public function create(): Node {
        return Circle {
            centerX : bind x, centerY : bind y, radius : bind radius
            fill : bind color
 
        };
    }
}

This is how output looks like : jar file.

I have written some attribute for further use, so please ignore the use.


Monday Aug 04, 2008

Java API + Flickr API

I decided to play with Flickr API's for Java FX coding. But in between I found myself in hell and I started with Java :-). As all of you know Flickr Support hell lot of API to view Image, to search image, to search comment, Image translation, Image upload and many more. Check out here for detailed API. Now using these API's are not at all tough, because its all a game of XML.

Here I have written a small code, which do this :

1. It search one image(it can work for more than one image) from search API of Flickr.
2. It writes the search data on a XML, which I am copying at D:\\Hello1.xml.
3. And finally the code is using XML parsing techniques to get the information required for image view.
4. Then I use JDK6 feature of Desktop and open the default browser with the parsed URL. And
Congratulations, you can see the image.

Code, can look little big because of bad coding and writing lot of repetitive things :D.  

package flickrapp;

import java.awt.Desktop;
import javax.xml.namespace.QName;
import javax.xml.stream.XMLEventReader;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.events.Attribute;
import javax.xml.stream.events.StartElement;
import javax.xml.stream.events.XMLEvent;
import java.io.\*;
import java.net.\*;
import java.util.\*;

public class Main {

    public static void main(String args[]) throws Exception {
        URLConnection uc = new URL("http://api.flickr.com/services/rest/?method=flickr.photos.search&api_key=e3471e67d4ac10c64055420d9b211b4f&per_page=1&text=Bangalore").openConnection();
        DataInputStream dis = new DataInputStream(uc.getInputStream());
        FileWriter fw = new FileWriter(new File("D:\\\\Hello1.xml"));
        String nextline;
        String[] servers = new String[10];
        String[] ids = new String[10];
        String[] secrets = new String[10];
        while ((nextline = dis.readLine()) != null) {
            fw.append(nextline);
        }
        dis.close();
        fw.close();
        String filename = "D:\\\\Hello1.xml";
        XMLInputFactory factory = XMLInputFactory.newInstance();
        System.out.println("FACTORY: " + factory);

        XMLEventReader r = factory.createXMLEventReader(filename, new FileInputStream(filename));
        int i = -1;
        while (r.hasNext()) {

            XMLEvent event = r.nextEvent();
            if (event.isStartElement()) {
                StartElement element = (StartElement) event;
                String elementName = element.getName().toString();
                if (elementName.equals("photo")) {
                    i++;
                    Iterator iterator = element.getAttributes();

                    while (iterator.hasNext()) {

                        Attribute attribute = (Attribute) iterator.next();
                        QName name = attribute.getName();
                        String value = attribute.getValue();
                        System.out.println("Attribute name/value: " + name + "/" + value);
                        if ((name.toString()).equals("server")) {
                            servers[i] = value;
                            System.out.println("Server Value" + servers[0]);
                        }
                        if ((name.toString()).equals("id")) {
                            ids[i] = value;
                        }
                        if ((name.toString()).equals("secret")) {
                            secrets[i] = value;
                        }
                    }
                }
            }
        }
        System.out.println(i);
        String flickrurl = "http://static.flickr.com/" + servers[i] + "/" + ids[i] + "_" + secrets[i] + ".jpg";
        try {
            URI uri = new URI(flickrurl);
            Desktop desktop = null;
            if (Desktop.isDesktopSupported()) {
                desktop = Desktop.getDesktop();
            }

            if (desktop != null) {
                desktop.browse(uri);
            }
        } catch (IOException ioe) {
            ioe.printStackTrace();
        } catch (URISyntaxException use) {
            use.printStackTrace();
        }
    }
}

Now see this line :

URLConnection uc = new URL("http://api.flickr.com/services/rest/?method=flickr.photos.search&api_key=e3471e67d4ac10c64055420d9b211b4f&per_page=1&text=Bangalore").openConnection();

Here some important thing to see :

http://api.flickr.com/services/rest/?method=flickr.photos.search    -> this is the way to write Flickr API.

api_key=e3471e67d4ac10c64055420d9b211b4f  -> required for service. This is my api_key, you can have your own. Just go to flickr service and generate your API_key

per_page=1  -> Here is what I meant one image, if you can change this to 10. It will gather information of top 10 images in XML file.

text=Bangalore  -> Sorry, I have hard coded it for now. This is the search string.

Now, look at the XML file get generated in D:\\Hello1.xml. You can see one entry with tag photo inside photos. So, we need to take some data from this XML file and add in proper style to get the correct URL and that is here:

String flickrurl = "http://static.flickr.com/" + servers[i] + "/" + ids[i] + "_" + secrets[i] + ".jpg";

Again, lot of things are hard coded(which I will correct in next post). Since only one image (i=0). I am assuming its a jpg image :D. Now calling Desktop API, you can load this image on default browser.

Now, this is still a live question, for certain keyword search, it gives the same result like when I search for keyword "Vaibhav", code and search box of Flickr provided the same result(which is not my photo :-( )  whereas if I search on things like "Bangalore", result is not similar for many cases. I don't know how Flickr handles it internally.

Probably next I will try to upload image or translate image but in Java FX :-)

Friday Jul 25, 2008

SubType Check Optimization in Java !

Lots of our friends keep on asking, why to use Java SE 5.0 or Java SE 6. And most of the time you need to reply something impressive, then only they will start using it and can understand more benefits.  I was reading the gradual performance improvement in JDK versions which is quite interesting. Java has spotted all its reason to being slow (very nice article, which speaks why Java is slow than C++) and optimized those on max level. One of the reasons mentioned in this article was Lots of Casts. And that's true, a good, big project code goes about millions of cast checking in Java and off course need attention for optimization. JDK 5 and onwards has done a fast subtype checking in Hotspot VM. This blog is dedicated on a small talk on the same, for detail read this article written by John and Cliff.

Prior to 5, Every Subtype has cached with its SuperType(casting of which is correct). The cache strength is 2 and if results return negative then its goes for a VM call which resolves this problem and caches if VM resolves it as positive. So anytime unavailability in cache is a costly operation where we need to make a call for VM. And in the worst scenario mentioned in SpecJBB we can have 3 rotating elements with 2 cache.

So, [A B] in cache <---- C found by VM and get cached, A is out now.

[B,C] in cache <-------- A negative test, VM call(+), get cached, B out.

[C,A] in cache <-------- B negative test, VM call(+), get cached, C out !

So, in basic term we can't trust on complexity(calls happen at runtime). And hence it better to move on a better algorithm. The new algorithm pass the code through an optimizer which checks more specification at compile time. Like if Base class and Derived class is known at compile time only. It try to understand lot of code at compile time only. It put the entire code inline and there is no requirement of VM calls. Complexity is quite consistent and it takes one load for most of the object or object array.

This also divide the subtype checks into primary and secondary checks. For Class, Array of Classes and for array of primitive value, primary check has been done whereas interface and array of interface are handled by secondary check. Finally a smart algorithm combines them.

In primary subtype check:

Aim to Check: Is S a subtype of T ? Calculate the depth of S and T. Depth mean to say all the parent. Though it is done in some base level or assemble level, I am writing a code in Java to find out the depth.  Here is the code using reflection API's:

package findparent;
public class Main {

    public static void main(String[] args) throws Exception {
        String[] display = new String[10];
        int i = 1;
        FifthClass tc = new FifthClass();
        Class classname = tc.getClass();
        display[0] = classname.getName();
        Class parent = classname.getSuperclass();
        while (!(parent.getName().equals("java.lang.Object"))) {
            display[i] = parent.getName();
            classname = parent.newInstance().getClass();
            parent = classname.getSuperclass();
            i++;
        }
        display[i] = "java.lang.Object";
        for (int j = 0; j <= i; j++) {
            System.out.println(display[j]);
        }
        System.out.println("Depth of tc is " + i);
    }
}

class FirstClass {
}

class SecondClass extends FirstClass {
}

class ThridClass extends SecondClass {
}

class ForthClass extends ThridClass {
}

class FifthClass extends ForthClass {
}

Now the algo. says:

S.is_subtype_of(T) :=
return (T.depth <= S.depth) ? (T==S.display[T.depth]) : false;

And further a lot of optimization. Which we will check in next blog :-). I will also try to cover how the secondary Subtype check is being done and also how to combine both the checks.

Till now, make a big inheritance tree and try to see the difference between older JDK and JDK5 onwards.

Friday Jul 18, 2008

Understanding JavaFX - Small Navigation Code

So finally I am able to write a small code with the new Java FX API and Builder provided in NB 6.1. I have also seen one bug got fixed (maybe initially it was handled on a different way). Initially when we make any FX project in Netbeans, it basically store the \*.fx code into classes folder as well. There is no way one can find the .class file of the .fx file, which is not a problem now.

I have written one small navigation code of map from key control. Which moves the map left, right, up and down from the corresponding key. And the most part of the code line is to handle the boundary condition like the image should not move left when it is already in left most region and so on. Thanks to Vikram for helping me out in writing boundary condition, this is always confusing for me :-D. Here is the small code:

import javafx.application.Frame;
import javafx.application.Stage;
import javafx.scene.paint.Color;
import javafx.input.KeyEvent;
import javafx.input.KeyCode;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.input.MouseEvent;
import javafx.scene.transform.Translate;
import java.lang.\*;
import javafx.scene.geometry.Line;

var x1 : Number = 0;
var y1 : Number = 0;
//var myImage = Image { url: "{__DIR__}/./earth-map-big.jpg" };
var myImage = Image { url: "http://arstechnica.com/reviews/4q00/macosx-pb1/images/earth-map-big.jpg" };
var line: Line;

Frame {
    title: "MyApplication"
    width: 500
    height: 500
    resizable: false
 
    closeAction: function() { 
        java.lang.System.exit( 0 ); 
    }
    visible: true
    stage: Stage {
        fill:Color.BLACK
        content: [
            ImageView {
                image : myImage
                transform : [ 
                    Translate { x : bind x1, y : bind y1 }
                ]
                onKeyPressed: function( e: KeyEvent ):Void {
                    System.out.println(x1 + " " + y1);
                   if(
                    e.getKeyText() == "Left")
                    {
                        if(x1 < 0) {
                            System.out.println(x1);
                            x1+=50;
                        }
                    }
                    if(
                    e.getKeyText() == "Right")
                    {
                        if(Math.abs(x1  -  500) < myImage.width) {
                            System.out.println(x1);
                            x1-=50;
                        }
                    }
                    if(
                    e.getKeyText() == "Down")
                    {
                        if(Math.abs(y1  -  500) < myImage.height) {
                            System.out.println(y1);
                            y1-=50;
                        }
                    }
                    if(e.getKeyText() == "Up")
                    {
                        if(y1 < 0) {
                            System.out.println(y1);
                            y1+=50;
                        }
                    }
                }
                opacity:1  
            }
        ]
   }
} 

I am loading the image from URL itself, so it will take sometime(because Image size is 3200 X 1600). Rest all is mathematics :-). Still lot more fancy job to do !

Friday Jul 11, 2008

Applet and JavaFX and Confusion

Two weeks back in BOJUG meeting, I have seen lot many engineers getting confuse with JavaFX. They want to know how to run FX code in browser. Shall we use applet to run FX code. And many more. Though it tough to explain everything in a small presentation but Harish Singh and we have tried our best to explain some of the queries. Yes, FX can be very well run in an applet. I have written one HelloWorld type of example for running FX code inside applet. Its very well same. \*.fx file create a .class file and then handling in the same way as we do with .class file.

Here is a small code for "My Hello World" (HelloApplet.fx)

import javafx.ui.\*;

Applet{
  content: Label {
    text: "My Hello world!"
  }
} 


Now you have to compile this with javafxc, so that we can use class file. For that you need to download javafx compiler, runtime and some more jars. From this link you can download it.

Now here is little tough part, making html file for applet :-). Tough because you get to know which jar files your code is using. And you will not get documents readily to say you which API belong to which package + API's in themselves are changing. So, you may not able to run your older codes. Anyway, I have written this html code(Hello.html):
<html>
  <body>
    <applet code="javafx.ui.Applet" width=480 height=560
     archive="javafxrt.jar, Scenario.jar, javafxgui.jar, javafxc.jar, javafx-swing.jar, javafx.jar">
     <param name="AppletClass" value="HelloApplet"> 
    </applet>
  </body>
</html>


Don't ask me why I have added some many archive. I got frustrated in knowing what residing where. And so, I have ended up adding all the jar that I have seen in the archive(in the link) :). Check it out, let me know if there exist any problem.

Surprisingly you can call Frame also from applet, check this code:

import javafx.ui.\*;
Frame {
   title: "Hello World F3"
   width: 200
   content: Label {
      text: "Hello World"
   }
   visible: true
}
In the next blog I will also cover some other way to use on web.

Thursday Jul 03, 2008

XML Event in JDK6

Java SE 6, added the new class XMLEvent in the package javax. xml. stream.events. This is the base event interface for handling markup events. Not only that,  Events may be cached and referenced after the parse has completed.

I have simply tried to write a code which can find the skeleton of my XML file and show me only tag structure. 10 lines of code is enough to do this job. And with the strong API of XMLEvent , you can play with thousands of things in a XML file.

Here is my XML file(taken somewhere from Internet):

 <recipe name="bread" prep_time="5 mins" cook_time="3 hours">
<!-- this is comment section -->
   <title>Basic bread</title>
   <ingredient amount="8" unit="dL">Flour</ingredient>
   <ingredient amount="10" unit="grams">Yeast</ingredient>
   <ingredient amount="4" unit="dL" state="warm">Water</ingredient>
   <ingredient amount="1" unit="teaspoon">Salt</ingredient>
   <instructions>
     <step>Mix all ingredients together.</step>
     <step>Knead thoroughly.</step>
     <step>Cover with a cloth, and leave for one hour in warm room.</step>
     <step>Knead again.</step>
     <step>Place in a bread baking tin.</step>
     <step>Cover with a cloth, and leave for one hour in warm room.</step>
     <step>Bake in the oven at 180(degrees)C for 30 minutes.</step>
   </instructions>
 </recipe>

And here is the small code, helped me to find out the tag structure.

import java.io.FileInputStream;
import javax.xml.stream.\*;
import javax.xml.stream.events.\*;

public class EventParse {
    public static void main(String[] args) throws Exception {

        String filename = "hello.xml";
        XMLInputFactory factory = XMLInputFactory.newInstance();
        XMLEventReader xmler = factory.createXMLEventReader(filename,new FileInputStream(filename));
        System.out.println("Skeleton of XML file:");
        while (xmler.hasNext()) {
            XMLEvent e = xmler.nextEvent();
                 if(e.getEventType()==1) {
                    System.out.println(e.toString());
                    }        
                  if(e.getEventType()==2) {
                    System.out.println(e.toString());
 
                    }
    }
   }
}

and the output:

<recipe cook_time='3 hours' name='bread' prep_time='5 mins'>
<title>
</title>
<ingredient amount='8' unit='dL'>
</ingredient>
<ingredient amount='10' unit='grams'>
</ingredient>
<ingredient amount='4' unit='dL' state='warm'>
</ingredient>
<ingredient amount='1' unit='teaspoon'>
</ingredient>
<instructions>
<step>
</step>
<step>
</step>
<step>
</step>
<step>
</step>
<step>
</step>
<step>
</step>
<step>
</step>
</instructions>
</recipe>

Tuesday Jul 01, 2008

BOJUG meet at Sun Campus

Here is my last week BOJUG meet slides. I have talked on Java SE6u10 features. Thanks to all the participants and organizers. Nice to see lot of Non-Sun people in Sun Campus to attend the meet.

Saturday Jun 28, 2008

Why JDK6 again ?

Again a comparison and reason why JDK6. Weeks back one of our team member gave a presentation on JVM performance improvement in Mustang. I have just collected a useful point here and try to compare with older JDK version. Here is the code:

import java.util.\*;

public class RuntimePerformanceGC {
 
    public static void main(String[] args) {
        RuntimePerformanceGC ob = new RuntimePerformanceGC();
        Vector v = new Vector();
        java.util.Date now = new java.util.Date(); 
        long t1 = now.getTime();                   
        ob.addItems(v);
        java.util.Date now1 = new java.util.Date();
        System.out.println(now1.getTime()-t1);
    }
    public void addItems(Vector v) {
        for(int i =0;i<500000;i++)
        v.add("Item" + i);
    }
}
 

And the output in ms is:

JDK1.4.2: 984

JDK 6: 578

You can see a massive difference. 37 percent improvement in time. Why ? Here goes :

This is because of Runtime Performance Optimization. The new lock coarsening optimization technique implemented in hotspot eliminates the unlock and relock operations when a lock is released and then reacquired with no meaningful work done in between those operations. And this is what happening in our example. Since, Vector do thread safe operation, it takes the lock for add, release the lock and then takes it again. 

So, I just tried to give one more reason why use JDK6 ;-). This is off course not the only reason for big improvement, I will try to cover some more in upcoming blogs :-)


Wednesday Jun 25, 2008

Talk about Core Java New book !

Talk of Cay Horstmann in Second Life happened to be cool. I got some problem in audio because of my low internet bandwidth. Here are some of the snaps.

 He covered some of the new features of SE5/6 in his talk. How those features get covered in book.

Monday Jun 23, 2008

Second Life session - Core Java, Volume II—Advanced Features

News for those who are not in Second Life(people there already know :-)) . Here is the Java Talk by Cay Horstmann. So, join the world of SecondLife and do attend the session. Here goes the detailed information:

SMI Press Author Chat with Cay Horstmann
Hosted by SDN
June 25, 2008 - 9am PT/SL
Where: Sun Pavillion, Andromeda Theater

http://slurl.com/secondlife/Sun%20Microsystems%201/128/81/71

Cay Horstmann will be talking about his new SMI Press books - Core Java, Volume II—Advanced Features and Core Java, Volume I-Fundamentals, Eighth Edition. Come listen to Cay (professor of computer science at San Jose State University and a frequent speaker at computer industry conferences) talk about his latest book and then participate in a chat with him during the Q&A!

See you there !

Thursday Jun 19, 2008

6u10 features - Presentation

Here is the presentation I made for the BOJUG meeting. It's not the final presentation. Please provide suggestions. I have tried to cover some of the important features of 6u10.

About

Hi, I am Vaibhav Choudhary working in Sun. This blog is all about simple concept of Java and JavaFX.

Search

Archives
« April 2014
SunMonTueWedThuFriSat
  
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
   
       
Today