Apache CXF Web Service Development - Balani Naveen - E-Book

Apache CXF Web Service Development E-Book

Balani Naveen

0,0
23,50 €

-100%
Sammeln Sie Punkte in unserem Gutscheinprogramm und kaufen Sie E-Books und Hörbücher mit bis zu 100% Rabatt.

Mehr erfahren.
Beschreibung

In Detail

Apache CXF framework helps you to develop a standards-based programming model and also provides a flexible deployment model for deploying web services. Developing SOAP and RESTful applications can be made easy by using Apache CXF framework. However, getting started with developing web services using the Apache CXF framework is not easy.

This is the first book that gives details on how to use the Apache CXF framework for developing SOAP and REST web services. It is a hands-on practical guide that simplifies working with CXF framework as it covers all major aspects with real-world examples. The chapters cover the various CXF features in detail and each has systematic steps with practical, simple examples to implement these features on your web services.

The book introduces the Apache CXF framework and its features such as Frontend API, Data Bindings, Transports, Spring-based configuration, and CXF tools. It also has chapters on SOAP and RESTful services. It will help you create RESTful services that support XML as well as the widely accepted Java Script Object Notation (JSON) format. It explains the components of CXF architecture that help developers customize the Apache CXF framework to suit the target application. The book covers both code-first and contract-first approaches for service deployment. You will see how to develop services in a flexible deployment model offered by CXF, unit test them in a stand-alone environment, and finally promote them in an application server environment.

The instructions in this book will help developers to build their application according their requirements by using any of the frontends supported by Apache CXF framework. The various CXF frontend APIs covered in this book provide a wide variety of options in developing and deploying your application.

The book introduces some advanced concepts such as Interceptors and features that will add extra capability to your service component. It will help you take advantage of different transport features offered by the CXF runtime such as HTTP, HTTP(S), and JMS protocols.
Finally, the book mentions various tools that help developers creating web services as well as creating Java and JavaScript-based web services clients which invoke a real-world .NET web service. These tools are standard batch files that can be easily executed from the Windows command shell by following the instructions in the book.

A practical hands-on guide to show you how to develop and deploy SOAP and RESTful services using Apache CXF framework

Approach

This book provides a quick start in developing web services using the open source Apache CXF framework. Each chapter uses illustrations from an Order Processing Application and all the code examples are built using the ANT tool. These practical, simple, and easy-to-work-with illustrations are accompanied by step-by-step instructions.

As a developer you can take advantage of these practical scenarios to understand the CXF framework and also make use of them in real-life applications. After reading this book, you will be able to develop and deploy services using the CXF framework.

Who this book is for

This book is for developers who want to design and develop SOAP and RESTful services using Apache CXF framework and leverage various CXF features for service development. It is ideal for developers who have some experience in Java application development as well as some basic knowledge of web services, but it covers some of the basic fundamentals of web services and REST to get you acquainted with these technologies before using these concepts to develop services using the CXF framework.

Sie lesen das E-Book in den Legimi-Apps auf:

Android
iOS
von Legimi
zertifizierten E-Readern

Seitenzahl: 357

Veröffentlichungsjahr: 2009

Bewertungen
0,0
0
0
0
0
0
Mehr Informationen
Mehr Informationen
Legimi prüft nicht, ob Rezensionen von Nutzern stammen, die den betreffenden Titel tatsächlich gekauft oder gelesen/gehört haben. Wir entfernen aber gefälschte Rezensionen.



Table of Contents

