Wednesday Jan 07, 2009

Pendulum Motion with controller in JavaFX

So, here goes one more Motion sample in JavaFX :). I have added Slider to control the value of "g" in Pendulum motion(just a thought, anything can be controlled like mass, length of pendulum). Pendulum do a complex calculation(Square root, Cosine, Sine) and I guess render is great in FX. Sorry again, as I am not able to post the applet. 

But here how it looks : 

The progress bar has been stolen from Chris Blog.

Here is the source code :

Main file, Pendulum.fx, Slider.fx.

Have a look and feel free to share your views.

Monday Dec 29, 2008

Image Depth - Z Ordering in JavaFX

While writing some of the samples in which we have to play with images, we sometimes has to manage the depth of the images. Like for the Carousel example, every image has a depth. In that example, actually images are not overlapping with each other, so we never need to write the Z-Order concept. But if someone want to write a Carousel or some application in which Images are residing over other images, we need to set the Z-order of Images. Z-Order in literal term means depth-ness of images. JavaFX gracefully provide API's to set the Z-order of images. With a simple call, you can set the images toFront or toBack features.

In this example, I have taken 3 images and try to set the depth-ness of images on the event of Buttons. 

                 First Image on Top                             Second Image on Top

      Third Image on Top

Here is the code to set the Z-Order : 

package zorder;

import javafx.scene.Group;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.paint.Color;
import javafx.scene.Scene;
import javafx.stage.Stage;
import javafx.scene.shape.Rectangle;
import javafx.scene.input.MouseEvent;
import javafx.ext.swing.SwingButton;

var im1 = ImageView {
    x: 100
    y: 100
    image: Image {
        url: "{__DIR__}im1.PNG"
    }
    opacity: 0.8
        };

var im2 = ImageView {
    x: 130
    y: 130
    image: Image {
        url: "{__DIR__}im2.PNG"
    }
    opacity: 0.8
        };

var im3 = ImageView {
    x: 160
    y: 160
    image: Image {
        url: "{__DIR__}im3.PNG"
    }
    opacity: 0.8
        };

var gp = Group {
    content:[
        im1, im2,im3
    ]

}
Stage {
    title: "Application title"
    width: 400
    height: 400
    scene: Scene {
        fill: Color.BLACK
        content: [
            gp,
            SwingButton {
                translateX: 10
                translateY: 10
                text: "Image 1"
                action: function() {
                    im1.toFront();
                }
            }
            SwingButton {
                translateX: 90
                translateY: 10
                text: "Image 2"
                action: function() {
                    im2.toFront();
                }
            }
            SwingButton {
                translateX: 170
                translateY: 10
                text: "Image 3"
                action: function() {
                    im3.toFront();
                }
            }
        ]
    }
}

From next blog, I will use applet or JNLP in place of images, as suggested by Dmitry in last blog. Pictures make it bulky and uneasy to load. But I was getting some problem in deploying the application on Sun blog which will be rectified soon. 

Friday Dec 26, 2008

Colliding Balls + JavaFX

Here is an example of one more physics system - Colliding Balls. This is one of the most common examples we find everywhere. I have written this on transparent window. And so, if we increase the width and height of the stage + width, height variable in MotionBall.fx, it will give us a feeling like FlyingSaucer which keep on running all the way on Desktop. Here it looks on top of my code :D.

So, the netbeans window on back and application is running on top of it. Actually dragged out of the browser and running. Just for adding information, we can run an application from netbeans on browser by Properties -> Run -> Run in Browser. Remeber to set the size of applet correct else the application display will not full.

Initially position in this application has been generated randomly + Damping motion has been applied. So, in sometime all the balls will settle down on base. These all parameters can be adjusted in the file. Ball Effect has been generated as usual by Gradient Effect. Some variable may be unused because of future plan :D.

Here goes the code:

MotionBall.fx :

