WSDL Basics


What and Why WSDL

WSDL is a descriptor for Web Service that is XML formatted. Like any J2EE descriptors, it basically describes the Web Service. Web Service is described as a set of endpoints (ports) which would have 2 parts – Abstract definition and Concrete binding (Will dive onto that later).

whatiswsdl

The WSDL is basically the contract between the client and implementation. Everything that are defined and exposed has a definition inside the WSDL file.

Why WSDL? – Enables automation of communication details between communicating partners. Machines can read XML/WSDL documents and able to invoke the defined service in WSDL. 3rd part can also verify if the communication conforms to WSDL standards.

WSDL Document Structure

 

<wsdl:definitions xmlns:wsdl="http://schemas.xmlsoap.org/wsdl"                   targetNamespace="your name space here"                   xmlns:tns="your name space here"                   xmlns:soapbind="http://schemas.xmlsoap.org/wsdl/soap">

    <wsdl:types>
        <xs:schema targetNamespace="your namespace here" xmlns:xsd="http://www.w3.org/2001/XMLSchema">

        </xs:schema>
    </wsdl:types>
    <wsdl:message name="some operation input">
           <!--Parts here-->
    </wsdl:message>

    <wsdl:message name ="some operation output">
        <!--Parts here-->
    </wsdl:message>

    <wsdl:portType name="your type name">
        <!-- Define operations here-->
    </wsdl:portType>

    <wsdl:binding name="your binding name" type="tns:port type name above">
        <!-- define style of transport here-->
    </wsdl:binding>

    <wsdl:service>
    </wsdl:service>

</wsdl:definitions>

On the sample above, the XML file uses the wsdl namespace as highlighted.

Example of WSDL document

The WSDL service above has a simple service generating strings and returning them. It will have a single operation called getSystemMessageAndReturn. It will be deployed using SOAP 1.1 over HTTP. The service takes a “string” message and responds with a message that has the “string” in it.

Nothing is much more simpler than that.

7 Elements of WSDL:

  • Types – data type definition and used to describe exchanged messages.
  • Message – abstract, typed definitions of data being exchanged
  • Operation – abstract description of an action. Refers to an input and/or output messages.
  • Port Type – Collection of operations
  • Binding – Concrete protocol and data format (encoding) for a particular Port type.
  • Port  – Defines a single communication endpoint. Endpoint address for binding. URL for HTTP, email address for SMTP.
  • Service -Aggregate set of related ports.

WSDL View of a Web Service

wsdl_doc.jpg

Web Service Invocation

wsdl_invoc

Message Element

A message element can consist of one or more logical parts. It is basically the data unit of an WSDL definition.

<definitions ....>
   <message name="nmtoken">
      <part name="nmtoken" element="qname"? type="qname" ?/>
   </message>
</definitions>

Types of Operations

There are 2 types of operations that we can define on our WSDL. One way or Two way.

One-way

The endpoint receives a message only.

<operation name="submitPurchase">
   <input message="purchase"/>
</operation>

Request/Response

The endpoint receives a message and sends a correlated message.

<operation name="submitPurchase">
   <input message="purchase"/>
   <output message="confirmation"/>
</operation>
<operation name="submitPurchase">
   <input message="purchase"/>
   <output message="confirmation"/>
   <fault message="faultMessage"/>
</operation>

Importing and Authoring Style

  • When a developer creates a web service, it is important to consider reusability and maintainability.
  • It is important also to maintain a WSDL document in 3 separate parts.
    • Data Type definitions
    • Abstract definitions
    • Specific Service Bindings
  • Use import element to import necessary part of WSDL document. This makes the parts more isolated and thus, maintainable.=

Examples

You can download some WSDL examples here.

On the next blog post, we’ll be creating a Web Service from scratch and apply all what we learned from here. See you!

SOAP Web Services


What is SOAP according to W3C Definition

“SOAP is a lightweight protocol intended for exchanging structured information in a decentralised, distributed environment. It uses XML technologies to define and extensible messaging framework providing a message construct that can be exchanged over a variety of underlying protocols. The framework has been design to be independent of any particular programming model and other implementation specific semantics.”