Apache CXF Web Service Development
Credits
About the Authors
About the Reviewer
Preface
What this book covers
What you need for this book
Who this book is for
Conventions
Reader feedback
Customer support
Errata
Piracy
Questions
1. Getting Familiar with CXF
Web service technology standards
XML
SOAP (Simple Object Access Protocol)
WSDL (Web Services Description language)
REST (Representational State Transfer)
Service Registry
Introducing web services
Approaches for web service development
Web service SOAP communication styles
Apache CXF
History of CXF
Why CXF?
Support for web service standards
Support for POJO (Plain Old Java Object)
Frontend programming APIs
Tools support
Support for RESTful services
Support for different transports and bindings
Support for non-XML binding
Ease of use
Flexible deployment
Setting up the environment
For ANT users
For Maven users
Summary
2. Developing a Web Service with CXF
The Order Processing Application
Developing a service
Creating a Service Endpoint Interface (SEI)
Developing a service implementation class
Spring-based server bean
Developing a client
Developing a Spring-based client bean
Developing web service client code
Running the program
Building the code
Deploying the code
Executing the code
CXF architecture
Bus
Frontend
JAX-WS
Simple frontend
Messaging and Interceptors
Service model
Data binding
Protocol binding
Transports
Summary
3. Working with CXF Frontends
JAX-WS frontend
Code-first development
Creating Service Endpoint Interface (SEI)
Adding Java annotations
javax.jws.WebService
javax.jws.soap.SOAPBinding
RPC versus Document style
javax.jws.WebMethod
Publishing the service
Developing a consumer
Running the Code-first example
Contract-first development
Generating service components
JAXB input and output message classes
Service Interface
Service implementation class
Standalone server class
Build file
Implementing the service method
Publishing the web service
Invoking the web service
Using dynamic client
Creating a simple dynamic client
Running the dynamic client
Using the CXF service model for building dynamic client
Running the dynamic client which uses Service Model API
Provider and Dispatch services
Understanding messaging modes
Message mode
Payload mode
Understanding types of message objects
javax.xml.transform.Source
DOMSource
SAXSource
StreamSource
javax.xml.soap.SOAPMessage
javax.activation.DataSource
Implementing Provider service
Publishing the Provider service
Implementing the Dispatch service
Running the provider dispatch example
Web service context
Implementing Context in service
Running the web service context example
Simple frontend
Developing a simple frontend
Creating service implementation class and interface
Creating server implementation
Creating client
Running the simple frontend example
Summary
4. Learning about Service Transports
Transport protocols in CXF
HTTP transport
SOAP over HTTP
SOAP 1.1 over HTTP
SOAP 1.2 over HTTP
HTTP only
HTTP conduit
HTTP destination
HTTPs transport
Developing the service and implementation class
Generating crypto key
Creating client and server bean configuration
Configuring the server to support SSL
Developing the client component
Building and deploying
Configuring SSL for Jetty runtime
JMS transport
Developing the service and implementation class
Developing an embedded broker
Creating a server and client bean configuration
Developing a client component
Performing build and deployment
Local transport
Developing SEI and an implementation class
Developing a server
Creating client bean configuration
Developing a Client
Building and executing
Summary
5. Implementing Advanced Features
Understanding CXF interceptors
Understanding interceptor phase and chain
Overview of the interceptor API
Interceptor interface
The PhaseInterceptor interface
The AbstractPhaseInterceptor class
Developing the custom interceptor
Developing the server side interceptor
Adding a server side interceptor to the Order Process service
Developing the client side interceptor
Adding a client side interceptor to the client code
Developing the standalone server for publishing the Order Process web service
Building and running the Order Process web service and interceptor
Building the code
Deploying the code
Executing the code
Testing the custom interceptor for negative condition
Understanding CXF features
Applying the GZIP feature to the Order Process web service
Developing service and implementation class
Developing a server component
Creating the client bean configuration file
Creating a client component to consume the service
Building and executing the code
Understanding CXF Invoker
Overview of Invoker API
The Invoker interface
The AbstractInvoker class
Developing custom invoker
Summary
6. Developing RESTful Services with CXF
Overview of REST and RESTful services
Java API for RESTful services
CXF JAX-RS implementation
Developing end-to-end RESTful services using CXF JAX-RS implementation
Developing the RESTful service
Creating Java data objects for Request and Response
Providing binding for the Request and Response data objects
Developing the implementation class
Adding Data Access logic to the implementation class
Creating the client
Making RESTful service available over HTTP
Running the program
Building the code
Deploying the code
Executing the code
Adding exception handling to RESTful service
Summary
7. Deploying RESTful Services with CXF
Packaging the Book Shop application
Configuring CategoryService RESTful bean using Spring
Integrating Spring using web.xml
Building and deploying the WAR file
Building the code
Deploying the code
Invoking operations on the Book Shop RESTful application
Installing POSTER client
Invoking the Book Shop application using the the POSTER tool
Invoking the Get Category operation
Invoking the Add Category operation
Invoking the Update Category operation
Invoking the Add Books operation
Invoking the Get Books operation
Invoking the Update Category operation with invalid request
Invoking the Get Category operation with invalid request
Invoking the Delete Category operation
Invoking the Book Shop application using CXF APIs
Configuring JSON support for the Book Shop application
Incorporating JSON message format for the Book Shop application
Invoking the Get Category operation with JSON as the message format
Invoking the Add Category operation with JSON as the message format
Invoking the Book Shop application with JSON as the message format using CXF APIs
Intercepting messages for the Book Shop application
Deploying the Book Shop application in the application servers
Summary
8. Working with CXF Tools
Invoking a web service using the Java client
Analyzing the service WSDL definition
Building and running the Java web service clients
Generate the web service clients
Analyzing the JAX-WS and client generated artifacts
Modifying the generated client
Building the client
Running the client
Invoking the web service using JavaScript
Building and running the Java web service clients
Generating the JavaScript client
Analyzing the generated artifacts
Creating the client
Running the client
Creating Service Implementation from the WSDL file
Generating and deploying the Service Implementation from the WSDL file
Generating the web Service Implementation
Analyzing the Service Implementation generated artifacts
Modifying the generated Service Implementation
Building the web service project
Deploying and publishing the web service
Invoking the web service
Validating WSDL files
Summary
A. Getting Ready with Code Examples
Downloading the source code
Downloading the software required for the book
Setting up the environment
Using Maven for Build management
Building chapter source code using Maven
B. Getting Started with Spring
Concept of POJO-based development
Understanding Inversion of Control
Overview of aspect-oriented programming
Introduction to Spring framework
The Spring IoC container
Creating a Spring IoC application
Creating the entity model
Creating services
Creating the application and wiring POJO
Creating the standalone client
Running the program
Building the code
Executing the code
Summary
Index