package collidingballs; import java.lang.\*; import javafx.scene.CustomNode; import javafx.scene.Group; import javafx.scene.Node; import javafx.scene.paint.\*; import javafx.scene.shape.\*; var spring : Number = 0.05; var gravity : Number = 0.05; var width : Number = 240; var height: Number = 320; var start: Number = 0; public class MotionBall extends CustomNode {     public var x: Number;     public var y: Number;     public var velocityX: Number;     public var velocityY: Number;     public var mass: Number;     public var radius: Number;     public var color: Color;     public function collision( balls: MotionBall[]) {         for(ball in balls) {             var dx : Number = ball.x - x;             var dy : Number = ball.y - y;             var distance : Number = Math.sqrt( dx \* dx + dy \* dy );             var minDist : Number = ball.radius + radius;             if( distance < minDist ) {                 var angle : Number = Math.atan2( dy, dx );                 var tx : Number = x + Math.cos( angle ) \* minDist;                 var ty : Number = y + Math.sin( angle ) \* minDist;                 var ax : Number = ( tx - ball.x ) \* spring;                 var ay : Number = ( ty - ball.y ) \* spring;                 velocityX -= ax;                 velocityY -= ay;                 ball.velocityX += ax;                 ball.velocityY += ay;             }         }     }     public function move(balls: MotionBall[]) {         velocityY += gravity;         x += velocityX;         y += velocityY;         if( x + radius >= width ) {             x = width + start - radius;             velocityX \*= - 0.9;         }         if( x - radius <= start ) {             x = start + radius;             velocityX \*= -0.9;         }         if( y + radius >= height ) {             y = height - radius;             velocityY \*= -0.9;         }         if( y - radius <= 40 ) {             y = 40 + radius;             velocityY \*= -0.9;         }     }     public override function create(): Node {         return Group {             content: [                 Circle {                     centerX: bind x,                     centerY: bind y,                     radius: bind radius                     fill: bind RadialGradient {                         centerX: 0.25                         centerY: 0.25                         proportional: true                         stops: [                             Stop {                                 offset: 0.0                                 color: color },                             Stop {                                 offset: 1.0                                 color: Color.BLACK },                         ]                     }                 }             ]         };     }



Main.fx :

package collidingballs; import collidingballs.MotionBall; import java.util.Random; import javafx.animation.KeyFrame; import javafx.animation.Timeline; import javafx.scene.paint.Color; import javafx.scene.Scene; import javafx.stage.Stage; import javafx.stage.StageStyle;

var balls: MotionBall[]; var rnd : Random = new Random(); for( i in [1..5] ) {     insert MotionBall {         x: rnd.nextInt( 240 ),         y: rnd.nextInt( 320 ),         radius: 30         color: Color.rgb(rnd.nextInt(255),rnd.nextInt(255),rnd.nextInt(255))     } into balls; } // timeline for colliding balls var t_collide = Timeline {     repeatCount: Timeline.INDEFINITE     keyFrames: [         KeyFrame {             time: 30ms             action: function() {                 for(ball in balls) {                     ball.collision(balls);                     ball.move(balls);                 }             }         }     ] } t_collide.play(); Stage {     title: "Collding Balls"     style: StageStyle.TRANSPARENT     width: 240     height: 320     scene: Scene {         fill: Color.TRANSPARENT         content: [             balls         ]     } }

Tuesday Dec 23, 2008

JavaFX ToolTip - A rough idea

I tried to write a very rough Tool Tip feature. Actually in JavaFX, we can write our own cool Tool tip. But in the meantime, we need to take care of boundary conditions of Tool tip. Here how it looks :

 A shadow effect.

Right now its just a bad code, we will make it good in next post :D. Here it is :

package tooltip;

import javafx.scene.CustomNode;
import javafx.scene.effect.DropShadow;
import javafx.scene.Group;
import javafx.scene.Node;
import javafx.scene.paint.Color;
import javafx.scene.shape.Rectangle;
import javafx.scene.shape.ShapeIntersect;
import javafx.scene.text.Font;
import javafx.scene.text.Text;

public class ToolTip extends CustomNode {

    public var x: Number;
    public var y: Number;
    //useless - content should decide
    public var width: Number = 100;
    public var height: Number = 50;
    //useless-Tooltip instance should be 
    //added dynamically 
    public var op: Number = 0.0;
    public var content: String;
 
    public override function create(): Node {
        return Group {
            content: [
                ShapeIntersect {
                    effect: DropShadow {
                        offsetY: -5
                        offsetX: -5
                        color: Color.color(0.4, 0.4, 0.4)

                    };
                    translateX: bind x
                    translateY: bind y
                    opacity: bind op
                    stroke: Color.GRAY
                    strokeWidth: 2
                    fill: Color.GREEN
 
                    a: [
                        Rectangle {
                            arcHeight:10
                            arcWidth:10
                            x: 0
                            y: 0
                            width: bind width
                            height: bind height
                        }
                        Rectangle {
                            rotate: 45
                            x: 40
                            y: 40
                            width: bind width / 5
                            height: bind 2 \* height / 5
                        }
                    ]
                },
                Text {
                    font: Font {
                        size: 14
                    }
                    translateX: bind x
                    translateY: bind y
                    opacity: bind op
                    x: 10,
                    y: 12
                    content: bind content
                }
            ]
        };
    }
} 

Main Code for this example :

package tooltip;

import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.stage.Stage;
import tooltip.ToolTip;
import javafx.scene.shape.Rectangle;
import javafx.scene.paint.Color;
import javafx.scene.text.Text;
import javafx.scene.text.Font;
import javafx.scene.input.MouseEvent;


var tt = new ToolTip;

var rect = Rectangle {
            x: 10,
            y: 10
            width: 180,
            height: 70
            stroke: Color.WHITE
            strokeWidth: 4
            fill: Color.YELLOWGREEN
            opacity: 0.8
        };

var text = Text {
            font: Font {
                size: 14
                name: "Arial"
            }
            x: 14,
            y: 30
            content: "HelloWorld - Beginning of a \\nnew technology always say\\n          - Hello World "
        };
var gp = Group {
    translateX: 60
    translateY: 260
    onMouseMoved: function( e: MouseEvent ):Void {
        tt.x = rect.x + tt.width;
        tt.y = rect.y - tt.height - 20;
        tt.op = 0.8;
        tt.content = "You can see \\n the help of \\nHelloWorld !";
    }
    onMouseExited: function( e: MouseEvent ):Void {
        tt.op = 0.0;
    }
    content: [
        rect, text,tt
    ]
}

Stage {
    title: "Tool-Tip"
    width: 450
    height: 480
    scene: Scene {
        fill:Color.BLACK
        content:[
            gp
        ]

    }
}⁞ 

If you are writing a generic tool tip take care of :

1. Scene size - it should not go off screen.

2. Height and Width of tool tip - Most of the tool tip has unit height but it depends on us, we can set it.

Friday Dec 19, 2008

Designer + Developer + JavaFX

Here is the little discussion on Designer + Developer workflow in JavaFX. Powered with Project Nile, we can export data from PhotoShop or Illustrator. Actually the complete production suite is awesome and provide developer and designer to work in parallel. Here how it is :

So, Developer can work on the business logic and till that time designer can design the actually content for developer. Finally it will merge in a great style. 

 Basic Requirement to do :

1. JavaFX Production Suite : Download from the start section of javafx.com.

2. For Designer : Any tool, either PhotoShop CS3 or Illustrator CS3. Officially CS3 is the supported platform but it works for CS4 as well.

3. For Developer : Java FX SDK: Download from the start section of javafx.com

Now, I am going ahead with PhotoShop. Copy the plugin from JavaFX production suite to PhotoShop. Run the PhotoShop, in export it will give you a save option in JavaFX, which basically saves the file in fxz format(a new format, why Sun need a new format, there is a lot of discussion and Jeet has pointed some reason in his blog).

Alright, so work started : 

I was watching the batman movie, so decide to take his awesome car, which is here :


In photoshop, I have changed the hue and exported all in fxz format.

Then I made a Netbeans Project, Copy the fxz file into the project space. We can now click on fxz file, we can see the preview and code as well. Right now, if we put some of the complex features of PhotoShop, I am afaird to say JavaFX will not catch those changes.

So, my fxz file(JavaFX.fxz) looks like this :

  /\*
 \* Generated by JavaFX plugin for Adobe Photoshop.
 \* Created on Fri Dec 19 19:17:33 2008
 \*/
//@version 1.0

Group {
    clip: Rectangle { x:0 y:0 width:576 height:432 }
    content: [
        ImageView {
            opacity: 1.0
            x: 0
            y: 0
            image: Image {
                url: "{__DIR__}Background.png"
            },
        },
    ]
}

Actually in my case there was nothing, so it generated a simple code :).