Simple Object Access Protocol

  • Wire protocol similar to IIOP for CORBA and JRMP for RMI
  • XML is used for data encoding – text and binary based protocol
  • Supports XML-based RPC (Remote Procedure Call) to ease the migration of existing RPC distribution schemes to SOAP based system (note that this approach is not being used anymore because of the introduction of RMI.

It is extremely important that any Java/J2EE developers understand the concept of how SOAP works as this will allow them to build better application that communicates and integrates with other systems. Like any other fundamentals, it is better to understand the underlying concepts.

Most of the time though, developers will be using a high-level API (JAX-WS) implementations to build these services thus the actual mechanism of SOAP is hidden.

Characteristic of SOAP

  • By default, SOAP is stateless but ultimately can be used to do stateful transactions (pass the state data to the object).
  • One way message exchange paradigm: Applications can create more complex interaction patterns by combining such one way exchange with features provided by underlying protocol (http), application specific information and higher level standard (such as “WS-Addressing”).
  • SOAP is silent on the semantics of any application-specific data it conveys. It doesn’t really care what kind of data (XML is only a recommendation as it’s a universal format – meaning any platform understands and can parse this kind of structure).

Design Goals of SOAP

  • Simplicity
  • Extensibility
  • Although it does offer the above, it doesn’t support advance support distributing features such as distributed GC, object by reference, activation and message batching.

SOAP Message Structure

soapmessagestructure

SOAP Message Envelope

  • Embedded information includes the namespace and encoding information
  • Header (Optional)
  • Body (Mandatory) – handled by the receiver

SOAP Header (<env:header>)

  • Used for extension (context, authentication, transaction, management)
  • Made of header blocks (composition of header blocks)
  • Most Web Service standard activities are basically defining standard header entries for a particular domain.

SOAP Header Blocks (Entries)

  • Child Elements of SOAP Header
  • Designed in anticpation of arious uses for SOAP
  • Inspected, inserted, deleted or forwarded by SOAP nodes encountered on the SOAP Message Path.

SOAP Body (<env:Body>)

  • Composition of body blocks
  • consumed by SOAP receiver
  • Carry end to end information (XML, RPC Methods and Parameters, SOAP Fault – exceptions)
  • SOAP Fault Messages

Fault Messages

If there are any errors encountered during the communication or any exceptions, a fault message will be thrown back to the client to allow it to handle the issue gracefully. There are pre-defined SOAP fault code values.

  • VersionMisMatch (invalid namespace in SOAP envelope of version mismatch)
  • MustUnderstand (Receiver does not understand and therefore cannot handle the mustUnderstand SOAP header block)
  • Client (client side communication error)
  • Server (server side communication error)

This can be used to return any readable exceptions to the client. This is extremely useful and a must do for anyone who creates web services.

Code Example

Concepts aside, let’s deep dive on the code example. I used NetBeans to create the example.

Tech Stack: NetBeans IDE with Java/Java EE, Glassfish Application Server
These are all bundled with NetBeans IDE if you download it from their site.
Project: Download it here.

The Web Service

Create a new Web Application Project.
samplewebservice_project

Create a simple Java Class and #Annotate

@WebService
public class SampleWebService {
    
    /**
     * Show Message
     * @param message
     * @return 
     */
    @WebMethod
    public String showMessage(String message){
        return message;
    }
}

Deploy the Web Service Application to Glassfish
deploywebservice

Test the Web Service using the “Test Web Service” option

After clicking the test below, a web page will be launched that will allow you to test the actual WebService method.
webservice_test
You can test the actual service by passing a value and clicking on the “showMessage” button.
webservice_test_actual
You can also access the WSDL file from the link provided. You can see the SOAP definitions, namespaces and entries.
webservice_wsdl

The Client

Not that hard to expose a service but what will it be without any clients using it? Let’s build a client that will actually call the Web Service. Once again, NetBeans provides us with a facility to create stubs and objects given a WSDL URL. Allowing use to focus on consuming the service.

Create a new Java Project

webservice_client_pro

Create a new Web Service Client within the Java Project

NetBeans IDE has a great feature to create Web Service Client. Beautifully and Gracefully creates the necessary objects given your WSDL.

webservice_client

Provide the WSDL URL and your set.

webservice_cl_provide_wsdl_url

Generated Source Code that your client can use

webservice_cl_gen_code

 

Call Web Service from the Client

After the stubs are generated, you can now call it from your project

/**
 *
 * @author alvinreyes
 */
public class SampleWebServiceClient {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        System.out.println(showMessage("Hello"));
    }

    private static String showMessage(java.lang.String arg0) {
        com.areyes.soap.sample.SampleWebServiceService service = new com.areyes.soap.sample.SampleWebServiceService();
        com.areyes.soap.sample.SampleWebService port = service.getSampleWebServicePort();
        return port.showMessage(arg0);
    }
    
}

Build your project before running the client. This will allow your project to recognize the new Java classes and packages.
webservice_cl_new_run

wsimport-client-SampleWebServiceService:
files are up to date
wsimport-client-generate:
Compiling 1 source file to /Users/alvinreyes/NetBeansProjects/SampleWebServiceClient/build/classes
compile-single:
run-single:
Hello
BUILD SUCCESSFUL (total time: 3 seconds)

You can download the actual project here

Web Services Overview


Introduction

