Sunday, December 25, 2011

Restful Web Services using JBoss RestEasy

Restful web service is built on top of HTTP protocol. We can say Restful web service is a type of Servlet. I am saying Restful web service is built on top of HTTP protocol because it support all HTTP operations. Initially this was porposed by Roy Fielding who was the main driver of HTTP.

The supported operations of a Restful web service are descrive below:
  • GET
  • POST
  • DELETE
  • PUT
Like JAX-WS, SUN Microsystem introduced JAX-RS for Restful web service. One more important feature of this is totally based on Java Annotation. You can make/published any POGO as a Restful web service, just need to annotate the

You can find number of implementations of JAX-RS. One most popular implementation is RestEasy.This is developed by JBoss community. The RestEasy is comes in two flaver, If you are using JBoss AS 7 then there is no need to add any distribution file for RestEasy. If you are using older version of JBoss, then you have to confugure the RestEasy.

For older version of JBoss, developer have to download a jar file named "resteasy-jaxrs-2.3.0.GA". You can foud this in <>.

Configuration:
  1. After download extract the file and copy all jar files from lib directory to your application.
  2. Modify our Web configuration file(web.xml) file. Add the following lines:
  3. Annotate your POGO for Restful web service.
  4. Deploy the application in JBoss AS.
Resteasy Web Service Annotations: 

@Path - Identifies the URI path that a resource class or class method will serve requests for. Paths are relative. For an annotated class the base URI is the application path, see ApplicationPath. For an annotated method the base URI is the effective URI of the containing class. For the purposes of absolutizing a path against the base URI , a leading '/' in a path is ignored and base URIs are treated as if they ended in '/'

@GET - Indicates that the annotated method responds to HTTP GET requests.

@POST - Indicates that the annotated method responds to HTTP POST requests.

@DELETE - Indicates that the annotated method responds to HTTP DELETE requests

@PUT - Indicates that the annotated method responds to HTTP PUT requests

@Form - This can be used as a value object for incoming/outgoing request/responses. You can re-use @*Param annotations on fields/methods of the parameter to unmarshall from the request or marshall to the response depending if you're using server-side JAX-RS or the Resteasy client framework
When using this on the server side, you must put your @*Param annotations on either fields or setter methods.
When using this with the Resteasy client framework, you must put your @*Param annotations on either fields or getter methods.


@FormParam - Binds the value(s) of a form parameter contained within a request entity body to a resource method parameter. Values are URL decoded unless this is disabled using the Encoded annotation. A default value can be specified using the DefaultValue annotation. If the request entity body is absent or is an unsupported media type, the default value is used.
The type T of the annotated parameter must either:
  1. Be a primitive type
  2. Have a constructor that accepts a single String argument
  3. Have a static method named valueOf or fromString that accepts a single String argument (see, for example, Integer.valueOf(String))
  4. Be List, Set or SortedSet, where T satisfies 2 or 3 above. The resulting collection is read-only.

If the type is not one of those listed in 4 above then the first value (lexically) of the parameter is used.

Note that, whilst the annotation target permits use on fields and methods, this annotation is only required to be supported on resource method parameters.

Sunday, September 11, 2011

Use Null Object instead of Null literals

Use Null Object instead of Null literals that reduce the extra overhead of checking whether the Object is created or not. Whenever you you want to access the object or access the properties of that object, you must have to check the object against the Null literals.

Sometime we heard that set some default value instead of null. There is no hard and fast rule for declaring all Objects with a default value.If we don't do then we have to take responsibility for exception NullPointerException.

So, I sugges to do Something for Nothing. This is not a new. If you go through the design patterns, you found that there is a Null Object Pattern. 

If a client calls a method on a field or variable that is null, an exception may be
raised, a system may crash, or similar problems may occur. To protect our systems from such unwanted behavior, we write checks to prevent null fields or
variables from being called and, if necessary, specify alternative behavior to
execute when nulls are encountered:

if (someObject != null)
  someObject.doSomething();
else
  performAlternativeBehavior();