Now, I have made another file, calling it CarRotate.fx :

package psfx;

import java.lang.\*;
import javafx.fxd.FXDLoader;
import javafx.scene.\*;
import javafx.scene.input.\*;
import javafx.scene.paint.Color;
import javafx.scene.shape.\*;
import javafx.stage.\*;


var group = Group {
    content: []
};
var fxdContent = FXDLoader.load("{__DIR__}JavaFX.fxz"); // loads the content
insert fxdContent into group.content; // inserts the fxd content into the group


Stage {
    title: "JavaFX Invaders"
    resizable: true
    width: 700
    height: 700
    onClose: function() { 
        System.exit (0);

    }
    scene: Scene {
        content: [
            group
            Rectangle {
                x: 330,
                y: 500
                width: 60,
                height: 30
                fill: Color.GRAY
                onMouseClicked: function( e: MouseEvent ):Void {
                    fxdContent.rotate = 90;
                }
            }
        ]
    }
};


Some part of the code is point of interest :
  var group = Group {

    content: []

};

var fxdContent = FXDLoader.load("{__DIR__}JavaFX.fxz"); // loads the content

insert fxdContent into group.content; // inserts the fxd content into the group

Here I have loaded the .fxz file into var fxdContent which is a node and node means things are in our hand. I have simply written a rotate equation on a button click which is working nicely.