Hello All! From this point forward, I’ll be doing series of posts related to Web Services. This is part of my on going certification study for the Web Services Expert exam. I’ll go from the fundamental questions of what Web Services are up to the deeper depths of it’s anatomy.

I don’t expect any of this to be published anywhere, but feel free to use my content for the right intentions and purposes.

For this post, I’ll be answering these few questions.

  • What is a Web Service
  • Why do we need Web Services
  • Where are & where are Web Services going?
  • Types of Web Services
  • Web Services on Java Platform

What are Web Services

Web services by definition are client and server applications that communicate over the WWW HTTP. It provides a standardisation of exposing services to multiple platforms, creating cross platform interoperability and extensibility. In a nutshell, it’s just a service exposed via the web which means accessible by HTTP/HTTPS.

Why do we need Web Services

There is always a growing demand for integrating systems that were built differently. The WEB has put a standard for all these systems to communicate with each other via it’s protocols. All platforms understand http and is able to parse XML format.

Where are & where are Web Services going?

It’s going bananas actually. Within the next couple of years, I can see that Web Services will be the main defacto approach in integrating many different applications and platforms. Tools will be available so that developers will easily integrate and create Web Services almost instantly and most of the what can be virtualize, will be soon be available as a service (and accessible via Web Service).

Types of Web Services

Big Web Services

Big Web Services uses XML as payloads and use the Simple Object Access Protocol to send and receive messages. We use JAX-WS and JAXB/JAXP implementation to read/write XML format file (structure data) and process them to our applications. Big Web Services are normally for large data that are mission critical to it’s purpose.

SOAP Web Services are also used to create stateful/session based service. This means that it can retain a specific client (thread) session and store its state on it’s entire lifespan.

REST Web Services

REST Web Services are much simpler mechanism. By default, stateless in nature, this is a type of Web Services we want to developer if we just want to expose a specific data structure. It’s simplicity has been the core point of it’s attractiveness to the developers and it’s lightweight approach makes it the primary choice for creating/integrating web services on micro / mobile devices.

It is important to understand the basic fundamentals/concepts of these 2 types as it will help you understand on how to effectively and efficiently design bullet proof Web Services for your customers.

On the next set of POST. I’ll be going on a deep dive adventure on creating our first BIG and REST Web Services.

Apache CXF – JAX-WS – Tutorial


A lot of Java Developers out there sees task with Web Service implementation daunting – well, nobody can blame them really, especially that it brings a lot of  complexity in development and design over the years of enterprise application development. For some though, learning it is somehow the next step in building a full blown enterprise application – Web Services – is one of the key schemes for implementing service oriented design – almost every platform available has support to the scheme, and that of course includes Java/J2EE.

In this tutorial, I will show how you will using Apache CXF to create  Web Servies using JAX-WS and the Apache CXF API to call specific service from a remote application.

  1. Building the Web Service Application : Server Side  – We need to build the application as well as the Web Services implementation code. This will be a generic WAR (Web Archive) that will house the actual implementation
  2. Building the Web Service Application: Client Side – Of course, we need to provide external clients a way for them to access the services – we will create a stub and give them out to clients for them to use the services.

FYI: I’m using Maven to simplify library definitions.

1st we create the Stub

this houses the interface and entities (Pojos) used to access the service. When you design your service – you usually create the class interfaces (reference) first and put it on another JAR file for re-distribution.

stub_1

2nd lets build the service.

We will be hosting the service from a Web Archive deployed to an application server.

POM. xml – We will be using Spring CDI and CXF – Might as well load up all the libraries needed.

server_1

We include the stub on the server as this will act as the reference of our implementation:

server_2

We now create the Service Implementation:

server_3

cxf-servlet (or beans.xml) – this is where we will call the factory that will publish the WSDL upon loading the context.

server_4

web.xml – we need to make sure that web service request will go thru CXF – since we are using its framework. Good thing about CXF is it does all the necessary binding, marshalling, unmarshalling as well as injecting the in / out interceptors.

server_5

Build and Deploy the WAR! – After deploying the war, view the context page. You should be seeing something like this:

server_6

If you manage to view the above URL – then you have successfully expose your service and can now be called by external clients

3rd we create the client app.

Now we create a standalone Java app to call the service – we will be using Spring again to context load client beans and we need include the stub so that we can have reference to the implementation.

beans.xml – create the xml and call the proxy factory bean to create the instance on runtime

client_1

Create the Client – We will now call the bean and use the reference to call the method.

client_2

4th Test! – Test your service!

You should now be able call the Service implementation!

client_3

Download the example here

With this simple example, its really a conclusive proof that creating Web Service now is just a breeze – We took advantage of Apache CXF as a service framework to simplify the development and Springs powerful CDI that almost took care the rest.