Repeating such null logic in one or two places in a system isn’t a problem,
but repeating it in multiple places bloats a system with unnecessary code. Compared with code that is free of null logic, code that is full of it generally takes
longer to comprehend and requires more thinking about how to extend. Null
logic also fails to provide null protection for new code. So if new code is written
and programmers forget to include null logic for it, null errors can begin to
occur.


The Null Object pattern provides a solution to such problems. It removes
the need to check whether a field or variable is null by making it possible to
always call the field or variable safely. The trick is to assign the field or variable
to the right object at the right time. When a field or variable can be null, you
can make it refer to an instance of a Null Object, which provides do-nothing,
default, or harmless behavior. Later, the field or variable can be assigned to
something other than a Null Object. Until that happens, all invocations safely
route through the Null Object.



Kent Beck - father of eXtream Programming and JUnit and also contributor of Eclipse.suggested use of Null Object instead of Null literals.
Benefits and Liabilities
+ Prevents null errors without duplicating null logic.
+ Simplifies code by minimizing null tests.
– Complicates a design when a system needs few null tests.
– Can yield redundant null tests if programmers are unaware of a Null
Object implementation.
– Complicates maintenance. Null Objects that have a superclass must
override all newly inherited public methods.

Java Database Connectivity Key points

1. Use Type two driver for two tiered applications to communicate from java client to database that gives better performance than Type1 driver.
2. Use Type four driver for applet to database communication that is two tiered applications and three tiered applications when compared to other drivers.
3. Use Type one driver if you don't have a driver for your database. This is a rare situation because all major databases support drivers or you will get a driver from third party vendors.
4. Use Type three driver to communicate between client and proxy server ( weblogic, websphere etc) for three tiered applications that gives better performance when compared to Type 1 &2 drivers.
5. ass database specific properties like defaultPrefetch if your database supports any of them.
6. Get database connection from connection pool rather than getting it directly
7. Use batch transactions.
8. Choose right isolation level as per your requirement. TRANSACTION_READ_UNCOMMITED gives best performance for concurrent transaction based applications. TRANSACTION_NONE gives best performance for non-concurrent transaction based applications.
9. Your database server may not support all isolation levels, be aware of your database server features.
10. Use PreparedStatement when you execute the same statement more than once.
11. Use CallableStatement when you want result from multiple and complex statements for a single request.
12. Use batch update facility available in Statements.
13. Use batch retrieval facility available in Statements or ResultSet.
14. Set up proper direction for processing rows.
15. Use proper getXXX() methods.
16. Close ResultSet, Statement and Connection whenever you finish your work with them.
17. Write precise SQL queries.
18. Cache read-only and read-mostly tables data.
19. Fetch small amount of data iteratively rather than whole data at once when retrieving large amount of data like searching database etc.

Saturday, September 10, 2011

Important guidlines for Java Programming

1. Never directly modify code generated by JAXB.
2. Generate JAXB into separate packages-don't commingle
3. Don't use generated JAXB classes as value objects in applications.
4. Do not close connection objects or issue commits, rollbacks, or savepoints within a DAO.
5. Database objects created within a method should be closed within the same method.
6. Always pass the database connection from the business logic layer.
7. Always specify a column list with an insert statement.
8. Always speicfy a column list with a select statement.
9. Use host variables in SQL statemnets instead of hard-coding literals in SQL strings.
10. code test cases for all DAO methods and put them in the test suite.
11. Any method that creates a database connection should close it in a finally block.
12. All exceptions thrown should implement.
13. Using stateless session beans improve performance.
14. Stateless session beans should avoid instance-level variables.
15. MDB's should not throw exceptions.
16. Acknowledge message receipt in a finally block.
17. Using native JDK exceptions before creating your own.
18. Exploit Java's unchecked exception capability.
19. Use native JDK exceptions before creating your own.
20. Limit the nesting depth of a try/catch block to two.
21. Don't catch exceptions and do nothing with them.
22. Never put a return statement in a finally block.
23. Avoid explicitly setting thread priority.
24. Explicitly name all created threads.
25. Identify all threads as daemon threads.
26. Log enough information on error so that you can reproduce an error sutuation in a single-threaded test case.
27. Explicitly name all created threads.

