Showing posts with label API. Show all posts
Showing posts with label API. Show all posts

Monday, August 24, 2009

Hyperlink in JavaFX


It's a long time being blogging. Actually not done anything new from long time :). Here is one simple concept which some guys asked me. We have provided hyperlink API in JavaFX 1.2 but some of us struggled to open a URL using hyperlink API.


Hmm, 2 ways to do it actually.


No1 : Use the Desktop API of JDK6. It's simple to use. One example is here.


So, very basic code will go like this :


  

package sample2;

import javafx.scene.Scene;
import javafx.stage.Stage;
import javafx.scene.control.*;
import java.net.*;

Stage {
title: "HyperLink to URL"
width: 240
height: 320
scene: Scene {
content: [
Hyperlink{
translateY: 160
translateX: 40
width: 150
text: bind "Visit javafx Samples! "
action: function():Void{
java.awt.Desktop.getDesktop().browse(new URI("http://javafx.com/samples"));
}
}
]
}
}




So, 2 things for running this code. First,Desktop API has been added in JDK6, so this code won't run on JDK5. Second, Add rt.jar(rt.jar of JDK6) file in the Libraries if you are using Netbeans


No2 : For only JavaFX code, we can use AppletStageExtension like this :


package sample1;

import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.scene.control.Hyperlink;
import javafx.stage.AppletStageExtension;

Stage {
title: "Hyperlink to URL"
width: 250
height: 80
scene: Scene {
content: [
Hyperlink {
text: "JavaFX Samples !"
action: function() {
AppletStageExtension.showDocument("http://javafx.com/samples");
}
}
]
}
}





In this case, you cant send hyperlink from Desktop Application, but it will work fine for applet or Browser application. So, best is to use this and then use our normal funda : if {__PROFILE__}" != "browser") --> use the Desktop API code. What you say :).


Please let me know if there is any issue in the code ! Or also if there is any better way to do this.




Java Debugging basics

Some simple debugging tools related to Java. These are for those who are new to Java.

1. Application is crashing : Most miserable one. Get your log file, try to analysis log. How to write log file, use Java Logger API. Java Logger had been introduced in JDK 1.4.2. The most awesome feature of Logger API is that you can use it in production without much overhead. The overhead is controlled by something called level in API. Level goes from FINEST to SEVERE. You can refer to O'Relly Book "Java, In a NutShell". I guess, it covers Logging API into a great detail.

Lot many things to know: Standalone application is crashing or web application. Its crashing with -client or -server option, appletviewer or browser, plugin or plugin2.

2. Application Hang: Most prominent reason for Hang is thread related. I don't know too many language but Java handles thread in most graceful way. What we can do when a Java Process or Application Hang:

- Hmm, get stack trace at Java and native level.
- Get to know current thread conditions and their status.
- Try to get core dump. Sometime, application will refuse to give you.
- Get to know machine detail. Almost all OS, use different thread model. Not only that in Solaris, 8 and 9 use different models. Sometime, it narrow down the problem, if you are luck :).

How to get all these information. Easy actually. Take help of Java Debugger, jdb(which is a part of JDK). In jdb, you can run the command like threads, thread, dump and many more. Take help of Windbg, if its a windows machine for native level. I find it useful and painful.

3. Your application is drinking memory: There is some memory leak. Best is to use jhat(part of JDK). First take a heap dump by using jmap, jconsole hprof. Pass that heap dump to jhat and it will bring a server and

dump all the information. Analyze where most of the memory is going. Writing to track the place from where memory is going. What is GC response on it. Change some arguments of GC and then give a try.


There are lot of JDK tools that help in analyzing JVM, threads, memory, process. See the list : http://java.sun.com/javase/6/docs/technotes/tools/

Garbage collector play important role in all of them, so always get to know what is best for what:- http://java.sun.com/javase/technologies/hotspot/gc/gc_tuning_6.html (Even you know less about GC, you can't resist yourself finishing this page, this is so interesting). In terms of GC, everything is improving day be day and we have new GC, Garbage First aka G1 ready. With Vikram, I had one presentation on G1 in Sun tech days - http://developers.sun.com/events/techdays/presentations/locations-2009/hyderabad/td_hyd_garbagcollector_aroskar_choudhary.pdf.

If you have any wired debugging story related to Java, please share :). Also, visit Visual VM which is meant to integrate all the command line tools of JDK.

Monday, December 22, 2008

JavaFX production Suite - How it work

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.

JavaFX - Developer and Designer work !

One more example of JavaFX production Suite. Though the complete thing can be done in Photoshop alone but I am just giving an example. I have made a house in Photoshop, which is not very good :(, but fair enough. And I animated the star effect in JavaFX.


So, here is my home in photoshop :



Actually this is funny, I was following a tutorial to make house and in temptation, I made shadow as well, but there is no meaning of shadow in night :). Now, I filled star sparking effect in this from JavaFX.




