SlideShare a Scribd company logo
WebServices
XML/WEBSERVICES
&
RESTful Services
(XML, DTD, XSD, JAX-P, JAX-B, SOAP, WSDL, JAX-WS, SOAP UI, JAX-RS & POSTMAN)
By: Mr. ZEESHAN KHAN
Email: zeeshan.maths@gmail.com
INDEX
Webservices Introduction
Introduction -----------------------------------------------------------------------1
Distributed Programming ---------------------------------------------------- 2-3
CORBA------------------------------------------------------------------------------------4
RMI ---------------------------------------------------------------------------------- 5-6
EJB ----------------------------------------------------------------------------------------------- 7
Common challenges inDistributed Programming ---------------------8
Webservices specifications -------------------------------------------------- 9
Webservices Architecture --------------------------------------------------- 10-11
Motivation and Characteristics---------------------------------------------- 12-13
Core Webservices Standards ------------------------------------------------------14-16
XML---------------------------------------------------------------------------- 18-22
DTD
Introduction ------------------------------------------------------------------------------- 24
SimpleElements -------------------------------------------------------------------------------- 25
CompoundElements --------------------------------------------------------------------------26
Attributes -----------------------------------------------------------------------------------27
DTDTypes----------------------------------------------------------------------------------------28-29
DTDDrawbacks --------------------------------------------------------------------------------- 30
XSD
Introduction -------------------------------------------------------------------------32
Simple Elements Declaration -------------------------------------------------- 33
Compound Elements Declaration --------------------------------------------34-35
Linking XSD to XML --------------------------------------------------------------------- 36
Element Cardinality ---------------------------------------------------------------- 37
Compositors (sequence, all and choice)-------------------------------------38-39
Global Elements --------------------------------------------------------------------40
Group Elements--------------------------------------------------------------------------------- 41-42
Inheritance in XSD----------------------------------------------------------------- 43
AttributesinXSD -------------------------------------------------------------------------- 44-46
RestrictiononSimpleTypes ----------------------------------------------------------------- 47-51
XSDNamespaces--------------------------------------------------------------------------------52-53
xs: include ---------------------------------------------------------------------------------- 54
xs:import -----------------------------------------------------------------------------------55-56
JAX-P
Introduction -------------------------------------------------------------------------- 58
SAXParser ----------------------------------------------------------------------------------------- 59-64
DOMParser--------------------------------------------------------------------------------- 65-69
STAXParser --------------------------------------------------------------------------------------- 70-71
XMLvalidation against XSD -------------------------------------------------------------------72-73
JAX-B
Introduction --------------------------------------------------------------------------- 74
JAX-B Architecture-------------------------------------------------------------------75
Binding------------------------------------------------------------------------------------------------ 76-77
One-Time Operations--------------------------------------------------------------- 78
UsingXJC ------------------------------------------------------------------------------------------------ 79-80
Runtime Operations -----------------------------------------------------------------81
Un-Marshalling -------------------------------------------------------------------------------------81-83
Marshalling ---------------------------------------------------------------------------- 84
In-Memory Validation--------------------------------------------------------------- 85
Getting Started with Webservices
Introduction --------------------------------------------------------------------------- 86
Webservicespre-requisites --------------------------------------------------------------------87-88
JAX-WS
Introduction --------------------------------------------------------------------------- 90-94
JAX-WS Features---------------------------------------------------------------------------95
JAX-WS Implementations----------------------------------------------------------96
ProviderDevelopment(ContractLastApproach)---------------------------------------97-100
Consumer Development ------------------------------------------------------------------------101 - 102
Provider(ContractFirstApproach) ---------------------------------------------------------- 103-107
SOAP Handlers Introduction ----------------------------------------------------- 108
Provider withSOAP Handler ------------------------------------------------------------------- 108-117
ConsumerwithSOAPHandler----------------------------------------------------------------- 118-121
APACHE AXIS2
Introduction ----------------------------------------------------------------------------122
Environment Setup---------------------------------------------------------------------------------123-125
webservicesdevelopmentusingAXIS2 -----------------------------------------------------126-131
Spring+JAX-WSIntegration --------------------------------------------------------------------132-138
Restful services
Introduction ----------------------------------------------------------------------------140-142
HttpMethods ----------------------------------------------------------------------------143-149
JAX-RS API Introduction ----------------------------------------------------------- 150
JSON----------------------------------------------------------------------------------------------------151-155
GSONAPI---------------------------------------------------------------------------------------------- 156-157
Jersey--------------------------------------------------------------------------------------------------- 158-159
JAX-RS Annotations overview---------------------------------------------------- 160
Restfulservicefirstapplication ----------------------------------------------------------------162-164
JAX-RS Injection ---------------------------------------------------------------------------------------- 165-167
RestResourcewithJSONdata ---------------------------------------------------------------- 168-170
@Consumes------------------------------------------------------------------------------------------171-173
Jersey2.xapplication ----------------------------------------------------------------------------174-179
JerseyClient-----------------------------------------------------------------------------------------180-183
RestAppwithoutXML --------------------------------------------------------------------- 185-186
Rest Easy Introduction--------------------------------------------------------------187
RestfulServicewithRestEasy ----------------------------------------------------------------- 188-189
RestEasy Client ----------------------------------------------------------------------------- 190
BootstrappinginRestEasy --------------------------------------------------------------------- 191-192
File Uploading -------------------------------------------------------------------------------------- 193-194
Spring+RestfulServiceIntegration --------------------------------------------------------- 195-211
Response --------------------------------------------------------------------------------------212
Http Headers --------------------------------------------------------------------------------------213--214
ExtractingRequestParameters----------------------------------------------------------------215-218
ExceptionHandling --------------------------------------------------------------------------------219-220
Caching ----------------------------------------------------------------------------------------------- 221-224
Security ------------------------------------------------------------------------------------------------224-230
Conclusion------------------------------------------------------------------------------------------------ 231-233
POSTMAN--------------------------------------------------------------------234-238
SpringIntegrationwithREST-------------------------------- 239-247
Web Services
1 | P a ge
Web Services are the mechanism or the medium of communication through which two applications / machines
willexchangethedata/businessservicesirrespectiveoftheirunderlinearchitectureandthetechnology.
In general, software applications are developed to be consumed by the human beings, where a person sends a
request to a software service which in-turn returns a response in human readable format.
In the modern era of technology if we want to build a software application we don't need to build each and
everything from scratch. There are lots of readymade services available which we can plug into our application
and we can start providing those services in our application.
For example, we want to display weather forecast information in our application but weather forecast information
will not be available in our application database. So, our application should talk to Satellites to get weather
forecastinformation.So,dowereallyneedtowritethecomplexlogictotalkwithsatellitetogetthedetails?-No,
we don't needtocollect, process andrenderthe datainyour application from satellite. Because some applications
arealreadydevelopedbypeopletogettheweatherforecastdetailsfromsatellitessowecanbuytheservices
from those people who already well-established in processing and publishing suchkind of data.
Now the question is how our application can talk to weather forecaster application? That's where Web services
comes into picture. Webservices allow us establish communication between two applications irrespective of the
language and irrespective of the platform. If two applications which are developed in two different languages able
to communicate with each other, then those applications are called as Interoperable applications. Webservices
are used develop interoperable applications.
AJavaapplicationcanconnect with.NetapplicationusingWebservicesandvice versa
A PHP application can connect with java application and vice versa
2 | P a ge
Web Services
Before jumping into Webservices development first let’s see some background related to Distributed
Computing.
TheInternethasrevolutionizedourbusinessbyprovidinganinformationhighway,whichactsasanewformof
communicationbackbone.Thisnewinformationmediumhasshiftedbusinessfromthetraditionalbrick-and-
mortar infrastructures to a virtual world where they can serve customers not just the regular eight hours, but
round-the-clock and around theworld. Additionally, it enhances our organizations with significant benefits in
terms of business productivity, cost savings, and customer satisfaction. As a result, modern organizations are
compelledtore-evaluatetheirbusinessmodelsandplanonabusinessvisiontointeractwiththeircustomers,
suppliers, resellers, and partners using an Internet-based technology space. To achieve this goal of obtaining an
Internetbusinesspresence, organizations areexposing anddistributingtheir business applicationsoverthe
Internet by going through a series of technological innovations. The key phenomenon of enabling business
applicationsover the Internet is based ona fundamentaltechnology called distributed computing.
Distributedcomputinghasbeenpopularwithinlocalareanetworksformanyyears,andittookamajorstep
forward by adopting the Internet as its base platform and by supporting its open standard-based technologies.
This chapter discusses the background of distributed computing and the evolution of Internet-enabled
technologies by focusing on the following:
1. The definition of distributed computing
2. The importance of distributed computing
3. Core distributed computing technologies such as the following:
• Client/server
• CORBA
• Java RMI
4. Common challenges in distributed computing
5. The role of J2EE and XML in distributed computing
6. Emergence of Web services and service-oriented architectures
What Is Distributed Computing?
In the early years of computing, mainframe-based applications were the best-fit solution for executing large-scale
data processing applications. With the advent of personal computers (PCs), the concept of software programs
runningonstandalonemachinesbecamemuchmorepopularintermsofthecostofownershipand the ease of
application use. With the number of PC-based application programs running on independent machines growing,
the communications between such application programs became extremely complex and added a growing
challenge in the aspect of application-to-application interaction. Lately, network computing gained importance,
andenablingremoteprocedurecalls(RPCs)overanetworkprotocolcalledTransmissionControlProtocol/Internet
Protocol (TCP/IP) turned out to be a widely accepted way for application software communication. Since then,
software applicationsrunning on a variety of hardware platforms, operating systems, and different networks
faced some challenges when required to communicate with each other and share data. This demanding
requirement lead to the concept of distributed computing applications.
As a definition, “Distributing Computing is a type of computing in which different components and objects
comprising an application can be located on different computers connected to a network” (www.webopedia.com,
May 2001). Below diagram shows a distributed computing model that provides an infrastructure enabling
invocations of object functions located anywhere on the network. The objects are transparent to the application
and provide processing power as if they were local to the application calling them.
3 | P a ge
Web Services
Today,SunJavaRMI(RemoteMethodInvocation),OMGCORBA(CommonObjectRequestBrokerArchitecture),
Microsoft DCOM (Distributed Component Object Model), and Message-Oriented Middleware (MOM) have
emerged as the mostcommon distributed computing technologies.These technologies, although different intheir
basic architectural design and implementation, address specific problems in their target environments. The
following sections discuss the use of distributed computing and briefly describe the most popular technologies.
The Importance of Distributed Computing
The distributed computing environment provides many significant advantages compared to a traditional
standalone application. The following are some of those key advantages:
Higher performance. Applications can execute in parallel and distribute the load across multiple servers.
Collaboration.Multipleapplicationscanbeconnectedthroughstandarddistributedcomputingmechanisms.
Higherreliabilityandavailability.Applicationsorserverscanbeclusteredinmultiplemachines.
Scalability. This can be achieved by deploying these reusable distributed components on powerful servers.
Extensibility. This can be achieved through dynamic (re)configuration of applications that are distributed across
the network.
Higherproductivityandlowerdevelopmentcycletime. Bybreakinguplargeproblemsintosmallerones,these
individual components can be developed by smaller development teams in isolation.
Reuse. The distributed components may perform various services that can potentially be used by multiple client
applications.Itsavesrepetitivedevelopmenteffortandimprovesinteroperabilitybetweencomponents.
Reducedcost.Becausethismodelprovidesalotofreuseofoncedevelopedcomponentsthatareaccessibleover
the network, significant cost reductions can be achieved.
Distributed computing also has changed the way traditional network programming is done by providing a
shareable object like semantics across networks using programming languages like Java, C, and C++. The fol-
lowing sections briefly discuss core distributed computing technologies such as Client/Server applications, OMG
CORBA, Java RMI and MOM.
Client-Server Applications
The early years of distributed application architecture were dominated by two-tier business applications. In a two-
tierarchitecturemodel,thefirst(upper)tierhandlesthepresentationandbusinesslogicoftheuserapplication
(client), and the second/lower tier handles the application organization and its data storage (server). This
approachiscommonlycalledclient-serverapplicationsarchitecture.Generally,theserverinaclient/server
4 | P a ge
Web Services
applicationmodelisadatabaseserverthatismainlyresponsiblefortheorganizationandretrievalofdata.The
application client in this model handles most of the business processing and provides the graphical user interface
of the application. It is a very popular design in business applications where the user interface and business logic
aretightlycoupledwithadatabaseserverforhandling dataretrievaland processing. Forexample,theclient-
server model has been widely used in enterprise resource planning (ERP), billing, and Inventory application
systemswheremanyclient businessapplicationsresiding inmultipledesktop systemsinteractwithacentral
database server.
Below figure shows an architectural model of a typical client server system in which multiple desktop-based
business client applications access a central database server.
Some of the common limitations of the client-server application model are as follows:
 Complex business processing at the client side demands robust client systems.
 Security is more difficult to implement because the algorithms and logic reside on the client side making
it more vulnerable to hacking.
 Increasednetworkbandwidthisneededtoaccommodatemanycallstotheserver,whichcanimpose
scalability restrictions.
 Maintenanceandupgradesofclientapplicationsareextremelydifficultbecauseeachclienthastobe
maintained separately.
 Client-server architecture suits mostly database-oriented standalone applications and does not target
robust reusable component- oriented applications.
To avoid the limitations of normal client-server architecture Distributed Technologies came into picture.
CORBA
TheCommonObjectRequestBrokerArchitecture(CORBA)isanindustrywide,openstandardinitiative,developed
by the Object Management Group (OMG) for enabling distributed computing that supports a wide range of
applicationenvironments.OMGisanonprofitconsortiumresponsiblefortheproductionandmaintenanceof
framework specifications for distributed and interoperable object-oriented systems.
CORBA differs from the traditional client/server model because it pro- vides an object-oriented solution that does
not enforce any proprietary protocols or any particular programming language, operating system, or hardware
platform. By adopting CORBA, the applications can reside and run on any hardware platform located anywhere
onthenetwork,andcanbewritteninanylanguagethathasmappingstoaneutralinterfacedefinitioncalledthe
Interface Definition Language (IDL). An IDL is a specific interface language designed to expose the services
(methods/functions) of a CORBA remote object. CORBA also defines a collection of system-level services for
5 | P a ge
WebServices
handling low-level application services like life-cycle, persistence, transaction, naming, security, and so forth.
Initially, CORBA 1.1 was focused on creating component level, portable object applications without
interoperability. The introduction of CORBA 2.0 added interoperability between different ORB vendors by
implementing an Internet Inter-ORB Protocol (IIOP). The IIOP defines the ORB backbone, through which other
ORBs can bridge and provide interoperation with its associated services.
In a CORBA-based solution, the Object Request Broker (ORB) is an object bus that provides a transparent
mechanism for sending requests and receiving responses to and from objects, regardless of the environment and
itslocation.TheORBinterceptstheclient’scallandisresponsibleforfind-ingitsserverobjectthatimplements
the request, passes its parameters, invokes its method, and returns its results to the client. The ORB, as part of its
implementation, provides interfaces to the CORBA services, which allows it to build custom-distributed
application environments.
Figure 1.3 illustrates the architectural model of CORBA with an example representation of applications written in
C, C++, and Java providing IDL bindings.
The CORBA architecture is composed of the following components:
IDL: CORBA uses IDL contracts to specify the application boundaries and to establish interfaces with its clients.
The IDL provides a mechanism by which the distributed application component’s interfaces, inherited classes,
events, attributes, and exceptions can be specified in a standard definition language supported by the CORBA
ORB.
Java RMI
TheRMI(RemoteMethodInvocation)isanAPIthatprovidesamechanismtocreatedistributedapplicationin
java. The RMI allows an object to invoke methods on an object running in another JVM.
The RMI provides remote communication between the applications using two objects stub and skeleton.
Understandingstubandskeleton:RMIusesstubandskeletonobjectforcommunicationwiththeremoteobject.
Aremote object is an object whosemethod canbe invoked from another JVM. Let's understandthe stub and
skeleton objects:
Stub
The stub is an object, acts as a gateway for the client side. All the outgoing requests are routed through it. It
residesattheclientsideandrepresentstheremoteobject.Whenthecallerinvokesmethodonthestubobject,
it does the following tasks:
6 | P a ge
WebServices
 It initiates a connection with remote Virtual Machine (JVM),
 It writes and transmits (marshals) the parameters to the remote Virtual Machine (JVM),
 It waits for the result
 It reads (unmarshals) the return value or exception, and
 It finally, returns the value to the caller.
Skeleton
Theskeleton isanobject, actsasagateway for the serverside object. Allthe incoming requests areroutedthrough
it. When the skeleton receives the incoming request, it does the following tasks:
 It reads the parameter for the remote method
 It invokes the method on the actual remote object, and
 It writes and transmits (marshals) the result to the caller.
 In the Java 2 SDK, a stub protocol was introduced that eliminates the need for skeletons.
Figure1.4depictsthearchitecturalmodelofaJavaRMI-basedapplicationsolution.
The Java RMI architecture is composed of the following components:
RMI client  The RMI client, which can be a Java applet or a stand- alone application, performs the remote
method invocations on a server object. It can pass arguments that are primitive data types or serializable objects.
RMI stub The RMI stub is the client proxy generated by the rmi compiler (rmic provided along with Java
developer kit—JDK) that encapsulates the network information of the server and performs the delegation of the
method invocation to the server. The stub also marshals themethod arguments and unmarshals the return values
from the methodexecution.
RMI infrastructure  The RMI infrastructure consists of two layers: the remote reference layer and the transport
layer.Theremotereferencelayerseparatesoutthespecificremotereferencebehaviorfromtheclientstub.It
handles certain reference semantics like connection retries, which are unicast/multicast of the invocation
requests.Thetransportlayeractuallyprovidesthenetworkinginfrastructure,whichfacilitatestheactualdata
transferduringmethodinvocations,thepassingofformalarguments,andthereturnofbackexecutionresults.
RMI skeleton The RMI skeleton, which also is generated using the RMI compiler (rmic) receives the invocation
requestsfromthestub andprocessesthearguments(unmarshalling) anddelegates them totheRMIserver. Upon
successfulmethodexecution,itmarshalsthereturnvaluesandthenpassesthembacktotheRMIstubviathe
RMI infrastructure.
7 | P a ge
WebServices
RMIserverTheserveristheJavaremoteobjectthatimplementstheexposedinterfacesandexecutesthe
client requests. It receives incoming remote method invocations from the respective skeleton, which passes the
parameters after unmarshalling. Upon successful method execution, return values are sent back to the skeleton,
which passes them back to the client via the RMI infrastructure.
Developing distributed applications in RMI is simpler than developing with Java sockets because there is no need
to design a protocol, which is a very complex task by itself. RMI is built over TCP/IP sockets, but the added
advantage is that it provides an object-oriented approach for inter- process communications. Java RMI provides
the Java programmers with an efficient, transparent communication mechanism that frees them of all the
application-levelprotocolsnecessarytoencodeanddecodemessagesfordataexchange.RMIenablesdistributed
resource management, best processing power usage, and load balancing in a Java application model. RMI-IIOP
(RMI over IIOP) is a protocol that has been developed for enabling RMI applications to interoperate with
CORBAcomponents. Although RMIhadinherentadvantages provided bythe distributed object modelofthe Java
platform, it also had some limitations:
 RMI is limited only to the Java platform. It does not provide language independence in its distributed
model as targeted by CORBA.
 RMI-based application architectures are tightly coupled because of the connection-oriented nature.
Hence, achieving high scalability in such an application model becomes a challenge.
 RMIdoesnotprovideanyspecificsessionmanagementsupport.Inatypicalclient/serverimplementation,
the server has to maintain the session and state information of the multiple clients who accessit.
Maintaining such information within the server application without a standard support is a complex task.
EJB
EJBisanacronymforenterprisejavabean.ItisaspecificationprovidedbySunMicrosystemstodevelopsecured,
robust and scalable distributed applications.
When use Enterprise Java Bean?
 Application needs Remote Access. In other words, it is distributed.
 Applicationneedstobescalable.EJBapplicationssupportsloadbalancing,clustering andfail-over.
 Application needs encapsulated business logic. EJB application is separatedfrom presentation and
persistent layer.
Types of Enterprise Java Beans
There are 3 types of enterprise bean in java.
 Session Bean: Session bean contains business logic that can be invoked by local, remote orwebservice
client.
 MessageDrivenBean:LikeSessionBean,itcontainsthebusinesslogicbutitisinvokedbypassing
message.
 EntityBean:Itencapsulatesthestatethatcanbepersistedinthedatabase.Itisdeprecated.Now,itis
replaced with JPA (Java Persistent API).
Difference between RMI and EJB
Both RMI and EJB, provides services to access an object running in another JVM (known as remote object) from
another JVM. The differences between RMI and EJB are given below:
8 | P a ge
WebServices
Common Challenges in Distributed Computing
Distributed computing technologies like CORBA, RMI, and EJB have been quite successful in integrating
applicationswithinahomogenousenvironmentinsidealocalareanetwork.AstheInternetbecomesalogical
solutionthatspansandconnectstheboundariesofbusinesses,italsodemandstheinteroperabilityofapplications
across networks. This section discusses some of the common challenges noticed in the CORBA, RMI and EJB based
distributed computing solutions:
 Maintenance of various versions of stubs/skeletons in the client and server environments is extremely
complex in a heterogeneous network environment.
 Quality of Service (QoS) goals like Scalability, Performance, and Availability in a distributed environment
consume a major portion of the application’s development time.
 Interoperabilityof applications implementing different protocols onheterogeneous platformsalmost
becomes impossible.
 Most of these protocols are designed to work well within local networks. They are not very firewall
friendly or able to be accessed over the Internet.
Thebiggest problem with application integration withthistightly coupled approachspearheaded by CORBA, RMI,
andEJBwasthatitinfluencedseparatesectionsofthedevelopercommunitywhowerealreadytiedtospecific
platforms. Microsoft Windows platform developers used DCOM, while UNIX developers used CORBA or RMI.
There was no big effort in the community to come up with common standards that focused on the interoperability
between these diverse protocols, thus ignoring the importance, and hence, the real power of distributed
computing.
As the distributed technologies are having some challenges to achieve interoperability everybody is looking for a
technology which provides interoperability. If everybody defines their own standards then we can’t achieve
interoperability.Toachieveinteroperabilityallofusshouldfollowsamestandardsthat’swhereWS-I(Webservices
Interoperability) non-profitable organization got started.
This WS-I is governed by a Board of Directors consisting of the founding members (IBM, Microsoft, BEA Systems,
SAP, Oracle, Fujitsu, Hewlett-Packard, and Intel) and two elected members (currently, Sun Microsystems and
webMethods). Since joining OASIS, other organizations have joined the WS-I technical committee including CA
Technologies, JumpSoft and Booz Allen Hamilton.
The organization's deliverables include profiles, sample applications that demonstrate the profiles' use, and test
tools to help determine profile conformance.
9 | P a ge
WebServices
According to WS-I, a profile is :- A set of named web services specifications at specific revision levels, together
with a set of implementation and interoperability guidelines recommending how the specifications may be used
to develop interoperable web services.
WS-I Org Given 4 Versions of Web Services specifications. They are
1) BasicProfile1.0(B.P1.0)
2) BasicProfile1.1(B.P1.1)
3) BasicProfile1.2(B.P1.2)
4) BasicProfile2.0(B.P2.0)
 B.P 1.0  Version 1.0 of this profile was released in early 2004.
 B.P1.1Version1.1publishedin2006doesnothavethesamescopeasversion1.0.Thepartofversion
1.0dealing withserializationofenvelopes andtheirrepresentation inmessageshasbeenmovedtoanew
profile called Simple Soap Binding Profile (SSBP)
 B.P1.2 Version 1.2 wasfinalized in November 2010. The main new features arethe support for MTOM
binary attachments andWS-Addressing
 B.P2.0Version2.0wasalsopublishedinNovember2010.ItusesSOAP1.2,UDDI3andWS-Addressing
As Every player in the market started providing support for Basic Profile Specifications given by WS-I, Sun also
addeditssupportforBasicProfilespecificationsandadoptedthosespecificationsbyprovidingbelowAPIs.
Java applications don’t know what is SOAP protocol and how to putxml into SOAP xml. Java must provide one api
to work with SOAP. That’s where SUN provided SAAJ (soap with attachments apifor java).
Javaapplications don’tknowhowtogenerateorreadWSDL. JavamustprovideoneapitoworkwithSOAP.That’s
where SUN provided WSDL4J api.
Java applications must connect with UDDI registry to publish/discover WSDL documents. That’s where JAX-R (Java
API for XML Registries) api provided by sun to work with UDDI registries.
Keeping all these APIs together, sun provided JAX-RPC AND JAX-WS APIS.
10 | P a
ge
Web Services
Web Services Architecture
Webservices arebasedon theconceptof service-orientedarchitecture(SOA). SOAisthelatestevolution of
distributed computing, which enables software components, including application functions, objects, and
processes from different systems, to be exposed as services.
AccordingtoGartnerresearch(June15,2001),“Webservicesarelooselycoupledsoftwarecomponentsdelivered
over Internet standardtechnologies.”
In short, Web services are self-describing and modular business applications that expose the business logic as
services over the Internet through programmable interfaces and using Internet protocols for the purpose of
providing ways to find, subscribe, and invoke those services.
Based on XML standards, Web services can be developed as loosely coupled application components using any
programminglanguage,anyprotocol,oranyplatform.Thisfacilitatesdeliveringbusinessapplicationsasaservice
accessible to anyone, anytime, at any location, and using any platform.
Basic Operational Model of Web Services
TheWeb Services architectureis baseduponthe interactions between threeroles: service provider, service
registryandservicerequestor.Theinteractionsinvolvethepublish,findandbindoperations.Together,these
roles and operations act upon the Web Services artifacts: the Web service software module and its description. In
a typical scenario, a service provider hosts a network-accessible software module (an implementation of a Web
service).TheserviceproviderdefinesaservicedescriptionfortheWebserviceandpublishesittoaservice
requestor or service registry. The service requestor uses a find operation to retrieve the service description locally
or from the service registry and uses the service description to bind with the service provider and invoke or
interact with the Web service implementation. Service provider and service requestor roles are logical constructs
and a service can exhibit characteristics of both. Below image illustrates these operations, the components
providing them and their interactions.
These roles and relationships are defined as follows:
Service Provider: From a business perspective, this is the business that requires Service requestor. certain
functions to be satisfied. From an architectural perspective, this is the application that is looking for and invoking
or initiating an interaction with a service. The service requestor role can be played by a browser driven by a person
or a program without a user interface, for example another Web service.
Service Requestor: From a business perspective, this is the business that requires Service requestor. certain
functions to be satisfied. From an architectural perspective, this is the application that is looking for and invoking
or initiating an interaction with a service. The service requestor role can be played by a browser driven by a person
or a program without a user interface, for example another Web service.
Service Registry: Service registry. This is a searchable registry of service descriptions where service providers
publish their service descriptions. Service requestors find services and obtain binding information (in the service
descriptions) for services during development for static binding or during execution for dynamic binding. For
statically bound service requestors, the service registry is an optional role in the architecture, because a service
provider can send the description directly to service requestors. Likewise, service requestors can obtain a service
description from other sources besides a service registry, such as a local file, FTP site, Web site, Advertisement
and Discovery of Services (ADS) or Discovery of Web Services (DISCO).
11 | P a
ge
Web Services
Operations in a Web Service Architecture
ForanapplicationtotakeadvantageofWebServices,threebehaviorsmusttakeplace:publicationofservice
descriptions, lookup or finding of service descriptions, and binding or invoking of services based on the service
description. These behaviors can occur singly or iteratively. In detail, these operations are:
PublishTobeaccessible,aservicedescriptionneedstobepublishedsothatthePublish.servicerequestorcan
find it. Where it is published can vary depending upon the requirements of the application (see “Service
Publication” for moredetails).
FindInthefindoperation,theservicerequestorretrieves aservice description directlyFind.orqueriesthe
service registry for the type of service required (see “Service Discovery” for more details). The find operation can
be involved in two different lifecycle phases for the service requestor: at design time to retrieve the service’s
interface description for program development, and at runtime to retrieve the service’s binding and location
description for invocation.
BindEventually,aserviceneedstobeinvoked.InthebindoperationtheserviceBind.requestorinvokesor
initiates aninteractionwiththeservice atruntimeusingthebinding details inthe service descriptiontolocate,
contact and invoke the service.
Artifacts of a Web Service
Service  Where a Web service is an interface described by a service description, its Service. implementation is
theservice.Aserviceisasoftwaremoduledeployedonnetworkaccessibleplatformsprovidedbytheservice
provider. It exists to be invoked by or to interact with a service requestor. It can also function as a requestor, using
other Web Services in its implementation.
Service Description  The service description contains the details of the interface and Service Description.
implementation of the service. This includes its data types, operations, binding information and network location.
Itcould alsoinclude categorization andothermetadata tofacilitate discovery andutilization by service requestors.
The service description might be published to a service requestor or to a service registry.
Consider the simple example shown below where a travel reservation services provider exposes its business
applicationsasWebservicessupportingavarietyofcustomersandapplicationclients.Thesebusinessapplications
areprovidedbydifferenttravelorganizationsresidingatdifferentnetworksandgeographicallocations.
12 | P a
ge
Web Services
The following is a typical scenario:
1. The Travel service provider deploys its Web services by exposing the business applications obtained from
differenttravelbusinesseslikeairlines,car-rental,hotelaccommodation,creditcardpayment,andsoforth.
2. Theserviceproviderregistersitsbusinessserviceswithdescriptionsusingapublicorprivateregistry.The
registry stores the information about the services exposed by the service provider.
3. The customer discovers the Web services using a search engine or by locating it directly from the registry and
then invokes the Web services for performing travel reservations and other functions over the Internet using any
platform or device.
4. In the case of large-scale organizations, the business applications consume these Web services for providing
travel services to their own employees through the corporate intranet.
Thepreviousexampleprovidesasimplescenarioofhowanorganization’sbusinessfunctionalitiescanbeexposed
as Web services and invoked by its customers using a wide range of application clients.
Motivation and Characteristics
Web-basedB2Bcommunicationhasbeenaroundforquitesometime.TheseWeb-basedB2Bsolutionsareusually
based on custom and proprietary technologies and are meant for exchanging data and doing transactions over
the Web. However, B2B has its own challenges. For example, in B2B communication, connecting new or existing
applications and adding new business partners have always been a challenge. Due to this fact, in some cases the
scalability of the underlying business applications is affected. Ideally, the business applications and information
fromapartnerorganizationshouldbeabletointeractwiththeapplicationofthepotentialpartnersseamlessly
without redefining the system or its resources. To meet these challenges, it is clearly evident that there is a need
forstandardprotocolsanddataformattingforenablingseamlessandscalableB2Bapplicationsandservices.Web
services provide the solution to resolve these issues by adopting open standards. Figure 2.2 shows a typical B2B
infrastructure(e-marketplace)usingXMLforencodingdatabetweenapplicationsacrosstheInternet.
13 | P a
ge
Web Services
Web services enable businesses to communicate, collaborate, and conduct business transactions using a
lightweight infrastructure by adopting an XML-based data exchange format and industry standard delivery
protocols.
The basic characteristics of a Web services application model are as follows:
 WebservicesarebasedonXMLmessaging,whichmeansthatthedataexchangedbetweentheWeb
service provider and the user are defined in XML.
 Web services provide a cross-platform integration of business applications over the Internet.
 To build Web services, developers can use any common programming language, such as Java, C, C++, Perl,
Python, C#, and/or Visual Basic, and its existing application components.
 Web services are not meant for handling presentations like HTML context—it is developed to generate
XML for uniform accessibility through any software application, any platform, or device.
 BecauseWebservicesarebasedonlooselycoupledapplicationcomponents,eachcomponentisexposed
as a service with its unique functionality.
 Web services use industry-standard protocols like HTTP, and they can be easily accessible through
corporate firewalls.
 Web services can be used by many types of clients.
 Web services vary in functionality from a simple request to a complex business transaction involving
multiple resources.
 All platforms including J2EE, CORBA, and Microsoft .NET provide extensive support for creating and
deploying Web services.
 Web services are dynamically located and invoked from public and private registries based on industry
standards such as UDDI and ebXML.
Why to Use Web Services?
Traditionally, Web applications enable interaction between an end user and a Web site, while Web services are
service-oriented and enable application- to-application communication over the Internet and easy accessibility to
heterogeneousapplicationsanddevices.ThefollowingarethemajortechnicalreasonsforchoosingWebservices
over Web applications:
 Web services can be invoked through XML-based RPC mechanisms across firewalls.
 Web services provide a cross-platform,cross-language solution basedonXML messaging.
14 | P a
ge
Web Services
 Webservices facilitate easeof application integration using a light- weight infrastructure without affecting
scalability.
 Web services enable interoperability among heterogeneous applications.
Core Web Services Standards
The five core Web services standards and technologies for building and enabling Web services are XML, SOAP,
WSDL and UDDI. An overview of each is presented in the following sections.
Extensible Markup Language (XML)
In February 1998, the Worldwide Web Consortium (W3C) officially endorsed the Extensible Markup Language
(XML) as a standard data for- mat. XML uses Unicode, and it is structured self-describing neutral data that can be
storedasasimpletextdocumentforrepresentingcomplexdataandtomakeitreadable.Today,XMListhede
facto standard for structuring data, content, and data format for electronic documents. It has already been widely
accepted asthe universal language lingua franca for exchanging information between applications, systems, and
devicesacrosstheInternet.InthecoreoftheWebservicesmodel,XMLplaysavitalroleasthecom-monwire
format in all forms of communication. XML also is the basis for other Web services standards. By learning XML,
youwillbewellpreparedtounderstandandexploreWebservices.FormoreinformationonXML,gotoChapter
8, “XML Processing and Data Binding with Java APIs,” or to the official W3C Web site for XML at
www.w3c.org/XML/.
Simple Object Access Protocol (SOAP)
SimpleObjectAccessProtocol,orSOAP,isastandardforalightweightXML-basedmessagingprotocol.Itenables
anexchangeofinformationbetweentwoormorepeersandenablesthemtocommunicatewitheachotherina
decentralized, distributed application environment. Like XML, SOAP also is independent of the application object
model, language, and running platforms or devices. SOAP is endorsed by W3C and key industry vendors like Sun
Microsystems, IBM, HP, SAP, Oracle, and Microsoft. These vendors have already announced their support by
participatingintheW3CXMLprotocol-workinggroup.TheebXMLinitiativefromUN/CEFACTalsohasannounced
its support forSOAP.
SOAP consists of three parts: an envelope that defines a framework for describing what is in a message, a set of
encodingrulesforexpressinginstancesof application-defineddatatypes,andaconventionforrepresenting
remoteprocedurecalls(RPCs)andresponses.SOAPcanbeusedincombinationwithorre-envelopedbyavariety
of network protocols such as HTTP, SMTP, FTP, RMI over IIOP or MQ.
15 | P a ge
WebServices
As per above diagram
 At (1) a service requestor’s application creates a SOAP message. This SOAP message is the request that
invokestheWebserviceoperationprovidedbytheserviceprovider.TheXMLdocumentinthebodyof
the message can be a SOAP RPC request or a document-centric message as indicated in the service
description.Theservicerequestorpresents thismessage togetherwiththenetworkaddressoftheservice
provider to the SOAP infrastructure (for example, a SOAP client runtime). The SOAP client runtime
interacts withanunderlying network protocol (for example HTTP) to send the SOAP message outover the
network.
 At (2) the network infrastructure delivers the message to the service provider’s SOAP runtime (for
example a SOAP server). The SOAP server routes the request message to the service provider's Web
service. The SOAP runtime is responsible for converting the XML message into programming language-
specificobjects ifrequired bytheapplication.Thisconversion isgoverned bytheencoding schemes found
within the message.
 TheWebservice is responsible for processing the requestmessage andformulating aresponse.The
response isalso a SOAPmessage. At(3)the response SOAPmessage ispresented tothe SOAP runtime
with the service requestor as the destination. In the case of synchronous request/response over HTTP,
the underlying request/response nature of the networking protocol is used to implement the
request/response natureofthemessaging.The SOAPruntime sendstheSOAPmessageresponsetothe
service requestor over the network.
 At (4) the response message is received by the networking infrastructure on the service requestor’s node.
The message is routed through the SOAP infrastructure; potentially converting the XML message into
objects in a target programming language. The response message is then presented to the application.
Web Services Definition Language (WSDL)
The Web Services Description Language (WSDL) is an XML-based interface definition language that is used for
describing the functionality offered by a web service. The acronym is also used for any specific WSDL description
of a web service (also referred to as aWSDLfile), which provides a machine-readable description of howthe
servicecanbecalled,whatparametersitexpects,andwhatdatastructuresitreturns.Therefore,itspurposeis
roughly similar to that of a type signature in a programming language.
The current version of WSDL is WSDL 2.0. The meaning of the acronym has changed from version 1.1 where the
"D" stood for"Definition".
16 | P a ge
Web Services
Types  a container for data type definitions using some type system (such as XSD).
Message  an abstract, typed definition of the data being communicated.
Operation  an abstract description of an action supported by the service.
Port Type  an abstract set of operations supported by one or more endpoints.
Bindingaconcreteprotocolanddataformatspecificationforaparticularporttype.
Port  a single endpoint defined as a combination of a binding and a network address.
Service  a collection of relatedendpoints.
Universal Description, Discovery, and Integration (UDDI)
Universal Description, Discovery, and Integration, or UDDI, defines the standard interfaces and mechanisms for
registries intended for publishing and storing descriptions of network services in terms of XML messages. It is like
theyellowpagesoratelephone directory where businesses listtheir products andservices. Webservices brokers
use UDDI as a standard for registering the Web service providers. By communicating with the UDDI registries, the
service requestors locate services and then invoke them.
UDDI was included in the Web Services Interoperability (WS-I) standard as a central pillar of web services
infrastructure,andtheUDDIspecificationssupportedapubliclyaccessible Universal Business Registry inwhich a
naming system was built around the UDDI-driven service broker.
UDDI has not been as widely adopted as its designers had hoped. IBM, Microsoft, and SAP announced they were
closing their public UDDI nodes in January 2006. The group defining UDDI, the OASIS Universal Description,
Discovery, and Integration (UDDI) Specification Technical Committee voted to complete its work in late 2007 and
has been closed. In September 2010, Microsoft announced they were removing UDDI services from future
versions of the Windows Server operating system. Instead, this capability would be moved to BizTalk Server.In
2013, Microsoft further announced the deprecation of UDDI Services in BizTalk Server.
A UDDI business registration consists of three components:
 White Pages — address, contact, and known identifiers;
 Yellow Pages — industrial categorizations based on standard taxonomies;
 Green Pages — technical information about services exposed by the business.
17 | P a ge
Web Services
XML
18 | P a ge
Web Services
Introduction
 XMl stands for extensible markup language
 Unlike C, C++ and Java etc. Xml is not a programming language. It is a markup language
 XMl was designed for transport and store data
 XML was defined and governed by W3C Org
 The first and final version of XML is XML 1.0
XML is not a database: You’re not going to replace an Oracle or MySQL server with XML. A database can
containXMLdata.Eitheras a VARCHARoraBLOBorassomecustomXML datatype,butthedatabase
It self is not an XML document. You can store XML data in database on a server or retrieve data from a
database in XML format.
What is mean by Extensible: Extensible means that the language can be extended and adapted to meet many
different needs. i.e XML allows developers and writers to invent the elements they need as they need them.
There issomeothermarkup language alsothere inthemarketthatis HTML
HTML was designed to display data, with focus on how data looks.
Differences between HTML and XML
XML HTML
1) Extensible markup language 1) Hypertext markup language
2) It is usedfortransport andstorethedata 2) It is used to display data
3) All the Elements are user-defined 3)AlltheelementsinHTMLarepredefined
4) It has infinite set of tags 4) It has finite set of tags
5) XML documents are re-usable 5)HTMLdoesnotsupportforre-usability
6) Every start tag must have end tag 6) Every start tag need not have end tag
7)XMLisDYNAMIC(i.e.Contentischanged
every time page is loaded)
7) HTML is static( i.e. Content does not
changedeverytimepageisloaded)
8)XMLattribute value mustbeenclosed
with quote(")
8) HTML attribute value can be present
without quotationmark
9) It is case-sensitive 9) It is not case sensitive
Everylanguagehaskeywords,IfyoutakeexampleasC,ithaskeywordslike(if, for,while,do,break,continue
etc.)but whenitcomestoXMLthereare no keywords orreservedwords.Whateveryouwritewillbecomethe
element of that XML document.
XML Declaration
Every XML document must start with PROLOG: - prolog stands for processing instruction, and typically used
for understanding abouttheversion of XML used andthe data encoding used.
Example: -<? xml version=”1.0” encoding=”UTF-8” standalone=”yes”?>
<?Xml:XMLparserusesthefirstfivecharacters(<?xml)tomakesomereasonableguessabouttheencoding
such as whether the document uses single-byte or multi-byte character set.
Version:Theattributeshouldhaveallthevalue1.0.Underveryunusualcircumstances,itmayalsohavethe
value 1.1. Since specifying version=”1.1” limits the document to the most recent versions of only a couple of
19 | P a ge
WebServices parsers,
and since all Xml 1.1 parsers must also support XML 1.0, you don’t want to casually set the version 1.1.
Encoding:XMLdocumentsareassumedtobeencodedintheUTF-8variablelengthencodingoftheUnicode
character set. This is strict superset of ASCII, so pure ASCII text files are also UTF-8 documents.
Standalone: Standalone attribute accepts only 2 values i.e. 1) no 2) yes
If standalone=”no”: - Application may be required to read an external DTD
If standalone=” yes” :- Application need to read internal DTD
XMlElement:Thedatabetweenangularbrackets(i.e.“<>”)iscalledElement
Ex: employee
Tag: The element with includes angle brackets is called Tag.
Ex: <employee>
In XML there are two types of elements as follows
StartElement/OpeningTag:-Startelementistheelementwhichiswritten in<elementname> indicating
the start of a block.
End Element/End Tag: - End element is the element which is written in </elementname> indicating the end of
a block.
An Element can contain:
1. Other elements (childelements)
2. Text-data
3. Attributes
4. Mix of all
XML elements naming rules
 Elements names arecase-sensitive
 Element name must start with letter or underscore
 Element name cannot start with letter xml (Or XML, or Xml etc.)
 Element name cannot containspaces
 Any name can be used, no word are reserved except XML.
XML Attribute
If we wantto have additional informationattachtoan element, instead of having it as content or another
element, we can write it as an Attribute of the element.
Example:
<employee type= ”permanent”>
<id> 1001 </id>
</employee>
Intheaboveexample“employee”isanelementwhichcontainsoneattributestype whichactsasa
supplementaryinformation, <id>is thesub-elementof the<employee> element.
Note: Attributes must be enclosed with single quote or double quotes
<employeeid=”101”name=”Ashok”/>(Valid)
<employeeid=”101”name=Ashok/>(In-valid)
20 | P a ge
Web Services
XML Comments
XMLcommentsaresyntacticallysimilartoHTMLcomments
Syntax: <! - - This is the comment- - >
Predefined Entities
Some characters have meaning in XML
ForExample:If youplacea characterlike“<”insideXML element,itwillgenerate errorbecausetheparser
interprets it as the start of new element.
The following code will generate an XML error
<salary> if salary <15000 then </salary>
To avoid above error replace “<” character with entity reference
<salary>ifsalary&lt;15000then</salary>
Lessthan(<) : &lt;
Greater than (>) : &gt;
Ampersand (&) : &amp;
Apostrophe (‘) : &apos;
Quotation (“) : &quot;
XML Well-formness
Ashowanyprograminglanguagehassyntaxinwritingitscode,Well-formnessof XMLdocumenttalksabout
howtowriteanXMLdocument.Well-formnessindicates thereadabilitynatureofanXMLdocument.In
other way if anXML document is said to be well-formed then it is readable in nature.
Following are the rules that describe the Well-formness of an XML Document.
* EveryXMLdocument muststart withPROLOG: -prolog standsforprocessing
* Every start tag must have end tag
* Elementsmaynestbutmaynotoverlap
* There must be exactly one root element
* Attribute value must bequoted
* An element cannot have two attributes with same name
Well-formed XML Not Well-formed XML
<employee>
<id>1208</id>
<name>Ashok</name>
</employee>
<employee type=permanent>
<id>1208</id>
<name>Ashok</name>
</employee>
Reason: It follows all the XML rules Reason: attribute values is not enclosed with "
21 | P a ge
Web Services
Not Well-formed XML Not Well-formed XML
<employee>
<id>1234</id>
<name>Ashok</name>
</employee>
<employee>
<id>2456</id>
<name>Ashok</name>
<employee>
<employee>
<id>1234
<name>Ashok<name>
</employee>
Reason: Only one root element is allowed Reason: Tags are not ended properly
For checking whether the XML document is well-formed or not some of the editors are there. They are
1) XMLcopyeditor 8) WMHelp XMLpad
2) EditXMLEditor 9) XMLLmind XMLEditor
3) AltovaXMSpy 10) Notepad++
4) Oxygen XML Editor
5) XML Writer XMLEditor
6) Stylus Studio
7) Liquid XML Studio
XML Validation
EveryXMLin-ordertoparse(read)shouldbewell-formedinnature.Assaid earlierwell-formnessofanXML
documentindicates whether it is readable or not, it doesn’t talk about whether the data contained in it is
valid ornot.
ValidityoftheXMLdocumentwouldbedefinedbytheapplicationwhichisgoing toprocessyourXML
document. Let’s considera scenario as follows.
22 | P a ge
Web Services
Intheabovepurchase-order.xmleventhoughitconfirmstoallthewell-formness rules,itcannot beusedfor
businesstransaction,asthe<quantity>elementcarriesthedata as“xyz”whichdoesn’tmakesanysense.
So,in orderto check fordata validity, we need to define thevalidationcriteria of anXML documentineither
a DTD or XSD document.
23 | P a ge
Web Services
DTD
24 | P a ge
Web Services
Introduction
 DTD stands for Document Type Definition.
 Itisthedocumentwhichdefinesthe structure and the legal elements and attributes of an XML
document
 An application can use a DTD to verify that XML data is valid
 Inalanguagebeforeusingavariableweneedtodeclareit.Similarly,beforeusing anelementinXML
first we need to declare it in DTD.
 DTDfileswillbesavedwith.dtdextension
Before start writing DTD, first we need to know two kinds of elements. They are
1) Simple Elements
2) Compound Elements
Let us take a sample po.xml file to demonstrate these elements
SimpleElements: Elementswhichcarrydata arecalledsimpleelements. Simple element cancontain only value
(data). It may not contain any child.
In the above XML file, simple Type elements are: itemCode, quantity, addrLine1, addrLine2, city, state, zip and
county.
25 | P a ge
WebServices
Compound Elements: An element which contains sub-elements under it is called compoundelement.
For above xml, DTD looks like shown below
Occurrences of an Element under another element
Intheabovexmlifweobservethe<items>element,itcancontainanynumber of<orderItems>elementsin
it, butat least one item elementmust betherefor a <purchaseOrder>.Thisiscalledoccurrenceofan
element underanother element, to indicate this we usethree symbols.
? – Represents the sub element under a parent element can appear zero or one- time (0/1).
+ - indicates the sub element must appear at least once and can repeat any number of times (1 – N)
* -indicatesthesubelementisoptionalandcanrepeatanynumberoftimes (0-N)
Youwillmark theoccurrenceof anelementunderanotherelementasfollows.
<! Elementelementname(sub-elem1(? /+/*),sub-elem2 (? /+/*)>
Leaving any element without any symbol indicates it is mandatory and at max can repeat only once.
Elements with any contents
Elements declared with the content type as ANY, can contain any combination of parsable data.
<! ELEMENT elementname ANY>
<! ELEMENT mailBody ANY>
In an e-mail body part we have content which can be mixture of any parsable characters which can be declared
as ANY type.
26 | P a ge
<mail>
<to>toaddr.com</to>
<from>fromaddr.com<from>
<subject>mysub</subject>
</mail>
<(OmRa)il>
<to>toaddr.com</to>
<from>fromaddr.com<from>
<mailBody>mysub</mailBody>
</mail>
WebServices
Elements with either/or content
Let’s consider an example where in an email the following elements will be there to, from, subject and
mailBody.IntheseelementstoandfromormandatoryelementsandeithersubjectormailBodyshouldbe
present but not both. To declare the same we need to use or content separator instead of sequence separator.
<! ELEMENT mail (to, from, (subject | mailBody)>
Fortheabovedeclarationthexmllooksasbelow.
Declaring Mixed content
We can even declare an element with mixture of parable data and elements called mixed content as follows.
<! ELEMENTmail (#PCDATA|to|from| subject|mailBody)*>
Declaring attribute for an element
Attributes provide extra information about elements
Syntax: - <! ATTLIST elementNameattributeName attributeType attributeValue>
AsshownabovetodeclareanattributeyouneedtousethetagATTLISTand elementnamestandsforwhich
element you want to declare the attribute and attributeName stands for what is the attribute you want to
have in that element.
The attributeType can be the following:
Type Description
CDATA The value is Character data
(en1|en2|..) Thevaluemustbeonefromthe enumerated
list of values.
ID The value is unique id.
IDREF The value is the id of another element
NMTOKEN The value is a valid XML element name
27 | P a ge
WebServices
The attributeValue can be the following:
Value Description
#REQUIRED The attribute is required
#IMPLIED The attribute is not required
#FIXED value The attribute value is fixed.
Default Attribute Value
<! ELEMENTshippingAddress (addressLine1, addressLine2, city, state, zip, country)>
<! ATTLISTshippingAddress type CDATA “permanent” >
#REQUIRED
<!ATTLISTshippingAddresstypeCDATA#REQUIRED>thisindicatestype attributeismandatoryin
shippingaddress element.
#IMPLIED
<! ATTLISTshippingAddresstypeCDATA#IMPLIED>,thisindicatesthetype attributein
shippingAddress elementisoptional.
#FIXED
<! ATTLISTshippingAddress typeCDATA #FIXED“permanent”>,thisindicatesthe type attribute in
shippingAddress elementmustcontainonlythe value as permanent.
Enumerated Attribute Values
ThisindicatesthetypeattributeinshippingAddresselementshouldcontainonly twopossiblevalueseither
permanent ortemporary.
DTDs are divided into 2 types
1. Internal DTD
2. External DTD
Internal DTD
If the DTD is declared inside the XML file, it should be wrapped in a DOCTYPE definition with the
following syntax:
28 | P a ge
WebServices
Below is the sample XML with Internal DTD
External DTD
ExternalDTDaresharedbetweenmultipleXMLdocuments.AnychangesareupdateinDTDdocument
effect or updated come to all XML documents.
External DTD two type:
a. Private DTD
b. Public DTD
Private DTD Private DTD identify by the SYSTEM keyword. Access for single or group of users.
YoucanspecifyrulesinexternalDTDfile.dtdextension.LaterinXMLfile<!DOCTYPE...>declarationto
linking this DTDfile.
PublicDTDPublicDTDidentifybythePUBLICkeyword.AccessanyusersandourXMLeditorareknowthe
DTD.
29 | P a ge
WebServices
Below XML is linked with Public DTD
Once DTD is linked with XML then we can validate our XML against DTD (see in below image)
30 | P a ge
Web Services
Drawbacks with DTD
It doesnot support the namespaces. Namespace is a mechanism by which element and attribute names
canbeassignedtogroups.However,inaDTDnamespaceshouldbedefinedwithintheDTD,which
violates the purpose of using namespaces.
It supports only the text string data type.
It is not object oriented. Hence, the concept of inheritance cannot be applied on the DTDs.
Limited possibilities to express the cardinality for elements.
To overcome the above drawbacks of DTD we will use XSD to define structure of the XML.
31 | P a ge
Web Services
XSD
32 | P a ge
Web Services
Introduction
XML Schema is an XML-based alternative to DTDs. An XML Schema describes the structure of an XML document. The
XMLSchema languageisalso referredtoas XML SchemaDefinition (XSD).ThepurposeofanXMLSchemaistodefine the
legal building blocks of an XML document, just like a DTD.
 XSD stands for XML Schema Definition
 XSD owned by world wide web consortium (W3Org)
 In 2001,theW3Cdevelopeda newschema languageto addressmanyof theshortcomingsof DTD
 XSD schema is used to define the structure of an XML document
 The main goal of XSD is to validate the XML document whether it is valid or not
 XSD is also an xml (It is special XML with fixed structure and fixed elements)
 XSD is more powerful and type strict in nature
 Schemas are another approach used by the XML parser to validate an XML document
 It is text file with .xsd extension
An XML Schema defines
Elements that can appear in a document
Defines attributes that can appear in a document
Defines which elements are child elements
Defines the order of child elements
Defines the number of child elements
Defines whether an element is empty or can
Defines data types for elements and attributes
Defines default and fixed values for elements and attributes
XML Schemas are richer and powerful than DTD because:
1. XML Schemas are extensible to future additions
2. XML Schemas themselves are written in XML
3. XML Schemas support data types
4. XML Schemas support namespaces
XML Schemas are Extensible
XML Schemas are extensible, because they are written in XML. With an Extensible Schema definition we can:
1. Reuse one Schema in other Schemas
2. Create our own data types derived from the standard types
3. Reference multiple schemas in the same document
Data types
OneofthegreateststrengthofXMLSchemasisthesupportfordatatypes.Byusingdatatypes,itis easierto:
1. Describe allowable document content
2. Validate the correctness of data
3. Work with data from a database
4. Define data facets (restrictions on data)
5. Define data patterns (data formats)
WebServices
As XSDis also an xml,it will start with aprologandit also contains only oneroot element. The<schema>
element is the root element of every XML Schema.
The <schema> element contains following attributes:
Attribute name Description Example
xmlns:xs Elements and Data types from
“http://www.w3.org/2001/XMLSchema"
namespace.
xmlns:xs=”
http://www.w3.org/2001/XMLSchema”
targetNamespace User defined elements and data types in our
schemabelongstoournamespacesuch as
“www.ashoksit.com”
targetNamespace=”www.ashoksoft.com”>
Xmlns Indicates default name space. Xmlns=”www.ashoksoft.com”
elementFromDefault Elements must be namespace qualified. elementFromDefault=”qualified”
The above attributes we discuss in detail in XSD namespaces concept.
As we have already discussed in DTD, an XML contains 2 types of elements. They are
1) Simple Elements
2) Compound Elements
InJava,wehavetostoresomevalueintoavariable,firstweneedtodeclarethevariablesimilarlyifwewantto
write one element in XML first we should declare that element in DTD or XSD.
Declaring Simple Elements in XSD
Name – name attributes holds element name
Type - type attribute holds element data type
Declaring Compound Elements in XSD
Ifwewanttosomevalueintoavariablefirstwemustdeclareavariablewithdatatype(Basedonnatureofthe
data we want to store into that variable we will decide data type for that variable).
IfwewanttostoreapersonnameintovariablethenwewillchooseStringdatatypelikebelow
String personName;
Ifwewanttostorepersonagethenwewilldeclareavariablewithintdatatypelikebelow
Int personage;
Similarly, I want to store student details like rollNumber, name and rank in a variable called ‘s’. Do we have any
predefined datatype in Java to store student values (rollNumber, name and rank) like this? – We don’t have any
such datatype injava.
Aswedon’thaveanypredefineddatatype,wemustcreateourowndatatypefor‘s’variabletostorestudent
values.WecanconsiderClassasauser-defineddatatypesowewillcreateaStudentclasstostorestudentdetails
and we can use that Student class as a data type for variable ‘s’ like below
33 |P a ge
Web Services
34 | P a ge
IfwewanttowriteoneelementinXMLfirstweshoulddeclareinXSD.Iwanttowriteoneelement<order-item>
in xml likebelow
Note: As we can see <order-item> contains child elements this is called Compound element.
To write <order-item> element in XML first we should declare this element in XSD with data type.
What datatype we can use for <order-item> element? – It’s based on nature of the data we want to store.
In<order-item>Iwanttostore<item-code>and<quantity>elements.DowehaveanydatatypeinXSDtostore
<item-code> and <quantity> elements? – No.
AsdiscussedabovetostoreStudentdatawehavedon’thavepredefineddatatypehencewehavecreated
Studentclassasuser-defineddatatype. Similarly,aswedon’thaveanypredefined datatypefor<order-item>we
havetocreateuser-defineddatatypeinXSD.TocreateUser-defineddatatypesinXSDwewilluseComplexType.
AcomplextypeelementisanXMLelementthatcontainsotherelementsand/orattributes.Injava
wewill useClassto create user-defined datatypeandin XSDwewill useComplexTypetocreateuser-
defined data type.
Declaring <order-item> as compound element in XSD
Web Services
35 | P a ge
Note: <xs:sequence /> represents child elements should be in same order
Now we understood how to declare Simple Elements and Compound elements in XSD so let'stake our
PO.xml and writePO.xsd
PO.xml
From the above XML identity Compound Elements and Simple Elements and declare them in XSD
PurchaseOrder, order-items, item and shipping-address are compound elements. To declare these compound
elementswe needComplexTypes (Foreachcompoundelementwe needone complextype).
Item-code, quantity, addrLine1, addrLine2, city, state, country and zipcode are Simple Elements
As XSD is also an XML it will start with Prolog
XSD contains only one root element that is <xs:schema />
Inside <xs:schema /> we can declare both Simple elements and compound elements
Web Services
36 | P a ge
Below is the PO.xsd which represents structure of PO.xml
In the approach, first we have taken XML and we have created XSD.
XSDRepresentsStructureoftheXML
XML  Holds the data
As XSDrepresents the structure ofthe XML,firstweshould create XSDandthen we need to create the XML to
storethedataintheformofelements.OncedataisstoreinXML,wecanvalidateourXMLagainstXSD.
To Validate XML against XSD, we should link XSD with our XML like below
Xmlns:xsi :- It represents XMLSchema-instance Namespace
Xsi:noNamespaceSchemaLocation :- Represents XSD file name (No namespaces in XSD)
Note : If we have namespaces in XSD then we should use xsi:schemaLocation attribute to link XSD to xml.
37 | P a ge
WebServices
Linking PO.xsd to PO.xml
OnceXSDislinkedtoXML,wecanvalidateourxmlagainstXSDusingAltovaXMLSpytool(usingF8shortcutkey).
Element Cardinality
Itispossibletoconstrainthenumberofinstances(cardinality)ofanXMLelementthatappearinanXML
document.Thecardinality isspecifiedusingtheminOccurs andmaxOccursattributes,andallowsanelementto
be specified as mandatory, optional, or can appear upto a set number of times. The default values for minOccurs
andmaxOccursis1.Therefore,ifboththeminOccurs andmaxOccursattributesareabsent,asinallthe previous
examples, the element must appear once and once only.
minOccurscanbeassignedanynon-negativeintegervalue(e.g.0,1,2,3...etc.),andmaxOccurscanbeassigned
any non-negative integer value or the special string constant "unbounded" meaning there is no maximum so the
element can occur an unlimited number of times.
38 | P a ge
WebServices
Defining Compositors
Compositors provide rules that determine how and in what order their children can appear within XML
document. There are three types of compositors. They are
1. <xs: sequence>
2. <xs: choice>
3. <xs: all>
<xs: sequence /> element
The <sequence> indicator specifies that the child elements must appear in a specific order:
<xs: all />element
The <all> indicator specifies that the child elements can appear in any order, andthateach child element must
occur onlyonce:
39 | P a ge
WebServices
<xs: choice /> element
XMLSchema<choice>element allowsonlyoneofthe elementscontainedin the<choice>declarationto be
present within the containing element.
As per above XSD, ShippingAddress can contain either office-address or home-address but not both
Global elements with ref attribute in XSD
If we declare an element inside ComplexType then it is called as local element
Ifwedeclareanelementinside<xs:schema>directlythenthatiscalledasglobalelement.
If Multiple ComplexTypes want to use same name for the element with same data type then we can
use Global Elements with ref attribute
40 | P a ge
Web Services
Let’s take BookStore.xml to demonstrate this
BookStore.xsd for above BookStore.xml
IfweseeintheaboveBookStore.xsd,“name”elementisdeclaredin2complextypes(Duplicateelement
declarationsarepresented).Toavoidduplicateelementdeclarations, wecanuseGlobalElementfor“name”
element likebelow
41 | P a ge
Web Services
<xsd:group> Element
If we want to re-use group of elements in several complextypesthen we canuse <xsd: group> element
Lets’ take Bank-Account.xml to demonstrate this
Inthebank-account.xml, both<savings-account/>and<current-account/>havingbelowthree
elements ascommon
42 | P a ge
Web Services
 <acc-id />
 <holder-name />
 <branch-name />
Insteadofwritingthese3elementsasglobalelements,wecancreatethemasagroupinxsdlikebelow
Now we can reference to this “AccDetailGroup” in multiple complextypes to use acc-id , holder-name
and branch-nameelements.
The modified bank-account.xsd is below (With Group element)
43 | P a ge
Web Services
Inheritance in XSD
Complextype extensionsarequite similartotheinheritanceinJavaandotherobject-orientedlanguages. New
complex types can be derived by extending existing complex types.
Now let’s take an travel-agency.xml to demonstrate this
Intheabovexml,both<DomesticFlight/>and<InternationalFlight />complextypesaresome commonelements.
So in XSD we can extend one complextype from another to re-use the elements
In below XSD <InternaltionFlight /> complextype is extending elements from <DomesticFlight /> complextype
44 | P a ge
Web Services
Attributes in XSD
An attribute provides extra information within an element. Attributes have name and type properties and are
defined within an XSD as follows:
An attribute is specified within a xs:complexType, the type information for the attribute comes from a
xs:simpleType (either defined inline or via a reference to a built inor user defined xs:simpleType definition). The
Type information describes the data the attribute can contain in the XML document, i.e. string, integer, date etc.
Attributes can also be specified globally and then referenced.
45 | P a ge
Web Services
 Mandatory Attribute: <attribute name= “empNo" type= “int“ use=“required”/>
 Default Attribute: <attribute name= “name” type= “string” default= “guest”/>
 Fixed Attribute: <attribute name= “salary” type= “decimal” fixed= “10000”/>
Note:Thedefaultand fixed attributescanbespecified within theXSDattributespecification (inthe sameway
as they are for elements).
Element with attributes
An empty complex element means no content rather only attributes.
In the example above, we define a complex type with a complex content. The complexContent element signals
thatweintendtorestrictorextendthecontentmodelofacomplextype,andtherestrictionofintegerdeclares
one attribute but does not introduce any element content.
Example:
<product id=”12345”/>
Element with attributes and text
Itcontainsonlytextandattributesi.e.,itcontainsonlysimplecontent(textandattributes),thereforeweadda
simpleContentelementaroundthecontent.WhenusingsimpleContent,wemustdefineanextensionor
restriction within the simpleContent element.
Note: Use the extension/restriction element to expand or to limit the base simple type for the element.
46 | P a ge
Web Services
Example:
<shoesize country="france">35</shoesize>
Element with sub elements and text
An XML element contains both text and sub elements.
Example:
<letter> </letter>
DearMr.<name>JohnSmith</name>.Yourorder<orderid>1032</orderid>.
Will be shipped on <shipdate>2001-07-13</shipdate>.
Sample XSD
AspertheaboveXSD,givenXMLisvalidornot?-Itisvalidonlybecausexsdsayszipcodeshouldcontain int
valueandxmlhavingintvalueonlybutpracticallyzipcodeshouldnotbesingledigitthenhowtovalidate
particularelementshouldcontainspecificNo.ofdigits?-That’swhereRestrictionscomesintopictureinXSD.
47 | P a ge
Web Services
Primitive types
The following table summarizes Primitive types in XML Schema Definition:
Primitive type Description Example
Decimal Specifies numeric value including fractional part. <prize>999.50</prize>
Float
Double
Boolean Specifies true or false value.
String Thestringdatatypecancontaincharacters,linefeeds,
carriage returns, and tab characters.
<customer>John Smit</customer>
Date The date format is always as: YYYY-MM-DD. <start>2012-01-21</start>
Time The time format is always as: hh:mm:ss <time>09:00:00</time>
dateTime The dateTime format is always as: YYYY-MM-
DDThh:mm:ss
<startdate>2012-01-
21T09:00:00</startdate>
gYearMonth Definesapartofadate-theyearandmonth(YYYY-
MM)
gYear Defines a part of a date - the year (YYYY)
gMonthDay Definesapartofadate-themonthandday(MM-DD)
gDay Defines a part of a date - the day (DD)
gMonth Defines a part of a date - the month (MM)
Duration Defines a time interval <period>P5Y2M10DT15H</period>
The example above indicates a
periodoffiveyears,twomonths,10
days, and 15 hours.
Base64Binary Base64-encoded binary data
hexBinary hexadecimal-encoded binary data
anyURI
QName
NOTATION
Derived Types: The following table summarized the derivedtypes
Derived type Description Example
integer Derived from decimal type without fractional part.
Long Derivedfromdecimal,whichissigned64-bitinteger.
Int Derivedfromdecimal,whichissigned32-bitinteger.
Short Derivedfromdecimal,whichissigned16-bitinteger.
Byte Derived from decimal, which is signed 8-bit integer.
nonPositiveInteger Anintegercontainingonlynon-positivevalues(..,-2,-
1,0)
negativeInteger An integer containing only negative values(…,-2,-1)
nonNegativeInteger Anintegercontainingonlynon-negativevalues (0,1,2,..)
UnsignedLong Derived from decimal, which is unsigned 64-bit integer.
UnsignedInt Derivedfromdecimal,whichisunsigned32-bitinteger.
UnsignedShort Derived from decimal, which is unsigned 16-bit integer.
UnsignedByte Derivedfromdecimal,whichisunsigned8-bitinteger.
PositiveInteger An integer containing only positive values(1,2…).
48 | P a ge
Web Services
normalizedString Derived from string type. Contains only characters
without line feeds, carriage returns, and tab characters.
<customer>John
Smith</customer>
Token Derivedfromstringtype.Containsonlycharacters
withoutlinefeeds,carriage returns,tabs, leading and
trailing spaces, and multiple spaces.
<customer>John
Smith</customer>
Language A string that contains a valid language id.
Name A string that contains a valid XML name.
NCName Name without colons but allows characters such as
hyphens.
bold_brash is valid. bold:brash
is invalid.
ID Only used with attributes.
IDREF
IDREFS
ENTITY
ENTITIES
NMTOKEN Derived fromstring,whichdoesnotacceptCommas,
Leadingortrailing whitespacewillberemoved. Used
with only attributes.
“x, y” is invalid.
“x y” is valid.
Built-in types with restrictions
The built-in types with restrictions are simple types.
Restrictionsareusedto defineacceptablevaluesfor XMLelementsorattributes.RestrictionsonXML elements are
called facets.
Restriction on values
Following example defines an element named “age” with a restriction. The value of the age element cannot be
lower than 21 and greater than 60.
Restriction on Set of values
To limit the content of an XML element to a set of acceptable values, we would use the enumeration
constraint.
49 | P a ge
Web Services
Restrictions on Series of Values
The ‘pattern’ constraint is used to limit the content of xml element to define a series of numbers or
letters.
Example#1:TheonlyacceptablevalueisTHREEoftheLOWERCASEorUPPERCASElettersfromatozorAtoZ.
Example #2: The acceptable value is zero or more occurrences of lowercase letters from a to z.
Example #3: The only acceptable value is male OR female.
Restrictions on Length
Tolimitthelength ofavalueinanelement,wewould usethelength, maxLength, andminLengthconstraints.
Example #1: This exampledefines an element called "password" with arestriction. The value must be exactly
eight characters:
50 | P a ge
WebServices
Example #2: This example defines another element called "password" with arestriction. The value must be
minimum five characters and maximum eight characters:
The following table summarizes attributes related to restrictions
CONSTRAINT DESCRIPTION
Enumeration Defines a list of acceptable values
Length Specifiestheexactnumberofcharactersorlistitemsallowed.Mustbeequaltoorgreaterthanzero
maxLength Specifies the maximum number of characters or list items allowed. Must be equal to or greaterthan
zero.
minLength Specifies the minimum number of characters or list items allowed. Must be equal to or greater than zero
maxExclusive Specifies the upper bounds for numeric values (the value must be less than this value)
maxInclusive Specifiestheupperboundsfornumericvalues(thevaluemustbelessthanorequaltothisvalue)
minExclusive Specifies the lower bounds for numeric values (the value must be greater than this value)
minInclusive Specifiesthelowerboundsfornumericvalues(thevaluemustbegreaterthanorequaltothisvalue)
Pattern Defines the exact sequence of characters that are acceptable
totalDigits Specifies the exact number of digits allowed. Must be greater than zero
fractionDigits Specifiesthemaximumnumberofdecimalplacesallowed.Mustbeequaltoorgreaterthanzero
<any>
The <any> element enables us to extend the XML document with elements not specified by our schema.
#family.xsd
51 | P a ge
WebServices
Nowwewanttoextendthe"person"elementwitha"children"element.Inthiscasewecandoso,evenifthe
author of the schema above never declared any "children" element.
#children.xsd
The XML file below (called "Myfamily.xml"), uses components from two different schemas; "family.xsd" and
"children.xsd".
#Myfamily.xml
So far in the XSD we have ignored namespaces as they will create confusion while writing and using basic XSDs.
Just to make you feel comfortable with XSD i have ignored namespaces in XSD but we can't ignore namespaces
completely. Namespaces plays vital role when we are working XSD andnamespaces are one ofthe reason to use
XSD inplace of DTD. Nowlet’s seewhat is namespace and what is thepurpose of Namespace.
52 | P a ge
WebServices
XSD Namespaces
When we are working on a project, several developers will create several classes and every developer will have a
freedom to choose their interested name for a class. In this scenario is there any possibility that multiple
developers will create classes using same name? – Yes, possibility isthere so it causes naming collision. Then
howtheycandifferentiatethisclassbelongstowhichdeveloper?–That’swherejavaprovidedPackages
concept.
Packagesareusedtoresolvenaming collisionthatoccursacrossmultipleclasseswhich arecreatedbymultiple
developers.
To resolve the naming collision every developer will bind his/her class to a package like below
With this SummaryReportDao.java class is binded to com.ibm.ctod.reports.dao package. So, wherever we want
to use SummaryReportDao.java class we should fully qualified class name like below
Note:Instead ofwritingcom.ibm.ctod.reports.daomultipletimesinclass,we canimportthispackageusing
import statement.
Like java, when multiple people are working on XSDs there is a possibility that they will use same names for
elementsandComplexTypesthenitcausesnamingcollision.ToresolvethisnamingcollisionXSDprovided
Namespaces.
XSD Namespaces has two faces
Declaring the namespace in the XSD document using Target namespace declaration
Using the elements that are declared under a namespace in xml document.
53 | P a ge
WebServices
XSD Target Namespace
Target namespace declaration is similar toa package declaration in java. You will bind your classes to a package
so,thatwhileusingthemyouwillreferwithfully qualifiedname.Similarly,whenyoucreateaComplexTypeor
an Elementyouwill bind them toa namespace, sothat while referring them you need to useqName.
Inordertodeclareapackage,weusepackagekeywordfollowedbynameofthe package.Todeclarea
namespace in XSD we need to use targetNamespace attribute at the Schema level followed by
targetNamespacelabel as shown below.
The PaytmType is by default is binded to the namespace “http://www.airtel.in/payments”
So,whilecreatinganelement“paytm”oftypePaytmTypeweshouldusethe qNameofthePaytmTyperather
simple name. (qName means namespace:element/type name).
Butthenamespacelabelscouldbeanyofthecharactersinlength,soifweprefix theentirenamespacelabel
toelement/typenamesitwouldbecometoughto read.So,to avoidthis problemXSDhasintroduceda
conceptcalledshortname. Insteadofreferringtonamespacelabelsyoucandefineashort nameforthat
namespacelabelusingxmlnsdeclarationatthe<schema>levelandyoucanuse theshortnameasprefix
insteadofthecompletenamespacelabel. In above Paytm.xsd we have written “airtel” as alias name for
targetNamespace like below
xmlns:airtel="http://www.airtel.in/payments"
targetNamespace="http://www.airtel.in/payments"
Injavawecanhaveonlyonepackagedeclarationataclasslevel.Inthesame waywecanhaveonlyone
targetNamespace declaration at an XSD document.
54 | P a ge
WebServices
Importance of xs:include and xs:import
Till now we have assumed that we only have a single schema file containing all your element definitions, but the
XSDstandardallowsyoutostructureyourXSDschemasbybreakingthemintomultiplefiles.Thesechild
schemas can then be included into a parent schema.
Breakingschemasintomultiplefilescanhaveseveraladvantages.Youcancreatere-usabledefinitionsthatcan
beusedacrossseveralprojects.Theymakedefinitionseasiertoreadandversionastheybreakdownthe
schema into smaller units that are simpler to manage.
When schemas breaked into multiple files how one schema can refer element/complexType from another
schema? – That’s where <xs:inclue /> and <xs:import /> comes into picture.
<xs:include/>: IfyouwanttouseXML schema components(elements/ ComplexTypes) from other XML
schemas with same targetNameSPaces, we should go for xs:include element
Syntax: <xs:include schemaLocation=”SchamUri”/>
Ex:<xs:includeschemaLocation=”Invoice.xsd”/>
Let’s demonstrate this using below Example
55 | P a ge
WebServices
Inovice.xsd is included in Customer.xsd using <xs:include /> element
We can write the XML for Customer.xsd like below
<xs:import /> :- If we want to use XML schema components from other XML schamas with different
targetNameSpaces, we should go for xs:import element.
Syntax : <xs:import namespace=”targetnamespace” schemalocation=”xsd uri”/>
Ex : <xs:import namespace=http://amazon.com/books/webservices schemaLocation=”amz.xsd”/>
56 | P a ge
Web Services
Let’s demonstrate <xs: import /> this with below example
Author.xsd is imported into Book.xsd using <xs: import /> element
Below is the xml that represents Book.xsd
57 | P a ge
Web Services
JAX-P
58 | P a ge
Web Services
Introduction
JAX-PstandsforJavaAPIforXML Processing. Aswediscussedearlier,XMLisalso a document whichholdsdata
in an XML format. Initially in Java there is no API that allows reading the contents of an XML document in an
XMLformat.Java programmershastolivewithJavaIOprogrammingtoreadthem inatext nature orneedto
build their own logic to read them in XML format.
Bylooking at thislot ofJava software vendors inthemarket hasstarted building theirownlibraries/API’sthat
allowsprocessinganXMLdocuments inXML nature. Fewofthem are DOM4J, JDOM.
Aftermanysoftwarevendorsstarteddevelopingtheirownlibraries,sunhasfinally releasedJAX-PAPIwhich
allows ustoworkwithXMLdocuments.Asindicated JAX-PisanAPIwhichmeansnotcompleteinnature,so
weneed implementations of JAX-PAPIandtherearemanyimplementationsof JAX-PAPIavailable fore.g..
Crimson,Xerces2,Oracle V2 Parseretc.
Xerces2 is thedefault parser that would be shippedas part of JDK1.5+. This indicates if you are working on
JDK1.5+ youdon’t need any separate Jar’s to work with JAX-PAPI.
XML Processing Methodologies
JAXPprovideswrappersaroundtwodifferentmechanismsforprocessingXMLdata.ThefirstistheSimpleAPI
forXMLorSAX,andiscoveredinthischapter.Thesecond,theDocumentObjectModel(DOM),iscoveredin
the next. In the SAX model, XML documents are provided to the application as a series of events, with each
eventrepresentingonetransitionintheXML document.Forexample,the beginningofanewelementcounts
as an event, as does the appearance of text inside that element. A SAX parser reads through the XML
document one time, reporting each event to the application exactly once in the order it appears in the
document. Event-based parsing has strengths and weaknesses.Very large documents can be processed with
events; there is no need to read the entire document into memory at once. However, working with sections
of an XML document (a record made up of many elements, for example) can become complicated because
the application developer has to track all the eventsfor a given section. SAX is a widely used standard, but is
notcontrolledbyanyindustrygroup. Rather,itisadefactostandardthatwasoriginallydevelopedbyasingle
developer (David Megginson) and by others in the XML community and is nowsupported by an open source
project(http://www.saxproject.org).TheSAXwrapper provided byJAXPallows forpluggingindifferent SAX
parsers without concern for the underlying implementation.This feature is somewhat moot because there
aren’t that many SAX parsers in widespread use today. However, it does provide for safeguards against
changes in future versions. SAX and DOM are the universal methodologies of processing (reading) XML
documents irrespective of a particular technology. Few programming languages/API’s supports only SAX way
of reading documents, few other supports only DOM and quite a few number support both the ways of
reading.
Simple API for XML (SAX)
The Simple API for XML (SAX) is available with the JAXP; SAX is one of two common ways to write software that
accesses XML data. SAX is an event-driven methodology for XML processing and consists of many
callbacks. Using SAX with JAXP allows developers to traverse through XML data sequentially, one element at a
time, using a delegation even model. Each time elements of the XML structure are encountered, an event is
triggered. Developers write event handlers to define customer processing for events they deem important. Each
elementisparseddowntoitsleafnodebeforemovingontothenextsiblingofthatelementintheXMLdocument,
therefore at no point is there any clear relation of what level of the tree we are at.
59 | P a ge
WebServices
The SAX Event Model
Most XML parsers fall into one of two main categories: tree-based or event based. Each kind of parser represents
XMLinformationslightlydifferently.Atree-basedparserconvertsanXMLdocumentintoatreeofobjects(You
will learn more about tree-based parsers in the next chapter). An event-based parser presents a document as a
series of events, each representing a transition in the document. Taken together, these events provide your
programwith acompletepictureofthedocument.Overviewof EventProcessing Imagineagainthatwe have
printedoutanXMLdocument.Howwouldyoubegintoreadthedocument?Youwouldprobablybeginatthetop
of thepageandcontinueline byline,lefttoright.Since youarefamiliar withXML, youknowthatthetags have
specificmeanings.Youwouldlikelytakenoticeofwhereoneelementendsandanotherbegins;andwitheach
newelementyouwould gain a betterunderstanding ofthecompletedocument. Event-basedparserswork in
much the same way. An event-based parser scans through a document from top to bottom. As it scans, the parser
takes notice of interesting points in the document.
For example, it would notice where one element ends and another begins. The parser then alerts your program,
givingittheopportunitytorespondtothetransition.Inparserterminology,thealertiscalledaneventandyour
program’sresponseisacallback.Acompletedocumentparsemayconsistofhundredsoreventhousandsof
events in series. Each event provides further information about the document. Handling hundreds or thousands
ofeventssounds overwhelming, andthere’s no doubtthatitcanget complicated. Event-based parsing suits some
situations better than others. The simpler the DTD associated with a document is, the easier it will be to use event-
based processing. Oftentimes these documents contain repeating groups of elements, where each group is to be
processedthesame way. Poor candidate documents are muchthe opposite.They are loosely-structured or
contain deep and complex hierarchies. You may also want to avoid documents where elements are reused
throughoutmultiplelevelsofahierarchy.Forthesetypesofdocuments,considerthetree-basedparsersdiscussed
elsewhereinthisbook.Ifyouareinterestedinusinganevent-basedparser,thenyouwillneedtolearntheSAX
API.
Any event based processing model contains three actors as described below.
Source:-istheoriginatorofevent,whocanraiseseveraltypesofevents. Eventscouldbeofmultipletypesif
weconsiderAWT,wecanconsidersourceas abutton,whichiscapableofraisingseveraltypesofeventslike
button click, mouse move, key pressed etc.
Listener:-Listeneristhepersonwhowilllistensforaneventfromthesource. Listenerlistensforaspecific
typeof eventfromthesourceandtriggers aneven handlingmethodontheEventhandlertoprocessit.
EventHandler:-Oncealistenercapturesanevent,toprocessit,it callsamethodontheeventhandlerclass.
As thereare different typesof events, tohandlethemtheeventhandlercontainsseveralmethodseach
target to handle and process a specific type of event.
60 | P a ge
Web Services
Inaddition,SAXisasequentialprocessingmodel,whichprocessXMLelements sequentiallyfromtoptothe
bottom.Whileprocessingthedocument,itplacesa pointertothedocumentandincrementssequentially
fromthetop.Based onthe type of element it is pointing to, it raises a respective event, which will notifythe
listener to handle and process it.
SoheresourceistheXMLdocumentwhichcanraiseseveraltypesofevents basedonthetypeofelementitis
pointingto(e.g...START_DOCUMENT, START_ELEMENTetc...). ListeneristheparserwhowillreadstheXML
document andtriggersamethodcallontheHandler.Eventhandlercontainsseveral methodstohandle
various types of events as shown below.
SAXisveryfastinprocessingXMLdocumentswhencomparedwithDOMand consumeslessamountof
memory,asatanygivenpointoftimeitloadsonly oneelementintothememoryandprocess.Hereonekey
thingto note is using SAXwecanonlyreadtheXMLdocument,wecannotmodify/createadocument.
Using JAX-P APIwecanprocess XMLdocuments inSAX model, here alsosource is theXML document, who is
capableofraisingmultipletypesofeventslikes startDocument,startElement,endDocumentetc.Inorderto
read the elements of XML and process them by raising events, we need a parser and here in SAX it is
SAXParser.
When to Use SAX
You want to process the XML document in a sequential manner from top to bottom.
SAXrequiresmuchlessmemorythanDOMbecauseSAXdoesnotcreateanin-memorytreeofthe
XMLdata,asaDOMdoes.Soif youwantto processa verylargeXMLdocument whoseDOMtree
would consume too much memory, you can shoose SAX over DOM.
If the XML document is not deeply nested
SAXisfastandefficientanditisusefulforstate-independentfiltering.SAXparsercallsamethod
whenever an element tag is encountered and calls a different method when text or character is
found.
Note: The disadvantage of SAX is that it does not provide random access to an XML document.
61 | P a ge
Web Services
Let us see an example program using SAX parser in Java.
This the xml file that we are going to read using SAX parser. The xml file contains a list of accounts
62 | P a ge
Web Services
Create a standalone project to read the above xml
Thenextstepistocreateourownhandlerclassto parsetheXMLdocument.DefaultHandlerclassprovides
default implementation ofContentHandler interface, so we can extend this class to create our own handler.
--------------------------------AccountHandler.java------------------------------
package com.xml.apps;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
public class AccountHandler extends DefaultHandler {
boolean bank = false;
boolean account = false;
boolean id = false;
boolean name = false;
boolean amt = false;
@Override
public void startDocument() throws SAXException {
System.out.println("Document started....");
}
@Override
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException {
if (qName.equals("Bank")) {
bank = true;
} else if (qName.equals("Account")) {
account = true;
System.out.println("Account Type:" + attributes.getValue("type"));
} else if (qName.equals("Id")) {
id = true;
} else if (qName.equals("Name")) {
name = true;
} else if (qName.equals("Amt")) {
amt = true;
}
}
@Override
public void characters(char[] ch, int start, int end) throws SAXException {
if (id) {
System.out.println("Acct id: " + new String(ch, start, end));
id = false;
}
if (name) {
System.out.println("Holder Name: " + new String(ch, start, end));
63 | P a ge
Web Services
name = false;
}
if (amt) {
System.out.println("Amount: " + new String(ch, start, end));
amt = false;
}
}
@Override
public void endElement(String uri, String localName, String qName)
throws SAXException {
}
@Override
public void endDocument() throws SAXException {
System.out.println("Document ended....");
}
}
-----------------------------------------0-------------------------------------------------
Intheaboveclassweareoverridingfivemethodswhichwouldbetriggered basedonthetypeofelementsthe
parser is pointing to on the source XML document.
 startDocument – would be triggered at the start of the XML document
 startElement – Whenever the parser encounters the starting element, it raises this method call by
passing the entire element information to the method.
 characters – This method would be invoked by the parser, whenever it encounters data portion
betweentheXMLelements.Tothismethoditpasses theentireXMLascharacterarrayalongwithtwo
other integers one indicating the position in the array from which the current data portion begins and
thesecond integer representing thenumberofcharacters thedata span to.
 endElement – would be triggered by the parser, when it encounters a closing element or ending
element.
 endDocument – would betriggered by the parser once it reaches end of the document.
Below is the Java program that uses SAXParserHandler to parse the XML to list of Employee objects.
64 | P a ge
Web Services
Inthelastchapterwediscussedevent-basedparsing.Event-basedparsinghassomelimitations.Forinstance,one
cannot manipulate entire sections of a document at once. Also, multiple passes over the document data calls for
multiple runs through the parser.Often, it would be more efficient if an entiredocument could be read into the
memoryandmanipulatedasanin-memoryrepresentation.ThiscanbeachievedusingtheDocumentObject
Model(DOM),whichisbyfarthemostwidelyusedamongthevariousstandardsproposedforinmemory
representation of XML documents. A standard specified by the World Wide Web Consortium (W3C), the DOM
specifies an abstract mapping of XML elements into runtime objects. Binding this specification to various
languages, including Java, has been implemented by a variety of vendors. In the DOM, every XML document is
representedasahierarchyofobjects.ThishierarchyformsatreestructurethatmimicsthestructureoftheXML
document.OnceyouarefamiliarwithXMLandDOM,translatingbetweenthetwobecomesasimplematter.
OnethingthecurrentDOMspecificationomitsisanAPIfortheparsingofanXMLdocumentintoaDOM.Thisis
left to the individual vendor when writing a DOM parser. The latest DOM specification (DOM 3) seeks to address
this issuetoo,butuntilitgains in popularity,application developers havetotake into accounttheprospectsof
modifying their code when moving to a different parser. JAXP solves this problem by presenting a standardized
interface forparsing
XML data; the result of this parsing is an object that conforms to the standard W3C DOM Document interface.
This chapter presents a discussion on the reading, writing, and simple manipulations of a DOM representation.
Morecomplexmanipulations,suchasthosepertainingtostylesheets,willbediscussedinthenextchapter.
65 | P a ge
Web Services
DOM parser
DOM(DocumentObjectModel)definesastandardforaccessingandmanipulatingdocuments.DOMbuilds
an in-memorytree representation of theXML document, where each node contains one of thecomponents
from an XML structure. The two most common types of nodes in XML document are element nodes and
text nodes.Java DOMparserAPI allows us to create nodes, remove nodes,change theircontents, and
traverse the nodehierarchy.
Points to note about DOM
DOM was designed to be language-neutral.
 DOM does not take advantage of Java’s object-oriented features.
DOMprovides a lotof flexibility for handling fully-fledged documents and complex applications. If
your programs handle simple data structures, then you can use JDOM or dom4j.
SinceDOMcreatesin-memorytree,forprocessingverylargeXMLdocuments,youshouldchoose
SAX or StAX beacuse DOM would consume too much memory.
DOM Parser API
The javax.xml.parsers.DocumentBuilder class defines API to obtain DOM Document instances from an XML
document. Using this class, an application program can obtain a Document from XML.
AninstanceofthisclasscanbeobtainedfromtheDocumentBuilderFactory.newDocumentBuilder()method.
Oncean instance of thisclass is obtained,XML canbe parsedfrom a varietyofinput sources.These input
sources are InputStreams, Files, URLs, and SAX InputSources.
Below is the architecture of a typical DOM parser application.
66 | P a ge
Web Services
Parse XML document using DOM parser in Java
67 | P a ge
Web Services
-----------------------------------------ParsingAccountsDataUsingDOM.java----------------------------------------------
public class ParseAccountsDataUsingDOM {
public static void main(String[] args) throws ParserConfigurationException,
SAXException, IOException {
// Get Document Builder
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
// Build Document
Document document = builder.parse(new File("Account.xml"));
// Normalize the XML Structure; It's just too important !!
document.getDocumentElement().normalize();
// Here comes the root node
Element root = document.getDocumentElement();
System.out.println(root.getNodeName());
// Get all employees
NodeList nList = document.getElementsByTagName("Account");
System.out.println("============================");
visitChildNodes(nList);
}
// This method is called recursively
private static void visitChildNodes(NodeList nList) {
for (int temp = 0; temp < nList.getLength(); temp++) {
Node node = nList.item(temp);
if (node.getNodeType() == Node.ELEMENT_NODE) {
System.out.println("Node Name = " + node.getNodeName()
+ "; Value = " + node.getTextContent());
// Check all attributes
if (node.hasAttributes()) {
// get attributes names and values
NamedNodeMap nodeMap = node.getAttributes();
68 | P a ge
Web Services
for (int i = 0; i < nodeMap.getLength(); i++) {
Node tempNode = nodeMap.item(i);
System.out.println("Attr name:"+ tempNode.getNodeName() + "; Value = "
+ tempNode.getNodeValue());
}
if (node.hasChildNodes()) {
// We got more childs; Let's visit them as well
visitChildNodes(node.getChildNodes());
}
}
}
}
}
}
--------------------------------------------.----------------------------------------------------
Create XML document using DOM parser in Java
Here is the input xml file we will be creating using DOM parser.
=========================DomparserCreateXml.java============================
import java.io.File;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Attr;
import org.w3c.dom.Comment;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
public class DomParserCreateXml {
public static void main(String[] args) {
try {
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.newDocument();
// root element
Element rootElement = doc.createElement("Employees");
doc.appendChild(rootElement);
// Employee element
Element employee = doc.createElement("Employee");
rootElement.appendChild(employee);
// setting attribute to element
Attr attr = doc.createAttribute("id");
attr.setValue("1");
employee.setAttributeNode(attr);
69 | P a ge
WebServices
// age element
Element age = doc.createElement("age");
age.appendChild(doc.createTextNode("28"));
employee.appendChild(age);
// firstname element
Element firstname = doc.createElement("firstname");
firstname.appendChild(doc.createTextNode("Ashok"));
employee.appendChild(firstname);
// lastname element
Element lastname = doc.createElement("lastname");
lastname.appendChild(doc.createTextNode("Kumar"));
employee.appendChild(lastname);
// role element
Element role = doc.createElement("role");
role.appendChild(doc.createTextNode("Developer"));
employee.appendChild(role);
Comment comment = doc.createComment("This is a comment");
rootElement.appendChild(comment);
form of a
// write the content into xml file
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
/* DOMSource acts as a holder for a transformation Source tree in the
* Document Object Model (DOM) tree.
*/
DOMSource source = new DOMSource(doc);
StreamResult result = new StreamResult(new File("D:employee.xml"));
transformer.transform(source, result);
// Output to console for testing purpose
StreamResult consoleResult = new StreamResult(System.out);
transformer.transform(source, consoleResult);
} catch (Exception e) {
e.printStackTrace();
}
}
}
--------------------------------------.------------------------------------------
StAX parser
StaX (Streaming API for XML) is a JAVA based API to parse XML documents similar to a SAX parser. There are
two main differences between SAX and StaX parsers. They are
SAXisapushAPI:-ItmeansthattheSAXparserwillsend(push)notificationstotheclientprogram
whenever it has processed an element, attribute or character.
OntheotherhandStAXisapullAPI:- ItmeanstheclientapplicationneedtoaskStAXparsertoget
information from XML whenever it needs.
StAX is an API for reading and writing XML Documents. SAX can be used only for reading XML.
Note that similar to SAX,StAX canonly process the XML document in a linear fashionfrom topto bottom
and you cannot have random access to an XML document.
70 | P a ge
WebServices
StAX API
StaX contains two distinct APIs to work with XML documents. They are
 Cursor API
 Event Iterator API
Applications can use any of these two API for parsing XML documents.
Cursor API
Asthenamesuggests,theStAXcursorAPIrepresentsacursorwithwhichyoucanparseanXMLdocument
from beginning to end. This cursor can point to one thing at a time, and always moves forward, never
backward, usually one info set element at a time.
The two main cursor interfaces are
 XMLStreamReader
 XMLStreamWriter
The XMLStreamReader interface has methods to read an XML document
TheXMLStreamWriterinterfaceprovidesmethodsforcreatinganXMLdocument.
TheXMLStreamReader interface has thefollowing important methods
• int next() – used to retrieve next parsing event.
• booleanhasNext()–Returnstrueiftherearemoreparsingeventsandfalseiftherearenomoreevents.
• String getText() – used to get text current value of an element
• String getLocalName() – used to get (local)name of an element
The XMLStreamWriter interface has the following important methods.
• writeStartElement (String localName) – Add start element of given name.
• writeEndElement (String localName) – Add an end element of given name.
• writeAttribute (String localName, String value) – Writes an attribute to the output stream without a
prefix.
• writeCharacters (String text) – Write text to the output.
Read XML using XMLStreamReader
------------------------StaxParserExample.java-----------------------------
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamConstants;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamReader;
public class StAXParserExample {
public static void main(String[] args) {
boolean bFirstName = false;
boolean bLastName = false;
boolean bRole = false;
boolean bAge = false;
try {
71 | P a ge
WebServices
XMLInputFactory factory = XMLInputFactory.newInstance();
XMLStreamReader streamReader = factory.createXMLStreamReader(new
FileInputStream(
"C:/Users/Ashok/Desktop/employees.xml"));
while (streamReader.hasNext()) {
int eventType = streamReader.next();
switch (eventType) {
case XMLStreamConstants.START_ELEMENT:
String qName = streamReader.getLocalName();
if (qName.equalsIgnoreCase("Employee")) {
System.out.println("Start Element : " + qName);
String id = streamReader.getAttributeValue(0);
System.out.println("Id : " + id);
} else if (qName.equalsIgnoreCase("age")) {
bAge = true;
} else if (qName.equalsIgnoreCase("firstname")) {
bFirstName = true;
} else if (qName.equalsIgnoreCase("lastname")) {
bLastName = true;
} else if (qName.equalsIgnoreCase("role")) {
bRole = true;
}
break;
case XMLStreamConstants.CHARACTERS:
String characters = streamReader.getText();
if (bAge) {
System.out.println("Age: " + characters);
bAge = false;
}
if (bFirstName) {
System.out.println("First Name: " + characters);
bFirstName = false;
}
if (bLastName) {
System.out.println("Last Name: " + characters);
bLastName = false;
}
if (bRole) {
System.out.println("Role: " + characters);
bRole = false;
}
break;
case XMLStreamConstants.END_ELEMENT:
String endName = streamReader.getName().getLocalPart();
if (endName.equalsIgnoreCase("Employee")) {
System.out.println("End Element :" + endName);
System.out.println();
}
break;
}
}
} catch (FileNotFoundException | XMLStreamException e) {
e.printStackTrace();
}
}
-----------------------------.-------------------------------------
72 | P a ge
WebServices
Validating XML against XSD
An XML document is considered ‘well-formed’ if it follows the normal rules of XML. i.e. all tags are closed properly
etc.Ontheother hand, anXML is consideredvalid if itfollows the rules specified in the DTDorXSD.
Below is the Account.xsd which represents Structure of the XML
Below is the Account.xml which holds the data as per Account.xsd .
73 | P a ge
Web Services
Manually wecan validate XML againstXSD using Altova XML Spytoolbutcanwevalidate XMLagainst XSD
programmatically?–Yes,wecanvalidateXMLagainstXSDprogrammatically usingSchemaandValidatorlike
below
Validating XML against XSD using DOM Parser
74 | P a ge
Web Services
JAX-B
75 | P a ge
Web Services
Introduction
Javaoffersseveraloptionsforhandling XMLstructuresandfiles.OneofthemostcommonandusedonesisJAXB.
ItoffersthepossibilitytoconvertJavaobjectsintoXMLstructuresandtheotherwayaround.JAXBcomeswith
the JRE standard bundle since the first versions of the JRE 1.6.
The first specification of JAXB was done in March 2003 and the work process is tracked in the Java Specification
Request 31: https://jcp.org/en/jsr/detail?id=31. In this specification request you can find a lot of information
regarding the long life of JAXB and all the improvements that have been made.
As already mentioned, JAXB is included in the JRE bundle since the update 1.6. Before that it was necessary to
include their libraries in the specific Java project in order to be able to use it.
Before JAXB was available (long time ago), the way Java had to handle XML documents was the DOM:
http://www.w3.org/-DOM/.Thiswasnotaverygoodapproachbecausetherewasalmostnotabstractionfrom
XMLnodesintoJavaobjectsandallvaluetypeswereinferredasStrings.JAXBprovidesseveralbenefitslikeObject
oriented approachrelatedtoXML nodes and attributes, typed values, annotations and mayothers.
JAXB stands for Java architecture for XML binding. It is used to convert XML to java object and java object to
XML.JAXBdefinesanAPIforreadingandwriting Javaobjectstoandfrom XMLdocuments. Unlike SAXand
DOM, we don't need to be aware of XML parsing techniques.
Basically, XML Binding API’s are categorized into two types of tools.
Design Time tools –In these type of tools, there will be a Binding compiler which willtake a Schema or DTD as
input and generated supported classes for converting the XML to Object andObject to XML.
Runtime tools – These willnot generate any classes rather on fly will take the XML as an input and based the
elementsnames,matchesthemwithcorrespondingattributenamesoftheclassandwillconvertXMLinto
Object of theclass.
WhenitcomestoJAX-BAPIitisadesigntimetool,whereitwillcomeupwithitsowncompilertogenerated
classestosupportthebindingprocess.BeforeproceedingfurtheronJAX-Bletusfirsttrytounderstandits
architecture and itsofferings.
Architecture
If a Java Object is following the structure of a Java class then that Object is called Instance of that class. If XML
documentisfollowingthestructureofanXSDdocumentcanIcalltheXMLasanInstanceofthatXSDornot?
Certainly, the answer for this would be yes.
InJava, Object structure would be defined by aclass. In XML, structure of an XML is defined by an XSD
document as shownbelow.
76 | P a ge
Web Services
If wetrytoderive a conclusionfromtheabove, wecanunderstandthat ClassesandXSDdocumentsbothtry
to represent the structure, so we can create set of Java classes which represents the structure of an XSD
document,thenthe XMLdocument(holdsdata)representingthestructureofthatXSDcanbe convertedinto
its associatedJava classObjects. Eventhewise versa wouldalso be possible.
Let us try to deep down into the above point. How to create user defined data type in Java? Using class
declaration.Howtocreateuserdefineddatatypein XSD?ByusingComplexTypedeclaration.Whichmeansa
ComplexTypeinXSDis equaltoa Java classin Java. As XSD document means itcontains elements and multiple
Complex Type’s so, to represent the structure of an XSD document in Java, it is nothing butcomposition of
variousJavaclasses(oneJavaclassto oneXSD ComplexType)representingitsstructure.
Mapping or Binding
Java objects canbe bondedto XML structures by usingcertain annotations and following specific rules. This is
whatwecallasmappingorBinding. Toperformthisbinding,weneedtogenerateBindingclasseswhich
represents structures of the XML.
77 | P a ge
Web Services
Let us take the example of PurchaseOrder XSD to understand better.
In the above XSD we have one element and four ComplexType declarations, as we discussed earlier
ComplexType declarations inXSD are equal toa Java class in Java. So from the above wecanderive four Java
classes as shown below.
class ShippingAddressType {
StringaddressLine1;
StringaddressLine2;
Stringcity;
Stringstate;
int zip;
Stringcountry;
}
class ItemType {
StringitemCode;
int quantity;
}
class OrderItemsType {
List<ItemType>item;
}
class PurchaseOrderType {
OrderItemsType orderItems;
ShippingAddressType shippingAddress;
}
FromtheabovewecancreatethePurchaseOrderTypeobjectrepresentingtheroot elementofXSD,canIhold
thePurchaseOrderXMLdocumentdataintothis instanceornot?Absolutelytheanswerwouldbeyes,because
PurchaseOrderType isrepresentingthestructureoftheXSDdocument,soitsinstancecanholditsXML data.
WiththisweunderstoodthatwecancreatedtheJavaclassesrepresentingthe structureofanXSDdocument,
hencethoseclassesarecalledasBindingClassesas thosearebondedtotheXSDdocumentstructureandthe
objects out of those classes arecalledbinding objects.
78 | P a ge
Web Services
NowweknowthatwecanconverttheXMLdocument dataintoa BindingClass Object,sotheprocessof
convertinganXMLtoaBindingclassObjectiscalledUn-Marshalling.AndtheprocessofconvertingaBinding
ObjectbackintoXML representationiscalledMarshallingandboththetypesofoperationsaresupported by
any of the XML Binding API’s including JAX-B.
So, JAX-B supports two types of operations
1) One-Time operations
2) Runtime operations.
Let us discuss them in detail below.
One-Time Operation
One-Time operations are the operations which would be done only once within the lifetime of an XSD or Binding
class.
Let’s say I want to convert the Purchase Order XML document to Object, this is Un-Marshalling. To perform Un-
Marshalling do we need Binding classes representing the structure of the Purchase Order XSD or not? So the
programmer has to read the contents of the XSD and based on the number of complex types he needs to create
equivalent Java classes representing their structure. As our purchase order XSD document contains only four
complextypesitwouldbeeasyforthedevelopertodeterminetherelationsbetweentheclassesandcan
create.Let’ssayIhaveanXSDdocumentinwhich100ComplexTypedeclarationsarethere,isiteasyfora
developertodevelop100 Java classesrepresentingthestructureof100ComplexTypes.Eventhoughitseemsto
be feasible, but it is a time taking task.
So,insteadofwritingtheBindingclassesmanually,JAX-Bhasprovidedatooltogenerated Bindingclasses from
XSDcalledXJC.AndtogenerateXSDfromaBindingclassthereisanothertoolcalledSchemagen.
IfIhaveanXSDdocument,howmanytimesdoIneedtogenerateJavaclassestoholdthedataofitsXML?It
wouldbeonlyonce,becauseclasseswillnotholddatatheyjustrepresentsstructure,soinstancesofthose
classesholdsdataofanXML. Eventhereversewouldalsobesame.AsweneedtogeneratetheBindingclasses
79 | P a ge
Web Services
or XSD only once this process is called one-time operations. And there are two types of one-time operations.
a) XJC – XSD to Java compiler – Generates Binding classes from XSD document
b) Schemagen – Schemagenerator – GeneratedXSDdocumentfrom an Binding class
How to use XJC or Schemagen?
Implementing all binding classes for an existing XML interface can be a time consuming and tedious task. But the
good news is, you do not need to do it. If you have a XSD schema description, you can use the xjc binding compiler
tocreatetherequiredclasses.Andevenbetter,xjcispartoftheJDK.Sothereisnoneedforexternaltoolsand
you should always have it at hand if required.
Open Command Prompt and type xjc -help command  It gives all xjc options like below
80 | P a ge
WebServices
 -d to definewhere the generated classes shall be stored in the file system,
 -p to define the package to be used and of course
 -help if you need anything else.
Generating Binding Classes for XSD using XJC
What does XJC generates?
WhenwerunXJC.batbygivingXSDasaninputalong withgeneratingbinding classesitgeneratesfewother
things as explained below.
All the binding classes would be generated into the given package com.amazon.types
1. Package-info.java–XJCaftermappingthenamespacetoapackagename,it wouldstorethismapping
information into a class called package-info.java. This is also generated under the above mapped
package only.
2. ObjectFactory.java – These Class Actsasfactoryclass, whichknows howto createobjects ofall the
Bindingclassesgenerated. Itcontainsmethods like createXXX, uponcallingthesemethods itwould
return respective binding classobjects.
3. SetofBindingclasses–WiththeaboveitgeneratesBindingclasses representingthestructureofeach
ComplexTypeinXSD.Canwecallanyjava classasBindingclass?No,thebindingclassesaretheclasses
whichare bondedtoXSDcomplexTypedeclarationsandtodenotethisrelationship, thosearemarked
withJAX-B annotations as described below.
81 | P a ge
Web Services
So,bytheaboveweunderstoodthatnoteveryJavaclassiscalledasBinding class,onlytheclasseswhichare
annotated with JAX-Bannotations are called bingingclasses.
So, from the above binding classes we can even generated XSD document by running the Schemagen tool.
Withthiswe understoodhowtoperformone-timeoperations.Nowwecan proceedonruntimeoperations.
Runtime Operations
Tillnowwediscussedabouthowtoperformone-timeoperations.Letustryto understandRuntimeoperations.
JAX-Bsupportsthreeruntimeoperations.
1) Un-Marshalling – The process ofconverting XML to JavaObject
2) Marshalling – The process of converting JavaObject with data to its XML equivalent
3) In-MemoryValidation – Beforeconverting anXML documentto JavaObject first we need to validate
whether theXML conforms to XSD or not would be doneusingIn-MemoryValidation.
If we want to perform runtime operations, first you need to do one-time operation. Unless you have binding
classes orXSDequivalent foranyexisting bindingclass,youcan’twork onruntimeoperations.
ByfollowingthethingsdescribedinearliersectionweassumeyoualreadycompletedtheOne-Timeoperations
andyouhavebindingclasseswithyou.Letus trytounderstandhowtoworkoneachoftheRuntimeoperations
in the following section.
Un-Marshalling:
Asdescribedearlier,theprocessofconvertinganXMLdocumentintoJava ObjectiscalledUn-Marshalling.In
order to perform Un-Marshalling, you need to have Binding Classes with you. You can generate these by
running XJC compiler. If you run XJC compiler on the Purchase-Order.xsd which was described earlier, the
following bindingclasseswill be generatedshown below.
i. @XMLType–Tothetopofthebindingclassitwouldbemarkedwith
@XMLType annotationindicatedthisclassisrepresentinganXML Complex
Type
ii. @XMLAccessorType(AccessType.FIELD)–Inconjunctionwith
@XMLType,onemoreannotation
@XMLAccessorType(AccessType.FIELD)alsowouldbegenerated.It denotes how to map XML elements to
Bindingclassattributes.Withthe AccessType.FIELDwearesayingtheelementsnamesmustbematched
with binding class attributes names to port the data.
iii. @XMLElement – This annotation is marked at the attributes of the Binding classes to indicates these
attributes arerepresenting elements ofXML.
82 | P a ge
Web Services
83 | P a ge
Web Services
HavingthebindingclasseswillnotautomaticallyconvertstheXMLdocument intoObjectoftheseclasses,
rather we needa mediator who would be able to read the contents of the XML,and identifytherespective
bindingclassforthat andcreatesobjectstopopulatedata.Thiswillbedonebyaclasscalled “Unmarshaller”.
AsJAX-BisanAPI,soUnmarshallerisaninterfacedefinedby JAX-BAPIanditsJAX-BAPIimplementations
(JAX-BRI or JaxMe) contains the implementationclassforthisinterface.
TheobjectofUnmarshallerhasamethodunmarshal(),thismethodtakesthe inputasXMLdocumentand
firstcheckforWell-formness.Oncethedocumentis well-formed,itsreadstheelementsoftheXMLandtries
to identify the binding classes for those respective elements based on @XMLType and @XMLElement
annotationsandconverts them into theObjects.
We have two problems here
1) Howto create Un-marshaller as we don’t knowimplementation class
2) Wheredoesun-marshallershouldsearchforidentifyingabindingclass(isit inentireJVMmemoryor
classpath?)
As we don’t know how to identify the implementation of Unmarshaller interface, we have a factory class
calledJAXBContextwhowillfindstheimplementation classforUnmarshallerinterfaceandwouldinstantiate.
Ithasamethod createUnmarshaller()whichreturnstheobjectofunmarshaller.Thisaddressed theconcern
#1
While creating the JAXBContext, we need to supply any of the three inputs statedbelow.
1) Packagenamecontainingthe binding classes
2) ObjectFactory.classreferenceasitknowsthebindingclasses.
3) IndividualBinding classesas inputs to theJAXBContext.
JAXBContextjaxbContext=JAXBContext.newInstance(“packagename”or
“ObjectFactory.class” or “BC1, BC2, BC3…”);
84 | P a ge
Web Services
Withtheabove statement, theJAXBContext wouldbe createdandloads the classes thatarespecifiedin the
package or referred by ObjectFactory or the individual binding classes specified and creates an in-memory
context holding these.
NowwhenwecalltheUnmarshaller.unmarshal()method,theUnmarshallerwill searcheswiththeclasses
loadedintheJAXBContextandtriestoidentifythe classesforanXMLelementbasedontheirannotations.
The code for UnMarshallinghasshownbelow.
Marshalling:
MarshallingistheprocessofconvertingtheObjectdatatoXML.Forperforming Marshallingalsoweneedto
createtheBindingclasses first.Oncewehave theBindingclasses,weneedtocreatetheObjectofthese
classes and should populate data inthem.
TheseobjectscanbemarshaledtoXMLusingtheMarshaller.Again,Marshalleris aninterface,toinstantiate
itweneedJAXBContext.Thenweneedtocalla methodmarshalbygivinginputasXMLandOutputstream
where we want to generate the output to.The belowprogram depicts the same.
85 | P a ge
WebServices
In-Memory Validation
While performing the Unmarshalling or Marshalling, we need to first of all validate whether the XML is valid
againsttheXSDdocumentornot,andwewill validateusingtheIn-Memoryvalidation.AnXMLcanbevalidated
againstanXSDdocument,soweneedtoreadtheXSD documentandshouldrepresentitinaJavaObjectcalled
Schema.
ButSchemaisaninterfaceandtocreatetheObjectofinterface,we needfactory calledSchema Factory.But
schema factory can created various types of XSD documents, so we need to provide the grammar of XSD
document which you want to load or created and would be done as show below.
Withtheabove we created aSchemaFactorywhich iscapableof creatingorloadingW3CXMLSchematype
documents.
Now we need to load the XSD document into the Schema class object as shown below.
Once the schema object is created holding the structure of XSD, we need to give it to Unmarshaller
before calling the unmarshal(). So, that Unmarshaller will validate the input XML with this supplied Schema
Object and then performs Unmarshalling. Otherwise Unmarshaller will throw exception, indicating the type
of validation failure. The below programs shows how to perform in-memory validation.
SchemaFactorysFactory=
SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_URI);
SchemapoSchema = sFactory.newSchema(new File(“Purchase-Order.xsd”));
86 | P a ge
WebServices
Getting Started withWebservices
Before discussing Web Service development, first we need to understand certain aspects related to Web
Services.ThepointswearediscussingbelowarecommonforbothJAX-RPCandJAX-WSaswell.
Types of Web Services
Asdiscussedearlier,wehavetwotypesofWebServicesJAX-RPCAPIadheringtheBP1.0,andJAX-WSAPI
adhering to BP 1.1. Now while developing a Web service, first of we need to choose a type. After choosing the
type,weneedtoselectanappropriateimplementationandvariousotheraspectsdescribedinfollowing
sections.
Web Service Development parts
Always a Web Service development involves two parts. Provider and Consumer. Provider is the actual Web
service, who will handle the incoming requests from the consumer. The Consumer is the Client Program which
wedeveloptoaccesstheProvider.NowbothJAX-RPCandJAX-WSAPI’shasprovidedclassesandinterfacesto
develop Consumer as well as Provider programs.
Ways of developing a Web Service
There are two ways of developing a Web service
Contract First approach: In Web Services, WSDL acts as a contract between Consumer and Provider. If consumer
wantstoknowtheinformationabouttheprovider,heneedstoseetheWSDLdocument.InaContractFirst
approach,thedevelopmentoftheproviderwillstartswithWSDL,fromwhichthenecessaryJavaclasses
requiredtobuildtheservicewouldbegenerated.AsthedevelopmentstartsfromWSDL,henceitiscalled
Contract First approach.
Contract Lastapproach: Here the developerfirst starts developing theservice bywriting theJava code,once
done then he will generate the WSDL contract to expose it as a Web Service. As the contract is being generated
at the end after the development is done, this is called Contract Last approach.
Choosing an Endpoint
InWebservicestheproviderisoftenreferredasEndpoint,asheistheultimatepointfromwhomwerequest
data or information.
NowinatypicalWebServicecommunication,theconsumerwillsendtheinitialrequestwithsomedatatothe
Provider.TheconsumercannotsendObjectdataoverthenetwork;ratherheneedstoconvertitintoXMLand
needstoplacetheXML into SOAP XML.ThentheSOAP XMLisbeingtransported over theHTTP protocol.This
means the consumer will send a HTTP request, to receive the HTTP request being sent by the consumer, at the
ProviderendweneedtohaveaHTTPListener.Thelistenerwilllistenfortheincomingrequestandforwardsit
forfurtherprocessingasshownbelowSoweunderstoodweneedalistenerattheprovidersidetohandlethe
incomingrequest.DowehaveanyexistingAPI’sinJavawhicharecapableofhandlingincomingHTTPRequests?
Those are nothing but Servlet or EJB.
87 | P a ge
WebServices
There are two types of Endpoints, where a developer can choose while developing a Provider.
Servlet Endpoint: Here at the provider end, the servlet acts as a listener in listening for the incoming request
from the client and would process.
EJBEndpoint:InplaceofServletevenwecansubstituteitwithEJB,andwecanmakeEJB’stohandleevenHTTP
Request as well.
Most of the people prefer to use Servlet endpoint rather than EJB endpoint as EJB seems to be heavy and costly
component,andforthesakeofdevelopingWebservices,theapplicationneedstobehostedonanEJB
container.
Message Exchange Patterns
Message exchange format talks about how a consumer does exchanges information withthe provider. This
could happen in three ways as described below.
Synchronous request/reply: In this pattern, the consumer sends the request with some data and will waits till
the provider finishes processing request and returns the response to the consumer.
Class A is calling a method execute () on B, until the method execute () finishes execution and returns value, the
do()methodwillbeblockedontheexecute()methodcall,asitisblockedonmethodcall,itiscalledblocking
request/reply or synchronous request reply. In this case also the Consumer program would be blocked on the
Providersmethodcall(request)andwillnotproceedsexecutionuntiltheProviderreturnsresponse.Which
meanstheConsumeropenedHTTPConnectionwouldbe opentilltheProvider returnsresponse.
Asynchronousrequest/replyorDelayedResponse:Inthispattern,theConsumerwillnotbeblockedonthe
Providers method call/request, rather after Consumer sendingtherequest;he disconnects/closes the HTTP
Connection.Theprovideruponreceivingtherequestwillholditandprocessitaftercertainamountoftime.
Once the response is ready willopensa new connection backtothe Consumer anddispatches theresponse.
Fore.g.letusconsideranexamplelikeyouaresendingalettertoyourfriend,whenyouposttheletteritwould
becarriedbythepostmastertoyourfriend.Oncetheletterhasbeenreceived,yourfriendmaynotimmediately
readtheletter,ratherwhenhefindsleisurehewillread.Tillyourfriendreadstheletterandgivethereplythe
postmastercan’twaitatyourfriend’sdoorratherhemoveson.Nowwhenyourfriendreadsyourletter,thenhe
will reply to your letter by identifying the from address on the letter and post back’s you thereply. Asthe
responsehereisnotimmediateandisbeingsentaftersometime,thisisalsocalledasDelayedresponse
pattern.
One way Invoke or Fire and forget: In this case, the consumer will send the request with some data, but never
expects a response from the provider. As the communication happens in only one direction it is called One-Way
invoke as well.
88 | P a ge
Web Services
Message Exchange formats
This describes about how the consumer will prepares/formats the xml message that should be exchanged with
the provider.
Fore.g.alecturerisdictatingthenotes,everystudenthastheirownwayofwritingthenotes.Someonemay
right the notes from bottom to top, others might right from top to bottom. In the same way, to send
information, the consumer has to prepare his data in XML format. How does consumer represents the data in
the XML document is called Message Exchange format?
The message exchange format would be derived by two parts
1) Style and other is 2) Use.
a) Style – The possible values the Style part can carry is rpc and document
b) Use – This could be encoded and literal
Withtheaboveitresultsinfourcombinationsasrpc-encoded,rpc-literal,document-literalanddocument-
encoded. Out of which document-encoded is not supported by any web service specification. We will discuss the
remaining three in later sections.
89 | P a ge
Web Services
JAX-WS
90 | P a ge
Web Services
Introduction
Java APIforXMLWebServices(JAX-WS),isastandardized APIforcreating webservices inXMLformat(SOAP).
JAX-WSprovides support for SOAP (Simple Object Access protocol) basedweb services.
Webservices have been arounda while now.Firstthere wasSOAP.But SOAPonlydescribed whatthe messages
looked like. Then there was WSDL. But WSDL didn't tell you how to write web services in Java. Then along came
JAX-RPC 1.0. After a few months of use, the Java Community Process (JCP) folks who wrote that specification
realizedthatitneededafewtweaks,soreleasedJAX-RPC1.1.Afterayearorsoofusingthatspecification,the
JCPfolkswantedtobuildabetterversion:JAX-RPC2.0.Aprimarygoalwastoalignwithindustrydirection,but
the industry was not merely doing RPC web services, they were also doing message-oriented web services. So
"RPC" was removed from the name and replaced with "WS" (which stands for web Services). Thus the successor
to JAX-RPC 1.1 is JAX-WS 2.0 - the Java API for XML-based web services.
What remains the same in JAX-RPC and JAX-WS?
BeforewetalkthedifferencesbetweenJAX-RPC1.1andJAX-WS2.0,weshouldfirstdiscusssimilaritiesbetween
JAX-RPC andJAX-WS
JAX-WSstillsupportsSOAP1.1overHTTP1.1,sointeroperabilitywillnotbeaffected.Thesamemessages
can still flow across the wire.
JAX-WSstillsupportsWSDL1.1,sowhatyou'velearnedaboutthatspecificationisstilluseful.AWSDL2.0
specification is nearing completion, but it was still in the works at the time that JAX-WS 2.0 was finalized.
What is different between JAX-RPC and JAX-WS?
SOAP 1.2: JAX-RPC and JAX-WS support SOAP 1.1. JAX-WS also supports SOAP 1.2.
XML/HTTP: The WSDL 1.1 specification defined an HTTP binding, which is a means by which you can send XML
messages over HTTP without SOAP. JAX-RPC ignored the HTTP binding. JAX-WS adds support for it.
WS-I's Basic Profiles: JAX-RPC supports WS-I's Basic Profile (BP) version 1.0. JAX-WS supports BP 1.1. (WS-I is
the web services interoperability organization.)
New Java features: JAX-RPC maps to Java 1.4. JAX-WS maps to Java 5.0. JAX-WS relies on many of the features
new in Java5.0.
JavaEE5,thesuccessortoJ2EE1.4,addssupportforJAX-WS,butitalsoretainssupportforJAX-RPC,whichcould
be confusing to today's web services novices.
The data mapping model:
JAX-RPChasitsowndata mappingmodel,which coversabout90percentofallschematypes.Thosethat
it does not cover are mapped to javax.xml. soap.SOAPElement.
JAX-WS's datamapping model is JAXB. JAXBpromises mappingsfor allXML schemas.
91 | P a ge
WebServices
The interface mapping model:
JAX-WS'sbasicinterfacemappingmodelis not extensivelydifferent fromJAX-RPC's; however:
JAX-WS's model makes use of new Java 5.0 features.
JAX-WS's model introduces asynchronous functionality.
The dynamic programming model:
JAX-WS's dynamic client model is quite different from JAX-RPC's. Many of the changes acknowledge industry
needs:
It introduces message-orientedfunctionality.
It introduces dynamic asynchronous functionality.
JAX-WS also adds a dynamic server model, which JAX-RPC does not have.
MTOM (Message Transmission Optimization Mechanism)
JAX-WS, via JAXB, adds support for MTOM, the new attachment specification. Microsoft never bought
into the SOAP with Attachments specification; but it appears that everyone supports MTOM, so
attachment interoperability should become a reality.
The handler model:
The handler model has changed quite a bit from JAX-RPC to JAX-WS.
JAX-RPChandlersrelyonSAAJ1.2.JAX-WShandlers relyonthenewSAAJ1.3specification.
SOAP 1.2
There is really not a lot of difference, from a programming model point of view, between SOAP 1.1 And SOAP 1.2.
As a Java programmer, the only place you will encounter these differences is
When using the handlers.
XML/HTTP
LikethechangesforSOAP1.2,thereisreallynotalotofdifference,fromaprogrammingmodelPointofview,
between SOAP/HTTP and XML/HTTP messages. As a Java programmer, the only Place you will encounter these
differences is when using the handlers. The HTTP binding has its own handler chain and its own set of message
context Properties.
WS-I's basic profiles
JAX-RPC1.1supportsWS-I'sBasicProfile(BP)1.0.Sincethattime,theWS-IfolkshaveDevelopedBP1.1(andthe
associated AP 1.0 and SSBP 1.0). These new profiles clarify some Minor points, and more clearly define
attachments. JAX-WS 2.0 supports these newer profiles. For the most part, the differences between them do not
affecttheJavaprogrammingmodel.TheExceptionisattachments.WS-Inotonlyclearedupsomequestionsabout
attachments, but they Also defined their own XML attachment type: wsi:swaRef. Many people are confused by all
these profiles. You will need a little history to clear up the confusion.
WS-I'sfirstbasicprofile(BP1.0)didagoodjobofclarifyingthevariousspecs.Butitwasn'tperfect.Andsupport
for SOAP with Attachments (Sw/A) in particular was still rather fuzzy. In their second iteration, the WS-I folks
pulled attachments out of the basic profile - BP 1.1 - and fixed some of the things they missed the first time around.
Atthat pointtheyalso addedtwo mutually exclusive supplements to thebasic profile:AP1.0 andSSBP1.0.AP 1.0
is the Attachment Profile which describes how to use Sw/A. SSBP 1.0 is the Simple SOAP Binding Profile, which
92 | P a ge
Web Services
describes a web services engine that does not support Sw/A (such as Microsoft's .NET). The remaining profiles
that WS-I has and is working on build on top of those basic profiles.
Summary
JAX-WS 2.0 is the successor to JAX-RPC 1.1. There are some things that haven't changed, but most of the
programmingmodelisdifferenttoagreaterorlesserdegree.Thetopicsintroducedinthistipwillbeexpanded
upon ina seriesoftipswhich we willpublish overthecomingmonthsthat willcompare,in detail,JAX-WSand
JAX-RPC.Atahighlevelthough,hereareafewreasonswhyyouwouldorwouldnotwanttomovetoJAX-WS
from JAX-RPC.
Reasons to stay with JAX-RPC 1.1:
Ifwewanttostaywithsomethingthat'sbeenaroundawhile,JAX-RPCwillcontinuetobesupportedfor
some time tocome.
If we don't want to step up to Java 5.
If we want to send SOAP encoded messages or create RPC/encoded style WSDL.
Reasons to step up to JAX-WS 2.0:
If we want to use the new message-oriented APIs.
If we want to use MTOM to send attachment data.
If we want better support for XML schema through JAXB.
If we want to use an asynchronous programming model in your web service clients.
If we need to have clients or services that can handle SOAP 1.2 messages.
If we want to eliminatetheneedfor SOAP inyour webservices and just usethe XML/HTTP binding.
SOAP
SOAP is an XML specification for sending messages over a network. SOAP messages are independent of any
operating system and canusea varietyof communication protocols including HTTP and SMTP.
SOAPisXMLheavy,hencebestusedwithtools/frameworks.JAX-WSisaframeworkthatsimplifiesusingSOAP.It
is part of standard Java.
SOAP message contains the following three parts:
Envelope: This Envelope element contains an optional Header element and a mandatory Body element.
Header: SOAP message contains the information which explains how the message is to be processed.
Body: Body part of the SOAP message contains the actual payload of the end to end message transmission.
93 | P a ge
Web Services
Java-XML Data Binding
SOAP-based web services use XML to exchange request and response messages. This requires an architecture for
converting Java objects to XMLandthereverse. JAXB(Java Architecture for XMLBinding) was developed forthis
purpose.
JAX-RPCusesitsowndatamappingmodel.ThisisbecausetheJAXBspecificationhadnotbeenfinalizedwhenthe
firstversionofJAX-RPCwascompleted.TheJAX-RPCdatamappingmodellackssupportforsomeXMLschemas.
JAX-WS uses JAXB for data binding. JAXB provides mapping for virtually all schemas.
Wecanuse JAXBannotations onyour Java bean and JAX-WSwill convert itandits properties to XML elements at
runtime when sending the SOAP message.
Web Services Definition Language (WSDL)
TheWebServicesDescriptionLanguagesisanXML-basedinterfacedefinitionlanguagethatisusedfordescribing
thefunctionalityofferedbyawebservice.TheacronymisalsousedforanyspecificWSDLdescriptionofaweb
service(alsoreferredtoasaWSDL file), which provides amachine-readable description ofhow theservicecanbe
called, what parameters it expects, and what data structures it returns. Therefore, its purpose is roughly similar
to that of a method signature in a programming language.
WSDL1.0(Sept.2000)wasdevelopedbyIBM,Microsoft,andAribatodescribeWebServicesfortheirSOAPtoolkit.
It was built by combining two service description languages: NASSL (Network Application Service Specification
Language) from IBM and SDL (Service Description Language) from Microsoft.
WSDL1.1,publishedinMarch2001,istheformalizationofWSDL1.0.Nomajorchangeswereintroducedbetween
1.0 and 1.1.
94 | P a ge
Web Services
WSDL 1.2 (June 2003) was a working draft at W3C, but has become WSDL 2.0. According to W3C: WSDL 1.2 is
easier and more flexible for developers than the previous version. WSDL 1.2 attempts to remove non-
interoperable features and also defines the HTTP 1.1 binding better. WSDL 1.2 was not supported by most SOAP
servers/vendors.
WSDL 2.0 became a W3C recommendation on June 2007. WSDL 1.2 was renamed to WSDL 2.0 because it has
substantial differences from WSDL 1.1. The changes are the following:
Added further semantics to the description language
Removed messageconstructs
Operator overloading notsupported
PortTypes renamed tointerfaces
Ports renamed toendpoints
The current version of WSDL is WSDL 2.0.
Definition: The definition element must be the root element of the WSDL specification.
This element defines the name of the web service, information about the multiple namespaces used though out
the WSDL document.
Types: This element is very important while sharing the data across multiple platforms using web services. The
datatypeof thevariableswe are usingin theweb services shouldbe compatible with all platforms.Thetypes
elementisusedtodefineallthedatatypesusedbetweentheendtoendtransmissions.XSDorXMLSchema
Definition is used to define the types used in theWSDL. The detailed overview of XSD will explain in the next
section.
95 | P a ge
WebServices
Message: Eachmessage describeseithertheinputoroutputofthewebservicetransmissionandithasthename
ofthemessage andzero or more-partmessage elements Inputmessage contains therequestinformation andthe
corresponding part message details. The output message element contains the details about the response from
the server.
portType: PortType elements are an entity like a Java class containing group of operations.
This element describes a complete operation definition by combining input and output messages. One portType
element can describe multiple operations
Binding: The binding element describes how the service will be implemented in the transmission.
Service: Service element provides the address, information about the service. This element defines the URL of
the service we are invoking
Top-Down vs. Bottom-Up
There are two ways of building SOAP web services. We can go with a top-down approach or a bottom-up
approach.
In a top-down (contract-first) approach, a WSDL document is created, and the necessary Java classes are
generated from the WSDL. In abottom-up(contract-last) approach, the Java classes are written, and the WSDL is
generated from theWSDL.
Writing a WSDL file can be quite difficult depending on how complex your web service is. This makes the bottom-
upapproachaneasieroption.Ontheotherhand,sinceyourWSDLisgeneratedfromtheJavaclasses,anychange
in code might cause a change in theWSDL. This is not the case for the top-down approach.
Features of JAX-WS
Requests and responses are transmitted as SOAP messages (XML files) over HTTP
Even though SOAP structure is complex, developer need not bother about the complexity in messaging.
The JAX-WS run time system manages all the parsing related stuffs.
SinceJAX-WSusestheW3Cdefinedtechnologies,aSOAPwebserviceclientcanaccessaSOAPwebservice
that is running in a non-java platform.
A machine readable WSDL (Web Service Description Language) file which describes all the operations
about a service can be present in case of SOAP web services
Annotations can be used with JAX-WS to simplify the development
Annotations used in JAX WS
AnnotationscanbeusedinJavaclassesincreatingwebservices.Themostcommonlyusedannotationsarelisted
below:
@WebService
@WebMethod
@WebParam
@WebResult
@SOAPBinding
@OneWay
AsJAX-WSisanAPIwecan’tstartthedevelopmentdirectlywithAPI.WeneedanimplementationforthisAPI.
96 | P a ge
WebServices
JAX-WS implementations
There are several implementations for JAX-WS. Some of them are:
Developing WebService using JAX-WS API with RI implementation
Deciding Technology Stack
Specification : B.P 1.1
API : JAX-WS
Implementation : Reference Implementation(RI)
Role : Provider
Approach : Contract LastApproach
Endpoint : Servlet Endpoint
MEP : Synchronous request - reply
MEF : Document Literal (By default)
97 | P a ge
WebServices
Requirement: Develop an application to performAirthematic Operations through WebService
Procedure of developing Provider
Step 1: - Create Dynamic web project in IDE and add jax-ws RI related jars in project lib folder
Step 2: - Create Service Endpoint Interface (This is optional in jax-ws api)
98 | P a ge
WebServices
Step3: - Create Service Implementation class
Step 4:- CreateWeb servicedeploymentdescriptorfileinprojectWEB-INF folder (sun-jaxws.xml)
with endpoint and url-pattern details
Step 5: Configure WSServletContextListener & WSServlet in web.xml
99 | P a ge
WebServices
Step 6: Deploy the application and access using Endpoint URL
Access the WSDL using below URL
Note: If we are able access the WSDL like above, that means Provider is up and running
100 |P a ge
WebServices
Step 7: Test the Provider using SOAP UI tool
Open SOAP UI - > Click on File - > New SOAP Project -> Enter Project Name and WSDL URL
Step 8: Send SOAP request like below - > we can SOAP Response
101 |P a ge
WebServices
Developing Consumer
After developing the provider, to access provider, we need to build the Consumer.
JAX-WSAPIsupportsboththedevelopmentsofProvideraswellasConsumer. JAX-WSAPIsupportstwotypes
of consumer, theyare
 Stub based consumer
 Dispatch API
From above two approaches, most of the projects use stub based consumer and following section describes how
to build a stub based consumer for JAX-WS Provider.
Procedure for Developing STUB Based Consumer for JAX-WS Provider
Step 1: Open IDE and create a Java Project
Step 2: Generate classes required for consumer using wsimport tool by giving wsdl URL as input
Syntax: wsimport –d src –keep –verbose WSDL_URL
Note: wsimport tool will be shipped as part of JDK itself
102 |P a ge
WebServices
After classes are generated -> Refresh the project - > we can see classes like below
Step 3: Develop Consumer class to access the provider
103 |P a ge
WebServices
Step 4: Run CalcServiceConsumer.java class
Contract First Approach
Step1: Create Dynamic web project and add jar files in project lib folder
104 |P a ge
WebServices
Step 2: Create WSDL file in project WEB-INF folder
---------------------------------------------WeatherService.wsdl Start---------------------------------------------
<?xml version="1.0" encoding="UTF-8"?>
<wsdl:definitions targetNamespace="http://service.weather.com"
xmlns:apachesoap="http://xml.apache.org/xml-soap"
xmlns:impl="http://service.weather.com"
xmlns:intf="http://service.weather.com" xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/"
xmlns:wsdlsoap="http://schemas.xmlsoap.org/wsdl/soap/"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<!--WSDL created by Apache Axis version: 1.4 Built on Apr 22, 2006 (06:55:48 PDT) -->
<wsdl:types>
<schema elementFormDefault="qualified"
targetNamespace="http://service.weather.com"
xmlns="http://www.w3.org/2001/XMLSchema">
<element name="getTemperature">
<complexType>
<sequence>
<element name="zip" type="xsd:int" />
</sequence>
</complexType>
</element>
<element name="getTemperatureResponse">
<complexType>
<sequence>
<element name="getTemperatureReturn"
type="xsd:double" />
</sequence>
</complexType>
</element>
</schema>
</wsdl:types>
<wsdl:message name="getTemperatureRequest">
<wsdl:part element="impl:getTemperature" name="parameters">
</wsdl:part>
</wsdl:message>
<wsdl:message name="getTemperatureResponse">
<wsdl:part element="impl:getTemperatureResponse" name="parameters">
</wsdl:part>
</wsdl:message>
<wsdl:portType name="WeatherService">
<wsdl:operation name="getTemperature">
<wsdl:input message="impl:getTemperatureRequest"
name="getTemperatureRequest">
</wsdl:input>
<wsdl:output message="impl:getTemperatureResponse"
name="getTemperatureResponse">
105 |P a ge
Web Services
</wsdl:output>
</wsdl:operation>
</wsdl:portType>
<wsdl:binding name="WeatherServiceSoapBinding" type="impl:WeatherService">
<wsdlsoap:binding style="document"
transport="http://schemas.xmlsoap.org/soap/http" />
<wsdl:operation name="getTemperature">
<wsdlsoap:operation soapAction="" />
<wsdl:input name="getTemperatureRequest">
<wsdlsoap:body use="literal" />
</wsdl:input>
<wsdl:output name="getTemperatureResponse">
<wsdlsoap:body use="literal" />
</wsdl:output>
</wsdl:operation>
</wsdl:binding>
<wsdl:service name="WeatherService">
<wsdl:port binding="impl:WeatherServiceSoapBinding" name="WeatherService">
<wsdlsoap:address
location="http://localhost:4040/WeatherWeb/services/WeatherServiceImpl" />
</wsdl:port>
</wsdl:service>
</wsdl:definitions>
-----------------------------------------------WeatherService WSDL End-------------------------------------------
Step-3:GenerateBindingclassesbasedonWSDLfileusingwsimporttool
Syntax:wsimport–dsrc–keep–verbosePATH_OF_WSDL
106 |P a ge
Web Services
Step 4: Create WeatherServiceImpl.java with business logic
Step 5: Create WebService deployment descriptor filein projectWEB-INF folder
(sun-jaxws.xml)
107 |P a ge
Web Services
Step 6: Configure WSServlet in web.xml file
Step 7: Deploy the application and access the Endpoint
Step 8: Test the Provider using SOAP UI tool
108 |P a ge
WebServices
SOAP Handlers
Handlersarethemessageinterceptorswhichdoesadditionalprocessingoftheinboundand
outbound messages.
Inbound messages are the request messages (client to web service)
Outbound messages are the response messages (web service to client)
Additional processing ofa SOAP message would beto add some additionalinformationto SOAP
headers or manipulate the values based on some condition etc.
Usecase-1:
AttachmostcommonlyusedparametersintheSOAPheaderusingahandlerattheclient
side.
Intheserverside,writeahandlerwhichcancheckthesecommonlyusedparametersfrom
the header and then produce the response from the cache if these parameters are found
otherwise get the data from the backend.
This way it will improve the web service performance.
Usecase-2:
In the client-side handler, add some client identityinformation in the SOAP header like IP
address of aclient
 In the server-side handler, extract the IP address from the SOAP header and check whether
it belongs to trusted IP addresses or not and then process it further if it’s a trusted IP else
throw an exception which can be sent as SOAP fault
JAX-WS provides 2 types of Message handlers
1. SOAP handlers
2. Logical handlers
SOAP handlers: SOAP handlers are the protocol specific handlers and they can access or change the protocol
specific aspect(likeheaders)of amessageand also,theycanalterthebodyof a SOAPmessage
Basically, SOAP handlers can access the entire SOAP message (header + body)
Logical handlers: Logical handlers are protocol-agnostic and cannot access or change any protocol-specific parts
(like headers) of a message.
They act only on the payload of the message.
Basically, Logical handlers can access only body of the message.
Note:ThemostpreferredhandleristheSOAPhandlerasitprovidesanaccesstotheentireSOAP
message (header +body)
109 |P a ge
Web Services
Message Context
Message context provides methods to access and modify the inbound and outbound messages.
It also provides some properties which can be used to determine whether message is inbound or outbound.
Each SOAP Handler should implement javax.xml.ws.handler.soap.SOAPHandler interface
Each Logical handlers should implement javax.xml.ws.handler.LogicalHandler interface
Messagecontextforlogicalhandlersisrepresentedbyjavax.xml.ws.handler.LogicalMessageContext
MessagecontextforSOAPhandlersisrepresentedby
javax.xml.ws.handler.soap.SOAPMessageContext
Message for logical handler is represented by javax.xml.ws.LogicalMessage
Message for SOAP handler is represented by javax.xml.soap.SOAPMessage
WecanwritebothSOAPhandlerandLogichandlerwithinahandlerchainbutinthiscase,logicalhandlers
will beexecuted before the SOAPhandlers onoutbound message and SOAP handlersareexecuted before the
logic handlers on inbound message. We can see that in below diagram
Web Services
110 |P a ge
How we define handlers?
To define a handler we just need to implement the handler interface and override the below 3 methods
1.handleMessage()
2.handleFault()
3.close()
handleMessage ( ) : This method will be called for both inbound and outbound messages Perform the additional
processing of the message in this method.
handleFault():ThismethodhandlestheprocessingofanySOAPfaultsgeneratedbythehandleMessage()
method, and also the faults generated by the back-end component
close():Thisiscalledafterthecompletionofmessageprocessingbyallhandlersforeachwebservice
invocation. Thismethod can be used to clean up all resources which are used during processing ofthe message.
Webservice development using SOAP Handler.
We are going to develop a Webservice provider i.e. AtmWeb. This Provider(IAtm.java) contains a withdraw(..)
methodtowithdrawmethod.Whenconsumersendrequestforwithdraw(..)method,firstIwanttovalidate
consumerusingaSecretKey.TovalidateconsumersentsecretkeyIamdevelopingAuthenticationHandler
(SOAP Handler). If secret-key is matched then consumer request will be processed and returns the successful
responseifsecret-keyisnotmatchedthenProvider willreturn SOAPFaultExceptionasaresponsetoConsumer.
As part of this Authentication Handler I am using Secret Key as  “Ashok-IT”
Web Services
111 |P a ge
Step-1: - Create a project like below
Provider contains below classes
AccountInfo.java, InvoiceInfo.java and TransactionInfo.java  Model classes
IAtm.java  Service Endpoint interface
AtmImpl.java  Service Endpoint Interface Implementation class
AuthenticationHandler.java  AuthenticationHandler tovalidate Secret Key
Handler-chain.xml  Handler Chain configuration file
Withdraw.java and WithdrawResponse.java  Binding classes
112 |P a ge
WebServices
Below are the model classes
Below are the Service Endpoint interface and Impl classes
113 |P a ge
WebServices
-----------------------------------------AuthenticateHandler.java start------------------------------------------------------
public class AuthenticateHandler implements SOAPHandler<SOAPMessageContext> {
//Choosing some secret key for validation
private static final String SECRET_KEY = "Ashok-IT";
@Override
public void close(MessageContext ctx) {
}
@Override
public boolean handleFault(SOAPMessageContext arg0) {
// TODO Auto-generated method stub
return false;
}
/**
* This method is used to handle inbound and outbound soap msgs
*/
@Override
public boolean handleMessage(SOAPMessageContext ctx) {
Boolean outbound = (Boolean) ctx.get(MessageContext.MESSAGE_OUTBOUND_PROPERTY);
if (!outbound) {
SOAPMessage soapMsg = ctx.getMessage();
try {
soapMsg.writeTo(System.out);
// Grabbing soap header from soap msg
SOAPHeader soapHeader = soapMsg.getSOAPHeader();
Iterator<?> headerIterator =
soapHeader.extractHeaderElements(SOAPConstants.URI_SOAP_ACTOR_NEXT);
// If soap header presented then process
if (headerIterator.hasNext()) {
Node node = (Node) headerIterator.next();
114 |P a ge
WebServices
if (node != null) {
String secretKey = node.getValue();
if (SECRET_KEY.equals(secretKey.trim())) {
// Key matching.. process the request
return true;
} else {
// Key did not match
// Throw SOAP Fault exception
generateSoapFaultException(soapMsg);
}
}
} else {
// Header is not there
// Throw SOAP Fault exception
generateSoapFaultException(soapMsg);
}
}catch(SOAPExceptione){
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
return true;
}
@Override
public Set<QName> getHeaders() {
// TODO Auto-generated method stub
return null;
}
115 |P a ge
WebServices
/**
* This method is used to generate SOAP Fault Exception when secret key is
* not matched
* @param soapMsg
*/
public void generateSoapFaultException(SOAPMessage soapMsg) {
SOAPBody soapBody;
try {
soapBody = soapMsg.getSOAPBody();
SOAPFault soapFault = soapBody.addFault();
soapFault.setFaultString("Secret Key is not matched...!!");
throw new SOAPFaultException(soapFault);
}catch(SOAPExceptione){
e.printStackTrace();
}
}
}
---------------------------------------------AuthenticateHandler.java End-----------------------------------------------
Below is the Handler-Chain configuration file
116 |P a ge
WebServices
Below are the Binding classes
Below is the Webservice description file
117 |P a ge
WebServices
Web Application Deployment Descriptor file
DeploytheProviderapplicationandaccessWSDLwithbelowURL
WSDL URL  http://localhost:4040/AtmWeb/withdraw?wsdl
If WSDL is accessible, provider is up and running
118 |P a ge
WebServices
AtmWeb-Consumer Development with SOAP Handler
Create a project
Create Client-Side stubs using WSDL URL  http://localhost:4040/AtmWeb/withdraw?wsdl
Below is the Consumer Side Handler class which is used to add Secret Key into soap message
--------------------------------------AtmWebConsumerHandler.java start----------------------------------------------
public class AtmWebConsumerHandler implements SOAPHandler<SOAPMessageContext> {
public boolean handleMessage(SOAPMessageContext context) {
System.out.println("Consumer : handleMessage() Begin");
Boolean outBoundProperty =
(Boolean) context.get(MessageContext.MESSAGE_OUTBOUND_PROPERTY);
// If its an outgoing message from client, then outBoundProperty will be
// true
if (outBoundProperty) {
try {
SOAPMessage soapMsg = context.getMessage();
SOAPEnvelope soapEnv = soapMsg.getSOAPPart().getEnvelope();
SOAPHeader soapHeader = soapEnv.getHeader();
119 |P a ge
WebServices
// if no header, add the header
if(soapHeader== null){
soapHeader = soapEnv.addHeader();
}
String secretKey = getSecretKey();
// add a soap header called "secretkey"
QName qname = new QName("http://service.atm.com/", "SecretKey");
SOAPHeaderElement soapHeaderElement =
soapHeader.addHeaderElement(qname);
soapHeaderElement.setActor(SOAPConstants.URI_SOAP_ACTOR_NEXT);
// Add Secret Key to SOAP header
soapHeaderElement.addTextNode(secretKey);
soapMsg.saveChanges();
//Outputthemessagetoconsole
soapMsg.writeTo(System.out);
}catch(SOAPExceptione){
System.err.println(e);
} catch (IOException e) {
System.err.println(e);
}
}
// Returning true makes other handler chain to continue the execution
return true;
}
publicbooleanhandleFault(SOAPMessageContextcontext){
System.out.println("Consumer : handleFault() Begin");
return true;
}
public void close(MessageContext context) {
System.out.println("Consumer : close() Begin");
}
120 |P a ge
WebServices
public Set<QName> getHeaders() {
System.out.println("Consumer : getHeaders() Begin");
return null;
}
private String getSecretKey() {
// This is the secret key which shared by provider
return "Ashok-IT";
}
}
--------------------------------------------------AtmWebConsumerHandler.java End----------------------------------------------
Add the @HandlerChain annotation in AtmImplService.java class like below
121 |P a ge
WebServices
Below is the Stub Based Consumer class to invoke Provider
122 |P a ge
WebServices
JAX-WS API with APACHE-AXIS2 IMPLEMENTATION
Apache Axis2 is a Web Services / SOAP / WSDL engine, the successor to the widely used Apache Axis
SOAP stack. There are two implementations of the Apache Axis2 Web services engine - Apache
Axis2/Java and ApacheAxis2/C.
Why Apache Axis2?
A new architecture for Axis2 was introduced during the August 2004 Summit in Colombo, Sri Lanka. The
new architecture on which Axis2 is based on is more flexible, efficient and configurable in comparison to
Axis1.x architecture. Some well-established concepts from Axis 1.x, like handlers etc., have been
preserved in the new architecture.
Apache Axis2 notonly supports SOAP 1.1 and SOAP 1.2,but it alsohasintegrated supportforthe widely
popularRESTstyleofWebservices.ThesamebusinesslogicimplementationcanofferbothaWS-*style
interface as well as a REST/POX style interface simultaneously.
Apache Axis2 is more efficient, more modular and more XML-oriented than the older version. It is
carefullydesignedtosupporttheeasyadditionofplug-in"modules"thatextendtheirfunctionalityfor
features such as security and reliability. The Modules currently available or under development include:
 WS-Security - Supported by Apache Rampart
 WS-Addressing -Module included as part of Axis2 core
Apache Axis2 is built on Apache AXIOM, a new high performant, pull-based XML object model.
Axis2 comes with many new features, enhancements and industry specification implementations. The
key features offered are as follows:
Speed-Axis2usesitsownobjectmodelandStAX(StreamingAPIforXML)parsingtoachievesignificantly
greater speed than earlier versions of Apache Axis.
Low memory foot print- Axis2 was designed ground-up keeping low memory foot print in mind.
AXIOM - Axis2 comes with its own light-weight object model, AXIOM, for message processing which is
extensible, highly performant and is developer convenient.
Hot Deployment - Axis2 is equipped with the capability of deploying Web services and handlers while
thesystemisupandrunning.Inotherwords,newservicescanbeaddedtothesystemwithouthaving
toshutdowntheserver.SimplydroptherequiredWebservicearchiveintotheservicesdirectoryinthe
repository,andthedeploymentmodelwillautomaticallydeploytheserviceandmakeitavailablefor
use.
Asynchronous Web services - Axis2 now supports asynchronous Web services and asynchronous Web
services invocation using non-blocking clients and transports.
123 |P a ge
WebServices MEP
Support-Axis2nowcomeshandywiththeflexibilitytosupportMessageExchangePatterns(MEPs) with
in-built support for basic MEPs defined in WSDL 2.0.
Flexibility - The Axis2 architecture gives the developer complete freedom to insert extensions into the
engineforcustomheaderprocessing,systemmanagement,andanythingelseyoucanimagine.
Stability-Axis2definesasetofpublishedinterfaces which changerelatively slowlycomparedtotherest
of Axis.
Component-orientedDeployment-YoucaneasilydefinereusablenetworksofHandlerstoimplement
common patterns of processing for your applications, or to distribute to partners.
Transport Framework - We have a clean and simple abstraction for integrating and using Transports
(i.e., senders and listeners for SOAP over various protocols such as SMTP, FTP, message-oriented
middleware, etc), and the core of the engine is completely transport-independent.
WSDLsupport-Axis2supportstheWebServiceDescriptionLanguage,version1.1and2.0,whichallows
you to easily build stubs to access remote services, and also to automatically export machine-readable
descriptions of your deployed services from Axis2.
Composition and Extensibility - Modules and phases improve support for composability and
extensibility. Modules support composability and can also support new WS-* specifications in a simple
and clean manner. They are however not hot deployable as they change the overall behavior of the
system.
Apache Axis2 software is coming in the form of two distributions
1) Binary Distribution
2) War Distribution
Binary Distribution: - which contains the Jar's and tools (Java2WSDL, WSDL2Java) that facilitate the
development of WebServices.
WarDistribution:-ActsasServer-SideRuntimeengineinwhichYourServicesaredeployedandexposed.
124 |P a ge
WebServices
Download Apache AXIS2 Distribution from below URL
Extract it into some suitable location
AfterDownloadingtheAxis2DistributionsfirstwecansetpathEnvironmentvariablesofAxis2binary
distributions.
125 |P a ge
Web Services
AftersettingtheEnvironmentvariablesforbinarydistributionwecandeploythe axis2.warfile
into any server
Then Check axis2 welcome page is opening (OR) not.
Configuring Apache AXIS-2 in Eclipse IDE
Step 1: Open Eclipse IDE Windows –> Preferences
Step2:BrowsethroughAxis-2preferencesandselectaxis-2distribution->ClickonApply- >Clickon
OK.
126 |P a ge
Web Services
That’s it!! we are done with installing Apache Axis2 plugin in Eclipse IDE
Now that we have installed Apache Axis2 plugin in Eclipse IDE and similarly configure Tomcat server
we will move on developing top-down approach using above configuration.
Developing JAX-WS API WebService using Apache – Axis2 implementation
Technology Used
Java 1.7
Eclipse Kepler IDE
Apache Axis2-1.6.2
Apache Tomcat-8.0.12
Step1:In Eclipse,createnew“Dynamic WebProject”
Step 2: Provide “Project Name” and make sure to change the “Dynamic web module version” to 2.5 –> click
Next
Step 3: By default, there will be “src” folder –> add “resources” folder to place XSD/WSDL using “Add
Folder…” button
Step 4: check “Generate web.xml” and Click Finish
Step 5: Initial project structure (Eclipse Package Explorer view)
127 |P a ge
Web Services
Step 6: Add Book Service WSDL and its associated XSD files under “resources” folder
BookService.wsdl
128 |P a ge
Web Services
Step 7: Right Click on Project –> New –> Web Service
Step 9: Configure required parameters
Web service type: Top down Java bean Web Service
Service definition: browse through WSDL file here
Configuration:
Server runtime: Tomcat 8.x server
Web service runtime: Apache Axis2
Service project: Project-name
129 |P a ge
Web Services
Step 11: accept default and click Next
Step 12: Click “Start Server”
Web Services
130 |P a ge
Step 13: This is optional –> accept default and click Finish
Step 14: After clicking Finish in the above step -> default endpoint implementation class will be opened in
Eclipse IDE
Step 15: Provide business logic to the endpoint class
Step 16: Web service implemented –> deploy the service to tomcat server
Deployment
Right click on project –> Run As –> Run on Server
Check whether web service is correctly deployed or not?
Step 17: This is home page, after deploying apache axis2 based web service in tomcat server. Click services
131 |P a ge
WebServices
Step 18: Click BookService to view wsdl of the deployed book service
IfweareabletoseetheWSDLinbrowserthatmeansourproviderisupandrunning.
We can test the provider using SOAP UI tool.
132 |P a ge
WebServices
Spring +JAXWS Web Services (SOAP) Integration Example:
133 |P a ge
WebServices
pom.xml
<projectxmlns="http://maven.apache.org/POM/4.0.0"xmlns:xsi="http://www.w3.org/2001/XML
Schema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-
v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.springjaxwsexample</groupId>
<artifactId>SpringJaxWsExample</artifactId>
<packaging>war</packaging>
<version>1.0</version>
<name>SpringJaxWsExample MavenWebapp</name>
<url>http://maven.apache.org</url>
<repositories>
<repository>
<id>java.net</id>
<url>http://download.java.net/maven/2</url>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>3.2.0.RELEASE</version>
</dependency>
<!-- JAX-WS-RI -->
<dependency>
<groupId>com.sun.xml.ws</groupId>
<artifactId>jaxws-rt</artifactId>
<version>2.2.3</version>
</dependency>
<!-- Library from java.net, integrate Spring with JAX-WS -->
<dependency>
<groupId>org.jvnet.jax-ws-commons.spring</groupId>
<artifactId>jaxws-spring</artifactId>
<version>1.8</version>
<exclusions>
<exclusion>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
</exclusion>
<exclusion>
134 |P a ge
Web Services
web.xml
<web-app>
<servlet>
<servlet-name>jaxwsservlet</servlet-name>
<servlet-class>
com.sun.xml.ws.transport.http.servlet.WSSpringServlet
</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>jaxwsservlet</servlet-name>
<url-pattern>/registerProduct</url-pattern>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
</exclusion>
<exclusion>
<groupId>com.sun.xml.stream.buffer</groupId>
<artifactId>streambuffer</artifactId>
</exclusion>
<exclusion>
<groupId>org.jvnet.staxex</groupId>
<artifactId>stax-ex</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.35</version>
</dependency>
<!-- https://mvnrepository.com/artifact/commons-pool/commons-pool -->
<dependency>
<groupId>commons-pool</groupId>
<artifactId>commons-pool</artifactId>
<version>1.6</version>
</dependency>
<!-- https://mvnrepository.com/artifact/commons-dbcp/commons-dbcp -->
<dependency>
<groupId>commons-dbcp</groupId>
<artifactId>commons-dbcp</artifactId>
<version>1.4</version>
</dependency>
</dependencies>
<build>
<finalName>SpringJaxWsExample</finalName>
</build>
</project>
135 |P a ge
WebServices
Note : ContextLoaderListener will create spring container.It searches the spring cfgfile name as
applicationContext.xml in WEB-INFfolder
Product.java
ProductDAO.java
</servlet-mapping>
<!-- Register Spring Listener -->
<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>
</web-app>
package com.springjaxwsexample.domain;
import java.io.Serializable;
publicclassProductimplements Serializable{
private Integer pid;
private String productName;
private Double price;
public Integer getPid() {
returnpid;
}
publicvoid setPid(Integer pid) {
this.pid = pid;
}
public String getProductName() {
returnproductName;
}
publicvoid setProductName(String productName) {
this.productName = productName;
}
public Double getPrice() {
returnprice;
}
publicvoid setPrice(Double price){
this.price = price;
}
}
package com.springjaxwsexample.dao;
import com.springjaxwsexample.domain.Product;
publicinterface ProductDAO {
publicint registerProduct(Product product);
}
136 |P a ge
WebServices
ProductDAOImpl.java
ProductService.java
ProductServiceImpl.java
package com.springjaxwsexample.dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import javax.sql.DataSource;
import com.springjaxwsexample.domain.Product;
publicclassProductDAOImplimplementsProductDAO{
private DataSource dataSource;//dependency
public void setDataSource(DataSource dataSource) {
this.dataSource = dataSource;
}
publicint registerProduct(Product product) {
intcount=0;
try{
Connection con=dataSource.getConnection();
String sql="insert into Product_Details values(?,?,?)";
PreparedStatement pst=con.prepareStatement(sql);
pst.setInt(1,product.getPid());
pst.setString(2,product.getProductName());
pst.setDouble(3,product.getPrice());
count=pst.executeUpdate();
}catch(SQLException se){
se.printStackTrace();
}
returncount;
}
}
package com.springjaxwsexample.service;
import com.springjaxwsexample.domain.Product;
public interface ProductService {
public boolean registerProduct(Product product);
}
package com.springjaxwsexample.service;
import com.springjaxwsexample.dao.ProductDAO;
import com.springjaxwsexample.domain.Product;
/** writing of this service is an optional
* in this class write Exception-Handling,Transaction-Management logic,loggers,Type-
Converstion,Bussiness logic's
* if we are not writing this separate service class then we include above logic directly in
webservice class
137 |P a ge
WebServices
ProductServiceWS.java
applicationContext.xml
*/
publicclass ProductServiceImpl implements ProductService{
private ProductDAO productDAO;
public void setProductDAO(ProductDAO productDAO) {
this.productDAO = productDAO;
}
public cboolean registerProduct(Product product) {
booleanflag=false;
intcount=productDAO.registerProduct(product);
if(count>0){
flag=true;
}
returnflag;
}
package com.springjaxwsexample.ws;
import javax.jws.WebMethod;
import javax.jws.WebService;
import com.springjaxwsexample.domain.Product;
import com.springjaxwsexample.service.ProductService;
@WebService
publicclass ProductServiceWs{
private ProductService productService;
@WebMethod(exclude=true)
public void setProductService(ProductService productService) {
this.productService = productService;
}
@WebMethod(exclude=false)
public Boolean registerProduct(Product product) {
Boolean flag=productService.registerProduct(product);
returnflag;
}
}
<beansxmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:ws="http://jax-ws.dev.java.net/spring/core"
xmlns:wss="http://jax-ws.dev.java.net/spring/servlet"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://jax-ws.dev.java.net/spring/core
http://jax-ws.dev.java.net/spring/core.xsd
http://jax-ws.dev.java.net/spring/servlet
http://jax-ws.dev.java.net/spring/servlet.xsd">
138 |P a ge
Web Services
Note: Test the above service by using SOAP UI tool.
<wss:bindingurl="/registerProduct">
<wss:service>
<ws:servicebean="#productServiceWs"/>
</wss:service>
</wss:binding>
<beanid="dataSource"class="org.apache.commons.dbcp.BasicDataSource">
<propertyname="driverClassName"value="com.mysql.jdbc.Driver"/>
<propertyname="url"value="jdbc:mysql://localhost:3306/nit"/>
<propertyname="username"value="root"/>
<propertyname="password"value="root"/>
</bean>
<beanid="productDAO"class="com.springjaxwsexample.dao.ProductDAOImpl">
<propertyname="dataSource"ref="dataSource"/>
</bean>
<beanid="productService"class="com.springjaxwsexample.service.ProductServiceImpl">
<propertyname="productDAO"ref='productDAO'/>
</bean>
<beanid="productServiceWs"class="com.springjaxwsexample.ws.ProductServiceWs">
<propertyname="productService"ref="productService"/>
</bean>
</beans>
139 |P a ge
Web Services
RestfulServices
Web Services
140 |P a ge
The term REST comes from Roy Fielding's PhD dissertation, published in 2000, and it stands for
REpresentationalStateTransfer.RESTbyitselfisnotanarchitecture;RESTisasetofconstraintsthat,
whenappliedtothedesignofasystem,createsasoftwarearchitecturalstyle.Ifweimplementallthe
RESTguidelinesoutlinedinFielding'swork,weendupwithasystemthathasspecificrolesfordata,
components, hyperlinks, communication protocols, and data consumers.
Fielding arrived at REST by evaluating all networking resources and technologies available for creating
distributed applications. Without any constraints, anything and everything goes, leading us to develop
applications that are hard to maintain and extend. He looks at document distributed application
architectural styles beginning with what he callsthe null space—which represents the availability of
every technology and every style of application development with no rules or limits—and ends with the
following constraints that define a RESTful system:
 It must be a client-server system
 Ithastobestateless—thereshouldbenoneedfortheservicetokeepusers'sessions;inother
words, each request should be independent of others
 It has to support a caching system—the network infrastructure should support cache at different
levels
 It hasto be uniformly accessible—each resource must have a unique address and a valid point of
access
 It has to be layered—it must support scalability
 Itshouldprovidecodeondemand—althoughthisisanoptionalconstraint,applicationscanbe
extendable at runtime by allowing the downloading of code on demand, for example, Java
Applets
These constraints don't dictate what kind of technology to use; they only define how data is transferred
between componentsandwhatarethebenefitsof followingtheguidelines. Therefore,a RESTful system
canbeimplementedinanynetworkingarchitectureavailable.Moreimportant,thereisnoneedforus
to invent new technologies or networking protocols: we can use existing networking infrastructures such
as the Web to create RESTful architectures. Consequently, a RESTful architecture is one that is
maintainable, extendable, anddistributed.
BeforeallRESTconstraintswereformalized,wealreadyhadaworkingexampleofaRESTfulsystem:that
ie Web.Wecanask,then,whytointroducetheseRESTfulrequirementstowebapplicationdevelopment
whenit'sagreedthattheWebisalreadyRESTful?-Weneedtofirstqualifyherewhatit'smeantforthe
Webto be RESTful.Ontheonehand,thestaticwebisRESTful, becausestaticwebsitesfollowFielding's
definition of a RESTful architecture. For instance, the existing web infrastructure provides caching
systems, stateless connection, and unique hyperlinks to resources, where resources are all of the
documents available on every website and the representations of these documents are already set by
files being browser readable (HTML files, for example).
Therefore, the static web is a system built on the REST-like architectural style. On the other hand,
traditionaldynamicwebapplicationshaven'talwaysbeenRESTful,becausetheytypicallybreaksomeof
the outlined constraints. For instance, most dynamic applications are not stateless, as servers require
tracking users through container sessions or client-side cookie schemes. Therefore, we conclude that
thedynamicwebisnotnormallybuiltontheREST-likearchitecturalstyle.Wecannowlookatthe
141 |P a ge
WebServices
abstractions that make a RESTful system, namely resources, representations, URIs, and the HTTP request
types that make up the uniform interface used for client/server data transfers.
Resources
A RESTful resource is anything that is addressable over the Web. By addressable, we mean resources
that canbe accessed andtransferredbetween clientsand servers.Subsequently, aresource isalogical,
temporalmappingtoaconcept in theproblem domainforwhich we are implementingasolution.
These are some examples of REST resources:
 A news story
 The temperature in NY at 4:00 p.m. EST
 A tax return stored in IRS databases
 A list of code revisions history in a repository like SVN or CVS
 A student in some classroom in some school
 A search result for a item in a web index, such as Google
Even though a resource's mapping is unique, different requests for a resource can return the same
underlying binary representation stored in the server. For example, let's say we have a resource within
thecontextofapublishingsystem.Then,arequestfor"thelatestrevisionpublished"andtherequest
for"revisionnumber12"willatsomepointintimereturnthesamerepresentationoftheresource:the
last revision is revision12.However, when thelatestrevision published isincreasedto version13,a
requesttothelatestrevisionwillreturnversion13,andarequestforrevision12willcontinuereturning
version12.AsresourcesinaRESTfularchitecture,eachoftheseresourcescanbeaccesseddirectlyand
independently, but different requests could point to the same data.
Because we areusing HTTP to communicate, we can transfer anykind ofinformation that can bepassed
between clients and servers. For example, if we request a text file from CNN, our browser receives a text
file.IfwerequestaFlashmoviefromYouTube,ourbrowserreceivesaFlashmovie.Thedataisstreamed
inbothcasesoverTCP/IPandthebrowserknowshowtointerpretthebinarystreamsbecauseofthe
HTTPprotocolresponseheaderContent-Type.Consequently,inaRESTfulsystem,therepresentationof
a resource depends on the caller's desired type (MIME type), which is specified within the
communication protocol's request.
Representation
The representation of resources is what is sent back and forth between clients and servers. A
representation is a temporal state of the actual data located in some storage device at the time of a
request. In general terms, it's a binary stream together with its metadata that describes how the stream
istobeconsumedbyeithertheclientortheserver(metadatacanalsocontainextrainformationabout
the resource, for example, validation, encryption information, or extra code to be executed at runtime).
Throughoutthelifeof aweb service theremaybea varietyof clientsrequestingresources.Different
clients are able to consume different representations of the same resource. Therefore, a representation
cantakevariousforms,suchasanimage,atextfile,oranXMLstreamoraJSONstream,buthastobe
available through the same URI.
142 |P a ge
WebServices
Forhuman-generatedrequeststhroughawebbrowser,arepresentationistypicallyintheformofan
HTML page. For automated requests from other web services, readability is not asimportant and a more
efficient representation can be used such as XML.
URI
A Uniform Resource Identifier, or URI, in a RESTful web service is a hyperlink to a resource, and it's the
only means for clients and servers to exchange representations. The set of RESTful constraints don't
dictatethat URIs must be hyperlinks. We onlytalkabout RESTfulURIs beinghyperlinks, because we are
using theWeb to create web services. If we were using a different set of supporting technologies, a
RESTfulURIwouldlookcompletelydifferent.However,thecoreideaofaddressabilitywouldstillremain.
In a RESTful system, the URI is not meant to change over time, as the architecture's implementation is
what managesthe services, locatestheresources, negotiatesthe representations, andthen sendsback
responses with the requested resources. More important, if we were to change the structure of the
storage device at the server level (swapping database servers, for example), our URIs will remain the
sameandbevalidforaslongthewebserviceisonlineorthecontextofaresourceisnotchanged.
WithoutRESTconstraints,resourcesareaccessedbylocation:typicalwebaddressesarefixedURIs.For
instance, if we rename a file on a web server, the URI will be different; if we move a file to a different
directory tree in a web server, the URI will change. Note that we could modify our web servers to execute
redirectsatruntimetomaintainaddressability,butifweweretodothisforeveryfilechange,ourrules
would becomeunmanageable.
Uniform interfaces through HTTP requests
In previous sections, we introduced the concepts of resources and representations. We said that
resources are mappings of actual entity states that are exchanged between clients and servers.
Furthermore, we discussed that representations are negotiated between clientsand servers throughthe
communicationprotocolatruntime—throughHTTP.Inthissection,welookindetailatwhatitmeans
toexchangetheserepresentations,andwhatitmeansforclientsandserverstotakeactionsonthese
resources.
Developing RESTful web services is similar to what we've been doing up to this point with our web
applications.However,thefundamentaldifferencebetweenmodernandtraditionalwebapplication
development is how we think of the actions taken on our data abstractions. Specifically, modern
development is rooted in the concept of nouns (exchange of resources); legacy development is rooted
in the concept of verbs (remote actions taken on data). With the former, we are implementing a RESTful
web service; with the latter, we are implementing an RPC-like service (Remote Procedure Call). What's
more, a RESTful service modifies the state of the data through the representation of resources; an RPC
service,ontheotherhand,hidesthedatarepresentationandinsteadsendscommandstomodifythe
state of the data at the server level (we never know what the data looks like).
Finally,in modern web application development we limit design andimplementation ambiguity, because
we have four specific actions that we can take upon resources—Create, Retrieve, Update, and Delete
(CRUD). On the other hand, in traditional web application development, we can have countless actions
with no naming or implementation standards.
143 |P a ge
WebServices
Therefore,withthedelineated rolesforresourcesand representations,we can nowmapourCRUD
actions to the HTTP methods POST, GET, PUT, and DELETE as follows:
Intheirsimplestform,RESTfulwebservicesarenetworkedapplicationsthatmanipulatethestateof
resources. In this context, resource manipulation means resource creation, retrieval, update, and
deletion. However, RESTful web services are not limited to just these four basic data manipulation
concepts. On the contrary, RESTful web services can execute logic at the server level, but remembering
that every result must be a resource representation of the domain at hand.
Let'snowlookatthefourHTTPrequesttypesindetailandseehoweachofthemisusedtoexchange
representations to modify the state of resources.
GET/RETRIEVE: The method GET is used to RETRIEVE resources.
Before digging into the actual mechanics of the HTTP GET request, first, we need to determine what a
resourceisinthe context of ourwebservice andwhat typeof representation we'reexchanging.
Fortherestofthissection,we'llusetheartificialexampleofawebservicehandlingstudentsinsome
classroom, with a location of http://ashokit.com/. For this service, we assume an XML representation of
a student to look as follows:
And a list of students to look like:
144 |P a ge
Web Services
With our representations defined, we now assume URIs of the form http://ashokit.com/students to
access a list of students, and http://ashokit.com/students/{name} to access a specific student that has
the unique identifier of value name.
We can now begin making requests to our web service. For instance, if we wanted the record for a
student with the name Jane, we make a request to the URI http://ashokit.com/students/Jane. A
representation of Jane, at the time of the request, may look like:
Subsequently, we can access a list of students through the URI http://ashokit.com/students. The
responsefromtheservicewillcontaintherepresentationofallstudentsandmaylooklike(assuming
there are two students available):
Now let's have a look at the request details. A request to retrieve a Jane resource uses the GET method
with the URI http://ashokit.com/students/Jane. A sequence diagram of our GET request looks as
follows:
145 |P a ge
Web Services
What's happening in the above GET request?
1. A Java client makes an HTTP request with the method type GET and Jane as the identifier for
the student.
2. The client setsthe representation type it can handle through the Acceptrequest headerfield.
3. ThewebserverreceivesandinterpretstheGETrequesttobearetrieveaction.Atthispoint,
thewebserverpassescontroltotheRESTfulframeworktohandletherequest.Notethat
RESTful frameworks don't automatically retrieve resources, as that's not their job. The job of a
framework isto easetheimplementation of the REST constraints. Business logic and storage
implementation is the role of the domain-specific Java code.
4. Theserver-sideprogramlooksfortheJaneresource.Findingtheresource couldmeanlooking
for it in a database, a filesystem, or a call to a different web service.
5. OncetheprogramfindsJane,itconvertsthebinarydataoftheresourcetotheclient's
requested representation.
6. WiththerepresentationconvertedtoXML,theserversendsbackanHTTPresponsewitha
numericcodeof200togetherwiththeXMLrepresentationasthepayload.Notethatifthere
areanyerrors,theHTTPserverreportsbackthepropernumericcode,butit'suptotheclient
to correctly deal with the failure.
Allthe messagesbetween clientandserverare standardHTTP protocol calls.For everyretrieve action,
we send a GET request and we get an HTTP response back with the payload of the response being the
representationoftheresourceor,ifthereisafailure,acorrespondingHTTPerrorcode(forexample,
404 if a resource is not found; 500, if there is a problem with the Java code in the form of an
exception).
146 |P a ge
Web Services
POST/CREATE: The method POST is used to CREATE resources.
Because we are creating a student, we usethe HTTP method POST. Again,the URI to create anew
student in our list is http://restfuljava.com/students/Jane. The method type for the request is set by
the client.
Assume Jane didn't exist in our list, and we want to add her. Our new Jane XML representation looks
like:
Notethatthelinkelementispartoftherepresentation,butit'semptybecausethisvalueisgenerated
atruntimeandnotcreatedbytheclientsendingthePOSTrequest.Thisisjustaconventionforthis
example; however, clients using a web service can dictate the structure of URIs.
Now, the sequence diagram of our POST request looks as follows:
147 |P a ge
Web Services
What'shappeninginabovePOSTrequest?
1. A Java client makes a request to the URI http://ashokit.com/students/Jane, with the HTTP
method set toPOST.
2. The POST request carries with it the payload in the form of an XML representation of Jane.
3. The server receives the request and lets the REST framework handle it; our code within the
framework executes the proper commands to storethe representation (again,the storage device
could be anything).
4. Once storingofthenewresourceiscompleted, aresponseissent back: ifit'ssuccessful, wesend
a code of 200; if it's a failure, we send the appropriate error code.
PUT/UPDATE: The method PUT is used to UPDATE resources.
Toupdatearesource,wefirstneeditsrepresentationintheclient;second,attheclientlevelweupdate
theresourcewiththenewvalue(s)wewant;and,finally,weupdatetheresourceusingaPUTrequest
together with the representation as its payload.
We're omitting the GET request to retrieve Jane from the web service, as it's the same one we illustrated
intheprevioussection.Wemust,however,modifytherepresentationattheclientlevelfirst.Assume
that we already have the student representation of Jane in the client and we want to change her age
from 10 to12.
148 |P a ge
Web Services
Our original student representation looks as follows:
Changing Jane's age to 12, our representation looks as follows:
We are now ready to connect to our web service to update Jane by sending the PUT request to
http://ashokit.com/students/Jane. The sequence diagram of our PUT request looks as follows:
What's happening in above PUT request?
1. A Java client makes a PUT request to http://ashokit.com/students/Jane, with the new XML
definition as itspayload.
2. TheserverreceivestherequestandletstheRESTframeworkhandleit.Atthispoint,weletour
code execute the proper commands to update the representation of Jane.
3. Once completed, a response is sent back.
149 |P a ge
WebServices
DELETE/DELETE: The method DELETE is used to DELETE representations.
Finally, deleting a resource makes use of the same URI we've used in the other three cases.
Assume we want to delete Jane from our data storage. We send a DELETE request to our service with
the URI http://ashokit.com/students/Jane.
The sequence diagram for our DELETE request looks like:
What's happening in above DELETE request?
1. A Java client makes a DELETE request to http://ashokit.com/students/Jane.
2. TheserverreceivestherequestandletstheRESTframeworkhandleit.Atthispoint,ourcode
executes the proper commands to delete the representation of Jane.
3. Once completed, a response is sent back.
150 |P a ge
WebServices
JAX-RS-> JAX-RS is API from sun .
JAX-RS API is used to develop/access the Restful services in java platform.
JAX-RS stands for Java API For Xml Restfull services.
JAX-RS Versions 0.x ,1.x (1.0, 1.1),2.x
JAX-RS 2.0 is the latest release of JAX-RS.
JAX-RS uses annotations,introduced in Java SE 5, to simplify the development and deployment
of Restful services resources andclients.
From version JAX-RS 1.1 on words , JAX-RS is an official part of Java EE 6
The Java API for RESTful Services provides portable APIs for developing, exposing and accessing
Webapplicationsdesignedandimplemented incompliancewithprinciplesof RESTarchitectural
style.
Implementations of Jax RS API:-
Apache CXF, an open source Web service framework
Jersey, the reference implementation from Sun (now Oracle)
RESTeasy, JBoss'simplementation
Restlet from jerome Louvel.
Apache Wink, Apache Software Foundation
Difference between SOAP and Restful services
In soap webservices we can use only xml to make communication between the client and server
provider.
InRestfullwebservicewecanmakecommunitactioninbetweenserverproviderandclientusing
 XML
 JSON (javascriptObjectNotation)
 text
 HTML
Soap WebService supports both server level and application level security
But Restfulservicessupportonlyserver levelsecuritybutnotfortheApplicationlevelsecurity.
What is aResource?
In REST architecture, everything is a resource. These resources can be text files, html pages, images,
videos or dynamic business data. REST Server simply provides access to resources and REST client
accesses and modifiestheresources. Hereeach resource isidentified byURIs. REST uses various
151 |P a ge
WebServices
representationstorepresentaresource liketext, JSON, XML. XML and JSONarethemostpopular
representations of resources.
Representation of Resources
A resource in REST is similar Object in Object Oriented Programming. Once a resource isidentified then
its representation is to be decided using a standard format so that server can send the resource in above
said format and client can understand the same format.
Forexample,inRESTfulWebServices- UserisaresourcewhichisrepresentedusingfollowingXML
format:
Same resource can be represented in JSON format:
JSON:
JSON stands for JavaScript Object Notation
JSON is also communicator like xml is between two language Applications.
<user>
<id>101</id>
<name>Mahesh</name>
<profession>Former</profession>
</user>
{
"id":101,
"name":"Mahesh",
"profession":"Former"
}
152 |P a ge
WebServices
we can apply Restriction xml document to accept the data by using DTD or XSD.
JSON we can't restrict to accept the data because it is normal text document.
JSON format is interoperable format
interoperable->lang independent and platform independent
JSONformat is very lightweight format compared to SOAP/XML.
JSON a is text-based document
Ex:-
{"studentId":101,"name":"raja","course":"java"}
 To read the JSON format data from the java application andto construct JSON format data bythe
java application we require JSON API.
Different vendors provided JSON API for the java language.
1. Jackson API
2. Gson (Google sun)API
3. JSON simple API
ByusingalltheaboveAPI’sfromjavaapplicationwecanconvertjavaobjecttojsonformatandjson
format to javaobject.
JSON Example with Jackson API:
1)Jackson API
Provides Object Mapper class that is used to convert java obj into json and json into java obj.
ObjectMapper class important methods
 public String writeValueAsString (-)-->used to convert java obj into json
 public T readValue(-)-->used to convert json into java obj
 JACKSON API is having two versions 1.x and 2.x versions
 if we are using Jackson 1.x version we can use the following jar's
153 |P a ge
Web Services
 jackson-core-asl jar
 jackson-mapper-asl jar
 the same above jar's if we want get with maven we can add the following dependencies in
pom.xml
 if we are using jackson 2.x version we can following jar's
 jackson-core jar
 jackson-annotations jar
 jackson-databinding jar
 with maven if we want to get the jar' we can add following dependencies in pom.xml file
154 |P a ge
Web Services
155 |P a ge
Web Services
156 |P a ge
Web Services
GSON Api to work with JSON Data
Create project like below
Add Gson maven dependency in pom.xml file like below
157 |P a ge
WebServices
Below is the model class to hold the data
Below class is used to convert Object data to Json data
158 |P a ge
WebServices
Below file contains data in json format
Below class is used to convert Json data into Java object
Jersey implementation:
In order to simplify development of RESTful Web services and their clients in Java, a standard and
portable JAX-RS API has been designed. Jersey RESTful Web Services implementation is an open source,
production quality ,used for developing RESTful Web Services in Java that provides support for JAX-RS
APIs and serves as a JAX-RS (JSR 311 & JSR 339) Reference Implementation.
Download the Jersey jar’s from ->https://jersey.java.net/
 Jersey implementation is given by sun and it is having two versions 1.x and 2.x
 Jersey 1.x provided Servlet com.sun.jersey.spi.container.servlet.ServletContainer
 Jersey 2.x provided Servlet org.glassfish.jersey.servlet.ServletContainer
159 |P a ge
WebServices
Steps to develop the Restful application:
step1: - create Root Resource class
step2: - create resource methods to expose
Step3: - configure the servlet in web.xml
(The Servlet is providing by JAX-RS API implementations)
step4: - deploy the app into server
Root Resource
 It is a server-side class which contains the data and functionality which is exposed as Resource
class to theClient.
 Root resource classesare simplejava classesthatare annotated with @Path annotation.
 TheResourceclassmethodsarerequiredtodenotewithresourcemethoddesignatorannotation
such as @GET, @PUT, @POST, @DELETE.
 Resourcemethodsaremethodsofaresourceclassannotatedwitharesourcemethoddesignator
annotation and exposing over the Network.
Root Resource class Example to produce JSON Response:
 Any class that is annotated with @Path Annotation is called as root Resource class.
 IntheRestfullservicestheResourcesclassesareassociatedwithURItoidentifyandaccessit.
 The @Path annotation's value is a relative URI path. In the example above, the Java class will be
hosted at the URI path /products.
Request Method Designator:
In the Resource classwrite themethodswhich wewanttoexposetheoverthe Httpprotocolsasresource
methods .The Methods should be annotated with relevant Http method designators like
@GET,@POST,@PUT and@DELETE.
 WhenwesentaGETrequestthemethodwith@GETannotationwouldbeexecutedtohandle
the request.
@Path("products")
public class ProductService{
@GET
@Path("getProduct")
@Produces(MediaType.APPLICATION_JSON)
// indicates the java method will produces content/response in JSON format
public ProductsearchProduct(){
//logic
}
}
160 |P a ge
WebServices
 @GET, @PUT, @POST, @DELETE and @HEAD are resource method designator annotations
defined by JAX-RS and which correspond to the similarly named HTTP methods. In the example
above, the annotated Java method will process HTTP GET requests.
Http Annotations
• @javax.ws.rs.GET
• @javax.ws.rs.POST
• @javax.ws.rs.PUT
• @javax.ws.rs.DELETE
Resource method:
• AmethodinaresourceclassthatisannotatedwithRequestMethodDesignatoriscalledasResource
method.
• A lot of information we want pull from an HTTP request and injecting it into a Java method.
• You might be interested in a URI query string value.
• TheclientmightbesendingcriticalHTTPheadersorcookievaluesthatyourserviceneedstoprocess
the request.
• JAX-RSletsyougrabthisinformationasyouneedit,throughasetofinjectionannotationsandAPIs.
JAX-RS API Annotations
• @javax.ws.rs.Path
• @javax.ws.rs.Consumes
• @javax.ws.rs.Produces
• @javax.ws.rs.QueryParam
• @javax.ws.rs.PathParam
• @javax.ws.rs.HeaderParam
• @javax.ws.rs.FormParam
• @javax.ws.rs.CookieParam
• @javax.ws.rs.MatrixParam
• @javax.ws.rs.BeanParam
161 |P a ge
WebServices
JAX-RS Annotations Overview
@QueryParam:
It is used for receiving the data as input through query String parameters as shown below.
The client is the following URL to access the above Service
URL:- http://<hostName>:<portNum>/context-root /products/searchProduct?pid=101
162 |P a ge
WebServices
TheaboveURLshowsthequeryparampid=101where101valuewillbepassedasaninputto
parameter pid of the method.
The QueryParameters are name-value paris.
TheQueryParametersarestartswith?intheURLand ifmultipleQueryparametersarethere
separated with &symbol
Ex2: Resource method with Multiple Query-Parameters
URL:http://<hostName>:<portNum>/context-root/products/searchProduct?pid=101&pname=mouse
Jersy 1.x Application
Step-1: - Create Maven Web application
163 |P a ge
WebServices
Step-2:-AddJerseyMavenDependenciesinpom.xmlfile
Step-3:-Createadomainclass(ThisisBindingclass)
164 |P a ge
WebServices
Step-5: - Create Resource class
Step-6: - Configure Jersey Runtime Servlet in web.xml file like below
Step-7: - Deploy the application and test Rest resource using POSTMAN tool
165 |P a ge
WebServices
@Matrix Param:
Theideaofmatrixparametersisthattheyarean arbitrarysetof name-valuepairsembeddedinauri
path segment.
The Matrix Parameters are starts with semicolon and if multiple parameters are there then
separated with semicolon.
The Matrix Parameters are Name-Value Pairs.
Url to access car resource :
http://localhost:6060/FirstRestEasyWeb/rest/car/order/benz;color=red/2001
166 |P a ge
Web Services
@FormParam
• @FormParam to bind html form fields to your method inputs.
• It works for http method POST.
When register.html form got submitted, request comes to UserRegResource class registerUserInfo () method.
As part of this method we are capturing form data using @FormParam annotaion
@BeanParam
• The @BeanParam annotation issomething newadded in the JAX-RS 2.0 specification.
• It allows you to inject an application-specific class whose property methods orfields are annotated
with any of the injection parameters
Ifwedon’thave@BeanFormWeneedtowritemany@FormParamannotationstocaptureaform
data. If form contains 20 fields then we have to 20 parameters for the method which is not
recommended. Below image depicts the same.
167 |P a ge
Web Services
To avoid the above problem, we can create a model class to store form data
We can use @BeanParam to inject form data into model/bean object like below
JAX-RS provider automatically constructs and injects an instance of your domain object which you
can now use within your methods.
168 |P a ge
Web Services
Jersey Application with JSON Data
Step-1  Create Maven Web Application
Step-2  Add below maven dependencies in project pom.xml
169 |P a ge
WebServices
Step-3  Create a domain class to hold the data
Step-4CreateResourceclasswithresourcemethods
The above Resource having a get request method and post request method
POST request methodisusedtoadd the customer usingcustomerdatainJSON format
GET request method is used to retrieve Customer data in JSON format
170 |P a ge
WebServices
Step-5 Create web.xml file with below details
• In the above web.xml file we can see two init parameters
• Jersey.config.server.provider.packages is used to load all resource classes before getting request
(This will improve performance of the application). If we don’t write this everytime resource class
should be loaded from classpath.
• POJOMappingFeature init param is used to map json data to pojo and vice versa.
Step-6  Deploy the application and test it using POSTMAN
To test the above Resource we can use SOAPUITool/PostMan/RestClient tool (OR) write a client
application.
171 |P a ge
WebServices
@Consumes
The @Consumes annotation is used to specify which MIME media types of representations a
resource can accept, or consume, from the client. If @Consumes is applied at the class level, all
the response methods accept the specified MIME types by default. If @Consumes is applied at
themethodlevel,it overrides any@Consumesannotationsapplied at theclasslevel.
 IfaresourceisunabletoconsumetheMIMEtypeofaclientrequest,theJerseyruntimesends
back an HTTP “415 Unsupported Media Type” error.
The value of @Consumes is an array of Stringof acceptable MIME types. For example:
@Consumes ({"text/plain, text/html"})
ThefollowingExampleisshowinghowtoconsumethedatainXMLbyusing@Consumesannotation.
web.xml
ProductService.java
172 |P a ge
WebServices
We can test above service by using the following client application As follows
package com.nit.client;
import java.io.StringWriter;
import javax.ws.rs.core.MediaType;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import com.nit.domain.Product;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.api.client.WebResource.Builder;
public class Test {
public static void main(String [] args) throws JAXBException {
String URL = "http://hostName:portNum/contextpath/products/registerProduct";
Client client = Client.create();
WebResource webResource = client.resource(URL);
Builder builder = webResource.type(MediaType.APPLICATION_XML);
builder.accept(MediaType.TEXT_PLAIN);
Productproduct=newProduct();
product.setPid(201);
product.setPname("mouse");
product.setPrice(900.0);
JAXBContext jaxbContext = JAXBContext.newInstance(Product.class);
Marshaller marshaller = jaxbContext.createMarshaller();
StringWriter writer = newStringWriter();
marshaller.marshal(product, writer);
String productXML = writer.toString();
ClientResponse clientResponse = builder.post(ClientResponse.class,productXML);
String response = clientResponse.getEntity(String.class);
s.o.p (clientResponse.getStatus()+""+ clientResponse.getStatusInfo());
S.o.p (response);
}
}
173 |P a ge
WebServices
Product.java
package com.nit.domain;
Import java.io.Serializable;
Import javax.xml.bind.annotation.XmlAttribute;
Import javax.xml.bind.annotation.XmlElement;
Import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement(name="product")
public class Product implements Serializable{
private int pid;
private String pname;
private double price;
@XmlAttribute(name="pid")
public int getPid() {
return pid;
}
public void setPid(int pid) {
this.pid = pid;
}
@XmlElement
public String getPname() {
return pname;
}
public void setPname(String pname) {
this.pname = pname;
}
@XmlElement
public double getPrice() {
return price;
}
Public void setPrice(double price) {
this.price = price;
}
}
174 |P a ge
Web Services
Jersey 2.x Example
175 |P a ge
Web Services
176 |P a ge
Web Services
Web Services
177|P a
pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-
v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.jerseyserverexample</groupId>
<artifactId>Jersey_Book_Service_Provider</artifactId>
<packaging>war</packaging>
<version>1.0</version>
<name>Jersey_Book_Service_Provider MavenWebapp</name>
<url>http://maven.apache.org</url>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.containers</groupId>
<artifactId>jersey-container-servlet</artifactId>
<version>2.22.2</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.0.1</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.hynnet/oracle-driver-ojdbc6 -->
<dependency>
<groupId>com.hynnet</groupId>
<artifactId>oracle-driver-ojdbc6</artifactId>
<version>12.1.0.1</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.media</groupId>
<artifactId>jersey-media-json-jackson</artifactId>
<version>2.22.2</version>
</dependency>
<dependency>
<groupId>com.jerseyutil</groupId>
<artifactId>Jersey_Book_Service_Util</artifactId>
<version>0.0.1-SNAPSHOT</version>
</dependency>
</dependencies>
<build>
<finalName>Jersey_Book_Service_Provider</finalName>
</build>
</project> ge
Web Services
178 |P a ge
Web Services
179 |P a ge
Web Services
180 |P a ge
pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.jerseyclientexample</groupId>
<artifactId>Jersey_Book_Service_Client</artifactId>
<packaging>war</packaging>
<version>0.0.1-SNAPSHOT</version>
<name>Jersey_Book_Service_Client MavenWebapp</name>
<url>http://maven.apache.org</url>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.core</groupId>
<artifactId>jersey-client</artifactId>
<version>2.22.2</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.media</groupId>
<artifactId>jersey-media-json-jackson</artifactId>
<version>2.22.2</version>
Web Services
181 |P a ge
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.0.1</version>
</dependency>
<dependency>
<groupId>com.jerseyutil</groupId>
<artifactId>Jersey_Book_Service_Util</artifactId>
<version>0.0.1-SNAPSHOT</version>
</dependency>
</dependencies>
<build>
<finalName>Jersey_Book_Service_Client</finalName>
</build>
</project>
Web Services
182 |P a ge
Theclientobjis heavyweightobject.Itisalwaysrecomndedtoclosetheclientobjectafterconsuming
the resource.
The client obj Establish the connection b.w client app to server app.
If we are using Jersey 1.x we can use the following code in the place of above code
Web Services
183 |P a ge
jersey 1.x version client code
@FormParam :
InJAX-RS,youcanuse@FormParamannotationtobindHTMLformparametersvaluetoaJavamethod.
The following example show you how to do it:
Note:@FormParamisusedtobindhtmlformfieldstoyourmethodinputs.Itworksonlyforhttp
method POST.
First create a HTML page with Form Parameters
a simple HTML form with “post” method.
UserForm.html
public class BookServiceClient{
public ResponseDTO saveBookDetails(Book book){
StringURL="http://localhost:8082/Jersey_Book_Service_Provider/books/registerBook";
Client client = Client.create();
WebResource resource=client.resource(URL);
Builder builder =resource.accept(MediaType.APPLICATION_JSON);
builder.type(MediaType.APPLICATION_JSON);
ClientResponse
clientResponse=builder.post(ClientResponse.class,JsonUtil.convertJavaToJson(book));
String jsonResponse=clientResponse.getEntity(String.class);
ResponseDTO
responseDTO=JsonUtil.convertJsonToJava(jsonResponse,ResponseDTO.class);
return responseDTO;
}
}
<html>
<body>
<h1>JAX-RS @FormQuery Testing</h1>
<form action="user/register" method="post">
Name : <input type="text" name="name" />
Age : <input type="text" name="age" />
<input type="submit" value="Add User" />
</form>
</body>
</html>
184 |P a ge
WebServices
Create A Resource class to get Form Parameters
Note:
Access HTML Page. URL: http://localhost:8080/RESTfulExample/UserForm.html
Then click on Add User Button get the Output.
Example to use @FormParam and to get above HTML form parameter values.
import javax.ws.rs.FormParam;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.core.Response;
@Path("user")
public class UserService {
@POST
@Path("/register")
@Produces(“text/plian”)
publicStringaddUser(@FormParam("name")Stringname,
@FormParam("age") int age) {
return “addUser is called, name : " + name + ", age : " + age);
}
}
185 |P a ge
WebServices
Restful Resource Development without XML configuration
Step-1  Create Maven web project
Note: In the above application no web.xml file (delete web.xml file from WEB-INF folder)
Step-2 Configure jersey dependencies in project pom.xml file
Note : As we have deleted web.xml file we are writing <failOnMissingWebXml> propert to false so
that it will not check for web.xml file
186 |P a ge
WebServices
Step-3  Create Application Configuration class (Extends from Application class)
Step-4  Create a Resource class
Step-5  Deploy the application and test it using POSTMAN tool
187 |P a ge
Web Services
RestEasy Implementation:
REST Easy is a JBoss project that provides various frameworks to help you build RESTful Web
Services and RESTful Java applications. It isa fully certified and portable implementation of the
JAX-RS2.0specification, aJCP specificationthatprovidesaJava APIforRESTfulWeb Services over
the HTTP protocol. The REST Easy can run in any Servlet container
 We can download the Rest Easy jar’s from http://resteasy.jboss.org/downloads
188 |P a ge
Web Services
HelloResource.java
package com.nit.service;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
@Path("hello")
public class HelloResource {
@Path("/sayHello/{name}")
@Produces(MediaType.TEXT_PLAIN)
@GET
public String sayHello(@PathParam("name") String name){
return "Hello"+name+"Welcome to RestEasy";
}
}
189 |P a ge
Web Services
MyApplication.java
We can access the above webservice by using a client Application (OR) SOAP UI tool
190 |P a ge
WebServices
RestEasy Client Application
Test.java
191 |P a ge
WebServices
RestEasy-Bootstrapping Application
Step-1  Create Maven Web application
Step-2  Configure resteasy dependencies in project pom.xml file like below
Step-3  Create Application Configuration class like below
192 |P a ge
WebServices
Step-4  Create Resource class like below
Step-5  Create web.xml file like below
Below is the Client class to rest the above Rest Resource
193 |P a ge
WebServices
File Uploading with Restful Resource
Below is the Resource class to upload the file
194 |P a ge
WebServices
Postman screen shot to upload file (We can test the above FileUploadResource using postman)
To upload file from user interface we can use below html form
195 |P a ge
WebServices
Spring+RestFul services (Jersey Implementation) Integration Example
<projectxmlns="http://maven.apache.org/POM/4.0.0"xmlns:xsi="http://www.w3.org/2001/X
MLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-
v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.springjerseyexample</groupId>
<artifactId>SpringJerseyRestFullExample</artifactId>
<packaging>war</packaging>
<version>0.0.1-SNAPSHOT</version>
<name>SpringJerseyRestFullExample MavenWebapp</name>
<url>http://maven.apache.org</url>
196 |P a ge
WebServices Mr. As<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>3.0.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>3.0.5.RELEASE</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.35</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.sun.jersey/jersey-server -->
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-server</artifactId>
<version>1.8</version>
</dependency>
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-asl</artifactId>
<version>1.9.13</version>
</dependency>
<dependency>
hok
<groupId>com.sun.jersey.contribs</groupId>
<artifactId>jersey-spring</artifactId>
<version>1.8</version>
<exclusions>
<exclusion>
<groupId>org.springframework</groupId>
<artifactId>spring</artifactId>
</exclusion>
<exclusion>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
</exclusion>
<exclusion>
<groupId>org.springframework</groupId>
197 |P a ge
Web Services
Book.java
package com.jerseyexample.domain;
import java.io.Serializable;
public class Book implements Serializable{
private Integer isbn;
private String title,author,publication;
private Double price;
public Integer getIsbn() {
returnisbn;
}
public void setIsbn(Integer isbn) {
this.isbn = isbn;
}
public String getTitle() {
returntitle;
}
public void setTitle(String title) {
this.title = title;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
<artifactId>spring-web</artifactId>
</exclusion>
<exclusion>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
</exclusion>
<exclusion>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
</exclusion>
<exclusion>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
</exclusion>
</exclusions>
</dependency>
</dependencies>
<build>
<finalName>SpringJerseyRestFullExample</finalName>
</build>
</project>
198 |P a ge
Web Services
ResponseDTO.java
package com.jerseyexample.domain;
import java.io.Serializable;
public class ResponseDTO implements Serializable{
private byte status;
private String msg;
private String data;
public byte getStatus() {
return status;
}
public void setStatus(byte status) {
this.status = status;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public String getData() {
return data;
}
public void setData(String data) {
this.data = data;
}
}
this.author = author;
}
public String getPublication() {
return publication;
}
public void setPublication(String publication) {
this.publication = publication;
}
public Double getPrice() {
return price;
}
public void setPrice(Double price) {
this.price = price;
}
}
199 |P a ge
WebServices
BookDAO.java
BookDAOImpl.java
package com.jerseyexample.dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import com.jerseyexample.domain.Book;
@Repository
public class BookDAOImpl implements BookDAO{
@Autowired
private DataSource dataSource;
public int registerBook(Book book) {
int count=0;
Connection con=null;
try{
con=dataSource.getConnection();
String sql="insert into Book_Details values(?,?,?,?,?)";
PreparedStatement pst=con.prepareStatement(sql);
pst.setInt(1,book.getIsbn());
pst.setString(2,book.getTitle());
pst.setDouble(3,book.getPrice());
pst.setString(4,book.getAuthor());
pst.setString(5,book.getPublication());
count=pst.executeUpdate();
}catch(SQLException se){
se.printStackTrace();
}finally{
if(con!=null){
try{
con.close();
}catch(SQLException se){
se.printStackTrace();
}
}
}
return count;
}
}
package com.jerseyexample.dao;
import com.jerseyexample.domain.Book;
public interface BookDAO {
public int registerBook(Book book);
}
200 |P a ge
WebServices
BookService.java
package com.jerseyexample.service;
import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.jerseyexample.dao.BookDAO;
import com.jerseyexample.domain.Book;
import com.jerseyexample.domain.ResponseDTO;
import com.jerseyexample.util.JsonUtil;
@Path("books")
@Service
publicclass BookService{
@Autowired
private BookDAO bookDAO;
@POST
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
@Path("/registerBook")
public String registerBook(String jsonBook){
System.out.println("Entered into registerBook ::"+jsonBook);
Book book=JsonUtil.convertJsonToJava(Book.class,jsonBook);
String msg="Registration Is Failure!Please Try Again";
ResponseDTO responseDTO=new ResponseDTO();
responseDTO.setMsg(msg);
int count=bookDAO.registerBook(book);
if(count>0){
msg="Registration Is Success";
responseDTO.setMsg(msg);
responseDTO.setStatus((byte)1);
responseDTO.setData(book.getIsbn().toString());
}
System.out.println("Response of registerBook ::"+responseDTO.getMsg());
String jsonResponseDTO=JsonUtil.convertJavaToJson(responseDTO);
return jsonResponseDTO;
}
}
201 |P a ge
WebServices
JsonUtil.java
package com.jerseyexample.util;
import java.io.IOException;
import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
public class JsonUtil {
publicstatic<T>TconvertJsonToJava(Class<T>cls,String json){
T response=null;
ObjectMapper mapper=new ObjectMapper();
try {
response=mapper.readValue(json,cls);
}catch(JsonParseExceptione){
e.printStackTrace();
} catch (JsonMappingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return response;
}
publicstaticStringconvertJavaToJson(Object obj){
String jsonStr="";
ObjectMapper mapper=new ObjectMapper();
try {
jsonStr=mapper.writeValueAsString(obj);
} catch (JsonGenerationException e) {
e.printStackTrace();
} catch (JsonMappingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return jsonStr;
}
}
202 |P a ge
WebServices
web.xml
applicationContext.xml
<web-app>
<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<servlet>
<servlet-name>jersey-serlvet</servlet-name>
<servlet-class>
com.sun.jersey.spi.spring.container.servlet.SpringServlet</servlet-class>
<init-param>
<param-name>com.sun.jersey.config.property.packages</param-name>
<param-value>com.jerseyexample.service</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>jersey-serlvet</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
</web-app>
<beansxmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<beanid="dataSource"class="org.springframework.jdbc.datasource.DriverManagerD
ataSource">
<propertyname="driverClassName"value="com.mysql.jdbc.Driver"/>
<propertyname="url"value="jdbc:mysql://localhost:3306/nit"/>
<propertyname="username"value="root"/>
<propertyname="password"value="root"/>
</bean>
<context:component-scanbase-
package="com.jerseyexample.service,com.jerseyexample.dao"/>
</beans>
203 |P a ge
WebServices
The Following Client Application is used to Test Above Restful Service
pom.xml
<projectxmlns="http://maven.apache.org/POM/4.0.0"xmlns:xsi="http://www.w3.org/
2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.restclient.client</groupId>
<artifactId>JerseyClientExample</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name> JerseyClientExample </name>
<url>http://maven.apache.org</url>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-client</artifactId>
<version>1.19.1</version>
</dependency>
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-asl</artifactId>
<version>1.9.13</version>
</dependency>
</dependencies>
</project>
204 |P a ge
WebServices
Book.java
package com.restclient.domain;
import java.io.Serializable;
public class Book implements Serializable {
private Integer isbn;
private String title,author,publication;
private Double price;
public Integer getIsbn() {
return isbn;
}
public void setIsbn(Integer isbn) {
this.isbn = isbn;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public String getPublication() {
return publication;
}
public void setPublication(String publication) {
this.publication = publication;
}
public Double getPrice() {
return price;
}
public void setPrice(Double price) {
this.price = price;
}
}
205 |P a ge
WebServices
Test.java
package com.restclient.client;
import java.io.IOException;
import javax.ws.rs.core.MediaType;
import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
import com.restclient.domain.Book;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.api.client.WebResource.Builder;
public class Test{
publicstaticvoidmain(String[]args)throwsJsonGenerationException,
JsonMappingException, IOException{
String URL="http://localhost:8090/SpringJerseyRestFullExample/books/registerBook";
Book book=new Book();
book.setIsbn(302);
book.setTitle("java");
book.setPrice(1900.0);
book.setPublication("nit");
book.setAuthor("jhon");
ObjectMapper mapper=new ObjectMapper();
String jsonBook=mapper.writeValueAsString(book);
System.out.println(jsonBook);
Client client=Client.create();
WebResource resource=client.resource(URL);
Builder builder=resource.accept(MediaType.APPLICATION_JSON);
builder.type(MediaType.APPLICATION_JSON);
ClientResponse clientResponse=builder.post(ClientResponse.class,jsonBook);
System.out.println(clientResponse.getStatus()+" "+clientResponse.getStatusInfo());
System.out.println(clientResponse.getEntity(String.class));
}
}
206 |P a ge
WebServices
Spring Rest-API Example:
pom.xml
<projectxmlns="http://maven.apache.org/POM/4.0.0"xmlns:xsi="http://www.w3.org/2001
/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.springrestexample</groupId>
<artifactId>SpringRestExample</artifactId>
<packaging>war</packaging>
<version>0.0.1-SNAPSHOT</version>
<name>SpringRestExample MavenWebapp</name>
<url>http://maven.apache.org</url>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>4.0.5.RELEASE</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
207 |P a ge
WebServices
User.java
<version>3.0.1</version>
</dependency>
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-asl</artifactId>
<version>1.9.13</version>
</dependency>
</dependencies>
<build>
<finalName>SpringRestExample</finalName>
</build>
</project>
package com.springrestexample.domain;
publicclass User {
privateintuserId;
private String userName;
private String email,mobile;
publicint getUserId() {
returnuserId;
}
publicvoid setUserId(intuserId) {
this.userId = userId;
}
public String getUserName() {
returnuserName;
}
publicvoid setUserName(String userName) {
this.userName = userName;
}
public String getEmail() {
returnemail;
}
publicvoid setEmail(String email){
this.email = email;
}
publicStringgetMobile(){
returnmobile;
}
publicvoid setMobile(String mobile){
this.mobile = mobile;
}
}
208 |P a ge
WebServices
UserService.java
UserServiceImpl.java
package com.springrestexample.service;
publicinterface UserService {
public String getUserDetails(Integer userId);
}
package com.springrestexample.service;
import org.springframework.stereotype.Service;
import com.springrestexample.domain.User;
import com.springrestexample.util.JsonUtil;
@Service
publicclass UserServiceImpl implements UserService{
public String getUserDetails(Integer userId) {
String jsonUser="{}";
if(userId!=null&&userId.equals(101)){
User user=new User();
user.setUserId(101);
user.setUserName("rama");
user.setEmail("rama@gmail.com");
user.setMobile("999999");
jsonUser=JsonUtil.javaToJson(user);
}
returnjsonUser;
}
}
209 |P a ge
WebServices
JsonUtil.java
package com.springrestexample.util;
import java.io.IOException;
import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
publicclass JsonUtil {
publicstatic String javaToJson(Object obj){
String jsonStr="{}";
ObjectMapper mapper=new ObjectMapper();
try {
jsonStr=mapper.writeValueAsString(obj);
} catch (JsonGenerationException e) {
e.printStackTrace();
} catch (JsonMappingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
returnjsonStr;
}
publicstatic<T>T jsonToJava(Class<T>cls,String str){
T response=null;
ObjectMapper mapper=new ObjectMapper();
try {
response=mapper.readValue(str,cls);
}catch(JsonParseExceptione){
e.printStackTrace();
} catch (JsonMappingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
returnresponse;
}
}
210 |P a ge
WebServices
UserController.java
web.xml
package com.springrestexample.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.springrestexample.service.UserService;
@RestController
publicclass UserController {
@Autowired
private UserService userService;
@RequestMapping(value="getUserInfo/{userId}",method=RequestMethod.GET)
@ResponseBody
public String getUserDetails(@PathVariable("userId") Integer userId){
String jsonUser=userService.getUserDetails(userId);
returnjsonUser;
}
}
<web-app>
<servlet>
<servlet-name>spring</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>spring</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
211 |P a ge
WebServices
spring-servlet.xml
TheRestTemplateclassisgivenbyspringframeworktoaccesstheRestfulservicesintheeasymanner.
Test.java
<beansxmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<context:component-scan
base-package="com.springrestexample.controller,com.springrestexample.service"/>
</beans>
package com.springrestclientexample;
import java.util.HashMap;
import java.util.Map;
import org.springframework.web.client.RestTemplate;
publicclass Test{
publicstaticvoid main( String[] args ) {
String url="http://localhost:8082/SpringRestServerEx/getUserInfo/{userId}";
RestTemplate restTemplate=new RestTemplate();
Map<String,Object>map=new HashMap<String, Object>();
map.put("userId",101);
String jsonUser=restTemplate.getForObject(url,String.class,map);
System.out.println(jsonUser);
}
}
212 |P a ge
WebServices
Response class:
Response class is present in javax.ws.rs.core package.
Defines the contract between a returned instance and the runtime when an application needs
to provide metadata to the runtime.
An application class can extend this class directly or can use one of the static methods to create
an instance of this class .
ThefollowingExampleisshowinghowtouseResponseclassasareturntypeto
resource method
The following Example is showing how to use XML format data with Response obj
Student.java
package com.nareshit.domain;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement
publicclassStudent{
privateIntegersid;
privateStringname;
//settersandgetters
}
package com.nareshit.service;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.core.Response;
@Path("hello")
public class HelloWorldService {
@GET
@Path("/sayHello/{name}")
public Response getMsg(@PathParam("name") String name) {
String output = "Hello : " + name+” Welcome “;
return Response.status(200).entity(output).build();
}
}
public class StudentService {
@GET
@Path("/getStudentDetails/{sid}")
@Produces(MediaType.APPLICATION_XML)
public Response getResult(@PathParam("sid) Integer sid){
Student std=new Student();
std.setName("sathish");
std.setSid(sid);
return Response.status(200).entity(std).build();
}
}
213 |P a ge
WebServices
Get HTTP header in JAX-RS
WehavetwowaystogetHTTPrequestheaderinJAX-RS:
1. Injectdirectlywith @HeaderParam
2. Programatically via @Context
1. @HeaderParam Example
In this example, it gets the browser “user-agent” from request header.
2) Pragmatically via
For @HeaderParam annotation Alternatively, you can also use @Context to get
“javax.ws.rs.core.HttpHeaders” directly,seeequivalentexample togetbrowser“user-
agent“.
Import javax.ws.rs.GET;
import javax.ws.rs.HeaderParam;
import javax.ws.rs.Path;
import javax.ws.rs.core.Response;
@Path("/users")
public class UserService {
@GET
public Response getHeadersResult(@HeaderParam("user-agent") String userAgent){
System.out.println("getHeaderResult method is calling and userAgent is :"+userAgent);
return Response.status(200).entity(userAgent).build();
}
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.HttpHeaders;
import avax.ws.rs.core.Response;
@Path("/users")
public class UserService {
@GET
@Path("/get")
@Produces(“text/plain”)
public String getHeaders(@Context HttpHeaders headers) {
String userAgent = headers.getRequestHeader("user-agent").get(0);
return "getHeaders is called, userAgent : " + userAgent;
}
}
@Context Annnotation :
214 |P a g
WebServices
List all request headers
You can also get list of available HTTP request headers via following code :
In general, @Context can be used to obtain contextual Java types related to the request or response.
(for example @Context HttpServletRequest request ).
@CookieParam:
 Cookie is a name-value pair.
 In General Cookie is transferring from Server to client and client to server.
 TheCookieobjectiscreatinginServerSystembutstoresinClientSystem.
We can retrieve the entire cookie by injecting the Cookie with the @CookieParam annotation by providing
the cookie name.
Note :
@Path("/users")
public class UserService {
@GET
@Path("/getAll")
@Produces(“text/plain”)
public Response getAllHeaders(@Context HttpHeaders headers){
MultivaluedMap<String,String> map=headers.getRequestHeaders();
Set<String> keys=map.keySet();
for(String key:keys){
System.out.println("Header Name : "+key);
List<String> headerValues=headers.getRequestHeader(key);
for(String headerValue:headerValues){
System.out.println(headerValue);
}
}
return Response.status(200).build();
}
}
@GET
@Produces(“text/plain”)
public String getCookie(@CookieParam("cookie-name") Cookie cookie){
System.out.println(cookie);
return “OK”;
}
e
215 |P a ge
WebServices
We can also retrieve just the cookie value by injecting the value with the @CookieParam annotation.
@GET
@Produces(“text/plain”)
public String getCookieValue(@CookieParam("name") String cookie){
System.out.println(cookie);
return “OK”;
}
Extracting RequestParameters:
Parameters of a resource method may be annotated with parameter-based annotations to get the
values from a request obj.
You can extract the following types of parameters for use in your resource class:
 QueryParam
 URI path(PathParam)
 FormParam
 Cookie Param
 Header Param
 MatrixParam
Query parameters are retrieved from the request URI query parameters and are specified by using
the javax.ws.rs.QueryParam annotation in the method parameter arguments.
The following example, from the Employee application, demonstrates using of @QueryParam annotation to
retrieve query parameters from the requested URL:
package com.nareshit.service;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Response;
@Path("employee")
public class EmployeeService {
@GET
@Path("/getEmployeeDetails")
public Response getEmployee(@QueryParam("dept") String department,
216 |P a ge
WebServices
In the above example, if you use "/employee/getEmployeeDetails" URI pattern, and you will get
"Query parameters are received. 'dept' value is: accounts and location value is: bangalore" as a
response.
Sometimes User-definedJavaprogramminglanguagetypesmaybeusedasqueryparameters(OR)
primitiveTypesusedasaqueryparameters (OR) collectiontypesusedasaqueryparametersasper
the requirements.
@QueryParam("location") String location){
String resp = "Query parameters are received. 'dept' value is: "
+department+" and location value is: "+location;
returnResponse.status(200).entity(resp).build();
}
}
In the above example, if you use
"/employee/getEmployeeDetails?location=hyderabad&dept=finance" URI pattern with query
parameters, getEmployee() method will be invoked, and you will get "Query parameters as 'dept'
value is: finance and location value is: hyderabad" as a response.
To assign default values to method input variables if the query parameters are not available You can
use @DefaultValue annotation to specify default value.
package com.nareshit.service;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Response;
@Path("employee")
public class EmployeeService {
@GET
@Path("/getEmployeeDetails")
public Response getEmployee (
@DefaultValue("accounts") @QueryParam("dept") String department,
@DefaultValue("bangalore")@QueryParam("location")Stringlocation){
String resp = "Query parameters are received. 'dept' value is: "
+department+" and location value is: "+location;
returnResponse.status(200).entity(resp).build();
}
}
217 |P a ge
WebServices
package com.nareshit.service;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Response;
@Path("employee")
public class EmployeeService {
@GET
@Path("/getEmployeeByDeptNo")
@Produces(MediaType.TEXT_PLAIN)
public String getEmployee(@QueryParam("deptNo") intdeptNo ){
return "Employee Name =raja ,Emp No = 101 , salary =2000 ,deptNo="+deptNo;
}
@GET
@Path("/getEmployeeByDeptName/{deptName}")
@Produces(MediaType.TEXT_PLAIN)
public String getEmployee(@PathParam("deptName") Employee emp){
return "Employee Name =raja ,Emp No = 101 , salary =2000
,deptName="+emp.getDeptName();
}
@GET
@Path("/deleteDepartments")
218 |P a ge
WebServices
The following code shows how to write Employee class for above example
The constructor for Employee takes a single String parameter.
Note :Both @QueryParam and @PathParam can be used only on the following Java types:
 All primitive types except char
 All wrapper classes of primitive types except Character
 Any class with a constructor that accepts a single String argument
 Anyclass with the staticmethod named valueOf(String) that accepts asingle String argument
@Produces(MediaType.TEXT_PLAIN)
public String deleteDepartments(@QueryParam("deptNo") List<Integer>deptNoList){
System.out.println(“List of Deprts:”+deptNoList);
return "Departments deleted ";
}
}
public class Employee{
private String deptName;
public Employee(String deptName) {
this.deptName=deptName;
}
public void setDeptName(String deptName){
this.deptName=deptName;
}
public String getDeptName(){
return deptName;
}
}
219 |P a ge
WebServices
 List<T>,Set<T>,orSortedSet<T>,whereTmatchesthealreadylistedcriteria.Sometimes,parameters
maycontainmorethanonevalueforthesamename.Ifthisisthecase,thesetypesmaybeused
to obtain allvalues
Note :
If @DefaultValue is not used in conjunction with @QueryParam, and the query parameter is not present in
therequest,thevaluewillbeanemptycollectionforList,Set,orSortedSet;nullforotherobjecttypes;
and the default for primitive types.
BeanParameters(By using @BeanParam annotation) (JAX-RS 2.0)):
Exception-Handling:
 Whenwe senda request to the resource,the resource sometimes maythrows Exceptions.
 If resource throws Exception , JAXRS runtime will convert that exception into an response
message with status code as error response code.
 Butifwewanttoreturnacustomerrorresponseratherthanadefaulterror responsemessage
we need to handle exceptions and should return as a response shown below.
package com.nareshit.bean;
public class EmployeeBean{
@QueryParam("salary")
private double salary;
@QueryParam("deptName")
private String deptName;
@QueryParam("location")
private String location;
//setters and getters
}
package com.nareshit.service;
@Path("/employee")
public class EmployeeService{
@GET
@Produces(MediaType.TEXT_PLAIN)
@Path("/searchEmployees")
public String searchEmployees(@BeanParam EmployeeBean employeeBean){
return "empNo =101 ,empName=rama,salary="+employeeBean.getSalary();
}
}
220 |P a ge
WebServices
UserNotFoundException.java
UserService.java
This above method may throws an appropriate exception when a user cannot be found. However, we
still need to create a Handler object to convert this exception into an actual JSON response so we get a
nice friendly error message. The class below handles this exception and will convert the error message
in the exception into a JSON response.The important annotation you’ll see on this class
i,e @Provider annotation.
public class UserNotFoundException extends Exception {
public UserNotFoundException() {
super();
}
public UserNotFoundException (String msg) {
super(msg);
}
public UserNotFoundException (String msg, Exception e) {
super(msg, e);
}
}
@Path("users")
public class UserService {
@GET
@Path("/getUser/{userId}")
@Produces(MediaType.APPLICATION_JSON)
public Response getUser(@PathParam("userId") String userId) throws UserNotFoundException {
if(userId.equals("101")){
User user=new User();
user.setUserId(userId);
user.setName("sathish");
user.setEmail("sathish@gmail.com");
user.setMobile("8888889988");
return Response.status(200).entity(user).type(MediaType.APPLICATION_JSON).build();
}
else{
throw new UserNotFoundException ("User does not exist with id " + userId);
}
}
}
221 |P a ge
WebServices
UserNotFoundExceptionHandler :
Caching:
When we opening of awebpage forthefirst time takes some time, but the second or third time it
loads faster. This happens because whenever we visit a webpage for the first time, our browser caches
the content and need not have to make a call over the network to render it.
Thiscachingabilityofthebrowsersavesalotofnetworkbandwidthandhelpsincuttingdownthe
server load.
1.)BrowserorlocalCaches:Thisisthelocalin-memorycacheofabrowser.Thisisthefastestcache
available. Whenever we hit a webpage a local copy is stored in browser and then second time it uses
this local copy instead of making a real request over the network.
2.)ProxyCaches:Thesearepseudowebserversthatworkasmiddlemenbetweenbrowsersand
websites.
These servers cache the static content and serve its clients so the client does not have to go to server
for these resources.
Content Delivery Networks (CDN) are of similar concept where in they provide proxy caches from their
servers , which helps in faster serving the content and sharing the load of servers.
Inconsistencyandinvalidation:Whenwearedealingwithcacheweneedtomakesurethatthe
stale data is invalidated and it should be consistent. So let’s see what all mechanisms are provided by
HTTP which can help us make effective use of HTTP caching.
HTTP Headers
BeforeHTTP1.1theonlywaytocontrolcachingbehaviorwaswiththehelpof“expries”header.Inthis
an expiry date can be specified.
But, later more powerful and extensive headers were introduced in HTTP 1.1, this was “cache-control”
header.Thisalongwith “retag”gave the realpowerto theapplications tocontrolthebehavior of
caches.
222 |P a ge
WebServices
JAX-RSsupportstheseandprovidesAPIstousethem.Wewillexplorehowwecanleveragecaching
using HTTP response headers and the support provided by JAX-RS.
Expires Header:
In HTTP 1.0, a simple response header called Expires would tellthe browser howlongit can cache an
object or page. It would be a date in future after which the cache would not be valid.
So, if we made an API call to retrieve data :
 This means the XML data is valid until 20th Dec 2016, 16:00 hours GMT.
 JAX-RS supports this header in javax.ws.rs.core.Response object.
GET /users/1
Theresponseheaderwouldbe:
HTTP/1.1 200 OK
Content-Type: application/xml
Expires: Tue,20 Dec2016 16:00 GMT
-----
<user id="1">...</users>
223 |P a ge
WebServices
But to support CDNs, proxy caches there was a need for more enhanced headers with richer set of
features, having more explicit controls. Hence in HTTP 1.1 few new headers were introduced and
Expires was deprecated. Let’s explore them.
With Cache-Control :
Cache-Control has a variable set of comma-delimited directives that define who, how and for how long
it can be cached. Let’s explore few of them:
–private/public : these are accessibility directives, private means a browser can cache the object but
the proxies or CDNs cannot and public makes it cacheable by all.
-no-cache, no-store,max-age are few others where name tells the story.
package com.cacheexample.service;
@Path(“user”)
publicclassUserService{
@Path("getUser/{uid}")
@GET
@Produces(MediaType.APPLICATION_XML)
public Response getUserXML(@PathParam("uid") Long uid){
User user=null;
if(uid.equals(101)){
user=new User();
user.setUserId(uid);
user.setUserName(“Ashok”);
user.setEmail(“ashok@gmail.com”);
}
ResponseBuilderbuilder=Response.ok(user,MediaType.APPLICATION_XML); //Puttingexpires
header for HTTP browser caching.
Calendar cal = Calendar.getInstance();
cal.set(2016,12,25,16,0);
builder.expires(cal.getTime());
return builder.build();
}
Note : ResponseBuilder object build the Response object
224 |P a ge
WebServices
JAX-RS provides javax.ws.rs.core.CacheControl class to represent this header.
RESTful Web Service Security
Security Areas:
There are two main areas for securities.
Authentication: Process of checking the user, who they claim to be.
Authorization: Process of deciding whether a user is allowed to perform an activity within the
application.
Different Authentications :
 BASIC Authentication
 It’ssimplestofalltechniquesandprobablymostusedaswell.Youuselogin/password
forms – it’s basic authentication only. You input your username and password and submit
theformto server, andapplicationidentifyyouasa user–youareallowedtousethe
system – else you get error.
package com.cacheexample.service;
@Path(“user”)
publicclassUserService{
@Path("getUser/{uid}")
@GET
@Produces(MediaType.APPLICATION_XML)
public Response getUserXMLwithCacheControl(@PathParam("uid") Long uid){
User user=null;
if(uid.equals(101)){
user=new User();
user.setUserId(uid);
user.setUserName(“Ashok”);
user.setEmail(“ashok@gmail.com”);
}
CacheControl cc = new CacheControl();
cc.setMaxAge(300);// set the max-age cache control directive.
cc.setPrivate(true);
ResponseBuilder builder = Response.ok(user,MediaType.APPLICATION_XML);
builder.cacheControl(cc);
return builder.build();
}
225 |P a ge
WebServices
 The main problem with this security implementation is that credentials are propagated in
aplainwayfromtheclienttotheserver.CredentialsaremerelyencodedwithBase64in
transit,butnotencryptedorhashedinanyway.Thisway,anysniffercouldreadthesent
packages over thenetwork.
DIGEST Authentication
This authentication method makes use of a hashing algorithms to encrypt the password
(called password hash) entered bythe user before sendingit to the server. This, obviously, makes it
much safer than the basic authentication method, in which the user’s password travels in plain text
that can be easily read by whoever intercepts it.
CLIENT CERT Authentication
 This is a mechanism in which a trust agreement is established between the server and the client
through certificates. They must be signed by an agency established to ensure that the
certificate presented for authentication is legitimate, which is known as CA.
 Usingthistechnique,whentheclientattemptstoaccessaprotectedresource,insteadof
providingausernameorpassword,itpresentsthecertificatetotheserver.Thecertificate
containstheuserinformationforauthenticationincludingsecuritycredentials,besidesa
unique private-public key pair. The server then determines if the user is legitimate through the
CA. Additionally, it must verify whether the user has access to the resource. This mechanism
must use HTTPS as the communication protocol as we don’t have a secure channel to prevent
anyone from stealing the client’s identity.
Ways to Secure RestFullWeb Services:
You can secure your Restful Web services using one of the following methods to support
authentication, authorization, orencryption:
1) Using web.xml deployment descriptor to define security configuration.
2) Using the javax.ws.rs.core.SecurityContext interface to implement security
programmatically.
3) By Applying annotations to your JAX-RS classes.
Securing RESTful Web Services Using web.xml
 YousecureRESTfulWebservicesusingtheweb.xmldeploymentdescriptorasyouwouldfor
other Java EE Web applications.
22
WebServices
 Forexample,tosecureyourRESTfulWebserviceusingbasicauthentication,performthe
following steps:
1. Definea<security-constraint>foreachsetofRESTfulresources(URIs)thatyouplantoprotect.
2. Use the <login-config> element to define the type of authentication you want to use and the
security realm to which the security constraints will be applied.
3. Define one or more security roles using the <security-role> tag and map them to the security
constraints defined in step 1.
4. Toenableencryption,addthe<user-data-constraint>elementandsetthe<transport-
guarantee> subelement to CONFIDENTIAL
Example 1 Securing RESTful Web Services Using Basic Authentication
Step1 : create Root Resource class as for your requirement :
Step2:- Configure The Security Configuration in web.xml file as follows
<web-app>
<servlet>
<servlet-name>RestServlet</servlet-name>
<servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>RestServlet</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
<security-constraint>
<web-resource-collection>
<web-resource-name>Products</web-resource-name>
<url-pattern>/*</url-pattern>
<http-method>GET</http-method>
<http-method>POST</http-method>
</web-resource-collection>
<auth-constraint>
<role-name>ADMIN</role-name>
6 |P a ge
package com.nareshit.service;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
@Path("products")
public class ProductService {
@GET
@Path("/getProductName")
@Produces(MediaType.TEXT_PLAIN)
public String getProductName(
@QueryParam("pid") Integer pid){
if(pid!=null && pid.equals(301)){
return "keyboard";
}
return "Product not found";
}
}
227 |P a ge
web.xml
WebServices
Step3:- Set username and password and Role’s in Tomcat Server
Changes in Tomcat Server ( tomcat-users.xml)
As stated above we are using Tomcat 7. Now for the user to be authenticated we will specify the role
‘ADMIN’(whichistherolechoseninour above)andsomeusername andpasswordinour
container. Thisusername and password will have to be supplied to access therestricted resource.
Step4:- Deploy the Project into the server
Note : Test the above Service By using Any RestClient tool.
While sending the request set username and password as follows.
FirstClickon Authentication intheclient toolBasicAuthentication
<tomcat-users>
<role rolename="manager-gui"/>
<role rolename="admin-gui"/>
<role rolename="admin"/>
<role rolename="customer"/>
<user username="customer" password="customer" roles="customer"/>
<user username="admin" password="admin" roles="admin"/>
<user username="admin" password="admin" roles="admin-gui,manager-gui"/>
</tomcat-users>
tomcat-users.xml
228 |P a ge
WebServices
Enter UserName and password
Enter the URL and send
229 |P a ge
WebServices
Output :
2) Securing RESTful Web Services Using SecurityContext
The javax.ws.rs.core.SecurityContext interface provides access to security-related information for a
request. The SecurityContext provides functionality similar to javax.servlet.http.HttpServletRequest,
enabling you to access the following security-related information:
java.security.Principal object containing the name of the user making the request.
Authentication type used to secure the resource, such as BASIC_AUTH, FORM_AUTH, and
CLIENT_CERT_AUTH.
Whether the authenticated user is included in a particular role.
Whether the request was made using a secure channel, such as HTTPS.
YouaccesstheSecurityContextbyinjectinganinstanceintoaclassfield,settermethod,ormethod
parameter using the javax.ws.rs.core.Context annotation.
The following shows how to inject an instance of SecurityContext into the sc method parameter using
the @Context annotation, and check whether the authorized user is included in the admin role before
returning the response.
Example 2 Securing RESTful Web Service Using SecurityContext
package com.nareshit.service;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
WebServices
import javax.ws.rs.core.SecurityContext;
@Path("products")
publicclassProductService{
@GET
@Path("/getProductName")
@Produces(MediaType.TEXT_PLAIN)
public String getProductName(
@QueryParam("pid") Integer pid,
@Context SecurityContext sc) {
if (sc.isUserInRole("admin")){
if(pid!=null && pid.equals(301)){
return "keyboard";
}
else{
return "Product Not Found";
}
}
}
}
3) Securing RESTful Web Services Using Annotations
Thejavax.annotation.securitypackageprovidesannotations,definedinTable1,thatyoucanuseto
secure your RESTful Web services.
Table 1 Annotations for Securing RESTful Web Services
Annotation Description
DeclareRoles Declares roles.
DenyAll Specifies that no security roles are
allowed to invoke the specified methods.
PermitAll Specifies that all security roles are allowed to
invoke the specified methods.
RolesAllowed Specifies the list of security roles that are allowed
to invoke the methods in the application.
RunAs Definestheidentityoftheapplicationduring
execution in a J2EE container.
230 |P a ge
231 |P a ge
WebServices
In Thefollowing Example getProductName methodisannotated with the @RolesAllowed annotation
to override the default and only allow users that belong to the ADMIN security role.
Example 3 Securing RESTful Web Service Using Annotations(javax.annotation.security)
Realm :
 Arealmisarepositoryofuserinformation;itisanabstractionofthedatastore–textfile,JDBC
database or a JNDI resource. This hasthe following information: username, password and the
roles which are assigned to the users.
Both of the authentication and authorization make up the security policy of a server. Tomcat
usesrealmstoimplement container-managed securityandenforcespecific securitypolicies.
Conculsion :
RESTful Services:
RESTstandsforRepresentationalStateTransfer.RESTwasatermcoinedbyRoyFieldinginhisdoctoral
dissertation.Itisanarchitecturestyleforforcreatingnetworkbasedapplications. Keypropertiesof
REST are client-server communication, stateless protocol, cacheable, layered implementation and
uniform interface
package com.nareshit.service;
import javax.annotation.security.RolesAllowed;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
@Path("products")
@RolesAllowed({"admin","customer"})
public class ProductService {
@GET
@Path("/getProductName")
@Produces(MediaType.TEXT_PLAIN)
@RolesAllowed("admin")
public String getProductName(
@QueryParam("pid")Integerpid){
if(pid!=null && pid.equals(301)){
return "keyboard";
}
else{
return "Product Not Found";
}
}
}
232 |P a ge
WebServices As
RESTful web services work with HTTP URLs Paths so it is very important to safeguard a RESTful web
serviceinthesamemannerasawebsiteisbesecured.Followingarethebestpracticestobefollowed
while designing a RESTful web service.
Validation-Validateallinputsonthe server.ProtectyourserveragainstSQLorNoSQLinjection
attacks.
Session based authentication - Use session based authentication to authenticate a user
whenever a request is made to a Web Service method.
NosensitivedatainURL-Neveruseusername,passwordorsessiontokeninURL,thesevalues
should be passed to Web Service via POST method.
Restriction on Method execution - Allow restricted use of methods like GET, POST, DELETE. GET
method should not be able to delete data.
ValidateMalformedXML/JSON-Checkforwellformedinputpassedtoawebservicemethod.
Throw generic Error Messages - A web service method should use HTTP error messages like 403
to show access forbidden etc.
S.N. HTTP Code & Description
1
200
OK, shows success.
2
201
CREATED,whenaresourceissuccessfulcreatedusingPOSTorPUTrequest.Returnlinktonewly
created resource using location header.
3
204
NO CONTENT, when response body is empty for example, a DELETE request.
4
304
NOT MODIFIED, used to reduce network bandwidth usage in case of conditional GET requests.
Response body should be empty. Headers should have date, location etc.
5
400
BAD REQUEST, states that invalid input is provided e.g. validation error, missing data.
6
401
UNAUTHORIZED, states that user is using invalid or wrong authentication token.
7
403
FORBIDDEN,statesthatuserisnothavingaccesstomethodbeingusedforexample,deleteaccess
without admin rights.
8
404
NOT FOUND, states that method is not available.
9
409
CONFLICT, states conflict situation while executing the method for example, adding duplicate
entry.
10
500
INTERNAL SERVER ERROR, states that server has thrown some exception while executing the
method.
233 |P a ge
WebServices
JAX-RS Annotations:
Following are the commonly used annotations to map a resource as a web service resource.
S.N. Annotation & Description
1
@Path
Relative path of the resource class/method.
2
@GET
HTTP Get request, used to fetch resource.
3
@PUT
HTTP PUT request, used to create resource.
4
@POST
HTTP POST request, used to create/update resource.
5
@DELETE
HTTP DELETE request, used to delete resource.
6
@HEAD
HTTP HEAD request, used to get status of method availability.
7
@Produces
States the HTTP Response generated by web service, for example APPLICATION/XML,
TEXT/HTML, APPLICATION/JSON etc.
8
@Consumes
States the HTTP Request type, for example application/x-www-form-urlencoded to
accept form data in HTTP body during POST request.
9
@PathParam
Binds the parameter passed to method to a value in path.
10
@QueryParam
Binds the parameter passed to method to a query parameter in path.
11
@MatrixParam
Binds the parameter passed to method to a HTTP matrix parameter in path.
12
@HeaderParam
Binds the parameter passed to method to a HTTP header.
13
@CookieParam
Binds the parameter passed to method to a Cookie.
14
@FormParam
Binds the parameter passed to method to a form value.
15
@DefaultValue
Assigns a default value to a parameter passed to method.
234 |P a ge
WebServices
POSTMAN
Introduction
PostmanisaChromeadd-onandMacapplicationwhichisusedtofirerequeststoanAPI.Itisverylightweight
and fast. Requests can be organized in groups, also tests can be created with verifications for certain conditions
ontheresponse.Withitsfeatures,itisverygoodandconvenientAPItool.Itispossibletomakedifferentkindsof
HTTPrequests–GET,POST,PUT,PATCHandDELETE.Itispossibletoaddheaderstotherequests.
Installation
Step-1  Open Google Chrome and type Postman  Click on below highlighted link
235 |P a ge
WebServices
Step-2  After clicking on “https://www.getpostman.com/apps” this URL below screen will be displayed
Step-3  Based on your operating system click on “Download” button (below Screen will be displayed)
236 |P a ge
WebServices
Stpe-4  Install downloaded exe file (Below screen will be displayed)
Step-5  It displays below screen (Create a free account)
237 |P a ge
WebServices
Step-6AfterAccountcreationLoginintoPostmanusinggivencredentials(belowscreenwillbedisplayed)
Step-7->FromtheabovescreenclickonRequestandenterdetails(SelcetPostManEcho)andclickon“Save
to Postman Echo”button
238 |P a ge
WebServices
Step-8  We can send http request to Rest API using request URL from below screen
Inthisscreen wecanuserequesttypelikeGET, POST, PUT andDelete
POSTMAN Screen shot for POST request
239 |P a ge
WebServices
Spring Integration with REST
Introduction
RESTfulwebservicesarebuilttoworkbestontheWeb.RepresentationalStateTransfer(REST)isanarchitectural
stylethatspecifiesconstraints, suchastheuniforminterface,thatif appliedtoawebservice inducedesirable
properties,suchasperformance,scalability,andmodifiabilitythatenableservicestoworkbestontheWeb.In
the REST architectural style, data and functionality are considered resources and are accessed using Uniform
ResourceIdentifiers(URIs),typicallylinksontheWeb.Theresourcesareacteduponbyusingasetofsimple,well-
defined operations. The REST architectural style constrains an architecture to a client/server architecture and is
designed to use a stateless communication protocol, typically HTTP. In the REST architecture style, clients and
servers exchange representations ofresources byusing a standardized interface and protocol.
The following principles encourage RESTful applications to be simple, lightweight, and fast:
Resource identification through URI: A RESTful web service exposes a set of resources that identify the targets
of the interaction with its clients. Resources are identified by URIs, which provide a global addressing space for
resourceandservicediscovery.Seethe@PathAnnotationandURIPathTemplatesformoreinformation.
Uniforminterface: Resources aremanipulated using afixedsetoffour create,read,update,delete operations:
PUT,GET,POST,andDELETE.PUTcreatesanewresource,whichcanbethendeletedbyusingDELETE.GET
retrievesthecurrentstateofaresourceinsomerepresentation.POSTtransfersanewstateontoaresource.
See Responding to HTTP Methods and Requests for more information.
Self-descriptivemessages:Resourcesaredecoupledfromtheirrepresentation sothattheircontentcanbe
accessedinavarietyofformats,suchasHTML,XML,plaintext,PDF,JPEG,JSON,andothers.Metadataabout
the resource is available and used, for example, to control caching, detect transmission errors, negotiate the
appropriate representation format, and perform authentication or access control. See Responding to HTTP
MethodsandRequestsandUsingEntityProviderstoMapHTTPResponseandRequestEntityBodiesformore
information.
Statefulinteractionsthroughhyperlinks:Everyinteractionwitharesourceisstateless;thatis,request
messages are self-contained. Stateful interactions are based on the concept of explicit state transfer. Several
techniquesexisttoexchangestate,suchasURIrewriting,cookies,andhiddenformfields.Statecanbe
embedded in response messages to point to valid future states of the interaction. See Using Entity Providers to
MapHTTPResponseandRequestEntityBodiesand“BuildingURIs”intheJAX-RSOverviewdocumentformore
information.
RESTful Web Services utilize the features of the HTTP Protocol to provide the API of the Web Service. It uses
the HTTP Request Types to indicate the type of operation:
GET:Retrieve/ Queryof existingrecords.
POST: Creatingnew records.
DELETE: Removing records.
PUT: Updating existing records.
Usingthese4HTTPRequestTypesaRESTfulAPImimicstheCRUDoperations(Create,Read,Update&
Delete).RESTisstateless, eachcall theto aRESTful Web Serviceiscompletely stand-alone,ithasno
knowledge of previousrequests.
240 |P a ge
WebServices
Below REST application performs CURD operations using Spring Service class
Step 1: Create Maven Web Project
241 |P a ge
WebServices
Step 2: Configure maven dependencies in project pom.xml file
Step 3: Create Domain class for Storing and Retrieving the data (User.java)
242 |P a ge
WebServices
Step 4: Create UserService.java class to perform Business operations
Step 5: Create RestController (UserRestController.java)
package com.app.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import com.app.domain.User;
import com.app.service.UserService;
@RestController
public class UserRestController {
@Autowired(required = true)
private UserService service;
@RequestMapping(value = "/add", method = RequestMethod.POST, consumes = { "application/xml",
"application/json" })
public @ResponseBody String addUser(@RequestBody User user) {
boolean isAdded = service.add(user);
if (isAdded) {
return "User Added successfully";
} else {
}
}
return "Failed to Add the User..!";
243 |P a ge
WebServices
@RequestMapping(value = "/get", produces = { "application/xml", "application/json" }, method =
RequestMethod.GET)
@ResponseBody
public User getUserById(@RequestParam(name = "uid") String uid) {
System.out.println("Getting User with User Id : " + uid);
User user = service.get(uid);
return user;
}
@RequestMapping(value = "/update", method = RequestMethod.PUT,
consumes = { "application/xml", "application/json" }
)
public @ResponseBody String update(@RequestParam("uid") String uid, @RequestBody User user) {
boolean isAdded = service.update(uid, user);
if (isAdded) {
return "User updated successfully";
} else {
}
}
return "Failed to update the User..!";
@RequestMapping(value = "/delete", method = RequestMethod.DELETE)
public @ResponseBody String delete(@RequestParam("uid") String uid) {
boolean isAdded = service.delete(uid);
if (isAdded) {
return "User Deleted successfully";
} else {
}
}
return "Failed to Delete the User..!";
public void setService(UserService service) {
this.service = service;
}
}
Step 6: Create AppConfig and AppInitiazer classes
AppConfiguration.java
244 |P a ge
WebServices
AppInitializer.java
Step 7: Deploy the Application into server (I have used Apache Tomcat 8.0)
Step8:TesttheApplicationusingPOSTMANplugininGoogleChrome
Testing AddUser
URI: http://localhost:6060/SpringRestIntegrationApp/rest/add
Method Type: POST
Consumes: {application/xml, application/json}
Produces: text/plain
Request Body Data: In XML Format
<? xml version="1.0" encoding="UTF-8"?>
<user>
<userid>101</userid>
<username>Raju</username>
<gender>Male</gender>
<email>Raj@gmail.com</email>
</user>
245 |P a ge
WebServices
POSTMAN Screenshot
Testing Fetch User
URI: http://localhost:6060/SpringRestIntegrationApp/rest/get?uid=101
Method Type: GET
Input: Request Parameter (? uid=101)
Produces: {application/xml, application/json}
POSTMAN Screenshot
Testing Update User
URL: http://localhost:6060/SpringRestIntegrationApp/rest/update?uid=101
Method Type: PUT
InputinURL:UserId(RequestParameter)?uid=101
Consumes: {application/xml, application/json}
246 |P a ge
WebServices
Produces: text/plain
Request Body Data: in XML format
<? xml version="1.0" encoding="UTF-8"?>
<user>
<userid>101</userid>
<username>Ashok</username>
<gender>Male</gender>
<email>ashok.b@gmail.com</email>
</user>
POSTMAN Screenshot
Testing Delete User
URL: http://localhost:6060/SpringRestIntegrationApp/rest/delete?uid=101
Method Type: DELETE
Input: Request Parameter (? uid=101)
Produces: text/plain
247 |P a ge
WebServices
POSTMAN Screenshot
=== Happing Learning ====

More Related Content

PDF
SAP Financial Accounting - Business Process Document
PDF
SAP Financial Accounting - Configuration Document
PDF
Co cca config ecc6
DOCX
PDF
Aralpha manual 2.4(1)
SAP Financial Accounting - Business Process Document
SAP Financial Accounting - Configuration Document
Co cca config ecc6
Aralpha manual 2.4(1)

Similar to XML / WEB SERVICES & RESTful Services (20)

PDF
Variant Configurition in SAP: Beginners Guide | www.sapdocs.info
PDF
ICP DAS USA Full Catalog
PDF
Precision Bearing House, Industrial Automation | PBH
DOCX
Kickstat File_Draft_ESXI5.1_Template
PDF
Final Report
DOCX
Dave bio data
DOCX
Dave bio data
DOCX
Dave bio data
PDF
PROGRAMI PER KURSIN ALPHA BUSINESS
PDF
SAP SD Training | SAP SD Configuration Guide | SAP SD Study Material
PDF
Sap sd-study-material-1511
PDF
SAP UTILITIES ONLINE TRAINING
PDF
Strategic Enterprise Design - 1st Enterprise Design Retreat by eda.c and EA F...
DOCX
Resume_RB
DOCX
CV_HARSHAL SHAH
PDF
Jonas Gassenmeyer – IT-Tage 2015 – Materialized Views in Oracle
PDF
Manual & guide_for_birt_eclipse_report designer
PDF
Manual & guide for birt eclipse report designer
PDF
Modelling for Strategic Design - IxDA Berlin 09/2013
PDF
BI in the Clouds (Wlodek Bielski Technology Stream)
Variant Configurition in SAP: Beginners Guide | www.sapdocs.info
ICP DAS USA Full Catalog
Precision Bearing House, Industrial Automation | PBH
Kickstat File_Draft_ESXI5.1_Template
Final Report
Dave bio data
Dave bio data
Dave bio data
PROGRAMI PER KURSIN ALPHA BUSINESS
SAP SD Training | SAP SD Configuration Guide | SAP SD Study Material
Sap sd-study-material-1511
SAP UTILITIES ONLINE TRAINING
Strategic Enterprise Design - 1st Enterprise Design Retreat by eda.c and EA F...
Resume_RB
CV_HARSHAL SHAH
Jonas Gassenmeyer – IT-Tage 2015 – Materialized Views in Oracle
Manual & guide_for_birt_eclipse_report designer
Manual & guide for birt eclipse report designer
Modelling for Strategic Design - IxDA Berlin 09/2013
BI in the Clouds (Wlodek Bielski Technology Stream)
Ad

More from Zeeshan Khan (12)

PPTX
Apache kafka
PDF
Spring security4.x
PPTX
Micro services overview
PDF
Manual Testing
PDF
Collection framework (completenotes) zeeshan
PDF
JUnit with_mocking
PPTX
OOPS in Java
PPTX
PPTX
Introduction to BIG DATA
PPTX
Big data
PPT
Android application development
PPTX
Cyber crime
Apache kafka
Spring security4.x
Micro services overview
Manual Testing
Collection framework (completenotes) zeeshan
JUnit with_mocking
OOPS in Java
Introduction to BIG DATA
Big data
Android application development
Cyber crime
Ad

Recently uploaded (20)

PDF
T3DD25 TYPO3 Content Blocks - Deep Dive by André Kraus
PDF
2025 Textile ERP Trends: SAP, Odoo & Oracle
PDF
Design an Analysis of Algorithms II-SECS-1021-03
PDF
System and Network Administration Chapter 2
PDF
Addressing The Cult of Project Management Tools-Why Disconnected Work is Hold...
PDF
Digital Strategies for Manufacturing Companies
PDF
Audit Checklist Design Aligning with ISO, IATF, and Industry Standards — Omne...
PPTX
history of c programming in notes for students .pptx
PPTX
Oracle E-Business Suite: A Comprehensive Guide for Modern Enterprises
PPTX
ai tools demonstartion for schools and inter college
PDF
How Creative Agencies Leverage Project Management Software.pdf
PDF
top salesforce developer skills in 2025.pdf
PPTX
Introduction to Artificial Intelligence
PDF
Design an Analysis of Algorithms I-SECS-1021-03
PDF
Why TechBuilder is the Future of Pickup and Delivery App Development (1).pdf
PDF
Wondershare Filmora 15 Crack With Activation Key [2025
PPTX
Lecture 3: Operating Systems Introduction to Computer Hardware Systems
PPTX
Operating system designcfffgfgggggggvggggggggg
PPTX
Odoo POS Development Services by CandidRoot Solutions
PPTX
Transform Your Business with a Software ERP System
T3DD25 TYPO3 Content Blocks - Deep Dive by André Kraus
2025 Textile ERP Trends: SAP, Odoo & Oracle
Design an Analysis of Algorithms II-SECS-1021-03
System and Network Administration Chapter 2
Addressing The Cult of Project Management Tools-Why Disconnected Work is Hold...
Digital Strategies for Manufacturing Companies
Audit Checklist Design Aligning with ISO, IATF, and Industry Standards — Omne...
history of c programming in notes for students .pptx
Oracle E-Business Suite: A Comprehensive Guide for Modern Enterprises
ai tools demonstartion for schools and inter college
How Creative Agencies Leverage Project Management Software.pdf
top salesforce developer skills in 2025.pdf
Introduction to Artificial Intelligence
Design an Analysis of Algorithms I-SECS-1021-03
Why TechBuilder is the Future of Pickup and Delivery App Development (1).pdf
Wondershare Filmora 15 Crack With Activation Key [2025
Lecture 3: Operating Systems Introduction to Computer Hardware Systems
Operating system designcfffgfgggggggvggggggggg
Odoo POS Development Services by CandidRoot Solutions
Transform Your Business with a Software ERP System

XML / WEB SERVICES & RESTful Services

  • 1. WebServices XML/WEBSERVICES & RESTful Services (XML, DTD, XSD, JAX-P, JAX-B, SOAP, WSDL, JAX-WS, SOAP UI, JAX-RS & POSTMAN) By: Mr. ZEESHAN KHAN Email: zeeshan.maths@gmail.com
  • 2. INDEX Webservices Introduction Introduction -----------------------------------------------------------------------1 Distributed Programming ---------------------------------------------------- 2-3 CORBA------------------------------------------------------------------------------------4 RMI ---------------------------------------------------------------------------------- 5-6 EJB ----------------------------------------------------------------------------------------------- 7 Common challenges inDistributed Programming ---------------------8 Webservices specifications -------------------------------------------------- 9 Webservices Architecture --------------------------------------------------- 10-11 Motivation and Characteristics---------------------------------------------- 12-13 Core Webservices Standards ------------------------------------------------------14-16 XML---------------------------------------------------------------------------- 18-22 DTD Introduction ------------------------------------------------------------------------------- 24 SimpleElements -------------------------------------------------------------------------------- 25 CompoundElements --------------------------------------------------------------------------26 Attributes -----------------------------------------------------------------------------------27 DTDTypes----------------------------------------------------------------------------------------28-29 DTDDrawbacks --------------------------------------------------------------------------------- 30 XSD Introduction -------------------------------------------------------------------------32 Simple Elements Declaration -------------------------------------------------- 33 Compound Elements Declaration --------------------------------------------34-35 Linking XSD to XML --------------------------------------------------------------------- 36 Element Cardinality ---------------------------------------------------------------- 37
  • 3. Compositors (sequence, all and choice)-------------------------------------38-39 Global Elements --------------------------------------------------------------------40 Group Elements--------------------------------------------------------------------------------- 41-42 Inheritance in XSD----------------------------------------------------------------- 43 AttributesinXSD -------------------------------------------------------------------------- 44-46 RestrictiononSimpleTypes ----------------------------------------------------------------- 47-51 XSDNamespaces--------------------------------------------------------------------------------52-53 xs: include ---------------------------------------------------------------------------------- 54 xs:import -----------------------------------------------------------------------------------55-56 JAX-P Introduction -------------------------------------------------------------------------- 58 SAXParser ----------------------------------------------------------------------------------------- 59-64 DOMParser--------------------------------------------------------------------------------- 65-69 STAXParser --------------------------------------------------------------------------------------- 70-71 XMLvalidation against XSD -------------------------------------------------------------------72-73 JAX-B Introduction --------------------------------------------------------------------------- 74 JAX-B Architecture-------------------------------------------------------------------75 Binding------------------------------------------------------------------------------------------------ 76-77 One-Time Operations--------------------------------------------------------------- 78 UsingXJC ------------------------------------------------------------------------------------------------ 79-80 Runtime Operations -----------------------------------------------------------------81 Un-Marshalling -------------------------------------------------------------------------------------81-83 Marshalling ---------------------------------------------------------------------------- 84 In-Memory Validation--------------------------------------------------------------- 85 Getting Started with Webservices Introduction --------------------------------------------------------------------------- 86 Webservicespre-requisites --------------------------------------------------------------------87-88 JAX-WS Introduction --------------------------------------------------------------------------- 90-94
  • 4. JAX-WS Features---------------------------------------------------------------------------95 JAX-WS Implementations----------------------------------------------------------96 ProviderDevelopment(ContractLastApproach)---------------------------------------97-100 Consumer Development ------------------------------------------------------------------------101 - 102 Provider(ContractFirstApproach) ---------------------------------------------------------- 103-107 SOAP Handlers Introduction ----------------------------------------------------- 108 Provider withSOAP Handler ------------------------------------------------------------------- 108-117 ConsumerwithSOAPHandler----------------------------------------------------------------- 118-121 APACHE AXIS2 Introduction ----------------------------------------------------------------------------122 Environment Setup---------------------------------------------------------------------------------123-125 webservicesdevelopmentusingAXIS2 -----------------------------------------------------126-131 Spring+JAX-WSIntegration --------------------------------------------------------------------132-138 Restful services Introduction ----------------------------------------------------------------------------140-142 HttpMethods ----------------------------------------------------------------------------143-149 JAX-RS API Introduction ----------------------------------------------------------- 150 JSON----------------------------------------------------------------------------------------------------151-155 GSONAPI---------------------------------------------------------------------------------------------- 156-157 Jersey--------------------------------------------------------------------------------------------------- 158-159 JAX-RS Annotations overview---------------------------------------------------- 160 Restfulservicefirstapplication ----------------------------------------------------------------162-164 JAX-RS Injection ---------------------------------------------------------------------------------------- 165-167 RestResourcewithJSONdata ---------------------------------------------------------------- 168-170 @Consumes------------------------------------------------------------------------------------------171-173 Jersey2.xapplication ----------------------------------------------------------------------------174-179 JerseyClient-----------------------------------------------------------------------------------------180-183 RestAppwithoutXML --------------------------------------------------------------------- 185-186 Rest Easy Introduction--------------------------------------------------------------187 RestfulServicewithRestEasy ----------------------------------------------------------------- 188-189 RestEasy Client ----------------------------------------------------------------------------- 190
  • 5. BootstrappinginRestEasy --------------------------------------------------------------------- 191-192 File Uploading -------------------------------------------------------------------------------------- 193-194 Spring+RestfulServiceIntegration --------------------------------------------------------- 195-211 Response --------------------------------------------------------------------------------------212 Http Headers --------------------------------------------------------------------------------------213--214 ExtractingRequestParameters----------------------------------------------------------------215-218 ExceptionHandling --------------------------------------------------------------------------------219-220 Caching ----------------------------------------------------------------------------------------------- 221-224 Security ------------------------------------------------------------------------------------------------224-230 Conclusion------------------------------------------------------------------------------------------------ 231-233 POSTMAN--------------------------------------------------------------------234-238 SpringIntegrationwithREST-------------------------------- 239-247
  • 6. Web Services 1 | P a ge Web Services are the mechanism or the medium of communication through which two applications / machines willexchangethedata/businessservicesirrespectiveoftheirunderlinearchitectureandthetechnology. In general, software applications are developed to be consumed by the human beings, where a person sends a request to a software service which in-turn returns a response in human readable format. In the modern era of technology if we want to build a software application we don't need to build each and everything from scratch. There are lots of readymade services available which we can plug into our application and we can start providing those services in our application. For example, we want to display weather forecast information in our application but weather forecast information will not be available in our application database. So, our application should talk to Satellites to get weather forecastinformation.So,dowereallyneedtowritethecomplexlogictotalkwithsatellitetogetthedetails?-No, we don't needtocollect, process andrenderthe datainyour application from satellite. Because some applications arealreadydevelopedbypeopletogettheweatherforecastdetailsfromsatellitessowecanbuytheservices from those people who already well-established in processing and publishing suchkind of data. Now the question is how our application can talk to weather forecaster application? That's where Web services comes into picture. Webservices allow us establish communication between two applications irrespective of the language and irrespective of the platform. If two applications which are developed in two different languages able to communicate with each other, then those applications are called as Interoperable applications. Webservices are used develop interoperable applications. AJavaapplicationcanconnect with.NetapplicationusingWebservicesandvice versa A PHP application can connect with java application and vice versa
  • 7. 2 | P a ge Web Services Before jumping into Webservices development first let’s see some background related to Distributed Computing. TheInternethasrevolutionizedourbusinessbyprovidinganinformationhighway,whichactsasanewformof communicationbackbone.Thisnewinformationmediumhasshiftedbusinessfromthetraditionalbrick-and- mortar infrastructures to a virtual world where they can serve customers not just the regular eight hours, but round-the-clock and around theworld. Additionally, it enhances our organizations with significant benefits in terms of business productivity, cost savings, and customer satisfaction. As a result, modern organizations are compelledtore-evaluatetheirbusinessmodelsandplanonabusinessvisiontointeractwiththeircustomers, suppliers, resellers, and partners using an Internet-based technology space. To achieve this goal of obtaining an Internetbusinesspresence, organizations areexposing anddistributingtheir business applicationsoverthe Internet by going through a series of technological innovations. The key phenomenon of enabling business applicationsover the Internet is based ona fundamentaltechnology called distributed computing. Distributedcomputinghasbeenpopularwithinlocalareanetworksformanyyears,andittookamajorstep forward by adopting the Internet as its base platform and by supporting its open standard-based technologies. This chapter discusses the background of distributed computing and the evolution of Internet-enabled technologies by focusing on the following: 1. The definition of distributed computing 2. The importance of distributed computing 3. Core distributed computing technologies such as the following: • Client/server • CORBA • Java RMI 4. Common challenges in distributed computing 5. The role of J2EE and XML in distributed computing 6. Emergence of Web services and service-oriented architectures What Is Distributed Computing? In the early years of computing, mainframe-based applications were the best-fit solution for executing large-scale data processing applications. With the advent of personal computers (PCs), the concept of software programs runningonstandalonemachinesbecamemuchmorepopularintermsofthecostofownershipand the ease of application use. With the number of PC-based application programs running on independent machines growing, the communications between such application programs became extremely complex and added a growing challenge in the aspect of application-to-application interaction. Lately, network computing gained importance, andenablingremoteprocedurecalls(RPCs)overanetworkprotocolcalledTransmissionControlProtocol/Internet Protocol (TCP/IP) turned out to be a widely accepted way for application software communication. Since then, software applicationsrunning on a variety of hardware platforms, operating systems, and different networks faced some challenges when required to communicate with each other and share data. This demanding requirement lead to the concept of distributed computing applications. As a definition, “Distributing Computing is a type of computing in which different components and objects comprising an application can be located on different computers connected to a network” (www.webopedia.com, May 2001). Below diagram shows a distributed computing model that provides an infrastructure enabling invocations of object functions located anywhere on the network. The objects are transparent to the application and provide processing power as if they were local to the application calling them.
  • 8. 3 | P a ge Web Services Today,SunJavaRMI(RemoteMethodInvocation),OMGCORBA(CommonObjectRequestBrokerArchitecture), Microsoft DCOM (Distributed Component Object Model), and Message-Oriented Middleware (MOM) have emerged as the mostcommon distributed computing technologies.These technologies, although different intheir basic architectural design and implementation, address specific problems in their target environments. The following sections discuss the use of distributed computing and briefly describe the most popular technologies. The Importance of Distributed Computing The distributed computing environment provides many significant advantages compared to a traditional standalone application. The following are some of those key advantages: Higher performance. Applications can execute in parallel and distribute the load across multiple servers. Collaboration.Multipleapplicationscanbeconnectedthroughstandarddistributedcomputingmechanisms. Higherreliabilityandavailability.Applicationsorserverscanbeclusteredinmultiplemachines. Scalability. This can be achieved by deploying these reusable distributed components on powerful servers. Extensibility. This can be achieved through dynamic (re)configuration of applications that are distributed across the network. Higherproductivityandlowerdevelopmentcycletime. Bybreakinguplargeproblemsintosmallerones,these individual components can be developed by smaller development teams in isolation. Reuse. The distributed components may perform various services that can potentially be used by multiple client applications.Itsavesrepetitivedevelopmenteffortandimprovesinteroperabilitybetweencomponents. Reducedcost.Becausethismodelprovidesalotofreuseofoncedevelopedcomponentsthatareaccessibleover the network, significant cost reductions can be achieved. Distributed computing also has changed the way traditional network programming is done by providing a shareable object like semantics across networks using programming languages like Java, C, and C++. The fol- lowing sections briefly discuss core distributed computing technologies such as Client/Server applications, OMG CORBA, Java RMI and MOM. Client-Server Applications The early years of distributed application architecture were dominated by two-tier business applications. In a two- tierarchitecturemodel,thefirst(upper)tierhandlesthepresentationandbusinesslogicoftheuserapplication (client), and the second/lower tier handles the application organization and its data storage (server). This approachiscommonlycalledclient-serverapplicationsarchitecture.Generally,theserverinaclient/server
  • 9. 4 | P a ge Web Services applicationmodelisadatabaseserverthatismainlyresponsiblefortheorganizationandretrievalofdata.The application client in this model handles most of the business processing and provides the graphical user interface of the application. It is a very popular design in business applications where the user interface and business logic aretightlycoupledwithadatabaseserverforhandling dataretrievaland processing. Forexample,theclient- server model has been widely used in enterprise resource planning (ERP), billing, and Inventory application systemswheremanyclient businessapplicationsresiding inmultipledesktop systemsinteractwithacentral database server. Below figure shows an architectural model of a typical client server system in which multiple desktop-based business client applications access a central database server. Some of the common limitations of the client-server application model are as follows:  Complex business processing at the client side demands robust client systems.  Security is more difficult to implement because the algorithms and logic reside on the client side making it more vulnerable to hacking.  Increasednetworkbandwidthisneededtoaccommodatemanycallstotheserver,whichcanimpose scalability restrictions.  Maintenanceandupgradesofclientapplicationsareextremelydifficultbecauseeachclienthastobe maintained separately.  Client-server architecture suits mostly database-oriented standalone applications and does not target robust reusable component- oriented applications. To avoid the limitations of normal client-server architecture Distributed Technologies came into picture. CORBA TheCommonObjectRequestBrokerArchitecture(CORBA)isanindustrywide,openstandardinitiative,developed by the Object Management Group (OMG) for enabling distributed computing that supports a wide range of applicationenvironments.OMGisanonprofitconsortiumresponsiblefortheproductionandmaintenanceof framework specifications for distributed and interoperable object-oriented systems. CORBA differs from the traditional client/server model because it pro- vides an object-oriented solution that does not enforce any proprietary protocols or any particular programming language, operating system, or hardware platform. By adopting CORBA, the applications can reside and run on any hardware platform located anywhere onthenetwork,andcanbewritteninanylanguagethathasmappingstoaneutralinterfacedefinitioncalledthe Interface Definition Language (IDL). An IDL is a specific interface language designed to expose the services (methods/functions) of a CORBA remote object. CORBA also defines a collection of system-level services for
  • 10. 5 | P a ge WebServices handling low-level application services like life-cycle, persistence, transaction, naming, security, and so forth. Initially, CORBA 1.1 was focused on creating component level, portable object applications without interoperability. The introduction of CORBA 2.0 added interoperability between different ORB vendors by implementing an Internet Inter-ORB Protocol (IIOP). The IIOP defines the ORB backbone, through which other ORBs can bridge and provide interoperation with its associated services. In a CORBA-based solution, the Object Request Broker (ORB) is an object bus that provides a transparent mechanism for sending requests and receiving responses to and from objects, regardless of the environment and itslocation.TheORBinterceptstheclient’scallandisresponsibleforfind-ingitsserverobjectthatimplements the request, passes its parameters, invokes its method, and returns its results to the client. The ORB, as part of its implementation, provides interfaces to the CORBA services, which allows it to build custom-distributed application environments. Figure 1.3 illustrates the architectural model of CORBA with an example representation of applications written in C, C++, and Java providing IDL bindings. The CORBA architecture is composed of the following components: IDL: CORBA uses IDL contracts to specify the application boundaries and to establish interfaces with its clients. The IDL provides a mechanism by which the distributed application component’s interfaces, inherited classes, events, attributes, and exceptions can be specified in a standard definition language supported by the CORBA ORB. Java RMI TheRMI(RemoteMethodInvocation)isanAPIthatprovidesamechanismtocreatedistributedapplicationin java. The RMI allows an object to invoke methods on an object running in another JVM. The RMI provides remote communication between the applications using two objects stub and skeleton. Understandingstubandskeleton:RMIusesstubandskeletonobjectforcommunicationwiththeremoteobject. Aremote object is an object whosemethod canbe invoked from another JVM. Let's understandthe stub and skeleton objects: Stub The stub is an object, acts as a gateway for the client side. All the outgoing requests are routed through it. It residesattheclientsideandrepresentstheremoteobject.Whenthecallerinvokesmethodonthestubobject, it does the following tasks:
  • 11. 6 | P a ge WebServices  It initiates a connection with remote Virtual Machine (JVM),  It writes and transmits (marshals) the parameters to the remote Virtual Machine (JVM),  It waits for the result  It reads (unmarshals) the return value or exception, and  It finally, returns the value to the caller. Skeleton Theskeleton isanobject, actsasagateway for the serverside object. Allthe incoming requests areroutedthrough it. When the skeleton receives the incoming request, it does the following tasks:  It reads the parameter for the remote method  It invokes the method on the actual remote object, and  It writes and transmits (marshals) the result to the caller.  In the Java 2 SDK, a stub protocol was introduced that eliminates the need for skeletons. Figure1.4depictsthearchitecturalmodelofaJavaRMI-basedapplicationsolution. The Java RMI architecture is composed of the following components: RMI client  The RMI client, which can be a Java applet or a stand- alone application, performs the remote method invocations on a server object. It can pass arguments that are primitive data types or serializable objects. RMI stub The RMI stub is the client proxy generated by the rmi compiler (rmic provided along with Java developer kit—JDK) that encapsulates the network information of the server and performs the delegation of the method invocation to the server. The stub also marshals themethod arguments and unmarshals the return values from the methodexecution. RMI infrastructure  The RMI infrastructure consists of two layers: the remote reference layer and the transport layer.Theremotereferencelayerseparatesoutthespecificremotereferencebehaviorfromtheclientstub.It handles certain reference semantics like connection retries, which are unicast/multicast of the invocation requests.Thetransportlayeractuallyprovidesthenetworkinginfrastructure,whichfacilitatestheactualdata transferduringmethodinvocations,thepassingofformalarguments,andthereturnofbackexecutionresults. RMI skeleton The RMI skeleton, which also is generated using the RMI compiler (rmic) receives the invocation requestsfromthestub andprocessesthearguments(unmarshalling) anddelegates them totheRMIserver. Upon successfulmethodexecution,itmarshalsthereturnvaluesandthenpassesthembacktotheRMIstubviathe RMI infrastructure.
  • 12. 7 | P a ge WebServices RMIserverTheserveristheJavaremoteobjectthatimplementstheexposedinterfacesandexecutesthe client requests. It receives incoming remote method invocations from the respective skeleton, which passes the parameters after unmarshalling. Upon successful method execution, return values are sent back to the skeleton, which passes them back to the client via the RMI infrastructure. Developing distributed applications in RMI is simpler than developing with Java sockets because there is no need to design a protocol, which is a very complex task by itself. RMI is built over TCP/IP sockets, but the added advantage is that it provides an object-oriented approach for inter- process communications. Java RMI provides the Java programmers with an efficient, transparent communication mechanism that frees them of all the application-levelprotocolsnecessarytoencodeanddecodemessagesfordataexchange.RMIenablesdistributed resource management, best processing power usage, and load balancing in a Java application model. RMI-IIOP (RMI over IIOP) is a protocol that has been developed for enabling RMI applications to interoperate with CORBAcomponents. Although RMIhadinherentadvantages provided bythe distributed object modelofthe Java platform, it also had some limitations:  RMI is limited only to the Java platform. It does not provide language independence in its distributed model as targeted by CORBA.  RMI-based application architectures are tightly coupled because of the connection-oriented nature. Hence, achieving high scalability in such an application model becomes a challenge.  RMIdoesnotprovideanyspecificsessionmanagementsupport.Inatypicalclient/serverimplementation, the server has to maintain the session and state information of the multiple clients who accessit. Maintaining such information within the server application without a standard support is a complex task. EJB EJBisanacronymforenterprisejavabean.ItisaspecificationprovidedbySunMicrosystemstodevelopsecured, robust and scalable distributed applications. When use Enterprise Java Bean?  Application needs Remote Access. In other words, it is distributed.  Applicationneedstobescalable.EJBapplicationssupportsloadbalancing,clustering andfail-over.  Application needs encapsulated business logic. EJB application is separatedfrom presentation and persistent layer. Types of Enterprise Java Beans There are 3 types of enterprise bean in java.  Session Bean: Session bean contains business logic that can be invoked by local, remote orwebservice client.  MessageDrivenBean:LikeSessionBean,itcontainsthebusinesslogicbutitisinvokedbypassing message.  EntityBean:Itencapsulatesthestatethatcanbepersistedinthedatabase.Itisdeprecated.Now,itis replaced with JPA (Java Persistent API). Difference between RMI and EJB Both RMI and EJB, provides services to access an object running in another JVM (known as remote object) from another JVM. The differences between RMI and EJB are given below:
  • 13. 8 | P a ge WebServices Common Challenges in Distributed Computing Distributed computing technologies like CORBA, RMI, and EJB have been quite successful in integrating applicationswithinahomogenousenvironmentinsidealocalareanetwork.AstheInternetbecomesalogical solutionthatspansandconnectstheboundariesofbusinesses,italsodemandstheinteroperabilityofapplications across networks. This section discusses some of the common challenges noticed in the CORBA, RMI and EJB based distributed computing solutions:  Maintenance of various versions of stubs/skeletons in the client and server environments is extremely complex in a heterogeneous network environment.  Quality of Service (QoS) goals like Scalability, Performance, and Availability in a distributed environment consume a major portion of the application’s development time.  Interoperabilityof applications implementing different protocols onheterogeneous platformsalmost becomes impossible.  Most of these protocols are designed to work well within local networks. They are not very firewall friendly or able to be accessed over the Internet. Thebiggest problem with application integration withthistightly coupled approachspearheaded by CORBA, RMI, andEJBwasthatitinfluencedseparatesectionsofthedevelopercommunitywhowerealreadytiedtospecific platforms. Microsoft Windows platform developers used DCOM, while UNIX developers used CORBA or RMI. There was no big effort in the community to come up with common standards that focused on the interoperability between these diverse protocols, thus ignoring the importance, and hence, the real power of distributed computing. As the distributed technologies are having some challenges to achieve interoperability everybody is looking for a technology which provides interoperability. If everybody defines their own standards then we can’t achieve interoperability.Toachieveinteroperabilityallofusshouldfollowsamestandardsthat’swhereWS-I(Webservices Interoperability) non-profitable organization got started. This WS-I is governed by a Board of Directors consisting of the founding members (IBM, Microsoft, BEA Systems, SAP, Oracle, Fujitsu, Hewlett-Packard, and Intel) and two elected members (currently, Sun Microsystems and webMethods). Since joining OASIS, other organizations have joined the WS-I technical committee including CA Technologies, JumpSoft and Booz Allen Hamilton. The organization's deliverables include profiles, sample applications that demonstrate the profiles' use, and test tools to help determine profile conformance.
  • 14. 9 | P a ge WebServices According to WS-I, a profile is :- A set of named web services specifications at specific revision levels, together with a set of implementation and interoperability guidelines recommending how the specifications may be used to develop interoperable web services. WS-I Org Given 4 Versions of Web Services specifications. They are 1) BasicProfile1.0(B.P1.0) 2) BasicProfile1.1(B.P1.1) 3) BasicProfile1.2(B.P1.2) 4) BasicProfile2.0(B.P2.0)  B.P 1.0  Version 1.0 of this profile was released in early 2004.  B.P1.1Version1.1publishedin2006doesnothavethesamescopeasversion1.0.Thepartofversion 1.0dealing withserializationofenvelopes andtheirrepresentation inmessageshasbeenmovedtoanew profile called Simple Soap Binding Profile (SSBP)  B.P1.2 Version 1.2 wasfinalized in November 2010. The main new features arethe support for MTOM binary attachments andWS-Addressing  B.P2.0Version2.0wasalsopublishedinNovember2010.ItusesSOAP1.2,UDDI3andWS-Addressing As Every player in the market started providing support for Basic Profile Specifications given by WS-I, Sun also addeditssupportforBasicProfilespecificationsandadoptedthosespecificationsbyprovidingbelowAPIs. Java applications don’t know what is SOAP protocol and how to putxml into SOAP xml. Java must provide one api to work with SOAP. That’s where SUN provided SAAJ (soap with attachments apifor java). Javaapplications don’tknowhowtogenerateorreadWSDL. JavamustprovideoneapitoworkwithSOAP.That’s where SUN provided WSDL4J api. Java applications must connect with UDDI registry to publish/discover WSDL documents. That’s where JAX-R (Java API for XML Registries) api provided by sun to work with UDDI registries. Keeping all these APIs together, sun provided JAX-RPC AND JAX-WS APIS.
  • 15. 10 | P a ge Web Services Web Services Architecture Webservices arebasedon theconceptof service-orientedarchitecture(SOA). SOAisthelatestevolution of distributed computing, which enables software components, including application functions, objects, and processes from different systems, to be exposed as services. AccordingtoGartnerresearch(June15,2001),“Webservicesarelooselycoupledsoftwarecomponentsdelivered over Internet standardtechnologies.” In short, Web services are self-describing and modular business applications that expose the business logic as services over the Internet through programmable interfaces and using Internet protocols for the purpose of providing ways to find, subscribe, and invoke those services. Based on XML standards, Web services can be developed as loosely coupled application components using any programminglanguage,anyprotocol,oranyplatform.Thisfacilitatesdeliveringbusinessapplicationsasaservice accessible to anyone, anytime, at any location, and using any platform. Basic Operational Model of Web Services TheWeb Services architectureis baseduponthe interactions between threeroles: service provider, service registryandservicerequestor.Theinteractionsinvolvethepublish,findandbindoperations.Together,these roles and operations act upon the Web Services artifacts: the Web service software module and its description. In a typical scenario, a service provider hosts a network-accessible software module (an implementation of a Web service).TheserviceproviderdefinesaservicedescriptionfortheWebserviceandpublishesittoaservice requestor or service registry. The service requestor uses a find operation to retrieve the service description locally or from the service registry and uses the service description to bind with the service provider and invoke or interact with the Web service implementation. Service provider and service requestor roles are logical constructs and a service can exhibit characteristics of both. Below image illustrates these operations, the components providing them and their interactions. These roles and relationships are defined as follows: Service Provider: From a business perspective, this is the business that requires Service requestor. certain functions to be satisfied. From an architectural perspective, this is the application that is looking for and invoking or initiating an interaction with a service. The service requestor role can be played by a browser driven by a person or a program without a user interface, for example another Web service. Service Requestor: From a business perspective, this is the business that requires Service requestor. certain functions to be satisfied. From an architectural perspective, this is the application that is looking for and invoking or initiating an interaction with a service. The service requestor role can be played by a browser driven by a person or a program without a user interface, for example another Web service. Service Registry: Service registry. This is a searchable registry of service descriptions where service providers publish their service descriptions. Service requestors find services and obtain binding information (in the service descriptions) for services during development for static binding or during execution for dynamic binding. For statically bound service requestors, the service registry is an optional role in the architecture, because a service provider can send the description directly to service requestors. Likewise, service requestors can obtain a service description from other sources besides a service registry, such as a local file, FTP site, Web site, Advertisement and Discovery of Services (ADS) or Discovery of Web Services (DISCO).
  • 16. 11 | P a ge Web Services Operations in a Web Service Architecture ForanapplicationtotakeadvantageofWebServices,threebehaviorsmusttakeplace:publicationofservice descriptions, lookup or finding of service descriptions, and binding or invoking of services based on the service description. These behaviors can occur singly or iteratively. In detail, these operations are: PublishTobeaccessible,aservicedescriptionneedstobepublishedsothatthePublish.servicerequestorcan find it. Where it is published can vary depending upon the requirements of the application (see “Service Publication” for moredetails). FindInthefindoperation,theservicerequestorretrieves aservice description directlyFind.orqueriesthe service registry for the type of service required (see “Service Discovery” for more details). The find operation can be involved in two different lifecycle phases for the service requestor: at design time to retrieve the service’s interface description for program development, and at runtime to retrieve the service’s binding and location description for invocation. BindEventually,aserviceneedstobeinvoked.InthebindoperationtheserviceBind.requestorinvokesor initiates aninteractionwiththeservice atruntimeusingthebinding details inthe service descriptiontolocate, contact and invoke the service. Artifacts of a Web Service Service  Where a Web service is an interface described by a service description, its Service. implementation is theservice.Aserviceisasoftwaremoduledeployedonnetworkaccessibleplatformsprovidedbytheservice provider. It exists to be invoked by or to interact with a service requestor. It can also function as a requestor, using other Web Services in its implementation. Service Description  The service description contains the details of the interface and Service Description. implementation of the service. This includes its data types, operations, binding information and network location. Itcould alsoinclude categorization andothermetadata tofacilitate discovery andutilization by service requestors. The service description might be published to a service requestor or to a service registry. Consider the simple example shown below where a travel reservation services provider exposes its business applicationsasWebservicessupportingavarietyofcustomersandapplicationclients.Thesebusinessapplications areprovidedbydifferenttravelorganizationsresidingatdifferentnetworksandgeographicallocations.
  • 17. 12 | P a ge Web Services The following is a typical scenario: 1. The Travel service provider deploys its Web services by exposing the business applications obtained from differenttravelbusinesseslikeairlines,car-rental,hotelaccommodation,creditcardpayment,andsoforth. 2. Theserviceproviderregistersitsbusinessserviceswithdescriptionsusingapublicorprivateregistry.The registry stores the information about the services exposed by the service provider. 3. The customer discovers the Web services using a search engine or by locating it directly from the registry and then invokes the Web services for performing travel reservations and other functions over the Internet using any platform or device. 4. In the case of large-scale organizations, the business applications consume these Web services for providing travel services to their own employees through the corporate intranet. Thepreviousexampleprovidesasimplescenarioofhowanorganization’sbusinessfunctionalitiescanbeexposed as Web services and invoked by its customers using a wide range of application clients. Motivation and Characteristics Web-basedB2Bcommunicationhasbeenaroundforquitesometime.TheseWeb-basedB2Bsolutionsareusually based on custom and proprietary technologies and are meant for exchanging data and doing transactions over the Web. However, B2B has its own challenges. For example, in B2B communication, connecting new or existing applications and adding new business partners have always been a challenge. Due to this fact, in some cases the scalability of the underlying business applications is affected. Ideally, the business applications and information fromapartnerorganizationshouldbeabletointeractwiththeapplicationofthepotentialpartnersseamlessly without redefining the system or its resources. To meet these challenges, it is clearly evident that there is a need forstandardprotocolsanddataformattingforenablingseamlessandscalableB2Bapplicationsandservices.Web services provide the solution to resolve these issues by adopting open standards. Figure 2.2 shows a typical B2B infrastructure(e-marketplace)usingXMLforencodingdatabetweenapplicationsacrosstheInternet.
  • 18. 13 | P a ge Web Services Web services enable businesses to communicate, collaborate, and conduct business transactions using a lightweight infrastructure by adopting an XML-based data exchange format and industry standard delivery protocols. The basic characteristics of a Web services application model are as follows:  WebservicesarebasedonXMLmessaging,whichmeansthatthedataexchangedbetweentheWeb service provider and the user are defined in XML.  Web services provide a cross-platform integration of business applications over the Internet.  To build Web services, developers can use any common programming language, such as Java, C, C++, Perl, Python, C#, and/or Visual Basic, and its existing application components.  Web services are not meant for handling presentations like HTML context—it is developed to generate XML for uniform accessibility through any software application, any platform, or device.  BecauseWebservicesarebasedonlooselycoupledapplicationcomponents,eachcomponentisexposed as a service with its unique functionality.  Web services use industry-standard protocols like HTTP, and they can be easily accessible through corporate firewalls.  Web services can be used by many types of clients.  Web services vary in functionality from a simple request to a complex business transaction involving multiple resources.  All platforms including J2EE, CORBA, and Microsoft .NET provide extensive support for creating and deploying Web services.  Web services are dynamically located and invoked from public and private registries based on industry standards such as UDDI and ebXML. Why to Use Web Services? Traditionally, Web applications enable interaction between an end user and a Web site, while Web services are service-oriented and enable application- to-application communication over the Internet and easy accessibility to heterogeneousapplicationsanddevices.ThefollowingarethemajortechnicalreasonsforchoosingWebservices over Web applications:  Web services can be invoked through XML-based RPC mechanisms across firewalls.  Web services provide a cross-platform,cross-language solution basedonXML messaging.
  • 19. 14 | P a ge Web Services  Webservices facilitate easeof application integration using a light- weight infrastructure without affecting scalability.  Web services enable interoperability among heterogeneous applications. Core Web Services Standards The five core Web services standards and technologies for building and enabling Web services are XML, SOAP, WSDL and UDDI. An overview of each is presented in the following sections. Extensible Markup Language (XML) In February 1998, the Worldwide Web Consortium (W3C) officially endorsed the Extensible Markup Language (XML) as a standard data for- mat. XML uses Unicode, and it is structured self-describing neutral data that can be storedasasimpletextdocumentforrepresentingcomplexdataandtomakeitreadable.Today,XMListhede facto standard for structuring data, content, and data format for electronic documents. It has already been widely accepted asthe universal language lingua franca for exchanging information between applications, systems, and devicesacrosstheInternet.InthecoreoftheWebservicesmodel,XMLplaysavitalroleasthecom-monwire format in all forms of communication. XML also is the basis for other Web services standards. By learning XML, youwillbewellpreparedtounderstandandexploreWebservices.FormoreinformationonXML,gotoChapter 8, “XML Processing and Data Binding with Java APIs,” or to the official W3C Web site for XML at www.w3c.org/XML/. Simple Object Access Protocol (SOAP) SimpleObjectAccessProtocol,orSOAP,isastandardforalightweightXML-basedmessagingprotocol.Itenables anexchangeofinformationbetweentwoormorepeersandenablesthemtocommunicatewitheachotherina decentralized, distributed application environment. Like XML, SOAP also is independent of the application object model, language, and running platforms or devices. SOAP is endorsed by W3C and key industry vendors like Sun Microsystems, IBM, HP, SAP, Oracle, and Microsoft. These vendors have already announced their support by participatingintheW3CXMLprotocol-workinggroup.TheebXMLinitiativefromUN/CEFACTalsohasannounced its support forSOAP. SOAP consists of three parts: an envelope that defines a framework for describing what is in a message, a set of encodingrulesforexpressinginstancesof application-defineddatatypes,andaconventionforrepresenting remoteprocedurecalls(RPCs)andresponses.SOAPcanbeusedincombinationwithorre-envelopedbyavariety of network protocols such as HTTP, SMTP, FTP, RMI over IIOP or MQ.
  • 20. 15 | P a ge WebServices As per above diagram  At (1) a service requestor’s application creates a SOAP message. This SOAP message is the request that invokestheWebserviceoperationprovidedbytheserviceprovider.TheXMLdocumentinthebodyof the message can be a SOAP RPC request or a document-centric message as indicated in the service description.Theservicerequestorpresents thismessage togetherwiththenetworkaddressoftheservice provider to the SOAP infrastructure (for example, a SOAP client runtime). The SOAP client runtime interacts withanunderlying network protocol (for example HTTP) to send the SOAP message outover the network.  At (2) the network infrastructure delivers the message to the service provider’s SOAP runtime (for example a SOAP server). The SOAP server routes the request message to the service provider's Web service. The SOAP runtime is responsible for converting the XML message into programming language- specificobjects ifrequired bytheapplication.Thisconversion isgoverned bytheencoding schemes found within the message.  TheWebservice is responsible for processing the requestmessage andformulating aresponse.The response isalso a SOAPmessage. At(3)the response SOAPmessage ispresented tothe SOAP runtime with the service requestor as the destination. In the case of synchronous request/response over HTTP, the underlying request/response nature of the networking protocol is used to implement the request/response natureofthemessaging.The SOAPruntime sendstheSOAPmessageresponsetothe service requestor over the network.  At (4) the response message is received by the networking infrastructure on the service requestor’s node. The message is routed through the SOAP infrastructure; potentially converting the XML message into objects in a target programming language. The response message is then presented to the application. Web Services Definition Language (WSDL) The Web Services Description Language (WSDL) is an XML-based interface definition language that is used for describing the functionality offered by a web service. The acronym is also used for any specific WSDL description of a web service (also referred to as aWSDLfile), which provides a machine-readable description of howthe servicecanbecalled,whatparametersitexpects,andwhatdatastructuresitreturns.Therefore,itspurposeis roughly similar to that of a type signature in a programming language. The current version of WSDL is WSDL 2.0. The meaning of the acronym has changed from version 1.1 where the "D" stood for"Definition".
  • 21. 16 | P a ge Web Services Types  a container for data type definitions using some type system (such as XSD). Message  an abstract, typed definition of the data being communicated. Operation  an abstract description of an action supported by the service. Port Type  an abstract set of operations supported by one or more endpoints. Bindingaconcreteprotocolanddataformatspecificationforaparticularporttype. Port  a single endpoint defined as a combination of a binding and a network address. Service  a collection of relatedendpoints. Universal Description, Discovery, and Integration (UDDI) Universal Description, Discovery, and Integration, or UDDI, defines the standard interfaces and mechanisms for registries intended for publishing and storing descriptions of network services in terms of XML messages. It is like theyellowpagesoratelephone directory where businesses listtheir products andservices. Webservices brokers use UDDI as a standard for registering the Web service providers. By communicating with the UDDI registries, the service requestors locate services and then invoke them. UDDI was included in the Web Services Interoperability (WS-I) standard as a central pillar of web services infrastructure,andtheUDDIspecificationssupportedapubliclyaccessible Universal Business Registry inwhich a naming system was built around the UDDI-driven service broker. UDDI has not been as widely adopted as its designers had hoped. IBM, Microsoft, and SAP announced they were closing their public UDDI nodes in January 2006. The group defining UDDI, the OASIS Universal Description, Discovery, and Integration (UDDI) Specification Technical Committee voted to complete its work in late 2007 and has been closed. In September 2010, Microsoft announced they were removing UDDI services from future versions of the Windows Server operating system. Instead, this capability would be moved to BizTalk Server.In 2013, Microsoft further announced the deprecation of UDDI Services in BizTalk Server. A UDDI business registration consists of three components:  White Pages — address, contact, and known identifiers;  Yellow Pages — industrial categorizations based on standard taxonomies;  Green Pages — technical information about services exposed by the business.
  • 22. 17 | P a ge Web Services XML
  • 23. 18 | P a ge Web Services Introduction  XMl stands for extensible markup language  Unlike C, C++ and Java etc. Xml is not a programming language. It is a markup language  XMl was designed for transport and store data  XML was defined and governed by W3C Org  The first and final version of XML is XML 1.0 XML is not a database: You’re not going to replace an Oracle or MySQL server with XML. A database can containXMLdata.Eitheras a VARCHARoraBLOBorassomecustomXML datatype,butthedatabase It self is not an XML document. You can store XML data in database on a server or retrieve data from a database in XML format. What is mean by Extensible: Extensible means that the language can be extended and adapted to meet many different needs. i.e XML allows developers and writers to invent the elements they need as they need them. There issomeothermarkup language alsothere inthemarketthatis HTML HTML was designed to display data, with focus on how data looks. Differences between HTML and XML XML HTML 1) Extensible markup language 1) Hypertext markup language 2) It is usedfortransport andstorethedata 2) It is used to display data 3) All the Elements are user-defined 3)AlltheelementsinHTMLarepredefined 4) It has infinite set of tags 4) It has finite set of tags 5) XML documents are re-usable 5)HTMLdoesnotsupportforre-usability 6) Every start tag must have end tag 6) Every start tag need not have end tag 7)XMLisDYNAMIC(i.e.Contentischanged every time page is loaded) 7) HTML is static( i.e. Content does not changedeverytimepageisloaded) 8)XMLattribute value mustbeenclosed with quote(") 8) HTML attribute value can be present without quotationmark 9) It is case-sensitive 9) It is not case sensitive Everylanguagehaskeywords,IfyoutakeexampleasC,ithaskeywordslike(if, for,while,do,break,continue etc.)but whenitcomestoXMLthereare no keywords orreservedwords.Whateveryouwritewillbecomethe element of that XML document. XML Declaration Every XML document must start with PROLOG: - prolog stands for processing instruction, and typically used for understanding abouttheversion of XML used andthe data encoding used. Example: -<? xml version=”1.0” encoding=”UTF-8” standalone=”yes”?> <?Xml:XMLparserusesthefirstfivecharacters(<?xml)tomakesomereasonableguessabouttheencoding such as whether the document uses single-byte or multi-byte character set. Version:Theattributeshouldhaveallthevalue1.0.Underveryunusualcircumstances,itmayalsohavethe value 1.1. Since specifying version=”1.1” limits the document to the most recent versions of only a couple of
  • 24. 19 | P a ge WebServices parsers, and since all Xml 1.1 parsers must also support XML 1.0, you don’t want to casually set the version 1.1. Encoding:XMLdocumentsareassumedtobeencodedintheUTF-8variablelengthencodingoftheUnicode character set. This is strict superset of ASCII, so pure ASCII text files are also UTF-8 documents. Standalone: Standalone attribute accepts only 2 values i.e. 1) no 2) yes If standalone=”no”: - Application may be required to read an external DTD If standalone=” yes” :- Application need to read internal DTD XMlElement:Thedatabetweenangularbrackets(i.e.“<>”)iscalledElement Ex: employee Tag: The element with includes angle brackets is called Tag. Ex: <employee> In XML there are two types of elements as follows StartElement/OpeningTag:-Startelementistheelementwhichiswritten in<elementname> indicating the start of a block. End Element/End Tag: - End element is the element which is written in </elementname> indicating the end of a block. An Element can contain: 1. Other elements (childelements) 2. Text-data 3. Attributes 4. Mix of all XML elements naming rules  Elements names arecase-sensitive  Element name must start with letter or underscore  Element name cannot start with letter xml (Or XML, or Xml etc.)  Element name cannot containspaces  Any name can be used, no word are reserved except XML. XML Attribute If we wantto have additional informationattachtoan element, instead of having it as content or another element, we can write it as an Attribute of the element. Example: <employee type= ”permanent”> <id> 1001 </id> </employee> Intheaboveexample“employee”isanelementwhichcontainsoneattributestype whichactsasa supplementaryinformation, <id>is thesub-elementof the<employee> element. Note: Attributes must be enclosed with single quote or double quotes <employeeid=”101”name=”Ashok”/>(Valid) <employeeid=”101”name=Ashok/>(In-valid)
  • 25. 20 | P a ge Web Services XML Comments XMLcommentsaresyntacticallysimilartoHTMLcomments Syntax: <! - - This is the comment- - > Predefined Entities Some characters have meaning in XML ForExample:If youplacea characterlike“<”insideXML element,itwillgenerate errorbecausetheparser interprets it as the start of new element. The following code will generate an XML error <salary> if salary <15000 then </salary> To avoid above error replace “<” character with entity reference <salary>ifsalary&lt;15000then</salary> Lessthan(<) : &lt; Greater than (>) : &gt; Ampersand (&) : &amp; Apostrophe (‘) : &apos; Quotation (“) : &quot; XML Well-formness Ashowanyprograminglanguagehassyntaxinwritingitscode,Well-formnessof XMLdocumenttalksabout howtowriteanXMLdocument.Well-formnessindicates thereadabilitynatureofanXMLdocument.In other way if anXML document is said to be well-formed then it is readable in nature. Following are the rules that describe the Well-formness of an XML Document. * EveryXMLdocument muststart withPROLOG: -prolog standsforprocessing * Every start tag must have end tag * Elementsmaynestbutmaynotoverlap * There must be exactly one root element * Attribute value must bequoted * An element cannot have two attributes with same name Well-formed XML Not Well-formed XML <employee> <id>1208</id> <name>Ashok</name> </employee> <employee type=permanent> <id>1208</id> <name>Ashok</name> </employee> Reason: It follows all the XML rules Reason: attribute values is not enclosed with "
  • 26. 21 | P a ge Web Services Not Well-formed XML Not Well-formed XML <employee> <id>1234</id> <name>Ashok</name> </employee> <employee> <id>2456</id> <name>Ashok</name> <employee> <employee> <id>1234 <name>Ashok<name> </employee> Reason: Only one root element is allowed Reason: Tags are not ended properly For checking whether the XML document is well-formed or not some of the editors are there. They are 1) XMLcopyeditor 8) WMHelp XMLpad 2) EditXMLEditor 9) XMLLmind XMLEditor 3) AltovaXMSpy 10) Notepad++ 4) Oxygen XML Editor 5) XML Writer XMLEditor 6) Stylus Studio 7) Liquid XML Studio XML Validation EveryXMLin-ordertoparse(read)shouldbewell-formedinnature.Assaid earlierwell-formnessofanXML documentindicates whether it is readable or not, it doesn’t talk about whether the data contained in it is valid ornot. ValidityoftheXMLdocumentwouldbedefinedbytheapplicationwhichisgoing toprocessyourXML document. Let’s considera scenario as follows.
  • 27. 22 | P a ge Web Services Intheabovepurchase-order.xmleventhoughitconfirmstoallthewell-formness rules,itcannot beusedfor businesstransaction,asthe<quantity>elementcarriesthedata as“xyz”whichdoesn’tmakesanysense. So,in orderto check fordata validity, we need to define thevalidationcriteria of anXML documentineither a DTD or XSD document.
  • 28. 23 | P a ge Web Services DTD
  • 29. 24 | P a ge Web Services Introduction  DTD stands for Document Type Definition.  Itisthedocumentwhichdefinesthe structure and the legal elements and attributes of an XML document  An application can use a DTD to verify that XML data is valid  Inalanguagebeforeusingavariableweneedtodeclareit.Similarly,beforeusing anelementinXML first we need to declare it in DTD.  DTDfileswillbesavedwith.dtdextension Before start writing DTD, first we need to know two kinds of elements. They are 1) Simple Elements 2) Compound Elements Let us take a sample po.xml file to demonstrate these elements SimpleElements: Elementswhichcarrydata arecalledsimpleelements. Simple element cancontain only value (data). It may not contain any child. In the above XML file, simple Type elements are: itemCode, quantity, addrLine1, addrLine2, city, state, zip and county.
  • 30. 25 | P a ge WebServices Compound Elements: An element which contains sub-elements under it is called compoundelement. For above xml, DTD looks like shown below Occurrences of an Element under another element Intheabovexmlifweobservethe<items>element,itcancontainanynumber of<orderItems>elementsin it, butat least one item elementmust betherefor a <purchaseOrder>.Thisiscalledoccurrenceofan element underanother element, to indicate this we usethree symbols. ? – Represents the sub element under a parent element can appear zero or one- time (0/1). + - indicates the sub element must appear at least once and can repeat any number of times (1 – N) * -indicatesthesubelementisoptionalandcanrepeatanynumberoftimes (0-N) Youwillmark theoccurrenceof anelementunderanotherelementasfollows. <! Elementelementname(sub-elem1(? /+/*),sub-elem2 (? /+/*)> Leaving any element without any symbol indicates it is mandatory and at max can repeat only once. Elements with any contents Elements declared with the content type as ANY, can contain any combination of parsable data. <! ELEMENT elementname ANY> <! ELEMENT mailBody ANY> In an e-mail body part we have content which can be mixture of any parsable characters which can be declared as ANY type.
  • 31. 26 | P a ge <mail> <to>toaddr.com</to> <from>fromaddr.com<from> <subject>mysub</subject> </mail> <(OmRa)il> <to>toaddr.com</to> <from>fromaddr.com<from> <mailBody>mysub</mailBody> </mail> WebServices Elements with either/or content Let’s consider an example where in an email the following elements will be there to, from, subject and mailBody.IntheseelementstoandfromormandatoryelementsandeithersubjectormailBodyshouldbe present but not both. To declare the same we need to use or content separator instead of sequence separator. <! ELEMENT mail (to, from, (subject | mailBody)> Fortheabovedeclarationthexmllooksasbelow. Declaring Mixed content We can even declare an element with mixture of parable data and elements called mixed content as follows. <! ELEMENTmail (#PCDATA|to|from| subject|mailBody)*> Declaring attribute for an element Attributes provide extra information about elements Syntax: - <! ATTLIST elementNameattributeName attributeType attributeValue> AsshownabovetodeclareanattributeyouneedtousethetagATTLISTand elementnamestandsforwhich element you want to declare the attribute and attributeName stands for what is the attribute you want to have in that element. The attributeType can be the following: Type Description CDATA The value is Character data (en1|en2|..) Thevaluemustbeonefromthe enumerated list of values. ID The value is unique id. IDREF The value is the id of another element NMTOKEN The value is a valid XML element name
  • 32. 27 | P a ge WebServices The attributeValue can be the following: Value Description #REQUIRED The attribute is required #IMPLIED The attribute is not required #FIXED value The attribute value is fixed. Default Attribute Value <! ELEMENTshippingAddress (addressLine1, addressLine2, city, state, zip, country)> <! ATTLISTshippingAddress type CDATA “permanent” > #REQUIRED <!ATTLISTshippingAddresstypeCDATA#REQUIRED>thisindicatestype attributeismandatoryin shippingaddress element. #IMPLIED <! ATTLISTshippingAddresstypeCDATA#IMPLIED>,thisindicatesthetype attributein shippingAddress elementisoptional. #FIXED <! ATTLISTshippingAddress typeCDATA #FIXED“permanent”>,thisindicatesthe type attribute in shippingAddress elementmustcontainonlythe value as permanent. Enumerated Attribute Values ThisindicatesthetypeattributeinshippingAddresselementshouldcontainonly twopossiblevalueseither permanent ortemporary. DTDs are divided into 2 types 1. Internal DTD 2. External DTD Internal DTD If the DTD is declared inside the XML file, it should be wrapped in a DOCTYPE definition with the following syntax:
  • 33. 28 | P a ge WebServices Below is the sample XML with Internal DTD External DTD ExternalDTDaresharedbetweenmultipleXMLdocuments.AnychangesareupdateinDTDdocument effect or updated come to all XML documents. External DTD two type: a. Private DTD b. Public DTD Private DTD Private DTD identify by the SYSTEM keyword. Access for single or group of users. YoucanspecifyrulesinexternalDTDfile.dtdextension.LaterinXMLfile<!DOCTYPE...>declarationto linking this DTDfile. PublicDTDPublicDTDidentifybythePUBLICkeyword.AccessanyusersandourXMLeditorareknowthe DTD.
  • 34. 29 | P a ge WebServices Below XML is linked with Public DTD Once DTD is linked with XML then we can validate our XML against DTD (see in below image)
  • 35. 30 | P a ge Web Services Drawbacks with DTD It doesnot support the namespaces. Namespace is a mechanism by which element and attribute names canbeassignedtogroups.However,inaDTDnamespaceshouldbedefinedwithintheDTD,which violates the purpose of using namespaces. It supports only the text string data type. It is not object oriented. Hence, the concept of inheritance cannot be applied on the DTDs. Limited possibilities to express the cardinality for elements. To overcome the above drawbacks of DTD we will use XSD to define structure of the XML.
  • 36. 31 | P a ge Web Services XSD
  • 37. 32 | P a ge Web Services Introduction XML Schema is an XML-based alternative to DTDs. An XML Schema describes the structure of an XML document. The XMLSchema languageisalso referredtoas XML SchemaDefinition (XSD).ThepurposeofanXMLSchemaistodefine the legal building blocks of an XML document, just like a DTD.  XSD stands for XML Schema Definition  XSD owned by world wide web consortium (W3Org)  In 2001,theW3Cdevelopeda newschema languageto addressmanyof theshortcomingsof DTD  XSD schema is used to define the structure of an XML document  The main goal of XSD is to validate the XML document whether it is valid or not  XSD is also an xml (It is special XML with fixed structure and fixed elements)  XSD is more powerful and type strict in nature  Schemas are another approach used by the XML parser to validate an XML document  It is text file with .xsd extension An XML Schema defines Elements that can appear in a document Defines attributes that can appear in a document Defines which elements are child elements Defines the order of child elements Defines the number of child elements Defines whether an element is empty or can Defines data types for elements and attributes Defines default and fixed values for elements and attributes XML Schemas are richer and powerful than DTD because: 1. XML Schemas are extensible to future additions 2. XML Schemas themselves are written in XML 3. XML Schemas support data types 4. XML Schemas support namespaces XML Schemas are Extensible XML Schemas are extensible, because they are written in XML. With an Extensible Schema definition we can: 1. Reuse one Schema in other Schemas 2. Create our own data types derived from the standard types 3. Reference multiple schemas in the same document Data types OneofthegreateststrengthofXMLSchemasisthesupportfordatatypes.Byusingdatatypes,itis easierto: 1. Describe allowable document content 2. Validate the correctness of data 3. Work with data from a database 4. Define data facets (restrictions on data) 5. Define data patterns (data formats)
  • 38. WebServices As XSDis also an xml,it will start with aprologandit also contains only oneroot element. The<schema> element is the root element of every XML Schema. The <schema> element contains following attributes: Attribute name Description Example xmlns:xs Elements and Data types from “http://www.w3.org/2001/XMLSchema" namespace. xmlns:xs=” http://www.w3.org/2001/XMLSchema” targetNamespace User defined elements and data types in our schemabelongstoournamespacesuch as “www.ashoksit.com” targetNamespace=”www.ashoksoft.com”> Xmlns Indicates default name space. Xmlns=”www.ashoksoft.com” elementFromDefault Elements must be namespace qualified. elementFromDefault=”qualified” The above attributes we discuss in detail in XSD namespaces concept. As we have already discussed in DTD, an XML contains 2 types of elements. They are 1) Simple Elements 2) Compound Elements InJava,wehavetostoresomevalueintoavariable,firstweneedtodeclarethevariablesimilarlyifwewantto write one element in XML first we should declare that element in DTD or XSD. Declaring Simple Elements in XSD Name – name attributes holds element name Type - type attribute holds element data type Declaring Compound Elements in XSD Ifwewanttosomevalueintoavariablefirstwemustdeclareavariablewithdatatype(Basedonnatureofthe data we want to store into that variable we will decide data type for that variable). IfwewanttostoreapersonnameintovariablethenwewillchooseStringdatatypelikebelow String personName; Ifwewanttostorepersonagethenwewilldeclareavariablewithintdatatypelikebelow Int personage; Similarly, I want to store student details like rollNumber, name and rank in a variable called ‘s’. Do we have any predefined datatype in Java to store student values (rollNumber, name and rank) like this? – We don’t have any such datatype injava. Aswedon’thaveanypredefineddatatype,wemustcreateourowndatatypefor‘s’variabletostorestudent values.WecanconsiderClassasauser-defineddatatypesowewillcreateaStudentclasstostorestudentdetails and we can use that Student class as a data type for variable ‘s’ like below 33 |P a ge
  • 39. Web Services 34 | P a ge IfwewanttowriteoneelementinXMLfirstweshoulddeclareinXSD.Iwanttowriteoneelement<order-item> in xml likebelow Note: As we can see <order-item> contains child elements this is called Compound element. To write <order-item> element in XML first we should declare this element in XSD with data type. What datatype we can use for <order-item> element? – It’s based on nature of the data we want to store. In<order-item>Iwanttostore<item-code>and<quantity>elements.DowehaveanydatatypeinXSDtostore <item-code> and <quantity> elements? – No. AsdiscussedabovetostoreStudentdatawehavedon’thavepredefineddatatypehencewehavecreated Studentclassasuser-defineddatatype. Similarly,aswedon’thaveanypredefined datatypefor<order-item>we havetocreateuser-defineddatatypeinXSD.TocreateUser-defineddatatypesinXSDwewilluseComplexType. AcomplextypeelementisanXMLelementthatcontainsotherelementsand/orattributes.Injava wewill useClassto create user-defined datatypeandin XSDwewill useComplexTypetocreateuser- defined data type. Declaring <order-item> as compound element in XSD
  • 40. Web Services 35 | P a ge Note: <xs:sequence /> represents child elements should be in same order Now we understood how to declare Simple Elements and Compound elements in XSD so let'stake our PO.xml and writePO.xsd PO.xml From the above XML identity Compound Elements and Simple Elements and declare them in XSD PurchaseOrder, order-items, item and shipping-address are compound elements. To declare these compound elementswe needComplexTypes (Foreachcompoundelementwe needone complextype). Item-code, quantity, addrLine1, addrLine2, city, state, country and zipcode are Simple Elements As XSD is also an XML it will start with Prolog XSD contains only one root element that is <xs:schema /> Inside <xs:schema /> we can declare both Simple elements and compound elements
  • 41. Web Services 36 | P a ge Below is the PO.xsd which represents structure of PO.xml In the approach, first we have taken XML and we have created XSD. XSDRepresentsStructureoftheXML XML  Holds the data As XSDrepresents the structure ofthe XML,firstweshould create XSDandthen we need to create the XML to storethedataintheformofelements.OncedataisstoreinXML,wecanvalidateourXMLagainstXSD. To Validate XML against XSD, we should link XSD with our XML like below Xmlns:xsi :- It represents XMLSchema-instance Namespace Xsi:noNamespaceSchemaLocation :- Represents XSD file name (No namespaces in XSD) Note : If we have namespaces in XSD then we should use xsi:schemaLocation attribute to link XSD to xml.
  • 42. 37 | P a ge WebServices Linking PO.xsd to PO.xml OnceXSDislinkedtoXML,wecanvalidateourxmlagainstXSDusingAltovaXMLSpytool(usingF8shortcutkey). Element Cardinality Itispossibletoconstrainthenumberofinstances(cardinality)ofanXMLelementthatappearinanXML document.Thecardinality isspecifiedusingtheminOccurs andmaxOccursattributes,andallowsanelementto be specified as mandatory, optional, or can appear upto a set number of times. The default values for minOccurs andmaxOccursis1.Therefore,ifboththeminOccurs andmaxOccursattributesareabsent,asinallthe previous examples, the element must appear once and once only. minOccurscanbeassignedanynon-negativeintegervalue(e.g.0,1,2,3...etc.),andmaxOccurscanbeassigned any non-negative integer value or the special string constant "unbounded" meaning there is no maximum so the element can occur an unlimited number of times.
  • 43. 38 | P a ge WebServices Defining Compositors Compositors provide rules that determine how and in what order their children can appear within XML document. There are three types of compositors. They are 1. <xs: sequence> 2. <xs: choice> 3. <xs: all> <xs: sequence /> element The <sequence> indicator specifies that the child elements must appear in a specific order: <xs: all />element The <all> indicator specifies that the child elements can appear in any order, andthateach child element must occur onlyonce:
  • 44. 39 | P a ge WebServices <xs: choice /> element XMLSchema<choice>element allowsonlyoneofthe elementscontainedin the<choice>declarationto be present within the containing element. As per above XSD, ShippingAddress can contain either office-address or home-address but not both Global elements with ref attribute in XSD If we declare an element inside ComplexType then it is called as local element Ifwedeclareanelementinside<xs:schema>directlythenthatiscalledasglobalelement. If Multiple ComplexTypes want to use same name for the element with same data type then we can use Global Elements with ref attribute
  • 45. 40 | P a ge Web Services Let’s take BookStore.xml to demonstrate this BookStore.xsd for above BookStore.xml IfweseeintheaboveBookStore.xsd,“name”elementisdeclaredin2complextypes(Duplicateelement declarationsarepresented).Toavoidduplicateelementdeclarations, wecanuseGlobalElementfor“name” element likebelow
  • 46. 41 | P a ge Web Services <xsd:group> Element If we want to re-use group of elements in several complextypesthen we canuse <xsd: group> element Lets’ take Bank-Account.xml to demonstrate this Inthebank-account.xml, both<savings-account/>and<current-account/>havingbelowthree elements ascommon
  • 47. 42 | P a ge Web Services  <acc-id />  <holder-name />  <branch-name /> Insteadofwritingthese3elementsasglobalelements,wecancreatethemasagroupinxsdlikebelow Now we can reference to this “AccDetailGroup” in multiple complextypes to use acc-id , holder-name and branch-nameelements. The modified bank-account.xsd is below (With Group element)
  • 48. 43 | P a ge Web Services Inheritance in XSD Complextype extensionsarequite similartotheinheritanceinJavaandotherobject-orientedlanguages. New complex types can be derived by extending existing complex types. Now let’s take an travel-agency.xml to demonstrate this Intheabovexml,both<DomesticFlight/>and<InternationalFlight />complextypesaresome commonelements. So in XSD we can extend one complextype from another to re-use the elements In below XSD <InternaltionFlight /> complextype is extending elements from <DomesticFlight /> complextype
  • 49. 44 | P a ge Web Services Attributes in XSD An attribute provides extra information within an element. Attributes have name and type properties and are defined within an XSD as follows: An attribute is specified within a xs:complexType, the type information for the attribute comes from a xs:simpleType (either defined inline or via a reference to a built inor user defined xs:simpleType definition). The Type information describes the data the attribute can contain in the XML document, i.e. string, integer, date etc. Attributes can also be specified globally and then referenced.
  • 50. 45 | P a ge Web Services  Mandatory Attribute: <attribute name= “empNo" type= “int“ use=“required”/>  Default Attribute: <attribute name= “name” type= “string” default= “guest”/>  Fixed Attribute: <attribute name= “salary” type= “decimal” fixed= “10000”/> Note:Thedefaultand fixed attributescanbespecified within theXSDattributespecification (inthe sameway as they are for elements). Element with attributes An empty complex element means no content rather only attributes. In the example above, we define a complex type with a complex content. The complexContent element signals thatweintendtorestrictorextendthecontentmodelofacomplextype,andtherestrictionofintegerdeclares one attribute but does not introduce any element content. Example: <product id=”12345”/> Element with attributes and text Itcontainsonlytextandattributesi.e.,itcontainsonlysimplecontent(textandattributes),thereforeweadda simpleContentelementaroundthecontent.WhenusingsimpleContent,wemustdefineanextensionor restriction within the simpleContent element. Note: Use the extension/restriction element to expand or to limit the base simple type for the element.
  • 51. 46 | P a ge Web Services Example: <shoesize country="france">35</shoesize> Element with sub elements and text An XML element contains both text and sub elements. Example: <letter> </letter> DearMr.<name>JohnSmith</name>.Yourorder<orderid>1032</orderid>. Will be shipped on <shipdate>2001-07-13</shipdate>. Sample XSD AspertheaboveXSD,givenXMLisvalidornot?-Itisvalidonlybecausexsdsayszipcodeshouldcontain int valueandxmlhavingintvalueonlybutpracticallyzipcodeshouldnotbesingledigitthenhowtovalidate particularelementshouldcontainspecificNo.ofdigits?-That’swhereRestrictionscomesintopictureinXSD.
  • 52. 47 | P a ge Web Services Primitive types The following table summarizes Primitive types in XML Schema Definition: Primitive type Description Example Decimal Specifies numeric value including fractional part. <prize>999.50</prize> Float Double Boolean Specifies true or false value. String Thestringdatatypecancontaincharacters,linefeeds, carriage returns, and tab characters. <customer>John Smit</customer> Date The date format is always as: YYYY-MM-DD. <start>2012-01-21</start> Time The time format is always as: hh:mm:ss <time>09:00:00</time> dateTime The dateTime format is always as: YYYY-MM- DDThh:mm:ss <startdate>2012-01- 21T09:00:00</startdate> gYearMonth Definesapartofadate-theyearandmonth(YYYY- MM) gYear Defines a part of a date - the year (YYYY) gMonthDay Definesapartofadate-themonthandday(MM-DD) gDay Defines a part of a date - the day (DD) gMonth Defines a part of a date - the month (MM) Duration Defines a time interval <period>P5Y2M10DT15H</period> The example above indicates a periodoffiveyears,twomonths,10 days, and 15 hours. Base64Binary Base64-encoded binary data hexBinary hexadecimal-encoded binary data anyURI QName NOTATION Derived Types: The following table summarized the derivedtypes Derived type Description Example integer Derived from decimal type without fractional part. Long Derivedfromdecimal,whichissigned64-bitinteger. Int Derivedfromdecimal,whichissigned32-bitinteger. Short Derivedfromdecimal,whichissigned16-bitinteger. Byte Derived from decimal, which is signed 8-bit integer. nonPositiveInteger Anintegercontainingonlynon-positivevalues(..,-2,- 1,0) negativeInteger An integer containing only negative values(…,-2,-1) nonNegativeInteger Anintegercontainingonlynon-negativevalues (0,1,2,..) UnsignedLong Derived from decimal, which is unsigned 64-bit integer. UnsignedInt Derivedfromdecimal,whichisunsigned32-bitinteger. UnsignedShort Derived from decimal, which is unsigned 16-bit integer. UnsignedByte Derivedfromdecimal,whichisunsigned8-bitinteger. PositiveInteger An integer containing only positive values(1,2…).
  • 53. 48 | P a ge Web Services normalizedString Derived from string type. Contains only characters without line feeds, carriage returns, and tab characters. <customer>John Smith</customer> Token Derivedfromstringtype.Containsonlycharacters withoutlinefeeds,carriage returns,tabs, leading and trailing spaces, and multiple spaces. <customer>John Smith</customer> Language A string that contains a valid language id. Name A string that contains a valid XML name. NCName Name without colons but allows characters such as hyphens. bold_brash is valid. bold:brash is invalid. ID Only used with attributes. IDREF IDREFS ENTITY ENTITIES NMTOKEN Derived fromstring,whichdoesnotacceptCommas, Leadingortrailing whitespacewillberemoved. Used with only attributes. “x, y” is invalid. “x y” is valid. Built-in types with restrictions The built-in types with restrictions are simple types. Restrictionsareusedto defineacceptablevaluesfor XMLelementsorattributes.RestrictionsonXML elements are called facets. Restriction on values Following example defines an element named “age” with a restriction. The value of the age element cannot be lower than 21 and greater than 60. Restriction on Set of values To limit the content of an XML element to a set of acceptable values, we would use the enumeration constraint.
  • 54. 49 | P a ge Web Services Restrictions on Series of Values The ‘pattern’ constraint is used to limit the content of xml element to define a series of numbers or letters. Example#1:TheonlyacceptablevalueisTHREEoftheLOWERCASEorUPPERCASElettersfromatozorAtoZ. Example #2: The acceptable value is zero or more occurrences of lowercase letters from a to z. Example #3: The only acceptable value is male OR female. Restrictions on Length Tolimitthelength ofavalueinanelement,wewould usethelength, maxLength, andminLengthconstraints. Example #1: This exampledefines an element called "password" with arestriction. The value must be exactly eight characters:
  • 55. 50 | P a ge WebServices Example #2: This example defines another element called "password" with arestriction. The value must be minimum five characters and maximum eight characters: The following table summarizes attributes related to restrictions CONSTRAINT DESCRIPTION Enumeration Defines a list of acceptable values Length Specifiestheexactnumberofcharactersorlistitemsallowed.Mustbeequaltoorgreaterthanzero maxLength Specifies the maximum number of characters or list items allowed. Must be equal to or greaterthan zero. minLength Specifies the minimum number of characters or list items allowed. Must be equal to or greater than zero maxExclusive Specifies the upper bounds for numeric values (the value must be less than this value) maxInclusive Specifiestheupperboundsfornumericvalues(thevaluemustbelessthanorequaltothisvalue) minExclusive Specifies the lower bounds for numeric values (the value must be greater than this value) minInclusive Specifiesthelowerboundsfornumericvalues(thevaluemustbegreaterthanorequaltothisvalue) Pattern Defines the exact sequence of characters that are acceptable totalDigits Specifies the exact number of digits allowed. Must be greater than zero fractionDigits Specifiesthemaximumnumberofdecimalplacesallowed.Mustbeequaltoorgreaterthanzero <any> The <any> element enables us to extend the XML document with elements not specified by our schema. #family.xsd
  • 56. 51 | P a ge WebServices Nowwewanttoextendthe"person"elementwitha"children"element.Inthiscasewecandoso,evenifthe author of the schema above never declared any "children" element. #children.xsd The XML file below (called "Myfamily.xml"), uses components from two different schemas; "family.xsd" and "children.xsd". #Myfamily.xml So far in the XSD we have ignored namespaces as they will create confusion while writing and using basic XSDs. Just to make you feel comfortable with XSD i have ignored namespaces in XSD but we can't ignore namespaces completely. Namespaces plays vital role when we are working XSD andnamespaces are one ofthe reason to use XSD inplace of DTD. Nowlet’s seewhat is namespace and what is thepurpose of Namespace.
  • 57. 52 | P a ge WebServices XSD Namespaces When we are working on a project, several developers will create several classes and every developer will have a freedom to choose their interested name for a class. In this scenario is there any possibility that multiple developers will create classes using same name? – Yes, possibility isthere so it causes naming collision. Then howtheycandifferentiatethisclassbelongstowhichdeveloper?–That’swherejavaprovidedPackages concept. Packagesareusedtoresolvenaming collisionthatoccursacrossmultipleclasseswhich arecreatedbymultiple developers. To resolve the naming collision every developer will bind his/her class to a package like below With this SummaryReportDao.java class is binded to com.ibm.ctod.reports.dao package. So, wherever we want to use SummaryReportDao.java class we should fully qualified class name like below Note:Instead ofwritingcom.ibm.ctod.reports.daomultipletimesinclass,we canimportthispackageusing import statement. Like java, when multiple people are working on XSDs there is a possibility that they will use same names for elementsandComplexTypesthenitcausesnamingcollision.ToresolvethisnamingcollisionXSDprovided Namespaces. XSD Namespaces has two faces Declaring the namespace in the XSD document using Target namespace declaration Using the elements that are declared under a namespace in xml document.
  • 58. 53 | P a ge WebServices XSD Target Namespace Target namespace declaration is similar toa package declaration in java. You will bind your classes to a package so,thatwhileusingthemyouwillreferwithfully qualifiedname.Similarly,whenyoucreateaComplexTypeor an Elementyouwill bind them toa namespace, sothat while referring them you need to useqName. Inordertodeclareapackage,weusepackagekeywordfollowedbynameofthe package.Todeclarea namespace in XSD we need to use targetNamespace attribute at the Schema level followed by targetNamespacelabel as shown below. The PaytmType is by default is binded to the namespace “http://www.airtel.in/payments” So,whilecreatinganelement“paytm”oftypePaytmTypeweshouldusethe qNameofthePaytmTyperather simple name. (qName means namespace:element/type name). Butthenamespacelabelscouldbeanyofthecharactersinlength,soifweprefix theentirenamespacelabel toelement/typenamesitwouldbecometoughto read.So,to avoidthis problemXSDhasintroduceda conceptcalledshortname. Insteadofreferringtonamespacelabelsyoucandefineashort nameforthat namespacelabelusingxmlnsdeclarationatthe<schema>levelandyoucanuse theshortnameasprefix insteadofthecompletenamespacelabel. In above Paytm.xsd we have written “airtel” as alias name for targetNamespace like below xmlns:airtel="http://www.airtel.in/payments" targetNamespace="http://www.airtel.in/payments" Injavawecanhaveonlyonepackagedeclarationataclasslevel.Inthesame waywecanhaveonlyone targetNamespace declaration at an XSD document.
  • 59. 54 | P a ge WebServices Importance of xs:include and xs:import Till now we have assumed that we only have a single schema file containing all your element definitions, but the XSDstandardallowsyoutostructureyourXSDschemasbybreakingthemintomultiplefiles.Thesechild schemas can then be included into a parent schema. Breakingschemasintomultiplefilescanhaveseveraladvantages.Youcancreatere-usabledefinitionsthatcan beusedacrossseveralprojects.Theymakedefinitionseasiertoreadandversionastheybreakdownthe schema into smaller units that are simpler to manage. When schemas breaked into multiple files how one schema can refer element/complexType from another schema? – That’s where <xs:inclue /> and <xs:import /> comes into picture. <xs:include/>: IfyouwanttouseXML schema components(elements/ ComplexTypes) from other XML schemas with same targetNameSPaces, we should go for xs:include element Syntax: <xs:include schemaLocation=”SchamUri”/> Ex:<xs:includeschemaLocation=”Invoice.xsd”/> Let’s demonstrate this using below Example
  • 60. 55 | P a ge WebServices Inovice.xsd is included in Customer.xsd using <xs:include /> element We can write the XML for Customer.xsd like below <xs:import /> :- If we want to use XML schema components from other XML schamas with different targetNameSpaces, we should go for xs:import element. Syntax : <xs:import namespace=”targetnamespace” schemalocation=”xsd uri”/> Ex : <xs:import namespace=http://amazon.com/books/webservices schemaLocation=”amz.xsd”/>
  • 61. 56 | P a ge Web Services Let’s demonstrate <xs: import /> this with below example Author.xsd is imported into Book.xsd using <xs: import /> element Below is the xml that represents Book.xsd
  • 62. 57 | P a ge Web Services JAX-P
  • 63. 58 | P a ge Web Services Introduction JAX-PstandsforJavaAPIforXML Processing. Aswediscussedearlier,XMLisalso a document whichholdsdata in an XML format. Initially in Java there is no API that allows reading the contents of an XML document in an XMLformat.Java programmershastolivewithJavaIOprogrammingtoreadthem inatext nature orneedto build their own logic to read them in XML format. Bylooking at thislot ofJava software vendors inthemarket hasstarted building theirownlibraries/API’sthat allowsprocessinganXMLdocuments inXML nature. Fewofthem are DOM4J, JDOM. Aftermanysoftwarevendorsstarteddevelopingtheirownlibraries,sunhasfinally releasedJAX-PAPIwhich allows ustoworkwithXMLdocuments.Asindicated JAX-PisanAPIwhichmeansnotcompleteinnature,so weneed implementations of JAX-PAPIandtherearemanyimplementationsof JAX-PAPIavailable fore.g.. Crimson,Xerces2,Oracle V2 Parseretc. Xerces2 is thedefault parser that would be shippedas part of JDK1.5+. This indicates if you are working on JDK1.5+ youdon’t need any separate Jar’s to work with JAX-PAPI. XML Processing Methodologies JAXPprovideswrappersaroundtwodifferentmechanismsforprocessingXMLdata.ThefirstistheSimpleAPI forXMLorSAX,andiscoveredinthischapter.Thesecond,theDocumentObjectModel(DOM),iscoveredin the next. In the SAX model, XML documents are provided to the application as a series of events, with each eventrepresentingonetransitionintheXML document.Forexample,the beginningofanewelementcounts as an event, as does the appearance of text inside that element. A SAX parser reads through the XML document one time, reporting each event to the application exactly once in the order it appears in the document. Event-based parsing has strengths and weaknesses.Very large documents can be processed with events; there is no need to read the entire document into memory at once. However, working with sections of an XML document (a record made up of many elements, for example) can become complicated because the application developer has to track all the eventsfor a given section. SAX is a widely used standard, but is notcontrolledbyanyindustrygroup. Rather,itisadefactostandardthatwasoriginallydevelopedbyasingle developer (David Megginson) and by others in the XML community and is nowsupported by an open source project(http://www.saxproject.org).TheSAXwrapper provided byJAXPallows forpluggingindifferent SAX parsers without concern for the underlying implementation.This feature is somewhat moot because there aren’t that many SAX parsers in widespread use today. However, it does provide for safeguards against changes in future versions. SAX and DOM are the universal methodologies of processing (reading) XML documents irrespective of a particular technology. Few programming languages/API’s supports only SAX way of reading documents, few other supports only DOM and quite a few number support both the ways of reading. Simple API for XML (SAX) The Simple API for XML (SAX) is available with the JAXP; SAX is one of two common ways to write software that accesses XML data. SAX is an event-driven methodology for XML processing and consists of many callbacks. Using SAX with JAXP allows developers to traverse through XML data sequentially, one element at a time, using a delegation even model. Each time elements of the XML structure are encountered, an event is triggered. Developers write event handlers to define customer processing for events they deem important. Each elementisparseddowntoitsleafnodebeforemovingontothenextsiblingofthatelementintheXMLdocument, therefore at no point is there any clear relation of what level of the tree we are at.
  • 64. 59 | P a ge WebServices The SAX Event Model Most XML parsers fall into one of two main categories: tree-based or event based. Each kind of parser represents XMLinformationslightlydifferently.Atree-basedparserconvertsanXMLdocumentintoatreeofobjects(You will learn more about tree-based parsers in the next chapter). An event-based parser presents a document as a series of events, each representing a transition in the document. Taken together, these events provide your programwith acompletepictureofthedocument.Overviewof EventProcessing Imagineagainthatwe have printedoutanXMLdocument.Howwouldyoubegintoreadthedocument?Youwouldprobablybeginatthetop of thepageandcontinueline byline,lefttoright.Since youarefamiliar withXML, youknowthatthetags have specificmeanings.Youwouldlikelytakenoticeofwhereoneelementendsandanotherbegins;andwitheach newelementyouwould gain a betterunderstanding ofthecompletedocument. Event-basedparserswork in much the same way. An event-based parser scans through a document from top to bottom. As it scans, the parser takes notice of interesting points in the document. For example, it would notice where one element ends and another begins. The parser then alerts your program, givingittheopportunitytorespondtothetransition.Inparserterminology,thealertiscalledaneventandyour program’sresponseisacallback.Acompletedocumentparsemayconsistofhundredsoreventhousandsof events in series. Each event provides further information about the document. Handling hundreds or thousands ofeventssounds overwhelming, andthere’s no doubtthatitcanget complicated. Event-based parsing suits some situations better than others. The simpler the DTD associated with a document is, the easier it will be to use event- based processing. Oftentimes these documents contain repeating groups of elements, where each group is to be processedthesame way. Poor candidate documents are muchthe opposite.They are loosely-structured or contain deep and complex hierarchies. You may also want to avoid documents where elements are reused throughoutmultiplelevelsofahierarchy.Forthesetypesofdocuments,considerthetree-basedparsersdiscussed elsewhereinthisbook.Ifyouareinterestedinusinganevent-basedparser,thenyouwillneedtolearntheSAX API. Any event based processing model contains three actors as described below. Source:-istheoriginatorofevent,whocanraiseseveraltypesofevents. Eventscouldbeofmultipletypesif weconsiderAWT,wecanconsidersourceas abutton,whichiscapableofraisingseveraltypesofeventslike button click, mouse move, key pressed etc. Listener:-Listeneristhepersonwhowilllistensforaneventfromthesource. Listenerlistensforaspecific typeof eventfromthesourceandtriggers aneven handlingmethodontheEventhandlertoprocessit. EventHandler:-Oncealistenercapturesanevent,toprocessit,it callsamethodontheeventhandlerclass. As thereare different typesof events, tohandlethemtheeventhandlercontainsseveralmethodseach target to handle and process a specific type of event.
  • 65. 60 | P a ge Web Services Inaddition,SAXisasequentialprocessingmodel,whichprocessXMLelements sequentiallyfromtoptothe bottom.Whileprocessingthedocument,itplacesa pointertothedocumentandincrementssequentially fromthetop.Based onthe type of element it is pointing to, it raises a respective event, which will notifythe listener to handle and process it. SoheresourceistheXMLdocumentwhichcanraiseseveraltypesofevents basedonthetypeofelementitis pointingto(e.g...START_DOCUMENT, START_ELEMENTetc...). ListeneristheparserwhowillreadstheXML document andtriggersamethodcallontheHandler.Eventhandlercontainsseveral methodstohandle various types of events as shown below. SAXisveryfastinprocessingXMLdocumentswhencomparedwithDOMand consumeslessamountof memory,asatanygivenpointoftimeitloadsonly oneelementintothememoryandprocess.Hereonekey thingto note is using SAXwecanonlyreadtheXMLdocument,wecannotmodify/createadocument. Using JAX-P APIwecanprocess XMLdocuments inSAX model, here alsosource is theXML document, who is capableofraisingmultipletypesofeventslikes startDocument,startElement,endDocumentetc.Inorderto read the elements of XML and process them by raising events, we need a parser and here in SAX it is SAXParser. When to Use SAX You want to process the XML document in a sequential manner from top to bottom. SAXrequiresmuchlessmemorythanDOMbecauseSAXdoesnotcreateanin-memorytreeofthe XMLdata,asaDOMdoes.Soif youwantto processa verylargeXMLdocument whoseDOMtree would consume too much memory, you can shoose SAX over DOM. If the XML document is not deeply nested SAXisfastandefficientanditisusefulforstate-independentfiltering.SAXparsercallsamethod whenever an element tag is encountered and calls a different method when text or character is found. Note: The disadvantage of SAX is that it does not provide random access to an XML document.
  • 66. 61 | P a ge Web Services Let us see an example program using SAX parser in Java. This the xml file that we are going to read using SAX parser. The xml file contains a list of accounts
  • 67. 62 | P a ge Web Services Create a standalone project to read the above xml Thenextstepistocreateourownhandlerclassto parsetheXMLdocument.DefaultHandlerclassprovides default implementation ofContentHandler interface, so we can extend this class to create our own handler. --------------------------------AccountHandler.java------------------------------ package com.xml.apps; import org.xml.sax.Attributes; import org.xml.sax.SAXException; import org.xml.sax.helpers.DefaultHandler; public class AccountHandler extends DefaultHandler { boolean bank = false; boolean account = false; boolean id = false; boolean name = false; boolean amt = false; @Override public void startDocument() throws SAXException { System.out.println("Document started...."); } @Override public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { if (qName.equals("Bank")) { bank = true; } else if (qName.equals("Account")) { account = true; System.out.println("Account Type:" + attributes.getValue("type")); } else if (qName.equals("Id")) { id = true; } else if (qName.equals("Name")) { name = true; } else if (qName.equals("Amt")) { amt = true; } } @Override public void characters(char[] ch, int start, int end) throws SAXException { if (id) { System.out.println("Acct id: " + new String(ch, start, end)); id = false; } if (name) { System.out.println("Holder Name: " + new String(ch, start, end));
  • 68. 63 | P a ge Web Services name = false; } if (amt) { System.out.println("Amount: " + new String(ch, start, end)); amt = false; } } @Override public void endElement(String uri, String localName, String qName) throws SAXException { } @Override public void endDocument() throws SAXException { System.out.println("Document ended...."); } } -----------------------------------------0------------------------------------------------- Intheaboveclassweareoverridingfivemethodswhichwouldbetriggered basedonthetypeofelementsthe parser is pointing to on the source XML document.  startDocument – would be triggered at the start of the XML document  startElement – Whenever the parser encounters the starting element, it raises this method call by passing the entire element information to the method.  characters – This method would be invoked by the parser, whenever it encounters data portion betweentheXMLelements.Tothismethoditpasses theentireXMLascharacterarrayalongwithtwo other integers one indicating the position in the array from which the current data portion begins and thesecond integer representing thenumberofcharacters thedata span to.  endElement – would be triggered by the parser, when it encounters a closing element or ending element.  endDocument – would betriggered by the parser once it reaches end of the document. Below is the Java program that uses SAXParserHandler to parse the XML to list of Employee objects.
  • 69. 64 | P a ge Web Services Inthelastchapterwediscussedevent-basedparsing.Event-basedparsinghassomelimitations.Forinstance,one cannot manipulate entire sections of a document at once. Also, multiple passes over the document data calls for multiple runs through the parser.Often, it would be more efficient if an entiredocument could be read into the memoryandmanipulatedasanin-memoryrepresentation.ThiscanbeachievedusingtheDocumentObject Model(DOM),whichisbyfarthemostwidelyusedamongthevariousstandardsproposedforinmemory representation of XML documents. A standard specified by the World Wide Web Consortium (W3C), the DOM specifies an abstract mapping of XML elements into runtime objects. Binding this specification to various languages, including Java, has been implemented by a variety of vendors. In the DOM, every XML document is representedasahierarchyofobjects.ThishierarchyformsatreestructurethatmimicsthestructureoftheXML document.OnceyouarefamiliarwithXMLandDOM,translatingbetweenthetwobecomesasimplematter. OnethingthecurrentDOMspecificationomitsisanAPIfortheparsingofanXMLdocumentintoaDOM.Thisis left to the individual vendor when writing a DOM parser. The latest DOM specification (DOM 3) seeks to address this issuetoo,butuntilitgains in popularity,application developers havetotake into accounttheprospectsof modifying their code when moving to a different parser. JAXP solves this problem by presenting a standardized interface forparsing XML data; the result of this parsing is an object that conforms to the standard W3C DOM Document interface. This chapter presents a discussion on the reading, writing, and simple manipulations of a DOM representation. Morecomplexmanipulations,suchasthosepertainingtostylesheets,willbediscussedinthenextchapter.
  • 70. 65 | P a ge Web Services DOM parser DOM(DocumentObjectModel)definesastandardforaccessingandmanipulatingdocuments.DOMbuilds an in-memorytree representation of theXML document, where each node contains one of thecomponents from an XML structure. The two most common types of nodes in XML document are element nodes and text nodes.Java DOMparserAPI allows us to create nodes, remove nodes,change theircontents, and traverse the nodehierarchy. Points to note about DOM DOM was designed to be language-neutral.  DOM does not take advantage of Java’s object-oriented features. DOMprovides a lotof flexibility for handling fully-fledged documents and complex applications. If your programs handle simple data structures, then you can use JDOM or dom4j. SinceDOMcreatesin-memorytree,forprocessingverylargeXMLdocuments,youshouldchoose SAX or StAX beacuse DOM would consume too much memory. DOM Parser API The javax.xml.parsers.DocumentBuilder class defines API to obtain DOM Document instances from an XML document. Using this class, an application program can obtain a Document from XML. AninstanceofthisclasscanbeobtainedfromtheDocumentBuilderFactory.newDocumentBuilder()method. Oncean instance of thisclass is obtained,XML canbe parsedfrom a varietyofinput sources.These input sources are InputStreams, Files, URLs, and SAX InputSources. Below is the architecture of a typical DOM parser application.
  • 71. 66 | P a ge Web Services Parse XML document using DOM parser in Java
  • 72. 67 | P a ge Web Services -----------------------------------------ParsingAccountsDataUsingDOM.java---------------------------------------------- public class ParseAccountsDataUsingDOM { public static void main(String[] args) throws ParserConfigurationException, SAXException, IOException { // Get Document Builder DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); // Build Document Document document = builder.parse(new File("Account.xml")); // Normalize the XML Structure; It's just too important !! document.getDocumentElement().normalize(); // Here comes the root node Element root = document.getDocumentElement(); System.out.println(root.getNodeName()); // Get all employees NodeList nList = document.getElementsByTagName("Account"); System.out.println("============================"); visitChildNodes(nList); } // This method is called recursively private static void visitChildNodes(NodeList nList) { for (int temp = 0; temp < nList.getLength(); temp++) { Node node = nList.item(temp); if (node.getNodeType() == Node.ELEMENT_NODE) { System.out.println("Node Name = " + node.getNodeName() + "; Value = " + node.getTextContent()); // Check all attributes if (node.hasAttributes()) { // get attributes names and values NamedNodeMap nodeMap = node.getAttributes();
  • 73. 68 | P a ge Web Services for (int i = 0; i < nodeMap.getLength(); i++) { Node tempNode = nodeMap.item(i); System.out.println("Attr name:"+ tempNode.getNodeName() + "; Value = " + tempNode.getNodeValue()); } if (node.hasChildNodes()) { // We got more childs; Let's visit them as well visitChildNodes(node.getChildNodes()); } } } } } } --------------------------------------------.---------------------------------------------------- Create XML document using DOM parser in Java Here is the input xml file we will be creating using DOM parser. =========================DomparserCreateXml.java============================ import java.io.File; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import org.w3c.dom.Attr; import org.w3c.dom.Comment; import org.w3c.dom.Document; import org.w3c.dom.Element; public class DomParserCreateXml { public static void main(String[] args) { try { DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); Document doc = dBuilder.newDocument(); // root element Element rootElement = doc.createElement("Employees"); doc.appendChild(rootElement); // Employee element Element employee = doc.createElement("Employee"); rootElement.appendChild(employee); // setting attribute to element Attr attr = doc.createAttribute("id"); attr.setValue("1"); employee.setAttributeNode(attr);
  • 74. 69 | P a ge WebServices // age element Element age = doc.createElement("age"); age.appendChild(doc.createTextNode("28")); employee.appendChild(age); // firstname element Element firstname = doc.createElement("firstname"); firstname.appendChild(doc.createTextNode("Ashok")); employee.appendChild(firstname); // lastname element Element lastname = doc.createElement("lastname"); lastname.appendChild(doc.createTextNode("Kumar")); employee.appendChild(lastname); // role element Element role = doc.createElement("role"); role.appendChild(doc.createTextNode("Developer")); employee.appendChild(role); Comment comment = doc.createComment("This is a comment"); rootElement.appendChild(comment); form of a // write the content into xml file TransformerFactory transformerFactory = TransformerFactory.newInstance(); Transformer transformer = transformerFactory.newTransformer(); /* DOMSource acts as a holder for a transformation Source tree in the * Document Object Model (DOM) tree. */ DOMSource source = new DOMSource(doc); StreamResult result = new StreamResult(new File("D:employee.xml")); transformer.transform(source, result); // Output to console for testing purpose StreamResult consoleResult = new StreamResult(System.out); transformer.transform(source, consoleResult); } catch (Exception e) { e.printStackTrace(); } } } --------------------------------------.------------------------------------------ StAX parser StaX (Streaming API for XML) is a JAVA based API to parse XML documents similar to a SAX parser. There are two main differences between SAX and StaX parsers. They are SAXisapushAPI:-ItmeansthattheSAXparserwillsend(push)notificationstotheclientprogram whenever it has processed an element, attribute or character. OntheotherhandStAXisapullAPI:- ItmeanstheclientapplicationneedtoaskStAXparsertoget information from XML whenever it needs. StAX is an API for reading and writing XML Documents. SAX can be used only for reading XML. Note that similar to SAX,StAX canonly process the XML document in a linear fashionfrom topto bottom and you cannot have random access to an XML document.
  • 75. 70 | P a ge WebServices StAX API StaX contains two distinct APIs to work with XML documents. They are  Cursor API  Event Iterator API Applications can use any of these two API for parsing XML documents. Cursor API Asthenamesuggests,theStAXcursorAPIrepresentsacursorwithwhichyoucanparseanXMLdocument from beginning to end. This cursor can point to one thing at a time, and always moves forward, never backward, usually one info set element at a time. The two main cursor interfaces are  XMLStreamReader  XMLStreamWriter The XMLStreamReader interface has methods to read an XML document TheXMLStreamWriterinterfaceprovidesmethodsforcreatinganXMLdocument. TheXMLStreamReader interface has thefollowing important methods • int next() – used to retrieve next parsing event. • booleanhasNext()–Returnstrueiftherearemoreparsingeventsandfalseiftherearenomoreevents. • String getText() – used to get text current value of an element • String getLocalName() – used to get (local)name of an element The XMLStreamWriter interface has the following important methods. • writeStartElement (String localName) – Add start element of given name. • writeEndElement (String localName) – Add an end element of given name. • writeAttribute (String localName, String value) – Writes an attribute to the output stream without a prefix. • writeCharacters (String text) – Write text to the output. Read XML using XMLStreamReader ------------------------StaxParserExample.java----------------------------- import java.io.FileInputStream; import java.io.FileNotFoundException; import javax.xml.stream.XMLInputFactory; import javax.xml.stream.XMLStreamConstants; import javax.xml.stream.XMLStreamException; import javax.xml.stream.XMLStreamReader; public class StAXParserExample { public static void main(String[] args) { boolean bFirstName = false; boolean bLastName = false; boolean bRole = false; boolean bAge = false; try {
  • 76. 71 | P a ge WebServices XMLInputFactory factory = XMLInputFactory.newInstance(); XMLStreamReader streamReader = factory.createXMLStreamReader(new FileInputStream( "C:/Users/Ashok/Desktop/employees.xml")); while (streamReader.hasNext()) { int eventType = streamReader.next(); switch (eventType) { case XMLStreamConstants.START_ELEMENT: String qName = streamReader.getLocalName(); if (qName.equalsIgnoreCase("Employee")) { System.out.println("Start Element : " + qName); String id = streamReader.getAttributeValue(0); System.out.println("Id : " + id); } else if (qName.equalsIgnoreCase("age")) { bAge = true; } else if (qName.equalsIgnoreCase("firstname")) { bFirstName = true; } else if (qName.equalsIgnoreCase("lastname")) { bLastName = true; } else if (qName.equalsIgnoreCase("role")) { bRole = true; } break; case XMLStreamConstants.CHARACTERS: String characters = streamReader.getText(); if (bAge) { System.out.println("Age: " + characters); bAge = false; } if (bFirstName) { System.out.println("First Name: " + characters); bFirstName = false; } if (bLastName) { System.out.println("Last Name: " + characters); bLastName = false; } if (bRole) { System.out.println("Role: " + characters); bRole = false; } break; case XMLStreamConstants.END_ELEMENT: String endName = streamReader.getName().getLocalPart(); if (endName.equalsIgnoreCase("Employee")) { System.out.println("End Element :" + endName); System.out.println(); } break; } } } catch (FileNotFoundException | XMLStreamException e) { e.printStackTrace(); } } -----------------------------.-------------------------------------
  • 77. 72 | P a ge WebServices Validating XML against XSD An XML document is considered ‘well-formed’ if it follows the normal rules of XML. i.e. all tags are closed properly etc.Ontheother hand, anXML is consideredvalid if itfollows the rules specified in the DTDorXSD. Below is the Account.xsd which represents Structure of the XML Below is the Account.xml which holds the data as per Account.xsd .
  • 78. 73 | P a ge Web Services Manually wecan validate XML againstXSD using Altova XML Spytoolbutcanwevalidate XMLagainst XSD programmatically?–Yes,wecanvalidateXMLagainstXSDprogrammatically usingSchemaandValidatorlike below Validating XML against XSD using DOM Parser
  • 79. 74 | P a ge Web Services JAX-B
  • 80. 75 | P a ge Web Services Introduction Javaoffersseveraloptionsforhandling XMLstructuresandfiles.OneofthemostcommonandusedonesisJAXB. ItoffersthepossibilitytoconvertJavaobjectsintoXMLstructuresandtheotherwayaround.JAXBcomeswith the JRE standard bundle since the first versions of the JRE 1.6. The first specification of JAXB was done in March 2003 and the work process is tracked in the Java Specification Request 31: https://jcp.org/en/jsr/detail?id=31. In this specification request you can find a lot of information regarding the long life of JAXB and all the improvements that have been made. As already mentioned, JAXB is included in the JRE bundle since the update 1.6. Before that it was necessary to include their libraries in the specific Java project in order to be able to use it. Before JAXB was available (long time ago), the way Java had to handle XML documents was the DOM: http://www.w3.org/-DOM/.Thiswasnotaverygoodapproachbecausetherewasalmostnotabstractionfrom XMLnodesintoJavaobjectsandallvaluetypeswereinferredasStrings.JAXBprovidesseveralbenefitslikeObject oriented approachrelatedtoXML nodes and attributes, typed values, annotations and mayothers. JAXB stands for Java architecture for XML binding. It is used to convert XML to java object and java object to XML.JAXBdefinesanAPIforreadingandwriting Javaobjectstoandfrom XMLdocuments. Unlike SAXand DOM, we don't need to be aware of XML parsing techniques. Basically, XML Binding API’s are categorized into two types of tools. Design Time tools –In these type of tools, there will be a Binding compiler which willtake a Schema or DTD as input and generated supported classes for converting the XML to Object andObject to XML. Runtime tools – These willnot generate any classes rather on fly will take the XML as an input and based the elementsnames,matchesthemwithcorrespondingattributenamesoftheclassandwillconvertXMLinto Object of theclass. WhenitcomestoJAX-BAPIitisadesigntimetool,whereitwillcomeupwithitsowncompilertogenerated classestosupportthebindingprocess.BeforeproceedingfurtheronJAX-Bletusfirsttrytounderstandits architecture and itsofferings. Architecture If a Java Object is following the structure of a Java class then that Object is called Instance of that class. If XML documentisfollowingthestructureofanXSDdocumentcanIcalltheXMLasanInstanceofthatXSDornot? Certainly, the answer for this would be yes. InJava, Object structure would be defined by aclass. In XML, structure of an XML is defined by an XSD document as shownbelow.
  • 81. 76 | P a ge Web Services If wetrytoderive a conclusionfromtheabove, wecanunderstandthat ClassesandXSDdocumentsbothtry to represent the structure, so we can create set of Java classes which represents the structure of an XSD document,thenthe XMLdocument(holdsdata)representingthestructureofthatXSDcanbe convertedinto its associatedJava classObjects. Eventhewise versa wouldalso be possible. Let us try to deep down into the above point. How to create user defined data type in Java? Using class declaration.Howtocreateuserdefineddatatypein XSD?ByusingComplexTypedeclaration.Whichmeansa ComplexTypeinXSDis equaltoa Java classin Java. As XSD document means itcontains elements and multiple Complex Type’s so, to represent the structure of an XSD document in Java, it is nothing butcomposition of variousJavaclasses(oneJavaclassto oneXSD ComplexType)representingitsstructure. Mapping or Binding Java objects canbe bondedto XML structures by usingcertain annotations and following specific rules. This is whatwecallasmappingorBinding. Toperformthisbinding,weneedtogenerateBindingclasseswhich represents structures of the XML.
  • 82. 77 | P a ge Web Services Let us take the example of PurchaseOrder XSD to understand better. In the above XSD we have one element and four ComplexType declarations, as we discussed earlier ComplexType declarations inXSD are equal toa Java class in Java. So from the above wecanderive four Java classes as shown below. class ShippingAddressType { StringaddressLine1; StringaddressLine2; Stringcity; Stringstate; int zip; Stringcountry; } class ItemType { StringitemCode; int quantity; } class OrderItemsType { List<ItemType>item; } class PurchaseOrderType { OrderItemsType orderItems; ShippingAddressType shippingAddress; } FromtheabovewecancreatethePurchaseOrderTypeobjectrepresentingtheroot elementofXSD,canIhold thePurchaseOrderXMLdocumentdataintothis instanceornot?Absolutelytheanswerwouldbeyes,because PurchaseOrderType isrepresentingthestructureoftheXSDdocument,soitsinstancecanholditsXML data. WiththisweunderstoodthatwecancreatedtheJavaclassesrepresentingthe structureofanXSDdocument, hencethoseclassesarecalledasBindingClassesas thosearebondedtotheXSDdocumentstructureandthe objects out of those classes arecalledbinding objects.
  • 83. 78 | P a ge Web Services NowweknowthatwecanconverttheXMLdocument dataintoa BindingClass Object,sotheprocessof convertinganXMLtoaBindingclassObjectiscalledUn-Marshalling.AndtheprocessofconvertingaBinding ObjectbackintoXML representationiscalledMarshallingandboththetypesofoperationsaresupported by any of the XML Binding API’s including JAX-B. So, JAX-B supports two types of operations 1) One-Time operations 2) Runtime operations. Let us discuss them in detail below. One-Time Operation One-Time operations are the operations which would be done only once within the lifetime of an XSD or Binding class. Let’s say I want to convert the Purchase Order XML document to Object, this is Un-Marshalling. To perform Un- Marshalling do we need Binding classes representing the structure of the Purchase Order XSD or not? So the programmer has to read the contents of the XSD and based on the number of complex types he needs to create equivalent Java classes representing their structure. As our purchase order XSD document contains only four complextypesitwouldbeeasyforthedevelopertodeterminetherelationsbetweentheclassesandcan create.Let’ssayIhaveanXSDdocumentinwhich100ComplexTypedeclarationsarethere,isiteasyfora developertodevelop100 Java classesrepresentingthestructureof100ComplexTypes.Eventhoughitseemsto be feasible, but it is a time taking task. So,insteadofwritingtheBindingclassesmanually,JAX-Bhasprovidedatooltogenerated Bindingclasses from XSDcalledXJC.AndtogenerateXSDfromaBindingclassthereisanothertoolcalledSchemagen. IfIhaveanXSDdocument,howmanytimesdoIneedtogenerateJavaclassestoholdthedataofitsXML?It wouldbeonlyonce,becauseclasseswillnotholddatatheyjustrepresentsstructure,soinstancesofthose classesholdsdataofanXML. Eventhereversewouldalsobesame.AsweneedtogeneratetheBindingclasses
  • 84. 79 | P a ge Web Services or XSD only once this process is called one-time operations. And there are two types of one-time operations. a) XJC – XSD to Java compiler – Generates Binding classes from XSD document b) Schemagen – Schemagenerator – GeneratedXSDdocumentfrom an Binding class How to use XJC or Schemagen? Implementing all binding classes for an existing XML interface can be a time consuming and tedious task. But the good news is, you do not need to do it. If you have a XSD schema description, you can use the xjc binding compiler tocreatetherequiredclasses.Andevenbetter,xjcispartoftheJDK.Sothereisnoneedforexternaltoolsand you should always have it at hand if required. Open Command Prompt and type xjc -help command  It gives all xjc options like below
  • 85. 80 | P a ge WebServices  -d to definewhere the generated classes shall be stored in the file system,  -p to define the package to be used and of course  -help if you need anything else. Generating Binding Classes for XSD using XJC What does XJC generates? WhenwerunXJC.batbygivingXSDasaninputalong withgeneratingbinding classesitgeneratesfewother things as explained below. All the binding classes would be generated into the given package com.amazon.types 1. Package-info.java–XJCaftermappingthenamespacetoapackagename,it wouldstorethismapping information into a class called package-info.java. This is also generated under the above mapped package only. 2. ObjectFactory.java – These Class Actsasfactoryclass, whichknows howto createobjects ofall the Bindingclassesgenerated. Itcontainsmethods like createXXX, uponcallingthesemethods itwould return respective binding classobjects. 3. SetofBindingclasses–WiththeaboveitgeneratesBindingclasses representingthestructureofeach ComplexTypeinXSD.Canwecallanyjava classasBindingclass?No,thebindingclassesaretheclasses whichare bondedtoXSDcomplexTypedeclarationsandtodenotethisrelationship, thosearemarked withJAX-B annotations as described below.
  • 86. 81 | P a ge Web Services So,bytheaboveweunderstoodthatnoteveryJavaclassiscalledasBinding class,onlytheclasseswhichare annotated with JAX-Bannotations are called bingingclasses. So, from the above binding classes we can even generated XSD document by running the Schemagen tool. Withthiswe understoodhowtoperformone-timeoperations.Nowwecan proceedonruntimeoperations. Runtime Operations Tillnowwediscussedabouthowtoperformone-timeoperations.Letustryto understandRuntimeoperations. JAX-Bsupportsthreeruntimeoperations. 1) Un-Marshalling – The process ofconverting XML to JavaObject 2) Marshalling – The process of converting JavaObject with data to its XML equivalent 3) In-MemoryValidation – Beforeconverting anXML documentto JavaObject first we need to validate whether theXML conforms to XSD or not would be doneusingIn-MemoryValidation. If we want to perform runtime operations, first you need to do one-time operation. Unless you have binding classes orXSDequivalent foranyexisting bindingclass,youcan’twork onruntimeoperations. ByfollowingthethingsdescribedinearliersectionweassumeyoualreadycompletedtheOne-Timeoperations andyouhavebindingclasseswithyou.Letus trytounderstandhowtoworkoneachoftheRuntimeoperations in the following section. Un-Marshalling: Asdescribedearlier,theprocessofconvertinganXMLdocumentintoJava ObjectiscalledUn-Marshalling.In order to perform Un-Marshalling, you need to have Binding Classes with you. You can generate these by running XJC compiler. If you run XJC compiler on the Purchase-Order.xsd which was described earlier, the following bindingclasseswill be generatedshown below. i. @XMLType–Tothetopofthebindingclassitwouldbemarkedwith @XMLType annotationindicatedthisclassisrepresentinganXML Complex Type ii. @XMLAccessorType(AccessType.FIELD)–Inconjunctionwith @XMLType,onemoreannotation @XMLAccessorType(AccessType.FIELD)alsowouldbegenerated.It denotes how to map XML elements to Bindingclassattributes.Withthe AccessType.FIELDwearesayingtheelementsnamesmustbematched with binding class attributes names to port the data. iii. @XMLElement – This annotation is marked at the attributes of the Binding classes to indicates these attributes arerepresenting elements ofXML.
  • 87. 82 | P a ge Web Services
  • 88. 83 | P a ge Web Services HavingthebindingclasseswillnotautomaticallyconvertstheXMLdocument intoObjectoftheseclasses, rather we needa mediator who would be able to read the contents of the XML,and identifytherespective bindingclassforthat andcreatesobjectstopopulatedata.Thiswillbedonebyaclasscalled “Unmarshaller”. AsJAX-BisanAPI,soUnmarshallerisaninterfacedefinedby JAX-BAPIanditsJAX-BAPIimplementations (JAX-BRI or JaxMe) contains the implementationclassforthisinterface. TheobjectofUnmarshallerhasamethodunmarshal(),thismethodtakesthe inputasXMLdocumentand firstcheckforWell-formness.Oncethedocumentis well-formed,itsreadstheelementsoftheXMLandtries to identify the binding classes for those respective elements based on @XMLType and @XMLElement annotationsandconverts them into theObjects. We have two problems here 1) Howto create Un-marshaller as we don’t knowimplementation class 2) Wheredoesun-marshallershouldsearchforidentifyingabindingclass(isit inentireJVMmemoryor classpath?) As we don’t know how to identify the implementation of Unmarshaller interface, we have a factory class calledJAXBContextwhowillfindstheimplementation classforUnmarshallerinterfaceandwouldinstantiate. Ithasamethod createUnmarshaller()whichreturnstheobjectofunmarshaller.Thisaddressed theconcern #1 While creating the JAXBContext, we need to supply any of the three inputs statedbelow. 1) Packagenamecontainingthe binding classes 2) ObjectFactory.classreferenceasitknowsthebindingclasses. 3) IndividualBinding classesas inputs to theJAXBContext. JAXBContextjaxbContext=JAXBContext.newInstance(“packagename”or “ObjectFactory.class” or “BC1, BC2, BC3…”);
  • 89. 84 | P a ge Web Services Withtheabove statement, theJAXBContext wouldbe createdandloads the classes thatarespecifiedin the package or referred by ObjectFactory or the individual binding classes specified and creates an in-memory context holding these. NowwhenwecalltheUnmarshaller.unmarshal()method,theUnmarshallerwill searcheswiththeclasses loadedintheJAXBContextandtriestoidentifythe classesforanXMLelementbasedontheirannotations. The code for UnMarshallinghasshownbelow. Marshalling: MarshallingistheprocessofconvertingtheObjectdatatoXML.Forperforming Marshallingalsoweneedto createtheBindingclasses first.Oncewehave theBindingclasses,weneedtocreatetheObjectofthese classes and should populate data inthem. TheseobjectscanbemarshaledtoXMLusingtheMarshaller.Again,Marshalleris aninterface,toinstantiate itweneedJAXBContext.Thenweneedtocalla methodmarshalbygivinginputasXMLandOutputstream where we want to generate the output to.The belowprogram depicts the same.
  • 90. 85 | P a ge WebServices In-Memory Validation While performing the Unmarshalling or Marshalling, we need to first of all validate whether the XML is valid againsttheXSDdocumentornot,andwewill validateusingtheIn-Memoryvalidation.AnXMLcanbevalidated againstanXSDdocument,soweneedtoreadtheXSD documentandshouldrepresentitinaJavaObjectcalled Schema. ButSchemaisaninterfaceandtocreatetheObjectofinterface,we needfactory calledSchema Factory.But schema factory can created various types of XSD documents, so we need to provide the grammar of XSD document which you want to load or created and would be done as show below. Withtheabove we created aSchemaFactorywhich iscapableof creatingorloadingW3CXMLSchematype documents. Now we need to load the XSD document into the Schema class object as shown below. Once the schema object is created holding the structure of XSD, we need to give it to Unmarshaller before calling the unmarshal(). So, that Unmarshaller will validate the input XML with this supplied Schema Object and then performs Unmarshalling. Otherwise Unmarshaller will throw exception, indicating the type of validation failure. The below programs shows how to perform in-memory validation. SchemaFactorysFactory= SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_URI); SchemapoSchema = sFactory.newSchema(new File(“Purchase-Order.xsd”));
  • 91. 86 | P a ge WebServices Getting Started withWebservices Before discussing Web Service development, first we need to understand certain aspects related to Web Services.ThepointswearediscussingbelowarecommonforbothJAX-RPCandJAX-WSaswell. Types of Web Services Asdiscussedearlier,wehavetwotypesofWebServicesJAX-RPCAPIadheringtheBP1.0,andJAX-WSAPI adhering to BP 1.1. Now while developing a Web service, first of we need to choose a type. After choosing the type,weneedtoselectanappropriateimplementationandvariousotheraspectsdescribedinfollowing sections. Web Service Development parts Always a Web Service development involves two parts. Provider and Consumer. Provider is the actual Web service, who will handle the incoming requests from the consumer. The Consumer is the Client Program which wedeveloptoaccesstheProvider.NowbothJAX-RPCandJAX-WSAPI’shasprovidedclassesandinterfacesto develop Consumer as well as Provider programs. Ways of developing a Web Service There are two ways of developing a Web service Contract First approach: In Web Services, WSDL acts as a contract between Consumer and Provider. If consumer wantstoknowtheinformationabouttheprovider,heneedstoseetheWSDLdocument.InaContractFirst approach,thedevelopmentoftheproviderwillstartswithWSDL,fromwhichthenecessaryJavaclasses requiredtobuildtheservicewouldbegenerated.AsthedevelopmentstartsfromWSDL,henceitiscalled Contract First approach. Contract Lastapproach: Here the developerfirst starts developing theservice bywriting theJava code,once done then he will generate the WSDL contract to expose it as a Web Service. As the contract is being generated at the end after the development is done, this is called Contract Last approach. Choosing an Endpoint InWebservicestheproviderisoftenreferredasEndpoint,asheistheultimatepointfromwhomwerequest data or information. NowinatypicalWebServicecommunication,theconsumerwillsendtheinitialrequestwithsomedatatothe Provider.TheconsumercannotsendObjectdataoverthenetwork;ratherheneedstoconvertitintoXMLand needstoplacetheXML into SOAP XML.ThentheSOAP XMLisbeingtransported over theHTTP protocol.This means the consumer will send a HTTP request, to receive the HTTP request being sent by the consumer, at the ProviderendweneedtohaveaHTTPListener.Thelistenerwilllistenfortheincomingrequestandforwardsit forfurtherprocessingasshownbelowSoweunderstoodweneedalistenerattheprovidersidetohandlethe incomingrequest.DowehaveanyexistingAPI’sinJavawhicharecapableofhandlingincomingHTTPRequests? Those are nothing but Servlet or EJB.
  • 92. 87 | P a ge WebServices There are two types of Endpoints, where a developer can choose while developing a Provider. Servlet Endpoint: Here at the provider end, the servlet acts as a listener in listening for the incoming request from the client and would process. EJBEndpoint:InplaceofServletevenwecansubstituteitwithEJB,andwecanmakeEJB’stohandleevenHTTP Request as well. Most of the people prefer to use Servlet endpoint rather than EJB endpoint as EJB seems to be heavy and costly component,andforthesakeofdevelopingWebservices,theapplicationneedstobehostedonanEJB container. Message Exchange Patterns Message exchange format talks about how a consumer does exchanges information withthe provider. This could happen in three ways as described below. Synchronous request/reply: In this pattern, the consumer sends the request with some data and will waits till the provider finishes processing request and returns the response to the consumer. Class A is calling a method execute () on B, until the method execute () finishes execution and returns value, the do()methodwillbeblockedontheexecute()methodcall,asitisblockedonmethodcall,itiscalledblocking request/reply or synchronous request reply. In this case also the Consumer program would be blocked on the Providersmethodcall(request)andwillnotproceedsexecutionuntiltheProviderreturnsresponse.Which meanstheConsumeropenedHTTPConnectionwouldbe opentilltheProvider returnsresponse. Asynchronousrequest/replyorDelayedResponse:Inthispattern,theConsumerwillnotbeblockedonthe Providers method call/request, rather after Consumer sendingtherequest;he disconnects/closes the HTTP Connection.Theprovideruponreceivingtherequestwillholditandprocessitaftercertainamountoftime. Once the response is ready willopensa new connection backtothe Consumer anddispatches theresponse. Fore.g.letusconsideranexamplelikeyouaresendingalettertoyourfriend,whenyouposttheletteritwould becarriedbythepostmastertoyourfriend.Oncetheletterhasbeenreceived,yourfriendmaynotimmediately readtheletter,ratherwhenhefindsleisurehewillread.Tillyourfriendreadstheletterandgivethereplythe postmastercan’twaitatyourfriend’sdoorratherhemoveson.Nowwhenyourfriendreadsyourletter,thenhe will reply to your letter by identifying the from address on the letter and post back’s you thereply. Asthe responsehereisnotimmediateandisbeingsentaftersometime,thisisalsocalledasDelayedresponse pattern. One way Invoke or Fire and forget: In this case, the consumer will send the request with some data, but never expects a response from the provider. As the communication happens in only one direction it is called One-Way invoke as well.
  • 93. 88 | P a ge Web Services Message Exchange formats This describes about how the consumer will prepares/formats the xml message that should be exchanged with the provider. Fore.g.alecturerisdictatingthenotes,everystudenthastheirownwayofwritingthenotes.Someonemay right the notes from bottom to top, others might right from top to bottom. In the same way, to send information, the consumer has to prepare his data in XML format. How does consumer represents the data in the XML document is called Message Exchange format? The message exchange format would be derived by two parts 1) Style and other is 2) Use. a) Style – The possible values the Style part can carry is rpc and document b) Use – This could be encoded and literal Withtheaboveitresultsinfourcombinationsasrpc-encoded,rpc-literal,document-literalanddocument- encoded. Out of which document-encoded is not supported by any web service specification. We will discuss the remaining three in later sections.
  • 94. 89 | P a ge Web Services JAX-WS
  • 95. 90 | P a ge Web Services Introduction Java APIforXMLWebServices(JAX-WS),isastandardized APIforcreating webservices inXMLformat(SOAP). JAX-WSprovides support for SOAP (Simple Object Access protocol) basedweb services. Webservices have been arounda while now.Firstthere wasSOAP.But SOAPonlydescribed whatthe messages looked like. Then there was WSDL. But WSDL didn't tell you how to write web services in Java. Then along came JAX-RPC 1.0. After a few months of use, the Java Community Process (JCP) folks who wrote that specification realizedthatitneededafewtweaks,soreleasedJAX-RPC1.1.Afterayearorsoofusingthatspecification,the JCPfolkswantedtobuildabetterversion:JAX-RPC2.0.Aprimarygoalwastoalignwithindustrydirection,but the industry was not merely doing RPC web services, they were also doing message-oriented web services. So "RPC" was removed from the name and replaced with "WS" (which stands for web Services). Thus the successor to JAX-RPC 1.1 is JAX-WS 2.0 - the Java API for XML-based web services. What remains the same in JAX-RPC and JAX-WS? BeforewetalkthedifferencesbetweenJAX-RPC1.1andJAX-WS2.0,weshouldfirstdiscusssimilaritiesbetween JAX-RPC andJAX-WS JAX-WSstillsupportsSOAP1.1overHTTP1.1,sointeroperabilitywillnotbeaffected.Thesamemessages can still flow across the wire. JAX-WSstillsupportsWSDL1.1,sowhatyou'velearnedaboutthatspecificationisstilluseful.AWSDL2.0 specification is nearing completion, but it was still in the works at the time that JAX-WS 2.0 was finalized. What is different between JAX-RPC and JAX-WS? SOAP 1.2: JAX-RPC and JAX-WS support SOAP 1.1. JAX-WS also supports SOAP 1.2. XML/HTTP: The WSDL 1.1 specification defined an HTTP binding, which is a means by which you can send XML messages over HTTP without SOAP. JAX-RPC ignored the HTTP binding. JAX-WS adds support for it. WS-I's Basic Profiles: JAX-RPC supports WS-I's Basic Profile (BP) version 1.0. JAX-WS supports BP 1.1. (WS-I is the web services interoperability organization.) New Java features: JAX-RPC maps to Java 1.4. JAX-WS maps to Java 5.0. JAX-WS relies on many of the features new in Java5.0. JavaEE5,thesuccessortoJ2EE1.4,addssupportforJAX-WS,butitalsoretainssupportforJAX-RPC,whichcould be confusing to today's web services novices. The data mapping model: JAX-RPChasitsowndata mappingmodel,which coversabout90percentofallschematypes.Thosethat it does not cover are mapped to javax.xml. soap.SOAPElement. JAX-WS's datamapping model is JAXB. JAXBpromises mappingsfor allXML schemas.
  • 96. 91 | P a ge WebServices The interface mapping model: JAX-WS'sbasicinterfacemappingmodelis not extensivelydifferent fromJAX-RPC's; however: JAX-WS's model makes use of new Java 5.0 features. JAX-WS's model introduces asynchronous functionality. The dynamic programming model: JAX-WS's dynamic client model is quite different from JAX-RPC's. Many of the changes acknowledge industry needs: It introduces message-orientedfunctionality. It introduces dynamic asynchronous functionality. JAX-WS also adds a dynamic server model, which JAX-RPC does not have. MTOM (Message Transmission Optimization Mechanism) JAX-WS, via JAXB, adds support for MTOM, the new attachment specification. Microsoft never bought into the SOAP with Attachments specification; but it appears that everyone supports MTOM, so attachment interoperability should become a reality. The handler model: The handler model has changed quite a bit from JAX-RPC to JAX-WS. JAX-RPChandlersrelyonSAAJ1.2.JAX-WShandlers relyonthenewSAAJ1.3specification. SOAP 1.2 There is really not a lot of difference, from a programming model point of view, between SOAP 1.1 And SOAP 1.2. As a Java programmer, the only place you will encounter these differences is When using the handlers. XML/HTTP LikethechangesforSOAP1.2,thereisreallynotalotofdifference,fromaprogrammingmodelPointofview, between SOAP/HTTP and XML/HTTP messages. As a Java programmer, the only Place you will encounter these differences is when using the handlers. The HTTP binding has its own handler chain and its own set of message context Properties. WS-I's basic profiles JAX-RPC1.1supportsWS-I'sBasicProfile(BP)1.0.Sincethattime,theWS-IfolkshaveDevelopedBP1.1(andthe associated AP 1.0 and SSBP 1.0). These new profiles clarify some Minor points, and more clearly define attachments. JAX-WS 2.0 supports these newer profiles. For the most part, the differences between them do not affecttheJavaprogrammingmodel.TheExceptionisattachments.WS-Inotonlyclearedupsomequestionsabout attachments, but they Also defined their own XML attachment type: wsi:swaRef. Many people are confused by all these profiles. You will need a little history to clear up the confusion. WS-I'sfirstbasicprofile(BP1.0)didagoodjobofclarifyingthevariousspecs.Butitwasn'tperfect.Andsupport for SOAP with Attachments (Sw/A) in particular was still rather fuzzy. In their second iteration, the WS-I folks pulled attachments out of the basic profile - BP 1.1 - and fixed some of the things they missed the first time around. Atthat pointtheyalso addedtwo mutually exclusive supplements to thebasic profile:AP1.0 andSSBP1.0.AP 1.0 is the Attachment Profile which describes how to use Sw/A. SSBP 1.0 is the Simple SOAP Binding Profile, which
  • 97. 92 | P a ge Web Services describes a web services engine that does not support Sw/A (such as Microsoft's .NET). The remaining profiles that WS-I has and is working on build on top of those basic profiles. Summary JAX-WS 2.0 is the successor to JAX-RPC 1.1. There are some things that haven't changed, but most of the programmingmodelisdifferenttoagreaterorlesserdegree.Thetopicsintroducedinthistipwillbeexpanded upon ina seriesoftipswhich we willpublish overthecomingmonthsthat willcompare,in detail,JAX-WSand JAX-RPC.Atahighlevelthough,hereareafewreasonswhyyouwouldorwouldnotwanttomovetoJAX-WS from JAX-RPC. Reasons to stay with JAX-RPC 1.1: Ifwewanttostaywithsomethingthat'sbeenaroundawhile,JAX-RPCwillcontinuetobesupportedfor some time tocome. If we don't want to step up to Java 5. If we want to send SOAP encoded messages or create RPC/encoded style WSDL. Reasons to step up to JAX-WS 2.0: If we want to use the new message-oriented APIs. If we want to use MTOM to send attachment data. If we want better support for XML schema through JAXB. If we want to use an asynchronous programming model in your web service clients. If we need to have clients or services that can handle SOAP 1.2 messages. If we want to eliminatetheneedfor SOAP inyour webservices and just usethe XML/HTTP binding. SOAP SOAP is an XML specification for sending messages over a network. SOAP messages are independent of any operating system and canusea varietyof communication protocols including HTTP and SMTP. SOAPisXMLheavy,hencebestusedwithtools/frameworks.JAX-WSisaframeworkthatsimplifiesusingSOAP.It is part of standard Java. SOAP message contains the following three parts: Envelope: This Envelope element contains an optional Header element and a mandatory Body element. Header: SOAP message contains the information which explains how the message is to be processed. Body: Body part of the SOAP message contains the actual payload of the end to end message transmission.
  • 98. 93 | P a ge Web Services Java-XML Data Binding SOAP-based web services use XML to exchange request and response messages. This requires an architecture for converting Java objects to XMLandthereverse. JAXB(Java Architecture for XMLBinding) was developed forthis purpose. JAX-RPCusesitsowndatamappingmodel.ThisisbecausetheJAXBspecificationhadnotbeenfinalizedwhenthe firstversionofJAX-RPCwascompleted.TheJAX-RPCdatamappingmodellackssupportforsomeXMLschemas. JAX-WS uses JAXB for data binding. JAXB provides mapping for virtually all schemas. Wecanuse JAXBannotations onyour Java bean and JAX-WSwill convert itandits properties to XML elements at runtime when sending the SOAP message. Web Services Definition Language (WSDL) TheWebServicesDescriptionLanguagesisanXML-basedinterfacedefinitionlanguagethatisusedfordescribing thefunctionalityofferedbyawebservice.TheacronymisalsousedforanyspecificWSDLdescriptionofaweb service(alsoreferredtoasaWSDL file), which provides amachine-readable description ofhow theservicecanbe called, what parameters it expects, and what data structures it returns. Therefore, its purpose is roughly similar to that of a method signature in a programming language. WSDL1.0(Sept.2000)wasdevelopedbyIBM,Microsoft,andAribatodescribeWebServicesfortheirSOAPtoolkit. It was built by combining two service description languages: NASSL (Network Application Service Specification Language) from IBM and SDL (Service Description Language) from Microsoft. WSDL1.1,publishedinMarch2001,istheformalizationofWSDL1.0.Nomajorchangeswereintroducedbetween 1.0 and 1.1.
  • 99. 94 | P a ge Web Services WSDL 1.2 (June 2003) was a working draft at W3C, but has become WSDL 2.0. According to W3C: WSDL 1.2 is easier and more flexible for developers than the previous version. WSDL 1.2 attempts to remove non- interoperable features and also defines the HTTP 1.1 binding better. WSDL 1.2 was not supported by most SOAP servers/vendors. WSDL 2.0 became a W3C recommendation on June 2007. WSDL 1.2 was renamed to WSDL 2.0 because it has substantial differences from WSDL 1.1. The changes are the following: Added further semantics to the description language Removed messageconstructs Operator overloading notsupported PortTypes renamed tointerfaces Ports renamed toendpoints The current version of WSDL is WSDL 2.0. Definition: The definition element must be the root element of the WSDL specification. This element defines the name of the web service, information about the multiple namespaces used though out the WSDL document. Types: This element is very important while sharing the data across multiple platforms using web services. The datatypeof thevariableswe are usingin theweb services shouldbe compatible with all platforms.Thetypes elementisusedtodefineallthedatatypesusedbetweentheendtoendtransmissions.XSDorXMLSchema Definition is used to define the types used in theWSDL. The detailed overview of XSD will explain in the next section.
  • 100. 95 | P a ge WebServices Message: Eachmessage describeseithertheinputoroutputofthewebservicetransmissionandithasthename ofthemessage andzero or more-partmessage elements Inputmessage contains therequestinformation andthe corresponding part message details. The output message element contains the details about the response from the server. portType: PortType elements are an entity like a Java class containing group of operations. This element describes a complete operation definition by combining input and output messages. One portType element can describe multiple operations Binding: The binding element describes how the service will be implemented in the transmission. Service: Service element provides the address, information about the service. This element defines the URL of the service we are invoking Top-Down vs. Bottom-Up There are two ways of building SOAP web services. We can go with a top-down approach or a bottom-up approach. In a top-down (contract-first) approach, a WSDL document is created, and the necessary Java classes are generated from the WSDL. In abottom-up(contract-last) approach, the Java classes are written, and the WSDL is generated from theWSDL. Writing a WSDL file can be quite difficult depending on how complex your web service is. This makes the bottom- upapproachaneasieroption.Ontheotherhand,sinceyourWSDLisgeneratedfromtheJavaclasses,anychange in code might cause a change in theWSDL. This is not the case for the top-down approach. Features of JAX-WS Requests and responses are transmitted as SOAP messages (XML files) over HTTP Even though SOAP structure is complex, developer need not bother about the complexity in messaging. The JAX-WS run time system manages all the parsing related stuffs. SinceJAX-WSusestheW3Cdefinedtechnologies,aSOAPwebserviceclientcanaccessaSOAPwebservice that is running in a non-java platform. A machine readable WSDL (Web Service Description Language) file which describes all the operations about a service can be present in case of SOAP web services Annotations can be used with JAX-WS to simplify the development Annotations used in JAX WS AnnotationscanbeusedinJavaclassesincreatingwebservices.Themostcommonlyusedannotationsarelisted below: @WebService @WebMethod @WebParam @WebResult @SOAPBinding @OneWay AsJAX-WSisanAPIwecan’tstartthedevelopmentdirectlywithAPI.WeneedanimplementationforthisAPI.
  • 101. 96 | P a ge WebServices JAX-WS implementations There are several implementations for JAX-WS. Some of them are: Developing WebService using JAX-WS API with RI implementation Deciding Technology Stack Specification : B.P 1.1 API : JAX-WS Implementation : Reference Implementation(RI) Role : Provider Approach : Contract LastApproach Endpoint : Servlet Endpoint MEP : Synchronous request - reply MEF : Document Literal (By default)
  • 102. 97 | P a ge WebServices Requirement: Develop an application to performAirthematic Operations through WebService Procedure of developing Provider Step 1: - Create Dynamic web project in IDE and add jax-ws RI related jars in project lib folder Step 2: - Create Service Endpoint Interface (This is optional in jax-ws api)
  • 103. 98 | P a ge WebServices Step3: - Create Service Implementation class Step 4:- CreateWeb servicedeploymentdescriptorfileinprojectWEB-INF folder (sun-jaxws.xml) with endpoint and url-pattern details Step 5: Configure WSServletContextListener & WSServlet in web.xml
  • 104. 99 | P a ge WebServices Step 6: Deploy the application and access using Endpoint URL Access the WSDL using below URL Note: If we are able access the WSDL like above, that means Provider is up and running
  • 105. 100 |P a ge WebServices Step 7: Test the Provider using SOAP UI tool Open SOAP UI - > Click on File - > New SOAP Project -> Enter Project Name and WSDL URL Step 8: Send SOAP request like below - > we can SOAP Response
  • 106. 101 |P a ge WebServices Developing Consumer After developing the provider, to access provider, we need to build the Consumer. JAX-WSAPIsupportsboththedevelopmentsofProvideraswellasConsumer. JAX-WSAPIsupportstwotypes of consumer, theyare  Stub based consumer  Dispatch API From above two approaches, most of the projects use stub based consumer and following section describes how to build a stub based consumer for JAX-WS Provider. Procedure for Developing STUB Based Consumer for JAX-WS Provider Step 1: Open IDE and create a Java Project Step 2: Generate classes required for consumer using wsimport tool by giving wsdl URL as input Syntax: wsimport –d src –keep –verbose WSDL_URL Note: wsimport tool will be shipped as part of JDK itself
  • 107. 102 |P a ge WebServices After classes are generated -> Refresh the project - > we can see classes like below Step 3: Develop Consumer class to access the provider
  • 108. 103 |P a ge WebServices Step 4: Run CalcServiceConsumer.java class Contract First Approach Step1: Create Dynamic web project and add jar files in project lib folder
  • 109. 104 |P a ge WebServices Step 2: Create WSDL file in project WEB-INF folder ---------------------------------------------WeatherService.wsdl Start--------------------------------------------- <?xml version="1.0" encoding="UTF-8"?> <wsdl:definitions targetNamespace="http://service.weather.com" xmlns:apachesoap="http://xml.apache.org/xml-soap" xmlns:impl="http://service.weather.com" xmlns:intf="http://service.weather.com" xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/" xmlns:wsdlsoap="http://schemas.xmlsoap.org/wsdl/soap/" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> <!--WSDL created by Apache Axis version: 1.4 Built on Apr 22, 2006 (06:55:48 PDT) --> <wsdl:types> <schema elementFormDefault="qualified" targetNamespace="http://service.weather.com" xmlns="http://www.w3.org/2001/XMLSchema"> <element name="getTemperature"> <complexType> <sequence> <element name="zip" type="xsd:int" /> </sequence> </complexType> </element> <element name="getTemperatureResponse"> <complexType> <sequence> <element name="getTemperatureReturn" type="xsd:double" /> </sequence> </complexType> </element> </schema> </wsdl:types> <wsdl:message name="getTemperatureRequest"> <wsdl:part element="impl:getTemperature" name="parameters"> </wsdl:part> </wsdl:message> <wsdl:message name="getTemperatureResponse"> <wsdl:part element="impl:getTemperatureResponse" name="parameters"> </wsdl:part> </wsdl:message> <wsdl:portType name="WeatherService"> <wsdl:operation name="getTemperature"> <wsdl:input message="impl:getTemperatureRequest" name="getTemperatureRequest"> </wsdl:input> <wsdl:output message="impl:getTemperatureResponse" name="getTemperatureResponse">
  • 110. 105 |P a ge Web Services </wsdl:output> </wsdl:operation> </wsdl:portType> <wsdl:binding name="WeatherServiceSoapBinding" type="impl:WeatherService"> <wsdlsoap:binding style="document" transport="http://schemas.xmlsoap.org/soap/http" /> <wsdl:operation name="getTemperature"> <wsdlsoap:operation soapAction="" /> <wsdl:input name="getTemperatureRequest"> <wsdlsoap:body use="literal" /> </wsdl:input> <wsdl:output name="getTemperatureResponse"> <wsdlsoap:body use="literal" /> </wsdl:output> </wsdl:operation> </wsdl:binding> <wsdl:service name="WeatherService"> <wsdl:port binding="impl:WeatherServiceSoapBinding" name="WeatherService"> <wsdlsoap:address location="http://localhost:4040/WeatherWeb/services/WeatherServiceImpl" /> </wsdl:port> </wsdl:service> </wsdl:definitions> -----------------------------------------------WeatherService WSDL End------------------------------------------- Step-3:GenerateBindingclassesbasedonWSDLfileusingwsimporttool Syntax:wsimport–dsrc–keep–verbosePATH_OF_WSDL
  • 111. 106 |P a ge Web Services Step 4: Create WeatherServiceImpl.java with business logic Step 5: Create WebService deployment descriptor filein projectWEB-INF folder (sun-jaxws.xml)
  • 112. 107 |P a ge Web Services Step 6: Configure WSServlet in web.xml file Step 7: Deploy the application and access the Endpoint Step 8: Test the Provider using SOAP UI tool
  • 113. 108 |P a ge WebServices SOAP Handlers Handlersarethemessageinterceptorswhichdoesadditionalprocessingoftheinboundand outbound messages. Inbound messages are the request messages (client to web service) Outbound messages are the response messages (web service to client) Additional processing ofa SOAP message would beto add some additionalinformationto SOAP headers or manipulate the values based on some condition etc. Usecase-1: AttachmostcommonlyusedparametersintheSOAPheaderusingahandlerattheclient side. Intheserverside,writeahandlerwhichcancheckthesecommonlyusedparametersfrom the header and then produce the response from the cache if these parameters are found otherwise get the data from the backend. This way it will improve the web service performance. Usecase-2: In the client-side handler, add some client identityinformation in the SOAP header like IP address of aclient  In the server-side handler, extract the IP address from the SOAP header and check whether it belongs to trusted IP addresses or not and then process it further if it’s a trusted IP else throw an exception which can be sent as SOAP fault JAX-WS provides 2 types of Message handlers 1. SOAP handlers 2. Logical handlers SOAP handlers: SOAP handlers are the protocol specific handlers and they can access or change the protocol specific aspect(likeheaders)of amessageand also,theycanalterthebodyof a SOAPmessage Basically, SOAP handlers can access the entire SOAP message (header + body) Logical handlers: Logical handlers are protocol-agnostic and cannot access or change any protocol-specific parts (like headers) of a message. They act only on the payload of the message. Basically, Logical handlers can access only body of the message. Note:ThemostpreferredhandleristheSOAPhandlerasitprovidesanaccesstotheentireSOAP message (header +body)
  • 114. 109 |P a ge Web Services Message Context Message context provides methods to access and modify the inbound and outbound messages. It also provides some properties which can be used to determine whether message is inbound or outbound. Each SOAP Handler should implement javax.xml.ws.handler.soap.SOAPHandler interface Each Logical handlers should implement javax.xml.ws.handler.LogicalHandler interface Messagecontextforlogicalhandlersisrepresentedbyjavax.xml.ws.handler.LogicalMessageContext MessagecontextforSOAPhandlersisrepresentedby javax.xml.ws.handler.soap.SOAPMessageContext Message for logical handler is represented by javax.xml.ws.LogicalMessage Message for SOAP handler is represented by javax.xml.soap.SOAPMessage WecanwritebothSOAPhandlerandLogichandlerwithinahandlerchainbutinthiscase,logicalhandlers will beexecuted before the SOAPhandlers onoutbound message and SOAP handlersareexecuted before the logic handlers on inbound message. We can see that in below diagram
  • 115. Web Services 110 |P a ge How we define handlers? To define a handler we just need to implement the handler interface and override the below 3 methods 1.handleMessage() 2.handleFault() 3.close() handleMessage ( ) : This method will be called for both inbound and outbound messages Perform the additional processing of the message in this method. handleFault():ThismethodhandlestheprocessingofanySOAPfaultsgeneratedbythehandleMessage() method, and also the faults generated by the back-end component close():Thisiscalledafterthecompletionofmessageprocessingbyallhandlersforeachwebservice invocation. Thismethod can be used to clean up all resources which are used during processing ofthe message. Webservice development using SOAP Handler. We are going to develop a Webservice provider i.e. AtmWeb. This Provider(IAtm.java) contains a withdraw(..) methodtowithdrawmethod.Whenconsumersendrequestforwithdraw(..)method,firstIwanttovalidate consumerusingaSecretKey.TovalidateconsumersentsecretkeyIamdevelopingAuthenticationHandler (SOAP Handler). If secret-key is matched then consumer request will be processed and returns the successful responseifsecret-keyisnotmatchedthenProvider willreturn SOAPFaultExceptionasaresponsetoConsumer. As part of this Authentication Handler I am using Secret Key as  “Ashok-IT”
  • 116. Web Services 111 |P a ge Step-1: - Create a project like below Provider contains below classes AccountInfo.java, InvoiceInfo.java and TransactionInfo.java  Model classes IAtm.java  Service Endpoint interface AtmImpl.java  Service Endpoint Interface Implementation class AuthenticationHandler.java  AuthenticationHandler tovalidate Secret Key Handler-chain.xml  Handler Chain configuration file Withdraw.java and WithdrawResponse.java  Binding classes
  • 117. 112 |P a ge WebServices Below are the model classes Below are the Service Endpoint interface and Impl classes
  • 118. 113 |P a ge WebServices -----------------------------------------AuthenticateHandler.java start------------------------------------------------------ public class AuthenticateHandler implements SOAPHandler<SOAPMessageContext> { //Choosing some secret key for validation private static final String SECRET_KEY = "Ashok-IT"; @Override public void close(MessageContext ctx) { } @Override public boolean handleFault(SOAPMessageContext arg0) { // TODO Auto-generated method stub return false; } /** * This method is used to handle inbound and outbound soap msgs */ @Override public boolean handleMessage(SOAPMessageContext ctx) { Boolean outbound = (Boolean) ctx.get(MessageContext.MESSAGE_OUTBOUND_PROPERTY); if (!outbound) { SOAPMessage soapMsg = ctx.getMessage(); try { soapMsg.writeTo(System.out); // Grabbing soap header from soap msg SOAPHeader soapHeader = soapMsg.getSOAPHeader(); Iterator<?> headerIterator = soapHeader.extractHeaderElements(SOAPConstants.URI_SOAP_ACTOR_NEXT); // If soap header presented then process if (headerIterator.hasNext()) { Node node = (Node) headerIterator.next();
  • 119. 114 |P a ge WebServices if (node != null) { String secretKey = node.getValue(); if (SECRET_KEY.equals(secretKey.trim())) { // Key matching.. process the request return true; } else { // Key did not match // Throw SOAP Fault exception generateSoapFaultException(soapMsg); } } } else { // Header is not there // Throw SOAP Fault exception generateSoapFaultException(soapMsg); } }catch(SOAPExceptione){ e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } return true; } @Override public Set<QName> getHeaders() { // TODO Auto-generated method stub return null; }
  • 120. 115 |P a ge WebServices /** * This method is used to generate SOAP Fault Exception when secret key is * not matched * @param soapMsg */ public void generateSoapFaultException(SOAPMessage soapMsg) { SOAPBody soapBody; try { soapBody = soapMsg.getSOAPBody(); SOAPFault soapFault = soapBody.addFault(); soapFault.setFaultString("Secret Key is not matched...!!"); throw new SOAPFaultException(soapFault); }catch(SOAPExceptione){ e.printStackTrace(); } } } ---------------------------------------------AuthenticateHandler.java End----------------------------------------------- Below is the Handler-Chain configuration file
  • 121. 116 |P a ge WebServices Below are the Binding classes Below is the Webservice description file
  • 122. 117 |P a ge WebServices Web Application Deployment Descriptor file DeploytheProviderapplicationandaccessWSDLwithbelowURL WSDL URL  http://localhost:4040/AtmWeb/withdraw?wsdl If WSDL is accessible, provider is up and running
  • 123. 118 |P a ge WebServices AtmWeb-Consumer Development with SOAP Handler Create a project Create Client-Side stubs using WSDL URL  http://localhost:4040/AtmWeb/withdraw?wsdl Below is the Consumer Side Handler class which is used to add Secret Key into soap message --------------------------------------AtmWebConsumerHandler.java start---------------------------------------------- public class AtmWebConsumerHandler implements SOAPHandler<SOAPMessageContext> { public boolean handleMessage(SOAPMessageContext context) { System.out.println("Consumer : handleMessage() Begin"); Boolean outBoundProperty = (Boolean) context.get(MessageContext.MESSAGE_OUTBOUND_PROPERTY); // If its an outgoing message from client, then outBoundProperty will be // true if (outBoundProperty) { try { SOAPMessage soapMsg = context.getMessage(); SOAPEnvelope soapEnv = soapMsg.getSOAPPart().getEnvelope(); SOAPHeader soapHeader = soapEnv.getHeader();
  • 124. 119 |P a ge WebServices // if no header, add the header if(soapHeader== null){ soapHeader = soapEnv.addHeader(); } String secretKey = getSecretKey(); // add a soap header called "secretkey" QName qname = new QName("http://service.atm.com/", "SecretKey"); SOAPHeaderElement soapHeaderElement = soapHeader.addHeaderElement(qname); soapHeaderElement.setActor(SOAPConstants.URI_SOAP_ACTOR_NEXT); // Add Secret Key to SOAP header soapHeaderElement.addTextNode(secretKey); soapMsg.saveChanges(); //Outputthemessagetoconsole soapMsg.writeTo(System.out); }catch(SOAPExceptione){ System.err.println(e); } catch (IOException e) { System.err.println(e); } } // Returning true makes other handler chain to continue the execution return true; } publicbooleanhandleFault(SOAPMessageContextcontext){ System.out.println("Consumer : handleFault() Begin"); return true; } public void close(MessageContext context) { System.out.println("Consumer : close() Begin"); }
  • 125. 120 |P a ge WebServices public Set<QName> getHeaders() { System.out.println("Consumer : getHeaders() Begin"); return null; } private String getSecretKey() { // This is the secret key which shared by provider return "Ashok-IT"; } } --------------------------------------------------AtmWebConsumerHandler.java End---------------------------------------------- Add the @HandlerChain annotation in AtmImplService.java class like below
  • 126. 121 |P a ge WebServices Below is the Stub Based Consumer class to invoke Provider
  • 127. 122 |P a ge WebServices JAX-WS API with APACHE-AXIS2 IMPLEMENTATION Apache Axis2 is a Web Services / SOAP / WSDL engine, the successor to the widely used Apache Axis SOAP stack. There are two implementations of the Apache Axis2 Web services engine - Apache Axis2/Java and ApacheAxis2/C. Why Apache Axis2? A new architecture for Axis2 was introduced during the August 2004 Summit in Colombo, Sri Lanka. The new architecture on which Axis2 is based on is more flexible, efficient and configurable in comparison to Axis1.x architecture. Some well-established concepts from Axis 1.x, like handlers etc., have been preserved in the new architecture. Apache Axis2 notonly supports SOAP 1.1 and SOAP 1.2,but it alsohasintegrated supportforthe widely popularRESTstyleofWebservices.ThesamebusinesslogicimplementationcanofferbothaWS-*style interface as well as a REST/POX style interface simultaneously. Apache Axis2 is more efficient, more modular and more XML-oriented than the older version. It is carefullydesignedtosupporttheeasyadditionofplug-in"modules"thatextendtheirfunctionalityfor features such as security and reliability. The Modules currently available or under development include:  WS-Security - Supported by Apache Rampart  WS-Addressing -Module included as part of Axis2 core Apache Axis2 is built on Apache AXIOM, a new high performant, pull-based XML object model. Axis2 comes with many new features, enhancements and industry specification implementations. The key features offered are as follows: Speed-Axis2usesitsownobjectmodelandStAX(StreamingAPIforXML)parsingtoachievesignificantly greater speed than earlier versions of Apache Axis. Low memory foot print- Axis2 was designed ground-up keeping low memory foot print in mind. AXIOM - Axis2 comes with its own light-weight object model, AXIOM, for message processing which is extensible, highly performant and is developer convenient. Hot Deployment - Axis2 is equipped with the capability of deploying Web services and handlers while thesystemisupandrunning.Inotherwords,newservicescanbeaddedtothesystemwithouthaving toshutdowntheserver.SimplydroptherequiredWebservicearchiveintotheservicesdirectoryinthe repository,andthedeploymentmodelwillautomaticallydeploytheserviceandmakeitavailablefor use. Asynchronous Web services - Axis2 now supports asynchronous Web services and asynchronous Web services invocation using non-blocking clients and transports.
  • 128. 123 |P a ge WebServices MEP Support-Axis2nowcomeshandywiththeflexibilitytosupportMessageExchangePatterns(MEPs) with in-built support for basic MEPs defined in WSDL 2.0. Flexibility - The Axis2 architecture gives the developer complete freedom to insert extensions into the engineforcustomheaderprocessing,systemmanagement,andanythingelseyoucanimagine. Stability-Axis2definesasetofpublishedinterfaces which changerelatively slowlycomparedtotherest of Axis. Component-orientedDeployment-YoucaneasilydefinereusablenetworksofHandlerstoimplement common patterns of processing for your applications, or to distribute to partners. Transport Framework - We have a clean and simple abstraction for integrating and using Transports (i.e., senders and listeners for SOAP over various protocols such as SMTP, FTP, message-oriented middleware, etc), and the core of the engine is completely transport-independent. WSDLsupport-Axis2supportstheWebServiceDescriptionLanguage,version1.1and2.0,whichallows you to easily build stubs to access remote services, and also to automatically export machine-readable descriptions of your deployed services from Axis2. Composition and Extensibility - Modules and phases improve support for composability and extensibility. Modules support composability and can also support new WS-* specifications in a simple and clean manner. They are however not hot deployable as they change the overall behavior of the system. Apache Axis2 software is coming in the form of two distributions 1) Binary Distribution 2) War Distribution Binary Distribution: - which contains the Jar's and tools (Java2WSDL, WSDL2Java) that facilitate the development of WebServices. WarDistribution:-ActsasServer-SideRuntimeengineinwhichYourServicesaredeployedandexposed.
  • 129. 124 |P a ge WebServices Download Apache AXIS2 Distribution from below URL Extract it into some suitable location AfterDownloadingtheAxis2DistributionsfirstwecansetpathEnvironmentvariablesofAxis2binary distributions.
  • 130. 125 |P a ge Web Services AftersettingtheEnvironmentvariablesforbinarydistributionwecandeploythe axis2.warfile into any server Then Check axis2 welcome page is opening (OR) not. Configuring Apache AXIS-2 in Eclipse IDE Step 1: Open Eclipse IDE Windows –> Preferences Step2:BrowsethroughAxis-2preferencesandselectaxis-2distribution->ClickonApply- >Clickon OK.
  • 131. 126 |P a ge Web Services That’s it!! we are done with installing Apache Axis2 plugin in Eclipse IDE Now that we have installed Apache Axis2 plugin in Eclipse IDE and similarly configure Tomcat server we will move on developing top-down approach using above configuration. Developing JAX-WS API WebService using Apache – Axis2 implementation Technology Used Java 1.7 Eclipse Kepler IDE Apache Axis2-1.6.2 Apache Tomcat-8.0.12 Step1:In Eclipse,createnew“Dynamic WebProject” Step 2: Provide “Project Name” and make sure to change the “Dynamic web module version” to 2.5 –> click Next Step 3: By default, there will be “src” folder –> add “resources” folder to place XSD/WSDL using “Add Folder…” button Step 4: check “Generate web.xml” and Click Finish Step 5: Initial project structure (Eclipse Package Explorer view)
  • 132. 127 |P a ge Web Services Step 6: Add Book Service WSDL and its associated XSD files under “resources” folder BookService.wsdl
  • 133. 128 |P a ge Web Services Step 7: Right Click on Project –> New –> Web Service Step 9: Configure required parameters Web service type: Top down Java bean Web Service Service definition: browse through WSDL file here Configuration: Server runtime: Tomcat 8.x server Web service runtime: Apache Axis2 Service project: Project-name
  • 134. 129 |P a ge Web Services Step 11: accept default and click Next Step 12: Click “Start Server”
  • 135. Web Services 130 |P a ge Step 13: This is optional –> accept default and click Finish Step 14: After clicking Finish in the above step -> default endpoint implementation class will be opened in Eclipse IDE Step 15: Provide business logic to the endpoint class Step 16: Web service implemented –> deploy the service to tomcat server Deployment Right click on project –> Run As –> Run on Server Check whether web service is correctly deployed or not? Step 17: This is home page, after deploying apache axis2 based web service in tomcat server. Click services
  • 136. 131 |P a ge WebServices Step 18: Click BookService to view wsdl of the deployed book service IfweareabletoseetheWSDLinbrowserthatmeansourproviderisupandrunning. We can test the provider using SOAP UI tool.
  • 137. 132 |P a ge WebServices Spring +JAXWS Web Services (SOAP) Integration Example:
  • 138. 133 |P a ge WebServices pom.xml <projectxmlns="http://maven.apache.org/POM/4.0.0"xmlns:xsi="http://www.w3.org/2001/XML Schema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven- v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.springjaxwsexample</groupId> <artifactId>SpringJaxWsExample</artifactId> <packaging>war</packaging> <version>1.0</version> <name>SpringJaxWsExample MavenWebapp</name> <url>http://maven.apache.org</url> <repositories> <repository> <id>java.net</id> <url>http://download.java.net/maven/2</url> </repository> </repositories> <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>3.8.1</version> <scope>test</scope> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>3.2.0.RELEASE</version> </dependency> <!-- JAX-WS-RI --> <dependency> <groupId>com.sun.xml.ws</groupId> <artifactId>jaxws-rt</artifactId> <version>2.2.3</version> </dependency> <!-- Library from java.net, integrate Spring with JAX-WS --> <dependency> <groupId>org.jvnet.jax-ws-commons.spring</groupId> <artifactId>jaxws-spring</artifactId> <version>1.8</version> <exclusions> <exclusion> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> </exclusion> <exclusion>
  • 139. 134 |P a ge Web Services web.xml <web-app> <servlet> <servlet-name>jaxwsservlet</servlet-name> <servlet-class> com.sun.xml.ws.transport.http.servlet.WSSpringServlet </servlet-class> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>jaxwsservlet</servlet-name> <url-pattern>/registerProduct</url-pattern> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> </exclusion> <exclusion> <groupId>com.sun.xml.stream.buffer</groupId> <artifactId>streambuffer</artifactId> </exclusion> <exclusion> <groupId>org.jvnet.staxex</groupId> <artifactId>stax-ex</artifactId> </exclusion> </exclusions> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.35</version> </dependency> <!-- https://mvnrepository.com/artifact/commons-pool/commons-pool --> <dependency> <groupId>commons-pool</groupId> <artifactId>commons-pool</artifactId> <version>1.6</version> </dependency> <!-- https://mvnrepository.com/artifact/commons-dbcp/commons-dbcp --> <dependency> <groupId>commons-dbcp</groupId> <artifactId>commons-dbcp</artifactId> <version>1.4</version> </dependency> </dependencies> <build> <finalName>SpringJaxWsExample</finalName> </build> </project>
  • 140. 135 |P a ge WebServices Note : ContextLoaderListener will create spring container.It searches the spring cfgfile name as applicationContext.xml in WEB-INFfolder Product.java ProductDAO.java </servlet-mapping> <!-- Register Spring Listener --> <listener> <listener-class> org.springframework.web.context.ContextLoaderListener </listener-class> </listener> </web-app> package com.springjaxwsexample.domain; import java.io.Serializable; publicclassProductimplements Serializable{ private Integer pid; private String productName; private Double price; public Integer getPid() { returnpid; } publicvoid setPid(Integer pid) { this.pid = pid; } public String getProductName() { returnproductName; } publicvoid setProductName(String productName) { this.productName = productName; } public Double getPrice() { returnprice; } publicvoid setPrice(Double price){ this.price = price; } } package com.springjaxwsexample.dao; import com.springjaxwsexample.domain.Product; publicinterface ProductDAO { publicint registerProduct(Product product); }
  • 141. 136 |P a ge WebServices ProductDAOImpl.java ProductService.java ProductServiceImpl.java package com.springjaxwsexample.dao; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.SQLException; import javax.sql.DataSource; import com.springjaxwsexample.domain.Product; publicclassProductDAOImplimplementsProductDAO{ private DataSource dataSource;//dependency public void setDataSource(DataSource dataSource) { this.dataSource = dataSource; } publicint registerProduct(Product product) { intcount=0; try{ Connection con=dataSource.getConnection(); String sql="insert into Product_Details values(?,?,?)"; PreparedStatement pst=con.prepareStatement(sql); pst.setInt(1,product.getPid()); pst.setString(2,product.getProductName()); pst.setDouble(3,product.getPrice()); count=pst.executeUpdate(); }catch(SQLException se){ se.printStackTrace(); } returncount; } } package com.springjaxwsexample.service; import com.springjaxwsexample.domain.Product; public interface ProductService { public boolean registerProduct(Product product); } package com.springjaxwsexample.service; import com.springjaxwsexample.dao.ProductDAO; import com.springjaxwsexample.domain.Product; /** writing of this service is an optional * in this class write Exception-Handling,Transaction-Management logic,loggers,Type- Converstion,Bussiness logic's * if we are not writing this separate service class then we include above logic directly in webservice class
  • 142. 137 |P a ge WebServices ProductServiceWS.java applicationContext.xml */ publicclass ProductServiceImpl implements ProductService{ private ProductDAO productDAO; public void setProductDAO(ProductDAO productDAO) { this.productDAO = productDAO; } public cboolean registerProduct(Product product) { booleanflag=false; intcount=productDAO.registerProduct(product); if(count>0){ flag=true; } returnflag; } package com.springjaxwsexample.ws; import javax.jws.WebMethod; import javax.jws.WebService; import com.springjaxwsexample.domain.Product; import com.springjaxwsexample.service.ProductService; @WebService publicclass ProductServiceWs{ private ProductService productService; @WebMethod(exclude=true) public void setProductService(ProductService productService) { this.productService = productService; } @WebMethod(exclude=false) public Boolean registerProduct(Product product) { Boolean flag=productService.registerProduct(product); returnflag; } } <beansxmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:ws="http://jax-ws.dev.java.net/spring/core" xmlns:wss="http://jax-ws.dev.java.net/spring/servlet" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd http://jax-ws.dev.java.net/spring/core http://jax-ws.dev.java.net/spring/core.xsd http://jax-ws.dev.java.net/spring/servlet http://jax-ws.dev.java.net/spring/servlet.xsd">
  • 143. 138 |P a ge Web Services Note: Test the above service by using SOAP UI tool. <wss:bindingurl="/registerProduct"> <wss:service> <ws:servicebean="#productServiceWs"/> </wss:service> </wss:binding> <beanid="dataSource"class="org.apache.commons.dbcp.BasicDataSource"> <propertyname="driverClassName"value="com.mysql.jdbc.Driver"/> <propertyname="url"value="jdbc:mysql://localhost:3306/nit"/> <propertyname="username"value="root"/> <propertyname="password"value="root"/> </bean> <beanid="productDAO"class="com.springjaxwsexample.dao.ProductDAOImpl"> <propertyname="dataSource"ref="dataSource"/> </bean> <beanid="productService"class="com.springjaxwsexample.service.ProductServiceImpl"> <propertyname="productDAO"ref='productDAO'/> </bean> <beanid="productServiceWs"class="com.springjaxwsexample.ws.ProductServiceWs"> <propertyname="productService"ref="productService"/> </bean> </beans>
  • 144. 139 |P a ge Web Services RestfulServices
  • 145. Web Services 140 |P a ge The term REST comes from Roy Fielding's PhD dissertation, published in 2000, and it stands for REpresentationalStateTransfer.RESTbyitselfisnotanarchitecture;RESTisasetofconstraintsthat, whenappliedtothedesignofasystem,createsasoftwarearchitecturalstyle.Ifweimplementallthe RESTguidelinesoutlinedinFielding'swork,weendupwithasystemthathasspecificrolesfordata, components, hyperlinks, communication protocols, and data consumers. Fielding arrived at REST by evaluating all networking resources and technologies available for creating distributed applications. Without any constraints, anything and everything goes, leading us to develop applications that are hard to maintain and extend. He looks at document distributed application architectural styles beginning with what he callsthe null space—which represents the availability of every technology and every style of application development with no rules or limits—and ends with the following constraints that define a RESTful system:  It must be a client-server system  Ithastobestateless—thereshouldbenoneedfortheservicetokeepusers'sessions;inother words, each request should be independent of others  It has to support a caching system—the network infrastructure should support cache at different levels  It hasto be uniformly accessible—each resource must have a unique address and a valid point of access  It has to be layered—it must support scalability  Itshouldprovidecodeondemand—althoughthisisanoptionalconstraint,applicationscanbe extendable at runtime by allowing the downloading of code on demand, for example, Java Applets These constraints don't dictate what kind of technology to use; they only define how data is transferred between componentsandwhatarethebenefitsof followingtheguidelines. Therefore,a RESTful system canbeimplementedinanynetworkingarchitectureavailable.Moreimportant,thereisnoneedforus to invent new technologies or networking protocols: we can use existing networking infrastructures such as the Web to create RESTful architectures. Consequently, a RESTful architecture is one that is maintainable, extendable, anddistributed. BeforeallRESTconstraintswereformalized,wealreadyhadaworkingexampleofaRESTfulsystem:that ie Web.Wecanask,then,whytointroducetheseRESTfulrequirementstowebapplicationdevelopment whenit'sagreedthattheWebisalreadyRESTful?-Weneedtofirstqualifyherewhatit'smeantforthe Webto be RESTful.Ontheonehand,thestaticwebisRESTful, becausestaticwebsitesfollowFielding's definition of a RESTful architecture. For instance, the existing web infrastructure provides caching systems, stateless connection, and unique hyperlinks to resources, where resources are all of the documents available on every website and the representations of these documents are already set by files being browser readable (HTML files, for example). Therefore, the static web is a system built on the REST-like architectural style. On the other hand, traditionaldynamicwebapplicationshaven'talwaysbeenRESTful,becausetheytypicallybreaksomeof the outlined constraints. For instance, most dynamic applications are not stateless, as servers require tracking users through container sessions or client-side cookie schemes. Therefore, we conclude that thedynamicwebisnotnormallybuiltontheREST-likearchitecturalstyle.Wecannowlookatthe
  • 146. 141 |P a ge WebServices abstractions that make a RESTful system, namely resources, representations, URIs, and the HTTP request types that make up the uniform interface used for client/server data transfers. Resources A RESTful resource is anything that is addressable over the Web. By addressable, we mean resources that canbe accessed andtransferredbetween clientsand servers.Subsequently, aresource isalogical, temporalmappingtoaconcept in theproblem domainforwhich we are implementingasolution. These are some examples of REST resources:  A news story  The temperature in NY at 4:00 p.m. EST  A tax return stored in IRS databases  A list of code revisions history in a repository like SVN or CVS  A student in some classroom in some school  A search result for a item in a web index, such as Google Even though a resource's mapping is unique, different requests for a resource can return the same underlying binary representation stored in the server. For example, let's say we have a resource within thecontextofapublishingsystem.Then,arequestfor"thelatestrevisionpublished"andtherequest for"revisionnumber12"willatsomepointintimereturnthesamerepresentationoftheresource:the last revision is revision12.However, when thelatestrevision published isincreasedto version13,a requesttothelatestrevisionwillreturnversion13,andarequestforrevision12willcontinuereturning version12.AsresourcesinaRESTfularchitecture,eachoftheseresourcescanbeaccesseddirectlyand independently, but different requests could point to the same data. Because we areusing HTTP to communicate, we can transfer anykind ofinformation that can bepassed between clients and servers. For example, if we request a text file from CNN, our browser receives a text file.IfwerequestaFlashmoviefromYouTube,ourbrowserreceivesaFlashmovie.Thedataisstreamed inbothcasesoverTCP/IPandthebrowserknowshowtointerpretthebinarystreamsbecauseofthe HTTPprotocolresponseheaderContent-Type.Consequently,inaRESTfulsystem,therepresentationof a resource depends on the caller's desired type (MIME type), which is specified within the communication protocol's request. Representation The representation of resources is what is sent back and forth between clients and servers. A representation is a temporal state of the actual data located in some storage device at the time of a request. In general terms, it's a binary stream together with its metadata that describes how the stream istobeconsumedbyeithertheclientortheserver(metadatacanalsocontainextrainformationabout the resource, for example, validation, encryption information, or extra code to be executed at runtime). Throughoutthelifeof aweb service theremaybea varietyof clientsrequestingresources.Different clients are able to consume different representations of the same resource. Therefore, a representation cantakevariousforms,suchasanimage,atextfile,oranXMLstreamoraJSONstream,buthastobe available through the same URI.
  • 147. 142 |P a ge WebServices Forhuman-generatedrequeststhroughawebbrowser,arepresentationistypicallyintheformofan HTML page. For automated requests from other web services, readability is not asimportant and a more efficient representation can be used such as XML. URI A Uniform Resource Identifier, or URI, in a RESTful web service is a hyperlink to a resource, and it's the only means for clients and servers to exchange representations. The set of RESTful constraints don't dictatethat URIs must be hyperlinks. We onlytalkabout RESTfulURIs beinghyperlinks, because we are using theWeb to create web services. If we were using a different set of supporting technologies, a RESTfulURIwouldlookcompletelydifferent.However,thecoreideaofaddressabilitywouldstillremain. In a RESTful system, the URI is not meant to change over time, as the architecture's implementation is what managesthe services, locatestheresources, negotiatesthe representations, andthen sendsback responses with the requested resources. More important, if we were to change the structure of the storage device at the server level (swapping database servers, for example), our URIs will remain the sameandbevalidforaslongthewebserviceisonlineorthecontextofaresourceisnotchanged. WithoutRESTconstraints,resourcesareaccessedbylocation:typicalwebaddressesarefixedURIs.For instance, if we rename a file on a web server, the URI will be different; if we move a file to a different directory tree in a web server, the URI will change. Note that we could modify our web servers to execute redirectsatruntimetomaintainaddressability,butifweweretodothisforeveryfilechange,ourrules would becomeunmanageable. Uniform interfaces through HTTP requests In previous sections, we introduced the concepts of resources and representations. We said that resources are mappings of actual entity states that are exchanged between clients and servers. Furthermore, we discussed that representations are negotiated between clientsand servers throughthe communicationprotocolatruntime—throughHTTP.Inthissection,welookindetailatwhatitmeans toexchangetheserepresentations,andwhatitmeansforclientsandserverstotakeactionsonthese resources. Developing RESTful web services is similar to what we've been doing up to this point with our web applications.However,thefundamentaldifferencebetweenmodernandtraditionalwebapplication development is how we think of the actions taken on our data abstractions. Specifically, modern development is rooted in the concept of nouns (exchange of resources); legacy development is rooted in the concept of verbs (remote actions taken on data). With the former, we are implementing a RESTful web service; with the latter, we are implementing an RPC-like service (Remote Procedure Call). What's more, a RESTful service modifies the state of the data through the representation of resources; an RPC service,ontheotherhand,hidesthedatarepresentationandinsteadsendscommandstomodifythe state of the data at the server level (we never know what the data looks like). Finally,in modern web application development we limit design andimplementation ambiguity, because we have four specific actions that we can take upon resources—Create, Retrieve, Update, and Delete (CRUD). On the other hand, in traditional web application development, we can have countless actions with no naming or implementation standards.
  • 148. 143 |P a ge WebServices Therefore,withthedelineated rolesforresourcesand representations,we can nowmapourCRUD actions to the HTTP methods POST, GET, PUT, and DELETE as follows: Intheirsimplestform,RESTfulwebservicesarenetworkedapplicationsthatmanipulatethestateof resources. In this context, resource manipulation means resource creation, retrieval, update, and deletion. However, RESTful web services are not limited to just these four basic data manipulation concepts. On the contrary, RESTful web services can execute logic at the server level, but remembering that every result must be a resource representation of the domain at hand. Let'snowlookatthefourHTTPrequesttypesindetailandseehoweachofthemisusedtoexchange representations to modify the state of resources. GET/RETRIEVE: The method GET is used to RETRIEVE resources. Before digging into the actual mechanics of the HTTP GET request, first, we need to determine what a resourceisinthe context of ourwebservice andwhat typeof representation we'reexchanging. Fortherestofthissection,we'llusetheartificialexampleofawebservicehandlingstudentsinsome classroom, with a location of http://ashokit.com/. For this service, we assume an XML representation of a student to look as follows: And a list of students to look like:
  • 149. 144 |P a ge Web Services With our representations defined, we now assume URIs of the form http://ashokit.com/students to access a list of students, and http://ashokit.com/students/{name} to access a specific student that has the unique identifier of value name. We can now begin making requests to our web service. For instance, if we wanted the record for a student with the name Jane, we make a request to the URI http://ashokit.com/students/Jane. A representation of Jane, at the time of the request, may look like: Subsequently, we can access a list of students through the URI http://ashokit.com/students. The responsefromtheservicewillcontaintherepresentationofallstudentsandmaylooklike(assuming there are two students available): Now let's have a look at the request details. A request to retrieve a Jane resource uses the GET method with the URI http://ashokit.com/students/Jane. A sequence diagram of our GET request looks as follows:
  • 150. 145 |P a ge Web Services What's happening in the above GET request? 1. A Java client makes an HTTP request with the method type GET and Jane as the identifier for the student. 2. The client setsthe representation type it can handle through the Acceptrequest headerfield. 3. ThewebserverreceivesandinterpretstheGETrequesttobearetrieveaction.Atthispoint, thewebserverpassescontroltotheRESTfulframeworktohandletherequest.Notethat RESTful frameworks don't automatically retrieve resources, as that's not their job. The job of a framework isto easetheimplementation of the REST constraints. Business logic and storage implementation is the role of the domain-specific Java code. 4. Theserver-sideprogramlooksfortheJaneresource.Findingtheresource couldmeanlooking for it in a database, a filesystem, or a call to a different web service. 5. OncetheprogramfindsJane,itconvertsthebinarydataoftheresourcetotheclient's requested representation. 6. WiththerepresentationconvertedtoXML,theserversendsbackanHTTPresponsewitha numericcodeof200togetherwiththeXMLrepresentationasthepayload.Notethatifthere areanyerrors,theHTTPserverreportsbackthepropernumericcode,butit'suptotheclient to correctly deal with the failure. Allthe messagesbetween clientandserverare standardHTTP protocol calls.For everyretrieve action, we send a GET request and we get an HTTP response back with the payload of the response being the representationoftheresourceor,ifthereisafailure,acorrespondingHTTPerrorcode(forexample, 404 if a resource is not found; 500, if there is a problem with the Java code in the form of an exception).
  • 151. 146 |P a ge Web Services POST/CREATE: The method POST is used to CREATE resources. Because we are creating a student, we usethe HTTP method POST. Again,the URI to create anew student in our list is http://restfuljava.com/students/Jane. The method type for the request is set by the client. Assume Jane didn't exist in our list, and we want to add her. Our new Jane XML representation looks like: Notethatthelinkelementispartoftherepresentation,butit'semptybecausethisvalueisgenerated atruntimeandnotcreatedbytheclientsendingthePOSTrequest.Thisisjustaconventionforthis example; however, clients using a web service can dictate the structure of URIs. Now, the sequence diagram of our POST request looks as follows:
  • 152. 147 |P a ge Web Services What'shappeninginabovePOSTrequest? 1. A Java client makes a request to the URI http://ashokit.com/students/Jane, with the HTTP method set toPOST. 2. The POST request carries with it the payload in the form of an XML representation of Jane. 3. The server receives the request and lets the REST framework handle it; our code within the framework executes the proper commands to storethe representation (again,the storage device could be anything). 4. Once storingofthenewresourceiscompleted, aresponseissent back: ifit'ssuccessful, wesend a code of 200; if it's a failure, we send the appropriate error code. PUT/UPDATE: The method PUT is used to UPDATE resources. Toupdatearesource,wefirstneeditsrepresentationintheclient;second,attheclientlevelweupdate theresourcewiththenewvalue(s)wewant;and,finally,weupdatetheresourceusingaPUTrequest together with the representation as its payload. We're omitting the GET request to retrieve Jane from the web service, as it's the same one we illustrated intheprevioussection.Wemust,however,modifytherepresentationattheclientlevelfirst.Assume that we already have the student representation of Jane in the client and we want to change her age from 10 to12.
  • 153. 148 |P a ge Web Services Our original student representation looks as follows: Changing Jane's age to 12, our representation looks as follows: We are now ready to connect to our web service to update Jane by sending the PUT request to http://ashokit.com/students/Jane. The sequence diagram of our PUT request looks as follows: What's happening in above PUT request? 1. A Java client makes a PUT request to http://ashokit.com/students/Jane, with the new XML definition as itspayload. 2. TheserverreceivestherequestandletstheRESTframeworkhandleit.Atthispoint,weletour code execute the proper commands to update the representation of Jane. 3. Once completed, a response is sent back.
  • 154. 149 |P a ge WebServices DELETE/DELETE: The method DELETE is used to DELETE representations. Finally, deleting a resource makes use of the same URI we've used in the other three cases. Assume we want to delete Jane from our data storage. We send a DELETE request to our service with the URI http://ashokit.com/students/Jane. The sequence diagram for our DELETE request looks like: What's happening in above DELETE request? 1. A Java client makes a DELETE request to http://ashokit.com/students/Jane. 2. TheserverreceivestherequestandletstheRESTframeworkhandleit.Atthispoint,ourcode executes the proper commands to delete the representation of Jane. 3. Once completed, a response is sent back.
  • 155. 150 |P a ge WebServices JAX-RS-> JAX-RS is API from sun . JAX-RS API is used to develop/access the Restful services in java platform. JAX-RS stands for Java API For Xml Restfull services. JAX-RS Versions 0.x ,1.x (1.0, 1.1),2.x JAX-RS 2.0 is the latest release of JAX-RS. JAX-RS uses annotations,introduced in Java SE 5, to simplify the development and deployment of Restful services resources andclients. From version JAX-RS 1.1 on words , JAX-RS is an official part of Java EE 6 The Java API for RESTful Services provides portable APIs for developing, exposing and accessing Webapplicationsdesignedandimplemented incompliancewithprinciplesof RESTarchitectural style. Implementations of Jax RS API:- Apache CXF, an open source Web service framework Jersey, the reference implementation from Sun (now Oracle) RESTeasy, JBoss'simplementation Restlet from jerome Louvel. Apache Wink, Apache Software Foundation Difference between SOAP and Restful services In soap webservices we can use only xml to make communication between the client and server provider. InRestfullwebservicewecanmakecommunitactioninbetweenserverproviderandclientusing  XML  JSON (javascriptObjectNotation)  text  HTML Soap WebService supports both server level and application level security But Restfulservicessupportonlyserver levelsecuritybutnotfortheApplicationlevelsecurity. What is aResource? In REST architecture, everything is a resource. These resources can be text files, html pages, images, videos or dynamic business data. REST Server simply provides access to resources and REST client accesses and modifiestheresources. Hereeach resource isidentified byURIs. REST uses various
  • 156. 151 |P a ge WebServices representationstorepresentaresource liketext, JSON, XML. XML and JSONarethemostpopular representations of resources. Representation of Resources A resource in REST is similar Object in Object Oriented Programming. Once a resource isidentified then its representation is to be decided using a standard format so that server can send the resource in above said format and client can understand the same format. Forexample,inRESTfulWebServices- UserisaresourcewhichisrepresentedusingfollowingXML format: Same resource can be represented in JSON format: JSON: JSON stands for JavaScript Object Notation JSON is also communicator like xml is between two language Applications. <user> <id>101</id> <name>Mahesh</name> <profession>Former</profession> </user> { "id":101, "name":"Mahesh", "profession":"Former" }
  • 157. 152 |P a ge WebServices we can apply Restriction xml document to accept the data by using DTD or XSD. JSON we can't restrict to accept the data because it is normal text document. JSON format is interoperable format interoperable->lang independent and platform independent JSONformat is very lightweight format compared to SOAP/XML. JSON a is text-based document Ex:- {"studentId":101,"name":"raja","course":"java"}  To read the JSON format data from the java application andto construct JSON format data bythe java application we require JSON API. Different vendors provided JSON API for the java language. 1. Jackson API 2. Gson (Google sun)API 3. JSON simple API ByusingalltheaboveAPI’sfromjavaapplicationwecanconvertjavaobjecttojsonformatandjson format to javaobject. JSON Example with Jackson API: 1)Jackson API Provides Object Mapper class that is used to convert java obj into json and json into java obj. ObjectMapper class important methods  public String writeValueAsString (-)-->used to convert java obj into json  public T readValue(-)-->used to convert json into java obj  JACKSON API is having two versions 1.x and 2.x versions  if we are using Jackson 1.x version we can use the following jar's
  • 158. 153 |P a ge Web Services  jackson-core-asl jar  jackson-mapper-asl jar  the same above jar's if we want get with maven we can add the following dependencies in pom.xml  if we are using jackson 2.x version we can following jar's  jackson-core jar  jackson-annotations jar  jackson-databinding jar  with maven if we want to get the jar' we can add following dependencies in pom.xml file
  • 159. 154 |P a ge Web Services
  • 160. 155 |P a ge Web Services
  • 161. 156 |P a ge Web Services GSON Api to work with JSON Data Create project like below Add Gson maven dependency in pom.xml file like below
  • 162. 157 |P a ge WebServices Below is the model class to hold the data Below class is used to convert Object data to Json data
  • 163. 158 |P a ge WebServices Below file contains data in json format Below class is used to convert Json data into Java object Jersey implementation: In order to simplify development of RESTful Web services and their clients in Java, a standard and portable JAX-RS API has been designed. Jersey RESTful Web Services implementation is an open source, production quality ,used for developing RESTful Web Services in Java that provides support for JAX-RS APIs and serves as a JAX-RS (JSR 311 & JSR 339) Reference Implementation. Download the Jersey jar’s from ->https://jersey.java.net/  Jersey implementation is given by sun and it is having two versions 1.x and 2.x  Jersey 1.x provided Servlet com.sun.jersey.spi.container.servlet.ServletContainer  Jersey 2.x provided Servlet org.glassfish.jersey.servlet.ServletContainer
  • 164. 159 |P a ge WebServices Steps to develop the Restful application: step1: - create Root Resource class step2: - create resource methods to expose Step3: - configure the servlet in web.xml (The Servlet is providing by JAX-RS API implementations) step4: - deploy the app into server Root Resource  It is a server-side class which contains the data and functionality which is exposed as Resource class to theClient.  Root resource classesare simplejava classesthatare annotated with @Path annotation.  TheResourceclassmethodsarerequiredtodenotewithresourcemethoddesignatorannotation such as @GET, @PUT, @POST, @DELETE.  Resourcemethodsaremethodsofaresourceclassannotatedwitharesourcemethoddesignator annotation and exposing over the Network. Root Resource class Example to produce JSON Response:  Any class that is annotated with @Path Annotation is called as root Resource class.  IntheRestfullservicestheResourcesclassesareassociatedwithURItoidentifyandaccessit.  The @Path annotation's value is a relative URI path. In the example above, the Java class will be hosted at the URI path /products. Request Method Designator: In the Resource classwrite themethodswhich wewanttoexposetheoverthe Httpprotocolsasresource methods .The Methods should be annotated with relevant Http method designators like @GET,@POST,@PUT and@DELETE.  WhenwesentaGETrequestthemethodwith@GETannotationwouldbeexecutedtohandle the request. @Path("products") public class ProductService{ @GET @Path("getProduct") @Produces(MediaType.APPLICATION_JSON) // indicates the java method will produces content/response in JSON format public ProductsearchProduct(){ //logic } }
  • 165. 160 |P a ge WebServices  @GET, @PUT, @POST, @DELETE and @HEAD are resource method designator annotations defined by JAX-RS and which correspond to the similarly named HTTP methods. In the example above, the annotated Java method will process HTTP GET requests. Http Annotations • @javax.ws.rs.GET • @javax.ws.rs.POST • @javax.ws.rs.PUT • @javax.ws.rs.DELETE Resource method: • AmethodinaresourceclassthatisannotatedwithRequestMethodDesignatoriscalledasResource method. • A lot of information we want pull from an HTTP request and injecting it into a Java method. • You might be interested in a URI query string value. • TheclientmightbesendingcriticalHTTPheadersorcookievaluesthatyourserviceneedstoprocess the request. • JAX-RSletsyougrabthisinformationasyouneedit,throughasetofinjectionannotationsandAPIs. JAX-RS API Annotations • @javax.ws.rs.Path • @javax.ws.rs.Consumes • @javax.ws.rs.Produces • @javax.ws.rs.QueryParam • @javax.ws.rs.PathParam • @javax.ws.rs.HeaderParam • @javax.ws.rs.FormParam • @javax.ws.rs.CookieParam • @javax.ws.rs.MatrixParam • @javax.ws.rs.BeanParam
  • 166. 161 |P a ge WebServices JAX-RS Annotations Overview @QueryParam: It is used for receiving the data as input through query String parameters as shown below. The client is the following URL to access the above Service URL:- http://<hostName>:<portNum>/context-root /products/searchProduct?pid=101
  • 167. 162 |P a ge WebServices TheaboveURLshowsthequeryparampid=101where101valuewillbepassedasaninputto parameter pid of the method. The QueryParameters are name-value paris. TheQueryParametersarestartswith?intheURLand ifmultipleQueryparametersarethere separated with &symbol Ex2: Resource method with Multiple Query-Parameters URL:http://<hostName>:<portNum>/context-root/products/searchProduct?pid=101&pname=mouse Jersy 1.x Application Step-1: - Create Maven Web application
  • 168. 163 |P a ge WebServices Step-2:-AddJerseyMavenDependenciesinpom.xmlfile Step-3:-Createadomainclass(ThisisBindingclass)
  • 169. 164 |P a ge WebServices Step-5: - Create Resource class Step-6: - Configure Jersey Runtime Servlet in web.xml file like below Step-7: - Deploy the application and test Rest resource using POSTMAN tool
  • 170. 165 |P a ge WebServices @Matrix Param: Theideaofmatrixparametersisthattheyarean arbitrarysetof name-valuepairsembeddedinauri path segment. The Matrix Parameters are starts with semicolon and if multiple parameters are there then separated with semicolon. The Matrix Parameters are Name-Value Pairs. Url to access car resource : http://localhost:6060/FirstRestEasyWeb/rest/car/order/benz;color=red/2001
  • 171. 166 |P a ge Web Services @FormParam • @FormParam to bind html form fields to your method inputs. • It works for http method POST. When register.html form got submitted, request comes to UserRegResource class registerUserInfo () method. As part of this method we are capturing form data using @FormParam annotaion @BeanParam • The @BeanParam annotation issomething newadded in the JAX-RS 2.0 specification. • It allows you to inject an application-specific class whose property methods orfields are annotated with any of the injection parameters Ifwedon’thave@BeanFormWeneedtowritemany@FormParamannotationstocaptureaform data. If form contains 20 fields then we have to 20 parameters for the method which is not recommended. Below image depicts the same.
  • 172. 167 |P a ge Web Services To avoid the above problem, we can create a model class to store form data We can use @BeanParam to inject form data into model/bean object like below JAX-RS provider automatically constructs and injects an instance of your domain object which you can now use within your methods.
  • 173. 168 |P a ge Web Services Jersey Application with JSON Data Step-1  Create Maven Web Application Step-2  Add below maven dependencies in project pom.xml
  • 174. 169 |P a ge WebServices Step-3  Create a domain class to hold the data Step-4CreateResourceclasswithresourcemethods The above Resource having a get request method and post request method POST request methodisusedtoadd the customer usingcustomerdatainJSON format GET request method is used to retrieve Customer data in JSON format
  • 175. 170 |P a ge WebServices Step-5 Create web.xml file with below details • In the above web.xml file we can see two init parameters • Jersey.config.server.provider.packages is used to load all resource classes before getting request (This will improve performance of the application). If we don’t write this everytime resource class should be loaded from classpath. • POJOMappingFeature init param is used to map json data to pojo and vice versa. Step-6  Deploy the application and test it using POSTMAN To test the above Resource we can use SOAPUITool/PostMan/RestClient tool (OR) write a client application.
  • 176. 171 |P a ge WebServices @Consumes The @Consumes annotation is used to specify which MIME media types of representations a resource can accept, or consume, from the client. If @Consumes is applied at the class level, all the response methods accept the specified MIME types by default. If @Consumes is applied at themethodlevel,it overrides any@Consumesannotationsapplied at theclasslevel.  IfaresourceisunabletoconsumetheMIMEtypeofaclientrequest,theJerseyruntimesends back an HTTP “415 Unsupported Media Type” error. The value of @Consumes is an array of Stringof acceptable MIME types. For example: @Consumes ({"text/plain, text/html"}) ThefollowingExampleisshowinghowtoconsumethedatainXMLbyusing@Consumesannotation. web.xml ProductService.java
  • 177. 172 |P a ge WebServices We can test above service by using the following client application As follows package com.nit.client; import java.io.StringWriter; import javax.ws.rs.core.MediaType; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException; import javax.xml.bind.Marshaller; import com.nit.domain.Product; import com.sun.jersey.api.client.Client; import com.sun.jersey.api.client.ClientResponse; import com.sun.jersey.api.client.WebResource; import com.sun.jersey.api.client.WebResource.Builder; public class Test { public static void main(String [] args) throws JAXBException { String URL = "http://hostName:portNum/contextpath/products/registerProduct"; Client client = Client.create(); WebResource webResource = client.resource(URL); Builder builder = webResource.type(MediaType.APPLICATION_XML); builder.accept(MediaType.TEXT_PLAIN); Productproduct=newProduct(); product.setPid(201); product.setPname("mouse"); product.setPrice(900.0); JAXBContext jaxbContext = JAXBContext.newInstance(Product.class); Marshaller marshaller = jaxbContext.createMarshaller(); StringWriter writer = newStringWriter(); marshaller.marshal(product, writer); String productXML = writer.toString(); ClientResponse clientResponse = builder.post(ClientResponse.class,productXML); String response = clientResponse.getEntity(String.class); s.o.p (clientResponse.getStatus()+""+ clientResponse.getStatusInfo()); S.o.p (response); } }
  • 178. 173 |P a ge WebServices Product.java package com.nit.domain; Import java.io.Serializable; Import javax.xml.bind.annotation.XmlAttribute; Import javax.xml.bind.annotation.XmlElement; Import javax.xml.bind.annotation.XmlRootElement; @XmlRootElement(name="product") public class Product implements Serializable{ private int pid; private String pname; private double price; @XmlAttribute(name="pid") public int getPid() { return pid; } public void setPid(int pid) { this.pid = pid; } @XmlElement public String getPname() { return pname; } public void setPname(String pname) { this.pname = pname; } @XmlElement public double getPrice() { return price; } Public void setPrice(double price) { this.price = price; } }
  • 179. 174 |P a ge Web Services Jersey 2.x Example
  • 180. 175 |P a ge Web Services
  • 181. 176 |P a ge Web Services
  • 182. Web Services 177|P a pom.xml <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven- v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.jerseyserverexample</groupId> <artifactId>Jersey_Book_Service_Provider</artifactId> <packaging>war</packaging> <version>1.0</version> <name>Jersey_Book_Service_Provider MavenWebapp</name> <url>http://maven.apache.org</url> <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>3.8.1</version> <scope>test</scope> </dependency> <dependency> <groupId>org.glassfish.jersey.containers</groupId> <artifactId>jersey-container-servlet</artifactId> <version>2.22.2</version> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>3.0.1</version> </dependency> <!-- https://mvnrepository.com/artifact/com.hynnet/oracle-driver-ojdbc6 --> <dependency> <groupId>com.hynnet</groupId> <artifactId>oracle-driver-ojdbc6</artifactId> <version>12.1.0.1</version> </dependency> <dependency> <groupId>org.glassfish.jersey.media</groupId> <artifactId>jersey-media-json-jackson</artifactId> <version>2.22.2</version> </dependency> <dependency> <groupId>com.jerseyutil</groupId> <artifactId>Jersey_Book_Service_Util</artifactId> <version>0.0.1-SNAPSHOT</version> </dependency> </dependencies> <build> <finalName>Jersey_Book_Service_Provider</finalName> </build> </project> ge
  • 185. Web Services 180 |P a ge pom.xml <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.jerseyclientexample</groupId> <artifactId>Jersey_Book_Service_Client</artifactId> <packaging>war</packaging> <version>0.0.1-SNAPSHOT</version> <name>Jersey_Book_Service_Client MavenWebapp</name> <url>http://maven.apache.org</url> <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>3.8.1</version> <scope>test</scope> </dependency> <dependency> <groupId>org.glassfish.jersey.core</groupId> <artifactId>jersey-client</artifactId> <version>2.22.2</version> </dependency> <dependency> <groupId>org.glassfish.jersey.media</groupId> <artifactId>jersey-media-json-jackson</artifactId> <version>2.22.2</version>
  • 186. Web Services 181 |P a ge </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>3.0.1</version> </dependency> <dependency> <groupId>com.jerseyutil</groupId> <artifactId>Jersey_Book_Service_Util</artifactId> <version>0.0.1-SNAPSHOT</version> </dependency> </dependencies> <build> <finalName>Jersey_Book_Service_Client</finalName> </build> </project>
  • 187. Web Services 182 |P a ge Theclientobjis heavyweightobject.Itisalwaysrecomndedtoclosetheclientobjectafterconsuming the resource. The client obj Establish the connection b.w client app to server app. If we are using Jersey 1.x we can use the following code in the place of above code
  • 188. Web Services 183 |P a ge jersey 1.x version client code @FormParam : InJAX-RS,youcanuse@FormParamannotationtobindHTMLformparametersvaluetoaJavamethod. The following example show you how to do it: Note:@FormParamisusedtobindhtmlformfieldstoyourmethodinputs.Itworksonlyforhttp method POST. First create a HTML page with Form Parameters a simple HTML form with “post” method. UserForm.html public class BookServiceClient{ public ResponseDTO saveBookDetails(Book book){ StringURL="http://localhost:8082/Jersey_Book_Service_Provider/books/registerBook"; Client client = Client.create(); WebResource resource=client.resource(URL); Builder builder =resource.accept(MediaType.APPLICATION_JSON); builder.type(MediaType.APPLICATION_JSON); ClientResponse clientResponse=builder.post(ClientResponse.class,JsonUtil.convertJavaToJson(book)); String jsonResponse=clientResponse.getEntity(String.class); ResponseDTO responseDTO=JsonUtil.convertJsonToJava(jsonResponse,ResponseDTO.class); return responseDTO; } } <html> <body> <h1>JAX-RS @FormQuery Testing</h1> <form action="user/register" method="post"> Name : <input type="text" name="name" /> Age : <input type="text" name="age" /> <input type="submit" value="Add User" /> </form> </body> </html>
  • 189. 184 |P a ge WebServices Create A Resource class to get Form Parameters Note: Access HTML Page. URL: http://localhost:8080/RESTfulExample/UserForm.html Then click on Add User Button get the Output. Example to use @FormParam and to get above HTML form parameter values. import javax.ws.rs.FormParam; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.core.Response; @Path("user") public class UserService { @POST @Path("/register") @Produces(“text/plian”) publicStringaddUser(@FormParam("name")Stringname, @FormParam("age") int age) { return “addUser is called, name : " + name + ", age : " + age); } }
  • 190. 185 |P a ge WebServices Restful Resource Development without XML configuration Step-1  Create Maven web project Note: In the above application no web.xml file (delete web.xml file from WEB-INF folder) Step-2 Configure jersey dependencies in project pom.xml file Note : As we have deleted web.xml file we are writing <failOnMissingWebXml> propert to false so that it will not check for web.xml file
  • 191. 186 |P a ge WebServices Step-3  Create Application Configuration class (Extends from Application class) Step-4  Create a Resource class Step-5  Deploy the application and test it using POSTMAN tool
  • 192. 187 |P a ge Web Services RestEasy Implementation: REST Easy is a JBoss project that provides various frameworks to help you build RESTful Web Services and RESTful Java applications. It isa fully certified and portable implementation of the JAX-RS2.0specification, aJCP specificationthatprovidesaJava APIforRESTfulWeb Services over the HTTP protocol. The REST Easy can run in any Servlet container  We can download the Rest Easy jar’s from http://resteasy.jboss.org/downloads
  • 193. 188 |P a ge Web Services HelloResource.java package com.nit.service; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; @Path("hello") public class HelloResource { @Path("/sayHello/{name}") @Produces(MediaType.TEXT_PLAIN) @GET public String sayHello(@PathParam("name") String name){ return "Hello"+name+"Welcome to RestEasy"; } }
  • 194. 189 |P a ge Web Services MyApplication.java We can access the above webservice by using a client Application (OR) SOAP UI tool
  • 195. 190 |P a ge WebServices RestEasy Client Application Test.java
  • 196. 191 |P a ge WebServices RestEasy-Bootstrapping Application Step-1  Create Maven Web application Step-2  Configure resteasy dependencies in project pom.xml file like below Step-3  Create Application Configuration class like below
  • 197. 192 |P a ge WebServices Step-4  Create Resource class like below Step-5  Create web.xml file like below Below is the Client class to rest the above Rest Resource
  • 198. 193 |P a ge WebServices File Uploading with Restful Resource Below is the Resource class to upload the file
  • 199. 194 |P a ge WebServices Postman screen shot to upload file (We can test the above FileUploadResource using postman) To upload file from user interface we can use below html form
  • 200. 195 |P a ge WebServices Spring+RestFul services (Jersey Implementation) Integration Example <projectxmlns="http://maven.apache.org/POM/4.0.0"xmlns:xsi="http://www.w3.org/2001/X MLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven- v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.springjerseyexample</groupId> <artifactId>SpringJerseyRestFullExample</artifactId> <packaging>war</packaging> <version>0.0.1-SNAPSHOT</version> <name>SpringJerseyRestFullExample MavenWebapp</name> <url>http://maven.apache.org</url>
  • 201. 196 |P a ge WebServices Mr. As<dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>3.8.1</version> <scope>test</scope> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>3.0.5.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>3.0.5.RELEASE</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.35</version> </dependency> <!-- https://mvnrepository.com/artifact/com.sun.jersey/jersey-server --> <dependency> <groupId>com.sun.jersey</groupId> <artifactId>jersey-server</artifactId> <version>1.8</version> </dependency> <dependency> <groupId>org.codehaus.jackson</groupId> <artifactId>jackson-mapper-asl</artifactId> <version>1.9.13</version> </dependency> <dependency> hok <groupId>com.sun.jersey.contribs</groupId> <artifactId>jersey-spring</artifactId> <version>1.8</version> <exclusions> <exclusion> <groupId>org.springframework</groupId> <artifactId>spring</artifactId> </exclusion> <exclusion> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> </exclusion> <exclusion> <groupId>org.springframework</groupId>
  • 202. 197 |P a ge Web Services Book.java package com.jerseyexample.domain; import java.io.Serializable; public class Book implements Serializable{ private Integer isbn; private String title,author,publication; private Double price; public Integer getIsbn() { returnisbn; } public void setIsbn(Integer isbn) { this.isbn = isbn; } public String getTitle() { returntitle; } public void setTitle(String title) { this.title = title; } public String getAuthor() { return author; } public void setAuthor(String author) { <artifactId>spring-web</artifactId> </exclusion> <exclusion> <groupId>org.springframework</groupId> <artifactId>spring-aop</artifactId> </exclusion> <exclusion> <groupId>org.springframework</groupId> <artifactId>spring-beans</artifactId> </exclusion> <exclusion> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> </exclusion> </exclusions> </dependency> </dependencies> <build> <finalName>SpringJerseyRestFullExample</finalName> </build> </project>
  • 203. 198 |P a ge Web Services ResponseDTO.java package com.jerseyexample.domain; import java.io.Serializable; public class ResponseDTO implements Serializable{ private byte status; private String msg; private String data; public byte getStatus() { return status; } public void setStatus(byte status) { this.status = status; } public String getMsg() { return msg; } public void setMsg(String msg) { this.msg = msg; } public String getData() { return data; } public void setData(String data) { this.data = data; } } this.author = author; } public String getPublication() { return publication; } public void setPublication(String publication) { this.publication = publication; } public Double getPrice() { return price; } public void setPrice(Double price) { this.price = price; } }
  • 204. 199 |P a ge WebServices BookDAO.java BookDAOImpl.java package com.jerseyexample.dao; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.SQLException; import javax.sql.DataSource; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Repository; import com.jerseyexample.domain.Book; @Repository public class BookDAOImpl implements BookDAO{ @Autowired private DataSource dataSource; public int registerBook(Book book) { int count=0; Connection con=null; try{ con=dataSource.getConnection(); String sql="insert into Book_Details values(?,?,?,?,?)"; PreparedStatement pst=con.prepareStatement(sql); pst.setInt(1,book.getIsbn()); pst.setString(2,book.getTitle()); pst.setDouble(3,book.getPrice()); pst.setString(4,book.getAuthor()); pst.setString(5,book.getPublication()); count=pst.executeUpdate(); }catch(SQLException se){ se.printStackTrace(); }finally{ if(con!=null){ try{ con.close(); }catch(SQLException se){ se.printStackTrace(); } } } return count; } } package com.jerseyexample.dao; import com.jerseyexample.domain.Book; public interface BookDAO { public int registerBook(Book book); }
  • 205. 200 |P a ge WebServices BookService.java package com.jerseyexample.service; import javax.ws.rs.Consumes; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.jerseyexample.dao.BookDAO; import com.jerseyexample.domain.Book; import com.jerseyexample.domain.ResponseDTO; import com.jerseyexample.util.JsonUtil; @Path("books") @Service publicclass BookService{ @Autowired private BookDAO bookDAO; @POST @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) @Path("/registerBook") public String registerBook(String jsonBook){ System.out.println("Entered into registerBook ::"+jsonBook); Book book=JsonUtil.convertJsonToJava(Book.class,jsonBook); String msg="Registration Is Failure!Please Try Again"; ResponseDTO responseDTO=new ResponseDTO(); responseDTO.setMsg(msg); int count=bookDAO.registerBook(book); if(count>0){ msg="Registration Is Success"; responseDTO.setMsg(msg); responseDTO.setStatus((byte)1); responseDTO.setData(book.getIsbn().toString()); } System.out.println("Response of registerBook ::"+responseDTO.getMsg()); String jsonResponseDTO=JsonUtil.convertJavaToJson(responseDTO); return jsonResponseDTO; } }
  • 206. 201 |P a ge WebServices JsonUtil.java package com.jerseyexample.util; import java.io.IOException; import org.codehaus.jackson.JsonGenerationException; import org.codehaus.jackson.JsonParseException; import org.codehaus.jackson.map.JsonMappingException; import org.codehaus.jackson.map.ObjectMapper; public class JsonUtil { publicstatic<T>TconvertJsonToJava(Class<T>cls,String json){ T response=null; ObjectMapper mapper=new ObjectMapper(); try { response=mapper.readValue(json,cls); }catch(JsonParseExceptione){ e.printStackTrace(); } catch (JsonMappingException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return response; } publicstaticStringconvertJavaToJson(Object obj){ String jsonStr=""; ObjectMapper mapper=new ObjectMapper(); try { jsonStr=mapper.writeValueAsString(obj); } catch (JsonGenerationException e) { e.printStackTrace(); } catch (JsonMappingException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return jsonStr; } }
  • 207. 202 |P a ge WebServices web.xml applicationContext.xml <web-app> <listener> <listener-class> org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <servlet> <servlet-name>jersey-serlvet</servlet-name> <servlet-class> com.sun.jersey.spi.spring.container.servlet.SpringServlet</servlet-class> <init-param> <param-name>com.sun.jersey.config.property.packages</param-name> <param-value>com.jerseyexample.service</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>jersey-serlvet</servlet-name> <url-pattern>/*</url-pattern> </servlet-mapping> </web-app> <beansxmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd"> <beanid="dataSource"class="org.springframework.jdbc.datasource.DriverManagerD ataSource"> <propertyname="driverClassName"value="com.mysql.jdbc.Driver"/> <propertyname="url"value="jdbc:mysql://localhost:3306/nit"/> <propertyname="username"value="root"/> <propertyname="password"value="root"/> </bean> <context:component-scanbase- package="com.jerseyexample.service,com.jerseyexample.dao"/> </beans>
  • 208. 203 |P a ge WebServices The Following Client Application is used to Test Above Restful Service pom.xml <projectxmlns="http://maven.apache.org/POM/4.0.0"xmlns:xsi="http://www.w3.org/ 2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.restclient.client</groupId> <artifactId>JerseyClientExample</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>jar</packaging> <name> JerseyClientExample </name> <url>http://maven.apache.org</url> <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>3.8.1</version> <scope>test</scope> </dependency> <dependency> <groupId>com.sun.jersey</groupId> <artifactId>jersey-client</artifactId> <version>1.19.1</version> </dependency> <dependency> <groupId>org.codehaus.jackson</groupId> <artifactId>jackson-mapper-asl</artifactId> <version>1.9.13</version> </dependency> </dependencies> </project>
  • 209. 204 |P a ge WebServices Book.java package com.restclient.domain; import java.io.Serializable; public class Book implements Serializable { private Integer isbn; private String title,author,publication; private Double price; public Integer getIsbn() { return isbn; } public void setIsbn(Integer isbn) { this.isbn = isbn; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getAuthor() { return author; } public void setAuthor(String author) { this.author = author; } public String getPublication() { return publication; } public void setPublication(String publication) { this.publication = publication; } public Double getPrice() { return price; } public void setPrice(Double price) { this.price = price; } }
  • 210. 205 |P a ge WebServices Test.java package com.restclient.client; import java.io.IOException; import javax.ws.rs.core.MediaType; import org.codehaus.jackson.JsonGenerationException; import org.codehaus.jackson.map.JsonMappingException; import org.codehaus.jackson.map.ObjectMapper; import com.restclient.domain.Book; import com.sun.jersey.api.client.Client; import com.sun.jersey.api.client.ClientResponse; import com.sun.jersey.api.client.WebResource; import com.sun.jersey.api.client.WebResource.Builder; public class Test{ publicstaticvoidmain(String[]args)throwsJsonGenerationException, JsonMappingException, IOException{ String URL="http://localhost:8090/SpringJerseyRestFullExample/books/registerBook"; Book book=new Book(); book.setIsbn(302); book.setTitle("java"); book.setPrice(1900.0); book.setPublication("nit"); book.setAuthor("jhon"); ObjectMapper mapper=new ObjectMapper(); String jsonBook=mapper.writeValueAsString(book); System.out.println(jsonBook); Client client=Client.create(); WebResource resource=client.resource(URL); Builder builder=resource.accept(MediaType.APPLICATION_JSON); builder.type(MediaType.APPLICATION_JSON); ClientResponse clientResponse=builder.post(ClientResponse.class,jsonBook); System.out.println(clientResponse.getStatus()+" "+clientResponse.getStatusInfo()); System.out.println(clientResponse.getEntity(String.class)); } }
  • 211. 206 |P a ge WebServices Spring Rest-API Example: pom.xml <projectxmlns="http://maven.apache.org/POM/4.0.0"xmlns:xsi="http://www.w3.org/2001 /XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.springrestexample</groupId> <artifactId>SpringRestExample</artifactId> <packaging>war</packaging> <version>0.0.1-SNAPSHOT</version> <name>SpringRestExample MavenWebapp</name> <url>http://maven.apache.org</url> <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>3.8.1</version> <scope>test</scope> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>4.0.5.RELEASE</version> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId>
  • 212. 207 |P a ge WebServices User.java <version>3.0.1</version> </dependency> <dependency> <groupId>org.codehaus.jackson</groupId> <artifactId>jackson-mapper-asl</artifactId> <version>1.9.13</version> </dependency> </dependencies> <build> <finalName>SpringRestExample</finalName> </build> </project> package com.springrestexample.domain; publicclass User { privateintuserId; private String userName; private String email,mobile; publicint getUserId() { returnuserId; } publicvoid setUserId(intuserId) { this.userId = userId; } public String getUserName() { returnuserName; } publicvoid setUserName(String userName) { this.userName = userName; } public String getEmail() { returnemail; } publicvoid setEmail(String email){ this.email = email; } publicStringgetMobile(){ returnmobile; } publicvoid setMobile(String mobile){ this.mobile = mobile; } }
  • 213. 208 |P a ge WebServices UserService.java UserServiceImpl.java package com.springrestexample.service; publicinterface UserService { public String getUserDetails(Integer userId); } package com.springrestexample.service; import org.springframework.stereotype.Service; import com.springrestexample.domain.User; import com.springrestexample.util.JsonUtil; @Service publicclass UserServiceImpl implements UserService{ public String getUserDetails(Integer userId) { String jsonUser="{}"; if(userId!=null&&userId.equals(101)){ User user=new User(); user.setUserId(101); user.setUserName("rama"); user.setEmail("rama@gmail.com"); user.setMobile("999999"); jsonUser=JsonUtil.javaToJson(user); } returnjsonUser; } }
  • 214. 209 |P a ge WebServices JsonUtil.java package com.springrestexample.util; import java.io.IOException; import org.codehaus.jackson.JsonGenerationException; import org.codehaus.jackson.JsonParseException; import org.codehaus.jackson.map.JsonMappingException; import org.codehaus.jackson.map.ObjectMapper; publicclass JsonUtil { publicstatic String javaToJson(Object obj){ String jsonStr="{}"; ObjectMapper mapper=new ObjectMapper(); try { jsonStr=mapper.writeValueAsString(obj); } catch (JsonGenerationException e) { e.printStackTrace(); } catch (JsonMappingException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } returnjsonStr; } publicstatic<T>T jsonToJava(Class<T>cls,String str){ T response=null; ObjectMapper mapper=new ObjectMapper(); try { response=mapper.readValue(str,cls); }catch(JsonParseExceptione){ e.printStackTrace(); } catch (JsonMappingException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } returnresponse; } }
  • 215. 210 |P a ge WebServices UserController.java web.xml package com.springrestexample.controller; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import com.springrestexample.service.UserService; @RestController publicclass UserController { @Autowired private UserService userService; @RequestMapping(value="getUserInfo/{userId}",method=RequestMethod.GET) @ResponseBody public String getUserDetails(@PathVariable("userId") Integer userId){ String jsonUser=userService.getUserDetails(userId); returnjsonUser; } } <web-app> <servlet> <servlet-name>spring</servlet-name> <servlet-class> org.springframework.web.servlet.DispatcherServlet </servlet-class> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>spring</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> </web-app>
  • 216. 211 |P a ge WebServices spring-servlet.xml TheRestTemplateclassisgivenbyspringframeworktoaccesstheRestfulservicesintheeasymanner. Test.java <beansxmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd"> <context:component-scan base-package="com.springrestexample.controller,com.springrestexample.service"/> </beans> package com.springrestclientexample; import java.util.HashMap; import java.util.Map; import org.springframework.web.client.RestTemplate; publicclass Test{ publicstaticvoid main( String[] args ) { String url="http://localhost:8082/SpringRestServerEx/getUserInfo/{userId}"; RestTemplate restTemplate=new RestTemplate(); Map<String,Object>map=new HashMap<String, Object>(); map.put("userId",101); String jsonUser=restTemplate.getForObject(url,String.class,map); System.out.println(jsonUser); } }
  • 217. 212 |P a ge WebServices Response class: Response class is present in javax.ws.rs.core package. Defines the contract between a returned instance and the runtime when an application needs to provide metadata to the runtime. An application class can extend this class directly or can use one of the static methods to create an instance of this class . ThefollowingExampleisshowinghowtouseResponseclassasareturntypeto resource method The following Example is showing how to use XML format data with Response obj Student.java package com.nareshit.domain; import javax.xml.bind.annotation.XmlRootElement; @XmlRootElement publicclassStudent{ privateIntegersid; privateStringname; //settersandgetters } package com.nareshit.service; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.core.Response; @Path("hello") public class HelloWorldService { @GET @Path("/sayHello/{name}") public Response getMsg(@PathParam("name") String name) { String output = "Hello : " + name+” Welcome “; return Response.status(200).entity(output).build(); } } public class StudentService { @GET @Path("/getStudentDetails/{sid}") @Produces(MediaType.APPLICATION_XML) public Response getResult(@PathParam("sid) Integer sid){ Student std=new Student(); std.setName("sathish"); std.setSid(sid); return Response.status(200).entity(std).build(); } }
  • 218. 213 |P a ge WebServices Get HTTP header in JAX-RS WehavetwowaystogetHTTPrequestheaderinJAX-RS: 1. Injectdirectlywith @HeaderParam 2. Programatically via @Context 1. @HeaderParam Example In this example, it gets the browser “user-agent” from request header. 2) Pragmatically via For @HeaderParam annotation Alternatively, you can also use @Context to get “javax.ws.rs.core.HttpHeaders” directly,seeequivalentexample togetbrowser“user- agent“. Import javax.ws.rs.GET; import javax.ws.rs.HeaderParam; import javax.ws.rs.Path; import javax.ws.rs.core.Response; @Path("/users") public class UserService { @GET public Response getHeadersResult(@HeaderParam("user-agent") String userAgent){ System.out.println("getHeaderResult method is calling and userAgent is :"+userAgent); return Response.status(200).entity(userAgent).build(); } import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.core.Context; import javax.ws.rs.core.HttpHeaders; import avax.ws.rs.core.Response; @Path("/users") public class UserService { @GET @Path("/get") @Produces(“text/plain”) public String getHeaders(@Context HttpHeaders headers) { String userAgent = headers.getRequestHeader("user-agent").get(0); return "getHeaders is called, userAgent : " + userAgent; } } @Context Annnotation :
  • 219. 214 |P a g WebServices List all request headers You can also get list of available HTTP request headers via following code : In general, @Context can be used to obtain contextual Java types related to the request or response. (for example @Context HttpServletRequest request ). @CookieParam:  Cookie is a name-value pair.  In General Cookie is transferring from Server to client and client to server.  TheCookieobjectiscreatinginServerSystembutstoresinClientSystem. We can retrieve the entire cookie by injecting the Cookie with the @CookieParam annotation by providing the cookie name. Note : @Path("/users") public class UserService { @GET @Path("/getAll") @Produces(“text/plain”) public Response getAllHeaders(@Context HttpHeaders headers){ MultivaluedMap<String,String> map=headers.getRequestHeaders(); Set<String> keys=map.keySet(); for(String key:keys){ System.out.println("Header Name : "+key); List<String> headerValues=headers.getRequestHeader(key); for(String headerValue:headerValues){ System.out.println(headerValue); } } return Response.status(200).build(); } } @GET @Produces(“text/plain”) public String getCookie(@CookieParam("cookie-name") Cookie cookie){ System.out.println(cookie); return “OK”; } e
  • 220. 215 |P a ge WebServices We can also retrieve just the cookie value by injecting the value with the @CookieParam annotation. @GET @Produces(“text/plain”) public String getCookieValue(@CookieParam("name") String cookie){ System.out.println(cookie); return “OK”; } Extracting RequestParameters: Parameters of a resource method may be annotated with parameter-based annotations to get the values from a request obj. You can extract the following types of parameters for use in your resource class:  QueryParam  URI path(PathParam)  FormParam  Cookie Param  Header Param  MatrixParam Query parameters are retrieved from the request URI query parameters and are specified by using the javax.ws.rs.QueryParam annotation in the method parameter arguments. The following example, from the Employee application, demonstrates using of @QueryParam annotation to retrieve query parameters from the requested URL: package com.nareshit.service; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.QueryParam; import javax.ws.rs.core.Response; @Path("employee") public class EmployeeService { @GET @Path("/getEmployeeDetails") public Response getEmployee(@QueryParam("dept") String department,
  • 221. 216 |P a ge WebServices In the above example, if you use "/employee/getEmployeeDetails" URI pattern, and you will get "Query parameters are received. 'dept' value is: accounts and location value is: bangalore" as a response. Sometimes User-definedJavaprogramminglanguagetypesmaybeusedasqueryparameters(OR) primitiveTypesusedasaqueryparameters (OR) collectiontypesusedasaqueryparametersasper the requirements. @QueryParam("location") String location){ String resp = "Query parameters are received. 'dept' value is: " +department+" and location value is: "+location; returnResponse.status(200).entity(resp).build(); } } In the above example, if you use "/employee/getEmployeeDetails?location=hyderabad&dept=finance" URI pattern with query parameters, getEmployee() method will be invoked, and you will get "Query parameters as 'dept' value is: finance and location value is: hyderabad" as a response. To assign default values to method input variables if the query parameters are not available You can use @DefaultValue annotation to specify default value. package com.nareshit.service; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.QueryParam; import javax.ws.rs.core.Response; @Path("employee") public class EmployeeService { @GET @Path("/getEmployeeDetails") public Response getEmployee ( @DefaultValue("accounts") @QueryParam("dept") String department, @DefaultValue("bangalore")@QueryParam("location")Stringlocation){ String resp = "Query parameters are received. 'dept' value is: " +department+" and location value is: "+location; returnResponse.status(200).entity(resp).build(); } }
  • 222. 217 |P a ge WebServices package com.nareshit.service; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.QueryParam; import javax.ws.rs.core.Response; @Path("employee") public class EmployeeService { @GET @Path("/getEmployeeByDeptNo") @Produces(MediaType.TEXT_PLAIN) public String getEmployee(@QueryParam("deptNo") intdeptNo ){ return "Employee Name =raja ,Emp No = 101 , salary =2000 ,deptNo="+deptNo; } @GET @Path("/getEmployeeByDeptName/{deptName}") @Produces(MediaType.TEXT_PLAIN) public String getEmployee(@PathParam("deptName") Employee emp){ return "Employee Name =raja ,Emp No = 101 , salary =2000 ,deptName="+emp.getDeptName(); } @GET @Path("/deleteDepartments")
  • 223. 218 |P a ge WebServices The following code shows how to write Employee class for above example The constructor for Employee takes a single String parameter. Note :Both @QueryParam and @PathParam can be used only on the following Java types:  All primitive types except char  All wrapper classes of primitive types except Character  Any class with a constructor that accepts a single String argument  Anyclass with the staticmethod named valueOf(String) that accepts asingle String argument @Produces(MediaType.TEXT_PLAIN) public String deleteDepartments(@QueryParam("deptNo") List<Integer>deptNoList){ System.out.println(“List of Deprts:”+deptNoList); return "Departments deleted "; } } public class Employee{ private String deptName; public Employee(String deptName) { this.deptName=deptName; } public void setDeptName(String deptName){ this.deptName=deptName; } public String getDeptName(){ return deptName; } }
  • 224. 219 |P a ge WebServices  List<T>,Set<T>,orSortedSet<T>,whereTmatchesthealreadylistedcriteria.Sometimes,parameters maycontainmorethanonevalueforthesamename.Ifthisisthecase,thesetypesmaybeused to obtain allvalues Note : If @DefaultValue is not used in conjunction with @QueryParam, and the query parameter is not present in therequest,thevaluewillbeanemptycollectionforList,Set,orSortedSet;nullforotherobjecttypes; and the default for primitive types. BeanParameters(By using @BeanParam annotation) (JAX-RS 2.0)): Exception-Handling:  Whenwe senda request to the resource,the resource sometimes maythrows Exceptions.  If resource throws Exception , JAXRS runtime will convert that exception into an response message with status code as error response code.  Butifwewanttoreturnacustomerrorresponseratherthanadefaulterror responsemessage we need to handle exceptions and should return as a response shown below. package com.nareshit.bean; public class EmployeeBean{ @QueryParam("salary") private double salary; @QueryParam("deptName") private String deptName; @QueryParam("location") private String location; //setters and getters } package com.nareshit.service; @Path("/employee") public class EmployeeService{ @GET @Produces(MediaType.TEXT_PLAIN) @Path("/searchEmployees") public String searchEmployees(@BeanParam EmployeeBean employeeBean){ return "empNo =101 ,empName=rama,salary="+employeeBean.getSalary(); } }
  • 225. 220 |P a ge WebServices UserNotFoundException.java UserService.java This above method may throws an appropriate exception when a user cannot be found. However, we still need to create a Handler object to convert this exception into an actual JSON response so we get a nice friendly error message. The class below handles this exception and will convert the error message in the exception into a JSON response.The important annotation you’ll see on this class i,e @Provider annotation. public class UserNotFoundException extends Exception { public UserNotFoundException() { super(); } public UserNotFoundException (String msg) { super(msg); } public UserNotFoundException (String msg, Exception e) { super(msg, e); } } @Path("users") public class UserService { @GET @Path("/getUser/{userId}") @Produces(MediaType.APPLICATION_JSON) public Response getUser(@PathParam("userId") String userId) throws UserNotFoundException { if(userId.equals("101")){ User user=new User(); user.setUserId(userId); user.setName("sathish"); user.setEmail("sathish@gmail.com"); user.setMobile("8888889988"); return Response.status(200).entity(user).type(MediaType.APPLICATION_JSON).build(); } else{ throw new UserNotFoundException ("User does not exist with id " + userId); } } }
  • 226. 221 |P a ge WebServices UserNotFoundExceptionHandler : Caching: When we opening of awebpage forthefirst time takes some time, but the second or third time it loads faster. This happens because whenever we visit a webpage for the first time, our browser caches the content and need not have to make a call over the network to render it. Thiscachingabilityofthebrowsersavesalotofnetworkbandwidthandhelpsincuttingdownthe server load. 1.)BrowserorlocalCaches:Thisisthelocalin-memorycacheofabrowser.Thisisthefastestcache available. Whenever we hit a webpage a local copy is stored in browser and then second time it uses this local copy instead of making a real request over the network. 2.)ProxyCaches:Thesearepseudowebserversthatworkasmiddlemenbetweenbrowsersand websites. These servers cache the static content and serve its clients so the client does not have to go to server for these resources. Content Delivery Networks (CDN) are of similar concept where in they provide proxy caches from their servers , which helps in faster serving the content and sharing the load of servers. Inconsistencyandinvalidation:Whenwearedealingwithcacheweneedtomakesurethatthe stale data is invalidated and it should be consistent. So let’s see what all mechanisms are provided by HTTP which can help us make effective use of HTTP caching. HTTP Headers BeforeHTTP1.1theonlywaytocontrolcachingbehaviorwaswiththehelpof“expries”header.Inthis an expiry date can be specified. But, later more powerful and extensive headers were introduced in HTTP 1.1, this was “cache-control” header.Thisalongwith “retag”gave the realpowerto theapplications tocontrolthebehavior of caches.
  • 227. 222 |P a ge WebServices JAX-RSsupportstheseandprovidesAPIstousethem.Wewillexplorehowwecanleveragecaching using HTTP response headers and the support provided by JAX-RS. Expires Header: In HTTP 1.0, a simple response header called Expires would tellthe browser howlongit can cache an object or page. It would be a date in future after which the cache would not be valid. So, if we made an API call to retrieve data :  This means the XML data is valid until 20th Dec 2016, 16:00 hours GMT.  JAX-RS supports this header in javax.ws.rs.core.Response object. GET /users/1 Theresponseheaderwouldbe: HTTP/1.1 200 OK Content-Type: application/xml Expires: Tue,20 Dec2016 16:00 GMT ----- <user id="1">...</users>
  • 228. 223 |P a ge WebServices But to support CDNs, proxy caches there was a need for more enhanced headers with richer set of features, having more explicit controls. Hence in HTTP 1.1 few new headers were introduced and Expires was deprecated. Let’s explore them. With Cache-Control : Cache-Control has a variable set of comma-delimited directives that define who, how and for how long it can be cached. Let’s explore few of them: –private/public : these are accessibility directives, private means a browser can cache the object but the proxies or CDNs cannot and public makes it cacheable by all. -no-cache, no-store,max-age are few others where name tells the story. package com.cacheexample.service; @Path(“user”) publicclassUserService{ @Path("getUser/{uid}") @GET @Produces(MediaType.APPLICATION_XML) public Response getUserXML(@PathParam("uid") Long uid){ User user=null; if(uid.equals(101)){ user=new User(); user.setUserId(uid); user.setUserName(“Ashok”); user.setEmail(“ashok@gmail.com”); } ResponseBuilderbuilder=Response.ok(user,MediaType.APPLICATION_XML); //Puttingexpires header for HTTP browser caching. Calendar cal = Calendar.getInstance(); cal.set(2016,12,25,16,0); builder.expires(cal.getTime()); return builder.build(); } Note : ResponseBuilder object build the Response object
  • 229. 224 |P a ge WebServices JAX-RS provides javax.ws.rs.core.CacheControl class to represent this header. RESTful Web Service Security Security Areas: There are two main areas for securities. Authentication: Process of checking the user, who they claim to be. Authorization: Process of deciding whether a user is allowed to perform an activity within the application. Different Authentications :  BASIC Authentication  It’ssimplestofalltechniquesandprobablymostusedaswell.Youuselogin/password forms – it’s basic authentication only. You input your username and password and submit theformto server, andapplicationidentifyyouasa user–youareallowedtousethe system – else you get error. package com.cacheexample.service; @Path(“user”) publicclassUserService{ @Path("getUser/{uid}") @GET @Produces(MediaType.APPLICATION_XML) public Response getUserXMLwithCacheControl(@PathParam("uid") Long uid){ User user=null; if(uid.equals(101)){ user=new User(); user.setUserId(uid); user.setUserName(“Ashok”); user.setEmail(“ashok@gmail.com”); } CacheControl cc = new CacheControl(); cc.setMaxAge(300);// set the max-age cache control directive. cc.setPrivate(true); ResponseBuilder builder = Response.ok(user,MediaType.APPLICATION_XML); builder.cacheControl(cc); return builder.build(); }
  • 230. 225 |P a ge WebServices  The main problem with this security implementation is that credentials are propagated in aplainwayfromtheclienttotheserver.CredentialsaremerelyencodedwithBase64in transit,butnotencryptedorhashedinanyway.Thisway,anysniffercouldreadthesent packages over thenetwork. DIGEST Authentication This authentication method makes use of a hashing algorithms to encrypt the password (called password hash) entered bythe user before sendingit to the server. This, obviously, makes it much safer than the basic authentication method, in which the user’s password travels in plain text that can be easily read by whoever intercepts it. CLIENT CERT Authentication  This is a mechanism in which a trust agreement is established between the server and the client through certificates. They must be signed by an agency established to ensure that the certificate presented for authentication is legitimate, which is known as CA.  Usingthistechnique,whentheclientattemptstoaccessaprotectedresource,insteadof providingausernameorpassword,itpresentsthecertificatetotheserver.Thecertificate containstheuserinformationforauthenticationincludingsecuritycredentials,besidesa unique private-public key pair. The server then determines if the user is legitimate through the CA. Additionally, it must verify whether the user has access to the resource. This mechanism must use HTTPS as the communication protocol as we don’t have a secure channel to prevent anyone from stealing the client’s identity. Ways to Secure RestFullWeb Services: You can secure your Restful Web services using one of the following methods to support authentication, authorization, orencryption: 1) Using web.xml deployment descriptor to define security configuration. 2) Using the javax.ws.rs.core.SecurityContext interface to implement security programmatically. 3) By Applying annotations to your JAX-RS classes. Securing RESTful Web Services Using web.xml  YousecureRESTfulWebservicesusingtheweb.xmldeploymentdescriptorasyouwouldfor other Java EE Web applications.
  • 231. 22 WebServices  Forexample,tosecureyourRESTfulWebserviceusingbasicauthentication,performthe following steps: 1. Definea<security-constraint>foreachsetofRESTfulresources(URIs)thatyouplantoprotect. 2. Use the <login-config> element to define the type of authentication you want to use and the security realm to which the security constraints will be applied. 3. Define one or more security roles using the <security-role> tag and map them to the security constraints defined in step 1. 4. Toenableencryption,addthe<user-data-constraint>elementandsetthe<transport- guarantee> subelement to CONFIDENTIAL Example 1 Securing RESTful Web Services Using Basic Authentication Step1 : create Root Resource class as for your requirement : Step2:- Configure The Security Configuration in web.xml file as follows <web-app> <servlet> <servlet-name>RestServlet</servlet-name> <servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class> </servlet> <servlet-mapping> <servlet-name>RestServlet</servlet-name> <url-pattern>/*</url-pattern> </servlet-mapping> <security-constraint> <web-resource-collection> <web-resource-name>Products</web-resource-name> <url-pattern>/*</url-pattern> <http-method>GET</http-method> <http-method>POST</http-method> </web-resource-collection> <auth-constraint> <role-name>ADMIN</role-name> 6 |P a ge package com.nareshit.service; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.QueryParam; import javax.ws.rs.core.MediaType; @Path("products") public class ProductService { @GET @Path("/getProductName") @Produces(MediaType.TEXT_PLAIN) public String getProductName( @QueryParam("pid") Integer pid){ if(pid!=null && pid.equals(301)){ return "keyboard"; } return "Product not found"; } }
  • 232. 227 |P a ge web.xml WebServices Step3:- Set username and password and Role’s in Tomcat Server Changes in Tomcat Server ( tomcat-users.xml) As stated above we are using Tomcat 7. Now for the user to be authenticated we will specify the role ‘ADMIN’(whichistherolechoseninour above)andsomeusername andpasswordinour container. Thisusername and password will have to be supplied to access therestricted resource. Step4:- Deploy the Project into the server Note : Test the above Service By using Any RestClient tool. While sending the request set username and password as follows. FirstClickon Authentication intheclient toolBasicAuthentication <tomcat-users> <role rolename="manager-gui"/> <role rolename="admin-gui"/> <role rolename="admin"/> <role rolename="customer"/> <user username="customer" password="customer" roles="customer"/> <user username="admin" password="admin" roles="admin"/> <user username="admin" password="admin" roles="admin-gui,manager-gui"/> </tomcat-users> tomcat-users.xml
  • 233. 228 |P a ge WebServices Enter UserName and password Enter the URL and send
  • 234. 229 |P a ge WebServices Output : 2) Securing RESTful Web Services Using SecurityContext The javax.ws.rs.core.SecurityContext interface provides access to security-related information for a request. The SecurityContext provides functionality similar to javax.servlet.http.HttpServletRequest, enabling you to access the following security-related information: java.security.Principal object containing the name of the user making the request. Authentication type used to secure the resource, such as BASIC_AUTH, FORM_AUTH, and CLIENT_CERT_AUTH. Whether the authenticated user is included in a particular role. Whether the request was made using a secure channel, such as HTTPS. YouaccesstheSecurityContextbyinjectinganinstanceintoaclassfield,settermethod,ormethod parameter using the javax.ws.rs.core.Context annotation. The following shows how to inject an instance of SecurityContext into the sc method parameter using the @Context annotation, and check whether the authorized user is included in the admin role before returning the response. Example 2 Securing RESTful Web Service Using SecurityContext package com.nareshit.service; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.QueryParam; import javax.ws.rs.core.Context; import javax.ws.rs.core.MediaType;
  • 235. WebServices import javax.ws.rs.core.SecurityContext; @Path("products") publicclassProductService{ @GET @Path("/getProductName") @Produces(MediaType.TEXT_PLAIN) public String getProductName( @QueryParam("pid") Integer pid, @Context SecurityContext sc) { if (sc.isUserInRole("admin")){ if(pid!=null && pid.equals(301)){ return "keyboard"; } else{ return "Product Not Found"; } } } } 3) Securing RESTful Web Services Using Annotations Thejavax.annotation.securitypackageprovidesannotations,definedinTable1,thatyoucanuseto secure your RESTful Web services. Table 1 Annotations for Securing RESTful Web Services Annotation Description DeclareRoles Declares roles. DenyAll Specifies that no security roles are allowed to invoke the specified methods. PermitAll Specifies that all security roles are allowed to invoke the specified methods. RolesAllowed Specifies the list of security roles that are allowed to invoke the methods in the application. RunAs Definestheidentityoftheapplicationduring execution in a J2EE container. 230 |P a ge
  • 236. 231 |P a ge WebServices In Thefollowing Example getProductName methodisannotated with the @RolesAllowed annotation to override the default and only allow users that belong to the ADMIN security role. Example 3 Securing RESTful Web Service Using Annotations(javax.annotation.security) Realm :  Arealmisarepositoryofuserinformation;itisanabstractionofthedatastore–textfile,JDBC database or a JNDI resource. This hasthe following information: username, password and the roles which are assigned to the users. Both of the authentication and authorization make up the security policy of a server. Tomcat usesrealmstoimplement container-managed securityandenforcespecific securitypolicies. Conculsion : RESTful Services: RESTstandsforRepresentationalStateTransfer.RESTwasatermcoinedbyRoyFieldinginhisdoctoral dissertation.Itisanarchitecturestyleforforcreatingnetworkbasedapplications. Keypropertiesof REST are client-server communication, stateless protocol, cacheable, layered implementation and uniform interface package com.nareshit.service; import javax.annotation.security.RolesAllowed; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.QueryParam; import javax.ws.rs.core.MediaType; @Path("products") @RolesAllowed({"admin","customer"}) public class ProductService { @GET @Path("/getProductName") @Produces(MediaType.TEXT_PLAIN) @RolesAllowed("admin") public String getProductName( @QueryParam("pid")Integerpid){ if(pid!=null && pid.equals(301)){ return "keyboard"; } else{ return "Product Not Found"; } } }
  • 237. 232 |P a ge WebServices As RESTful web services work with HTTP URLs Paths so it is very important to safeguard a RESTful web serviceinthesamemannerasawebsiteisbesecured.Followingarethebestpracticestobefollowed while designing a RESTful web service. Validation-Validateallinputsonthe server.ProtectyourserveragainstSQLorNoSQLinjection attacks. Session based authentication - Use session based authentication to authenticate a user whenever a request is made to a Web Service method. NosensitivedatainURL-Neveruseusername,passwordorsessiontokeninURL,thesevalues should be passed to Web Service via POST method. Restriction on Method execution - Allow restricted use of methods like GET, POST, DELETE. GET method should not be able to delete data. ValidateMalformedXML/JSON-Checkforwellformedinputpassedtoawebservicemethod. Throw generic Error Messages - A web service method should use HTTP error messages like 403 to show access forbidden etc. S.N. HTTP Code & Description 1 200 OK, shows success. 2 201 CREATED,whenaresourceissuccessfulcreatedusingPOSTorPUTrequest.Returnlinktonewly created resource using location header. 3 204 NO CONTENT, when response body is empty for example, a DELETE request. 4 304 NOT MODIFIED, used to reduce network bandwidth usage in case of conditional GET requests. Response body should be empty. Headers should have date, location etc. 5 400 BAD REQUEST, states that invalid input is provided e.g. validation error, missing data. 6 401 UNAUTHORIZED, states that user is using invalid or wrong authentication token. 7 403 FORBIDDEN,statesthatuserisnothavingaccesstomethodbeingusedforexample,deleteaccess without admin rights. 8 404 NOT FOUND, states that method is not available. 9 409 CONFLICT, states conflict situation while executing the method for example, adding duplicate entry. 10 500 INTERNAL SERVER ERROR, states that server has thrown some exception while executing the method.
  • 238. 233 |P a ge WebServices JAX-RS Annotations: Following are the commonly used annotations to map a resource as a web service resource. S.N. Annotation & Description 1 @Path Relative path of the resource class/method. 2 @GET HTTP Get request, used to fetch resource. 3 @PUT HTTP PUT request, used to create resource. 4 @POST HTTP POST request, used to create/update resource. 5 @DELETE HTTP DELETE request, used to delete resource. 6 @HEAD HTTP HEAD request, used to get status of method availability. 7 @Produces States the HTTP Response generated by web service, for example APPLICATION/XML, TEXT/HTML, APPLICATION/JSON etc. 8 @Consumes States the HTTP Request type, for example application/x-www-form-urlencoded to accept form data in HTTP body during POST request. 9 @PathParam Binds the parameter passed to method to a value in path. 10 @QueryParam Binds the parameter passed to method to a query parameter in path. 11 @MatrixParam Binds the parameter passed to method to a HTTP matrix parameter in path. 12 @HeaderParam Binds the parameter passed to method to a HTTP header. 13 @CookieParam Binds the parameter passed to method to a Cookie. 14 @FormParam Binds the parameter passed to method to a form value. 15 @DefaultValue Assigns a default value to a parameter passed to method.
  • 239. 234 |P a ge WebServices POSTMAN Introduction PostmanisaChromeadd-onandMacapplicationwhichisusedtofirerequeststoanAPI.Itisverylightweight and fast. Requests can be organized in groups, also tests can be created with verifications for certain conditions ontheresponse.Withitsfeatures,itisverygoodandconvenientAPItool.Itispossibletomakedifferentkindsof HTTPrequests–GET,POST,PUT,PATCHandDELETE.Itispossibletoaddheaderstotherequests. Installation Step-1  Open Google Chrome and type Postman  Click on below highlighted link
  • 240. 235 |P a ge WebServices Step-2  After clicking on “https://www.getpostman.com/apps” this URL below screen will be displayed Step-3  Based on your operating system click on “Download” button (below Screen will be displayed)
  • 241. 236 |P a ge WebServices Stpe-4  Install downloaded exe file (Below screen will be displayed) Step-5  It displays below screen (Create a free account)
  • 242. 237 |P a ge WebServices Step-6AfterAccountcreationLoginintoPostmanusinggivencredentials(belowscreenwillbedisplayed) Step-7->FromtheabovescreenclickonRequestandenterdetails(SelcetPostManEcho)andclickon“Save to Postman Echo”button
  • 243. 238 |P a ge WebServices Step-8  We can send http request to Rest API using request URL from below screen Inthisscreen wecanuserequesttypelikeGET, POST, PUT andDelete POSTMAN Screen shot for POST request
  • 244. 239 |P a ge WebServices Spring Integration with REST Introduction RESTfulwebservicesarebuilttoworkbestontheWeb.RepresentationalStateTransfer(REST)isanarchitectural stylethatspecifiesconstraints, suchastheuniforminterface,thatif appliedtoawebservice inducedesirable properties,suchasperformance,scalability,andmodifiabilitythatenableservicestoworkbestontheWeb.In the REST architectural style, data and functionality are considered resources and are accessed using Uniform ResourceIdentifiers(URIs),typicallylinksontheWeb.Theresourcesareacteduponbyusingasetofsimple,well- defined operations. The REST architectural style constrains an architecture to a client/server architecture and is designed to use a stateless communication protocol, typically HTTP. In the REST architecture style, clients and servers exchange representations ofresources byusing a standardized interface and protocol. The following principles encourage RESTful applications to be simple, lightweight, and fast: Resource identification through URI: A RESTful web service exposes a set of resources that identify the targets of the interaction with its clients. Resources are identified by URIs, which provide a global addressing space for resourceandservicediscovery.Seethe@PathAnnotationandURIPathTemplatesformoreinformation. Uniforminterface: Resources aremanipulated using afixedsetoffour create,read,update,delete operations: PUT,GET,POST,andDELETE.PUTcreatesanewresource,whichcanbethendeletedbyusingDELETE.GET retrievesthecurrentstateofaresourceinsomerepresentation.POSTtransfersanewstateontoaresource. See Responding to HTTP Methods and Requests for more information. Self-descriptivemessages:Resourcesaredecoupledfromtheirrepresentation sothattheircontentcanbe accessedinavarietyofformats,suchasHTML,XML,plaintext,PDF,JPEG,JSON,andothers.Metadataabout the resource is available and used, for example, to control caching, detect transmission errors, negotiate the appropriate representation format, and perform authentication or access control. See Responding to HTTP MethodsandRequestsandUsingEntityProviderstoMapHTTPResponseandRequestEntityBodiesformore information. Statefulinteractionsthroughhyperlinks:Everyinteractionwitharesourceisstateless;thatis,request messages are self-contained. Stateful interactions are based on the concept of explicit state transfer. Several techniquesexisttoexchangestate,suchasURIrewriting,cookies,andhiddenformfields.Statecanbe embedded in response messages to point to valid future states of the interaction. See Using Entity Providers to MapHTTPResponseandRequestEntityBodiesand“BuildingURIs”intheJAX-RSOverviewdocumentformore information. RESTful Web Services utilize the features of the HTTP Protocol to provide the API of the Web Service. It uses the HTTP Request Types to indicate the type of operation: GET:Retrieve/ Queryof existingrecords. POST: Creatingnew records. DELETE: Removing records. PUT: Updating existing records. Usingthese4HTTPRequestTypesaRESTfulAPImimicstheCRUDoperations(Create,Read,Update& Delete).RESTisstateless, eachcall theto aRESTful Web Serviceiscompletely stand-alone,ithasno knowledge of previousrequests.
  • 245. 240 |P a ge WebServices Below REST application performs CURD operations using Spring Service class Step 1: Create Maven Web Project
  • 246. 241 |P a ge WebServices Step 2: Configure maven dependencies in project pom.xml file Step 3: Create Domain class for Storing and Retrieving the data (User.java)
  • 247. 242 |P a ge WebServices Step 4: Create UserService.java class to perform Business operations Step 5: Create RestController (UserRestController.java) package com.app.controller; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.RestController; import com.app.domain.User; import com.app.service.UserService; @RestController public class UserRestController { @Autowired(required = true) private UserService service; @RequestMapping(value = "/add", method = RequestMethod.POST, consumes = { "application/xml", "application/json" }) public @ResponseBody String addUser(@RequestBody User user) { boolean isAdded = service.add(user); if (isAdded) { return "User Added successfully"; } else { } } return "Failed to Add the User..!";
  • 248. 243 |P a ge WebServices @RequestMapping(value = "/get", produces = { "application/xml", "application/json" }, method = RequestMethod.GET) @ResponseBody public User getUserById(@RequestParam(name = "uid") String uid) { System.out.println("Getting User with User Id : " + uid); User user = service.get(uid); return user; } @RequestMapping(value = "/update", method = RequestMethod.PUT, consumes = { "application/xml", "application/json" } ) public @ResponseBody String update(@RequestParam("uid") String uid, @RequestBody User user) { boolean isAdded = service.update(uid, user); if (isAdded) { return "User updated successfully"; } else { } } return "Failed to update the User..!"; @RequestMapping(value = "/delete", method = RequestMethod.DELETE) public @ResponseBody String delete(@RequestParam("uid") String uid) { boolean isAdded = service.delete(uid); if (isAdded) { return "User Deleted successfully"; } else { } } return "Failed to Delete the User..!"; public void setService(UserService service) { this.service = service; } } Step 6: Create AppConfig and AppInitiazer classes AppConfiguration.java
  • 249. 244 |P a ge WebServices AppInitializer.java Step 7: Deploy the Application into server (I have used Apache Tomcat 8.0) Step8:TesttheApplicationusingPOSTMANplugininGoogleChrome Testing AddUser URI: http://localhost:6060/SpringRestIntegrationApp/rest/add Method Type: POST Consumes: {application/xml, application/json} Produces: text/plain Request Body Data: In XML Format <? xml version="1.0" encoding="UTF-8"?> <user> <userid>101</userid> <username>Raju</username> <gender>Male</gender> <email>Raj@gmail.com</email> </user>
  • 250. 245 |P a ge WebServices POSTMAN Screenshot Testing Fetch User URI: http://localhost:6060/SpringRestIntegrationApp/rest/get?uid=101 Method Type: GET Input: Request Parameter (? uid=101) Produces: {application/xml, application/json} POSTMAN Screenshot Testing Update User URL: http://localhost:6060/SpringRestIntegrationApp/rest/update?uid=101 Method Type: PUT InputinURL:UserId(RequestParameter)?uid=101 Consumes: {application/xml, application/json}
  • 251. 246 |P a ge WebServices Produces: text/plain Request Body Data: in XML format <? xml version="1.0" encoding="UTF-8"?> <user> <userid>101</userid> <username>Ashok</username> <gender>Male</gender> <email>ashok.b@gmail.com</email> </user> POSTMAN Screenshot Testing Delete User URL: http://localhost:6060/SpringRestIntegrationApp/rest/delete?uid=101 Method Type: DELETE Input: Request Parameter (? uid=101) Produces: text/plain
  • 252. 247 |P a ge WebServices POSTMAN Screenshot === Happing Learning ====