Open navigation menu
Close suggestions
Search
Search
en
Change Language
Upload
Sign in
Sign in
Download free for days
93%
(27)
93% found this document useful (27 votes)
15K views
301 pages
Java Web Services Sriman PDF
Uploaded by
swarna
AI-enhanced title
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content,
claim it here
.
Available Formats
Download as PDF or read online on Scribd
Download
Save
Save Java-Web-Services-sriman.pdf For Later
93%
93% found this document useful, undefined
7%
, undefined
Embed
Share
Print
Report
93%
(27)
93% found this document useful (27 votes)
15K views
301 pages
Java Web Services Sriman PDF
Uploaded by
swarna
AI-enhanced title
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content,
claim it here
.
Available Formats
Download as PDF or read online on Scribd
Carousel Previous
Carousel Next
Download
Save
Save Java-Web-Services-sriman.pdf For Later
93%
93% found this document useful, undefined
7%
, undefined
Embed
Share
Print
Report
Download now
Download
You are on page 1
/ 301
Search
Fullscreen
Understanding Java _Web Services JAX-RPC, JAX-WS & JAX-RS Mr. Sriman As part of this we are going to cover Web Services and its related technologies like XML, XSD, DTD, JAX-P, JAX-B, JAX-RPC, JAX-WS, andl JAX-RS etc. Provides an in- depth understanding of each including the exampies.1 INTRODUCTION .. 11 _DistRpuTHD Praseanmne, scant . senses 8 4.4.1 Advantages of Distributed programming. . 10 1.2 JAVA ROLE Ed DiSTRIEUTED PROGRAMMING 40 1.2.1 CORBA... 10 1.2.2 RMF 1 1.2.3 EB ester 42 1.2.4 Web services. a 2 EVOLUTION, 2a 3 ARCHITECTURE .. 3.1 Meotu 3.2 PRorocor.. 3.3 LANGUAGE... 3.4 BINDING PROTOCOL. este 2.5 WSDL (Wes Service DescRirricn LANGUAGE) .. 3.6 UDDI (Univensat Desciarion ano DiscoveRy Inte@narton RESIST) 4 XML, 4.1 XML ELemenr. 4.2 XM Ariigute. 4.3 WELL-FoaNNESs, 44 XMLUSAGE.. 45° Vaupatty . 5 DTD sssssne 5.4 SyUTax Fon DECLARING SIMPLE ELEMENT OF AN XML. 5.2 Switax FoR Compcquno ELEMENT OF AN XML. 5.3 OCCURRENCES OF AN FLEHEAT UNDER ANOTHER ELEHENT 5.4 ELEMENTS Watl ANY CONTENTS 5.8 ELEMENTS wr ermcn/oR CONTEN: 5.6 DECLARING MixeD conTeNT 5.7 DECLARING ATTRIBUTE FOR AN ELEMENT. 5.7.1 Default Attribute Value. 5.7.2 PREQUIRED.. 5.7.3 STMPLIED 5.7.4 PFIXED, . 5.7.5 Enumeroted Atiribute Values... 58 6 XML SCHEMA DOCUMENT (xSD) 61 62 63 64 65 Java ABL'S For WS-1 51 Daaweac with DTDs, SEQUENCE VS ALL. cssscsee eserves Extewoins Comtex TveEs, IMPOSING RESTRICTIONS ON SIMPLETYPES .. DeceagiN ATTRIBUTES FOR COMPLEX ELEMEMIS DECLARING ATTRISUTES FOR SIMPLE ELEMENTS6.8 WosKtne wens Crore. 6.7 UsING REF 6.8 —ImpoRT VS Inciwoe,, 6.8.1 Import. ee os 7 XSD NAMESPACE TA XSDTARGETHAMESPACE ssssseneren 7.2 USING ELEMENTS FROME AN KHL NAMESPACE (XMLNS) 7.3 PPORTING MULTIPLE XSD'S In XML, 7.4 DisreRENce BETWEEN DTD aND XSD.... 8 AXP 8.1 XML PROcessins METHODOLOGIES. 8.1.1 SAX (Simple Access for XML). esse 8.1.2 DOM (Document Object Model). 8.1.3 Validating XML, with an XSD using JAX-Presscccuonno 8.1.4 Difference between SAX and DOM. 9 JAX-B 9.1 ARCHITECTURE . 9.2 ONE-TIME OPERATION wens 9.2.4 How to use XIC or Schemagen?. 9.2.2 What does XIC generates?. 9.3. Runtime Oreravion seve 9.3.1 UneMarstalling eereseesee 9.3.2 Marshalting 9.2.3 In-Memary Validation nesses 10 GETTING STARTED WITH WEB SERVICES.. 10,1. Tyres oF Wen SERVICES . 10.2 Wee SeeviCe DEVELOPMENT PARTS... 10.5 WAYS OF DEVELOPING A WES SERVICE saver 10.3.4 Contract First approach... 10.3.2 Contract Last approach. 10.4 Choosine av Enppomt 10.4.4 Serviet Endpoint... 10.4.2 EIB Endpoint . 10.5 MESSAGE EXCHANGE PATTERNS .., 10.5.1 Synchronous request/reply.. 10.5.2 Asynchronous request/reely or Delayed Response 10.5.3 One way Invoke or Fire and forget. 10.6 Message EXCHANGE FORMATS... 24 JAXRPC API (SI IMPLEMENTATION) LLL BurLome Prowines, sopnsneie 7 11.4.1 Contract Last (Servlet Endpoint, Sync reajreply with rpe-encoded) 79 11.1.2 Request Processing FIOW svvuenessieesiairnecnseseisnines 90 11.1.3 Contract Last ~ Activity Guide... 92 11.1.4 Contract First (Servet Endpoint, Sync req/reply with rpc-encoded) 99ALLS Contract First Activity Guide .., psouctinetstteees 108 11.2 Buona Covsune 107 AL.2.1 Stub based Clee corn . 07 | 11.2.2 Stub based client ~ Activity Guide we ELL 11.2.1 Dynamic Proxy 41.2.2 Dynamic Invocation Interface. 12 WEB SERVICE DESCRIPTION LANGUAGE (WSDL) Jeo 13° JAX-RPC API (APACHE AXIS)... 13.2 ConricuRiNs APACHE Ax 13.2 Contaacr FIRST QOAX-RPC APL, APACHE Aids, SEAVLET ENDROMT, SUC REG/NEPLY) 13.3 REQUEST PROCESSING FLOW.. 13.4 Conraser Finst - AcTIVITY Guitbe. 414 JAX-WS API (SUN REFERENCE IMPLEMENTATION) ws... 14.1 DIFFERENCE BETWEEN TAXRPC AND JAK-WS APE sss evs 14.2 ConTRAcr Last (JA-WS APL (RI), SERVLET ENDPOINT, SNe REG/AEDLY)... 14.3 Contract Last Activity GumDE... 14,4 Cowrnacr Frest JAX-WS API (RI), SeRULET ENDPOINT, Srvc REU/REHLY) 14.5 Contract Fisst~ ACTIVITY GuIC% . 14.6 Butloine Cowsumes .. 14,7 Siup aaseo cowsunee ~ AcriviTY Guioe.. 14.8 DISPATCH API Cust 14.9 DusreRENCE BETWEEN VARIOUS MESSucE EXCHANGING FORMATS. 14.9.1 RPC/Encoded, 14,9.2 RPC/uiteral saseeemeseeeen 14.9.3 Document/ENCOPEE vasessvoeines poeetonnniaevete 14.8.4 Document/Litera! . 414,8.5 Document/Wrapped .. 1s soap., 15.1 INTRODUCTION sea 15.2 THE SOAP Messase 15.3 THe SOAP Navesrace: 15.4 Cove Mopuies win SOAP NanESPacES 15.5 THE SDAP Message Pam 15,6 THE SOAP Booy, 15.7 SOAP FauLIS 15.7.1 Fauitcode Element. 15.7.2 Detailed Element... 15.8 SOAP over HTTP, 16 JAX-WS API (APACHE AXIS 2 - IMPLEMENTATION) .. 16.7 UNDERSTANDING Axis DistRIEUTION 16.2 AKISZ.WAK DISTRIBUTION 16.3 CONFIGURING Axis 2 eNviRoNMENT 16.4 Dercoveent MoDeL 26.5. BunLDINs ProvioRR... 17 SECURING JAX-WS (APACHE AxIS2)17.1 Secunina a Wen Seevices, se 18 JAX-WS API (ORACLE JDEVELOPER IDE) .. 18.1 INSTALLATION B ConPicupa 18.2 BUILOING PROVIDER (CONT@ACT LAST) stssusesnse 319 JAX-WS API (APACHE CXF IMPLEMENTATION) 49.1 UnbeRstanoing ApacHE CXF SISFRIBUTION.. 19.2 BuLDING ProwipeR, 19.3 BuiLoinG CONSUMER «4 20 JAX-RS API (RESTFUL SERVICE) 20.1 PainicerLes connate 202 ARCHETECTURE saseseesssseea 20.3. Java SuPpoRT FOR REST. 20.4 SETTING ve ResTERS¥ (J8055) 20.5 DEVELOPING FILST RESTEASY APPLICATION 20.6 Deve.oninc Finsr JERSEY APPLICATION... 20.7 BOOTSTRAP OFTIONS. 20.7.1 RestEasy, . ee ee 20.7.3 Common bootstrap option. 20.8 WoRKinG with HTTP METHOD soe 20.9 JAK-RS BOECTION.... 20.9.1 Path Parameters sors 20.9.2 Matrix Parameters 20.9.3 Header Parameter scrven 20.9.4 Cookie Parameter. 20.9.5 Form Parameter. 20.9.6 Accessing Programatic Headers and Cookies. 20.9.7 Working with Uriinfo .. 20.9.8 Automatic Parameter COnVErSION. 20.9.9 Bean Parameter se 20,9,10 Custom Parameter Converter 20.10 SuB-ResoURcE Locator 20,10.1 Static Dispatch. 20.10.31 Dynamic Dispatch 2011 CONTENT HARDLERS..succanennsarstsstnenstnevatsesne 20.12 CUSTOM CONTENT HANDLERS sss 20.13 Cowpuex REsroNses 20.14 EXCEPTION HanoUTs. 20.15 JAX-RS QUENT... 20.16 WORKING wiTH ABSTRACT CLASSES AND TwTERFACES 20.17 ASVNC SERVER AD CLIENT. 20.48 TAcHING.. 20.19 SECURITY. 20.20 WoRS wine SeainG INTEGRATION . 22 XML VS JSON. 22288, 299Web serviceWeb Service is the technology that allows us to build interoperable distributed applications, Before understanding anything about web services let's first of all try to understand what is distributed application and what does interoperability means. Hatvifured Prograsmnty We have a piece of work or Job or Task, if it is assigned to ene person he needs 100 hours of time to build the solution. But 1 want this job to be completed much lesser time than this. To reduce the amount of time needed, there are multiples ways, out of which few are: a) Increase the energy efficiency levels of the resource, in other words scale up the hardware of the machine. Let’s say if the machine has been configured with 2 GB RAM and takes 100 hours of time to compute the solution, increase the RAM from 2 GB to 4 GB, so that the Job would be computed quicker within 95 hours, Increasing the RAM size from 2 GB to 4 GB has improved the performance and reduced the processing time by 5 hours so, let’s say if I increase the RAM from 4 to 8 oF 8 to 16 oF 16 to 32, the performance improvement might be observed but it would not be always rejatively impacted, You might see performance improvement up to certain extent but ‘beyond that they may not be any further effect in performance even you scale up the system. b) Engineer the system. To build a solution for a job always there are multiple ways of doing it, but to complete it within fess amount of time we should have @ proficient skill set in working an it. When writing logic, we can produce the same output by \riting 10 lines of code and even with 5 lines of code, to reduce the amount of code to build the solution; we need to engineer our system, By modularization and effective design we can always reduce the number of lines and tune the logic to complete it faster. The more you engineer/tune the less the time required to process it, But this would also not always relative, because even overdose af medicine will acts as poison, beyond certain extent if you try to re-use or reduce the amount of lines, rather than giving a positive effect; it might downgrade the performance of the application itself, By now we understood that we can reduce the turnaround time that is required to execute a job by one person, but that is up to certain limit, may be could be 10% oF 20% of the actual time, but we may not surprisingly bring down it to half or quarter of the original time by single person. But there are use cases that demands high amount of throw put or less processing time, such kind of jobs cannot be handled by one person rather we need to distribute such jobs between more than one people. The seme is shown in the below figure,Person In the above diagram, it shows 3 100 hours of job has been divided into multiple parts (let's say two equal 50 heurs) and each part is independent with other part. The parts are assigned or shared! across two or more people, so that each one would be able to execute on its own piece to build a partial sofution, as there are working parallel the time required to complete 100 hours of job by two person's working parallel is SO hours and the time required to combine their individual outputs to form the ficial output may be 5 hours, So, the total time required to build the fina! solution would be 55 hours which when compare with ane person working on that Job it’s @ great performance improvement and drastic change in turmaround time, So, if you went greater performance improvements or quicker turnaround time such kind of jobs must be distributed across various people. Initially we have programs which are designed to run on one Box/Machine, Like when we develop °C” language program, it will execute on a machine and can talk to other programs which are running on same machine. In this case if we run two instances of the program “Pi” on the same machine both instances will execute simultaneously by sharing the totally hard of the same machine. In this case they won't be any performance improvement as they cannot scale up beyond the current machine configuration.Now we are looking to build applications/programs which not only execute on a Machine and talk to other programs on the same machine, these programs should alse be able £0 access/communicate with other programs which are running on different machine. In order for a program te talk to other program running on Gifferent machines, both the machines should be connected over wire/network. So, we are trying to build applications which can talk aver the network, which means network enabled or network aware applications. By now we understood distributed applications means the pragrams which are designed to taik to other programs which may be running an same or physically separated but cerimected via network machines as well granwains There are several advantages of going for distributed programming few of them are as described below. a) Higher throughput: - In distributed programming the na of jobs being computed within a particular time would be more when compared with one program running on one machine, 5) Quicker turnaround time: - if a job takes 100 hours of time to complete, if We distribute this job across multiple machines and executed parallely, it would be completed much faster than 100 hours, So, turnaround time would be faster when we distribute it. €) High availability of resources: - If a job has been assigned to one person to ‘execute, if he falls sick they won't be any other person who is going to back up the first person to complete it. In case if we distribute it across more than one resource and if one falls sick always there are other people/resources who can share the load of the person and can complete it. @) High utilization of resources: - There are some resources which are very costly, let's say printer. If want every employee in the organization to have access to printer, instead of buying 100 printers for 100 employees, we can have one printer which can shared across 100 employees so that it would be Litilized by everyone effectively. Ole in Ets Every progremming languages added support to build distributed applications Equally Java also has its contribution towards it. Java has various API's which allows us to build distributed/remote applications, Let's try to understand closely the API's in Java, their advantages and disadvantages of each, and what are the factors driving us to Web services. Jnuted Programming CORBA stands for Common Object Request Broker architecture, After socket Programming, the first API that has release by Java te support Distributedprogramming is CORBA. In CORBA programmer has to code using IDL. IDL stands for “Interface Definition Language”, it is @ scripting fanguage where CORBA developer wntes the IDL file and gives it to CORBA compiler. The CORBA compiler wilt generate the language specific object (let's say Java or C or C++ or snet). In to the generated Object, the programmer has to write the business logie. After writing the business logic, in order to expose the CORBA object over the network it has to be deployed on MOM’s. MOM stands for Message Oriented Middleware and is nothing but a CORBA server. The purpose of MOM |s to host and expose only the CORBA objects, But in order to use MOM, we need to acquire license and involves cost {not open source). Considering all the above factors, like develooment will starts with IDL (seems to be different from general way of programming) and deploying requires 2 licensing server, at those times working would CORBA seems to be complicated and quite messy, This makes CORBA quickly vanish from the market. aE RMI stands for Remote Method invocation. After CORBA, SUN released RMI as | an API to support distributed programming, It atlows a Jave Object to be exposed over the network. SUN designed RMI keeping in view of ali the complexities and drawbacks in CORBA and ensured those will not be re- introduced in RMI. So, in RMI java developer instead of writing a different language script like IDL, he will start with Java Object development and once he finish writing the business logic in the POJO, he will give it as input to RMI Compiler, which will generates abstractions (a tayer on top of it} to expose over the network. Here the programmer need to worry to code a different language file or need not write the code in some other generated object, rather the development starts with POJO and once finishes will generate network abstractions to expose it, To expose the generated object over network, it has to be deployed on a server called RMI server. The RMI server is open source and would be shipped as part of IDK and is very light weight server. With this if you observe almost all the dis-advantages with CORBA have been fixed in RMI and it Is light weight. (Out of its simplicity, it introduced certain dis-advantages as well. In RMI developer has to deploy the RMI object on RMI server and it is absolutely light weight, it is just a registry holding the RMI object with a name to locate it. Apart from this the server would not provide any infrastructural services like security or connection pooling or transactions and these has to be coded by developer itself, which would be so costly and huge emount of effort is required.i | { | | EJB stands for Enterprise Jave Bean, which is next to RMI. From the EJB's onwards the concept of managed object came into picture. You will write an Object which acts as an EJB and is deployed an a managed server called EIB container, While your £18 object is executing, it might need some external infrastructural resource support, instead of programmer coding for it, like security oF transaction or auditing or cannection pooling, these would be configured, maintained and provided to the EJB object by EJB Container itself, So, programmer need not worry about implementing these infrastructural Tesources and he cannot concentrate on his business fogic leaving it to Container to provide them. This makes programmer iife easier rather than coding each and everything out of box But the problem with EJB is when you expose an Object as EJB, it can be accessed over the network by other programs, The other programs which wants to access the EJB object should also be Java applications only and non-java Programs cannot access EJB’s as shown below. Program accessing €33 £38" object {Should be Tava Program) (running on £38 Container) _ web servic ‘Web services aise allows a program to expose objects over the network, but the difference between other distributed objects (RMI or EJB) and Web Service distributed object is these are not only platform (OS) independent, these are even language independent. Which means you can write a Web service Object using C, Ctr, Perl, Phython, PHP, Java or Net and can expose over the network. In order to access this, the other program could be written in any of the programming languages like C or C+-tor Perl or Java etc, Anything that is accessible irrespective of Piatform and programming language is called Interoperability. This mean we are building distributed interoperable programs using Web services(can Programs eqcescing Web Service (also called as consumer ne coded in Java, C, Cis, one | ecgqen TyInitially every language can build pregrams which can run on one machine. There after every program tanguiige strived to build applications which can nat only talk to the applications running on same machine but also they should be able to communicate with programs running on different machines but, connected over the network, which is nothing but distributed programming. With this the vention didn’t end, they want te still find a way to build distributed programs which can talk over heterogeneous systems (irrespective of platforms and programming languages) is called interoperable distributed applications To bulld interoperable distributed applications, every software vendor in the. industry started defining their own standards. Let us say SUN has defined its own standards, Microsoft defined its own standards and 18M carne with its own, standards ete If vendor has their own stack of standards for example as shown below [Vendor ‘SUN Microsoft | 16M ‘Transport Protocol aime ere ‘SMTP Language for exchanging data | XML fase Tea JWSDL | MSWSDL ‘TeM4sDL Description Java programs can only understand the data transmitted over HTTP, so if a Microsoft program is sending the data over FTP, it cannot be read/received by a Java application. In this case Interoperability never will become a reality. Finally it was realized by every software vendor that we cannot build independently an interoperable distributed applications, unless everyone has agreed upan same standards, There comes an organization WS-I, stands for Web Service Interoperability organization, It is a non-profitable organization which is formed to build open standards for building interoperable distributed applications. The members of this Group are people/representatives from various vendors in the software industry, WS+I has released BP 1,0 (Basic Profile) specification document, The specification document comprises of set of quidelines or standards that must be used to build an interoperable distributed programs. BP 1.0 doesn't talk about how te develop an interoperable distributed apptication in Java rather they will talk about the standards or guidelines to build web service in any programing language. After few years of BP 1.0, WS-I has again released one more specification document BP 1.1 his the successor of BP 1.0 which contains some advancements than its earlierAs discussed above WS-I's BP 1.0 and BP 1.1 specification documents contains guidelines for building Web Services in any programming language, those are not specific for Java, SUN has to adapt those guidelines to facilitate building of Web services in Java. ‘To build WS-1’s BP 1.0 complaint Web Services SUN has released JAX-RPC APL and to build 8P 1.1 complaint Web Services JAX-WS API has been released, As BP 1.1 is the successor of BP 1.0, similarly JAX-WS API is the successor of JAX-RPC APL Always using Specifications and API's we cannot build programs rather for an APL we need implementation. There a lot of Implementations available for both JAX- RPC API and JAX-WS API, few are open source and few other are commercial. Below is the table showing the implementations of JAX-RPC API and JAX-WS API. API {Implementations Description ~ TJAXCRPC SI Java APT for XML Remote | Procedural calls Sun “ | Implementation a - pane < Apache AX! Apache group provided g implementation & e ‘Oracle Web logic Web Oracle Corp z Services a -. ~ 5 — ‘BM Web Sphere Web 18M Services JAX-WS RE Java APT for XML Web Services Reference linpiementation Hatro One more SUN Implementation po a Apache AXiS2 ‘Anather Apache group implementation to support development of JAX-WS API complaint Web services. Apache OF ‘Apache group JAX-WS API Services TaM Web Sphere Web: ServicesLet us try fo understand what we need to build @ Web Service in general. It’s similar to block diagram ofa computer tike we need mouse, key board, monitor, CPU ete. Let us also identify here what are ail the various components required to build @ Web Service, P 1 two people want to exchange information between them, what they need? To propagate their wave tengths from one person to other, they need medium, Medium acts as a physical channel on which data would be exchanged. If two computers want to exchange data, first they should be connected over a wire or network, Having medium itself is enough? With medium we can propagate the wave lengths, but there is not guarantee of receiving the information intact and properly, Let's say two people are tatking to each other, instead of one person listening to other both the peopte started talking to each ather at the same time. It seems instead of taiking there are barking at each other, would the communication be effective? Rather if there are set of rules that guards their communication, for e.g.. first person says am starting the conversation so that the other person would be in listening mode, once the first person finishes, he will ‘Say am done so, that the other person can start the conversation by following the samme rules. This Indicates we need set of rules that guards the communication channel which 's nothing but 2 protocol, If two computer systems want to exchange data, having Network itself is not enough we need a protocol to guard the exchange of data ever them. Protocol simulates that everyone has their independent bands of communication channel to exchange information, even though everyone is sharing the same physical channel. in the same way if two programs want to exchange the data over the network, they need physical data transport protocol like TCP/IP or RMI/ILOP or HTTP or SMTP etc. The recommended protocol in case of Web Service communication is HTTP,Now we have medium and protocol to transmit information between two people, but both the parties nas to exchange the information in same language, which means a commen language to exchange information in an understandable manner like English or French or Japanese etc. If these two are computers, we can exchange the data between them in an ASCIL oF UNICODE encoded characters. Far example it could be a CSV or a text file of information encoded in common enceding, CSV files are good when your data is strictly tabular and you know its structure. If you have relationships between different levels of data, CSV are not competent to hold such information. CSV is not self-expianatery which means based on the position of fields user has to lnterpret the type or nature of information. Let's consider a simple example to understand the same, ‘There are two systems, one is a Bank system and the other is client who is trying to send the deposit data to deposit into his account. He has sent the information in a CSV format as shown below. 1, AC342, Suresh, 422, D, W ‘The field order in which he sent the information is Serial No, Account No, Name, Amount, Operation Type and Branch Code. The Bank system upon receiving the data has started interpreting the data in this order Amount, Account No, Name, Serial No, Branch Code and Operation Type. The problem with the above representation is the data is not self-explanatory, which is nothing but semantics of data is missing; the receiver of the data also has to interpret the data in seme order (which is not guarantee). This might lead to incorrect operations as above instead of deposit, it teads to withdrawl, Instead of CSV, we can represent the data in MS-Word, MS-Excel ete, But the probiem with these kinds of representations is those are recognized by only Windows and few other platforms, which means those are platform dependent formats, We are trying to build an interoperable solution, which means the data we carry between systems must also be interoperable, Only way of carrying data between systems in an interoperable manner is XML. XML Stands for Extensible Markup Language. It is not a programming language; it is used for storing information in it. How we store the data in MS-Word or MS- Excel or a CSV file similarly XML is also a document which stares data in @ XML Format, The data represented in XML has well-defined structure and has semantics attached to it (self-explanatory) as shown below
1
i saceno>AC324Suresh |
|
0
|cimgssnesee n= rrancades AC222
533fd
b ‘Secret password
John
33kk
> Password with which want to register Lsfresistration> In the above XML we are trying to represent two different types of data one is business data nothing but AccountNo, username and password with which you want to register your account, The other one is helper data or processing data secret password given by bank with which you can be authorized to register. As discussed it contains two types of data, it would be confusing for the person who is trying to read this XML, to identify which is processing data and which is business data. We need a wrapper on top of it to differentiate the same, which is nothing but SOAP. SOAP stands for “Simple Object Access Protocol”. It is also an XML, but SOAP XML has @ rigid structure and has reserved grammar with which we need to write it, SOAP XML has root element as Envelope and has two sections, first one is header and second one is body as shown below.=Envelope>
| <|—processing daté'or helper data
| | =I—Business data | ___ Ail the processing data will be placed under
element and the business data will be placed inside element. SOAP is also called as Binding Protocol, because it binds our business XML, It acts as an Application Specific Protocol, because the receiver of the SOAP XM. will be able to identify and differentiate which is processing data and which is business XML, SOAP defines the rules in which other applications has to interpret the data so It is called Application Specific protocol, Along with that SOAP is also called as carrier of the actuat Payload. As our business XML is placed inside the SOAP XML and Is carried by SOAP. It is also called as carrier of the actual payload, erica Description Lispuig} As we know in a Web Service two parts are involved, one is provider and the second one is consumer, Provider is the person who always listens for incoming requests from a consumer and serves data as part of request. Consumer is the requestor, who always seeks information from the Provider. So, for a consumer in-order to get the data from the Provider, he needs to know the information about the provider. This means the information about the provider has to be document in some document like MS-Word or PDF etc. The Problem with this is you are trying to build an Interoperable distributed. application which can be accessible by any one literally, but the documentation about it is being documented in non-interoperable document, will it be understood by everyone. That means not only the program the documentation should also be interoperable, there comes WSDL. WSDL Stands for Web Service Description Language. It is also an XML type document, this makes it interoperable, WSDL has a pre-defined structure and has gramrnar, using which you need to write the WSDL document. WSDL document will provides the entire information about the provider like Service name, Number of Operations, their parameters and return types and Location of the Service ete ‘The consumer can know the entire information about the provider by seeing its WSDL document Note: WSDL is a static entity which describes information about the Provider. It 5 fs not a program to execute,After clacumenting the information about the service in WSDL, we need to distribute the WSDL document to the consumer's. Do we have ane consumer for a Provider and multiple Consumers? For @ Provider it could have as many consumers as possible, so we need to circulate or distribute the WSL document to each and every consumer, Will it be feasible to give WSOL document to each and every consumer, ideally speaking will not be possible that’s where UDDI came into picture, UDDI stands for “Universal Description and Discovery Intearation Registry”, this is the registry which store’s all the WSDL documents in It. Provider will publishes the WSDL ' documents to the UDDI registry and Consumers will browse for a WSDL document from the registry, UDDI should be accessible irrespective of programming language which means these should also be interoperable, that's why those are built using XML technology, so those are also called as XML registries, ‘There are two types of UDDI registries a) Private UDDI ~ These are maintained internal to an organization and would be accessible within the organizational n/w. b) Public UDDI ~ These are accessible globatly across over the network. But few i would be open source hosting and few would be commercial, From the above we understood what are the components required to build a Web Service, below is the diagram depicting the Architecture of a Web Service, Consumer rTP Provider Provecol Web Service Architecture diagram Explanation: - Consumer is the person who tries to access the information fram the Provider, and Provider is the person who always services the Consumer,‘Those should be often referred to as Consumer and Provider and should not call them as Client and Server in case of Web Services, Consumer and Provider want to exchange information, so first they should be connected with a wire and needs a protocol to guard their communication. The recommended protocol in a web service communication Is HTTP, HTTP protocol is firewall friendly, They need a common language to exchange data, the defacto standard for exchanging information between computers is XML, But anfy XML is not enough, ‘as @ Web Service communication not only transmits business data, It might also transmit helper or processing information, so we need a layer on top of it called SOAP, SOAP stands for “Simple Object Access Protocol” acts as @ binding protocol to classify the information, If the consumer wants to access the provider, he needs to know the information about the provider. So, the information about the provider is documented in a document called WSDL and is being published by the Provider in @ registry called UDDI. The process of putting the document into the UDDI registry is called Publish and would be generally done by Provider. Now the consumer has to connect to the registry and performs a search on the registry which is called Discovery to find an appropriate WSDL document, Downloads it locally and now starts understanding the information about provider, He will builds @ program called "Web Service Client” using the information in the WSDL document through which he will sends the request and gets the response back, By the above we understood that language for exchanging the information is XML. Binding protocol is SOAP which is nothing but XML and Description of the Service Is, WSDL, Is also XML. Registry in which we store the WSDL is UDDI, built on top of XML technologies, everything in Web service is built on XML and without XML Web. Services would not be possible, so first we need to understand XML, let’s move to XML.XMLXML stands for extensible markup jancuage. Markup language is the language using which you can build other languages like, HTML, XML. XML is defined and governed by W30rg. The first and final version of XML is XML 1.0. XML is the document which represents data, Unlike C, C++, Java etc, XML is not @ programing language. Tt is the defacto standard for exchanging information between computer systems. When we represent data in an xm! document it would be more structured and has well defined semantics attached to If, "Semantics" here represents what 2 particular data field is representing or stands for, so that any person reading the xml document would be able to interpret in the same manner. Another significant feature of XML is, once written it is portable across the platforms (Windows, Linux etc), No changes are required to carry the data across platforms. Every language has keywords, If you take example as C, it has keywords like (if, for, while, do, break, continue etc.) but when it comes to KML there are no keywords or reserved words. What you write will become the element of that XML document. i, XML Biamant Element in an XML is written in angular braces for é.g.
. In XML there are two types of elements as follows 1) Start Element/Opening Tag: ~ Start element is the element which is written in
indicating the start of a block 2) End Element/End Tag: - End element is the element which is written in
indicating the end of a block As everything is written in terms of start and end elements, XML is said to be more structured in nature. An XML Element may contain content or may contain other elements under it. So, XML elernents which contain other elements In it are called as Compound elements or XML Containers, 2 XML Attribute If we want to have supplementary information attach to an element, instead of having it as content or another element, we can write it as an Attnbute of the element. Exampte:-
2) Root Element: - XML document must contain a roat element, and should be the only one root element, All the other elements should be the children of root element, 3) Level constraint; - Every start element must have an end element and the fevel at which you open a start element, the same fevel you need to close your end element as well. Exampte:-
John
(- info is closed in-correctly --)) student: if any XML is said to follow the above defined rules then it is termed as well- formed. 4.4 XML Usage ‘An XML document is used in two scenanos 1) Used for transferring information:- As said earlier XML is a document | representing data and is used for carrying information between two computer systems in an Interoperable manner. 2) Configurations: - in J2E€ world every component/resource you develop like Serviet or E5B, it has to be deployed into a Web Server, For e.g. in a Serviet application, the path with which the servlet has ta be accessible should be Specified to the Servlet container so that it can map the incoming request tothe Servlet, This is done in a web.xml. When we provide the configuration information in @ XML file the main advantage 1s, the same xml document can be used in different platforms without changing anything, Every XMU in-order to parse (read) should be well-formed in nature. As said earlier well-formness of an XML document indicates whether it is readable or not, it doesn’t talks about whether the data contained in it is valid or not, Validity of the XMt document would be defined by the application which is going to process your XML document, Let's consider a scenario as follows. You want to get driving license. In arder to get a driving license you need to follow certain process like filling the RTA forms and signing them and submitting to the RTA department, Instead of this can you write your own format of fetter requesting the driving license from an RTA department, which seems to be not relevant because driving license is something that would be issued by the RTA department. So, the whole and sole authority of defining what should a person has to provide data to get a driving license wil lies in the hands of RTA department rather than you. In the same way when an application is going to process your xml document, the authority of defining what should be there as part of that xml is lies in the hands of the application which is going to process your document. For example let's consider the below xmb fiagment. Example:- PurchaseOrder xm! document
citemCode>1C323 24 sitem> sitemCode>1C324 abe
In the above xml even though it confirmes to all the well-formness rules, it cannot, be used for business transaction, as the 2
element carries the data as “abe” which doesn't makes any sense, So, in order to check for data validity we need to define the validation criteria of an XML document in either a DTD or XSD document. :DTD stands for Document Type Definition. I Is the document which defines the structure of an XML docuniént, In an XML document we have two types of elernents; elements which carry data are called simple elements. An element which contains sub-elements under itis called compound element, In a language before using & variable we need to declare it, Similarly before using an element in XML first we need to declare it in DTD. While declaring the element in DTD, we need to tell whether it is a simple or compound element. So, we need to understand the syntax of how to declare simple and compound elements of an xml in dtd Srsan for Declaring Stmpls Mec ent of an Kate Fore.g.. ‘ As per the above declaration, it means in my xml we should have an element whose name is iternCode ang it contains content of type #PCDATA (parsable character data). In an XML characters like “<",“=*,“", “” and "&" are valid characters and if the text content contains those characters the parsers are going to parse or will expand them as further entities, 2 for Loepponne ote <)ELEMENT quantity (#PCDATA)>
As per the above declaration, we declared an element itemCode in XML which contains child elements like itemCode, quantity. In XML
| ~itemCode>IC200
35
We need to follow certain rules while dectaring elements in DTD. 1) Element name should follow the java veriable naming conventions. 2) Content of an XML is always case-sensitive. So, if we declare element names in small case in DTD, it should appear in small case in XML as well. 3) The child elements separator in the above example is used as,” comma. This is also called as sequence separator. This means in the item element, the first child should be iternCode followed by quantity. Let's take 3 complete XML and derive how the DTD looks like for it. Here are few of the guidelines in creating e DTD from XML. 1) Identify ail the simple elements of XML from bottom of the XML and draft them: in the DTD, 2) Identify the compound elements of XML from lowest level in the XML ang draft them in the DTD. XML Document
1C323
24
1C324
abe
spurchaseOrder> For the above xml the DTD looks as shown below. [
| | | } In the abave xml if you observe the orderftems clement can contain any number of item elements in it, buf atleast one item element must be there for a PurchaseOrder. This is called occurrence of an element under another element, to indicate this we use three 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) * - indicates the sub element is optional and can repeat any number of times (@-N) You will mark the occurrence of an elernent under another element as follows. {Element elementname (sub-elemd (7/+/"), sub-elemz(7/+/*)}> Leaving any element without any symbol indicates it is mandatory and at max can repeat only once. any Cosmet Elements declared with the content type as ANY, can contain any combination of parsable data, Biaewents avi In an e-mail body part we have content which can be mixture of any parsable characters which can be declared as ANY type, MMemerds weit: av Seeker Let's consider an example where in an email the following elements will be there to, from, subject and mait@ody, In these elements to and from or mandatory elements and either subject or maltBody should be present but aot both. To declare the same we need to use or content separator instead of sequence separator.
For the above declaration the xml looks as below.
. jon smail> |
toaddr.com
toaddr.com
fromaddr.com
from=fromaddr.com
mysub/subject> |
mysub J
—__._] —. We can even declare an element with mixture of parsable data and elements called mixed content as follows. 8.7 Declaring atirlovie for an elem Syntax:- As shown above to declare an attribute you need to use the tag ATTLIST and elementname stands for which 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: NMTOKEN The value is a valid XML element name ips Teescripton ‘CDATA ~ - “| The value is Character data _ (end Fenai- The wall Must Be one From the enumerated fist of vaiues. ic) "The value is unique 1d. \ [REF The varies the Wot anathar aswene ||| PREQUIRED IMPLIED
In xml i
of
othe
or Declaring a complex type is equal to declaring a class in java, In java we define User-defined data types using class declaration. When we declare a class it represents the structure of our data type, but it doesn’t allocates any memory. ‘Once a class has been declared you can create any number of objects of that class. ‘The same can be applied in case of complex type declaration in an XSD document. In order to create user-defined data type in XSD document you need ta declare a complex type, creating a complex indicates you just declared the class structure, ‘Once you create your own data type, now you can define as many elements youneed of that type. Let's say for example I declared a complex type whose name is AddressType as foilows xs :complexType name: sxs:sequence> |
|
| sxsielement name-="city" type="xs:string’/> | ddresstype"> | [e4sscomplextype= Now the above fragment indicates you created your own user-defined dats type whose name is “AddressType". Now you can declare any number of elements representing that type as shown below.
Let's take an XML document for which we will show how its XSD looks like XML Document ~ Courier consignment information
C4242.
durga
Sriman
S.R Nagar
Opp ChaitanyaHyderabad
Andhra Pradesh
353
[
XSD Document ~ coi iee consignment information [wie ora) 2001) XMLScAEnE"> [exsischema xmins:xs="hth “consignment” type=“consignmentType"/ =
«xs:sequence>
| |
|
|
|
8.2 Sequence V5 Al When declaring a complex type, following the
tag we see a tag
or
, When we use
under
tag, what it Indicates is all the elements that are declared in that complex type must appear in the same arder in xml document. For example let's take a complex type declaration "ItemType” which uses
tag in its declaration, [
So while using the item element in the xml we need to declare the itemCode and quantity sub-elements under item in the same order as shown below,
IC303
35
When we use
, under item element the itemCode and quantity may not appear in the same order. First quantity might appear then itemCode can present in the xml, When we use
all the elements under it should appear atleast 0 and at max once. XSD along with altowing you to declare your own data types, it will also allow you to extend your own types by the means of inheritance s shown below,
|
| ‘
|
“county” types"xs:int"/> n Simple Types XSD's allows you to define data validations on the data an element Is going to carry. In order to do this you can define your own simpleType by extending the ine built types and can impose restrictions on it as shown befow
| : In XML we can place supplementary information to an element in an attribute, Let’s understand how to add an atinbute to an element, attribute “type” Indicating whether the shipping address is permanent or temporary. In order to do this we need to modify the existing complex type and should add the attribute type to it, | In our example shippingAddress is an compound element. Now we want te add ane In case of attributes, we should dectare the attributes in a complex type at the last after the
tag, because sequence doesn’t apply for attributes. -
S Socharvig Aitriiutes far
For the above element deciaration the xml equivatent looks like below. local">353i Choice is used for specifying the either or condition in XS0's. For example we have purchaseOrder elenfent, In a purchaseGrder element we have orderitems as first element, Now when it comes to second one we may have shippingAddress or usShippingAddrass element. itis not necessary to present both but either this or the other is mandatory in Impose such kind of constraint we need to use Choice element as shown below.
sxsielement name="orderKems” type="orderitemsType"/> |
hippingAddress” '
In you want to refer one XSP in another XSO there are two options available, First one is Import and the other is Include Import has to be used when the namespaces of both the XSD documents are different for e.g. Fouxsd -
| I Po2.xsd sity ‘tte: /debayt in/sates/types” '
If you observe in the above scenario po2.xsd want's to use few elements declared in po1.xsd. In order to do that first po2.xsd should refer the pol.xsd. as both the namespaces of these documents are different we should use impart rather than include. oe Let's say we have a XSD document with more than 100 elements, Writing or managing the elements in one single XSD is not so easy and is error prone as well. Instead we can split it in to two XSD's and can include one into another. Which means if two XSD's are having the same namespace we need to use include tag to include one in the other, which is similar to combining two into one, PoLxsd '
Po2xsd xxsischems targetNamespac: ‘http: //ebay1 in/sales/types">
Every programming language one or in another way allows you to declare user= defined data types, Let’s cBnsider the case of "C” language it allows you to declare your own types using Structure, In case of "C++" Class declaration allows you to declare your awn type, same in case of Java as well, When it comes to XSD you can dectare your element type using XSD complex type declaration, As how any language altows you to create your own types, they allow you to rasoive the naming collision between their types. Let's cansider the case of Java; it allows you to declare your own types by class declarations. But when a programmer is given a choice of declaring their own types, language has to provide a means to resolve type names collision declared by several programmers. Java allows resolving those type naming conflicts using packages. Packages are the means of grouping together the retated types. it will allow you to uniquely identify a type by prefixing the package name. In the same way XSD also allows you to declare your own data type by using Complex Type declaration and In the same way it allows you to resolve the type naming conflicts by means of Nomespace declaration, XSD Namespaces has two faces, 1) Declaring the namespace in the XSD document using Targetnamespace declaration 2) Using the elements that are deciared under a namespace in xml dacument. & Yargatnanaspare Targetnamespace declaration is similar to a package declaration in java. You will bind your classes to a package so, that white using them you will refer with fully qualified name. Similarty when you create @ complexType or an Element you will bind them to a namespace, so that while referring them yau need to use Name, In order te deciare a package we use package Keyword followed by name of the package. To declare a namespace in XSD we need to use targetNameSpace attribute at the Schema level followed by targetnamespace fabel as shown below.2 Using elements trom ad xen & Exampte:- "ht: /iwww.w3.or0/200LXMischema” targetnamespace ="htip://dursasort.com/training/catendac/types" > ‘
-
The courseType by default is binded to the namespace. http: //duruasoft. com/trainina/calendacitypes So, while creating an element “course” of type courseType you should use the qName of the courseType rather simple name, (qName means namespace:element/type name). But the namespace labels could be any of the characters in length, so if we prefix the entire namespace label to element/type names it would become tough to Fead, So, to avoid this problem XSD has introduced a concept called short name, Instead of referring to namespace labels you can define a short name for that namespace label using xmlns declaration at the
level and you can use the short name as prefix instead of the complete namespace label as shown below. ‘http [Jwiww.w3.0rg/2001/KMLSchema” targetnamespace=hita.//duraasolt.com/iraining/catendar/types xmins:dt="http:/ /durgasoft.com /training/calendar/types”>
‘
‘
In the above xmt we stated this xml is using xsd document courselnfo.xsd whose pamespace is hitpi//duraasott comtraining/calender/tynes If you want to include two XSD documents in the xmi then you need to declare in schematocation tag
. For example:
Now in the above xml we are using two XSD documents courselnfo.xsd ai element Is used from courseinfo.xsd or vacation.xsd. To indicate it we sh prefix the namespace to the course element, nd vacation, xsd. With this declaration we will not be able to find whether the course ‘ould But the namespace labels can be arbitrary string of characters in any length. So, we need to define short name, so that we can prefix shortname while referring the elements as shown below, ‘ = "Uth-8>
|
="xs:stsing"/> "xsiinty> Po2.xsd >
‘
fetisitem"/> Po.xml < Perl version="1,0" encoding="UTF-8"7> i j
cetliitem> ett sitemCode>1C1001 et] :quantity>12 fet Liitem> L
“DID i DTD stands for document type definition | DTD’s are not XML Type documents | i DTD’s are tough to learn as those are | + not XML documents. Se, ai XML programmer has to under new syntaxes in coding DTD DTD's are not type safe, these will | represents all the elements with data type as (#2CDATA), | DTD's don't allow you to create use- defined types, create any number of elements, Documents XSD'S are XML Type documents As XSD's are XML type decuments it is easy for any programmer to work with xSD, XSD's are strictly typed, where the language has list of pre-defined data types in it, While declaring the element you need tell whether this element is of what type. XSD‘s allows you to create user- defined data types using complexType declaration and using that type you canJAX-PJAX-P stands for Jeva API for XML Processing, As we ciscussed earlier, XML is alse a document which holds data in an XML format. Initially in Java there is no API that allows reading the contents of an XML document in an XML format, Java Programmers has to live with Java TO programming to read them i a text nature or need to build their own logic to read them in XML format. By looking at this lot of Java software vendors in the market has started building their own libraries/API’s that allows processing an XML documents in XML nature. Few of them are DOM), JOON. But the problem with third party libraries are you need to stick with vendor specific classes, as there Is no common API which facilities switching between them. For example if we want to work with database programming in Java, we need to use JDBC API provided by Sun. But IDBC APT itself is not enough, as any API contains only set of Interfaces and abstract classes and only few concrete implementations, So we need an implementation to work with a specific database. JDBC Drivers are the implementations of the JDBC API which allows you to deal with specific database. Advantage of using standard JDBC API is your API classes never allow your code to expose to the implementation, so that your code would be flexible enough to change between different databases by simply switching the drivers. : Lets say in order to execute a sal query against a database you need Connection. But Connection is an interface provided by JDBC API, and we need to find the implementation class of Connection Interface and should instantiate it. Instead of us finding the Implementation class, JDBC APT has provided a class DriverManager which acts as a factory class who knows how to find the appropriate implementation of Connection Interface and instantiate it. epinan OracieIacdriver DriverBanag [ne gelConnect lang) object ! iNSSqiserverDriver) L_ | Soanect ior puject ee. oeThe advantage of going for Factory class like "DriverManager” is by passing different url, username and password, you would be able to switch between one database vendor to another database vendor, After many software vendors started developing their own libraries, sun has finally released JAX-P APE which allows us to work with XML documents, As indicated JAX-P is an API which means not complete in nature, so we need implementations of JAX-P API and there are many implementations of JAX-P API available for e.g, Crimson, Xerces2, Oracle V2 Parser etc. Xerces2 is the default parser that would be shipped as part of JDK1.5+. This indicates if you are working on JDK1.5+ you don’t need any separate Jar’s to work with JAX-P API SAL AML Precenging Mathosiotagies Let's park aside JAX-P for now and try te understand the ways of processing an XML document, If you are asked to read notes, each one has their own preference of reading the notes like one will start reading it from middle and other from the first chapter etc. In the same way there are multiple methods of reading the XML documents exists, those are SAX and DOM. SAX and DOM are the universal methodologies of processing (reading) XML. documents irrespective of a particular technolagy. Few programming languages/AP!’s supports only SAX way of reading documents, few other supports only DOM and quite a few number support both the ways of reading. Let us try to understand what these methodologies are and how to rea XML. documents following these methodologies, Zot SAK (avnia Accass fae 2ML) SAX stands for Simple Access for XML, it is a methodology that allows reading XML documents in an event based processing model. Any event based processing model contains three actors as described below. Source: ~ is the originator of event, who can raise several types of events, Events could be of multiple types if we consider AWT, we can consider source as a button, which is capable of raising several types of events like button click, mouse move, key pressed etc. Listener: - Listener is the person who will listens for an event fram the source, Ustener listens for 3 specific type of event from the source and triggers an even handling methad on the Event handler to process it, Event Handler: - Once a listener captures an event, in order to process it, it calls a method on the event handler ciass. As there are different types of events, to handle them the event handler contains several methods each target to handle and process @ specific type of event,In addition SAx is a sequential processing madel, which process XML elements sequentially from top to the bottorn, While processing the document, tt places a pointer to the docurnent'and increments sequentially from the top. Based on the type of element it is pointing te, it raises a respective event, which will notify the listener to handle and process it So here source is the XML document which can raise several types of events based on the type of element it is pointing to (e.g.,. START_DOCUMENT, START. ELEMENT etc,..}. Listener is the parser who will reads the XML document and triggers a method call on the Handler. Event handler contains several methods to handle various types of events as shown below. [fe SE var ee SAX is very fast In processing XML documents when compared with DOM and consumes fess amount of memory, as at any given point of time it loads only one element into the memary and process. Here one key thing to note is using SAX we can only read the XML document, we cannot modify/create a document, Using JAX-P API we can process XML documents in SAX madel, here also source is the XML document, who is capable of raising multiple types of events likes startDocument, startElement, endDocument etc, In order to read the elements of XML and process them by raising events, we need a parser and here in SAX it is SAXParser. As indicated earlier JAX-P is an API which contains interfaces/abstract classes and few concrete implementations, SAXParser is also an interface, in order to instantiate it, we need to find the respective implementation of It, instead of we finding, the API has provided a factory, SAXParserFactory which would be able to Instantiate the implementation of SAXParser. The following two lines shows how to instantiate the SAXParser, 'SAXParserFactory saxParserFactory = SAXParserFactory.newinstance(); IS&XParser parser = saxParserFactory.newSAXParser();, Along with the parser, we need @ Handler class to handle the event and process It. A handler class woud be written by extending it from DefaultHandler, we can override the methods to process respective events, Below is the example showing a class extending from DefaultHandler,parser. handler; package com. import org.xml.sax Attributes; | import org.xmi.sax SAXException; import org.xmi.sax-helpers.DefaultHandler; public dass POHandler extends DefaultHandler < @override public vold characters(char{] xmt, int offSet, int len) throws SAXException{ | String data = new String(xmt, ofSet, len) System out print(data), 3 @Overnide i public void endDacument{} throws SAXException { System.out.printin("END DOCUMENT"); 3 @Override public void endélement(String arg, String argi, String localName) throws SAXException < System out printin(""HocalName+">"); 3 @Override public void startDocument() throws SAXException { System.out.printin(“START DOCUMENT"); 3 @Override public void startElement(String argQ, String arg1, String locaiName, Attributes arg3) throws SAXException ¢ System.out.print("<"HocalName+" In the above class we are overriding five methods which would be triggered based on the type of elements the parser is pointing to on the source XML document. a) startDocument ~ would be triggered at the start of the XML document b) 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 between the XML elements. To this method it passes the entire XML as character array along with twa other integers one indicating the position in the array from which the current data portion begins and the second integer representing the number of characters the data span to. d) endElement ~ would be triggered by the parser, when It encounters @ closing element or ending element.i | | i; ®) endDocument ~ would be triggered by the parser once it reaches end of the document. Once the handler has been created, we need to call the parser class parset) method by passing the source as XML and the handler as the object of handler cass which we created just now. So, that the parser will reads the XML, elements. and triggers @ respective method call on the handler object provided. The below program will reads the XML document sequentially and prints it en to the console, package com.saxparser parser; i impart java.io.File: | import java.io, lOException, | i import javax.xml. parsers. ParserConfigurationException; import javax.xml-parsers, SAXParser; import Javax.xnil parsers. SAXParserFactory; import org.xml.sax.SAXException; import com.saxparser.handier.POHandler; i public class POParser { Bublic static void main(String args{]) throws ParserConfigurationException, SAXException, IOException { SAxParserFactory factory = SAXParserFactory.newinstance(); SAXParser parser = factory.newSAXParser(); parser.parse(new Fite “D:\\WorkShop\\Traininas\\March, 2012\Web Services\\SAXParser\\resources\\po.xml"), new POHandter()); }Input XML]
sorderitems>
“itemCode>1C29029«/itemCode> |
10
sshippingAddress type="primary">
Durga Soft Solutions Pvt Ltd
S R Nagar
Hyderabad
AP
500038
scountry>India
capers |». quant ity ) bee ’ The above diagram shows for an Input XML how DOM toads and builds @ tree structure representing elements and data, As DOM loads the entire XML into memory at one shot, to load it takes some time and as it holds the complete XML in-memory, it consumes more amount of memory. That's the reason DOM is relatively slow when compared with SAX, The main advantage of DOM is unlike SAX, it is a readi/wite API which allows you to create/modify a document. Anything in DOM is called 2 Node, There are several types of Node like Document Node, Element Node, Text Node and Empty node etc, The top of the i document is called the Document Node, if an element which Is enclosed in L angular braces (<>) then it is called element node and if it just represents data then it is called Text node. When we give XML document to DOM, it loads the XML and builds tree structure: representing elements as nodes as described above, Then it places a pointer to the top level of the tree which is a Document Node. To navigate between various elements in DOM, it has provided convenient methods by calling which we can traverse between them, :+ ais parent + be ischildof parent a ~ a a ~ is parent + band ¢~ are children of a those are children of same parent [+ band care called siblings, as |: i | Relation between nodes in DOM As explained above except the root element all the other elements have a parent node. Children of same parent are called brother/sister in other words sibtings. JAX-P provides a way to work with these nodes in Java, JAX-P has provided methods like getFirstChild(), getChildNodes etc to access children of a parent. In the same way to access the siblings it has provided methods like getNextSibkings(). Before using the above methods, first of all we need to load the XML document as Gescribed earlier. An XML document in JAX-P DOM is represented in Document class object. As said earlier JAX-P is an API and org.w2c.dom.Document is an interface. So, we need to provide implementation for Document object and should instantiate by loading the XML into it. So, we need @ Butlder which will read the existing XML, loads and places in the Secument object, this would be done by DocumentBuilder, he is the person who knows how to read an existing XML document and loads in memary, along with that using DocumentBuilder we can create or modify existing documents as well (DOM is a read/write API so to support writing we need builder to build/modify document).Unfortunately DocumentBuilder is an abstract class, 50 fo instantiate it we need DocumentBuilderFactory. So, to summarize DocumentBuilderFactory knows > creating DocumentBuilder > Knows creating Document, The belaw plece of code shows how to load an existing XML document and represent in Document Object. DocumentBuilderFactory factary ~ DocumentBuilderFactory.newlastance(); DocumentBuilder bullder = factory.newDecumentBuilder{): i Document doc = builder.parse(new File("po.xm!"))3 ! Alter creating the Document abject, it points to the top of the Document which is called Document Node. Now we need to use methods to navigate between the elements of it, Below sample program shows how to navigate to an element orderitems in the earlier XML. i Note: - we need to set factory.setignoringElementContentWhitespace(trua) to i Ignore newlines and whitespaces in the document while parsing, package com.domparser.parser; | import java.to. File; import java.io, JOException; Import Javax.xmi.parsers. DocumentBullder; ' import Javax.xml. parsers. DocumentBuilderFactory; | Inport javax.xml. parsers, ParserConfigurationException; import org.w3c.dom.Document; import org.xmi.sax. SAXException; public class PODomParser { Public static void matn(String argsf]) throws ParserConfigurationException, SAXException, 10£xception { DocumentBuilderFactory factory = DacumentBuilderFactory.newlnstance(); DocumentBuilder builder = factory. newDocumentBullder(); Document poDocument = builder -parse(new File( | "D:\\WorkShop\\Trainings\\March, 2012\\Web Services\\DOMParser\\resources\\po.xrnl")); System, out.printin(poDocument.getFirstChild( ).getFirstChild().getNodena) me())}: + +Instead to print the entire XML document on to the consule we need to traverse all the elements recursively. As you know DOM loads the XML dacument represents it in a Hierarchfeal fashion (Tree structure), any Hierarchical representations needs recursion technic as the things would be in parent and child nested format. If we take Binary tree, the tree traversal algorithms are In- order, pre-order and post-order which are recursive technic based traversal, algaritivns, The below programs shows how to traverse between all the DOM nodes recursively, package com.po.parsery | import java.io.File; import Java.io.1OException; import javax.xml.parsers.DocumentBullder; import Javax.xmi parsers. DocumientBuilderFactory; import javax.xmnl.parsers.PerserConfigurationException; import org.w3c.dom.Document; import org,w3c.dom.Node; import org,w3c.dom.NodeList; import org.xinl.sax.SAXException; public class PODOMParser private static final String XMi_PATH = “C:\Workshop\\Trainings\\WebServices\\Batch12092012\\Web Services\PODOM\\resources\\po.xrnI"; public static void main(String args[]) throws ParserConfigurationException, SAXExcention, IOException DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory. setl¢noringElementContentWhitespace(true); DocumentBuilder builder = factory. newDocumentBuilder(); Document doc = builder.parse(new File(XML_PATH)); //Systern.out.printin(dec, getFirstChild().getFirstChild(). getNodeName()); printNode(doe); Contd...Drivate static voi¢ printNode(Nade node) { if (node !=-ull) ¢ int type = node, gethodeType(), switch (type) { case Node.DOCUMENT_NODE: System. out.printin("<2xmt version: printNode(nede,getFirstChild()); break; case Node. ELEMENT_NODE: | i | | os) | System outprint("<"+node.getNadeNemeQs*>"); | NodeList childrens = node,getChildNodest); iffchildrens t= pull} ¢ | for(int =0;i
} ‘System. out, printin(""+node.getNodeName()+">");| break; case Node TEXT_NODE: System. out.print{node. getNodeValue()), break; 8.5.3 Validating KO with While parsing an XML, the parser only checks for well-formness of an XML tt never i checks whether it is valid or invalid, But in a typical business transaction we should ! first validate the XML before parsing it To validate an XML we need either a DTD/XSD, Now we are trying to understand how to validate an XML with an XSD in java using JAX-P API. To validate an XML first of all we need to load the contents of XSD and keep in a java object called Schema, Schema is coming from JAX-P API which means it is an abstract class, The implementation for the Abstract class Schema will be there with resp implementation, in our case with Xerces2, As we don't know who is the implementation for Schema class we need one more factory class called SchemaFactory. White creating the SchemaFactory we need to Pass the input as W3C XML Sciema Namespace URI as input, to indicate we are going to read the contents of XML Scherna compliant XSD, Once we create the Schemafactory we can call newSchema method on it by passing File pointing to XSD as input.After creating the Schema object call a method newVatidator() will gives you the validator object. On this object you can call the method called validate by passing XML as input. If the XML passed is invalid, it throws exception otherwise will not return anything SchemaFactory schemaFactory SchemaFactory.newInstance(XMLConstants. W3C_XML_NS_URI); Schema poSchema = schemaFactory newSchema{new File{XSD_PATH)); Validator v = poSchema.newValidator(); v.validate(new StreamSource(new File(XML_PATH)); before 2 Till now we understood what is SAX and DOM and how to process them using JAX-P. Let us understand what the differences between them are. ‘SAX Dom + SAX stands for Simple Access for + stands for Document Object XML APL Model | + Ttis an event based processing + itis a hierarchical processing model, modet where it loads the entire XML i + It process the XML sequentially one | memory and represents in tree after the other from top to battom structure [+ Tt consumes less amount of + DOM supports random access of memory as at any point of time elements loads only one element into the TE consumes huge amount of : tmemory memory as it loads the entire XMi. i + It is faster when compared with and forms tree structure (Generally ‘ DOM as it doesn’t need to load or form anything. , for 1kb of xml document it takes | 10kb memory ta hold in memory, + SAX is an readonly API, which | which means it multiplies by 10X) means we can just read the XML | + It is slow when compared with SAX documents, but we cannot modify | as it has to represent the XML by or create new. loading it, + DOM isa read and write API using which we can read/modify/create an XML document, In order to overcome the both the dis-advantages in SAX and DOM new processing model came which is STAX, stands for Streaming API for XML. This is uniike SAX event based or DOM hierarchical based, it Is 4 pull based event parser.JAX-BJAX-B stands for Java Architecture for XML Binding; it is the APT that is used for Binding Java Object to XMi. document and XML documents to Java Object back. Let us try to understand, where we can use JAX-B in a typical Web service : communication. As we know in Web service communication always they involve two actors Consumer and Provider. Consumer could be written In any language and even the Provider can also be coded in any language. If we consider a scenario where consumer and provider both are coded in Java Language and now the consumer wants to send some information to the provider. As consumer is a java program he holds the information in-terms of Java Object, so in order to send the Java Object data over the network, he needs to serialize the contents of that object into bits and bytes and has to send to Provider, Up on receiving the serialized stream of data, the Provider will de-sertalize and build back the object for processing, The problem with this approach is Serialization is the protocol proprietary for Java language and non-Java progrems cannot understand serialized data send by java application. So, this breaks the thum® rule Interoperability. So, if the consumer wants to send some information to the provider rather than converting It into serialized stream of data, he should convert the Java Object data to XML representation and should send to Provider. Now provider upon receiving the XML he has to convert it to Java Object and process it. Again Provider instead of returning Java Object as response, he should convert the response Object to XML and shouid send it to consumer as response. The consumer has to convert that incoming KML data to Object to use it, This is depicted in the below diagram. S conser By now we understood we should not use Object serialization for exchanging data in web services rather we should convert them to XML. In-order to work with XML Java has already provided API's for dealing with XML data which is JAX-P. In JAX-P we can use either SAX or DOM parser to convert Java to XML and wise versa.Even though we can achleve this with JAX-P, @ programmer has to write manually the parser’s dealing with this, and more over there arg limitations with JAX-P. Let’s say if a Java Program wants to modify a Purchase Order XML document data, It contains several things like Orderltems, Items and ShippingAddress information. Rather than dealing them as elements, attributes or Text node, it would be easy for 8 Java Programmer to look at them in-terms of Java Objects with data and rnodify them than modifying them as XML. This can be accomplished by using the XML. Binding API's Initially Java doesn’t have XML Binding supported API's; there are lat of third party XML binding libraries are released by software vendors in Java like bX, Castor, XML. Beans, Apache Data binding API, Javolution etc. Then SUN has realized and released its own APE for dealing with XML Binding in Java JAX-B APT”. SUN has even released an implementations for it JAX-B RI (Reference Implementation) aiong with that we have one open source implementations for JAX-B API, JaxMe. Basicelly XML Binding API's are categorized into two types of tools. a) Design Time tools - In these type of tools, there will be an Binding compiler which will take @ Schema or OTD as input and generated supported classes for converting the XML to Object and Object to XML. b) Runtime tools ~ These will not generate any classes rather on fly will take the XML as an input and based the elements names, matches them with corresponding attribute names of the class and will convert XML into Object of the dass. When it comes to JAX-B API It Is 3 design time tool, where it will come up with its own compiler to generated classes to support the binding process, Before proceeding further on JAX-B let us first try to understand its architecture and its offerings. Most of the XML ginding API’s architectures are similar to, what we are discussing now. Ifa Java Object is following the structure of a Java class then that Object is called Instance of that class. If XML document is following the structure of an XSD document can I cali the XML as an Instance of that XSD or not? Certainly the answer for this would be yes. In Java, Object structure would be defined by a class. In XMi, structure of an XML. is defined by an XSD document as shown below,Object as Instance OF Jaya class. uwssumt [Java Class! Tf we try to derive @ logical conclusion from the above, we can understand that Classes and XSD documents both try to represent the structure, so we can create set of Java classes which represents the structure of an XSD document, then the XML document (helds data) representing the structure of that XSD can be converted into its associated Java class Objects. Even the wise versa would also be possible. Let us try to deep down into the above point. How to created user defined data type in Java? Using class declaration. How to created user defined data type in XSD? By using ComplexType declaration. Which means a ComplexType in XSD is ‘equal to a Java class in Java, As XSD document means it contains elements and multiple ComplexType’s so, to represent the structure of an XSD document in Java, itis nothing but composition of various Java classes (one Java class > one XSD ComplexType) representing its structure ‘The below diagram shows a pictorial representation of the above description, oe OBjeck-TF InstanceLet us take the example of PurchaseOrder XSD to understand better,
|
|
“at:orderitemsType pe
‘
s
{
sistring’/> i :
i /xsischema> 'xs:string"/> xsuint'/> maxOccurs="unbounded"/> | In the above XSD we have one element and four ComplexType declarations, as we discussed earlier ComplexType declarations in XSD are equal to a Java class in Java. So from the above we can derive four Java classes as shown below.[elas ShippingAddresstype ¢ class Rem Type ¢ Sring audrestine, | “Sth temcoce String addresstine2, |, int quenety String city; }> String state, int zip; String country; class Orderitemstype { class PorchaseGrdertype ListeltemType> item, OrderitemsType erderttems; + ShippingAddressType shippingAddress) Frorn the above we can create the PurchaseOrderType object representing the root element of XSD, can I hold the PurchaseOrder XML decument data into this instance or not? Absolutely the answer would be yes, because PurchaseOrderType is representing the structure of the XSD document, so its instance can hold its XML, data, With this we understood that we can created the Java classes representing the structure of an XSD document, hence those classes are called as Binding Classes as those are bonded to the XSD document structure and the abjects out of those classes are called binding objects. Now we know that we can convert the XML document data into @ Binding Class ‘Object, so the process of converting an XML to a Binding class Object is called Un Marshalling. And the process of converting a Binding Object back into XML representation is called Marshalling and both the types of operations are supported by any of the XML Binding API's including JAX-B. _ Sill, Instance of XS0 x80 viecoalatng eo ine cha Opgett is Enstance Li EE a ‘The above architecture is the generalized architecture which can be applied to any XML Binding API's including JAX-B.With cur earlier discussions we understaod that a tyaical XMI. Binding API shoud support Un-Marshalling and Marshalling operations. But to perform Un-Marshalling and Marshailing Operations do we need binding classes or not? So, JAX-B supports two types of operations 1) One-Time operations 2) Runtime operations. Let us discuss ther in detail below. One-Time operations ere the operations which would be done only once within the lifetime of an XSD or Binding class, Let’s say I went 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 XSO 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 complex types it would be easy for the developer to determine the relations between the classes and can create Let’s say I have an XSD document in which 106 Complextype declarations are there, is it easy for a developer to develop 100 Java classes representing the structure of 100 ComplexTypes. Even though it seems to be feasible, but it is a time taking task. So, instead of writing the Binding classes manually, JAX-B has provided a tool to generated Binding classes from XSD called XIC. And Eo generate XSD from a Binding class there Is another tool called Schemagen. If T have an XSD document, how many times do I need to generate Java classes to hold the data of its XML? It would be only once, because classes will net held data they just represents structure, so instances of those classes holds data of an XML. Even the reverse would also be same. As we need to generate the Binding classes or XSD only once this process is called one-time operations. And there are ‘two types of one-time operations. a) X3C ~ XSD to Java compiler - Generates Binding classes from XSD document b) Schemagen ~ Schema generator ~ Generated XSD document from an Sinding class. Point to recollect: - We said JAX-B is a design time tool, if you see now it has a binding compiler which will generates classes at design time,XIC or Schemagen are the toals that will come when we install JWSDP. JWSOP. stands for Java Web Service Developer Pack and it is software which offers development tools and libraries with which we can work on Web Services related technology applications {for example JAX-P, JAX-B, SAA), FastInfoset, JAX-RPC and JAX-WS etc), When we install JWSDP by defauilt it would be installed under ¢:\Sur\JWSDP-2.0. Under this directory it will have one more directory called 1AX6 this is the directory under which ali the JAXB related tools and jars would be located. > CASun\WSDP-2.0 [= JAXB [= hb Je> bin |» soc.bat, xje.sh, schemagen.bat and schemagen.sh From this directory I can run xjc.bat or schemagen.bat to generate Binding Glasses or XSD document respectively. Most of the times we use xjc tool rather than schemagen tool. Because we will start with XSD most of the time to work on XML binding APIs, So let us first try to understand how to execute XJC, the same can be even cared for schemagen as well XJC compiler will take input as XSD and will generates set of binding classes. Now where should 1 generate these binding classes, do I need to generate them in the JAXB\bin directory or by Project Folder “src” directory? The answer would be should generated in your project source directory, So to generate under source directory of your project you need to run the XJC.bat from the Project directory rather that the JAXB\bin directory. To run it from project directory we need to set the system path pointing to it as shown below. + C:> set path=%epath%;c: \sun\wsdp-2.0\jaxb\bin, After setting the path, we need to switch to the project directory. For example if your project is under D:\ drive and the folder is Sample you need to switch to the Sample directory under D:\ drive and should execute the XJC.bat by giving XML as input as shown below. » C:> ed D:\Sample » Xje -d sre resources\po.xsd In the above command we are saying take the po.xsd as an input under resources directory (from the current directory) and generate the binding classes under (-d represents the directory) sre directory in my Sample Project.When we run XJC.bat by giving XSD as an input aleng with generating binding classes it generates fexwother things as explained below, 4) Generates Package based on the Namespace - In an XSD document, it woutd contain an XSD namespace declaration, Namespaces in XSD similar to. packages in Java. So when XIC is generating Binding class for every ComplexType declaration. It would have to even consider mapping the XSD Namespace to package name and should generate the classes under that mapped package (because the ComplexType declared under targetnamespace are bonded to Namespace, so those classes have to be bonded to packages). XIC by default will uses a mechanism to map a Namespace to package in Java as shown below, |TargetNamespace in XSD ~ http://ebay.in/sales/types Package Name In Java — ignore http: // or www Find the first “/" forward slash and extract the substring (ebay.in) Now delimit by *.” (dot) and extract tokens in reverse order in.ebay In the remaining string “sales/types” delimit by °/" forward slash and append them to the first constructed package name The resulted package name would become in.ebay.sales.types. All the binding classes would be generated into the above package | b) Package-info.java ~ XIC after mapping the namespace to @ package narne, it would store this mapping information into a class called package-info.java, This | also generated under the above mapped package only €) ObjectFactory java - These Class Acts as factory class, which knows how to create objects of all the Binding classes generated. It contains methods like createXXX, upon calling these methods it would return respective binding class objects, 4) Set of Binding classes ~ With the above it generates Binding classes representing the structure of each ComplexType in XSD. Can we call any java class as Binding class? No, the binding classes are the classes which are bonded to XSD complexType declarations and to denote this relationship, those are marked with JAX-B annotations as described below. i. @XMLType - To the top of the binding class it would be marked with @XMLType annotation indicated this class is representing an XML. Complex Type i, @XMLAccessorType(AccessType, FIELD) ~ In conjunction with @XMLType, one more annotation @XMLAccessorType(AccessType. FIELD) also would be generated, It denotes how to map XML elements to Binding class attributes, With the AccessType,FIELD we are saying the elements names must be matched with binding class attributes names to port the data Wi, @XMLElement ~ This annotation is marked at the attributes of the Binding classes to indicates these actributes are representing elements of XML,So, by the above we understood that not every Java class is called as Binding class, only the classes which are annotated with JAX-B annotations are called binging classes. So from the above binding classes we can even generated XSD document ay running the Schemagen tool as welt, this is left to you as exercise. With this we understood how to perform one-time operations. Now we can proceed on runtime operations. Till now we discussed about how to perform one-time operations. Let us try to. understand Runtime operations. JAX-8 supports three runtime operations. @) Un-Marshalling ~ The process of converting XML. to Java Object b) Marshalling - The process of converting Java Object with data to its XML equivalent ¢) In-Memory Validation ~ Before converting an XML document to Java Object first we need to validate whether the XML conforms to XSD or net would be done using In-Memory Velidation If we want to perform runtime operations, first you need to do one-time ‘operation. Uniess you have binding classes or XSD equivalent for any existing binding class, you can’t work on runtime operations. By following the things clescribed in earlier section we assume you already completed the One-Time operations and you have binding classes with you. Let us try to understand how to work on each of the Runtime operations in the following section. 1 um Marshotling As described earlier, the process of converting an XML. document into Java Object is called Un-Marshalling. In order to perform Un-Marshaliing, you need to have Binding Classes with you. You can generate these by running XIC compiler. If you run XC compiler on the po.xsd which was described earlier, the following binding classes will be generated shown below.package org amazon types sales; i | @XmiAccessorTyne(AcoessType. FIELD) | @XmIType(name = *shippingAddressTyoe", propOrder = ¢ | “eddressLinet*, | “addresstine2" j “eity", ' “state", | Tze. “eountry* » public class ShippingAddressType { | | @XmlElement(namespace = "http: //amazon. ora/types/sales") protected String addressbine1; ‘@XmiElement{namespace = "http://amazon.org/types/sales") | protected String addresstine2, ‘@XmiElement(namespace = "http: //amazon. org/types/sales") | protected String city; @XmiElement(namespace = “http:/Jamazon.ora/types/sales") protected String state; @XmiElement(namespace = “http: /Jamazon.org/types/sales", type = Integer.class) protected int zip; ‘@XmlElement(namespace = “hetp://amazon. org/types/sales") | protected String country; A setters and getters ¥ package org.amazon. types. sales; @xmiAccessorType(AccessType. FIELD) @XmiIType(name = "itemType", propOrder = *itemCode", “quantity” | » public class TtemType { ‘@XmlElement(namespace = “http: //emazon.ora/types/sales") protected String itemCode, @Xmiglement(namespace Integer.class} protected int quantity; ‘htt: /Jamazon.org/types/sales", type = Uf setters and getters | package org.emazon.types. sales; @XmiAccessorType(AccessType. FIELD) _F@xmitype(name = “orderitemsType", propOrder item" y) _ puplic class OrderItemsType © | @xmiciement(namespace = *http://emazon.ora/types/sales”) protected List
item; public List
getitem{) ¢ if {item == null) { item = new ArrayList
(};, } return this.item; oy package org.amazon.types.sales; @XinlRootElement @XmlaccessorType(AccessType. FIELD) | @XmiType(name = "purchaseOrderTyp: | torderttems", “shippingAddress" » public class PurchaseOrderType { @XmiElement(nemespace = "http://emazon.org/types/sales") protected OrderitemsType orderltems; @XmiEiement(namespace = “http:/Jamazon.ora/types/sales") protected ShippingAddressType shippingAddress; { + Package-Info.java ‘@yavax,. xml. bind. annotation. XmISchema(namespace = "nttp://amazon.org/types/sates") package org.amazan.types.sales;[package ord amazon.types sales; | @xmiRegistry i | Public dass ObjectFactory { private final static QName _PurchaseOrder._QNAME = new | QName("“http://amazon.org/types/sales", "purchaseOrder"); public ObjectFactory() { > public ShippingAddressType createShippingAddressType() { return new ShippingAddressType(); | + public OrderitemsType createOrderltemsType() { | return new OrderltemsType(); > | public PurchaseOrderType createPurchaseOrderType() { | Feturn new PurchaseOrderType(); | + public ItemType createltemType() { return new ItemTypet); + @XmiglementDecl(namespace = "http://amazon.org/types/sales", | name = "purchaseOrder") public JAXBElement
createPurchaseOrder(PurchaseOrderType value) { return new JAXBElement
(_PurchaseOrder_QNAME, PurchaseOrderType.class, null, value); 3 Oh Having the binding lasses will not automatically converts the XML document into Object of these classes, rather we need a mediator who would be able to read the contents of the XML, and identify the respective binding class for that and creates objects to populate data. This will be done by a class called “Unmarshalier’, As JAX-B is an API, so Unmarshaller is an interface defined by JAX-B API and its JAX-B API implementations (JAX-8 RI or JaxMe) contains the implementation class for this interface. ‘The object of Unmarshaller has a method unmarshal() , this methed takes the input as XML document and first check for Well-formness, Once the document is, well-formed, its reads the elements of the XML and tries to identify che binding lasses for those respective elements based on @XMLType and @XMLElement annotations and converts them into the Objects. We have two problems here1} How to created Un-marshatler as we don’t know implementation class 2) Where does un-marshatler should search for identifying a binding class (is it in entire JVM memery or classpath?) As we don’t know how to identify the implementation of Unmarshaller interface, we have a factory class called JAXBContext who will finds the implementation class for Unmarshaller interface and would instantiate. It has a method createUnmarshalter() which returns the object of unmarshaller, This addressed the concern #1. While creating the JAXBContext, we need to supply any of the three inputs stated below. 1) Package name containing the binding classes 2) ObjectFactory.class reference as it knows the binding classes. 3) Individual Binding classes as inputs to the JAXBContext, JAXBContext jaxbContext = JAXEContext.newinstance(*packagename” or “ObjectFactory.class” or "BC1, BC2, BC3.."); With the above statement, the JAXBContext would be created and loads the classes that are specified in the package or referred by ObjeciFactory or the Individual binding classes specified and creates a in-memory context holding these, Now when we call the Unmarshalier.unmarshal{} method, the Unmarshaller will searches with the classes foaded in the JAXBContext and tries to identifies the classes for an XML element based on their annotations. The cade for UnMarshalling has been shown below.package com.pe,unmarshall; public class POUnmarshaller { public static void main(String args{]) throws SAXException { mye JAXBContext jContext = JAXBContext snewInstance("“org.amazon.types.sales”); Unmarshalier poUnmarshaller = iContext.createtinmershaller(), JAXBElement
jlement = (OAXBElement
) pounmarshatler { -unmarshal(new File( “D:\\WorkShop\\Frainings\\aug, | 2011\\Web Services\\PO}ax8\\resourcestipo.xml")); PurchaseOrderType poType = jelement.getVaiue(); System. out.printin(poType.getShippingAddress(). getAddresstinet()); ‘System, out. pnntin(poType.getOrderltems( }.getltem().get(0) getltemCode()}, } catch (AXBException e) { e.printStackTrace(); + chatting Marshalting is the process of converting the Object data to XML, For performing Marshalting also we need to first of ali have the Binding classes. Once we have the Binding classes, we need to create the Object of these classes and should populate data in them, These objects can be marshalec te XML using the Marshaller, Again Marshatler is an interface, to instantiate it we need JAXBContext, Then we need to call 4 method marshall by giving input as XML and Qutputstream where we want to generate the output to, The below program depicts the same.package com.po.unmarshall; public class POMarshaller"{ public static void main(Steing argsti) ¢ ny JAXBContext Context = JAXBContext newlnstance({"org.amazon,types. sales"); Marshaller poMarshaller = jContext.createMarshailer(); ShippingAddressType shippingAddress = new ShippingAddressType(); shippingAddress, setAddressLinel("121/A"}; shippingAddress.setAddresstine2(“Punjagutta PS"); shippingAddress.setCity(" Hyd"); shippingAddress. setState("AP"); i shippingAddress.setCountry("India"); shippingAddress. setZip(24244); itemType itemt = new ItemType(); item1.setItemCode("IC2002"}; item setQuantity(34}; ItemType item2 = new ItemType(); ttem2.setitemCode(*IC2003"); itemn2 setQuantity(1); OrderitemsType oit = new OrderitemsType(); oit.getItem().add{item 1); olt.getitem().add(item2); PurchaseOrderType pot = new PurchaseOrderType(); pot.setOrderltems(cit); pot. setShippingAddress(shippingAddress); poMarshaller. marshal(pot, System.out); } catch (JAXBExcention 2) { e.printStackTrace(); While performing the Unmarshalling or Mershalling, we need to first of all validate whether the XML is valid against the XSD document or not, and we will validate using the in-Memory validation, An XML can be validated against an XSD document, so we need to read the XSD- document and should represent it in a Java Object called Schema,But Schema Is an interface and to create the Object of interface, we need factory called SchemaFactory, But schema factory can created various types of XSD documents, so we neecte provide the grammar of XSD document which you want to load or created and would be done es show below, | SchemaFactory sFactory = Schemafactory.newlnstance(xMLConstants. W3C_XML_SCHEMA_URI); With the above we created a SchemaFactory which is capable of creating or loading W3C XML Schema tyne documents, Now we need to load the XSD document into the Schema class object as shown belor — | Schema poSchema Factory newSchema(new File("po.xsi Once the schema object Is created holding the structure of KSD, we need to give it to Unmarshaller before calling the unmarshal(). So, that Unmarshalier 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 haw to perform in-memory validation. package com.po.unmarshall; public class POUnmershaller ¢ public static void main(String argst]) throws SAXException { ‘SchemaFactory sFactory = SchemaFactory snewInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); ‘Schema poSchema = sFactory shewSchema(new File("po.xsd"))} JAXBContext jContext = JAXBContext newInstance(“org.amazon.types.sales"); Unmarshatler poUnmarshalter = jContext.createUnmarshaller(); poUnmarshaller.setSchema(poschema); JAXBElement
jElement = QAXBEtement
) poUnmershaller sunmarshal(new File(*pe.xmi)); PurchaseOrderType poType = jElement.getValue(); System.out. printin(poType.getShippingAddress().getaddressLinei()}; System, out.printin(poF ype.getOrderlterns(),getitem( }.aet(0) -getltemCodet);JAX-RPC12.3 Ways af devele: Before discussing about JAX-RPC APE based Web Service development, first we need to understand certain aspects related to Web Services, The points we are discussing below are common for both JAX-RPC and JAX-WWS as well. 2 PvE % As discussed earlier, we have two types of Web Services JAX-RPC API adhering the SP 1.0, and JAX-WS API adhering to BP 1.1, Now while developing a Web service, first of we need to choose a type. After choosing the type, we need to select an appropriate implementation and various other aspects described in Followina ' sections. Always a Web Service development involves two parts. Provider and Consumer. Provider is the actuat Web service, who will handle the incoming requests from the consumer. The Consumer is the Client Program which we develop to access the Provider. Now both JAX-RPC and JAX-WS API's has provided classes and interfaces to develop Consumer as well as Provider programs. ga Web orice, i ‘There are two ways of developing a Web service 3.4 Fi In Web Services, WSDL acts as a contract between Consumer and Provider. If consumer wants to know the information about the provider, he needs to see the WSDL document, In a Contract First approach, the development of the provider will starts with WSDL, from which the necessary Java classes required to build the service would be generated. As the development starts from WSDL, hence it is called Contract First approach. 40.9.2 Ganteact Last approacty Here the devetoper first starts developing the service by writing the Java code, once done then he will generates the WSDL contract to expose it as a Web Service. As the contract is belng generated at the end after the development is done, this is called Contract Last approach. 14.4 Chaaging an Endpoint In Web services the provider is often referred as Endpoint, as he is the ultimate Point from whom we request data o information, Now in @ typical Web Service communication, the consumer will sends the initial request with some data to the Provider. The consumer cannot send Object data over the network; rather he needs to convert it into XML and needs to place the XML into SOAP XML. Then the SOAP XML is being transported over the HTTP Protocol, This means the consumer will send @ HTTP request, in order to receive the HTTP request being sent by the consuiner, at the Provider end we need toi. have a HTTP Listener, The listener will listens for the incoming request and forwards it for further processing as shown below xe consumer HTTP Suev at EIR provider Protocol So we understood we need a listener at the provider side to handle the incoming request. Do we have any existing API's in Java which are capable of handling incoming HTTP Requests? Those are nothing but Serviet or £8. ‘There are two types of Endpoints, where a developer can choose while developing a Proviger. dfnrekel Eadpsint Here at the provider end, the serviet acts as a listener in listening for the incoming request from the client and would process. EIB Beays In place of Serviet even we can substitute it with EB, and we can make EI8’s to handle even HTTP Request as well. Most of the people prefer to use Servlet endpoint rather than EJS endpoint as EIB seems to be heavy and costly component, and for the sake of developing Web services, the application needs to be hosted on an EJB container. 3 tessa: tig Message exchange format talks about how a consumer does exchanges inforrnation with the provider. This could happen in three ways as described below. tery 5.4 Synchronous raguest/resiy In this pattern, the consumer sends the request with some data and will waits tifl the provider finishes processing request and returns the response to the consumer.For e.g. let's take two classes A and B as shown below ic class At public BE or public void dot} public int execute() { Bb = new 8); di some logic | int I b.execute(}; // blocked return 33; | {7 some other processing > | 3 } | + Class A is calling @ method execute() on B, until the method execute() finishes execution and returns value, the dot) method will be blocked on the execute) method call, as it is blocked on method call, # is called blocking request/reply or synchronous request reply. In this case also the Consumer program would be blocked on the Providers method call (request) and will not proceeds execution until the Provider returns response. Which means the Consumer opened HTTP Connection would be open till the Provider returns response, In this pattern, the Consumer will not be blocked on the Providers method callfrequest, rather after Consumer sending the request; he disconnects/coses the HTTP Connection. The provider upon receiving the request will hold it and process it after certain amount of time, Once the response is ready will opens a ew connection back to the Consumer and dispatches the response, For e.g, let us consider an example like you are sending a letter to your friend, when you post the letter it would be carried by the postmaster to your friend, ‘Once the letter has been received, your friend may not immediately read the letter, rather when he finds leisure he will reed, Till your friend reads the letter and give the reply the postmaster can't wait at your friends door rather he moves on, Now when your friend reads your letter, then he will reply to your etter by identifying the from address on the letter and post back's you the reply. As the response here is not immediate and is being sent after sometime, this is also called as Delayed response pattern. S. 9 tine wey braver pf dea ge 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. wage Exeba ‘ This describes about how the consumer will prepares/formats the xml message that should be exchanged with the provider,For e.g. a lecturer is dictating the notes, every student has their own way of writing the notes. Someane may right the notes from bottom to top, others might right from top to battom. In the same way, in order to send information, the consumer has to prepare his data In XML format. How does consumer represents the data in the XML document is calied Message Exchange format, ‘The message exchange format would be derived by two parts 1) Style and other is 2) Use. 9) Style - The possible values the Style part can carry is rpc and document b) Use ~ This could be encoded and literal With the above it results in four combinations as rpc-encoded, rpc-literal, cocument-literal and dacument-encoded. Out of which decument-encoded is not supported by any web service specification ‘We will discuss the remaining three in later sections,G1 fre mine 1} In this section we will try to Unéerstand how to work with JAX-RPC API Web services using JAX-RPC SI {reference implementation provided by SUN) Implementation, By default any JAX-RPC API based web service uses the default message exchange pattern as RPC-Encoded, Before developing @ consumer, first they should be @ provider to access it, So, let us start first with Provider Development. As you know there are multiple things you need to consider while building provider, we are developing here JAX-RPC SI ~ Contract Last ~ Serviet Endpoint ~ Sync req/repl ~ REC-Encoded Service, you ref reply weit py As you know always from architecture point of view, the contract between provider and consumer is WSDL. Here always the service development would be storted with Java and at the end, contract would generated, as the contract is being generated at the eng, it is called contract last approach, As we are Java programmers, it would be easy for us te start with Java rather than with WSDL, so we are trying to understand development of the provider using Contract Last. Let us try to under step by step, how to develop a JAX-RPC SI service in contract last approach, a) Write SEI Interface ~ Always from an architecture point of view, the contract between the consumer and the provider is WSDL. From Java point of view, the contract between consumer and the provider is interface. How does the consumer knows the number of operations exposed by the provider, declaratively he can see it in WSDL and from program perspective he can refer the Interface, ‘The Web service development always starts with SEI interface, stands for Service Endpoint Interface, As it describes the entire information about the Provider (service), it is called Service Endpoint Interface, It acts as a contract between Consumer and Provider, All the methods declared in the SEI interface are exposed as Web Service methods, There are certain rules you need to follow while writing SEI interface in JAX-RPC API described below i) SEI interface must extend from java.rmi,Remote interface - The methods declared in this interface are by default exposed over the network and can be accessed remotely, to indicate that, it has to be extended from Java.rmi,Remote, In addition to this, to differentiate a normal interface toa remotely accessible interface, it has to extend from Remote,li) Declare all the methods which you want to expose as Remote methods ~ If you want to expose five methads as Web service methods, all those five methods has to be declared in SEI interface, Only the methods declared in SEI interface are exposed as Web Service methods or remote accessible methods, others would be treated as locet methods iif} Web Service methods shoutd take parameters and return returnvakies as ! Serlalizabie - The methods we deciare in SEI interface should take parameters as Serializable, and even return values must be serializable. i) Should throw RemoteException ~ SEI interface methads should throw RemoteException. Let us say a program along with performing some operation; he is trying to access the Web service. Refer to the below snippet class BookInfoRetrelver { public void findBook(int isbn) ¢ try Booklnfo info = // call service and get Book info // perform something using bookInfo } catch(RemoteException re) { } catch(NullPointerException npe)¢ > Now in the above code, we are trying to get the book information by i calling the service, after getting the BookInfo, we are computing i something with the data. While executing the findBook method an exception was occurred, how do I need to find whether the exception wes caused due to Web service call or the local code has thrown the error? If the type of Exception being caught is RemoteException, it indicates a Remote program has caused the error. Otherwise would be considering as focal code has raised the exception In order to differentiate between local exceptions and Web service exceptions, my SEI interface Web service method should always throw RernoteException, In addition to this, even your method is declared to throw RemoteException, the code inside your method may net be throwing exception at all. Tn such conditlon, why should 1 declare it to throw? Your code may not be throwing the exception, but while client sending a request to the provider, they could be some network failures, In such cases the Web service runtime will propagates such failures to the client by throwing Remotetxception to the User, so by declaring RemoteException you are always preparing the consumer to handle.b) With the above rules, let us try to write an SEL Interface as shown below. package com.store servte; import java.rmi.Remote; import Java.rmiRemotetxception; 11 SEL public interface Store extends Remote £ float getBookPrice(String isbn) throws RemoteException; 3 Provide Implementation class - Write a class which implements from SEt : interface, your implementation class must provide implementation from all the methods which ere declared in SEI interface. Implementation class could contain some other methods as well, but those will not be exposed as Web Service methods, Your web service methods overridden fram SEI interface may or may not throws Remote Exception. ‘The Implementation class methods will contain business logic to handle and process the incoming requests, but the logic you wrote here may or may not raise any exceptions, In a case where your logic is causing any exceptions, you don't need to deciare your method to throw RemoteException. But if your business logic is raising a NullPointerException or SqlException, the class should not throw NullPointerexception or SglException rather those exceptions has to be caught in try/catch block and should wrap those exceptions into Remotetxception and should throw to the Consumer, Below snippet shows the Implementation class for the abave SEI Interface,package com.store,service, Import java.emi.RemoteException; | public class Storeimp! implements Store { public float getBookPrice(String isbn) { Float price = 0.0%; HF (null |= Ssbm && F™sequats{isbn)) i connect to do df query table 1] get data and return if (*ISBN1001" equats(isbn)) : price = 232.23; } else f (*ISBN1002",cquals(isbn)) { i price = 242.356; 3 3 return price; + Le €) Generate Binding classes - After developing the SEI interface and Implementation classes we need to run @ tool catled wscompile to generated binding classes. > What tools are available? ‘The wscompile tool is shipped as part of JWSDP. For developing a JAX-RPC API RI based Web service we need some set of tools/compilers to generate some classes similar to we generate in JAX-B, but where are these tools under? These tools are available to you when you install JWSDP, Basically we will use two toois for JAX-RPC API RI based web service development. 1} Wscompite ~ Used for generating binding classes from SEI interface or wsoL |} Wsdeploy ~ Used for generating service related configurations which are required to deploy your service.Both these tools ere shipped as part of IWSOP when you install and are available under the below folder. Ci>Sun\WSDP-2.0 {> jaxrpe }-bin {+ wscomplle.bat, wscomplle.sh, wsdeploy.bat, wsdeploy.sh > Why to run wscompile? Now let us try to understand why I need to generate binding classes? As we know the Consumer wil send's the request to the Provider requesting for some data or processing, Here sending the request to the Provider is nothing but invoking 2 method on the Provider for e.g. in the above code he will call getBookPrice method to get the price of the book While calling this method, the consumer needs te send data required for executing the method. Does the consumer need to send the Java type data? He shouldn't rather send XML equivalent of it for example if it is rpc-encoded, the request XML will look as shown below, ‘
|
|
| -
‘
}
|
Along with configuration file he needs to specify some more switches while running the command as described below, wa stands for directory under which you want to generate | the source files [S-genserver” | The binding classes generated by wscompile tool are. required by both consumer and provider to exchange data, but the classes generated at Provider side would be different from classes that are generated at Consumer side, The wscompile too! is designed to | generate both Provider side as wetl as Consumer side Glasses, But while running the tool you need to specify whether you want to run it Server side or client side Here “gen:server” indicates Provider side classes ~-keep” wscompile tool will takes the SET interface and | message encoding format, generates the binding Classes, After that it wil compites the binding classes and deletes the source files generated. If you want to retain the source files which are generated you need to use *-keep” | As we know wscompile tool will takes the SEI interface as input and generates binding classes. So in-order to | read the method signatures in the SEI interface, does the wscompile takes the Source of SET as Input or its class file? Always the class files are compiled outcomes which| doesn't have any syntax errors, so tools will always 1 takes the class files as input rather than source, | So using “-cp" we will specify the location of class files Hf config.xml contains a
or
element, wscompile generates a model file that contains the internal data structures that describe the service. If you've already generated @ model file In this manner, then you can reus For example: it the next time you run wscompile,
—L Below is the piece of code showing how to run the command? wscompile ~gen:server ~d src ~cp build\classes ~keep model-rpc-enc.xml.gz
\config.xenl With the above command, the wscompile reads the contents of the config. xml and Identifies the SEI interface an¢ Implementation class and validates against all the rules in ienplementing them. Once those are valid, it starts reading the methods of the SEI interface and generates the following artifacts[Reawesisiruct — | Tepresenting the structure of request | xml representing the structure of response xml | ReauestStructSOAPSerializer/Builders ResponseStructSOAPSerialiaer Tie a Model wsoL 7 | | | ‘These classes knows how to convert request XML into RequestStruct class objects This knows how to conve ResponseStruct object to response XML Who facilitates the processing of request Contains the internal data structures using which we can recreate the service | Describes the information about the service If you observe the above, the WSDL has been generated taking the input as Java classes and hence this is called Contract Last approach. With this above we generated all the classes that are required to facilitate the conversion of XML to Java and Java to XML at the Provider side for every method. mi d) Write jaxrpe~ After generating the necessary binding classes te expose our class as service, we need to configure the endpaint Information of our service in a configuration file called jaxrpe-rixmi As how you write web.xml to attach for @ Serviet an URL te access, for even your Web service class we need to attach an URL to expose It as an service so that Consumers can access the service by using the URL we specified here. Here we configure the complate endpoint information atong with attaching it to an URL to access as shown below. Note: - The file name should be jaxrpe-ri.xml and it is mandatory te use the same file name you should place this file under WEB-INF dicectory only.| [
tp://Java.sun.com/xml/ns/jax-rpe/ri/runtime! ='com.store service Sterelmpl’ ‘com, store. service, Store_Tie! '/WEB-INF/wsdierpc-enc.xml.g2" ‘/WEB-INF/StoreService. wsdl’ service='{htip://safaribooks.com/books/sale} StoreService’ port="{http://saferibooks.com/books/sale)StorePort* uripattern="/store’/ > =| re | a From the above configuration it picks up the Tie class name matching the Servlet Path and forwards the request to the Tie for further processing. Tie class has the logic for processing the SOAP XML, and extracts the actual XML from the SOAP Body and then passes it to request SOAP serializers/De-Serializers to convert into Java Object, Then passes the Object data as input to the Service method. Once the Service method finishes processing, it returns Java Object data as response to the Tie, Now Tie converts this back into XML and then inte SOAP. XML and places it into HTTP Response Message and sends back it to the Consumer.New Dynamic Web Project The following section walks you through the detaifed steps of creating the Service using the above described steps in Screen shots. Create @ new Dynamic Web Project in eclipse, expand the Project directory a1 Aavigate into WebContent/WEB-INF/Iib directory, Copy/paste all the jaxrpe jar’s that are given In Jar bundles folder to the above li project, Configure the Bulla path by right clicking on the project, select configure build path and switch to libraries tab and add ali the jar’s in the lib to the Project class Path tigate Taba meet sects tock Bane oe Based ne Bevnpee Becton Bowe Write SEI Interface - package 2 dant + Hy oilman Oren baieWrite SEI Implementation class Fae ea 5 | phckage = 2 paid * #s Desloymert eset: Sekine ab snes ie sencee 5 Bina Rewires aBec \ public float getscokPrice (String float price = 0.6: mi Jnaserp resources sete | Af isbn != mull af lisbavequais(™")) bern | Sf (isbn.equals(*rseice1")) 1 cen | peice = 242.21 Boome | ) else 42 (20a. ) Braise | price = 453. Eecwr | ) | irae | i apc Bae | ston toy i Bose ' Gropatenw ae = asc © Brwpomsec treo tte . fiom tanocee ae z oa a oa | samen 3 anne S|] emir E neigus x 3 e = § || 2 | 3 i 2 t As explained earlier WSCOMPILE tool will generates the binding classes by taking o S| the config.xml as input. As you have to generate the binding classes into & § Project Sre directory, you need to run the tool from Project directory. So you § need to set First of all the System Path pointing to the location of WSCOMPILE a“ 3 bat file, end then switch to the Project directory and run WSCOMPILE as shown below.j Sultch to Project directory for example | | Cd D:\Folder1\Folder2\Bookweb If you execute DIR command under this directory you must see “src” till then you need to navigate. Now execute the below command wscompile -d src ~gen:server ~cp build\classes keep -verbose ~model model- rpc-enc.xml.gz WebContent\WEB-INF\config.xml SMU Drag and Drop WSDL and Model files generated into WebContent\WEB-INF Output of wscompi directoryWrite jaxrpe-ri.xml cwebServices malns="hbtp://java.su Book” jescription="A simple Book Service" /WEE-INF /BockService. wsdl" interface="com.bookweb. service. Book" implementation="cam.bookweb. service. Book Impl” model="/WEB-INF/mode1-rpe-enc.xm1.gz"/>
i Export the project as WAR soho ce Requeststruf ce Requestsrud binding 1) Booking ove WAR Export Export Web project tothe loca le system, Web projet: | Bookiieb Restination: | C:iBookweb.wwar ‘Torget runing Cloptimize for 2 specie server runtime Clerport soures Hes EnQvenunte Sastina ieMires a) Open Favortee sis7012 133 srmi2 1223 Extract the generated WAR po. p Fite JARAL XML Document a 2s JANA) NIL Document Now the generated web.xml and jaxrpc-ri-runtime.xml generated here should be copy pasted into the
\WebContent\WEB-INF and override. Copy/Paste extracted files |res Add and Remove Moai resources that are configured onthe server Booed ‘Move resources to the ight to contgure them on the server salable: Configured: » asoliver snsee binding [
Address: Imp: keethost 8080 Book Web getPrice j Ws0L peas S80 Sooke" BY] sce bree Port QName: (hip: booksericecrz sl)BookPort Remote merce combookweh senice Book Implementation clas: com book serie Bocklaph Modet pTocahore S080 Book Web getPice7model You can test your service in SOAP UI by importing the WSDL — inontract First (Serviet En: This is no way different from, contract last approach, all the request processing flow and other concepts (serializers/de-serializers) will still applicable even you develop the service using contract first approach. Only difference would be the way you are developing the service. Sync req/reply with rpc ded As indicated earlier, you can develop a Web service in two approaches contract first and contract last. We already discussed about contract last approach. Now we are trying to build the Provider using contract first approach. In web services, the contract between provider and consumer is WSDL, as it is contract first approach, the development will starts from WSDL rather than from Java. Now the developer has to write the WSDL document from which he generates the necessary java classes to expose it as service. By looking at the WSDL ~ PortType we can create the SEI interface and based on the operation input and output types we can create method with parameters and return types. We need serializers and de-serializers to map incoming XML data to method parameters and return value of the method to XML back.Sample WSDL document is provided here for your reference. t
‘
‘
rem" type="xs:string" /> ‘quantity” type="xstint™ /> s:string" /> xs:string” /> rder">
‘
soapActior ‘encoded" />
Instead of developer writing the above classes, we can run the wscompile tool which is shipped as part of JWSDP by giving input as WSDL. Now the wscompile will loads the WSDL document and reads various elements of WSDL and generates the required classes to build the Web service. Following are the classes generated when we run wscompile. | SET Interface Will be generated based on PortType in WSDL [Input/Output classes You SEI Interface methods will take parameters | and by looking at the PortType operations we | will know what are input/output elements. Based on this we can find their relevant XSD types and can generate classes representing input/output parameters of the SEI Methods. Request/Response Struct, These classes are required to convert the input Serializers and Deserializers _| XML to Object and Object back to XML Service Interface and Impl Required for building Consumer (we can ignore this class if we are building Provider)‘As we know wscompile will not directly takes the WSDL, rather we need to write the config.xml and need to configure WSDL location in it rather than SET interface and Implementation. Nowe give this config.xml as input to wscompile so that it generates the classes required to build the Web service. config.xml
‘
|wscompile ~gen: server ~d src ~keep ~verbose ~model model-rpe-enc.xmi.gz |WebContent\WEB-INF\config.xm As all the classes are available to build the Service, we need to write now the Implementation class implementing the SEI interface. Then we need to write the Jaxrpc-ri.xml, which attaches url to the endpoint. Now export the project as war and run wsdeploy tool by giving war as input wsdeploy -o target.war source. war It will generate the target.war which contains the jaxrpc-ri-runtime.xml and web.xml. Copy these two files into the project WEB-INF directory and deploy the project and start the server. You should be able to access your Provider/Service.11.1.5 Contract First- Activity Guid The following section walks you through the detailed steps of how to create JAX- RPC SI based service using Contract First approach As it is contract first approach, the developer has to write the WSDL document identifying the Service and its operations. Need to place the WSDL document in WebContent/WEB-INF directory § a Pertnneenen ie caren = £ ~ k?xml version="1.6" encoding="UTF-8"?> 3
2
poe | -
“ntte://java. sun..com/xal/ns/Jox-r} "webContent /WEB- INF/PurchaseOrderse:| Now we need to run the wscompile tool to generate classes by giving Input 2 asconfig.xm! . £ | wscompile ~gen:server -d src -keep ~verbose -model model-rpc- § _enc.xml.gz WebContent\WEB-INF\config.xmi 2 _ (if you observer -cp is not there as we are not providing any classes as Z § input rather it reads the wsdl) il _ =e — 2 [e Purchasedraerved . Sac | Zz Bi Apache Tomcat 6.0 [Apac| a Si ve igplinats | o | 5 i & (> METAANE I 2 2 > WEB.INE | = Sib 3 Bi cortigent 3 28 japet-untimese € a jarpe-riaet i g 1 PurchaseOrdeseni = We need to provide the endpoint configuration in jaxrpe-rixml. Here we ‘map the endpoint with an url, from which the jaxrpe-ri-runtime.xml and web.xml would be generated by wsdeploy tool. Note: - We need to place this file in WEB-INF directory and the file name should be jaxrpe-ri.xml only. gE cendpoint ‘name: "Order $ displayNane: 4 e descriptions "Used for finding price of book" x wsdl="/ES-INF/PurchaseOrderService.wsdl” 5 interface="con. purchaseorder. service. Order” 2 inplenentations ‘com. purchaseorder. service. Orde = odel="/NES-INF/wsdl-rpe-enc.xml..g2"/> z
«lastener-class>¢om.sun.xml. rpc. sei
«servlet -name>0rder
com.sun.xml. rpc. ser
1¢/load-on-starty
Order
[
/erder
Now run the wscompile tool by giving the above config.xml as input. While Funning as we are developing the consumer, we need to use ~gen:client as we need consumer side binding classes. As we don’t have any classes right now we don’t need to specify ~cp. The command reference and set of classes that would be generated are shown below. wscompile -gen:client -d src -keep ~verbose config\config.xml SET Interface Required to know the methods that are available at Provider side | Stub Implementation of SEI interface at the Consumer side contains the logic for sending the request and extracting the response from the Provider Service/Impl Factory, knows how to create the object of Stub 1e-Serializers Facilitates in converting Object to XML_| and wise versa Request/Response struct Classes represents the structure of input/output XMLIf you open the generated Stub class it clearly indicates as implementing from SEI interface and it overrides the methods in the SEI interface, but those methods will nat have business logic, ratfier they have the logic for converting object data into XML, and send over the HTTP connection to the Provider. package com.store.service; public class Store_Stub extends com.sun.xml.rp implements com.store.service.Store { \__[ Implements SEI // skipped code for clarity ee public float getBookPrice(java.lang.String string_t) | throws java.rmi,RemoteException { ape Overrides try { method StreamingSenderState _state = _start(_handlerChain); InternalSOAPMessage _request = _state.getRequest(); _request.setOperationCode(getBookPrice_OPCODE); ‘com.store.service.Store_getBookPrice_RequestStruct _myStore_getBookPrice_RequestStruct new com.store,service,Store_getBookPrice_RequestStruct(); _MyStore_getBookPrice_RequestStruct.setString_1(string_1); // skipped code for clarity. _send((Java.lang.String) _getProperty(ENDPOINT_ADDRESS_PROPERTY), _state); com.store.service.Store_getBookPrice_ResponseStruct _myStore_getBookPrice_ResponseStruct = null; Object _responseObj = _state.getResponse().getBody().getValue(); if (_responseObj instanceof SOAPDeserializationState) { ‘“myStore_getBookPrice_ResponseStruct = (com.store.service.Store_getBookPrice_ResponseStruct) (SOAPDeserializationStat e)_responseObj).getInstance(); } else { _myStore_getBookPrice_ResponseStruct = (com.store.service.Store_getBookPrice_ResponseStruct)_responseObj; } return _myStore_getBookPrice_ResponseStruct.getResult(); // skipped code for clarityNow write test class in which create the Object of SEI interface, we know the Implementation of SEI interface at the consumer side is Stub. Rather than we directly exposed to the generated Stub, it is being created by Service. Blow is the code snippet shows you how to build the program package com.store.service; Import java.rmi,RemoteException; Import javax.xml.rpc.ServiceException; public class AccessStoreTest { Public static void main(String aras[]) throws ServiceException, RemoteException { StoreService service = new StoreService_Impl(); Store port = service.getStorePort(); float price = port.getBookPrice("ISBN1001"); System.out.printin("Price : " + price);Web Services 11.2.2 Stub based client - Activity Guide Project nme SeveCent [Use adaue cron |
Fesme imple 1 jecpeepiyer ie elt setbepier fe eagparmpisar stacapit S-2jer nercedoel jee i arise or Le senkig ate 2 activation Jespe-impler Jompee ser rater sea) oj oy sahimetjae | treed iene "Create a Config folder in the Project directory: ereaté config xml Inside the config folder created. Now configure the wsdl location of the provider for whom. you want to generate the binding classes. versions '/.2" eneadings y ‘ak InsP p0-epe fe wad Locations “http: //Lt atone :3080) Starrechs stare us uckagetionas cis. a80°8. Service's peelNavigate to the Project directory, Set the Path pointing to the location of wscompie tool, Run the wscompile tao! by giving above config.xml as input, Note: - While runping the wscompite tool, the provider should be up and | running, 2. 2 ES g 5 5 @ Create Test class, in which create the Object of SEI interface with the help of Service as shown below. And run the client will be able to get the data from the Provider. package con.store.serviees ” Anport java.rai Renoterxception; public cluss‘AccessStoreTest { public static void main(String argsf]) threws Service: RemoteEaception { Storeservice service = new Storeservice_tnpl(); Store port = service.getstorePort(}; Create Test class float price = port.gettodkPrice("TSEN1801"); System.out.printin("Price : ° + price); bienIn this type of consumer, we don't need to generate any binding classes or Stub object at the design tine, The Stub (implementation of SEI interface at the client + side) will get generated on fly at runtime within the JVM 1m order to generate the Stud class at runtime, we need to use the JAX-RPC API specific classes, who know how to generate it. First the programmer has to browse the WSDL document, In the WSDL. document he needs to identify the PortType, operations and inputfoutput Messages, from which he needs to build the SEI interface with methods, Parameters and return types, ‘Once the SEI interface has been build, we need to use couple of JAX-RPC API classes to provide the Stub implementation of the SEI interface, The steps for the same are detailed below. 1) Create ServiceFactory - Stub is the implementation of SET interface which acts as @ Port through which we communicate to the Provider. But we don’t know how to create the Port Object. As we know Service knows how to create the Port Object, we need to create the javax.xml.rpc Service object, But Service is an Interface and to instantiate tie Implementation of this Interface, we need to approach ServiceFactory. ServiceFactory sfactory = ServiceFactory.newInstance(); 2) Create Service from the ServiceFactory ~ As Service acts as factory for creating the Port, from the ServiceFactory we need to create the Service. While creating the Service, we need to pass two parameters as input. A) WSDL Url, B) qName of the Service, So, while creating the Service Gbyect, It toads the WSDL document and searches for the existence of the Service QName in the WSDL document. If available, with the definitions of that Service (references to the Port) will creates the Service. | Service service = sfactory.createService(new java.net, URL(Wsdlurl}, new QName(amspe, serviceName)); 3) Call getPort method ~ On the service created above, we need to call the getPort method by passing qName of the Port and SEI Interface Type. By reading the Port definition, the getPort methed will try to generate a Stub class at runtime by implementing the SEI interface which is passed 3s reference and returns the Object of it. Store port = service. getPort{new QName(nmspe, portName), Store.class);Once we have the port, we can any methods on the Port which inturn makes a remote call to the Prayider. The following code snippet shows how to build a Dynamic Proxy based client package com.store,service.dp. client; public class StoreDPClient { private static final String WSOL_URL = | Mattp://localhost: 8680/StoreWeb/store7WSDL", private static final String SERVICE_NM = *StoreService*; private static final String PORT_NM = "StorePort", private static final String TRG_NMSPC “http: //safaribeoks. com/books/sale”, public static void main(Steing[] args) throws ServiceException, MalformedURLException, RemoteException { ServiceFactory factory = ServiceFactory. newinstance(); Service storeService = factory, createService( new Java.net.URL(WSDL_URL}, new QName(TRG_NMSPC, SERVICE_NM)); Store port = (Store) storeService.getPort( new QName{TRG_NMSPC, PORT_NM), Store.class); System.out.printin(*Price : " + port. getBookPrice("ISBN1001")); LL2.d Hynamie Invecation Taterface It is similar to Java reflection technic. In reflection we would be able to call a method on a class using the class name and method name dynamically at runtime on fly, Similarly with Dynamic Invocation Interface, a client can call a remote procedure even the signature of the remote procedure or the name of the service is unknown until runtime In case of Stub or DP based client, we need to have SEI interface or generated classes to access the Provider; unlike in case of DIT we just need couple of things like Service Name, Port Name, Operation Name and Target Endpoint address etc to access the Service.Steps to build a DI based client 1) Create the ServiceFactory - As we know ServiceFactory is the class who knows how to instantiate the Implementation of Service Interface. ServiceFactory sfactory = ServiceFactory.newinstance(}, 2) Create the Service ~ We need to create the Service from the ServiceFactory. While create the Service, we need to give the input as qName of the Service from the WSOL Service element. Service service = sfactory.createService(new QName(nmspe, servicenm)); 3) Create the call ~ Call is the Object which allows you to call a remote procedure on the Provider. To create the Call object, we need to calt createCall method on the Service Object. While creating the call object, to the createCall() method, we need to pass the Port Name from which you want to get the Call object as shown below, Call methodCal! = service.createCall(new QName(nmspe, portnmn)); 4) Set the parameters on the Call object ~ The call just we retrieved is a generic Call object which is not pointing to any specific endpoint. Now we need to set the values like method name, Target Endpoint Address, Input/Ouput paramters etc, methodCali.setTargetEndpointaddress(°URL"); methodCall.setOperationName(new QName(ninspc, "getBookPrice"); methodCall addParameter("String_1”, new QName(nmspe, typename), ParamterMode,IN); methodCall.setReturnType(new QName(nmspc, typename); 5) Along with that we need to set the below properties SOAPACTION_URI_PROPERTY SOAPACTION_USE_PROPERTY ENCODING_STYLE_PROPERTY 6) Invoke the method on the Call Object - To invoke the remote procedure on the service, we need to catl Call.invoke(new Object{}{}) by passing required Inputs as Object{] where it returns the response back to the user. The below code snippet shows the complete example on the same.package cam.store.service dit client; “] public class StoreDilChent¢ private static final String ENDPOINT_URL = “hetp: /flocathost: 8080/StoreWeb/store"; private static final String SERVICE_NM = "StoreService”; private static final String PORT_NM = “StorePort*, private static fina] String TRG_NMSPC = “http: //safaribooks.com/books/sate"; Private static final String METHOD_NM private static final String TYP_NMSPC = “http://www 93.0rg/2001/XMLSchema”, ‘getBookPrice”, public static void main(String[] args) throws ServiceException, RemoteException { ServiceFactory factory Service storeService QName(TRG_NMSPC, erviceFactory.newinstance(); factory createService(new SERVICE_NM)); Call getBookPriceCall = storeService.createCall(new QName(TRG_NMSPC, PORT_NM), new QName(TRG_NMSPC, METHOD_NM)); getBookPriceCail.setTarget€ndpointaddress(ENDPOINT_URL); getBookPriceCall.setReturnType(new QName(TYP..NMSPC, “foat"}); getBookPriceCall. addParameter("'String.1", new QName(TYP_NMSPC, "string"), ParameterMode.IN}; getBookPriceCall. setProperty( Call. SOAPACTION_USE_PROPERTY, true); getBookPriceCall. setProperty(Call, SOAPACTION_URI_ PROPERTY, getBookPriceCall. setProperty( Call, ENCODINGSTYLE_URI_PROPERTY, "attp://schemas.xmlsoap. org/soap/encading/"); Object price = getBookPriceCall.invoke(new Object{] { "ISBN1001" System out.printin("Price |" + price);
You might also like
Sriman Understanding Java WebServices PDF
PDF
100% (2)
Sriman Understanding Java WebServices PDF
210 pages
Web Services Material - Sriman Latest PDF
PDF
No ratings yet
Web Services Material - Sriman Latest PDF
300 pages
WebServices Notes by Sekhar Sir JavabynataraJ
PDF
88% (8)
WebServices Notes by Sekhar Sir JavabynataraJ
161 pages
Java Web Services-Sriman
PDF
89% (9)
Java Web Services-Sriman
301 pages
Java Quick Revision
PDF
No ratings yet
Java Quick Revision
7 pages
Core Java Study Final
PDF
No ratings yet
Core Java Study Final
410 pages
Java Means Durgasoft: An Introduction To Ant
PDF
No ratings yet
Java Means Durgasoft: An Introduction To Ant
13 pages
DURGAs SCJP Material PDF
PDF
No ratings yet
DURGAs SCJP Material PDF
14 pages
Sathaya Institute KVR Sir Java Notes
PDF
50% (2)
Sathaya Institute KVR Sir Java Notes
147 pages
Declaration and Access Modifiers PDF
PDF
No ratings yet
Declaration and Access Modifiers PDF
88 pages
Java - Lang Package PDF
PDF
No ratings yet
Java - Lang Package PDF
75 pages
Building A Custom Tag Library
PDF
50% (2)
Building A Custom Tag Library
29 pages
Corejava Concepts
PDF
100% (1)
Corejava Concepts
328 pages
Web Services Syllabus
PDF
No ratings yet
Web Services Syllabus
3 pages
Hari Krishna Volume 1a PDF
PDF
No ratings yet
Hari Krishna Volume 1a PDF
324 pages
Spring Data JPA Notes
PDF
No ratings yet
Spring Data JPA Notes
12 pages
Advance Java Natraz
PDF
No ratings yet
Advance Java Natraz
485 pages
3.predicate Study Material 2
PDF
100% (1)
3.predicate Study Material 2
15 pages
JSP Faqs
PDF
No ratings yet
JSP Faqs
16 pages
Unit - V Web Services
PDF
No ratings yet
Unit - V Web Services
109 pages
CoreJava iNetSolv
PDF
67% (9)
CoreJava iNetSolv
191 pages
Networking PDF
PDF
No ratings yet
Networking PDF
10 pages
Spring Core
PDF
No ratings yet
Spring Core
169 pages
Java Durga Sir Notes
PDF
100% (1)
Java Durga Sir Notes
55 pages
Com Chapter - 5
PDF
No ratings yet
Com Chapter - 5
4 pages
Java Server Pages Part-1: Naresh I Technologies
PDF
No ratings yet
Java Server Pages Part-1: Naresh I Technologies
5 pages
Development PDF
PDF
No ratings yet
Development PDF
20 pages
Java Multitherding
PDF
100% (1)
Java Multitherding
23 pages
CoreJava1 Niraj
PDF
100% (1)
CoreJava1 Niraj
308 pages
11.batch Updations
PDF
No ratings yet
11.batch Updations
5 pages
Web Service Lectures
PDF
No ratings yet
Web Service Lectures
62 pages
Core Java
PDF
No ratings yet
Core Java
6 pages
Complete Java Training in Naresh I Technologies
PDF
No ratings yet
Complete Java Training in Naresh I Technologies
24 pages
Flow Control
PDF
100% (2)
Flow Control
29 pages
Collections and Generics
PDF
No ratings yet
Collections and Generics
27 pages
Core Java by KV Rao
PDF
100% (1)
Core Java by KV Rao
370 pages
Adv - Java Means Durga Sir... : Durgasoft, Plot No: 202, Iind Floor, Huda Maitrivanam, Ameerpet, Hyderabad-500038
PDF
No ratings yet
Adv - Java Means Durga Sir... : Durgasoft, Plot No: 202, Iind Floor, Huda Maitrivanam, Ameerpet, Hyderabad-500038
14 pages
Packages PDF
PDF
No ratings yet
Packages PDF
21 pages
5.coding Questions
PDF
No ratings yet
5.coding Questions
44 pages
JDBC PDF
PDF
100% (1)
JDBC PDF
30 pages
MAD Chapter - 3: Web Services For Mobile Devices
PDF
No ratings yet
MAD Chapter - 3: Web Services For Mobile Devices
25 pages
Java - Io Package and Serialization
PDF
100% (1)
Java - Io Package and Serialization
14 pages
Distributed Computing - Lab Report: - :By:-Ms Poonam Singh Chandravanshi
PDF
No ratings yet
Distributed Computing - Lab Report: - :By:-Ms Poonam Singh Chandravanshi
58 pages
Chapter One Introduction
PDF
No ratings yet
Chapter One Introduction
5 pages
Web Services Overview:: A Technical Introduction
PDF
No ratings yet
Web Services Overview:: A Technical Introduction
19 pages
Adv - Java Means Durga Sir: Plot No: 202, Iind Floor, Huda Maitrivanam, Ameerpet, Hyd-5000038
PDF
No ratings yet
Adv - Java Means Durga Sir: Plot No: 202, Iind Floor, Huda Maitrivanam, Ameerpet, Hyd-5000038
22 pages
Zewdie Midterm Study Guide
PDF
No ratings yet
Zewdie Midterm Study Guide
20 pages
Natraj JSP
PDF
100% (1)
Natraj JSP
87 pages
1.basics of Web Service
PDF
No ratings yet
1.basics of Web Service
5 pages
Servlets Context
PDF
No ratings yet
Servlets Context
16 pages
WEB SERVICE Vs WEB API
PDF
No ratings yet
WEB SERVICE Vs WEB API
3 pages
Web Services
PDF
No ratings yet
Web Services
35 pages
Web Services
PDF
No ratings yet
Web Services
63 pages
XML, Web Service and SOA
PDF
No ratings yet
XML, Web Service and SOA
10 pages
Q.2 Explain The Features of WCF in Detail?: List Advantage and Disadvantage of Soap
PDF
No ratings yet
Q.2 Explain The Features of WCF in Detail?: List Advantage and Disadvantage of Soap
6 pages
Java Web Service
PDF
No ratings yet
Java Web Service
4 pages
Web Services With JAX-RPC and Apache Axis
PDF
No ratings yet
Web Services With JAX-RPC and Apache Axis
38 pages
Web Services Notes
PDF
No ratings yet
Web Services Notes
119 pages
Web Service
PDF
No ratings yet
Web Service
3 pages
Java Web Services Interview Questions and Answers: Overview: Integration Styles?
PDF
No ratings yet
Java Web Services Interview Questions and Answers: Overview: Integration Styles?
25 pages