Thursday, October 27, 2011

Java - Simple Iterator

Iterator itr = list.iterator();
        while(itr.hasNext()) {

            Object element = itr.next();
            System.out.print(element + " ");

        }

Java - Traversing a map

System.out.println(lineSeparator + "Using traditional Iterator and key set");
for(Iterator it = data.keySet().iterator(); it.hasNext();) {
    Object key = it.next();
    Object value = data.get(key);
    System.out.println(key + " = " + value);
}

Monday, October 24, 2011

Creating SOAP Message Handlers in 3 Simple Steps - Part 1

This tutorial takes a look at SOAP Message handlers and how easy it is to write handlers using JAX-WS 2.0. JAX-WS 2.0 allows both regular Java classes and stateless EJBs(Session beans) to be exposed as web services. The JAX-WS 2.0 is the core specification that defines the web services standard for Java EE 5 specification. JAX-WS 2.0 is an extension of the Java API for XML-RPC (JAX-RPC) 1.0.
SOAP message handlers are used to intercept the SOAP message as they make their way from the client to the end-point service and vice-versa. These handlers intercept the SOAP message for both the request and response of the Web Service. If you are familiar with EJB interceptors, handlers are similar to EJB interceptors and are defined in an XML file.
A few typical scenarios where you would be using SOAP Message handlers are: to encrypt and decrypt messages, to support logging, caching and in some cases auditing, and in rare cases to provide transaction management as well.
So much for the theory. Lets see the three basic steps to use a simple log handler to intercept and print our SOAP messages (request and response).
In this tutorial, we are going to expose an EJB 3 stateless session bean as a web service which is simple and can be done by adding the @WebService annotation. So, here comes the source code for the interface as well as the implementation class which is self explanatory:
Listing 1: Remote Interface
01.package com.ws;
02. 
03.import javax.ejb.Remote;
04. 
05./**
06.*
07.* @author meerasubbarao
08.*/
09.@Remote
10.public interface HelloWebServiceRemote {
11. 
12.String sayHello(String name);
13. 
14.}
Listing 2: Bean Implementation
01.package com.ws;
02. 
03.import javax.ejb.Stateless;
04.import javax.jws.WebMethod;
05.import javax.jws.WebParam;
06.import javax.jws.WebService;
07. 
08./**
09.*
10.* @author meerasubbarao
11.*/
12.@WebService
13.@Stateless
14.public class HelloWebServiceBean implements HelloWebServiceRemote {
15. 
16.@WebMethod(operationName = "sayHello")
17.public String sayHello(@WebParam(name = "name") String name) {
18.return "Hello " + name;
19.}
20. 
21. 
22.}
You can package the two source files in a jar, deploy to your application server, and test it. Quite simple, right? For this tutorial, I am using GlassFish V2 application server and SoapUI to test my web services. Shown below are the request and response from SoapUI:


