Sunteți pe pagina 1din 70

UNIT V

5.1 WEB SERVICES Introduction To Web Services Web Services can convert your applications into Web-applications.Web Services are published, found, and used through the Web. What are Web Services? Web services are application components Web services communicate using open protocols Web services are self-contained and self-describing Web services can be discovered using UDDI Web services can be used by other applications XML is the basis for Web services The basic Web services platform is XML + HTTP.XML provides a language which can be used between different platforms and programming languages and still express complex messages and functions.The HTTP protocol is the most used Internet protocol. Web services platform elements: SOAP (Simple Object Access Protocol) UDDI (Universal Description, Discovery and Integration) WSDL (Web Services Description Language) Why Web Services? A few years ago Web services were not fast enough to be interesting. Interoperability has Highest Priority When all major platforms could access the Web using Web browsers, different platforms could interact. For these platforms to work together, Web-applications were developed. Web-applications are simple applications that run on the web. These are built around the Web browser standards and can be used by any browser on any platform.Web Services take Web-applications to the Next Level By using Web services, your application can publish its function or message to the rest of the world.Web services use XML to code and to decode data, and SOAP to transport it (using open protocols).With Web services, your accounting department's Win 2k server's billing system can connect with your IT supplier's UNIX server.

Page 1

Web Services have Two Types of Uses Reusable application-components. There are things applications need very often. So why make these over and over again? Web services can offer application-components like: currency conversion, weather reports, or even language translation as services. Connect existing software. Web services can help to solve the interoperability problem by giving different applications a way to link their data. With Web services you can exchange data between different applications and different platforms. Web Services Concepts Web Services have three basic platform elements: SOAP, WSDL What is SOAP? SOAP is an XML-based protocol to let applications exchange information over HTTP. Or more simple: SOAP is a protocol for accessing a Web Service. SOAP stands for Simple Object Access Protocol SOAP is a communication protocol SOAP is a format for sending messages SOAP is designed to communicate via Internet SOAP is platform independent SOAP is language independent SOAP is based on XML SOAP is simple and extensible SOAP allows you to get around firewalls SOAP is a W3C standard What is WSDL? WSDL is an XML-based language for locating and describing Web services. WSDL stands for Web Services Description Language WSDL is based on XML WSDL is used to describe Web services WSDL is used to locate Web services WSDL is a W3C standard

Page 2

Any application can have a Web Service component.Web Services can be created regardless of programming language.

A Web Service Example In the following example we will use ASP.NET to create a simple Web Service that converts the temperature from Fahrenheit to Celsius, and vice versa: <%@ WebService Language="VBScript" Class="TempConvert" %> Imports System Imports System.Web.Services Public Class TempConvert :Inherits WebService <WebMethod()> Public Function FahrenheitToCelsius (ByVal Fahrenheit As String) As String dim fahr fahr=trim(replace(Fahrenheit,",",".")) if fahr="" or IsNumeric(fahr)=false then return "Error" return ((((fahr) - 32) / 9) * 5) end function <WebMethod()> Public Function CelsiusToFahrenheit (ByVal Celsius As String) As String dim cel cel=trim(replace(Celsius,",",".")) if cel="" or IsNumeric(cel)=false then return "Error" return ((((cel) * 9) / 5) + 32) end function end class This document is saved as an .asmx file. This is the ASP.NET file extension for XML Web Services. Example Explained The first line in the example states that this is a Web Service, written in VBScript, and has the class name "TempConvert": <%@ WebService Language="VBScript" Class="TempConvert" %> Page 3

The next lines import the namespace "System.Web.Services" from the .NET framework: ImportsSystem Imports System.Web.Services The next line defines that the "TempConvert" class is a WebService class type: Public Class TempConvert :Inherits WebService The next steps are basic VB programming. This application has two functions. One to convert from Fahrenheit to Celsius, and one to convert from Celsius to Fahrenheit.The only difference from a normal application is that this function is defined as a "WebMethod()". Use "WebMethod()" to convert the functions in your application into web services: <WebMethod()> Public Function FahrenheitToCelsius (ByVal Fahrenheit As String) As String dim fahr fahr=trim(replace(Fahrenheit,",",".")) if fahr="" or IsNumeric(fahr)=false then return "Error" return ((((fahr) - 32) / 9) * 5) end function <WebMethod()> Public Function CelsiusToFahrenheit (ByVal Celsius As String) As String dim cel cel=trim(replace(Celsius,",",".")) if cel="" or IsNumeric(cel)=false then return "Error" return ((((cel) * 9) / 5) + 32) end function Then, end the class: end class 5.2 JAX-RPC Concepts Java APIs for XML-based Remote Procedure Call (JAX-RPC) help with Web service interoperability and accessibility by defining Java APIs that Java applications use to develop and access Web services. JAX-RPC fully embraces the heterogeneous nature of Web services -- it allows a JAX-RPC client to talk to another Web service deployed on a different platform and coded in a different language. Similarly, it also allows clients on other platforms and coded in different languages to talk to a JAX-RPC service. JAX-RPC also defines the mapping between WSDL service descriptions and Java interfaces.

Page 4

This introduces the JAX-RPC technology and describes its client and server programming models. JAX-RPC hides the complexity of underlying protocols and message-level processing from application developers crafting Web services using the Java 2 platform. The API combines XML with Remote Procedure Call (RPC), which is a mechanism enabling clients to execute procedures on distributed or remote systems, so that developers can build Web services and clients. SOAP and WSDL are language-neutral standards defined by the World Wide Web Consortium (W3C). SOAP is a lightweight, XML-based protocol for exchange of information in a decentralized, distributed environment. The core of this protocol is a SOAP envelope. The envelope defines a framework for describing what is in a message and how to process it. SOAP defines a set of encoding rules for expressing instances of application-defined data types. It defines a convention for representing RPC requests and responses. WSDL specifies an XML format for describing a Web service as a set of endpoints operating on messages. The operations and messages are defined abstractly and then bound to a concrete network protocol (HTTP) and a message format (SOAP) to define an endpoint (or port). Related ports are combined into abstract endpoints, also called services. WSDL describes the Web service in a standard format: it specifies the service's location and the operations exposed by the port in the service. The JAX-RPC reference implementation, available in the Java Web Services Developer Pack Early Access 2 (JWSDP EA2) release, includes a tool that can parse existing WSDL files or generate WSDL files for a Web service.
An Example Application: SunReg Web Service Consider an example enterprise Web service to illustrate the JAX-RPC concepts and programming models. This enterprise Web service, called SunReg, allows employees in an organization to inquire about and register for various courses offered by their internal education center. SunReg allows employees to send queries about the courses offered by the education center. The Web service provides the employee with information about each course, such as course description, the campus where the course is conducted, and the duration of the course. Employees can also use SunReg to enroll in specific courses of their interest. The employee and course information is stored in a database. Figure 1 shows a use case diagram for the SunReg Web service.

The SunReg application exposes these functions as Web services to all employees of the organization. Employees access the Web service using browser-based clients, such as applets or Java applications. In addition, a client on a different platform can access the Web service using a different language. This kind of interoperability is achieved because JAX-RPC adheres to SOAP 1.1 and WSDL 1.1 standards.

Page 5

Figure 1. The SunReg Web service allows users to look for a course and register for a course. SunReg is developed, deployed, and published as a JAX-RPC Web service endpoint. Once developed, an endpoint is deployed in a container that supports the JAX-RPC runtime system, which in turn supports the underlying XML-based protocol and transport. The Web service endpoint can be a servlet-based endpoint deployed on a servlet container or a stateless session bean. JWSDP provides Tomcat as the servlet container, which is what we used for the SunReg Web service endpoint. JWSDP also provides a Java-to-WSDL mapping tool that can publish the service description along with the endpoint.
A Note About Software Versions Used in This Example In this article, we use the JAX-RPC reference implementation that comes bundled with JWSDP EA2 for developing and deploying our Web service. The JAX-RPC implementation in JWSDP EA2 is based on the 0.7 version of the specification. The code examples in this article are compatible with the JWSDP EA2 release, current at this writing. The JWSDP first customer release, currently planned for mid-June, will incorporate the latest revisions of the JAX-RPC specification. The code samples here will need an update at that time; look for updates or advice about migrating applications on this Web site about that time. Also note that we refer to the JWSDP installation directory as JWSDP_HOME through out this article. Developing a Service As noted already, a JAX-RPC service endpoint represents a Web service endpoint. When you're ready to create a service endpoint, you:

Write only two classes. One class exposes the service method signatures and the other class provides the method implementations. Define an XML configuration file that contain instructions to generate various client-side and server-side artifacts required by JAX-RPC. This configuration file is consumed by the Java-to-WSDL mapping tool. Define a web.xml file that specifies the deployment descriptor for service deployment in a servlet container.

Page 6

Coding the Service Endpoint Interface

You start by defining two classes. First you define the class that represents the remote interface to the service; this is the service endpoint interface. It contains the signatures for the methods that a client may invoke on the service. The service endpoint interface extends the java.rmi.Remote interface, and its methods must throw the java.rmi.RemoteException. Although each method can throw a service-specific exception, to keep the application simple we do not include them in the examples with this article. Code Sample 1 shows code for the service endpoint interface for SunReg, named SunRegPort. Code Sample 1: The service endpoint interface, SunRegPort
public interface SunRegPort implements java.rmi.Remote { public Course[] getCourseInfo() throws RemoteException; public void registerCourseInfo(Employee emp, Course[] courseArray) throws RemoteException; }

As

the service endpoint interface, SunRegPort, implements the interface. It provides two methods: getCourseInfo and registerCourseInfo. Employees use getCourseInfo to obtain information about the courses available in the education center. It's possible to add as a convenience method, a second, overloaded getCourseInfo method that offers an optional search criteria.
java.rmi.Remote

required,

Employees use the registerCourseInfo method to sign up for courses they have selected. You can set up registerCourseInfo to throw a service-specific exception to indicate if the employee is not allowed to register for a particular course.

Figure 2: Course and Employee JAX-RPC Value types Page 7

Course

and

Employee value types are defined according to the JavaBeans pattern defined

by the JAX-RPC specification. All the member variables of the value types are declared as private. The data type of each member variable is a JAX-RPC-supported data type. Each member variable has a getter and setter method as defined by the JavaBeans design pattern.
Coding the Service Endpoint Class