Wednesday, July 20, 2011

Register dynamic Web Service Client Handler


package javawiki.webservice.consumer;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import javawiki.webservice.common.LogHandler;
import javawiki.webservice.provider.GetBookDetails;
import javawiki.webservice.provider.LibraryService;
import javax.xml.namespace.QName;
import javax.xml.ws.BindingProvider;
import javax.xml.ws.Service;
import javax.xml.ws.handler.Handler;
public class ConsumeLibraryService {
 public static void main(String arg[])
 {
  try
  {
   URL url = new URL("http://localhost:8080/libraryservice/LibraryService");
   QName qName = new QName("http://javawikiforbeginners.blogspot.com/JavaLibraryService/","JavaLibraryService");
   Service service = Service.create(url, qName);
   LibraryService libraryService = service.getPort(LibraryService.class);
   BindingProvider bindingProvider = (BindingProvider) libraryService;
   
   List<Handler> handlerChain = new ArrayList<Handler>();
   
   handlerChain.add(new LogHandler());
   
   bindingProvider.getBinding().setHandlerChain(handlerChain);
   
   GetBookDetails aBookDtls = libraryService.getBook("123456");
   System.out.println(aBookDtls.getBook());
  }
  catch(Exception ex)
  {
   ex.printStackTrace();
  }
 }
}



package javawiki.webservice.common;
import java.util.Set;
import javax.xml.namespace.QName;
import javax.xml.ws.handler.MessageContext;
import javax.xml.ws.handler.soap.SOAPHandler;
import javax.xml.ws.handler.soap.SOAPMessageContext;
public class LogHandler implements SOAPHandler<SOAPMessageContext>{
 @Override
 public Set<QName> getHeaders() {
  // TODO Auto-generated method stub
  return null;
 }
 @Override
 public void close(MessageContext context) {
  System.out.println("Closing message");
 }
 @Override
 public boolean handleFault(SOAPMessageContext context) {
  // TODO Auto-generated method stub
  return false;
 }
 @Override
 public boolean handleMessage(SOAPMessageContext context) {
  Boolean outbound = (Boolean) context
  .get(SOAPMessageContext.MESSAGE_OUTBOUND_PROPERTY);
  
  System.out.println(context.keySet());
  
  if(outbound)
  {
   System.out.println("=====================this is outbound log handler===============");
   return true;
  }
  else
  {
   System.out.println("=====================this is inbound log handler===============");
   return false;
  }
 }
}

Tuesday, July 5, 2011

Validate JAXB Object with XML Schema

We can validate JAXB Object with XML Schema(XSD). JAXB provide a class named Validator to validate against a schema. This class is available since Java 1.5


package javawiki.jaxb.validation;

import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;

@XmlRootElement
@XmlType(name = "Customer", propOrder = {
"name",
"phoneNumber",
})
public class Customer {

private String name;
private List phoneNumber;

public Customer() {
phoneNumber = new ArrayList();
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public List getPhoneNumber() {
return phoneNumber;
}

public void setPhoneNumber(List phoneNumber) {
this.phoneNumber = phoneNumber;
}
}

package javawiki.jaxb.validation;

public class PhoneNumber {

}


<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
 <xs:element name="customer">
  <xs:complexType>
   <xs:sequence>
    <xs:element name="name" type="stringMaxSize5" />
    <xs:element ref="phoneNumber" maxOccurs="3" />
   </xs:sequence>
  </xs:complexType>
 </xs:element>

 <xs:element name="phoneNumber">
  <xs:complexType />
 </xs:element>

 <xs:simpleType name="stringMaxSize5">
  <xs:restriction base="xs:string">
   <xs:maxLength value="5" />
  </xs:restriction>
 </xs:simpleType>

</xs:schema>


package javawiki.jaxb.validation;

import org.xml.sax.ErrorHandler;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;

public class MyErrorHandler implements ErrorHandler {

