Translate

Tuesday, November 20, 2012

JUnit Rules

Source: http://www.codeaffine.com/2012/09/24/junit-rules/


JUnit Rules


The first time I stumbled over a JUnit @Rule annotation I was a bit irritated of the concept. Having a public field in a test case seemed somewhat odd and so I was reluctant to use it regularly. But after a while I got used to that and it turned out that rules can ease writing tests in many ways. This post gives a quick introduction of the concept and some short examples of what rules are good for.

What are JUnit Rules?
Let’s start with a look at a JUnit out-of-the-box rule. The TemporaryFolder is a test helper that can be used to create files and folders located under the file system directory for temporary content1. The interesting thing with the TemporaryFolder is that it guarantees to delete its files and folders when the test method finishes2. To work as expected the temporary folder instance must be assigned to an @Ruleannotated field that must be public, not static, and a subtype of TestRule:
01public class MyTest {
02     
03  @Rule
04  public TemporaryFolder temporaryFolder = new TemporaryFolder();
05
06  @Test
07  public void testRun() throws IOException {
08    assertTrue( temporaryFolder.newFolder().exists() );
09  }
10}
How does it work?
Rules provide a possibility to intercept test method calls similar as an AOP framework would do. Comparable to an around advice in AspectJ you can do useful things before and/or after the actual test execution3. Although this sounds complicated it is quite easy to achieve.
The API part of a rule definition has to implement TestRule. The only method of this interface called apply returns a Statement. Statements represent – simply spoken – your tests within the JUnit runtime and Statement#evaluate() executes them. Now the basic idea is to provide wrapper extensions of Statement that can do the actual contributions by overriding Statement#evaluate():
01public class MyRule implements TestRule {
02
03  @Override
04  public Statement apply( Statement base, Description description ) {
05    return new MyStatement( base );
06  }
07}
08
09public class MyStatement extends Statement {
10
11  private final Statement base;
12
13  public MyStatement( Statement base ) {
14    this.base = base;
15  }
16
17  @Override
18  public void evaluate() throws Throwable {
19    System.out.println( "before" );
20    try {
21      base.evaluate();
22    } finally {
23      System.out.println( "after" );
24    }
25  }
26}
MyStatement is implemented as wrapper that is used inMyRule#apply(Statement,Destination) to wrap the original statement given as argument. It is easy to see that the wrapper overrides Statement#evaluate() to do something before and after the actual evaluation of the test4.
The next snippet shows how MyRule can be used exactly the same way as theTemporaryFolder above:
01public class MyTest {
02
03  @Rule
04  public MyRule myRule = new MyRule();
05     
06  @Test
07  public void testRun() {
08    System.out.println( "during" );
09  }
10}
Launching the test case leads to the following console output which proves that our example rule works as expected. The test execution gets intercepted and modified by our rule to print ‘before’ and ‘after’ around the ‘during’ of the test:
before
during
after
Now that the basics are understood let’s have a look at slightly more useful things you could do with rules.
Test Fixtures
Quoted from the according wikipedia section a test fixture ‘is all the things that must be in place in order to run a test and expect a particular outcome. Frequently fixtures are created by handling setUp() and tearDown() events of the unit testing framework’.
With JUnit this often looks somewhat like this:
01public class MyTest {
02
03  private MyFixture myFixture;
04
05  @Test
06  public void testRun1() {
07    myFixture.configure1();
08    // do some testing here
09  }
10     
11  @Test
12  public void testRun2() {
13    myFixture.configure2();
14    // do some testing here
15  }
16     
17  @Before
18  public void setUp() {
19    myFixture = new MyFixture();
20  }
21
22  @After
23  public void tearDown() {
24    myFixture.dispose();
25  }
26}
Consider you use a particular fixture the way shown above in many of your tests. In that case it could be nice to get rid of the setUp() and tearDown() methods. Given the sections above we now know that this can be done by changing MyFixture to implement TestRule. An appropriate Statement implementation would have to ensure that it calls MyFixture#dispose() and could look like this:
01public class MyFixtureStatement extends Statement {
02
03  private final Statement base;
04  private final MyFixture fixture;
05
06  public MyFixtureStatement( Statement base, MyFixture fixture ) {
07    this.base = base;
08    this.fixture = fixture;
09  }
10
11  @Override
12  public void evaluate() throws Throwable {
13    try {
14      base.evaluate();
15    } finally {
16      fixture.dispose();
17    }
18  }
19}
With this in place the test above can be rewritten as:
01public class MyTest {
02
03  @Rule
04  public MyFixture myFixture = new MyFixture();
05
06  @Test
07  public void testRun1() {
08    myFixture.configure1();
09    // do some testing here
10  }
11     
12  @Test
13  public void testRun2() {
14    myFixture.configure2();
15    // do some testing here
16  }
17}
I come to appreciate the more compact form of writing tests using rules in a lot of cases, but surely this is also a question of taste and what you consider better to read5.
Fixture Configuration with Method Annotations
So far I have silently ignored the Description argument ofTestRule#apply(Statement,Description). In general a Description describes a test which is about to run or has been run. But it also allows access to some reflective information about the underlying java method. Among others it is possible to read the annotations attached to such a method. This enables us to combine rules with method annotations for convenience configuration of a TestRule.
Consider this annotation type:
1@Retention(RetentionPolicy.RUNTIME)
2@Target({ElementType.METHOD})
3public @interface Configuration {
4  String value();
5}
Combined with the following snippet inside MyFixture#apply(Statement,Destination)that reads the configuration value annotated to a certain test method…
1Configuration annotation
2  = description.getAnnotation( Configuration.class );
3String value = annotation.value();
4// do something useful with value
… the test case above that demonstrates the usage of the MyFixture rule can be rewritten to:
01public class MyTest {
02
03  @Rule
04  public MyFixture myFixture = new MyFixture();
05
06  @Test
07  @Configuration( value = "configuration1" )
08  public void testRun1() {
09    // do some testing here
10  }
11     
12  @Test
13  @Configuration( value = "configuration2" )
14  public void testRun2() {
15    // do some testing here
16  }
17}
Of course there are limitations to the latter approach due to the fact that annotations only allow Enums, Classes or String literals as parameters. But there are use cases where this is completely sufficient. A nice example using rules combined with method annotations is provided by the restfuse library. If you are interested in a real world example you should have a look at the library’s implementation of the Destinationrule6.
Comming to the end the only thing left to say is that I would love to hear from you about other useful examples of JUnit rules you might use to ease your daily testing work

  1. The directory which is in general returned by System.getProperty( "java.io.tmpdir" ); ↩
  2. Looking at the implementation of TemporaryFolder I must note that it does not check if the deletion of a file is successful. This might be a weak point in case of open file handles ↩
  3. And for what it’s worth you even could replace the complete test method by something else ↩
  4. The delegation to the wrapped statement is put into a try...finally block to ensure that the functionality after the test gets executed, even if the test would fail. In that case an AssertionError would be thrown and all statements that are not in the finally block would be skipped ↩
  5. You probably noted that the TemporaryFolder example at the beginning is also nothing else but a fixture use case ↩
  6. Note that restfuse’s Destination class implements MethodRule instead of TestRule. This post is based on the latest JUnit version where MethodRule has been marked as@Deprecated. TestRule is the replacement for MethodRule. But given the knowledge of this post it should be nevertheless easily possible to understand the implementation

