Friday Mar 26, 2010

Tech Days 2010 @ Hyderabad

2010 Sun Tech days over. Nice time at presentation and in train too. Nothing more to write. James was good. 

Presentation here: 

 G1 presentation  and mixing Lightweight/Heavyweight components.

Tuesday Dec 22, 2009

LiveConnect improvement in JDK6

JDK6 has done lot of changes in LiveConnect. LiveConnect is a feature in the browser for communication between Java Applet and JavaScript. With the new Plugin2, most of the work has been left on browser to do. Initially it was Java which do a good amount of work. So, now the Java Plug-in will operate like any other scriptable Plug-in. ..............
[Read More]

Tuesday Dec 15, 2009

Lightweight and Heavyweight components - Mess it !

So, if you are a Swing Developer, you have heard many stories where someone messed Lightweight component with Heavyweight component. In one line " A heavyweight component is one that is associated with its own  native screen resource (commonly known as a peer). A lightweight component is one that "borrows" the screen resource of an ancestor  (which means it has no native resource of its own -- so it's "lighter")."

 Now many times you have heard "Don't mix lightweight and heavyweight". What will happen ? Alright, here is a small code : ............

[Read More]

Wednesday Nov 25, 2009

Sorting and OpenJDK

If you are looking for sorting algorithms and if you use some sorting algorithm in your code/application/big application, then have a look here. First of all sorting/searching is a classic thing. It take more than 70 percent of your application time.People/Developer/Mathematician do a lot of work on optimizing this work to get Best, best out of best.

Early days, JDK used to use QuickSort which is one of the best sorting algorithm and go for a complexity of O(nlogn). But mind it, QuickSort is a recursive algorithm and consume space. Whereas some of the algorithm which has the complexity like O(n\^2) go for less complex in terms of memory. These days our platform varies from small mobile device to a terabyte storage machine............

[Read More]

Monday Aug 24, 2009

Debugging basics and some link - Java

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. ...........
[Read More]

Wednesday Aug 12, 2009

Netbeans Java Presentation

Small presentation(actually very small) on Netbeans and Java. Mostly covers the features, netbeans provide for Java SE. Like Profiling, Debugging..

http://blogs.sun.com/vaibhav/resource/BasicOfNetbeans_Java.pdf



Friday May 29, 2009

Welcoming JavaOne

Straightaway to JavaOne : http://java.sun.com/javaone/

Best wished to all the presenters and attendees. JavaOne going to rock :).

PS: Sorry, no technical writing in this post.

Tuesday Jan 06, 2009

Managing Java Process from Java Code

Back to Java :). Here is a small blog on how to manage Java Process from Java itself.

Long back, I had written one blog on how to list Java Process running on System by Java Code. But with the new features of JDK6, you can not only see the list but can manage the other running Java Process. This is possible using class LocalVirtualMachine. This class has a list of methods :

connectorAddress,
displayName,
getAllVirtualMachines,
getLocalVirtualMachine,
isAttachable,
isManageable,
startManagementAgent,
toString,
vmid

Here I am just showing a simple code, which will again tell you all the running Java Process.

import sun.tools.jconsole.\*;
import java.util.\*;
public class Main {

public static void main(String[] args) {
Map map = LocalVirtualMachine.getAllVirtualMachines();
Iterator iter = map.values().iterator();
LocalVirtualMachine vm = null;
while (iter.hasNext()) {
vm = (LocalVirtualMachine)iter.next();
System.out.println(vm.displayName());
}
}
}

A very very small code :). Note that this class is not in rt.jar so we need to add jconsole.jar and tools.jar in the classpath section.
So, for running we need to use :

D:/Program Files/Java/jdk1.6.0_11/bin/ControlJavaApp>../javac -cp "D:/Program Fi
les/Java/jdk1.6.0_11/lib/jconsole.jar" Main.java

D:/Program Files/Java/jdk1.6.0_11/bin/ControlJavaApp>../java -cp .;"D:/Program F
iles/Java/jdk1.6.0_11/libjconsole.jar";"D:Program Files/Java/jdk1.6.0_11/lib/t
ools.jar" Main

Or we can modify classpath in Env. Variables.

Right now, in my system it is displaying:

Main
org/netbeans/modules/javafx/preview/Main 1
That means, this code itself and Netbeans is running as a java process.

In next blog, we will try to see how to manage(not listing) other running java code from a java code. I am not able to find too much of doc from net, so things are slow :).

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{}
    }
}

Wednesday Nov 26, 2008

Plug-in 2 - New/Old Plug-in's

With Plug-in 2(Java 6u10), a whole new experience comes into Java Plug-in. I have mentioned the new features of Plugin2 in some of my presentations of 6u10.

For detail, please visit this link : http://java.sun.com/javase/6/webnotes/6u10/plugin2/index.html

Switching between old/new plugin:

Java Control Panel - Advanced - Java Plug-in - Enable the next gen plug-in.

(Check this link : http://www.java.com/en/download/help/new_plugin.xml)

By default, it will take new plugin, but untick it for old plugin.

Wednesday Nov 19, 2008

Java Market Trend

Today I got a mail from Carl. He works in a company which provides Marketing stats. Here are some of the exciting marketing stats of Java :

1. Median Salary :


Generated By: OdinJobs - Techonology Job Search Engine

2. Jobs Trend line

Compare Market Statistics Generated By: OdinJobs - Techonology Job Search Engine

3. Salary Histogram :

Compare Market Statistics Generated By: OdinJobs - Techonology Job Search Engine


Now, see the market increase in Java Gaming.And there is a reason behind it, people start realizing that Java is fast and a suitable language for gaming. It happened for quite a long time developed used to think that Java is a slow language and not meant for game.

Compare Market Statistics Generated By: OdinJobs - Techonology Job Search Engine

Banking sector, this is quite obvious because of the market fall down, else it was little above than the last year performance.

Compare Market Statistics Generated By: OdinJobs - Techonology Job Search Engine

Defense: This is quite an interesting market. It speaks about the robustness and security of Java. Defense finds it the best language for their purpose.

Compare Market Statistics Generated By: OdinJobs - Techonology Job Search Engine

For more visit this link : Java Market Stats

Sunday Sep 21, 2008

Java - Instruction set rather than time

One guy asked a question on a Java Forum: which operation is faster - post-increment or pre-increment. I really don't feel these things make a big difference in code performance. I have written a small code to check what nanosecond API of Java is telling about it. And again I reached to a wrong benchmarking. 

class InstructionCheck {
    private int x = 0;
 
    public void countup_() {
        ++x;
    }
    public void countup() {
        x++;
    }
    public void countdown() {
        x--;
    }
    public void count2up() {
        x = x+2;
    }
    public void count2down() {
        x = x-2;
    }
    public static void main(String[] args) {
        long stime = 0;
        long etime = 0;
        InstructionCheck ic = new InstructionCheck();

        stime = System.nanoTime();
        ic.countup_();
        System.out.println(System.nanoTime() - stime);

        stime = System.nanoTime();
        ic.countup();
        System.out.println(System.nanoTime() - stime);

        stime = System.nanoTime();
        ic.countdown();
        System.out.println(System.nanoTime() - stime);

        stime = System.nanoTime();
        ic.count2up();
        System.out.println(System.nanoTime() - stime);

        stime = System.nanoTime();
        ic.count2down();        
        System.out.println(System.nanoTime() - stime);
    }
}         

And the output after several run: 

20952
5308
5587
5587
5308

Now, no doubt the first value is not correct, because of some other reason(I really don't know why) but may be some reigster setting, first time using the class or something else.

But if we see the assemble code, it will simple say that there is(should) no difference in ++i or i++. Look at this :

public void countup_();
  Code:
   0:   aload_0
   1:   dup
   2:   getfield        #2; //Field x:I
   5:   iconst_1
   6:   iadd
   7:   putfield        #2; //Field x:I
   10:  return

public void countup();
  Code:
   0:   aload_0
   1:   dup
   2:   getfield        #2; //Field x:I
   5:   iconst_1
   6:   iadd
   7:   putfield        #2; //Field x:I
   10:  return

The complete assemble code, you can see by option javap -c FileName. My personal opinion is to check the instruction set rather checking the time by nanosecond or millisecond because some benchmarking issue can lead to a different result(which can be completely wrong, like in our case). Here we can easily see that ++i and i++ leads to same instruction and hence both will be more or less equal in performace.

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.

Saturday Sep 13, 2008

Last week.. a competition code !

Last week, IEC celebrates OpenSource Mela. In code war, we got a programming contest in which the problem statement is :

5 \* 4 / 2 - 5 + 2 = 7 (evaluated from left to right). So, input format is:

5 4 2 5 2 7

and output is to put into a valid expression format(all possible format). So, if its 2 2 4, then 2+2=4 and 2\*2=4 is possible. I have written some code for this, which goes here :

package problemstatement1;

import java.util.List;

public class Main {

    String input = "2 0 2";
    String output = new String();  // 5 \* 4 / 2 - 5 + 2 = 7
    int resultVal = 0;
    String operatorseq = new String();
    int result = 0;
    int totalcounter = 0;
    boolean flag = true;
 
    // converting input into easy format
 
    String[] inputtoken = input.split(" ");
    int[] numberseq = new int[inputtoken.length - 1];
    int totaloperator = numberseq.length - 1;
 
    public void isValid() {
        if (inputtoken.length < 3) {
            System.out.println("Usages ... Input Parameter should be three or more ");
            System.exit(0);
        }
    }

    public void processInput() {
        try {
        resultVal = Integer.parseInt(inputtoken[inputtoken.length - 1]);
        } catch(NumberFormatException e) {
            System.out.println("Parsing error" + "  " + e);
            System.exit(0);
        }
        for (int i = 0; i < numberseq.length; i++) {
            try {
            numberseq[i] = Integer.parseInt(inputtoken[i]);
            } catch(NumberFormatException e) {
                System.out.println("Parsing error" + "  " + e);
                System.exit(0);
              }
        }
    }

    public void showInput() {
        for (int i = 0; i < numberseq.length; i++) {
            // System.out.println(numberseq[i]);
        }
    }

    public void getPermutation() {
        GenerateOperators gen = new GenerateOperators("+-\*/", totaloperator);
        List<String> v = gen.getVariations();
        System.out.println("Possible Solutions");
        for (int i = 0; i < v.size(); i++) {
            operatorseq = v.get(i);
            manupulate();
        }
    }

    public void manupulate() {
 
        result = 0;
 
        for (int i = 0; i < operatorseq.length(); i++) {
            if (i == 0) {
                if ((operatorseq.charAt(i)) == '+') {
                    result = result + (numberseq[i] + numberseq[i + 1]);
                }
                if ((operatorseq.charAt(i)) == '-') {
                    result = result + (numberseq[i] - numberseq[i + 1]);
                }
                if ((operatorseq.charAt(i)) == '\*') {
                    result = result + (numberseq[i] \* numberseq[i + 1]);
                }
                if ((operatorseq.charAt(i)) == '/') {
                    try {
                    result = result + (numberseq[i] / numberseq[i + 1]);
                    } catch(Exception e) {
                        flag = false;
                        // don't do anything
                    }
                }
            } else {
                if ((operatorseq.charAt(i)) == '+') {
                    result = result + numberseq[i + 1];
                }
                if ((operatorseq.charAt(i)) == '-') {
                    result = result - numberseq[i + 1];
                }
                if ((operatorseq.charAt(i)) == '\*') {
                    result = result \* numberseq[i + 1];
                }
                if ((operatorseq.charAt(i)) == '/') {
                    try {
                        result = result / numberseq[i + 1];
                    } catch(Exception e) {
                        flag = false;
                        // don't do anything
                    }
                }
            }
        }
        if (result == resultVal && flag == true) {
            totalcounter++;
            System.out.println("");
            for (int i = 0; i < numberseq.length - 1; i++) {
                System.out.print(numberseq[i] + "" + operatorseq.charAt(i));
            }
            System.out.print(numberseq[numberseq.length - 1]);
            System.out.print("= " + result);
        }
     }

    public void count() {
        if(totalcounter == 0 ) {
            System.out.println("NO EXPRESSION POSSIBLE");
            System.exit(0);
        }
        else {
            System.out.println("");
            System.out.println("Total Possible Solution :" + totalcounter);
        }
    }
    public static void main(String[] args) {
        Main main = new Main();
        main.isValid();
        main.processInput();
        main.showInput();
        main.getPermutation();
        main.count();
    }
}

and one more file which is : 

package problemstatement1;

import java.util.List;
import java.util.ArrayList;

public class GenerateOperators {

   private String a;
   private int n;

   public GenerateOperators(String a, int n) {
       this.a = a;
       this.n = n;
   }

   public List<String> getVariations() {
       int l = a.length();
       int permutations = (int) Math.pow(l, n);
       char[][] storeCombination = new char[permutations][n];
       for (int x = 0; x < n; x++) {
           int temp = (int) Math.pow(l, x);
           for (int p1 = 0; p1 < permutations;) {
               for (int al = 0; al < l; al++) {
                   for (int p2 = 0; p2 < temp; p2++) {
                       storeCombination[p1][x] = a.charAt(al);
                       p1++;
                   }
               }
           }
       }

       List<String> result = new ArrayList<String>();
       for (char[] permutation : storeCombination) {
           result.add(new String(permutation));
       }
       return result;

   }

   public static void main(String[] args) {
       GenerateOperators gen = new GenerateOperators("AAAMMBR", 7);
       List<String> v = gen.getVariations();
             for (int i=0;i<v.size();i++) {
           String s1 = v.get(i);
           System.out.println(s1);
       }

   }
}

Feel free to use this code :-).



Sunday Sep 07, 2008

Sunday work - Tracing in FX and Blog Change :-)

 I did some fine tuning in my blog page after long time :-). I have added two more link in Links section, which can be helpful in :