Now that we know our web services work, lets start writing the message handler, which as I said earlier is just 3 steps. So, what are these SOAP message handlers? They are simple Java classes that can used to modify SOAP messages; both request as well as response. These handlers have access to both the SOAP header as well as the body of the message.
Lets move on to create SOAP message handlers:
Step 1. Implement the SOAPHandler interface.
01.package com.ws;
02. 
03.import java.io.IOException;
04.import java.util.Collections;
05.import java.util.Set;
06.import java.util.logging.Level;
07.import java.util.logging.Logger;
08.import javax.xml.namespace.QName;
09.import javax.xml.soap.SOAPException;
10.import javax.xml.soap.SOAPMessage;
11.import javax.xml.ws.handler.MessageContext;
12.import javax.xml.ws.handler.soap.SOAPHandler;
13.import javax.xml.ws.handler.soap.SOAPMessageContext;
14. 
15./**
16.*
17.* @author meerasubbarao
18.*/
19.public class LogMessageHandler implements SOAPHandler<SOAPMessageContext> {
20. 
21.public boolean handleMessage(SOAPMessageContext messageContext) {
22.return true;
23.}
24. 
25.public Set<QName> getHeaders() {
26.return Collections.EMPTY_SET;
27.}
28. 
29.public boolean handleFault(SOAPMessageContext messageContext) {
30.return true;
31.}
32. 
33.public void close(MessageContext context) {
34.}
35. 
36.}
The handleMessage() method is invoked for both incoming as well as outgoing messages. Lets add a new method called log() and invoke this method from the handleMessage method. Shown below are both the methods:
01.private void log(SOAPMessageContext messageContext) {
02.SOAPMessage msg = messageContext.getMessage(); //Line 1
03.try {
04.msg.writeTo(System.out);  //Line 3
05.} catch (SOAPException ex) {
06.Logger.getLogger(LogMessageHandler.class.getName()).log(Level.SEVERE, null, ex);
07.} catch (IOException ex) {
08.Logger.getLogger(LogMessageHandler.class.getName()).log(Level.SEVERE, null, ex);
09.}
10.}
In line 1, we are retrieving the SOAPMessage from the message context. Line 3 will print the incoming and outgoing messages in our GlassFish console.
Invoke this method from within the handleMessage() as shown:
1.public boolean handleMessage(SOAPMessageContext messageContext) {
2.log(messageContext);
3.return true;
4.}
Step 2: Create the XML file for the Handler Chain.
Create this XML file in the same package as the web service with the name LogMessage_handler.xml.
01.<?xml version="1.0" encoding="UTF-8"?>
02.<handler-chains xmlns="http://java.sun.com/xml/ns/javaee">
03.<handler-chain>
04.<handler>
05.<handler-name>com.ws.LogMessageHandler</handler-name>
06.<handler-class>com.ws.LogMessageHandler</handler-class>
07.</handler>
08.</handler-chain>
09.</handler-chains>
Lets take a close look at the various elements used above:

1. <handler-chains> is the root element that will contain a list of all handler chains that are defined for the Web Service.
2. The <handler-chain> child element of the <handler-chains> element lists all the handlers in the handler chain.
3. Within the <handler-chain> element is defined the <handler>, each handler element must in turn specify the name and also the fully qualified name of the Java class that implements the handler. If you have more than one handler, specify each one of them within the handler-chain element.

Step 3: Invoking the Handler
The @HandlerChain annotation is used to define a set of handlers that are invoked in response to a SOAP message. So, within our HelloWebServiceBean implementaion, you need to make a simple change to invoke the Log Handler as shown below in Line 1:
01.package com.ws;
02. 
03.import javax.ejb.Stateless;
04.import javax.jws.HandlerChain;
05.import javax.jws.WebMethod;
06.import javax.jws.WebParam;
07.import javax.jws.WebService;
08. 
09./**
10.*
11.* @author meerasubbarao
12.*/
13.@WebService
14.@Stateless
15.@HandlerChain(file = "LogMessage_handler.xml") // Line 1
16.public class HelloWebServiceBean implements HelloWebServiceRemote {
17. 
18.@WebMethod(operationName = "sayHello")
19.public String sayHello(@WebParam(name = "name") String name) {
20.return "Hello " + name;
21.}
22.}
We added the annotation for the handlers; lets recompile, repackage and redeploy the application.

Now invoke the web service from SoapUI and see if it works. If it does, we should be able to see the request and response logged in our GlassFish console window.
Here is the final output:
**RemoteBusinessJndiName: com.ws.CustomerManagerRemote; remoteBusIntf: com.ws.CustomerManagerRemote
LDR5010: All ejb(s) of [EJBWebServices] loaded successfully!
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ws="http://ws.com/"><soapenv:Header/><soapenv:Body><ws:sayHello>