Monday, September 17, 2012

JAX-WS Hello World Example – RPC Style


JAX-WS Hello World Example – RPC Style

By - November 16, 2010
Source: http://www.mkyong.com/webservices/jax-ws/jax-ws-hello-world-example/
JAX-WS is bundled with JDK 1.6, which makes Java web service development easier to develop. This tutorial shows you how to do the following tasks:
  1. Create a SOAP-based RPC style web service endpoint by using JAX-WS.
  2. Create a Java web service client manually.
  3. Create a Java web service client via wsimport tool.
  4. Create a Ruby web service client.
You will be surprise of how simple it is to develop a RPC style web service in JAX-WS.
Note
In general words, “web service endpoint” is a service which published outside for user to access; where “web service client” is the party who access the published service.

JAX-WS Web Service End Point

The following steps showing how to use JAX-WS to create a RPC style web service endpoint.

1. Create a Web Service Endpoint Interface

File : HelloWorld.java
package com.mkyong.ws;
 
import javax.jws.WebMethod;
import javax.jws.WebService;
import javax.jws.soap.SOAPBinding;
import javax.jws.soap.SOAPBinding.Style;
 
//Service Endpoint Interface
@WebService
@SOAPBinding(style = Style.RPC)
public interface HelloWorld{
 
 @WebMethod String getHelloWorldAsString(String name);
 
}