1. Telling which JRE's are there on your machine(blog readers) machine.

2. And second will install the latest JRE(It will start installation directly, so careful :-D)

Alright, So now again one post for JavaFX. Finally I am able to write tracing path code in JavaFX. I have seen this in lot of Physics Motions where they show motion with tracing effect. Have a look at the output :

Here the ball is moving in a cosine fashion and so the trace. Easiest way to achieve this is to write code in update method. Have a look on the code, its small:

package tracemotion;

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

import java.lang.System;
import java.lang.Math;

var t : Number = 0.0;

Frame {
    var input : TracingBall = TracingBall {};
    stage : Stage {
        fill: Color.BLACK;
        content : bind [
            input
        ]
    }
 
    visible : true
    title : "Tracing Ball"
    width : 600
    height : 600
    closeAction : function() { java.lang.System.exit( 0 ); }
}

class TracingBall extends CustomNode {

    attribute tracingballs : Circle[];
    attribute length : Integer = 600;
    attribute timer : Timeline = Timeline {
        repeatCount: Timeline.INDEFINITE
        keyFrames :
            KeyFrame {
                time : 100ms
                action : function() {
                    update();
                    t = t+0.3;
                }
            }
    }
 public function update() : Void {
        for( i in [0..length - 30] ) {
            tracingballs[i].centerX = tracingballs[i+30].centerX;
            tracingballs[i].centerY = tracingballs[i+30].centerY;
            tracingballs[i].radius = tracingballs[i+30].radius;
            tracingballs[i].opacity=0.4;
        }
        tracingballs[length] = Circle {
           centerX : bind(100 + t \* 30), 
           centerY : (300 + Math.cos(t) \* 100), 
           radius : 30, 
           fill : bind LinearGradient {
                    proportional: true
                    stops: [
                        Stop { offset: 0.0 color: Color.RED },
                        Stop { offset: 1.0 color: Color.GAINSBORO },
                    ]
                },
           opacity : 1.0 
 
        };
 }
 public function create(): Node {
        return Group {
            content : bind[tracingballs]   
        };
 }
 init {
        for( i in [0..length] ) {
            insert Circle { fill : bind LinearGradient {
                    proportional: true
                    stops: [
                        Stop { offset: 0.0 color: Color.RED },
                        Stop { offset: 1.0 color: Color.GAINSBORO },
                    ]
                },
                } into tracingballs;
 
        }   
        timer.start();
    }        
}
Some lines in code are filling those fancy colors in ball(some lines are hard coded as well).I am a real bad guy in filling nice catchy colors(this color looks like a sun and a moon combination). Any comments/improvements are welcome !
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