Filling star effect need same which we have written for sparkling glasses. Just some changes here and there. In the last blog we have already discussed how to import work from Photoshop.

Here are the things to download:

1. House in fxz format .

2. Code (Main.fx, Star.fx)

Lot many things can be done. But I don't know Photoshop.

Wednesday, December 10, 2008

Physics Motion - Spring 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



Regret to say, ball will not look like a real 3D ball in FX Mobile because of Bug ID: RT-2205, which basically speaks that Mobile Runtime don't understand Radial Gradient, hoping this will be fixed soon.

Here are the code files :

1. Main file.

2. Spring file.

3. SpringEquation file.

Enjoy FX'ing !

Tuesday, December 09, 2008

3D E'FX's in JavaFX

Me and Vikram was looking today some of the cool flash examples and I have seen the button effect at some place, when you press the button it really goes like inside and coming out. But that was an effect achieved by the images(two different images, one unpressed button and one pressed button) and then we thought to simulate this effect by code. Somehow we are able to do that in FX, here is the final outcome:




What we have tried to do is pressing one button will put the other in unpressed mode and vice-versa. This has been achieved by some of the cool API's of JavaFX. And we have used the DistantLight effect of JavaFX which gives a lighting effect in its awesome way. Actually this can be more cooler but I left that for developer to modify it according to their need :). But this is a modular code and can be used in any of the button place.


Here is the simple code for the same(again code is not written in the most optimized way but in the best way for understanding) :



package lighteff;

import javafx.scene.effect.light.DistantLight;
import javafx.scene.effect.Lighting;
import javafx.scene.Group;
import javafx.scene.input.MouseEvent;
import javafx.scene.paint.Color;
import javafx.scene.paint.RadialGradient;
import javafx.scene.paint.Stop;
import javafx.scene.Scene;
import javafx.scene.shape.Circle;
import javafx.scene.text.Font;
import javafx.scene.text.Text;
import javafx.stage.Stage;
import javafx.stage.StageStyle;

var factor = 5;
var scale = 1.0;
var factor1 = 10;
var scale1 = 0.85;

Stage {
title: "Control Panel"
width: 290
height: 180
style: StageStyle.UNDECORATED
scene: Scene {
fill: Color.BLACK
content: [
Group {
effect: Lighting {
light: DistantLight {
azimuth: 90
elevation: 60
}
surfaceScale: bind factor
}
content: [
Circle {
centerX: 100,
centerY: 100
radius: 40
fill: Color.RED


onMousePressed: function( e: MouseEvent ):Void {
scale = 0.85;
factor = 10;
scale1 = 1.0;
factor1 = 5;
}
},
Text {
fill: Color.WHITE
scaleX: bind scale
scaleY: bind scale
font: Font {
size: 24
}
x: 71,
y: 105
content: "Press"
}
]
},
Group {
effect: Lighting {
light: DistantLight {
azimuth: 90
elevation: 60
}
surfaceScale: bind factor1
}
content: [

Circle {
centerX: 200
centerY: 100
radius: 40
fill: Color.BLUE
onMousePressed: function( e: MouseEvent ):Void {
scale1 = 0.85;
factor1 = 10;
scale = 1.0;
factor = 5;
}
},
Text {
fill: Color.WHITE
scaleX: bind scale1
scaleY: bind scale1
font: Font {
size: 24
}
x: 171,
y: 105
content: "Press"
}
]
}
]

}
}

Wednesday, August 06, 2008

JavaFX Reflection Game !

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".
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, August 04, 2008

Play with Flickr API in Java !

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, May 11, 2007

How to get ?

I was trying to automate some of my manual work, I came across one problem. Is java providing any option by which if I give the file name and directory name it will go ahead and search that file in the given directory or sub-directory and return me the complete path of the file ? Unfortunately not :(, there is no direct API that can do this work for me. But Kannan told me that one can make a code which can recursively do this work. And he already had written some code for this. I was trying to tackle this problem with a different approach. The approach is something like:

On windows, dos gives me an option to search a file in a dir or sub-dir by command:
dir filename /s
Linux and Solaris gives me option of search the same by command: find /directory_name filename
So, why not using the runtime option of java system class and write a code like:

if ( OS == Windows) {get it by dir filename /s}
elseif (OS == Linux or Solaris or Unix){get it by find /directory_name filename}
else {God Knows only :)}
Right now I am not ready with code(because this dos is not giving anything directly, so need to remove useless things) but will come back soon with the results and the optimal code. Any suggestions are most welcome.