2. Create a Web Service Endpoint Implementation

File : HelloWorldImpl.java
package com.mkyong.ws;
 
import javax.jws.WebService;
 
//Service Implementation
@WebService(endpointInterface = "com.mkyong.ws.HelloWorld")
public class HelloWorldImpl implements HelloWorld{
 
 @Override
 public String getHelloWorldAsString(String name) {
  return "Hello World JAX-WS " + name;
 }
 
}

3. Create a Endpoint Publisher

File : HelloWorldPublisher.java
package com.mkyong.endpoint;
 
import javax.xml.ws.Endpoint;
import com.mkyong.ws.HelloWorldImpl;
 
//Endpoint publisher
public class HelloWorldPublisher{
 
 public static void main(String[] args) {
    Endpoint.publish("http://localhost:9999/ws/hello", new HelloWorldImpl());
    }
 
}
Run the endpoint publisher, and your “hello world web service” is deployed in URL “http://localhost:9999/ws/hello“.

4. Test It

You can test the deployed web service by accessing the generated WSDL (Web Service Definition Language) document via this URL “http://localhost:9999/ws/hello?wsdl” .

Web Service Clients

Ok, web service is deployed properly, now let’s see how to create web service client to access to the published service.

1. Java Web Service Client

Without tool, you can create a Java web service client like this :
package com.mkyong.client;
 
import java.net.URL;
import javax.xml.namespace.QName;
import javax.xml.ws.Service;
import com.mkyong.ws.HelloWorld;
 
public class HelloWorldClient{
 
 public static void main(String[] args) throws Exception {
 
 URL url = new URL("http://localhost:9999/ws/hello?wsdl");
 
        //1st argument service URI, refer to wsdl document above
 //2nd argument is service name, refer to wsdl document above
        QName qname = new QName("http://ws.mkyong.com/", "HelloWorldImplService");
 
        Service service = Service.create(url, qname);
 
        HelloWorld hello = service.getPort(HelloWorld.class);
 
        System.out.println(hello.getHelloWorldAsString("mkyong"));
 
    }
 
}
Output
Hello World JAX-WS mkyong

2. Java Web Service Client via wsimport tool

Alternative, you can use “wsimport” tool to parse the published wsdl file, and generate necessary client files (stub) to access the published web service.
Where is wsimport?
This wsimport tool is bundle with the JDK, you can find it at “JDK_PATH/bin” folder.
Issue “wsimport” command.
wsimport -keep http://localhost:9999/ws/hello?wsdl
It will generate necessary client files, which is depends on the provided wsdl file. In this case, it will generate one interface and one service implementation file.
File : HelloWorld.java
package com.mkyong.ws;
 
import javax.jws.WebMethod;
import javax.jws.WebParam;
import javax.jws.WebResult;
import javax.jws.WebService;
import javax.jws.soap.SOAPBinding;
 
/**
 * This class was generated by the JAX-WS RI.
 * JAX-WS RI 2.1.1 in JDK 6
 * Generated source version: 2.1
 * 
 */
@WebService(name = "HelloWorld", targetNamespace = "http://ws.mkyong.com/")
@SOAPBinding(style = SOAPBinding.Style.RPC)
public interface HelloWorld {
 
