Part Three Exploring Java Web Services Developer Pack. Chapter 7 .. Ramesh Nagappan is an experienced software architect who specializes in. Java -, XML- as a free download from maroc-evasion.info To build. Developing Java Web Services. Authors: Ramesh Nagappan After providing a detailed introduction to Web services in this text, the authors walk you through the Web services architecture and its ACM eBooks: The ACM Learning Center. NET Interoperability / - Exploring Java Web Services Developer Pack: Introduction RAMESH NAGAPPAN is an Enterprise Java Architect at Sun Java Center.
|Language:||English, Spanish, Hindi|
|Genre:||Children & Youth|
|Distribution:||Free* [*Registration needed]|
Exploring Java Web Services Developer Pack. Security in RAMESH NAGAPPAN is an Enterprise Java Architect at Sun Java Center. Developing Java Web Services: Architecting and Developing Secure Web Services Using Java [Ramesh Nagappan, Since JWSDP is a free download from Sun, it is a good way to experiment with web services without a large investment. Ramesh Nagappan Robert Skoczylas Rima Patel Sriganesh . Introduction to the Java Web Services Developer Pack (JWSDP) Java Web Services Developer Pack Web site at maroc-evasion.info webservices/pdf/WSFL. pdf.
Heartfelt gratitude to our friends at Sun Microsystems for their help and support while accomplishing this work. Around P. In the next few days, we created the proposal for this book. Both Sameer and Sada helped us initiating this huge effort and in getting the proposal written; much thanks to them for all their efforts. My special thanks goes to Sunil Mathew and my fellow architects at the Sun Java center for their constant encouragement for writing this book.
Thanks to the Apache Axis team and my friends at Apache Software Foundation for being helpful, answering my questions, and updating me with changes.
Finally, the largest share of the credit goes to my loving wife, Joyce, my little buddy Roger, and my parents for all their love and support. Only through their love and support, am I able to accomplish any goal. Robert Skoczylas After long, long hours of hard work we are finally done with the chapters and ready to thank and recognize the help of many people who gave us guidance, direction, and support.
Special thanks to Sada Rajagopalan for his contributions to the first chapter of the book. Your amazing motivation got this ball rolling. Big thanks to all the expert contributors of the Java, XML, and Web services mailing lists out there, your feedback adds a great value to this work.
I want to thank all my friends at the Sun Java Center for all their support, especially my manager, Sunil Mathew, for his constant encouragement.
Thanks to my parents, Urszula and Jacek, and my brother Slawomir, who always show me the way things need to be done. Thank you! Then, navigate to the source directory and run the Ant utility. Upon successful completion, you will find the output shown in Figure 3.
To execute the static client AcmeWebServiceClient class, you may execute the Ant utility with run as an argument. As part of every Web service deployment, the WebLogic 7.
Through this home page, it does the following: Building the Web Services Architecture To test the operations, just click on the operation links. To invoke the getProductCatalog operation, click on the link. Then click on the Invoke button to display the results. Upon successful execution, the browser will display the output shown in Figure 3.
And, the final test is to display the WSDL-based service description describing the service and operations provided by the Web service provider.
The browser then will display the output shown in Figure 3. Although it is not mandatory to choose any programming language for implementing the client interfaces, it must support the use of SOAP for communication. As discussed earlier, we will be using Apache Axis 1.
To create the service requestor clients as Java proxies, the following tasks are involved: Install and set up the Apache Axis development environment. Ensure that Axis class libraries and other optional libraries that is, Apache Xerces, Xalan are in the Java compiler class path. Create a test client directory and run the org. Building the Web Services Architecture 3.
Using an Ant script, compile the generated source files along with a stub client, which invokes the services from the ACME Web services. Test the client execution. For example, you may execute the following command line: WSDL This will generate a package named localhost that includes a list of client stub classes as follows: A typical implementation will be as follows: Upon successful completion, the system will display the output shown in Figure 3. Building the Web Services Architecture Figure 3.
The complete source code and instructions for executing the previous example are available as part of the source code bundle as Chapter3. In this section, we have illustrated a complete example of implementing Web services by exposing J2EE components deployed in a J2EE application server and accessing those services using a SOAP-based client environment.
Summary This chapter has thoroughly studied building Web services architecture and implementing J2EE-based Web services. It also has examined the different strategies and architectural models of developing Web services. In general, we have looked at such varied topics as Web service architecture and its characteristics, the core building blocks of Web services, standards and technologies available for implementing Web services, Web services communication models, how to develop Web services-enabled applications, how to develop Web services from J2EE applications, and a complete illustration of developing J2EE-based Web services.
In addition, this chapter illustrates an example of developing a Web services solution using a SOAP implementation. With the emergence of Web services, SOAP has become the de facto communication protocol standard for creating and invoking applications exposed over a network. Using XML notation, SOAP defines a lightweight wire protocol and encoding format to represent data types, programming languages, and databases.
This enables inter-application communication in a distributed environment and interoperability between heterogeneous applications over the networks.
With its widespread acceptance by leading IT vendors and Web developers, SOAP is gaining popularity Chapter 4 and adoption in most popular business applications for enabling them as Web services. It is important to note that SOAP is an ongoing W3C effort in which leading IT vendors are participating in order to come to a consensus on such important tasks associated with XML-based protocols and to define their key requirements and usage scenarios.
For consistency and better understanding, the chapter discusses both versions of SOAP and its features. XMLbased protocols have been used in the industry for a while now—some even before the W3C SOAP effort began—however, some of these protocols did not get accepted by the industry for various reasons.
Some of the popular XML-based protocols are the following: XMI defines an open information interchange model for CORBA and object-based technologies in a standardized way, enabling them to interoperate using XML and providing the ability to exchange programming data over the Internet. The parameters can consist of numbers, scalars, strings, dates, lists, and complex records. Allaire Macromedia, Inc.
It defines an XML-based data exchange model between applications leveraging data syndication and B2B collaboration. In , the SOAP 1. Later, the SOAP 1. SOAP is intended for use as a portable communication protocol to deliver SOAP messages, which have to be created and processed by an application.
In general, SOAP is simple and extensible by design, but unlike other distributed computing protocols, the following features are not supported by SOAP: In fact, SOAP is leveraged by an ebXML Messaging service as a communication protocol with an extension that provides added security and reliability for handling business transactions in e-business and B2B frameworks.
It does not mandate a single programming language or a platform, nor does it define its own language or platform. The example shown in Listing 4. In the scenario in Listing 4. In Listing 4. Note that a SOAP application should incorporate and use the relevant SOAP namespaces for defining its elements and attributes of its sending messages; likewise, it must be able to process the receiving messages with those specified namespaces. The following list their forms in both versions 1.
It is represented as the root element of the message as Envelope. As we discussed earlier, it is usually declared as an element using the XML namespace http: As per SOAP 1. Encoding styles also can be defined using a namespace under Envelope to represent the data types used in the message.
Listing 4. They have a key and value pair that identifies the different attribute. Many attributes can exist in one element. If attributes are used, the XML document can have a reduced number of tags, as shown in the following code: Attributes also apply to all of the elements that are nested within the element holding the attribute. The following example shows how the currency attribute applies to different scotch brands: Lagavulin Entities Entities are variables used to define common text or shortcuts to text.
Table 8. downloadOrder has child elements, starting with Header, which contain the downloader information followed by many LineItem elements that contain the product number and quantity of the ordered products. Between the Header and first LineItem is an empty tag called Products.
This empty tag serves as a delimeter between the header and the line items. Each LineItem contains the type of product that it represents. By specifying the URL, the namespace becomes a unique identifier. A URL is usually combined with a prefix to make the different elements distinguishable from each other. The URL does not refer to any particular file or directory on the Web, it simply acts as a unique association or label for the defined namespace. If the namespaces are not explicitly defined, the XML elements are considered to reside in a default namespace.
Consider the following example XML structure where the tag is found in two distinct places: The most common conflicts arise when multiple XML documents use identical tags that have different meanings. The parser must understand to which tag the application is referring. Having said that, the syntax using namespaces specification will convert the tags into something less ambiguous, such as and. The following sample shows the distinction of both tags: The Header element of the catalog XML document does not use the Catalog namespace, instead, it uses the default namespace without any prefixes.
Validation of XML Documents Before the parser processes a document, it is checked for well-formedness. A well-formed document is a document in which every tag has an Chapter 8 equivalent closing tag meaning; it conforms to the XML specification. A document that is well formed may not necessarily be valid. A valid document is a document that conforms to certain constraints defined in a schema definition.
Validity is used for checking whether a document conforms to certain standards agreed upon by collaborating parties for example, two businesses conducting the exchange of computer parts. These two businesses must provide the data in such a way that they both understand what is represented and what is meant by it. The following example demonstrates a structure that is not well formed: Jane 21 In the previous example, the Age and Employee elements are not properly nested.
The order in which the paired tags are opened and closed is very important for a document to be considered well formed. This error is corrected in the following example, in which the two elements are properly nested: Jane 21 Well-formedness is very important because it enables the parser to process the XML document in a more efficient way.
In order for validity to be checked, a definition document must be provided to define what the document is allowed to have as tags and attributes and the type of elements that should be present within a particular tag. Consider a simple example in which the Product element contains a type defining the type of product that a company is offering. The company offers two types of products hardware or software.
Suppose that its Product element is defined as follows: Generic Mouse In this case, this document would not be considered valid, because the receiving party would not know what the additional type means. The newest generation of validation standards is based on the XML Schema Definition, which is a more complete feature set that enables developers to define restrictions using XML syntax. XML elements are declared with an element declaration using the following syntax: Element-name is the XML element definition.
Element-content defines the type of element. It defines whether the element is a data type or a compound type consisting of other elements and data. Various element types can be defined in an element, among which are the following: Empty tag. Character data; should not be parsed by the XML parser. Parsed character data; parsed by the XML parser.
Any content. The following examples show how to define DTDs in Chapter 8 both internal and external ways. These examples demonstrate how to define an element Product with children sequences of Id and Price: The XML file size is reduced to the following: See Table 8. The Product element can contain zero or one instance of the child element. The syntax for a single attribute is as follows: The syntax for a multi-attribute element is as follows: The following XML code respects the definitions of the enumerated attribute values defined previously.
Product could be of the type hardware, software, or services. The default value, if not provided in the attribute list definition, is hardware because this is the first entry in the enumeration. Entity can be used for internal definitions, as follows: The XML data is the same whether or not an internal or external entity source is used. It has solved many problems that developers were facing.
In the current wave of technological evolutions, DTDs are not able to handle some requirements with ease. DTDs are not very good at expressing sophisticated constraints on elements, such as the number of maximum and minimum occurrences of a particular element.
DTDs do not have the capability to reuse previously defined structures. They also do not have support for type inheritance, subtyping, and abstract declarations. This standard is becoming more popular as the definition format, because it is easier to understand and maintain.
XML Schema is hierarchical and enables type, structure, and relationship definitions to exist as well as field validations within elements. It starts with as the root element. It then includes references to an XML Schema namespace declaration.
Namespace declarations are needed in this case because the document being operated upon references specific elements from the schema. The schema elements provide the semantics for constraining elements in the other namespace of the XML document being processed. The following is a fragment of an XML Schema declaration: The root element contains a targetNamespace attribute, which specifies the target that the schema will constrain.
The previous example shows that two different namespaces are defined. One is the default namespace unqualified used by the XML Schema and the second qualified is the target document defined using the Catalog prefix. There are no general rules for choosing a namespace as the default. There are suggestions to make the default namespace the same as the targetNamespace. There is not an optimal solution to this problem; which default namespace is optimal truly depends upon whether the schema will be extended, whether it will import different schemas, and any number of other things.
In that case, the location of the XML schemas must be specified using the schemaLocation attribute. The following example shows a fragment of an XML document: John Doe Futsji Another way to use multiple schemas is to import one schema into another, which is achieved in the following code: The import element is used to specify the namespace along with the URI location of the schema definition. Now that we have the root element defined, the rest should be straightforward.
A schema definition is composed of elements and attributes that describe the content of the XML document. A name and a type represent an element. The type sets a restriction to which the XML document elements must conform.
Primitive or simple element types are defined by the XML Schema specification.
Simple data types cannot contain other elements or any other attributes. The schema element, using simple data types, is defined using the following syntax: For example: Name is used to identify the XML element that the schema is constraining. There also are other possibilities of various options, such as the occurrence of an element in the XML document.
Revisiting the syntax, we get When unspecified, both options default to 1, meaning that one occurrence exists per definition. For example, the following is a definition for the LineItem element, which has to occur at least many times and has no maxOccurs limit: Complex or user-defined elements are used to define elements that consist of other elements and attributes. The syntax used for complex types is represented in the following order: For example, a Product contains a name, description, and price, and is considered to be a complex type, as shown in the following fragment: The nesting of elements could be very deep; schema does not impose any restrictions on this.
downloader and Product are user-defined types that contain more embedded elements.
One last restriction is that the product description appears zero or one times. The following is an example of this scenario: The types used in the previous example are called explicit types. Explicit types are defined in such a way that they can be reused in the same or different document. There also are cases where the element contains a type, which is unique to a specific element definition and will not be reused anywhere else. This is referred to as an implicit type or a nameless type.
Implicit type enables the definition of a user-defined type within an element. The following example demonstrates the use of an implicit type. The downloaderInfo type cannot be reused anywhere else in this XML document except in the definition of downloadOrderType, which is shown in the following fragment of code: This example demonstrates an instance of a local definition because the elements of Name, Description, and Price belong to the ProductType element.
The following example uses global definitions, where Name, Description, and Price can be reused in other elements throughout the document: The use of global and local definitions is really a matter of taste. Some of the best practices suggest making the declarations local if the elements are specific to the element being defined. Otherwise, if the elements can be reused throughout the document, then make the declarations global.
Figure 8. In this case, XML Schema is used as the default to provide a set of simple data types that can be used to define certain elements in an XML document.
In addition, the Catalog schema is used to provide more extensible user-defined types used within the XML document. TE Previous sections of this chapter have discussed empty tags. These empty tags also can be constrained by the XML Schema definitions. This is accomplished by defining an element name containing a complexType of type empty, as follows: Attributes Attributes are used to provide additional information to an XML data element.
For example, the element Price can have an attribute identifying the currency of the price, as shown in the following: The syntax for attribute definitions is as follows: Simple types cannot have attributes; therefore they must be defined as a complexType because of the attribute addition.
The attribute for Price is currency, which identifies the kind of currency of the price. The power of this definition can be extended by adding an option for making the attribute mandatory, thus providing a default currency or restricting the attribute to a list of possible currencies. To add a list of restricted values for an attribute, use an enumeration option: There are still limitations that cannot be solved with this standard alone. Instead, other technologies must be added and combined to solve more complex problems revolving around data restrictions and validations.
For example, imagine an element, which has the following restrictions: The element of a Product is smaller or equal to the element of a download Order. There are many different standards and tools that solve problems that DTDs and XML schemas cannot handle, such as the following languages: Parsing of the data is an essential mechanism used for interpreting the tags and elements that compose an XML data structure.
There have been many vendor implementations that enable the parsing of XML, but one major factor was lacking: These two standards provide a standardized and vendor-neutral approach for XML processing. The following sections describe the two standards by going through the APIs and examples. The process in which the XML is being interpreted is called parsing and the process where various templates are applied to XML to produce a different output is called transformation.
Many vendors have implemented their own specific parsers that address the two Chapter 8 most common parsing models of SAX and DOM. This led to API standardization complexities where applications using one specific vendor were using specific method calls to perform equivalent parsing tasks. In the case where the parsers needed to be swapped, developers had to rewrite the parsing code to adapt to the new specific vendor standard. The purpose of the specification was to provide a standard high-level API layer for abstracting lower-level details of XML parsing.
The first version of JAXP 1. The feature set focused around parsing, which was a limitation that many have complained about because it did not provide support for any XML transformation processing. The latest version of JAXP 1. This abstraction is referred to as pluggable interface. Uses for JAXP JAXP provides a pluggability layer, which enables application developers to change parser implementations without affecting the application logic.
One JAXP-compliant parser can be exchanged for another parser seamlessly, without much effort. JAXP provides a set of standard interfaces that encapsulate the details behind parser interactions. These interfaces act as abstractions that prevent the developer from working with XML directly. In order for a parser and transformer to be compliant, it must follow the JAXP specification.
The flexibility of having the freedom to choose any parser is very important. It enables an application developer to choose a parser provider that best suits the requirements of the service. In addition to the pluggability layer, JAXP is made simple. The parsing classes and interfaces are packaged under the javax. Transformation classes and interfaces are packaged in javax. The parser implementation is packaged in parser. Developers have the tendency to refer to the com.
ParserConfigurationException javax. DocumentBuilder avax.
DocumentBuilderFactory javax. SAXParser javax. TransformerFactoryConfigurationError javax. Transformer javax. TransformerFactory Factory Configuration Exception class used for handling javax. SAXResult javax. SAXSource javax. DOMLocator javax.
DOMResult javax. DOMSource javax. StreamResult javax. It provides the transparent instantiation of the parser implementation. In reality, this is the mechanism that promotes the pluggability approach by enabling the developers to define the factory implementation as a parameter passed to the Java virtual machine.
System Property java -Djavax. For more information on how the mechanism works, refer to http: The following sections discuss the API and the different standards that it supports. It is similar to the AWT 1. SAX supports validation but does not enforce the use of it. It uses a sequential readonly approach and does not support random access to the XML elements. One way of doing it is to use a JAXP javax. SAX as a processing model is very simple see Figure 8.
The basics consist of the following three steps: Implement a class that extends the DefaultHandler and holds callback methods for every type of construct found in XML that contains implementation based on your needs.
Instantiate a new SAX Parser class. Read the XML source sequentially. With the sequential reading, it is not possible to randomly access elements in the structure. The rest depends upon your implementation residing in the Handler class. These steps consist of the following: Setting options such as namespaces, validation, and features 3. DefaultHandler handles all of the callbacks for specific tags.
In order for an application to obtain an instance of the parser, it must get an instance of the SAXParserFactory. It then gets a SAXParser upon which it can call parse methods. Instantiate the implemented Handler class. See SAXParser javadoc for different options available in the parse method. This type of implementation is referred to as the JAXP pluggability layer, because it is very generic the way the factory class is retrieved.
Parser vendors can be swapped without much effort as long as they comply to the JAXP 1. A ParserConfigurationException is thrown when the parser is not returned properly. This line can be placed in a configuration file java. Properties or simply passed as an argument to the Java call.
The most common implementations known to developers are the Sun Crimson reference implementation and Apache Xerces. This is important when multiple documents are used with the same application. To configure the parser to be namespace aware, perform the following steps: If parser.
To configure the parser to be a validation-aware parser, perform the following steps: If the parser is not available, a factory configuration exception is thrown. To verify whether a parser supports validation, the following method is available from the parser class: This method is called on the factory class just like setNamespaceAware and setValidating. This option sets various features implemented by the vendors to be configured in a parser.
The following sample shows a sample handler that extends from the DefaultHandler. The developer has full control over the action that can take place while the XML document is read. The following code lists the methods that need to be implemented when extending from DefaultHandler: This method is called only once at the start of the XML document.
This method is called when the parser reaches the end of the XML document. This method is called for character data residing inside an element. This method is called every time a new opening tag of an element is encountered for example,. This method is called when an element ends for example,. This parser is an implementation that is provided by many vendors. Because it conforms to the specification, it can be easily exchanged.
Obtaining the parser object is pretty straightforward. Developers must instantiate the factory class, and from the factory class they must instantiate a new parser class: The factory configuration can be wrong, and an exception will be thrown to indicate this problem. The exception is called FactoryConfigurationException, and it must be caught during the instantiation of the factory object.
The second area where the application can fail is while the parser object is instantiated. In this case, the ParserConfigurationException must be caught while the factory instantiates a new parser. The following is a listing of more complete code: The following are possibilities in which the parser can be used: Data also can be parsed with non-JAXP parsers such as the underlying org. SAX 2. Because low-level SAX parsing is not in the scope of this book, it will not be covered in more detail.
This handler class provides logic coded in the callback methods defined by the programmer. The parse method accepts various input parameters, including java. InputStream, org. InputSource, java. File, and java. The second parameter is the implementation of the DefaultHandler class. Before running the code, compile the java files using the ANT script provided with the examples. To run, execute the following command: Listing 8.
The W3C definition www. The DOM processing model consists of reading the entire XML document into memory and building a tree representation of the structured data see Figure 8. This process can require a substantial amount of memory when the XML document is large.
By having the data in memory, DOM introduces the capability of manipulating the XML data by inserting, editing, or deleting tree elements. Unlike the SAX, it supports random access to any node in the tree. It is considered more intensive on the resources, because it loads the entire XML document into memory. The basic steps for using DOM processing are as follows: Instantiate a new Builder class. The Builder class is responsible for reading the XML data and transforming it into a tree representation.
Create the Document object once the data is transformed. Use the Document object to access nodes representing elements from the XML document. The XML source is read entirely into memory and is represented by the Document object. This enables the application to access any node randomly, which is something that SAX cannot do.
One disadvantage of DOM is that it can be inefficient when large data is read into memory. This is not something that is mandated by the JAXP 1. The following is an example showing the steps for getting a Document org. Document object, which consists of an in-memory tree structure composed of nodes. Instantiate a new document builder class, once the factory is obtained, by calling the newDocumentBuilder static method: Parse, using the Builder class, which contains a parse method that accepts an input stream representing the XML data: The configuration of the factory class is exactly the same as the SAX configuration, except for the class names.
The following is an example of the java system property option for a DocumentBuilderFactory class: It uses the steps explained previously to produce a Document object that represents the parsed XML data. Using Namespaces A parser that is namespace-aware is a parser that is able to handle naming collisions. To configure the parser to be namespace-aware, the factory class must be configured. The book is written by three Sun employees so it does tend to be a bit Sun-centric as the next sections shows.
A case study wraps up the six chapters putting the whole thing together. The book ends with a chapter on security and a look at Sun ONE. The book is full of examples demonstrating how to use each of these technologies. When you read a line such as, "The real fun is understanding how the EncryptDecrypt class works," you know you are dealing with authors who love code.
For developing Java web services you will be hard pressed to find a better book than this one.