We can see the rotated car and hue which is the asset of PhotoShop in Green color. Huh, finally its done. Sorry, for posting bad example.

Thursday Dec 18, 2008

Initial Look of Physics App.

So, finally I decided to add all the motion(physics) application under one tree. Still I am not able to write too much of them but we will do it soon. Here are some which I merged into one and it looks like : 


Soon, the further work will be done. We will remove application like Carousel,Spring because its already in our repository. This application will also depicts 2 scene mode, how to remove content and add content dynamically.

Sorry for not posting the code, its in the mid and in a bad shape :).

Wednesday Dec 17, 2008

Playing with Color in JavaFX

JavaFX provide a rich API for playing with colors for an image or object. The best depicted in this sample but I will show you very quickly how to change the color of a car on JSlider. I have taken this nice car from Path Animation Sample and on JSlider, I will reproduce lot of Car color like this :

Actually this is very small but some one who want to develop car race required lot of car colors(it can be done at runtime)

Code here :

package carcolors;

import javafx.scene.effect.ColorAdjust;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.Scene;
import javafx.stage.Stage;
import javafx.animation.Timeline;
import javafx.animation.KeyFrame;
import javafx.animation.Interpolator;
import javafx.ext.swing.SwingSlider;

var hue = 0;
var s = SwingSlider {
                minimum: -100
                maximum: 100
                value: hue
                vertical: false
            };
Stage {
    title: "Application title"
    width: 250
    height: 280
    scene: Scene {
        content: [
            s,
            ImageView {
                x: 100
                y: 100
                image: Image {
                    url: "{__DIR__}car.png"
                }
                effect: ColorAdjust {
                    hue: bind s.value/100.0
                }
            },
         ]

    }
}

Wednesday Dec 10, 2008

Spring Motion - Physics in JavaFX

3 weeks back, we were thinking of some cool application to make. I am a guy who has seen very less outside world, so coming up with some great idea is always tough for me. So, deciding that, I went back to my tenth class physics book and saw some of the cool physics motion. Its one of the tough subject and always screw me in exam. Searching some of the easy equation, I though to make one spring motion. Meantime, I though there is some spring motion residing in our repository. Actually one of the Josh applications do it in awesome way, but still we were missing the actual feel of Spring motion because of the gig-gag and spiral stuff attached to the wall and spring is going up and down in it, with a complete view of awesomeness :). This is what finally we achieve from this blog :

 I can still bet this can be 3 times much better than what you are seeing here. So, little of good news here that this sample can be executed on mobile

Here are the code files :

1. Main file.

2. Spring file.

3. SpringEquation file.

Enjoy FX'ing !

Saturday Dec 06, 2008

Mobile + Desktop JavaFX !

Just want to put the attention on one important point regarding the coding in JavaFX. Everyone who is using JavaFX has to understand that this technology is supported on Mobile, Desktop and TV(tomorrow it will be). So, its important as a developer to write Generic Applications which run across the platform. In such cases you need to know how to adjust some silly things in the code, like so desktop it can be a big font whereas you need to reduce font size for mobile or same case with images. 