 @Override
 public void error(SAXParseException exception) throws SAXException {
  System.out.println(exception.getLocalizedMessage());
 }

 @Override
 public void fatalError(SAXParseException exception) throws SAXException {
  System.out.println(exception.getLocalizedMessage());
 }

 @Override
 public void warning(SAXParseException exception) throws SAXException {
  System.out.println(exception.getLocalizedMessage());
 }

}


package javawiki.jaxb.validation;

import java.io.File;

import javax.xml.XMLConstants;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.util.JAXBSource;
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;
import javax.xml.validation.Validator;

public class DemoSchemaValidation {

 public static void main(String[] args) {
  Customer customer = new Customer();
        customer.setName("Jane ");
        customer.getPhoneNumber().add(new PhoneNumber());
        customer.getPhoneNumber().add(new PhoneNumber());
        customer.getPhoneNumber().add(new PhoneNumber());
        
        try
        {
         JAXBContext jc = JAXBContext.newInstance(Customer.class);
         JAXBSource source = new JAXBSource(jc, customer);
 
         SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); 
         Schema schema = sf.newSchema(new File("src/javawiki/jaxb/validation/customer.xsd")); 
 
         Validator validator = schema.newValidator();
         validator.setErrorHandler(new MyErrorHandler());
         validator.validate(source);
        }catch(Exception ex)
        {
         ex.printStackTrace();
        }
 }

}

Output:
cvc-maxLength-valid: Value 'Jane Doe' with length = '8' is not facet-valid with respect to maxLength '5' for type 'stringMaxSize5'.
cvc-type.3.1.3: The value 'Jane Doe' of element 'name' is not valid.
cvc-complex-type.2.4.d: Invalid content was found starting with element 'phoneNumber'. No child element is expected at this point.

Sunday, June 19, 2011

Web Service Stack

Whenever we talking about Web Service, we heard "Web Service Stack". What does it mean. Its an internal architecture/implementation of Web Services. This implementation is Comprises of protocols.Those protocols are stack over each other. Yes, but maintain a sequence. This protocol stack is used to define, locate, implement, and make Web services interact with each other.
There are four Web Service protocols:


1. Transport Protocol/Transport Layer : The Transport layer is the first component in the stack and is responsible for moving XML messages between applications. The Transport protocol most commonly used is the standard HTTP protocol. Other commonly used Web protocols are SMTP and FTP.

2. Messaging Protocol/XML Messaging : The messaging layer in the protocol stack is based on an XML model. XML is widely used in Web Services applications and is the foundation for all web services. XML is just one of the standards enabling web services to map between technology domains. You will find many resources on the Web that describe XML messaging. For more information, refer to the World Wide Web Consortium (W3C) site on Messaging listed in the link list below.

The XML Messaging specification is a broadly-defined umbrella under which a number of more specific protocols are defined. SOAP is one of the more popular standards, and is one of the most significant standards in communicating web services over the network. XML provides a means for communicating over the Web using an XML document that both requests and responds to information between two disparate systems. SOAP allows the sender and the receiver of XML documents to support a common data transfer protocol for effective networked communication.

3. Description Protocol/WSDL Layer : This layer represents a way of specifying a public interface for a web service. It contains information on available functions, on data types for XML messaging, binding information about the transport protocol, and the location of the specific web service.

Any client application that wants to know about a service, what data it expects to receive, whether or not it delivers any results, and the supported transport, uses WSDL to find that information. When you create a Web Service, it must be described and advertised to its potential customers before it can be used. WSDL provides a common format for describing and publishing that web service information. Typically, WSDL is used with SOAP, and the WSDL specification includes a SOAP binding.

4. Discovery Protocol/UDDI Layer : This layer represents a way to publish and find web services over the Web. You can think of this layer as the White and Yellow Pages of your phonebook. The White pages of web services provides general information about a specific company, for instance, their business name, description, and address. The Yellow Pages includes the classification of data for the services offered, for instance, industry type and products.