Apache CXF Web Service Development

Naveen Balani

Rajeev Hathi

Apache CXF Web Service Development

Copyright © 2009 Packt Publishing

All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.

Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the authors, nor Packt Publishing, and its dealers and distributors will be held liable for any damages caused or alleged to be caused directly or indirectly by this book.

Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.

First published: December 2009

Production Reference: 2291209

Published by Packt Publishing Ltd.

32 Lincoln Road

Olton

Birmingham, B27 6PA, UK.

ISBN 978-1-847195-40-1

www.packtpub.com

Cover Image by Vinayak Chittar (<[email protected]>)

Credits

Authors

Naveen Balani

Rajeev Hathi

Reviewer

Brett Porter

Acquisition Editor

Usha Iyer

Development Editor

Reshma Sundaresan

Technical Editor

Shadab N Khan

Copy Editor

Leonard D'silva

Indexer

Hemangini Bari

Editorial Team Leader

Akshara Aware

Project Team Leader

Priya Mukherji

Project Coordinator

Ashwin Shetty

Proofreader

Kevin McGowan

Graphics

Nilesh R. Mohite

Production Coordinator

Adline Swetha Jesuthas

Cover Work

Adline Swetha Jesuthas

About the Authors

Naveen Balani works as a Software Architect with IBM India Software Labs (ISL). He leads the design and development activities for WebSphere Business Services Fabric product out of ISL Mumbai. He has over nine years of industrial experience and has architected and implemented large scale enterprise solutions.