    /**
     * 
     * @param arg0
     * @return
     *     returns java.lang.String
     */
    @WebMethod
    @WebResult(partName = "return")
    public String getHelloWorldAsString(
        @WebParam(name = "arg0", partName = "arg0")
        String arg0);
 
}
File : HelloWorldImplService.java
package com.mkyong.ws;
 
import java.net.MalformedURLException;
import java.net.URL;
import javax.xml.namespace.QName;
import javax.xml.ws.Service;
import javax.xml.ws.WebEndpoint;
import javax.xml.ws.WebServiceClient;
import javax.xml.ws.WebServiceFeature;
 
/**
 * This class was generated by the JAX-WS RI.
 * JAX-WS RI 2.1.1 in JDK 6
 * Generated source version: 2.1
 * 
 */
@WebServiceClient(name = "HelloWorldImplService", 
 targetNamespace = "http://ws.mkyong.com/", 
 wsdlLocation = "http://localhost:9999/ws/hello?wsdl")
public class HelloWorldImplService
    extends Service
{
 
    private final static URL HELLOWORLDIMPLSERVICE_WSDL_LOCATION;
 
    static {
        URL url = null;
        try {
            url = new URL("http://localhost:9999/ws/hello?wsdl");
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
        HELLOWORLDIMPLSERVICE_WSDL_LOCATION = url;
    }
 
    public HelloWorldImplService(URL wsdlLocation, QName serviceName) {
        super(wsdlLocation, serviceName);
    }
 
    public HelloWorldImplService() {
        super(HELLOWORLDIMPLSERVICE_WSDL_LOCATION, 
   new QName("http://ws.mkyong.com/", "HelloWorldImplService"));
    }
 
    /**
     * 
     * @return
     *     returns HelloWorld
     */
    @WebEndpoint(name = "HelloWorldImplPort")
    public HelloWorld getHelloWorldImplPort() {
        return (HelloWorld)super.getPort(
   new QName("http://ws.mkyong.com/", "HelloWorldImplPort"), 
   HelloWorld.class);
    }
 
    /**
     * 
     * @param features
     *  A list of {@link javax.xml.ws.WebServiceFeature} to configure on the proxy.  
     *  Supported features not in the <code>features</code> parameter will have their default values.
     * @return
     *  returns HelloWorld
     */
    @WebEndpoint(name = "HelloWorldImplPort")
    public HelloWorld getHelloWorldImplPort(WebServiceFeature... features) {
        return (HelloWorld)super.getPort(
   new QName("http://ws.mkyong.com/", "HelloWorldImplPort"), 
   HelloWorld.class, 
   features);
    }
 
}
Now, create a Java web service client which depends on the above generated files.
package com.mkyong.client;
 
import com.mkyong.ws.HelloWorld;
import com.mkyong.ws.HelloWorldImplService;
 
public class HelloWorldClient{
 
 public static void main(String[] args) {
 
  HelloWorldImplService helloService = new HelloWorldImplService();
  HelloWorld hello = helloService.getHelloWorldImplPort();
 
  System.out.println(hello.getHelloWorldAsString("mkyong"));
 
    }
 
}
Here’s the output
Hello World JAX-WS mkyong

3. Ruby Web Service Client

Often time, web service development is mixed use with other programming language. So, here’s a Ruby web service client example, which is used to access the published JAX-WS service.
# package for SOAP-based services
require 'soap/wsdlDriver'
 
wsdl_url = 'http://localhost:9999/ws/hello?wsdl'
 
service = SOAP::WSDLDriverFactory.new(wsdl_url).create_rpc_driver
 
# Invoke service operations.
data1 = service.getHelloWorldAsString('mkyong')
 
# Output results.
puts "getHelloWorldAsString : #{data1}"
Output
getHelloWorldAsString : Hello World JAX-WS mkyong

Tracing SOAP Traffic

From top to bottom, showing how SOAP envelope flows between client and server. See #1 web service client again :
    URL url = new URL("http://localhost:9999/ws/hello?wsdl");
    QName qname = new QName("http://ws.mkyong.com/", "HelloWorldImplService");
    Service service = Service.create(url, qname);
 
    HelloWorld hello = service.getPort(HelloWorld.class);
 
    System.out.println(hello.getHelloWorldAsString("mkyong"));
Note
To monitor SOAP traffic is very easy, see this guide – “How to trace SOAP message in Eclipse IDE“.

1. Request a WSDL file

First, client send a wsdl request to service endpoint, see HTTP traffic below :
Client send request :
GET /ws/hello?wsdl HTTP/1.1
User-Agent: Java/1.6.0_13
Host: localhost:9999
Accept: text/html, image/gif, image/jpeg, *; q=.2, */*; q=.2
Connection: keep-alive
Server send response :
HTTP/1.1 200 OK
Transfer-encoding: chunked
Content-type: text/xml;charset=utf-8
 
<?xml version="1.0" encoding="UTF-8"?>
 
<definitions 
 xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/" 
 xmlns:tns="http://ws.mkyong.com/" 
 xmlns:xsd="http://www.w3.org/2001/XMLSchema" 
 xmlns="http://schemas.xmlsoap.org/wsdl/" 
 targetNamespace="http://ws.mkyong.com/" 
 name="HelloWorldImplService">
 
 <types></types>
 
<message name="getHelloWorldAsString">
 <part name="arg0" type="xsd:string"></part>
</message>
<message name="getHelloWorldAsStringResponse">
 <part name="return" type="xsd:string"></part>
</message>
 
<portType name="HelloWorld">
 <operation name="getHelloWorldAsString" parameterOrder="arg0">
  <input message="tns:getHelloWorldAsString"></input>
  <output message="tns:getHelloWorldAsStringResponse"></output>
 </operation>
</portType>
 
<binding name="HelloWorldImplPortBinding" type="tns:HelloWorld">
 
 <soap:binding transport="http://schemas.xmlsoap.org/soap/http" style="rpc"></soap:binding>
 <operation name="getHelloWorldAsString">
  <soap:operation soapAction=""></soap:operation>
  <input>
   <soap:body use="literal" namespace="http://ws.mkyong.com/"></soap:body>
  </input>
  <output>
   <soap:body use="literal" namespace="http://ws.mkyong.com/"></soap:body>
  </output>
 </operation>
 
</binding>
 
<service name="HelloWorldImplService">
<port name="HelloWorldImplPort" binding="tns:HelloWorldImplPortBinding">
<soap:address location="http://localhost:9999/ws/hello"></soap:address>
</port>
</service>
</definitions>

2. hello.getHelloWorldAsString()

A second call, client put method invoke request in SOAP envelope and send it to service endpoint. At the service endpoint, call the requested method and put the result in a SOAP envelope and send it back to client.
Client send request :
POST /ws/hello HTTP/1.1
SOAPAction: ""
Accept: text/xml, multipart/related, text/html, image/gif, image/jpeg, *; q=.2, */*; q=.2
Content-Type: text/xml; charset=utf-8
User-Agent: Java/1.6.0_13
Host: localhost:9999
Connection: keep-alive
Content-Length: 224
 
<?xml version="1.0" ?>
 <S:Envelope xmlns:S="http://schemas.xmlsoap.org/soap/envelope/">
  <S:Body>
   <ns2:getHelloWorldAsString xmlns:ns2="http://ws.mkyong.com/">
    <arg0>mkyong</arg0>
   </ns2:getHelloWorldAsString>
  </S:Body>
 </S:Envelope>
Server send response :
HTTP/1.1 200 OK
Transfer-encoding: chunked
Content-type: text/xml; charset=utf-8
 
<?xml version="1.0" ?>
 <S:Envelope xmlns:S="http://schemas.xmlsoap.org/soap/envelope/">
  <S:Body>
   <ns2:getHelloWorldAsStringResponse xmlns:ns2="http://ws.mkyong.com/">
    <return>Hello World JAX-WS mkyong</return>
   </ns2:getHelloWorldAsStringResponse>
  </S:Body>
 </S:Envelope>

Download Source Code

Download It – JAX-WS-HelloWorld-RPC-Example.zip (14KB)

Top 8 Java People You Should Know

Source: http://www.mkyong.com/featured/top-8-java-people-you-should-know/

Here are the top 8 Java people, they’re created frameworks, products, tools or books that contributed to the Java community, and changed the way of coding Java.
P.S The order is based on my personal priority.

8. Tomcat & Ant Founder

James-Duncan-Davidson
James Duncan Davidson, while he was software engineer at Sun Microsystems (1997–2001), created Tomcat Java-based web server, still widely use in most of the Java web projects, and also Ant build tool, which uses XML to describe the build process and its dependencies, which is still the de facto standard for building Java-based Web applications.

7. Test Driven Development & JUnit Founder

Kent-Beck
Kent Beck, creator of the Extreme Programming and Test Driven Development software development methodologies. Furthermore, he and Erich Gamma created JUnit, a simple testing framework, which turn into the de facto standard for testing Java-based Web applications. The combine of JUnit and Test Driven Development makes a big changed on the way of coding Java, which causes many Java developers are not willing to follow it.

6. Java Collections Framework

Joshua-Bloch
Joshua Bloch, led the design and implementation of numerous Java platform features, including JDK 5.0 language enhancements and the award-winning Java Collections Framework. In June 2004 he left Sun and became Chief Java Architect at Google. Furthermore, he won the prestigious Jolt Award from Software Development Magazine for his book, “Effective Java”, which is arguably a must read Java’s book.

5. JBoss Founder

Marc-Fleury
Marc Fleury, who founded JBoss in 2001, an open-source Java application server, arguably the de facto standard for deploying Java-based Web applications. Later he sold the JBoss to RedHat, and joined RedHat to continue support on the JBoss development. On 9 February 2007, he decided to leave Red Hat to pursue other personal interests, such as teaching, research in biology, music and his family.

4. Struts Founder

Craig-McClanahan
Craig Mcclanahan, creator of Struts, a popular open source MVC framework for building Java-based web applications, which is arguably that every Java developer know how to code Struts. With the huge success of Struts in early day, it’s widely implemented in every single of the old Java web application project.

3. Spring Founder

Rod-Johnson
Rod Johnson, is the founder of the Spring Framework, an open source application framework for Java, Creator of Spring, CEO at SpringSource. Furthermore, Rod’s best-selling Expert One-on-One J2EE Design and Development (2002) was one of the most influential books ever published on J2EE.

2. Hibernate Founder

gravin-king
Gavin King, is the founder of the Hibernate project, a popular object/relational persistence solution for Java, and the creator of Seam, an application framework for Java EE 5. Furthermore, he contributed heavily to the design of EJB 3.0 and JPA.

1. Father of the Java programming language

James-Gosling
James Gosling, generally credited as the inventor of the Java programming language in 1994. He created the original design of Java and implemented its original compiler and virtual machine. For this achievement he was elected to the United States National Academy of Engineering. On April 2, 2010, he left Sun Microsystems which had recently been acquired by the Oracle Corporation. Regarding why he left, Gosling wrote on his blog that “Just about anything I could say that would be accurate and honest would do more harm than good.”






Sunday, September 16, 2012

Web Container / Web Server / HTTP Server


Web Container : 
  • In J2EE Architecture, a web container(also known as servlet container or servlet engine), is used to manage the components like servlets, JSP.
  • It provides a runtime environment to the components of J2EE.
  • When ever web server receive a request it forward it to web container which deals with it by instantiating,initializing and invoking Servlets and JSP pages. So,basically it controls the whole life cycle of servlet and JSP. 
  • It is a part of the web server.
  • Example: Apache Tomcat.

Web Server / HTTP Server :
  • It is a server which is capable of handling HTTP request send by a client and respond back with a HTTP respond.
  • Example: Apache Web Server.

Application Server / App Server :
  • It can handle all application operations between users and an organization's back end business applications or databases.
  • It's for complex transaction-based application.
  • It is frequently viewed as part of a three-tier application, where top-most tier is Presentation tier(GUI layer), then the Logic tier(an Application Server) and Data tier(consist of database server).
  • Example: IBM - WebSphere Application Server.