Java Code Geeks

Wednesday, March 17, 2010

JSF and PopUP

By default JSF has no support for PopUps, unless you are using any custom JSF component library like Tomahawk (http://myfaces.apache.org/tomahawk/index.html), it is tough to achieve pop ups in JSF.
Lets say we want to create a web page which shows a link and on click of that link, one popup should appear with details of the element clicked. This is a very standard requirement like on click of "username" the pop up window should display the details of the user. In JSF it becomes tough because onclick event we can fire a javascript but that is not in sync with the backend action bean.
There is however an easy solution for this problem. The solution is to do the followings
1. Create one controller and bind it to the request scope
2. On click, form a URL which will look like this "newpage.jsp?param1=val"
3. The controller should read the params passed in the URL and process accordingly, for example in this case, the param would be the name of the user and the controller should contact LDAP or backend database server to fetch details data.
The controller can get the details of the parameters passed along with the URL by using FacesContext.getCurrentInstance().getExternalContext().getRequestParameterValuesMap() - this will return the map whose key is the parameter name passed in the URL.

Friday, March 12, 2010

My Status update

wow just by looking at my blog, I am figuring out how much busy I was in last couple of months. Well, 2010 is here with lots of activity for myself. The first major change was breaking up with HP. It was a long relationship - around 7 years, found myself becoming very comfortable, so decided to leave and come to US as a consultant.
As a consultant, I am doing some pretty good work in last three month or so. I worked on JSF, worked on Webservices - Axis2 (and SwA).. its cool. I want to write about JSF 1.1 and PopUp, will post it as soon as I get some free time.

Monday, December 7, 2009

JAX-RPC and JAX-WS - how does the SOAP look?

Lets consider a method like the following –

public void purchaseOrder(String item, int quantity, String description)

When this method is serialized to SOAP packet using JAX-RPC engine, the packet looks like the below





This is called SOAP encoding. The method name is the root element under the Body tag of the soap packet. Each parameter is having type defined and the value. This type will be used by the SOAP brokers/engines to de-serialize to String or int values.

The same method needs to be written like “public void someMethod(PurchesOrder po)”
to be serialized to the similar SOAP packet using JAX-WS Document literal engine .
The same method can be left unchanged to be serialized to the similar SOAP packet using JAX-WS Document literal Wrapped (wrapped means, the parameters are wrapped inside the method name) engine .
The sample SOAP packet for JAX-WS is shown below-




In case of JAX-WS, the entire XML inside the Body is deserialized to an JavaBean following JAXB. The WSDL will contain the XSD for the PurchesOrder Bean.

Monday, August 24, 2009

Anti Patterns

Just finished reading this book on anti patterns. It is a very nice book which describes how we (the developer as well as the architects and managers) fail to deliver a software project properly even after all of our good intentions. Sometimes we follow wrong architecture, sometime the deadly sins of sloth, narrow-mindness, Apathy towards technology etc etc..
I quite like the anecdotal evidences that the authors have come up with for each of the well known anti patterns. While reading the book, sometimes I just jumped out from chair and shouted "oh god, I have experienced such problems before". I am sure, as a developer or lead or budding architect, I will be very careful now onwards to look for anti patterns while designing as well as while doing coding or reviews.

Sunday, May 31, 2009

Futuristic Build Process

Build – by definition is to compile all the source code of a project and create the deliverables. For example, build is to compile all Java code using ant or maven and then create the executable jar files or war files or ear files.

An effective build system goes long way to help the project. Nightly or at least weekly development build bits are essential to check the status of the project. Lets divide build systems in its effectiveness.

Step 0 – Build system checks the syntax errors. This is really basic and a must do for build systems. If there is a syntax error in any code , build should fails. It usually does as the compiler stops if there is a syntax error.

Step 1 – Build fails if the unit test fails on the code. This is where most of current projects are. Build fires the compilation, followed by creation of deployable jars/wars. As the last step, build fires the JUnit test cases. If the JUnit test case fails, build breaks. This makes sure the build output is sane and no unit test cases have failed on the build output.

Step 2 – Now lets consider of a build system which breaks if the code checkin has more complexity than the standard, or if the code coverage of the code checkin is less. There are several software metrics that are available now, like “Code Coverage”, “Cyclomatic complexity of code”, “CRAP Metric (Change Risk Analyzer and Predictor)”. [ there are already plugins available on the CRAP and Cyclomatic Metric, where can be found here]

If Build system is integrated with calculation of these metrics, that would guarentee a uniform code complexity and if anytime code complexity numbers come high from the code analysis tools, build should break. This is surely a cool thing to do considering the fact that now-a-days much of the code is getting auto generated. Example, you have a webservice which was using Framework version 1 {like axis1} and you were compiling WSDL file to generate the stub code. You move to Version 2 and build breaks because the auto generated code is more complex and hard to maintain.

It should be a collective decision of the project team whether to go for higher complexity of the code as a team.


This is where at Step2, I think the next generation build systems will go.

Saturday, March 21, 2009

How to connect to Tomcat to gather information from JMX MBeans?

Tomcat provides see of information through its JMX MBeans. It is also easy to connect to tomcat over JMX, just run tocat using the following options -



  1. -Dcom.sun.management.jmxremote.port=9999

  2. -Dcom.sun.management.jmxremote.ssl=false

  3. -Dcom.sun.management.jmxremote.authenticate=false



This will start the tomcat server on port 9999. Use these JVM options in the catalina.bat file - and keep them as JAVA_OPTS.

Once tomcat has opened this port, connect to tomcat using this sample code -



  1. JMXServiceURL jurl = new JMXServiceURL("service:jmx:rmi:///jndi/rmi://localhost:9999/jmxrmi");

  2. JMXConnector jmxc = JMXConnectorFactory.connect(jurl, null);

  3. MBeanServerConnection mbsc = jmxc.getMBeanServerConnection();



This will connect to the tomcat server running on localhost with port 9999.

To fetch the value of an attribute - use the following code -



  1. mbsc.getAttribute(
    new ObjectName(ManagementFactory.RUNTIME_MXBEAN_NAME, "VmVersion");



The above code will fetch the JVM version of the tomcat JVM using the standard runtime MBean of the JVM.

Sunday, January 25, 2009

Trie in Java

Trie is a good datastucture, details can be found here - http://en.wikipedia.org/wiki/Trie . I came across Trie while performing "Prefix" based searching. Have you ever Wondered what Data Structure is used behind the Mobile SMSes ? When we type SMS, it finishes the words or proposes what could be the end of the word. They are usually done by Trie or data structures like Trie.
Trie consumes less space so they are hot favourite data structures on PDAs or devices with less memory. Searching of a string in Trie takes around O(m) where m = length of the key. Compare it with Binary Tree which is O(logn) where n = number of elements in the tree. For a dictionary, this n could be real large.

Here is a simple implimentation of the Trie..
One class is called Node class which holds the Key and the value.



  1. public class Node {


  2. private char key;

  3. private String value;

  4. private List children;

  5. private boolean isTerminal;

  6. public boolean isTerminal() {

  7. return isTerminal;

  8. }

  9. public void setTerminal(boolean isTerminal) {

  10. this.isTerminal = isTerminal;

  11. }

  12. public Node(char key,String value)

  13. {

  14. this(key,value,new ArrayList());

  15. }

  16. public Node(char key, String value, List children) {

  17. super();

  18. this.key = key;

  19. this.value = value;

  20. this.children = children;

  21. }


  22. public char getKey() {

  23. return key;

  24. }

  25. public void setKey(char key) {

  26. this.key = key;

  27. }

  28. public String getValue() {

  29. return value;

  30. }

  31. public void setValue(String value) {

  32. this.value = value;

  33. }

  34. public List getChildren() {

  35. return children;

  36. }

  37. public void setChildren(List children) {

  38. this.children = children;

  39. }


  40. public void addChildren(Node child)

  41. {

  42. this.children.add(child);

  43. }






}

And the Main Trie class which builds the tree and finds any key...


package com.ds.trie;


  1. import java.io.BufferedReader;

  2. import java.io.File;

  3. import java.io.FileNotFoundException;

  4. import java.io.FileReader;

  5. import java.io.IOException;

  6. import java.util.ArrayList;

  7. import java.util.LinkedList;

  8. import java.util.List;

  9. import java.util.Queue;


  10. public class Trie {


  11. private Node root;

  12. private File fname;


  13. public Trie (String filename)

  14. {

  15. this.root = new Node('r',"root");

  16. this.fname = new File(filename);

  17. }


  18. public void buildTrie()

  19. {

  20. try {


  21. if (!fname.isFile())

  22. throw new FileNotFoundException("");

  23. BufferedReader f = new BufferedReader(new FileReader(fname));

  24. String key;

  25. try {

  26. while ((key = f.readLine()) != null)

  27. {

  28. // making value = full name only = key

  29. build(key,root,key);

  30. }

  31. } catch (IOException e) {

  32. // TODO Auto-generated catch block

  33. e.printStackTrace();

  34. }

  35. } catch (FileNotFoundException e) {

  36. // TODO Auto-generated catch block

  37. e.printStackTrace();

  38. }

  39. }


  40. // key = shamik

  41. private void build(String key,Node root,String value) {

  42. // TODO Auto-generated method stub

  43. char c = key.charAt(0); // c = s

  44. String tail = null;

  45. if (key.length() > 1)

  46. tail = key.substring(1); // hamik

  47. Node resultNode = findKeyinChildren(root,c); // find 's' in the children

  48. if (resultNode == null)

  49. {

  50. // this is a new key

  51. Node newNode = new Node(c,value);

  52. if (tail == null)

  53. newNode.setTerminal(true);

  54. else

  55. newNode.setTerminal(false);


  56. root.addChildren(newNode);

  57. if (tail == null)

  58. {

  59. return;

  60. }

  61. else

  62. build(tail,newNode,value);

  63. }

  64. else // got the key - s

  65. {

  66. if (tail == null)

  67. return;

  68. build (tail,resultNode,value);

  69. }

  70. }


  71. private Node findKeyinChildren(Node root, char c) {

  72. // TODO Auto-generated method stub

  73. List list = root.getChildren();

  74. if (list == null || list.size() == 0)

  75. return null;

  76. for (int i=0; i < list.size(); i++)

  77. {

  78. Node oneNode = list.get(i);

  79. if (oneNode.getKey() == c)

  80. return oneNode;

  81. }

  82. return null;

  83. }


  84. public List findKey(String key)

  85. {


  86. String value = null;

  87. List values = new ArrayList();


  88. Node resultNode = findinTrie(key,root);


  89. if (resultNode == null)

  90. {

  91. value = "Not found";

  92. values.add(value);


  93. }

  94. else

  95. {


  96. printTree(resultNode,values);


  97. }

  98. return values;


  99. }


  100. private void printTree(Node resultNode,List values) {

  101. // TODO Auto-generated method stub

  102. List list = resultNode.getChildren();


  103. if (resultNode.isTerminal())

  104. values.add(resultNode.getValue());


  105. if (list.size() == 0)

  106. {


  107. return;


  108. }

  109. else

  110. {

  111. for (int i=0; i<list.size();i++)

  112. {

  113. Node oneNode = list.get(i);

  114. printTree(oneNode,values);

  115. }

  116. }

  117. }


  118. private Node findinTrie(String key, Node root) {

  119. // TODO Auto-generated method stub

  120. // Implementing the Breath First Traversal

  121. char first = key.charAt(0);

  122. String tail = null;

  123. if (key.length() > 1)

  124. tail = key.substring(1);


  125. Node resultNode = this.findKeyinChildren(root, first);

  126. if (resultNode == null)

  127. {

  128. return null;

  129. }

  130. else

  131. {

  132. if (tail == null)

  133. return resultNode;

  134. else

  135. resultNode = findinTrie(tail,resultNode );

  136. }


  137. return resultNode;

  138. }


  139. public static void main(String[] args)

  140. {

  141. if (args.length <= 0)

  142. {

  143. System.out.println("Usage : Trie ");

  144. System.exit(1);

  145. }

  146. Trie trie = new Trie("C:\\test\\dictionary");

  147. trie.buildTrie();

  148. System.out.println("Going to look for " + args[0]);

  149. List vals = trie.findKey(args[0]);

  150. for (int i=0; i<vals.size(); i++)

  151. {

  152. System.out.println("possible value = " + vals.get(i));

  153. }


  154. }


  155. }