Naveen Balani likes to research upcoming technologies and is a Master Author with IBM developerWorks having written over 60 plus publications, on topics such as Web services, ESB, JMS, SOA, architectures, open source frameworks, semantic Web, J2ME, pervasive computing, Spring, Ajax, and various IBM products. He started working with web services way back in 2001 and proposed the first MVC web services-based pattern (http://www.ibm.com/developerworks/library/ws-mvc/) in 2002.

Naveen Balani's articles on Spring Series (http://www.ibm.com/developerworks/web/library/wa-spring1/) were rated as the top articles in the last 10 years for developerWorks web architecture zone. He has co-authored books on Spring framework (http://www.wrox.com/WileyCDA/WroxTitle/Beginning-Spring-Framework-2.productCd-047010161X.html) and Multiple IBM Redbooks on WebSphere Business Services Fabric and BPM 6.2 Product deployments. You can reach him on his website—http://soaweb.co.in

I would like to thank my wonderful wife, Sonia, for her love and patience and her endless support in spending many hours sitting beside me, reviewing my work and providing valuable inputs.

I would also like to thank my parents for their support and encouragement in all my endeavors.

And last but not least, to my good friend and co-author Rajeev Hathi.

Rajeev Hathi is a J2EE Consultant and Developer living in Mumbai, India. He grew up in a joint Hindu family and pursued his primary education in the field of Economics and Commerce. His hobbies are watching sports and listening to rock music. His favorite bands are Pink Floyd and Dire Straits.

Rajeev has written several articles for IBM developerWorks portal. His major contributions are in the fields of Java, web service, and DB2. He developed an interest in computers after pursuing a diploma in Advanced Systems Management at NIIT (National Institute of Information Technology).

Rajeev has been working on J2EE-based projects for more than ten years now. He has worked with several companies offering software services and conducted various knowledge sessions on Java and J2EE. He has attained several Java-based certifications such as SCJP, SCWCD, SCBCD, and SCEA. He, along with the co-author Naveen Balani, has initiated a portal http://soaweb.co.in which aims to provide online consulting on the subject of web services.

A book is often the product of many hands. To start with I'd like to thank Usha Iyer, an Acquisition Editor with Packt Publishing, for having enough faith in my writing skills and abilities. My special thanks to the Packt Publishing team in making enormous efforts to make this book a reality. A good book cannot be made better without a constructive review and feedback and the reviewers equally contributed to the whole writing process.

I owe thanks to my wonderful and lovely friend, Sunita, who instilled in me enough confidence and zest to make my writing look effortless. I owe thanks and gratitude to my family members who have supported and encouraged my writing efforts day and night. And last but not least, without my co-author and amazing friend Naveen Balani, this project would not have been achievable.

Finally, I would like to dedicate this book to my late parents and late sister without their blessings, this project would have just remained a mere thought.

About the Reviewer

Brett Porter is a software developer from Sydney, Australia, with a passion for development tooling, and automation. Seeking a more standardized and reproducible solution to organize, build, and deploy a number of software projects across teams, he discovered an early beta of Maven 1.0 in 2003, and has since been heavily involved in the development of the project. Brett is a Director and a Member of the Apache Software Foundation. He is a member of the Apache Maven Project Management Committee, and has conducted presentations and training on Maven and related tooling at several conferences and events. He founded the Archiva project in 2005.

Brett is the co-author of Apache Maven 2: Effective Implementation, published by Packt Publishing in 2009. He was also the co-author of Better Builds with Maven, the first book to be written about the Maven 2.0 release in 2005, and has been involved in reviewing Maven: A Developer's Notebook and Java Power Tools.

My thanks goes to everyone involved at the Apache Software Foundation, and all those that contribute to and use the software. You make projects such as CXF and the many others possible.

I'd also like to thank my wife Laura and my young daughter Samantha, who could afford to spare me the extra hours to review this book, so soon after having written my own!

Preface

Apache CXF is an open source services framework that makes web service development easy, simplified, and standard based. CXF provides many features such as frontend programming, support for different transports and data bindings, support for different protocols, and other advanced concepts like Features and Invokers. It also provides a programming model to build and deploy RESTful services.

The focus of the book is to provide readers with comprehensive details on how to use the CXF framework for web services development. The book begins by giving us an overview of CXF features and architecture. Each feature is explained in a separate chapter, each of which covers well defined practical illustrations using real world examples. This helps developers to easily understand the CXF API. Each chapter provides hands on examples and provides step-by-step instructions to develop, deploy, and execute the code.

What this book covers

The book is about the CXF service development framework. The book covers two of the most widely used approaches, for web services development, SOAP and REST. Each chapter in the book provides hands on examples, where we look in detail at how to use the various CXF features in detail to develop web services in a step-by-step fashion.

Chapter 1: Getting Familiar with CXF revisits web service concepts and provides an introduction to CXF framework and its usage, and prepares the CXF environment for the following chapters. By the end of this chapter the reader will be able to understand the core concepts of CXF.

Chapter 2: Developing a Web Service with CXF focuses on getting the reader quickly started with the CXF framework by developing a simple web service and running it under the Tomcat container.

By the end of this chapter the reader will be able to develop a simple web service using CXF.

Chapter 3: Working with CXF Frontends illustrates the use of different frontends, like JAX-WS and CXF simple fronted API, and shows how to apply code-first and contract-first development approaches for developing web services. We will look at how to create dynamic web service clients, the use of web service context, and how to work directly with XML messages using CXF Provide and Dispatch implementation.

By the end of this chapter the reader will be able to apply different frontends to develop a web service.

Chapter 4: Learning about Service Transports explains basic transport protocols for a service and shows you how to configure HTTP, HTTP(s), JMS, and Local protocol for web services communication. You will get introduced to the concept of HTTP conduit, which enables the client program to apply policies or properties to HTTP and HTTPs protocols, and how to generate a crypto key and a key store for HTTPs based service communication. You will learn how to use JMS protocol for web services communication and how to facilitate web services message exchange using CXF Local service transport.

By the end of this chapter the reader will be able develop services with different transports

Chapter 5: Implementing Advanced Features will explain advanced concepts using CXF Features, Interceptors, and Invokers, and how to integrate these concepts in existing applications.

By the end of this chapter the reader will be able develop services with features like Interceptors and Invokers

Chapter 6: Developing RESTful Services with CXF explains the concept of REST technology and JAX-RS specifications, how CXF realizes the JAX-RS specification, and demonstrates additional features for developing enterprise RESTful services. We will look at how to design, develop, and unit test the RESTful Service by taking a real world example using CXF JAX-RS implementation.

By the end of this chapter the reader will be able to design, develop, and unit test the RESTful service

Chapter 7: Deploying RESTful Services with CXF will explain how to deploy REST services in a container like Tomcat using Spring configuration, and how to test out the various operations exposed by the RESTFul application using CXF RESTful client API using a web service development tool. We will look at how to enable exception handling, JSON message support, and logging support for RESTful applications using CXF framework.

By the end of this chapter the reader would be able utilize various CXF features for developing RESTful services and how to leverage Spring configuration for deploying RESTful service in the tomcat container.

Chapter 8: Working with CXF Tools will explain some of the commonly used CXF tools that assist us in web services development. We will look at how to invoke a real world .NET service over the internet using a Java client and JavaScript, create web service implementation from WSDL files, generate WSDL files from web service implementation, and validate the WSDL file for compliance.

By the end of this chapter the reader will be able to use different CXF tools to develop a service.

Appendix A deals with how to set up the CXF environment, provides details on how the source code for each chapter is organized, and shows how to run the source code examples using the ANT tool and Maven Tool.

Appendix B provides an explanation of the basics of the Spring framework and IoC concepts, along with an end-to-end example which utilizes Spring IoC concepts.

By the end of this Appendix chapter the reader will have a good understanding of Spring capabilities used in the context of CXF web services development in this book.

What you need for this book

You will need the following software to be installed before running the code example:

Java 5 or higher. Apache CXF requires JDK 5 or a later version. JDK 5 can be downloaded from the following site: http://java.sun.com/j2se/1.5.0/download.jspTomcat 6.0 or higher. There is no strict requirement for Tomcat for CXF. In fact, any servlet container that supports Java 5 or higher can be used with CXF. For our illustrations, we will use Tomcat as our servlet container. Tomcat version 6.0 can be downloaded from the following site: http://tomcat.apache.org/download-60.cgiApache Ant 1.7.1 or higher. Ant will be used to build and deploy the code. The build utility can be downloaded from the site: http://ant.apache.org/bindownload.cgiCXF binary distribution 2.2.3 or latest. CXF binary distribution can be downloaded from the site: http://cxf.apache.org/download.html. Maven 2.x or higher, if you plan to use Maven instead of ANT for running the code examples. Maven can be downloaded from the site http://maven.apache.org/

Refer to Appendix A for more details on how to set up the environment for running the code examples.

Who this book is for

This book is for developers who want to design and develop SOAP and RESTful services using Apache CXF framework, and leverage various CXF features for service development. It is ideal for developers who have some experience in Java application development as well as some basic knowledge of web services, but it covers some of the basic fundamentals of web services and REST to get you acquainted with these technologies before using these concepts to develop services using the CXF framework.

Reader feedback

Feedback from our readers is always welcome. Let us know what you think about this book—what you liked or may have disliked. Reader feedback is important for us to develop titles that you really get the most out of.

To send us general feedback, simply send an email to <[email protected]>, and mention the book title via the subject of your message.

If there is a book that you need and would like to see us publish, please send us a note in the SUGGEST A TITLE form on www.packtpub.com or email <[email protected]>.

If there is a topic that you have expertise in and you are interested in either writing or contributing to a book on, see our author guide on www.packtpub.com/authors.

Customer support

Now that you are the proud owner of a Packt book, we have a number of things to help you to get the most from your purchase.

Tip

Downloading the example code for the book

Visit http://www.packtpub.com/files/code/5401_Code.zip to directly download the example code.

The downloadable files contain instructions on how to use them.

Errata

Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you find a mistake in one of our books—maybe a mistake in the text or the code—we would be grateful if you would report this to us. By doing so, you can save other readers from frustration, and help us to improve subsequent versions of this book. If you find any errata, please report them by visiting http://www.packtpub.com/support, selecting your book, clicking on the let us know link, and entering the details of your errata. Once your errata are verified, your submission will be accepted and the errata added to any list of existing errata. Any existing errata can be viewed by selecting your title from http://www.packtpub.com/support.

Piracy

Piracy of copyright material on the Internet is an ongoing problem across all media. At Packt, we take the protection of our copyright and licenses very seriously. If you come across any illegal copies of our works, in any form, on the Internet, please provide us with the location address or web site name immediately so that we can pursue a remedy.

Please contact us at <[email protected]> with a link to the suspected pirated material.

We appreciate your help in protecting our authors, and our ability to bring you valuable content.

Questions

You can contact us at <[email protected]> if you are having a problem with any aspect of the book, and we will do our best to address it.

Chapter 1. Getting Familiar with CXF

We often require real world systems and applications to integrate with each other. Application integration is one of the critical areas that you need to focus on during application development, if your application involves integrating with third party or external systems. Alternatively, depending on your requirements, you may want other systems to access your application. Let's take an example of a credit card company providing services to guarantee payments made by consumers. These services are available over the Web, and consumers or applications, such as an online shopping application, or an airline firm that accepts credit cards as payment for its services, uses the credit card payment service for a consumer's payments. Since the credit card services can be accessed by any application client such as a web browser or a WAP (Wireless ApplicationProtocol) enabled phone, and developed using any programming language, there is a need for a standard-based communication where the services offered can be used by any application, irrespective of any underlying technology. This is where web services come into play, and to simplify the design and development of web services, you have the option of using various web service frameworks. Apache CXF is one such leading standard-based web services framework whose goal is to simplify web services development.

In order to get started with the CXF framework, you first need to understand the concepts behind web services, the technology, and the standards that make up web service and features provided by the CXF framework. This chapter will cover these core concepts.

Specifically, in this chapter we will cover the following topics:

The core technology standards and concepts behind web servicesApproaches for web services developmentOverview of Apache CXF frameworkFeatures provided by Apache CXF frameworkSetting up Apache CXF environment

Web service technology standards

Before you look at the concept behind web services you need to understand the core technology standards that make up web services. Covering all the concepts and standards associated with web services is a vast topic in itself. In this chapter we attempt to cover the relevant web service standards and information used in the context of this book to get you acquainted with the technologies for developing web services using CXF. Some of the concepts will be explained in greater detail during the course of this book.

XML

XML stands for Extensible Markup Language. XML is a markup language that specifies or describes the format of the data to be exchanged between two parties. The data is significantly structured as tags or elements in a hierarchical order. A user can create his/her own tag to represent structured information. XML has become the de facto standard for representing structured information. Some of the important standard technologies associated with an XML document are listed below:

XML namespace—an XML namespace is a standard for providing uniquely named elements and attributes in an XML document. The XML namespace concept is similar to package definitions in Java, which provide conflict resolution of class names based on package declarations. A namespace is declared using the reserved XML attribute xmlns, the value of which must be a URI (Uniform Resource Identifier) reference, for example, xmlns=http://www.w3.org/1999/xhtml or using a prefix xmlns:xhtml=http://www.w3.org/1999/xhtml.XML schema—XML schema provides a means of defining the structure, content, and semantics of XML documents. The XML Schema data model includes the vocabulary (element and attribute names), the content model (relationships and structure), and data types. An example of XML Schema describing address information is provided below:
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:element name="address" type="Address"/> <xs:complexType name="Address"> <xs:sequence> <xs:element name="addressLine1" type="xs:string"/> <xs:element name="addressLine2" type="xs:string"/> <xs:element name="city" type="xs:string"/> <xs:element name="state" type="xs:string"/> <xs:element name="country" type="xs:string"/> </xs:sequence> </xs:complexType> </xs:schema>

In the above example, xs represents the namespace of the XML Schema. The address represents an element whose type is Address. The Addresstype in turn is represented as complexType (similar to a Java bean Address class which stores address information), which is comprised of elements "addressLine1", "addressLine2", "city", "state", and "country" with data type as string. The code listing below provides a valid Address XML document based on the above Address XML schema. The Address XML Schema provides validation for the following XML document:

<address xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="address.xsd"> <addressLine1>1501 ACity</addressLine1> <addressLine2>UCity</addressLine2> <city>SFO</city> <state>CA</state> <country>US</country> </address>

SOAP (Simple Object Access Protocol)

SOAP is a protocol for exchanging XML-based messages over a network, typically using HTTP protocol. The SOAP message format is comprised of a SOAP Envelope which encloses all request information. The SOAP Envelope, in turn, is then made up of optional headers and a body. The headers optionally contain context related information, such as security or transaction, while the body contains actual payload or application data.

The following listing provides a sample SOAP message format containing address information:

<?xml version="1.0"?> <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ns1="http://apress.com/beginjava6/address" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> <soapenv:Header></soapenv:Header> <soapenv:Body> <ns1:Address> <ns1:addressLine1>1501ACity</ns1:addressLine1> <ns1:addressLine2>UCity</ns1:addressLine2> <ns1:city>SFO</ns1:city> <ns1:state>CA</ns1:state> <ns1:country>US</ns1:country> </ns1:Address> </soapenv:Body> </soapenv:Envelope>

WSDL (Web Services Description language)

WSDL is a standard-based XML language used to describe web services. Under WSDL, a web service is described as a set of communication endpoints that are capable of exchanging messages. These communication endpoints are called ports.

An endpoint is comprised of two parts:

The first part is the abstract definitions of operations (similar to methods in Java) provided by the services and messages (input and output parameter types for methods) which are needed to invoke the service. The set of abstract operation definitions is referred to as port type.The second part is the concrete binding of those abstract definitions of operations to concrete network protocol, where the service is located, and message format for the service.

The WSDL binding describes how the service is bound to a messaging protocol, particularly the SOAP messaging protocol. Typically, the WSDL files would be created using the tool provided by the web service framework. The following block of code shows a listing of Address Verification WSDL, which uses the Address XML schema. Please refer to the inline comments for an explanation of the elements in the below WSDL file:

<?xml version='1.0' encoding='UTF-8'?><wsdl:definitions name="AddressVerifyProcessImplService" targetNamespace="http://order.demo/" xmlns:ns1="http://schemas.xmlsoap.org/soap/http" xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/" xmlns:tns="http://order.demo/" xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> <wsdl:types> <!-- Schema definition for Address element. This serves as the input message format for invoking the Address verification service. --> <xs:schema attributeFormDefault="unqualified" elementFormDefault="unqualified" targetNamespace="http://order.demo/" xmlns:tns="http://order.demo/" xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:element name="Address" type="tns:address" /> <xs:element name="verifyAddress" type="tns:verifyAddress" /> <xs:element name="verifyAddressResponse" type="tns:verifyAddressResponse" /> <xs:complexType name="verifyAddress"> <xs:sequence> <xs:element minOccurs="0" name="arg0" type="tns:address" /> </xs:sequence> </xs:complexType> <xs:complexType name="address"> <xs:sequence> <xs:element minOccurs="0" name="addressLine1" type="xs:string" /> <xs:element minOccurs="0" name="addressLine2" type="xs:string" /> <xs:element minOccurs="0" name="city" type="xs:string" /> <xs:element minOccurs="0" name="country" type="xs:string" /> <xs:element minOccurs="0" name="state" type="xs:string" /> </xs:sequence> </xs:complexType> <xs:complexType name="verifyAddressResponse"> <xs:sequence> <xs:element minOccurs="0" name="return" type="xs:string" /> </xs:sequence> </xs:complexType> </xs:schema> </wsdl:types> <!-- Specifies the Messages for Address Verification Service. --> <wsdl:message name="verifyAddressResponse"> <wsdl:part element="tns:verifyAddressResponse" name="parameters"> </wsdl:part> </wsdl:message> <wsdl:message name="verifyAddress"> <wsdl:part element="tns:verifyAddress" name="parameters"> </wsdl:part> </wsdl:message> <!-- Specifies the Operations for Verify Address service. --> <wsdl:portType name="AddressVerifyProcess"> <wsdl:operation name="verifyAddress"> <wsdl:input message="tns:verifyAddress" name="verifyAddress"> </wsdl:input> <wsdl:output message="tns:verifyAddressResponse" name="verifyAddressResponse"> </wsdl:output> </wsdl:operation> </wsdl:portType> <!-- Specifies the SOAP Binding for Verify Address Process. --> <wsdl:binding name="AddressVerifyProcessImplServiceSoapBinding" type="tns:AddressVerifyProcess"> <soap:binding style="document" transport="http://schemas.xmlsoap.org/soap/http" /> <wsdl:operation name="verifyAddress"> <soap:operation soapAction="" style="document" /> <wsdl:input name="verifyAddress"> <soap:body use="literal" /> </wsdl:input> <wsdl:output name="verifyAddressResponse"> <soap:body use="literal" /> </wsdl:output> </wsdl:operation> </wsdl:binding> <!-- Service definition for Verify Address . --> <!-- The soap location specifies the URL where the address verify service is located. --> <wsdl:service name="AddressVerifyProcessImplService"> <wsdl:port binding="tns:AddressVerifyProcessImplServiceSoapBinding" name="AddressVerifyProcessImplPort"> <soap:address location="http://localhost:9000/AddressVerifyProcess" /> </wsdl:port> </wsdl:service> </wsdl:definitions>

Note

In Chapter 8 you will look at how to use the various CXF tools for web services development and format of WSDL files in detail.

REST (Representational State Transfer)

REST (Representational State Transfer) is neither a technology nor a standard; it's an architectural style—a set of guidelines for exposing resources over the Web. The REST architecture style is related to a resource, which is a representation identified by a Uniform Resource Indicator (URI), for example, http://cxf.soaweb.co.in/mybook. The resource can be any piece of information such as a book, order, customer, employee, and so on. The client queries or updates the resource through the URI and, therefore, influences a state change in its representation. All resources share a uniform interface for the transfer of state between client and resource.

The World Wide Web is a classic example built on the REST architecture style. As implemented on the World Wide Web, URIs identify the resources (http://amazon.com/mybook), and HTTP is the protocol by which resources are accessed. HTTP provides a uniform interface and set of methods to manipulate the resource. A client program, like a web browser, can access, update, add, or remove a Web resource through URI using various HTTP methods, like GET and POST, thereby changing its representational state.

Note

In Chapter 6 and 7 you will look at the REST concepts in detail and how to develop web services using the REST architecture style (also termed RESTful Web Services).

Service Registry

Service Registry provides a mechanism to look up web services. Traditionally, there was UDDI specification that defined the standards on registering and discovering a web service, but it lacked enterprise-wide adoption. Enterprises started shipping their own version of Service Registry, providing enterprise capabilities like service versioning, service classifications, and life cycle management.

Introducing web services

There are many different definitions available for a web service. The World Wide Web Consortium (W3C) defines a web service as follows:

A Web service is a software system identified by a URI whose public interfaces and bindings are defined and described using XML (specifically WSDL). Its definition can be discovered by other software systems. These systems may then interact with the web service in a manner prescribed by its definition, using XML-based messages conveyed by Internet protocols.

Simply, put web service is a software component that provides a business function as a service over the web that can be accessed through a URL. Web services are next generation web applications, modules, or components that can be thought of as a service provided over the web. Traditionally, we had static HTML pages as web content, which evolved into more dynamic full featured web applications providing business functionality and rich GUI features to the end user. A web service component is one step ahead of this web paradigm and provides only business service, usually in the form of raw XML data that can be digested by virtually all client systems. The GUI and business functionality are well separated. A web service can be thought of as a self contained, self describing, modular application that can be published, located, and invoked across the web.

The greatest benefit that web services provide is interoperability. Web services can be ported on any platform and can be written in different programming languages. Similarly, the client accessing the web service can be an application written in a different language and running on a different platform than that of a service itself.

Approaches for web service development

Two of the most widely used approaches for developing web services are SOAP (Simple Object Access Protocol) and the REST (Representational State Transfer) architecture style. In depth details on developing SOAP-based web services are provided in Chapters 2-5, while Chapters 6 and 7 are dedicated to RESTful web service development.

A web service involves three types of roles—a service consumer, a service provider, and an optional service registry. The following diagram shows the interaction between the service provider, the service consumer, and the service registry:

The service providers furnish the services over the web and respond to web service requests. The service consumer consumes the services offered by the service provider. In SOAP-based web services, the service provider publishes the contract (WSDL file) of the service over the web where a consumer can access it directly or by looking up a service registry. The service consumer usually generates a web service client code from a WSDL file using the tools offered by the web service framework to interact with the web service. In the next chapter you will look at how to create web service clients from a WSDL file.

Note

In Chapter 8 you will look at how to use various CXF tools for web service development.

With RESTful Web Services there is no formal contract between the service provider and the service consumer. The service requestor needs to know the format of the message, for instance, XML or JSON (Java Script Object Notation), and operations supported by the service provider. The service provider exposes the set of operations using standard HTTP methods like GET or POST. The service requestor invokes one of the methods defined for the resources using the URI over the HTTP protocol.

The choice of adopting SOAP rather than REST depends on your application's requirements. If your requirement consists of transmitting and receiving simple XML messages, then you would probably go with RESTful Web Services. However, if your requirement consists of various contracts to be defined and negotiated between the provider and consumer such as using a WSDL (Web Service Description Language) file and adhering to various web services specifications (WS Specifications) such as web service security for enterprise adoption, then SOAP-based web services is the right option. If you are developing SOAP-based services, then you also need to be aware of SOAP communication styles.

Web service SOAP communication styles

The web service SOAP communication style plays a significant role in communicating SOAP XML messages between the service provider and the service consumer. There exist two types of SOAP message styles, Document and RPC. The SOAP message styles are defined in a WSDL document as SOAP binding. A SOAP binding can have either an encoded use or a literal use. Encoding as the term implies, the message would be encoded using some format, while literal specifies plain text messages without any encoding logic.

Document style, as the name suggests, deals with XML documents as payloads which adhere to well defined contracts, typically created using XML schema definitions. The XML schema format specifies the contract for business messages being exchanged between web service provider and consumer, which the consumers can call and adhere to. The XML schema defines the request and response message format between the service provider and the service consumer. Document literal style is the preferred way of web service communication for achieving interoperability.

RPC (Remote Procedure Call) style, on the other hand, indicates that the SOAP body contains an XML representation of a method. In order to serialize method parameters into the SOAP message so it can be deserialized back by any web service implementation, the SOAP specification defines a standard set of encoding rules. As RPC is traditionally used in conjunction with SOAP encoding rules, the combination is referred to as RPC/encoded. You also have an RPC/literal communication style model where you don't have any encoding formats, but the messages are still limited to RPC method-based communication, where messages can't be validated as they are not tied to any XML Schema definition. You should probably avoid developing RPC style web services as it has a lot of interoperability issues.

Note

There are lot of specifications designed for SOAP-based web services. These web service specifications are designed for interoperable protocols for Security, Reliable Messaging, Management, and Transactions in loosely coupled systems. The specifications are built on top of the core XML and SOAP standards.

Apache CXF

Apache CXF is an open source web service framework that provides an easy to use, standard-based programming model for developing web services. Web services can be implemented using different application protocols like SOAP, XML, JSON, RESTful HTTP, and support various transport protocols like HTTP or JMS (Java Message Service).

History of CXF

Exactly what does CXF stand for? Apache CXF is the product of two projects, Celtix and XFire, hence the name CXF. Celtix, an open source Java-based Enterprise Service Bus (ESB) project, is a product of ObjectWeb consortia that delivers open source middleware solutions. The project was sponsored by IONA. On the other hand, XFire, a Java-based SOAP framework, is an open source project from Codehaus. Both Celtix and XFire, while in their initial versions, had many things in common and therefore the developers of both projects decided to bring out the best of both worlds and planned a better 2.0 version of Celtix and XFire. The communities of both these projects entered incubation at the Apache Software foundation to develop version 2.0. It took about 20 months at the Apache incubator before CXF finally rolled out. CXF is now formally known as Apache CXF which concentrates on delivering an open source web service framework. The framework which had its first release as v2.0, is now evolved as v2.2, with bug fixes, and the addition of new features.

Why CXF?

Picking up a framework is always a challenging task. There are many web service frameworks available today. Historically, there was Axis 1 which evolved into Axis 2, providing better flexibility and enhanced support for web service standards. Other widely used web service frameworks are GlassFish Metro, Glue, JBossWS, and so on. Every web services framework aims to provide a robust infrastructure for the developer to conveniently build, deploy, and publish the web services. So which one is the better framework? That's a million dollar question!

We choose CXF rather than other web service frameworks as it supports all the leading web service standards and provides a simplified programming model for developing SOAP and RESTful-based web services, along with options for various other application protocols. CXF provides a flexible deployment model for implementing web services. More specifically, we choose CXF as it provides the following capabilities.

Support for web service standards

Web service standards define the norms of a web service implementation with respect to its interoperability. The standards ensure that a web service is accessed independently of the client platform.

The framework provides the following web service standards support:

Java API for XML Web Services (JAX-WS)SOAPWeb Services Description Language (WSDL)Message Transmission Optimization Mechanism (MTOM)WS-Basic ProfileWS-AddressingWS-PolicyWS-ReliableMessagingWS-Security

One of the most important web services technologies is JAX-WS. JAX-WS is a specification designed to simplify the construction of primarily SOAP-based web services and web service clients in Java. JAX-WS also includes the Java Architecture for XML Binding (JAXB) and SOAP with Attachments API for Java (SAAJ).

JAXB offers data binding capabilities by providing a convenient way to map XML schema to a representation in Java code. The JAXB shields the conversion of XML schema messages in SOAP messages to Java code without having the developers see the XML and SOAP parsing. The JAXB specification defines the binding between Java and XML schema. SAAJ provides a standard way of dealing with XML attachments contained in a SOAP message. CXF provides support for a complete JAX-WS stack. We will look at how to use the JAX-WS standards while developing web services in the next chapter.

The WS-Addressing, WS-Policy, WS-ReliableMessaging, and WS-Security are all part of the web services specification aimed to bring in consistency in various areas of web services. For instance, WS-Security specification is about how integrity and confidentiality can be enforced on web services using a standard method.

The WS-I Basic Profile is a specification from the Web Services Interoperability industry consortium (WS-I