<name>Javalobby</name>
</ws:sayHello></soapenv:Body></soapenv:Envelope>
<S:Envelope xmlns:S="http://schemas.xmlsoap.org/soap/envelope/"><S:Body><ns2:sayHelloResponse xmlns:ns2="http://ws.com/"><return>Hello Javalobby</return></ns2:sayHelloResponse></S:Body></S:Envelope>
In this article, we saw how simple and easy it was to create and use SOAP Handlers to intercept request and response of SOAP messages. We implemented the SOAPHandler interface, wrote minimal XML to define the handler chain, and finally added one simple annotation to the web service implementation class. We were also able to test these web service using SoapUI.

Ref: http://java.dzone.com/articles/creating-soap-message-handlers

Thursday, October 20, 2011

Adding a new library to NetBeans

Most libraries come as part of the platform you’re using, which is specified in the Java Platform Manager. Additional libraries can be added through the Library Manager which you find on the Tools menu. This makes it easier to use libraries because the NetBeans IDE will use this information to provide you documentation support (JavaDoc), to see the source code, etc. In addition NetBeans will ensure that the library is available on the classpath when executing the application.
To add a new library click the New Library... button. Give a name to the library and click the OK button. T he library should appear in the library tree at the left hand side of the Library Manager dialog box.

NetBeans librarymanager.PNG

Tuesday, October 18, 2011

JQuery

Useful links

http://docs.jquery.com/UI/Slider
http://jqueryui.com/themeroller/

Planning to Build vs. Building the Plan

Dwight D. Eisenhower once said "In preparing for battle, I have always found that plans are useless, but planning is indispensable."

Project Management Training Sessions

I ran a couple of sessions with the same material, for the same organization, but with different groups. We ran simulations where the students were tasked with physically building a small but complex device.

Initially they try to build with virtually no planning, then they get another crack at it with this experience behind them, and finally they create a project schedule aimed at making the building process as efficient as possible.

Process


With the first group, this network planning session was extremely chaotic. It was difficult to discern any progress with the team. Several people voiced some frustration during the exercise, and indeed, nobody in the group managed to put together a complete network. Nobody could express which tasks were on the critical path, and nobody had a defendable expectation of how long the overall project would take.

For the second group, there was far more visible organization. The teams disseminated and shared their knowledge very effectively. At the end of the planning session, each of the four component teams produced schedules that looked very similar, with critical paths and durations that all came in within 20% of each other. Every one was a credible plan of attack for building the device.

Both groups managed to identify all of the same optimizations to bring the overall project duration down, and had good ideas of how to resource the project effectively.

Results


When they were unleashed to build the device one last time the first team, that had been so chaotic in the planning stages, ran like a fine tuned engine and completed the project in record time. The second group, despite building a credible schedule, ran out of time and was not able to finish.

The real kicker here is that the group that finished in record time, did so in a time that was within 10% of what was expected from the other group's schedules! It appears that while one group did a great job of building a schedule, the other group did a great job of planning how to build the device.

Conclusion


In the real world, clients couldn't care less how pretty the schedule is if you never manage to deliver the product. That chaos during the planning activity was the necessary walking through of how the successful group would coordinate to get the job done.

It really isn't the plan that is important, but the activity of planning. The discussions and debate, sometimes heated arguments, can go a long way towards helping the team arrive at a common understanding of what needs to be done.

Apparently, Eisenhower also once said "What counts is not necessarily the size of the dog in the fight, but the size of the fight in the dog."

Project Workplan

After the Project Definition has been prepared, the workplan can be created. The workplan provides the step-by-step instructions for constructing project deliverables and managing the project. You should use a prior workplan from a similar project as a model, if one exists. If not, build one the old-fashioned way by utilizing a work-breakdownstructure and network diagram.


Best Practice – The Planning Horizon

Create a detailed workplan, including assigning resources and estimating the work as far out as you feel comfortable. This is your planning horizon. Past the planning horizon, lay out the project at a higher level, reflecting the increased level of uncertainty. The planning horizon will move forward as the project progresses. High-level activities that were initially vague need to be defined in more detail as their timeframe gets closer.