The service endpoint class provides an actual implementation of the methods defined in the service endpoint interface. (You can also call a service implementation class a servant, as we do later in this article.) Code Sample 2 shows the service implementation class for SunRegPort, named SunRegImpl. Code Sample 2: The service implementation class SunRegImpl
import java.xml.rpc.server.ServiceLifecycle; public class SunRegImpl implements SunRegPort, ServiceLifecycle { Connection dbConnection = null; public void init(Object context) { String dbUrl = ((ServletContext)context).getInitParameter("dbUrl"); dbConnection = DriverManager.getConnection(dbUrl); //other relevant code } public void destroy() { //release the database connection } public Course[] getCourseInfo() { //get course information using the database //connection } public void registerCourseInfo(Employee emp, Course[] courseArray) { //register for the course information using //the database connection }}

The

SunRegImpl class contains the implementations for the methods getCourseInfo and registerCourseInfo. (Code Sample 2 does not show those two method implementations because they are relevant only to the application.) SunRegImpl also extends the java.xml.rpc.server.ServiceLifecycle interface, which is an important

part of defining a service. Through the implementation of the ServiceLifecycle interface, the JAX-RPC runtime system manages the life cycle of the service endpoint objects. SunRegImpl implements the init and destroy methods inherited from the ServiceLifecycle interface. The JAXRPC runtime system invokes the init method for the initialization of the service endpoint object. The service endpoint uses the init method to initialize its configuration and set up access to any external resources. The context parameter in the init method enables the endpoint to access the endpoint context provided by the underlying JAX-RPC runtime system. The JAX-RPC runtime invokes the destroy method when it determines that the service endpoint object no longer handles remote invocations. Page 8

Defining the Configuration File

Next, you need to define a configuration file to generate the various server-side artifacts required by the JAX-RPC runtime. This configuration file specifies the name of the service (or services) and its endpoint interface and class. This configuration file, called config.xml in our case and shown in Code Sample 3, follows the JAX-RPC specification, but is also specific to the particular JAX-RPC implementation. While its syntax may vary from one implementation to another, the configuration file contains the information required by the xrpcc tool. Code Sample 3: The configuration file for SunReg
<?xml version="1.0" encoding="UTF-8"?> <configuration xmlns="http://java.sun.com/jax-rpc-ri/xrpcc-config"> <rmi name="SunReg" targetNamespace="http://sunreg.org/wsdl" typeNamespace="http://sunreg.org/types"> <service name="SunRegService" packageName="sunreg"> <interface name="SunRegPort" servantName="SunRegImpl"/> </service> </rmi> </configuration>

Take a more detailed look at the significant attributes in the configuration file: The rmi element includes name, typeNamespace, and targetNamespace attributes: The name attribute of the rmi element (SunReg in the code sample) is used to generate the WSDL file for publication in a public registry. The typeNamespace attribute defines the name space in the WSDL document for types generated by the xrpcc tool. The targetNamespace attribute is used for qualifying everything else in the WSDL document. The service element includes name and packageName attributes: The name attribute of the service element, SunRegService in the above code, is used to generate a properties file that the servlet-based JAX-RPC runtime uses for dispatching the request to tie-and-servant combination. The packageName attribute specifies the package in which xrpcc tool generates all the artifacts.
Defining the Deployment Descriptor

Because we intend to deploy SunReg on JWSDP as a WAR (Web archive file) file, we need to create a web.xml file for SunReg. The web.xml file contains information important for deploying the service, such as mapping the service to an URL, specifying the location of the configuration file in the WAR file, and so forth. Code Sample 4 shows the web.xml for deploying the SunReg service on a JWSDP container.

Page 9

Code Sample 4: The web.xml for deploying the SunReg service on a JWSDP container
<web-app> <context-param> <param-name>dbUrl</param-name> <param-value>jdbc:cloudscape:sunregDB</param-value> </context-param> <servlet> <servlet-name>SunregEndpoint</servlet-name> <servlet-class>com.sun.xml.rpc.server.http.JAXRPCServlet </servlet-class> <init-param> <param-name>configuration.file</param-name> <param-value> /WEB-INF/SunRegService_Config.properties </param-value> </init-param> <load-on-startup>0</load-on-startup> </servlet> <servlet-mapping> <servlet-name>SunregEndpoint </servlet-name> <url-pattern>/jaxrpc/*</url-pattern> </servlet-mapping> </web-app>

Notice in Code Sample 4 that the web.xml file specifies dbUrl as a context parameter, which means its value applies to all the servlets defined in the WAR file. Recall that the servant implementation init method (in SunRegImpl in Code Sample 2) obtained this context parameter value to make a JDBC connection to the database. The servlet class JAXRPCServlet is available in the JAX-RPC server runtime (that is, it is in the jaxrpc-ri.jar file found in the directory JWSDP_HOME/common/lib), and it is responsible for dispatching a request from a stub to a tie-and-servant combination within the container. The tie-and-servant combination is dictated by the _Config.properties file, which in our example is SunRegService_Config.properties. The _Config.properties file is specified to the servlet as an init-param. The xrpcc tool generates this properties file. The name of this file is derived from the name attribute of the service element in the config.xml file. Finally, you specify the url-pattern attribute for the endpoint. This determines the service endpoint URL for the Web service.
Compiling the Service

You compile the service endpoint interface and service endpoint class using a Java compiler. Then you generate the various server-side artifacts required by the JAX-RPC runtime by inputting the configuration tool to the Java-to-WSDL mapping tool, xrpcc, which comes bundled with JWSDP. One of the required artifacts is the WSDL service description. Recall that a service endpoint is mapped to a WSDL service description. This WSDL document describes the service endpoint in terms of abstract definitions of port types, operations, messages, and concrete protocol binding.

Page 10

You'll find the xrpcc tool in the directory


xrpcc.sh

JWSDP_HOME/bin.

It is executed by entering

or

xprcc.bat from that directory. The xrpcc tool generates stub, tie, and other

client-side and server-side artifacts required by the JAX-RPC runtime. The command to generate the files is:
xrpcc.sh -both -keep -d classes config.xml

The options to the xrpcc tool are:


-both

instructs the xrpcc tool to generate both client-side and server-side

artifacts. instructs the tool to keep the intermediate generated source files. -d specifies the destination directory for generated artifacts.
-keep

Alternatively, you can generate just the client-side and server-side artifacts by specifying either the -client or -server option to the xrpcc tool instead of specifying the -both option. Because the options -client, -server, and -both are mutually exclusive you can use only one of the options with the xrpcc tool. Among the various artifacts generated by the xrpcc tool, stubs and ties are the most important. Stubs and ties are classes that enable communication between a service endpoint and a service client. The stub class sits on the client side, between the service client and the JAX-RPC client runtime system. The stub class is responsible for converting a request from a JAX-RPC service client to a SOAP message and sending it across to the service endpoint using the specified protocol (in our case HTTP). It also converts the response from the service endpoint, which it receives in the form of a SOAP message, to the format required by the client. Converting a client request to SOAP format is called marshalling; converting back from SOAP format to a client response is unmarshalling. Similarly, the tie class resides on the server side, between the service endpoint and the JAX-RPC runtime system. The tie class handles marshalling and unmarshalling the data between the service endpoint class and the SOAP format. A stub is a local object that acts as a proxy for the service endpoint, as illustrated in Figure 3.

Figure 3: JAX-RPC runtime and generated classes

Page 11

The xrpcc tool also generates a properties file that associates each servant with a generated tie file (on the server side). The name of this file is formed by appending _Config.properties to the name attribute of the service element in the XML configuration file. There is one such properties file per service element. Thus, for the service SunRegService, the xrpcc compiler generates SunRegService_Config.properties file. The xrpcc tool also generates a WSDL file that describes the service in a standard format. Although it's not recommended to edit the _Config.properties file, it is possible to do so. We appended a line in the SunRegService_Config.properties to make the WSDL service description accessible over the Web. We added, as the last line in SunRegService_Config.properties, the following line:
wsdl.location=/WEB-INF/SunReg.wsdl

Deploying the Service Once the xrpcc tool has completed its job, you must package and deploy the service on a servlet container (we used Tomcat for the example application). The service endpoint interface, service endpoint class, and web.xml file, along with other generated artifacts and configuration properties file, are bundled into a standard WAR file (see Code Sample 5 for the structure of the sample WAR file). Because we want the WSDL service description for SunReg to be accessible by the service endpoint, we also need to bundle SunReg.wsdl in the WAR file. The WAR file is then deployed on to the servlet container. Successful deployment results in an URL (endpoint) that a client can use to access the service, as illustrated in Figure 4.

Figure 4: Deploying the service and related files. The developer writes two Java language files, two XML files, and the client application. Page 12

Note that there are generated files in addition to the ones shown in Figure 4. All of the generated files are packaged to the WAR file. The structure of the WAR file for SunReg looks like Code Sample 5. Code Sample 5: The structure of the web.xml WAR file for the example SunReg application
META-INF/ META-INF/MANIFEST.MF WEB-INF/ WEB-INF/classes/ WEB-INF/classes/sunreg/ WEB-INF/classes/sunreg/Course.class WEB-INF/classes/sunreg/Employee.class WEB-INF/classes/sunreg/SunRegPort.class WEBINF/classes/sunreg/SunRegImpl.class WEB-INF/classes/sunreg/SunRegPort_Tie.class WEB-INF/classes/sunreg/Course_SOAPSerializer.class WEB-INF/classes/sunreg/Employee_SOAPSerializer.class WEB-INF/classes/sunreg/GetCourseInfo_RequestStruct.class WEB-INF/classes/sunreg/GetCourseInfo_ResponseStruct.class WEB-INF/classes/sunreg/RegisterCourseInfo_RequestStruct.class WEB-INF/classes/sunreg/RegisterCourseInfo_ResponseStruct.class WEB-INF/classes/sunreg/GetCourseInfo_RequestStruct_SOAPSerializer.class WEB-INF/classes/sunreg/GetCourseInfo_ResponseStruct_SOAPSerializer.class WEB-INF/classes/sunreg/ RegisterCourseInfo_RequestStruct_SOAPSerializer.class WEB-INF/classes/sunreg/ RegisterCourseInfo_ResponseStruct_SOAPSerializer.class WEB-INF/classes/sunreg/GetCourseInfo_ResponseStruct_SOAPBuilder.class WEB-INF/classes/sunreg/RegisterCourseInfo_RequestStruct_SOAPBuilder.class WEB-INF/classes/sunreg/SunRegService_SerializerRegistry.class WEB-INF/SunRegService_Config.properties WEB-INF/SunReg.wsdl WEB-INF/web.xml

In this web.xml file, SunRegPort_Tie refers to the tie class. Furthermore, each method invocation and response is modeled as a struct (based on the SOAP 1.1 specification). Thus, the xrpcc tool generates _RequestStruct and _ResponseStruct classes for each method defined in the remote interface. Classes ending in _SOAPSerializer are used for serializing and deserializing the value types and the structs. Classes ending in _SOAPBuilder are helper classes used by _SOAPSerializer classes. SunRegService_SerializerRegistry registers all serializer classes for the JAX-RPC runtime. How might a client access the SunReg service? If the SunReg service is packaged into a WAR file named SunReg.war and deployed on a servlet container installed on the host howru at port 8080, the URL for the endpoint accessible to a JAX-RPC client is:
http://howru:8080/SunReg/jaxrpc

Note that jaxrpc comes from the url-pattern defined in the web.xml file. When an employee accesses this URL in a browser window, the browser displays the message shown in Figure 5. Page 13

Figure 5.

The

display that

appears

when

user

accesses

http://howru:8080/SunReg/jaxrpc in a browser The browser shows all the ports supported at this endpoint. Each port is mapped to a Java interface. Thus, the Web browser displays SunRegPort as a port supported at the endpoint:
http://howru:8080/SunReg/jaxrpc/SunRegPort

The WSDL description for the service can be accessed by clicking the "here" link or it can be found at the URL:
http://howru:8080/sunreg/jaxrpc?WSDL

Invoking the Service The JAX-RPC Web service endpoint is available to any type of client, regardless of the language or platform used by that client. A service client invokes a service endpoint using one of the following methods:

Stub-based programming model. This model involves code generation using the WSDL-to-Java mapping tool. Dynamic Invocation Interface (DII). DII is a call interface that supports programmatic creation and invocation of a RPC request. Dynamic proxies First let's discuss using the stub-based programming model to invoke the service. There are two approaches with this model. You can generate stubs from a service endpoint interface by running the xrpcc tool with either the -both option or -client option. More commonly, you can generate stubs by importing the published service description, WSDL, in the xrpcc tool.

Page 14

Generating Stubs from the Service Endpoint Interface

To generate stubs from the service endpoint interface, you provide either the -both or client option when invoking the xrpcc tool, as described earlier in this article under Compiling the Service.

To access this Web service, you need to write three lines of code in the client application, as follows: Get a handle to the service's generated stub file. Set the target endpoint. The target endpoint is the URL where the Web service is installed. Invoke the service method through the stub reference. Code sample 6 shows an example. Code Sample 6: Accessing the Web Service
SunRegPort_Stub stub = (SunRegPort_Stub)(new SunRegService_Impl().getSunRegPort()); stub._setProperty(Stub.ENDPOINT_ADDRESS_PROPERTY, "http://howru:8080/sunreg/jaxrpc/SunRegIF"); Course[] courseArray = stub.getCourseInfo();

The xrpcc tool generates its client-side implementation classes for the service, as we discussed earlier. A client-side implementation class enables the client to get a handle to the stub of the service endpoint interface. The xrpcc tool forms the name of the client implementation file by appending _Impl to the name attribute of the service element in the XML configuration file. Thus, the SunReg-generated client implementation file is called SunRegService_Impl. This generated implementation file includes a get method, getSunRegPort, which returns a reference to the stub for the service endpoint interface. After getting a reference to the stub, you set the endpoint address on it by invoking the _setProperty method on the stub. The Stub.ENDPOINT_ADDRESS_PROPERTY refers to javax.xml.rpc.service.endpoint.address. It is a property that describes the service endpoint address. The client uses the stub reference to invoke methods on the service. When the client invokes a method on the service through the stub, the stub marshals the request into a SOAP message and transmits the SOAP packet to the JAX-RPC servlet deployed in the servlet container. The JAX-RPC servlet looks at the SunRegService_Config.properties file for the appropriate tie-and-servant combination, and then dispatches the request to that tie-and-servant combination. The method response goes back to the client along the same path. An application can be run as an applet if the correct permissions are set. To run this application as an applet, you must give permissions to the applet sandbox security model, as shown in Code Sample 7. Code Sample 7: Setting up the application to run as an applet Page 15

grant { permission java.util.PropertyPermission "com.sun.xml.rpc.streaming.XMLWriterFactory", "read"; permission java.util.PropertyPermission "com.sun.xml.rpc.streaming.XMLReaderFactory", "read"; };

Generating Stubs from WSDL

Because the WSDL service description for SunReg has already been published, we can generate the various client-side artifacts by importing the WSDL into the xrpcc tool. To do this, you use the -client option when you invoke the xrpcc tool and provide a configuration file. Because the Web service is already installed, starting from WSDL does not require generating server-side artifacts (such as tie files). The xrpcc tool does not expect service definition files as input; instead, it expects as input the XML configuration file with the information about the WSDL file. A WSDL file, which is the file published in the public registry, describes a complete Web service in a standard format. In addition, a WSDL file describes how to access the Web service: it contains the port offered by the service and the endpoint where the service is installed. A port is the WSDL equivalent to a remote Java interface (for example, SunRegPort when starting from a service endpoint interface). An endpoint is usually the URL to the service embedded within the WSDL file. Less often, an endpoint may be the service's URI (Uniform Resource Identifer). Keep in mind that you do not need to know these WSDL details. Usually, you use a tool to generate WSDL files or to interpret already generated WSDL files. The xrpcc tool that comes bundled with JWSDP is one such tool. Returning to the SunReg example application, generating clients from the service endpoint interface is most useful when all employees access the same set of courses. It's conceivable that some departments within the organization may want to filter the set of courses available for their employees. To filter courses, they can use the xrpcc tool to import the WSDL file and generate stub files. They can then use these stubs to filter the courses. Let's look at how to do this. To begin, assume that the SunReg service is deployed in a servlet-based container, just as in the description of generating stubs from the service endpoint interface earlier in this section. The endpoint has been published and we have added the wsdl.location name and value pair to the SunRegService_Config.properties file, making the WSDL accessible. (See Compiling the Service, above, if you need to refresh your recollection of that technique.) Now, the Payroll department decides to filter courses for its employees. To do this, the Payroll department's system administrator obtains the WSDL file published by SunReg and feeds it to the xrpcc tool along with the XML configuration file, shown in Code Sample 8. Code Sample 8: The contents of the XML configuration file, config.xml
<configuration xmlns="http://java.sun.com/jax-rpc-ri/xrpcc-config">

Page 16

<wsdl name="SunRegService" location="http://howru:8080/sunreg/jaxrpc?WSDL" packageName="sunreg" /> </configuration>

Notice that the config.xml file for generating stubs from a WSDL is different than the configuration file starting from a service endpoint interface. For the WSDL model, the configuration file specifies three pieces of information: The name of the Web service, the wsdl name attribute. The xrpcc tool generates the service implementation file from the service name and appends _Impl to the service name, SunRegService_Impl in our case. The location of the WSDL. The configuration file also includes a location attribute with an URL that points to the location of the WSDL. The payroll system administrator can copy the WSDL locally and then use it. Alternatively, he may decide to specify the location as an URL, which in our case is http://howru:8080/SunReg/jaxrpc?WSDL. The name of the WSDL package. The packageName attribute specifies the fully qualified name of the package for the generated classes and interfaces from the WSDL. Using this information, the tool generates the necessary client-side artifacts. Note that the WSDL accessible by the location attribute ?WSDL is preconfigured with the correct endpoint URL within the service element of WSDL.
Dynamic Invocation Interface

Sometimes the xrpcc tool does not have the requisite tools to parse the WSDL and generate client-side artifacts. When this happens, the client uses a dynamic invocation interface (DII) instead. Using DII, a client can call a service or a remote procedure on a service without knowing the exact service name or the procedure's signature ahead of time. A DII client can discover this information at runtime, making use of a service broker that can dynamically look up the service and its remote procedures. You can refer to the Java Web Services Developer Pack tutorial for an example of a DII client. 5.2 WRITING A SIMPLE JAVA WEB SERVICE WITH JAX-RPC This section shows how to build and deploy a simple web service and client. A later section, Web Service Clients, provides examples of additional JAX-RPC clients that access the service. The source code for the service is in <INSTALL>/j2eetutorial14/examples/jaxrpc/helloservice/ and the client is in <INSTALL>/j2eetutorial14/examples/jaxrpc/staticstub/. Figure 8-1 illustrates how JAX-RPC technology manages communication between a web service and client.

Page 17

Figure 8-1 Communication Between a JAX-RPC Web Service and a Client

The starting point for developing a JAX-RPC web service is the service endpoint interface. A service endpoint interface (SEI) is a Java interface that declares the methods that a client can invoke on the service. You use the SEI, the wscompile tool, and two configuration files to generate the WSDL specification of the web service and the stubs that connect a web service client to the JAX-RPC runtime. For reference documentation on wscompile, see the Application Server man pages at http://docs.sun.com/db/doc/817-6092. Together, the wscompile tool, the deploytool utility, and the Application Server provide the Application Server's implementation of JAX-RPC. These are the basic steps for creating the web service and client: Code the SEI and implementation class and interface configuration file. Compile the SEI and implementation class. Use wscompile to generate the files required to deploy the service. Use deploytool to package the files into a WAR file. Deploy the WAR file. The tie classes (which are used to communicate with clients) are generated by the Application Server during deployment. Code the client class and WSDL configuration file. 6. Use wscompile to generate and compile the stub files. 7. Compile the client class. Run 8. the client. 9. 1. 2. 3. 4. 5. The sections that follow cover these steps in greater detail. Coding the Service Endpoint Interface and Implementation Class In this example, the service endpoint interface declares a single method named sayHello. This method returns a string that is the concatenation of the string Hello with the method parameter. A service endpoint interface must conform to a few rules: Page 18

It extends the

java.rmi.Remote interface.

It must not have constant declarations, such as public final static. The methods must throw the java.rmi.RemoteException or one of its subclasses. (The methods may also throw service-specific exceptions.) Method parameters and return types must be supported JAX-RPC types (see Types Supported by JAX-RPC). In this example, the service endpoint interface is named HelloIF: package helloservice; import java.rmi.Remote; import java.rmi.RemoteException; public interface HelloIF extends Remote { public String sayHello(String s) throws RemoteException; } In addition to the interface, you'll need the class that implements the interface. In this example, the implementation class is called HelloImpl: package helloservice; public class HelloImpl implements HelloIF { public String message ="Hello"; public String sayHello(String s) { return message + s; } } Building the Service To build MyHelloService, in a terminal window go to the <INSTALL>/j2eetutorial14/examples/jaxrpc/helloservice/ directory and type the following: asant build The build task command executes these asant subtasks:
compile-service generate-wsdl

Page 19

The compile-service Task This asant task compiles HelloIF.java and HelloImpl.java, writing the class files to the build subdirectory. The generate-WSDL Task The generate-wsdl task runs wscompile, which creates the WSDL and mapping files. The WSDL file describes the web service and is used to generate the client stubs in Static Stub Client. The mapping file contains information that correlates the mapping between the Java interfaces and the WSDL definition. It is meant to be portable so that any J2EEcompliant deployment tool can use this information, along with the WSDL file and the Java interfaces, to generate stubs and ties for the deployed web services. The files created in this example are MyHelloService.wsdl and mapping.xml. The generate-wsdl task runs wscompile with the following arguments: wscompile -define -mapping build/mapping.xml -d build -nd build -classpath build config-interface.xml The -classpath flag instructs wscompile to read the SEI in the build directory, and the define flag instructs wscompile to create WSDL and mapping files. The -mapping flag specifies the mapping file name. The -d and -nd flags tell the tool to write class and WSDL files to the build subdirectory. The wscompile tool reads an interface configuration file that specifies information about the SEI. In this example, the configuration file is named config-interface.xml and contains the following: <?xml version="1.0" encoding="UTF-8"?> <configuration xmlns="http://java.sun.com/xml/ns/jax-rpc/ri/config"> <service name="MyHelloService" targetNamespace="urn:Foo" typeNamespace="urn:Foo" packageName="helloservice"> <interface name="helloservice.HelloIF"/> </service> </configuration> This configuration file tells wscompile to create a WSDL file named MyHello Service.wsdl with the following information: The service name is
MyHelloService.

Page 20

The WSDL target and type namespace is

urn:Foo. The choice for what to use for

the namespaces is up to you. The role of the namespaces is similar to the use of Java package names--to distinguish names that might otherwise conflict. For example, a company can decide that all its Java code should be in the package com.wombat.*. Similarly, it can also decide to use the namespace http://wombat.com. The SEI is helloservice.HelloIF. The packageName attribute instructs wscompile to put the service classes into the helloservice package. Packaging and Deploying the Service Behind the scenes, a JAX-RPC web service is implemented as a servlet. Because a servlet is a web component, you run the New Web Component wizard of the deploytool utility to package the service. During this process the wizard performs the following tasks: Creates the web application deployment descriptor Creates a WAR file Adds the deployment descriptor and service files to the WAR file To start the New Web Component wizard, select File wizard displays the following dialog boxes. New Web Component. The

1. Introduction dialog box a. Read the explanatory text for an overview of the wizard's features. b. Click Next. 2. WAR File dialog box a. Select the button labeled Create New Stand-Alone WAR Module. b. In the WAR File field, click Browse and navigate to c. In the File Name field, enter d. Click Create Module File. e. Click Edit Contents.
<INSTALL>/j2eetutorial14/examples/jaxrpc/helloservice/. MyHelloService.

f. In the tree under Available Files, locate the <INSTALL>/j2eetutorial14/examples/jaxrpc/helloservice/ directory. g. Select the build subdirectory. h. Click Add. i. Click OK. j. In the Context Root field, enter /hello-jaxrpc. k. Click Next. 3. Choose Component Type dialog box a. Select the Web Services Endpoint button. b. Click Next. 4. Choose Service dialog box Page 21

a. In the WSDL File combo box, select


INF/wsdl/MyHelloService.wsdl.

WEB-

b. In the Mapping File combo box, select build/mapping.xml. c. Click Next. 5. Component General Properties dialog box a. In the Service Endpoint Implementation combo box, select helloservice.HelloImpl. b. Click Next. 6. Web Service Endpoint dialog box a. In the Service Endpoint Interface combo box, select helloservice.HelloIF. b. In the Namespace combo box, select urn:Foo. c. In the Local Part combo box, select HelloIFPort. d. The deploytool utility will enter a default Endpoint Address URI HelloImpl in this dialog. This endpoint address must be updated in the next section. e. Click Next. f. Click Finish. Specifying the Endpoint Address To access MyHelloService, the tutorial clients will specify this service endpoint address URI: http://localhost:8080/hello-jaxrpc/hello The /hello-jaxrpc string is the context root of the servlet that implements MyHelloService. The /hello string is the servlet alias. You already set the context root in Packaging and Deploying the Service with deploytool above. To specify the endpoint address, set the alias as follows: In deploytool, select MyHelloService in the tree. In the 1. tree, select HelloImpl. 2. Select the Aliases tab. 3. In the Component Aliases table, add /hello. 4. In the Endpoint tab, select hello for the Endpoint Address in the Sun-specific 5. Settings frame. 6. Select File Save. Deploying the Service In deploytool, perform these steps: 1. In the tree, select MyHelloService. 2. Select Tools Deploy. Page 22

You can view the WSDL file of the deployed service by requesting the URL http://localhost:8080/hello-jaxrpc/hello?WSDL in a web browser. Now you are ready to create a client that accesses this service. 5.3 WRITING CODE FOR JAVA WEB SERVICE CLIENT Coding the Static Stub Client Before it can invoke the remote methods on the stub, the client performs these steps: 1. Creates a
Stub object:

(Stub)(new MyHelloService_Impl().getHelloIFPort()) The code in this method is implementation-specific because it relies on a MyHelloService_Impl object, which is not defined in the specifications. The MyHelloService_Impl class will be generated by wscompile in the following section. 2. Sets the endpoint address that the stub uses to access the service: stub._setProperty (javax.xml.rpc.Stub.ENDPOINT_ADDRESS_PROPERTY, args[0]); At runtime, the endpoint address is passed to HelloClient in args[0] as a command-line parameter, which asant gets from the endpoint.address property in the build.properties file. This address must match the one you set for the service in Specifying the Endpoint Address. 3. Casts
stub to the service endpoint interface, HelloIF:

HelloIF hello = (HelloIF)stub; Here is the full source code listing for the HelloClient.java file, which is located in the directory <INSTALL>/j2eetutorial14/examples/jaxrpc/staticstub/src/: package staticstub; import javax.xml.rpc.Stub; public class HelloClient { private String endpointAddress; public static void main(String[] args) { System.out.println("Endpoint address = " + args[0]); Page 23

try { Stub stub = createProxy(); stub._setProperty (javax.xml.rpc.Stub.ENDPOINT_ADDRESS_PROPERTY, args[0]); HelloIF hello = (HelloIF)stub; System.out.println(hello.sayHello("Duke!")); } catch (Exception ex) { ex.printStackTrace(); } } private static Stub createProxy() { // Note: MyHelloService_Impl is implementation-specific. return (Stub) (new MyHelloService_Impl().getHelloIFPort()); } } Building and Running the Static Stub Client To build and package the client, go to the <INSTALL>/j2eetutorial14/examples/jaxrpc/staticstub/ directory and type the following: asant build The build task invokes three asant subtasks:
generate-stubs compile-client package-client

The generate-stubs task runs the wscompile tool with the following arguments: wscompile -gen:client -d build -classpath build config-wsdl.xml This wscompile command reads the MyHelloService.wsdl file that was generated in Building the Service. The command generates files based on the information in the WSDL file and the command-line flags. The -gen:client flag instructs wscompile to generate the stubs, other runtime files such as serializers, and value types. The -d flag tells the tool to write the generated output to the build/staticstub subdirectory. The wscompile tool reads a WSDL configuration file that specifies the location of the WSDL file. In this example, the configuration file is named config-wsdl.xml, and it contains the following: <configuration xmlns="http://java.sun.com/xml/ns/jax-rpc/ri/config"> Page 24

<wsdl location="http://localhost:8080/hellojaxrpc/hello?WSDL" packageName="staticstub"/> </configuration> The packageName attribute specifies the Java package for the generated stubs. Notice that the location of the WSDL file is specified as a URL. This causes the wscompile command to request the WSDL file from the web service, and this means that the web service must be correctly deployed and running in order for the command to succeed. If the web service is not running or if the port at which the service is deployed is different from the port in the configuration file, the command will fail.The compile-client task compiles src/HelloClient.java and writes the class file to the build subdirectory. The package-client task packages the files created by the generate-stubs and compile- client tasks into the dist/client.jar file. Except for the HelloClient.class, all the files in client.jar were created by wscompile. Note that wscompile generated the HelloIF.class based on the information it read from the MyHelloService.wsdl file. To run the client, type the following: asant run This task invokes the web service client, passing the string Duke for the web service method parameter. When you run this task, you should get the following output: Hello Duke 5.4 DESCRIBING WEB SERVICES Web Services Description Language is an XML-based language used to define Web services and describe how to access them. Fortunately, you do not need to learn all the nitty gritty details because there are tools that generate WSDL for you. This article gives you just enough WSDL knowledge to understand what's going on and to be able to tweak toolgenerated WSDL files and troubleshoot WSDL-related problems. For example, you'll need to know WSDL if your Web service methods accept objects as parameters. This is because you'll need to define the data types corresponding to those objects in the service's WSDL file. To get the most benefit out of this article you'll need to understand XML Namespaces and the basics of XML Schema Definition Language. You can start by reading my XML Namespaces for VB programmers tutorial. I'll be writing a tutorial on XSD soon, so be sure to check back here soon. As a VB programmer, you probably know that type libraries are used to describe COM components. A type library contains information about the component's unique identifier (the CLSID), the interfaces that the component implements, and the method signatures for each interface. WSDL is used to describe the Web service, specify its location, and describe the operations (i.e. methods) it exposes, similar to how a type library is used to describe a Page 25

COM component. In the remainder of this article, I'll explain the fundamentals of WSDL and walk you through an example of a WSDL file generated by the Microsoft SOAP Toolkit V2 RC 0. Web service and a client invoking it in two different ways: Using SOAP and using HTTP GET. Each invocation consists of a request and a response message. Defining Services I built a simple VB class to use for this article. The class is called Weather and has one method (for now) called GetTemperature: Public Function GetTemperature(ByVal zipcode As String, _ ByVal celsius As Boolean) As Single 'just sends a harcoded value for now If celsius Then GetTemperature = 21.7 Else GetTemperature = 71.06 End If End Function You can think of the class as the Web service and the GetTemperature method as an operation on that service. To describe this service, you use the WSDL <service> element. All WSDL elements belong to the WSDL namespace, which is defined as: http://schemas.xmlsoap.org/wsdl/ (Note that at the time of this writing, section 1.2 of the WSDL 1.1 specification has a typo where it defines this namespace). As an example, consider a service that you call weatherservice, the service would be defined using WSDL like this: <definitions name ='weatherservice' xmlns='http://schemas.xmlsoap.org/wsdl/'> <service name='WeatherService' > </service> </definitions> WSDL namespace as the default namespace for the document so all elements belong to this namespace unless they have another namespace prefix. I omitted all other namespace declarations from this example to keep it clear. Each service is defined using a service element. Inside the service element, you specify the different ports on which this service is accessible. A port specifies the service address, for example, http://localhost/demos/wsdl/devxpert/weatherservice.asp The port definition would be like this: <port name='WeatherSoapPort' binding='wsdlns:WeatherSoapBinding' > <soap:address location='http://localhost/demos/wsdl/devxpert/weatherservice.asp' /> </port> Each port has a unique name and a binding attribute. We'll discuss the binding attribute later in this article. When using SOAP, the port element contains a <soap:address/> element with the actual service address. Here, the soap namespace prefix refers to the Page 26

namespace http://schemas.xmlsoap.org/wsdl/soap/ This namespace is used for SOAPspecific elements within WSDL. Such elements are also known as WSDL SOAP extension elements. We'll see some more examples of WSDL extension elements throughout this document.A Web service does not have to be exposed using SOAP. For example, if your Web service is exposed via HTTP GET, the port element would contain an <http:address/> element similar to this: <http:address location="http://localhost/demos/wsdl/devxpert/weatherGET.asp"/> A Web service may be accessible on many ports. For example, you might make your service available via SOAP and HTTP GET and possibly even via SMTP. For this Web service, you would have three ports each one with a different name. What's Your Message We'll make a transition now and start discussing how to define your service's request and response messages. A message is protocol independent, that is, a message may be used with SOAP, HTTP GET, or any other protocol. To use Web services in a remote procedure call (RPC) model, there are two messages you must describe. There's the input or request message, which is sent from the client to the service and there's the output or response message, which is sent back the opposite way.. WSDL, but you'll be using SOAP most of the time so that's what I'm focusing on). For example, the GetTemperature method would correspond to two messages: A request message sent from client to service and a response message sent back to the client: <message name='Weather.GetTemperature'> <part name='zipcode' type='xsd:string'/> </message> <message name='Weather.GetTemperatureResponse'> <part name='Result' type='xsd:float'/> </message> You'll note that the data types are prefixed with the xsd namespace prefix (assuming it was declared earlier in the document). XSD defines many data types that you can draw from when defining the message parts. The Microsoft SOAP Toolkit's documentation lists the supported XSD types and their mapping to VB data types. This list is repeated in table 1 for your convenience. Note that there are more data types in XSD than in VB that's why they're listed by the XSD type first. XSD (Soap) Type VB Comments anyURI String base64Binary Byte() boolean Boolean Integer Range validated on conversion. byte Date Time set to 00:00:00 date Date dateTime Double double String No validation or conversion performed duration String No validation or conversion performed ENTITIES S tring No validation or conversion performed ENTITY Single float

Page 27

gDay

String No validation or conversion performed

gMonth String No validation or conversion performed gMonthDay String No validation or conversion performed gYear String No validation or conversion performed gYearMonth String No validation or conversion performed . Port Types and Operations If you've been following closely, you'll note that just defining your messages does not tie them together as a request-response pair corresponding to a method call. To do this you define operations using the WSDL <operation> element. An operation specifies which message is the input and which message is the output like this: <operation name='GetTemperature' parameterOrder='zipcode celsius'> <input message='wsdlns:Weather.GetTemperature' /> <output message='wsdlns:Weather.GetTemperatureResponse' /> </operation> The parameterOrder attribute is optional and may be used to specify a space-delimited list of part names to indicate the order of parameters when making the RPC call. Inside the <operation> you specify <input> and <output> elements. Each refers to the corresponding message by its fully qualified name, e.g. wsdlns:Weather.GetTemperature. The collection of all operations (i.e. methods) exposed by your service is called a portType and is defined using the WSDL <portType> element like this: <portType name='WeatherSoapPort'> <operation name='GetTemperature' parameterOrder='zipcode celsius'> <input message='wsdlns:Weather.GetTemperature' /> <output message='wsdlns:Weather.GetTemperatureResponse' /> </operation> <!-- other operations would go here --> </portType> So the <operation> element is a child of <portType>. You can call the portType whatever you want. Binding It All Together We are now making a transition from abstract data types, messages, and operations to concrete physical representation of messages on the wire. To define the concrete aspects of operations, you use the WSDL <binding> element: <binding name='WeatherSoapBinding' type='wsdlns:WeatherSoapPort' > . </binding> Again, the name of the binding can be whatever you want. However, you must use this same name for the binding attribute on the <port> element (see Defining Services above). Inside the <binding> element you have a WSDL SOAP extension element called <soap:binding> which is used to specify the transport protocol you're using (SOAP can be used over HTTP, SMTP, or possibly any other transport) and the style of request (rpc and document are the two styles). For example: <soap:binding style='rpc' Page 28

transport='http://schemas.xmlsoap.org/soap/http' />

5.5 REPRESENTING DATA TYPES: XML SCHEMA BUILT-IN DATATYPES

Page 29

Each built-in datatype in this specification (both primitive and derived) can be uniquely addressed via a URI Reference constructed as follows: 1. the base URI is the URI of the XML Schema namespace 2. the fragment identifier is the name of the datatype For example, to address the int datatype, the URI is: http://www.w3.org/2001/XMLSchema#int Additionally, each facet definition element can be uniquely addressed via a URI constructed as follows: 1. the base URI is the URI of the XML Schema namespace 2. the fragment identifier is the name of the facet For example, to address the maxInclusive facet, the URI is: http://www.w3.org/2001/XMLSchema#maxInclusive Additionally, each facet usage in a built-in datatype definition can be uniquely addressed via a URI constructed as follows: 1. the base URI is the URI of the XML Schema namespace 2. the fragment identifier is the name of the datatype, followed by a period (".") followed by the name of the facet For example, to address the usage of the maxInclusive facet in the definition of int, the URI is: http://www.w3.org/2001/XMLSchema#int.maxInclusive XML SCHEMA The purpose of an XML Schema is to define the legal building blocks of an XML document, just like a DTD. An XML Schema: defines elements that can appear in a document defines attributes that can appear in a document defines which elements are child elements defines the order of child elements defines the number of child elements defines whether an element is empty or can include text defines data types for elements and attributes Page 30

defines default and fixed values for elements and attributes

XML Schemas are the Successors of DTDs We think that very soon XML Schemas will be used in most Web applications as a replacement for DTDs. Here are some reasons: XML Schemas are extensible to future additions XML Schemas are richer and more powerful than DTDs XML Schemas are written in XML XML Schemas support data types XML Schemas support namespaces USER DEFINED SIMPLE TYPES XSD Simple Elements XML Schemas define the elements of your XML files.A simple element is an XML element that contains only text. It cannot contain any other elements or attributes. What is a Simple Element? A simple element is an XML element that can contain only text. It cannot contain any other elements or attributes.However, the "only text" restriction is quite misleading. The text can be of many different types. It can be one of the types included in the XML Schema definition (boolean, string, date, etc.), or it can be a custom type that you can define yourself.You can also add restrictions (facets) to a data type in order to limit its content, or you can require the data to match a specific pattern. Defining a Simple Element The syntax for defining a simple element is: <xs:element name="xxx" type="yyy"/> where xxx is the name of the element and yyy is the data type of the element. XML Schema has a lot of built-in data types. The most common types are: xs:string xs:decimal xs:integer xs:boolean xs:date Page 31

xs:time Example Here are some XML elements: <lastname>Refsnes</lastname> <age>36</age> <dateborn>1970-03-27</dateborn> And here are the corresponding simple element definitions: <xs:element name="lastname" type="xs:string"/> <xs:element name="age" type="xs:integer"/> <xs:element name="dateborn" type="xs:date"/> Restrictions on Values The following example defines an element called "age" with a restriction. The value of age cannot be lower than 0 or greater than 120: <xs:element name="age"> <xs:simpleType> <xs:restriction base="xs:integer"> <xs:minInclusive value="0"/> <xs:maxInclusive value="120"/> </xs:restriction> </xs:simpleType> </xs:element> USER DEFINED COMPLEX TYPES XSD Complex Elements A complex element contains other elements and/or attributes.A complex element is an XML element that contains other elements and/or attributes.There are four kinds of complex elements: empty elements elements that contain only other elements elements that contain only text elements that contain both other elements and text Examples of Complex Elements A complex XML element, "product", which is empty: Page 32

<product pid="1345"/> A complex XML element, "employee", which contains only other elements: <employee> <firstname>John</firstname> <lastname>Smith</lastname> </employee> A complex XML element, "food", which contains only text: How to Define a Complex Element Look at this complex XML element, "employee", which contains only other elements: <employee> <firstname>John</firstname> <lastname>Smith</lastname> </employee> We can define a complex element in an XML Schema two different ways: 1. The "employee" element can be declared directly by naming the element, like this: 2. <xs:element name="employee"> <xs:complexType> <xs:sequence> <xs:element name="firstname" type="xs:string"/> <xs:element name="lastname" type="xs:string"/> </xs:sequence> </xs:complexType> </xs:element> 2. The "employee" element can have a type attribute that refers to the name of the complex type to use: <xs:element name="employee" type="personinfo"/> <xs:complexType name="personinfo"> <xs:sequence> <xs:element name="firstname" type="xs:string"/> <xs:element name="lastname" type="xs:string"/> </xs:sequence> </xs:complexType> An XML Document Page 33

Let's have a look at this XML document called "shiporder.xml": <?xml version="1.0" encoding="ISO-8859-1"?> <shiporder orderid="889923" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="shiporder.xsd"> <orderperson>John Smith</orderperson> <shipto> <name>Ola Nordmann</name> <address>Langgt 23</address> <city>4000 Stavanger</city> <country>Norway</country> </shipto> <item> <title>Empire Burlesque</title> <note>Special Edition</note> <quantity>1</quantity> <price>10.90</price> </item> <item> <title>Hide your heart</title> <quantity>1</quantity> <price>9.90</price> </item> </shiporder> The XML document above consists of a root element, "shiporder", that contains a required attribute called "orderid". The "shiporder" element contains three different child elements: "orderperson", "shipto" and "item". The "item" element appears twice, and it contains a "title", an optional "note" element, a "quantity", and a "price" element. The line above: xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" tells the XML parser that this document should be validated against a schema. The line: xsi:noNamespaceSchemaLocation="shiporder.xsd" specifies WHERE the schema resides (here it is in the same folder as "shiporder.xml"). 5.6 COMMUNICATING OBJECT DATA: SOAP What is SOAP? SOAP stands for Simple Object Access Protocol SOAP is a communication protocol SOAP is for communication between applications SOAP is a format for sending messages SOAP communicates via Internet SOAP is platform independent Page 34

Why SOAP? It is important for application development to allow Internet communication between programs.Today's applications communicate using Remote Procedure Calls (RPC) between objects like DCOM and CORBA, but HTTP was not designed for this. RPC represents a compatibility and security problem; firewalls and proxy servers will normally block this kind of traffic.A better way to communicate between applications is over HTTP, because HTTP is supported by all Internet browsers and servers. SOAP was created to accomplish this.SOAP provides a way to communicate between applications running on different operating systems, with different technologies and programming languages.SOAP is a W3C Recommendation SOAP Syntax SOAP Building Blocks A SOAP message is an ordinary XML document containing the following elements: An Envelope element that identifies the XML document as a SOAP message Header element that contains header information A Body element that contains call and response information A Fault element containing errors and status information All the elements above are declared in the default namespace for the SOAP envelope: http://www.w3.org/2001/12/soap-envelope and the default namespace for SOAP encoding and data types is: http://www.w3.org/2001/12/soap-encoding Syntax Rules Here are some important syntax rules: A SOAP message MUST be encoded using XML A SOAP message MUST use the SOAP Envelope namespace A SOAP message MUST use the SOAP Encoding namespace A SOAP message must NOT contain a DTD reference A SOAP message must NOT contain XML Processing Instructions Skeleton SOAP Message

Page 35

<?xml version="1.0"?> <soap:Envelope xmlns:soap="http://www.w3.org/2001/12/soap-envelope" soap:encodingStyle="http://www.w3.org/2001/12/soap-encoding"> <soap:Header> ... </soap:Header> <soap:Body> ... <soap:Fault> ... </soap:Fault> </soap:Body> </soap:Envelope> SOAP Envelope Element The SOAP Envelope element is the root element of a SOAP message. The SOAP Envelope Element The required SOAP Envelope element is the root element of a SOAP message. This element defines the XML document as a SOAP message. EXAMPLE <?xml version="1.0"?> <soap:Envelope xmlns:soap="http://www.w3.org/2001/12/soap-envelope" soap:encodingStyle="http://www.w3.org/2001/12/soap-encoding"> ... Message information goes here ... </soap:Envelope> The xmlns:soap Namespace Notice the xmlns:soap namespace in the example above. It should always have the value of: "http://www.w3.org/2001/12/soap-envelope". The namespace defines the Envelope as a SOAP Envelope.

Page 36

If a different namespace is used, the application generates an error and discards the message. The encodingStyle Attribute The encodingStyle attribute is used to define the data types used in the document. This attribute may appear on any SOAP element, and applies to the element's contents and all child elements. A SOAP message has no default encoding. Syntax soap:encodingStyle="URI" <?xml version="1.0"?> <soap:Envelope xmlns:soap="http://www.w3.org/2001/12/soap-envelope" soap:encodingStyle="http://www.w3.org/2001/12/soapencoding"> ... Message information goes here ... </soap:Envelope> SOAP Header Element The SOAP Header element contains header information. The SOAP Header Element The optional SOAP Header element contains application-specific information (like authentication, payment, etc) about the SOAP message. If the Header element is present, it must be the first child element of the Envelope element. Note: All immediate child elements of the Header element must be namespace-qualified. <?xml version="1.0"?> <soap:Envelope xmlns:soap="http://www.w3.org/2001/12/soap-envelope" soap:encodingStyle="http://www.w3.org/2001/12/soap-encoding"> <soap:Header> <m:Trans xmlns:m="http://www.w3schools.com/transaction/" soap:mustUnderstand="1">234 </m:Trans> Page 37

</soap:Header> ... ... </soap:Envelope> The example above contains a header with a "Trans" element, a "mustUnderstand" attribute with a value of 1, and a value of 234.SOAP defines three attributes in the default namespace ("http://www.w3.org/2001/12/soap-envelope"). These attributes are: mustUnderstand, actor, and encodingStyle.The attributes defined in the SOAP Header defines how a recipient should process the SOAP message. SOAP Body Element he SOAP Body element contains the actual SOAP message. The SOAP Body Element The required SOAP Body element contains the actual SOAP message intended for the ultimate ndpoint of the message. Immediate child elements of the SOAP Body element may be namespace-qualified. Example: <?xml version="1.0"?> <soap:Envelope xmlns:soap="http://www.w3.org/2001/12/soap-envelope" soap:encodingStyle="http://www.w3.org/2001/12/soap-encoding"> <soap:Body> <m:GetPrice xmlns:m="http://www.w3schools.com/prices"> <m:Item>Apples</m:Item> </m:GetPrice> </soap:Body> </soap:Envelope> The example above requests the price of apples. Note that the m:GetPrice and the Item elements above are application-specific elements. They are not a part of the SOAP namespace. SOAP Fault Element The SOAP Fault element hold errors and status information for a SOAP message. The optional SOAP Fault element is used to indicate error messages.

Page 38

If a Fault element is present, it must appear as a child element of the Body element. A Fault element can only appear once in a SOAP message.The SOAP Fault element has the following sub elements: Sub Element <faultcode> <faultstring> <faultactor> <detail> SOAP Fault Codes The faultcode values defined below must be used in the faultcode element when describing faults: Error VersionMismatch MustUnderstand Client Server SOAP HTTP Binding The HTTP Protocol HTTP communicates over TCP/IP. An HTTP client connects to an HTTP server using TCP. After establishing a connection, the client can send an HTTP request message to the server: POST /item HTTP/1.1 Host: 189.123.345.239 Content-Type: text/plain Content-Length: 200 The server then processes the request and sends an HTTP response back to the client. The response contains a status code that indicates the status of the request: 200 OK Content-Type: text/plain Content-Length: 200 Page 39 Description Found an invalid namespace for the SOAP Envelope element An immediate child element of the Header element, with the mustUnderstand attribute set to "1", was not understood The message was incorrectly formed or contained incorrect information There was a problem with the server so the message could not proceed Description A code for identifying the fault A human readable explanation of the fault Information about who caused the fault to happen Holds application specific error information related to the Body element

In the example above, the server returned a status code of 200. This is the standard success code for HTTP. If the server could not decode the request, it could have returned something like this: 400 Bad Request Content-Length: 0 SOAP HTTP BINDING A SOAP method is an HTTP request/response that complies with the SOAP encoding rules. HTTP + XML = SOAP A SOAP request could be an HTTP POST or an HTTP GET request. The HTTP POST request specifies at least two HTTP headers: Content-Type and Content-Length. Content-Type The Content-Type header for a SOAP request and response defines the MIME type for the message and the character encoding (optional) used for the XML body of the request or response. Syntax Content-Type: MIMEType; charset=character-encoding Example POST /item HTTP/1.1 Content-Type: application/soap+xml; charset=utf-8 Content-Length The Content-Length header for a SOAP request and response specifies the number of bytes in the body of the request or response. Syntax Content-Length: bytes POST /item HTTP/1.1 Content-Type: application/soap+xml; charset=utf-8 Content-Length: 250 Page 40

SOAP Example A SOAP Example In the example below, a GetStockPrice request is sent to a server. The request has a StockName parameter, and a Price parameter that will be returned in the response. The namespace for the function is defined in "http://www.example.org/stock". A SOAP request: POST /InStock HTTP/1.1 Host: www.example.org Content-Type: application/soap+xml; charset=utf-8 Content-Length: nnn <?xml version="1.0"?> <soap:Envelope xmlns:soap=http://www.w3.org/2001/12/soap-envelope soap:encodingStyle="http://www.w3.org/2001/12/soap-encoding"> <soap:Body xmlns:m="http://www.example.org/stock"> <m:GetStockPrice> <m:StockName>IBM</m:StockName> </m:GetStockPrice> </soap:Body> </soap:Envelope> The SOAP response: HTTP/1.1 200 OK Content-Type: application/soap+xml; charset=utf-8 Content-Length: nnn <?xml version="1.0"?> <soap:Envelope xmlns:soap="http://www.w3.org/2001/12/soap-envelope" soap:encodingStyle="http://www.w3.org/2001/12/soap-encoding"> <soap:Body xmlns:m="http://www.example.org/stock"> <m:GetStockPriceResponse> <m:Price>34.5</m:Price> </m:GetStockPriceResponse> </soap:Body> Page 41

</soap:Envelope>

5.7 RELATED TECHNOLOGIES WSDL Web Services Description Language WSDL (Web Services Description Language) is a standard method to provide description of services, the XML vocabulary IDL. Web Services Description Language (WSDL) specification defines an XML vocabulary, the vocabulary in accordance with the request and response messages, the service requester and service provider defines a contract between the. We can define the Web services software, the software interface by describing the SOAP messages WSDL document to provide reusable application functionality, and use the standard transmission protocol for transmission. WSDL description contains the necessary details in order to service requester can use a particular service: Request Message Format Response message format where to send the message. WSDL is based on XML, so the WSDL document is a computer-readable (machinereadable). This development environment to use WSDL to automatically handle the process of integration services to the requester application. For example, Java, WebSphere Studio generates a proxy object, it can achieve the same services as local objects, but in fact only the proxy object created to process the request and response messages parsing. Regardless of whether the services using Java, C # or other language, the generated Java proxy objects from the WSDL description can call any Web service. In fact, WSDL can not be achieved as the programming language as described in detail. UDDI Universal Description, Discovery and Integration (Universal Description, Discovery and Integration) specification provides a common set of SOAP API, making service agent can be achieved. UDDI to publish and discover services, the availability of required services defines a standard interface (based on the SOAP message). UDDI publishing and discovery services to achieve the SOAP request to explain the basic data storage for use in the data management function calls.In order to publish and find other SOA services, UDDI SOAP message by defining a standard to achieve the service registration (Service Registry). Registration is a service agency, which is found in the UDDI service requester in need of service providers and distribution intermediary between. Once the requester has decided to use a particular service, developers usually by means of development tools Page 42

(such as Microsoft Visual Studio. NET) and through the creation to send the request and access services to handle the response code to bind services.SOA does not need to use UDDI, but because UDDI is built up to complete their work in the SOA, so the UDDI service discovery is a good solution. ESB ESB (Enterprise Service Bus) is a pillar of SOA architecture technology. As a message broker architecture provides message queuing system, using terms such as SOAP or JMS (Java Message Service) and other standard technologies.Some people ESB described an open, standards-based information system, through the simple standard adapters and interfaces, to complete the coarse-grained applications (such as services) and interoperability between other components. ESB's main functions are: communication and information processing, interactive services and safety control, service quality and service level management, modeling, management and self-government, infrastructure, intelligence and so on. 5.8 SOFTWARE INSTALLATION The command prompt window The command prompt is run from its own window by invoking the Windows XP command interpreter that is provided by the file cmd.exe located in the folder \Windows\System32\. (The old DOS command interpreter is command.com.) If you look in this folder you may also see several files that look suspiciously like some of the old DOS files. They are, however, different 32-bit versions with many new features. The command prompt window can be opened by entering "cmd" (without quotes) into Start- Run or through Start-All Programs-Accessories. A black and white window (the colors can be changed) containing the command prompt will open. The window looks just like the old DOS window but don't be fooled, it isn't. Note that it is possible to open several windows containing command prompts, all running independently. It is even possible to run a separate command prompt shell inside another command prompt window Internal and external commands There are two kinds of commands that can be run from the command prompt. There are the internal commands that are built into the command interpreter like "del" and "dir". These commands can only be run from a command prompt (or by invoking the command interpreter in some other way). They are listed in the table below. There is also a large list of external commands that use an additional executable file that can be run from either the command prompt or the Start-Run line. Details of the various commands are available in several places. In the Professional version of Windows XP there is a help file Page 43

ntcmds.chm, which has details of all the commands and their many switches. The help file can be opened by entering (without the quotes) "hh ntcmds.chm" into Start-Run. Starting the Windows XP Setup program at a command prompt To start Windows XP at a command prompt, follow these steps: 1. Insert the Windows XP CD-ROM in the CD-ROM or DVD-ROM drive. 2. Start the computer to an Command Prompt with CD-ROM support. If your computer does not have MS-DOS already installed, or you otherwise cannot start to an Command Prompt in the Boot menu, click the following article number to view the article in the Microsoft Knowledge Base: 187632 How to create a Windows 98 startup disk that supports FAT32 3. Start SMARTDrive if it is not already started. To do this, change to the folder that contains the Smartdrv.exe file, type smartdrv, and then press ENTER. If you do not use SMARTDrive, the Windows XP Setup program may copy files to the hard disk slowly. 4. At the command prompt, type drive:, and then press ENTER (where drive is the drive that contains the Windows XP CD-ROM). 5. Type cd i386, and then press ENTER. 6. Type winnt, and then press ENTER. The Windows XP Setup program starts. 7. Type the path of the Windows XP installation files, and then press ENTER. For example, type d:\i386. The Windows Setup program copies files to the hard disk. When the files are copied, you receive the following message: The MS-DOS based part of The Setup Program Is complete.The Setup program will now restart your computer. After your computer restarts,the Windows XP Setup program will continue. Press ENTER to restart your computer and continue Windows XP Setup. 8. Remove any floppy disks from the computer, and then press ENTER. The computer restarts, and the Windows XP Setup program resumes. Press ENTER to continue. Page 44

9. Follow the steps to select and format a partition where you want to install Windows XP. If your hard disk contains only one partition, do not delete it from the list of existing partitions. The Windows XP Setup program has copied the installation files to this partition. 10. Follow the steps in the Windows Setup Wizard to complete the installation of Windows XP. Environment Variables What Are Environment Variables? Environment Variables are stored in a small area of memory available to all programs running within or on top of the DOS environment (including Windows). They are called "variables" because they can be changed. In fact, some variables need to be reestablished after every reboot. Variable names are NOT case sensitive within Windows. For the Ruby language, Facter stores and retrieves "facts" from operating systems. Windows System Environment Variables These system environment variables are automatically created by Windows upon boot-up in Windows Registry key HKEY_LOCAL_MACHINE\ SYSTEM\ CurrentControlSet\ Control\ Session Manager\ Environment

Variable %SystemDrive% %SystemRoot% %WinDir% %SystemDirectory% %ComSpec%

Sample Typical Value C: C:\WINDOWS C:\WINNT C:\WINDOWS C:\WINNT C:\WINDOWS\System32 C:\WINNT\System32 C:\WINDOWS\system32\cmd.exe The path including the command interpreter program.

Page 45

Variable

Sample Typical Value C:\WINDOWS\Program Files C:\Users\W\AppData\Local\Temp on Windows Vista & 2008 C:\DOCUME~1\Usr\LOCALS~1\Temp (compressed form of) C:\Documents Settings\Temp and Settings\Usr\Local

%programfiles% %Temp% %Tmp%

%HOMEDRIVE% %HOMEPATH%

C: The drive letter associated with the user's home directory The path to the user's home directory as defined in UMD/AD (excluding drive): \Users\<USERNAME> on Windows Vista & 2008 \Documents and Settings\Guest on Windows XP Windows_NT (even on Windows Vista & XP machines The operating system the user is running The name of the domain that contains the user's account. On a stand-alone machine, the same as the machine name. The user's name C:\Users\<USERNAME> The user's root folder

%OS%

%USERDOMAIN%

%USERNAME% %USERPROFILE%

%USERPROFILE%\Desktop The user's desktop folder User Environment Variables Added by Applications User environment variables are HKEY_CURRENT_USER\Environment stored in Windows Registry

Within a command batch file, to list Oracle Environment Variables echo ORACLE_SID = %ORACLE_SID% echo ORACLE_HOME = %ORACLE_HOME% echo ORA_NLS = %ORA_NLS% echo. echo PATH = %PATH% echo. echo Machine Name to messenger service: net name

Page 46

Creating Variables on Linux To update an environment variable that lives until the next reboot: #export PATH=?/usr/local/XXX/bin:$PATH? #echo $PATH Notice that colons are used to separate path items. To create an environment variable that lives forever, update your .bash_profile file: XXXPATH=?/usr/local/XXX/bin? export XXXPATH For a list of environment settings (arguments) for a process with PID 23141 (on Solaris): pargs -ae 23141 Java Environment Variables JDK versions 1.2 and 1.3 require variables Xrunmic_supp and Xbootclasspath %mic_class% The Java interpreter searches the PATH for a class by name and loads the first one it finds. So specify your own library and the most recent library first (especially if you use the same name as a class in a standard library). Also, for best performance, place the most-often used libraries at the front of the path. This applies to LIBPATH and LD_LIBRARY_PATH variables for most often used JNI libraries. Java 1.4 Documentation on Classpath notes that the preferred method for command-line tools such as java, javac, or javadoc is to NOT use environment variables but instead specify -classpath as part of the command invoking a Java program. The System environment variable CLASSPATH must be in upper case (not "classpath"). CLASSPATH is used to specify the full path and file name of every jar file used by java programs. Thus CLASSPATH could be quite long. C:\jdk1.3.1_01\src.jar; C:\jdk1.3.1_01\lib\dt.jar; C:\jdk1.3.1_01\lib\tools.jar; C:\jdk1.3.1_01\jre\lib\il8n.jar; Page 47

C:\jdk1.3.1_01\jre\lib\jaws.jar; C:\jdk1.3.1_01\jre\lib\rt.jar; C:\jdk1.3.1_01\jre\demo\sound\JavaSound.jar; C:\jdk1.3.1_01\demo\jfc\SwingSet2\SwingSet2.jar; C:\jdk1.3.1_01\demo\jfc\SwingApplet\SwingApplet.jar; Sun's JDK adds: C:\jdk1.3.1_01\; C:\jdk1.3.1_01\Bin; C:\jdk1.3.1_01\Lib; A common mistake with CLASSPATH is to specify only folder paths and leave out jar file names. Semicolons should separate each jar file specification. On client machines, Microsoft's VM CLASSPATH is, by default: %windows%\Java\Classes\Classes.zip; This string is stored in environment variable CLASSPATH or Windows registry key HKLM\Software\Microsoft\Java VM\Classpath Windows 95/98 computers should limit CLASSPATH to less than 400 characters. Dick Baldwin notes in his tutorial that if you want the CLASSPATH to point to class files that belong to a package, you should specify a path name that includes the path to the directory one level above the directory having the name of your package. For example, suppose you want the Java interpreter to be able to find classes in the package mypackage. If the path to the mypackage directory is C:\java\MyClasses\mypackage, you would set the CLASSPATH variable as follows: set CLASSPATH=C:\java\MyClasses The purpose of the package directive is to identify a particular class (or group of classes contained in a single source file (compilation unit)) as belonging to a specific package. In Linux: pCLASSPATH=/usr/local/java/jre/bin My CLASSPATH: 1. C:\PROGRA~1\MERCUR~1\MERCUR~1\classes; 2. C:\PROGRA~1\MERCUR~1\MERCUR~1\classes\srv; 3. C:\PROGRA~1\Java\jdk1.5.0_02\lib\rt.jar Page 48

JWSDP INSTALLATION The Java Web Services Developer Pack (Java WSDP) is a free integrated toolkit that allows Java developers to build and test XML applications, Web services, and Web applications with the latest Web services technologies and standards implementations. The JWSDP includes the following Apache Tomcat EA development container . Ant Build Tool.
Download WSDP
The JWSDP is available at

http://java.sun.com/webservices/downloads/webservicespack.html. The latest version is 1.3. For this you will need Java 1.4. For Mac OS X Java 1.4 For Mac OS X 10.2 or ealier, you will need an earlier version. These can be hard to find. Java(TM) Web Services Developer Pack 1.1 has been available at http://java.sun.com/webservices/downloads/1.1/webservicespack_1.1.html . J2EE The ant build tool will need the java 2 Enterprise Edition archive j2ee.jar. For this example we will download version the version from http://java.sun.com/j2ee/sdk_1.3/. Install Start the download script. You may need to decompress the download if your browser did not. cd download directory chmod +x on jwsdp-1_3-unix.sh ./jwsdp-1_3-unix.sh his will starts install shield. Agree to the license and follow the directions. For the example, we choose the options.
o o o

place in $HOME/jwsdp-1.1 no web proxy typical config with Tomcat

We now will move the extract to its real home in /Library or /opt
o o o

Create target directory mkdir /Library/JWSDP Page 49

o o o o o o o o o

-- or -mkdir /opt/JWSDP Move/copy jwsdp-1.1 to directory mv jwsdp-1.1 /Library/JWSDP Create Home links

cd /Library/JWSDP ln -s jwsdp-1.1 Home The templates in later sections assume the location is in /opt/tomcat. We create the link. On OS X, you may need to create the /opt directory. START UP TOMCAT Look at /Library/JWSDP/docs/tomcat/index.html for info on how to configure and set up tomcat. There is a link for Install and Run under Getting Started. The basic steps are as follows. Set JAVA_HOME to your java installation Set CATALINA_HOME to your container installation Invoke the start up script sudo $CATALINA_HOME/bin/startup.sh Use your browser to access the server with http://localhost:8080. Be prepared to wait awhile for tomcat to start. It neeTM to compile and load alot. If all goes well, you should ds see a page something like Java Web Services Developer Pack 1.1 The sample files contains a file Mac OS X start up item. You need to edit the Tomcat startup file to match your installation. export JAVA_HOME=/System/Library/Frameworks/JavaVM.framework/Home export CATALINA_HOME="/Library/JWSDP/Home" Place the startup in the /Library/StartupItems sudo mv Tomcat /Library/StartupItems Install the J2EE jar We only need to unpack the download and move it to our java environment tar xf j2sdkee1.3.1.tar cd j2sdkee1.3.1/lib cp j2ee.jar /Library/Java/Extensions Page 50

Linux will of course have a different location. TES T


quick test

is to move to a clean directory and execute ant. You should see a message that the build.xml is missing. % ant Buildfile: build.xml does not exist! Build failed 5.9 STORING JAVA OBJECTS AS FILES Object Serialization Object Serialization extends the core Java Input/Output classes with support for objects. Object Serialization supports the encoding of objects, and the objects reachable from them, into a stream of bytes; and it supports the complementary reconstruction of the object graph from the stream. Serialization is used for lightweight persistence and for communication via sockets or Remote Method Invocation (RMI). The default encoding of objects protects private and transient data, and supports the evolution of the classes. A class may implement its own external encoding and is then solely responsible for the external format. Serialization now includes an API that allows the serialized data of an object to be specified independently of the fields of the class and allows those serialized data fields to be written to and read from the stream using the existing protocol to ensure compatiblity with the default writing and reading mechanisms. Support for deserialization of unshared objects Serialization now provides extra support for deserialization of objects which are known to be unshared in the data-serialization stream. The new support is provided by the following API additions in package java.io: ObjectInputStream.readUnshared() ObjectOutputStream.writeUnshared(Object obj) ObjectStreamField(String name, Class type, boolean unshared) Previously, security-conscious programmers had to clone private internal objects after deserializing them to guard against the possibility that outside parties with access to the serialization stream could append spurious back handles to the sensitive objects, resulting in extra references to them during deserialization. However, this solution slows performance and wastes memory -- two objects must be created and a copy operation invoked in order to ensure a unique reference to a single usable object. Security permissions now required to override putFields, readFields Beginning with J2SE 1.4.0, ObjectOutputStream's public one-argument constructor requires the "enableSubclassImplementation" SerializablePermission when invoked Page 51

(either

directly

or

indirectly)

by

subclass

which

overrides

ObjectOutputStream.putFields or ObjectOutputStream.writeUnshared. Also beginning with J2SE 1.4.0, ObjectInputStream's public one-argument constructor requires the "enableSubclassImplementation" SerializablePermission when invoked (either directly or indirectly) by a subclass which overrides ObjectInputStream.readFields or ObjectInputStream.readUnshared. These changes will not affect the great majority of applications. However, it will affect any ObjectInputStream/ObjectOutputStream subclasses which override the putFields or readFields methods without also overriding the rest of the serialization infrastructure. Support for class-defined readObjectNoData method In addition to supporting class-defined writeObject() and readObject() methods, serialization now includes support for class-defined readObjectNoData() methods. Each class-defined readObjectNoData() method is required to have the following signature: private void readObjectNoData() throws ObjectStreamException; The readObjectNoData() method is analogous to the class-defined readObject() method, except that (if defined) it is called in cases where the class descriptor for a superclass of the object being deserialized (and hence the object data described by that class descriptor) is not present in the serialization stream. More formally: If object O of class C is being deserialized, and S is a superclass of C in the VM which is deserializing O, then S.readObjectNoData() is invoked by ObjectInputStream during the deserialization of O if and only if the following conditions are true: 1. S implements java.io.Serializable (directly or indirectly). 2. S defines an readObjectNoData() method with the signature listed above. 3. The serialization stream containing O does not include a class descriptor for S among its list of superclass descriptors for C. Note that readObjectNoData() is never invoked in cases where a class-defined readObject() method could be called, though serializable class implementors can call readObjectNoData() from within readObject() as a means of consolidating initialization code. See the class description in the API specification of ObjectInputStream for more information. Serialization performance enhancements Several changes have been made to serialization to improve overall performance: UTF string reads/writes have been optimized to reduce unnecessary memory allocation and synchronization/method call overhead. Code for reading and writing primitive data arrays has been streamlined. Float and double array reads/writes have been reimplemented to minimize the number of calls to native methods. Internal buffering has been improved. Reflective operations for getting/setting primitive field values have been batched to minimize the number of separate native method calls. Page 52

Defining serializable fields for a class By default, the values of all non-static and non-transient fields of a serializable class are written when an instance of that class is serialized. In 1.2, a new mechanism was introduced to allow classes finer control of this process. By declaring a special field serialPersistentFields, serializable classes can dictate which fields will be written when instances of the class (or subclasses) are serialized. This feature also enables classes to "define" serializable fields which do not correspond directly to actual fields in the class. Used in conjunction with the serializable fields API (described below), this capability allows fields to be added or removed from a class without altering the serialized representation of the class. See sections 1.5 and 1.7 of the Java Object Serialization Specification for details. Serializable fields API (since 1.2) Introduced in 1.2, the serializable fields API allows class-defined writeObject/readObject methods to explicitly set and retrieve serializable field values by name and type. This API is particularly useful for classes that need to maintain backwards compatibility with older class versions; in some cases, the older version of the class may have defined a set of serializable fields that cannot be mapped directly to the fields of the current class. In this case, newer versions of the class can define custom writeObject and readObject methods that convert the internal state of a given instance of the (new) class into the "old" serialized form, and vice versa. For more information, see section 1.7 of the Java Object Serialization Specification. 5.10 DATABASES AND JAVA SERVLETS The Java Programming Language and JDBC A Java program, written properly and according to specification, can run on any Java technology-enabled platform without recompilation. The Java programming language is completely specified and, by definition, a Java technology-enabled platform must support a known core of libraries. One such library is the java.sql package or JDBC, which you can think of as a portable version of ODBC, and is itself a major standard. Using the Java programming language in conjunction with JDBC provides a truly portable solution to writing database applications. A JDBC driver is a class that implements the JDBC Driver interface and understands how to convert program (and typically SQL) requests for a particular database. Clearly, the driver is what makes it all work. There are four different driver types, which are discussed in the JDK (Java Development Kit) documentation at JDBC Driver Types. This course uses type 4 drivers because of their nearly zero installation requirements and dynamic nature. Another driver type may make more sense for your particular project. Most database vendors now provide drivers to implement the JDBC API for their particular systems..

Page 53

JDBC 1.0

The JDBC 1.0 API provided the basic framework for data access, consisting primarily of the following interfaces and classes: o o o o o o o o o o Driver DriverManager Connection Statement PreparedStatement CallableStatement ResultSet DatabaseMetaData ResultSetMetaData Types

As you will see in this course, you pass a Driver to the DriverManager and then obtain a Connection. A Statement, PreparedStatement, or CallableStatement is then created and used to update the database or execute a query. A query returns a ResultSet containing the requested data, which is retrieved by Type. DatabaseMetaData and ResultSetMetaData classes are available to provide information about a database or a ResultSet. JDBC 2.0 The JDBC 2.0 API is broken into two parts: the core API, which this course discusses, and the JDBC 2.0 Optional Package. In general, the JDBC 2.0 core API adds a few more classes, but is primarily concerned with performance, class enhancements and functionality, and the new SQL3 (also known as SQL-99) datatypes.The new functionality in the core API includes scrollable result sets, batch updates, programmatic inserts, deletes, and updates, performance hints, character streams for streams of internationalized Unicode characters, full precision for java.math.BigDecimal values and support for time zones in Date, Time, and Timestamp values.At the time this course was prepared, the JDBC 3.0 draft was under review and planned to be included in the 1.4 release of the JDK. A Complete Example The first hands-on experience with JDBC in this course involves a basic but complete example to illustrate the overall concepts related to creating and accessing information in a database. The fundamental issues encountered when writing any database application are: Creating a database. A database can be created using tools supplied by the database vendor, or via SQL statements fed to the database from a Java program. Since there is normally a database administrator (of course, as a developer, this may Page 54

be you), and not all JDBC drivers support database creation through Data Definition Language ( DDL), this topic will, in general, be left as DBMS (DataBase Management System) and driver specific. If you are interested in more details, there typically is a CREATE DATABASE statement, but be sure to review your DBMS SQL reference, as it is not part of the SQL standard, but is DBMS-dependent. Connecting to the database. This is the first job of the JDBC driver, and specific information must be passed to it. The basic information requirements are a Database URL (Universal Resource Locator), a User ID, and a Password. Depending on the driver, there may be many other arguments, attributes, or properties available. Here are two examples: Creating a table. While the database contains tables, the tables are the actual components that contain data, in the form of rows and columns. Table creation is accomplished by the DDL CREATE TABLE statement. This statement has many options, some differing from vendor to vendor; again, be sure to review your DBMS SQL reference for specifics. Inserting information into a database. Again, data can be entered and maintained using database-specific tools, or with SQL statements sent programmatically. This course, as might be expected, will focus on using JDBC to send SQL statements to the database. Selectively retrieving information. After sending SQL commands to retrieve the data and using JDBC to get results into variables, program code works as with any other variables to display or manipulate that data MS Access JDBC Driver -- Connecting MS Access with Java Download MS Access JDBC driver here. To connect Java with MS Access, you need a JDBC driver. Although Microsoft do not produce a JDBC driver for MS Access, you can use the Easysoft JDBC-ODBC Bridge as a MS Access JDBC driver. Use the JDBC-ODBC Bridge to provide the connectivity layer between your Java code and MS Access database. The MS Access database can be on the same machine as your Java or a remote machine.

Page 55

Accessing MS Access from Java Prerequisites An installed and licensed Easysoft JDBC-ODBC Bridge (JOB) server on a supported Windows platform that has Microsoft Office installed. If you have not yet installed the JOB software or you are having problems with the installation, use our. to help you through the installation. An existing Access database file (.mdb) on the Windows machine. Assumptions You accepted the default options during the install. This tutorial was written assuming the demonstration clients were installed on the same Windows machine as the JOB server. You can check to see if you have these installed by choosing Start > Programs > Easysoft > JDBC-ODBC Bridge. From here you should see both an Applet demo and an Application demo. We have also assumed that you have installed the JOB software as a valid Windows User who has access to the target database. Configuring the Microsoft Access ODBC Data Source You will find the ODBC Administrator within Administrative Tools from your Control Panel.From here you will create your new System DSN. Click the Add button and then select the Microsoft Access Driver and click Finish.Give your DSN a meaningful name and click Select. Here you will be able to browse to your existing .mdb file.Once you have selected the database you want to access, click OK and then OK again to exit the dialog box. You have now created your data source. Running the Demo Applet Within your services manager, make sure that the JOB service is running, and then open a web browser and go to the following URL http://localhost:8031.This will open the JOB Web Administrator where you have many configuration options. On the left hand Page 56

side, you will see a Test Applet link. This will show you a box with various parameters. The Logon User and Password should be the same as your valid Windows details.Once you have entered your username and password, click the Connect button. This will then display a pop-up box: CONNECTING TO MYSQL This sample Java program connects to MySQL database using JDBC, executes a query and retrieves and prints the value of the database field.This same sample code can be used to connect to any type of database, all you need to do is change the connection url (dbUrl in the sample). For this code to work properly, you will need to download the mysql driver for JDBC in other words Java Connectors from mysql.com site.If after downloading the URL it still doesn't work then it is probably due to the classpath. You will have to add the driver jar file in the classpath. import java.sql.*; import javax.sql.*; public class jdbcdemo{ public static void main(String args[]){ String dbtime; String dbUrl = "jdbc:mysql://your.database.domain/yourDBname"; String dbClass = "com.mysql.jdbc.Driver"; String query = "Select * FROM users"; try { Class.forName("com.mysql.jdbc.Driver"); Connection con = DriverManager.getConnection (dbUrl); Statement stmt = con.createStatement(); ResultSet rs = stmt.executeQuery(query); while (rs.next()) { dbtime = rs.getString(1); System.out.println(dbtime); } //end while con.close(); } //end try catch(ClassNotFoundException e) { e.printStackTrace(); } Page 57

catch(SQLException e) { e.printStackTrace(); }} //end main } //end class The JDBC API is a Java API that can access any kind of tabular data, especially data stored in a Relational Database. JDBC helps you to write java applications that manage these three programming activities: o Connect to a data source, like a database o Send queries and update statements to the database o Retrieve and process the results received from the database in answer to your query The following simple code fragment gives a simple example of these three steps: Connection con = DriverManager.getConnection ( "jdbc:myDriver:wombat", "myLogin","myPassword"); Statement stmt = con.createStatement(); ResultSet rs = stmt.executeQuery("SELECT a, b, c FROM Table1"); while (rs.next()) { int x = rs.getInt("a"); String s = rs.getString("b"); float f = rs.getFloat("c"); } This short code fragment instantiates a DriverManager object to connect to database driver and log into the database, instantiates a Statement object that carries your SQL language query to the database; instantiates a ResultSet object that retrieves the results of your query, and executes a simple while loop, which retrieves and displays those results. It's that simple.

Page 58

S-ar putea să vă placă și