Here is one sample code, which can show you how to do :

package sample11;

import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.scene.text.Text;
import javafx.scene.text.Font;

var mobile = FX.getProperty("javafx.me.profiles");
var isMobile = (mobile != null);
var s = 24;
var content = "Default";
if(isMobile == true) {
    s = 10;
    content = "Content in Mobile"
}
else { 
    s = 20;
    content = "Content on Desktop"
}

Stage {
    title: "Checking the Font"
    width: 350
    height: 280
    scene: Scene {
        content: Text {
            font : bind Font {
                size : s
            }
            x: 10, y: 30
            content: bind content
        }

    }
}

Run it on Desktop and on Mobile and see the different output.

(How to run on Mobile ? ---> Netbeans6.5 -> YourProject -> Right Click ->Properties -> Run -> Run as Mobile Emulator)

This feature has been nicely used in this sample :  InterestingPhotos.

Monday Dec 01, 2008

A simple bad digital Clock

Here how to use Java code inside JavaFX and make a simple digital clock. Bad because i have not put the proper makeup :).

//Clock.fx

package digitalclock;

import javafx.scene.\*;
import javafx.scene.paint.\*;
import javafx.scene.text.\*;
import javafx.scene.transform.\*;
import javafx.animation.\*;
import javafx.scene.shape.\*;

// Java Legacy
import java.util.\*;

var months:String[] = ["JAN", "FEB", "MAR", "APR", "MAY", "JUN",
                "JUL", "AUG", "SEP", "OCT", "NOV", "DEC"];

public class Clock extends CustomNode {

   var radius = -20;
    // shifting the X center
    var centerX: Number = 50 ;
    // shifting the Y center
    var centerY: Number = 50 ;
    var hours:String;
    var minutes:String;
    var seconds:String;
    var date:String;
    var month:String;
    var year:String;
    var combination: String;

    // intializing the watch
    init {
        var timeline = Timeline {
            repeatCount: Timeline.INDEFINITE
            keyFrames : [
                KeyFrame {
                    time : 1s
                    action: function() {
                        actionOnTick();
                    }
                }
            ]
        }
        timeline.play();
    }
    function createCalendar() {
        var date = new Date();
        def calendar = Calendar.getInstance();
        calendar.setTime(new Date()); // fix for mobile
        calendar
    }
    // action taken on one tick
    public function actionOnTick () {
        var calendar = createCalendar();
        seconds = String.valueOf(calendar.get(Calendar.SECOND));
        if(seconds.length()!=2)  {
            seconds = "0{seconds}";
        }
        minutes = String.valueOf(calendar.get(Calendar.MINUTE));
        if(minutes.length()!=2)  {
            minutes = "0{minutes}";
        }
        hours = String.valueOf(calendar.get(Calendar.HOUR));
         if(hours.length()!=2)  {
            hours = "0{hours}";
        }
        date = String.valueOf(calendar.get(Calendar.DATE));
        if(date.length()!=2)  {
            date = "0{date}";
        }
        month = months[(calendar.get(Calendar.MONTH))];
        year = String.valueOf((calendar.get(Calendar.YEAR)));
        combination = "{hours}:{minutes}:{seconds}  {date}-{month}-{year}";
    }

    // overriding the method create()
    public override function create(): Node {
        return Group {
            transforms: [
                Transform.translate(centerX, centerY)
            ]
            content: [

                Rectangle {
                    x: -35, y: 2\*radius/3 - 15
                    width: 120 height: 20
                    fill: Color.GRAY
                    opacity:0.4
                    strokeWidth: 2
                    stroke: Color.BLACK
                    arcHeight:10
                    arcWidth:10
                },
                Text {
                    font: Font {
                        size: 11
                        name: "Arial"
                    }
                    x: -31 , y: 2 \* radius / 3
                    content: bind combination
                },
                  ]
                }
        };
} 


//Main.fx
package digitalclock;

import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.scene.text.Text;
import javafx.scene.text.Font;

Stage {
    title: "Digital Clock"
    width: 160
    height: 100
    scene: Scene {
        content: Clock{}
    }
}