The protocol you use to publish your web services is known as UDDI. The UDDI Business Registry allows anyone to search existing UDDI data and enables you to register your company and its services. With RAD Studio, your data automatically gets published to the registry, or a distributed directory for business and web services.

Sunday, June 12, 2011

SOA and Web Service

SOA and Web Service are two different things. SOA stands for "Service Oriented Architecture". SOA is an software architecture. SOA is used to create a distributed system. SOA can be used to enable Software as a Service(SAAS). SOA uses the find-bind-execute paradigm. In this paradigm, service providers register their service in a public registry. This registry is used by consumers to find services that match certain criteria. If the registry has such a service, it provides the consumer with a contract and an endpoint address for that service. One thing is that, Services are the building blocks of SOA.

Web Services are the preferred standard-based way to realize SOA architecture. Web services are software systems designed to support interoperable machine-to-machine interaction over a network. This interoperability is gained through a set of XML-based open standards, such as WSDL, SOAP, and UDDI. These standards provide a common approach for defining, publishing, and using web services.

Java API for XML(JAX):
1. Java API for XML Processing(JAXP) 1.2 - This API lets you process XML documents by invoking a SAX or DOM parser in your application. JAXP 1.2 supports W3C XML Schema.

2.Java API for XML-based RPC (JAX-RPC) 1.1 - This is an API for building and deploying SOAP+WSDL web services clients and endpoints.

3.Java APIs for XML Registries (JAXR) 1.0.4 - This is a Java API for accessing different kinds of XML registries. It provides you with a single set of APIs to access a variety of XML registries, including UDDI and the ebXML Registry. You don't need to worry about the nitty-gritty details of each registry's information model.

4.SOAP with Attachments API for Java (SAAJ) 1.2 - This API lets you produce and consume messages conforming to the SOAP 1.1 specification and SOAP with Attachments note.

5.JSR 109: Web services for J2EE 1.0 - JSR 109 defines deployment requirements for web services clients and endpoints by leveraging the JAX-RPC programming model. In addition, it defines standard deployment descriptors using the XML Schema, thereby providing a uniform method of deploying web services onto application servers through a wide range of tools.

6.JAX-WS 2.0 (JSR 224) -

7.JAXB - the Java Architecture for XML Binding.

8.StAX - the Streaming API for XML.

Sun's new version of web service stack is JAX-WS.

The difference between JAX-RPC and JAX-WS web service stack.

Thursday, May 26, 2011

Web Service Properties

1) self-contained - no additional software is required for WS:
   a) client-side: a programming language with XML/HTML client support
   b) server-side: a web server and a SOAP server are needed
2) loosely coupled - client and server only knows about messages - a
   simple coordination level that allows for more flexible re-configuration
3) web-enabled – WS are published, located and invoked across the web,
   using established lightweight Internet standards
4) language-independent and interoperable - client and server may be
   implemented in different environments and different languages
   composable - WS can be aggregated using workflow techniques to
   perform higher-level business functions
6) dynamically bound - with UDDI and WSDL, the discovery and binding of
   web services can be automated
7) programmatic access - the web services approach does not provide a
   graphical user interface but operates at the command level
8) wrap existing applications - stand-alone applications can easily be
   integrated by implementing a web service as an interface

Friday, March 11, 2011

Externalize complex types for Web Service

It is a good programming practise to externalize re-usable complex types or elements in a separate XSD. This can be achived by using standard XML features.

XML provides a way to import any XSD in another XSD file. Now you can use those complex types or elements from imported XSD, but one thing is that you have to specify imported xsd file in a separated namespace and use the namespace prefix to use the complex type or element.

Suppose i have a XSD file, named base.xsd. In which i have a complex type:


Another xsd file in which AddressBn complex type will be used:


Steps:
1. specify namespace for the imported xsd as shown in the first highlighted text.

2. import the xsd file, with target namespace and schema location attribute as shown in the second highlighted text.

3. use the complex type or element prefix with namespace as shown in the third highlighted text.

Sunday, February 13, 2011

Required Annotations for Web Service - Java

Java6 provides some annotations for creating Webservice, when the strategy is bottom-up. Here I describe some required annotations for that.