Monday Sep 15, 2008

A nasty Problem - Java Code

Few days back, I got a problem in which actually I have to get the fields, constructor and method name from a java class. One can think of using reflection API and the problem is easy to solve, but that is not the case. Reflection API can only be used on class files not Java file. Than a quick idea came into mind to compile the file internally, use reflection and then delete the class file, if user don't want to see it. This is never be a tough job if I use JDK6 JavaCompiler code which is :

import java.io.IOException;

import javax.tools.JavaCompiler;
import javax.tools.ToolProvider;

public class JDK6FirstCompile {
  public static void main(String args[]) throws IOException {
    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    int results = compiler.run(null, null, null, "HelloWorld.java");
    System.out.println("Success: " + (results == 0));
  }
}


class HelloWorld {
  public static void main(String args[]) {
    System.out.println("Hello, World");
  }
}


But but, I was constraint to use JDK5 or less. So, this JDK6 API is not worth for me :-(. Finally, came up with a small code, which probably can do this in all the case. Hoping it will not lose any generic behavior and run in all cases.

Here is the code:

import java.io.\*;

public class CompileCheck {

public void compileClasses2() {
        try {
            String command = System.getProperty("java.home")+File.separator + ".." + File.separator+"bin"+File.separator+"javac " + "HelloWorld.java";
            System.out.println(command);
            Runtime.getRuntime().exec(command);
    } catch (Exception e) { }
    }


    public static void main(String[] args) {
 
        CompileCheck c = new CompileCheck();
        c.compileClasses2();
    }
}


In place of HelloWorld, I can surely use any path where the java file resides. And off course, I can use \*.java as well :-). Please let me know your opinion or any other method easier than this from which I can get class methods, attributes and all from a java file.

Tuesday Aug 05, 2008

Reflection in JavaFX - Crying baby !

On the way to exploring little more API of JavaFX, I reached to a fair animation. That is reflection. Here is the output of "crying baby". I always scare of using cartoon character because those are Copyright Image. 

 And lots of guys kicked me in the last post because code size was too big, but now its Java FX and I can also show the power of scripting :-).  Here is the code:

import javafx.application.Frame;
import javafx.application.Stage;
import javafx.scene.geometry.Circle;
import javafx.scene.paint.Color;
import javafx.scene.image.ImageView;
import javafx.scene.image.Image;
import javafx.scene.effect.\*;

Frame {
    title: "Crying Baby"
    width: 400
    height: 700
    closeAction: function() { java.lang.System.exit( 0 ); 
    }
    visible: true

    stage: Stage {
        fill: Color.WHITE
        content: [
            ImageView {
                x: 100
                y:10
                image: Image {
                    url: "http://www.powermixradio.com/GGG-SAD-CARTOON.jpg"
                }
                effect: Reflection { 
                    bottomOpacity:0.1
                    fraction: 1 
                    topOffset: 50
                }  
            },
            ImageView {
                x:0
                y:300
                image: Image {
                    url: "http://www.toyotapartsstore.com/images/71111_2_%20mirror_8CE1.jpg"
                }
                opacity:0.5
            }
        ] 
    }   
}


Things to watch:

1. Effect: Reflection -

bottomOpacity:0.1 - set the opacity of image in reflection.

fraction: 1 - set how much part of the image should come in reflection. 

topOffset: 50 - How far image from the focus. There are some more useful parameters in this.

2. Opacity of second Imageview allow me to see the reflection of first image, else it will cover the reflection.

On the way to make some moving animation, but I don't know what happened to the support of gif image. gif image works like static image, don't know why ?

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 :-)

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>

Sunday May 25, 2008

This is always confusing :(

Java is well known language in itself for the consistent API and always motivate user to follow good naming convention. But small confusion always wired me. Most of the time,Enumeration and Iterator code goes in the same manner but off course for different use. We generally check for having next element in a while loop and if yes, we manipulate something out of it. I find something confusing here :

Iterator it = ...
while(it.hasNext())
{
...it.next()...
}

Enumeration e = ...
while(e.hasMoreElements())
{
...e.nextElement()...
}

Why such a confusing API here? What was wrong if we have e.hasNext() and e.next() in place of e.hasMoreElements() and e.nextElements(). Should be easy for user to remember only one pattern !

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