1. @WebService - This annotation is used to identified the WebService name in the SEI.
2. @WebMethod - This annotation is used to identified the WebService Operation in SEI.
3. @WebParam - This annotation is used to identified the WebService Operation's parameter name in SEI.
4. @WebResult - Customizes the mapping of the return value to a WSDL part and XML element

Thursday, February 10, 2011

Writing Web Services using Bottom-Up approch

In this approch, you have to do the following steps:

1. Create SEI (Service Endpoint Interface) and its implementation class. The SEI defines the methods that are available for service consumer. Those methods are called Operations - There are two basic patterns for creating an SEI:
   • Green field development
   You are developing a new service from the ground up. When starting fresh, it is best to start by creating the SEI first. You can then distribute the SEI to any developers that are responsible for implementing the services and consumers that use the SEI.

   • Service enablement
   In this pattern, you typically have an existing set of functionality that is implemented as a Java class and you want to service enable it. This means that you will need to do two things:
      a.Create an SEI that contains only the operations that are going to be exposed as part of the service.
      b.Modify the existing Java class so that it implements the SEI.

2. Add the required annotations -

3. Generate WSDL for contract of the service. This step is optional, if you treat SEI as a contract for your service then no need to create WSDL.

4. Publish the web service - You can use any web container to publish the service. The process is the same as adding servlet for web application.


Example:

Create POJOs for the Service:






Create SEI:


Create SIB:


Publish the service:


Create Service Consumer:


Result:


Download the complete example

Sunday, January 9, 2011

Web Service Development Strategies

When developing a Web Service Endpoint (the server-side) you have the option of starting from Java (bottom-up development), or from the abstact contract (WSDL) that defines your service (top-down development). If this is a new service (no existing contract), the bottom-up approach is the fastest route; you only need to add a few annotations to your classes to get a service up and running. However, if you are developing a service with an already defined contract, it is far simpler to use the top-down approach.

Bottom-up use cases:
• Providing a new service, and you want the contract to be generated for you.


Top-down use cases:
• Replacing the implementation of an existing Web Service, and you can't break compatibility with older clients.
• Exposing a service that conforms to a contract specified by a third party (e.g. a vender that calls you back using an already defined protocol).
• Creating a service that adheres to the XML Schema and WSDL you developed by hand up front.

There are no of tools for working with Top-down and Bottom-up Web Service Development.

1. JBossWS is one of the implementation of JAX-WS, provided by JBoss.
Bottom-up
• JBossWS - wsprovide :- Generates JAX-WS portable artifacts, and provides the abstract contract. Used for bottom-up development(Java).

Top-down
• JBossWS - wsconsume :- Consumes the abstract contract (WSDL and Schema files), and produces artifacts for both a server and client. Used for top-down and client development.

2. Sun's implementation of JAX-WS, available with JDK6 distribution.
Bottom-up
• wsgen :- Generates JAX-WS portable artifacts, and provides the abstract contract. Used for bottom-up development(Java).

Top-down
• wsimport :- Consumes the abstract contract (WSDL and Schema files), and produces artifacts for both a server and client. Used for top-down and client development.

Method Overloading in WSDL

There is no direct way to overload java method in WSDL, WSDL does not support Overloading mechanism, but you can achive this through other ways. This will be done through RequestWrapper and ResponseWrapper Annotation. Those Annotations are need to be included in Service Implementation Bean(SIB). There is no harm if you add those in Service Implementation(SI). But SIB is mandatory.

@RequestWrapper - have localName, targetNamespace and class. For method overloading you have to specify class name field.

@ResponseWrapper - have same fileds as RequestWrapper, here also you have to specify class name field.

Code Snippet for Service Implementation:


Code Snippet for Service Implementation Bean:


Use this commeand to generate server side artifact and WSDL:
I am using JAX-WS with Jdk6.

prabir$> wsgen -keep -wsdl -cp bin HelloServer -d client

Here HelloServer is the Service endpoint implementation class also known as Service Implementation Bean.