Web Technology - V Unit - Notes
Web Services: JAX-RPC-Concepts-Writing a Java Web
Service-Writing a Java Web Service Client-Describing Web Services: WSDL-
Representing Data Types: XML Schema-Communicating Object Data: SOAP Related
Technologies-Software Installation-Storing Java Objects as Files-Databases and
Java Servlets.
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.
Web Services have Two
Types of Uses Reusable application-components.
There are things
applications needs 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 simpler:
·
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
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
ImportsSystem.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" %>
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) e
nd 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. This introduces the
JAXRPC 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.
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 throughout 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 contains 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.
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 required, the service endpoint interface,
SunRegPort, implements the java.rmi.Remote 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. 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.
Course and Employee JAX-RPC Value types
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 he
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.
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 files in the WAR file, and so
forth. Code Sample 4 shows the web.xml for deploying the SunReg service on a
JWSDP container.
Code Sample 4:
The web.xml for deploying the SunReg service
on a JWSDP container
<web-app> <context-param>
<param-name>dbUrl</param-name> <paramvalue>
jdbc:cloudscape:sunregDB</param-value>
</context-param> <servlet> <servletname>
SunregEndpoint</servlet-name>
<servletclass>
com.sun.xml.rpc.server.http.JAXRPCServlet
</servlet-class> <init-param>
<param-name>configuration.file</param-name>
<param-value> /WEBINF/
SunRegService_Config.properties
</param-value> </init-param> <load-onstartup>
0</load-on-startup> </servlet>
<servlet-mapping> <servletname>
SunregEndpoint </servlet-name>
<url-pattern>/jaxrpc/*</url-pattern> </servletmapping>
</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 jaxrpcri. 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.
You'll find the xrpcc tool in the directory
JWSDP_HOME/bin. It is executed by entering xrpcc.sh 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.
- keep
instructs the tool to keep the intermediate generated source files.
- d
specifies the destination directory for generated artifacts.
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.
JAX-RPC runtime and generated classes
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.propertiesto
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 a 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=/WEBINF/ 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.
Deploying the service and
related files. The developer writes two Java language files, two XML files, and
the client application.
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 WEBINF/
classes/sunreg/SunRegPort.class WEB-INF/
classes/sunreg/SunRegImpl.class WEBINF/
classes/sunreg/SunRegPort_Tie.class WEBINF/
classes/sunreg/Course_SOAPSerializer.class
WEBINF/
classes/sunreg/Employee_SOAPSerializer.class
WEBINF/
classes/sunreg/GetCourseInfo_RequestStruct.class
WEBINF/
classes/sunreg/GetCourseInfo_ResponseStruct.class
WEBINF/
classes/sunreg/RegisterCourseInfo_RequestStruct.class
WEBINF/
classes/sunreg/RegisterCourseInfo_ResponseStruct.class
WEBINF/
classes/sunreg/GetCourseInfo_RequestStruct_SOAPSerializer.class
WEBINF/
classes/sunreg/GetCourseInfo_ResponseStruct_SOAPSerializer.class
WEBINF/
classes/sunreg/ RegisterCourseInfo_RequestStruct_SOAPSerializer.class
WEBINF/
classes/sunreg/
RegisterCourseInfo_ResponseStruct_SOAPSerializer.class WEBINF/
classes/sunreg/GetCourseInfo_ResponseStruct_SOAPBuilder.class
WEBINF/
classes/sunreg/RegisterCourseInfo_RequestStruct_SOAPBuilder.class
WEBINF/
classes/sunreg/SunRegService_SerializerRegistry.class
WEBINF/
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
The
display that appears when a 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.
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 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">
<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.3 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/.
illustrates how JAX-RPC technology manages
communication between a web service and client. 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 AXRPC 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:
1. Code the SEI and implementation class and
interface configuration file.
2. Compile the SEI and implementation class.
3. Use wscompile to generate the files
required to deploy the service.
4. Use deploytool to package the files into
a WAR file.
5. Deploy the WAR file. The tie classes
(which are used to communicate with clients) are generated by the Application
Server during deployment.
6. Code the client class and WSDL
configuration file.
7. Use wscompile to generate and compile the
stub files.
8. Compile the client class.
9. Run the client.
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:
- 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
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 J2EE-compliant 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 generatewsdl 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. 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 FileNewWeb Component. The
wizard displays the following dialog boxes.
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 <INSTALL>/j2eetutorial14
/examples/jaxrp/helloservice/.
a. In the WSDL File combo box, select
WEB-INF/wsdl/MyHelloService.wsdl.
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:
1. In deploytool, select MyHelloService in
the tree.
2. In the tree, select HelloImpl.
3. Select the Aliases tab.
4. In the Component Aliases table, add
/hello.
5. In the Endpoint tab, select hello for the
Endpoint Address in the Sun-specific Settings frame.
6. Select FileSave.
Deploying the Service
In deploytool, perform these steps:
1. In the tree, select MyHelloService.
2. Select ToolsDeploy.
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.4 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]);
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:
<configurationxmlns="http://java.sun.com/xml/ns/jax-rpc/ri/config">
<wsdl location="http://localhost:8080/hello-
jaxrpc/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
5.5 DESCRIBING WEB
SERVICES - WSDL
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 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 namespace http://schemas.xmlsoap.org/wsdl/soap/ This namespace is used
for SOAP-specific 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 byte Integer Range validated on conversion.
date Date Time set to 00:00:00
dateTime
Date
double Double
duration String No validation or
conversion performed
ENTITIES String No validation or
conversion performed
ENTITY S tring No validation or
conversion performed
float Single Page.
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' transport='http://schemas.xmlsoap.org/soap/http'
/>
5.6 REPRESENTING DATA
TYPES:
XML SCHEMA BUILT-IN
DATATYPES
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
- 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
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 <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:
<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
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.7 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
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
<?xml version="1.0"?>
<soap:Envelope
xmlns:soap="http://www.w3.org/2001/12/soapenvelope"
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. 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/soap-encoding">
... 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/soapenvelope"
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>
</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
- The
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
holds errors and status information for a SOAP message. The optional SOAP Fault
element is used to indicate error messages. 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:
SubElement
Description
<faultcode> A code for identifying the
fault
<faultstring> A human readable
explanation of the fault
<faultactor> Information about who
caused the fault to happen
<detail> Holds application specific
error information related to the Body element
5.8 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 (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.9 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 StartRun 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 possibl e 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 int ernal comm ands that are
buil t int o the comm and int erpreter li ke “ 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 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.
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). The y ar e c all ed “v ariabl es” be
cause the y c an be chan ged. In f act,
some v ariables 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
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” ). C LASS P A TH is used to specif y 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;
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.
2.C:\PROGRA~1\MERCUR~1\MERCUR~1\classes\srv;
3. C:\PROGRA~1\Java\jdk1.5.0_02\lib\rt.jar
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 .
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 constructorrequires the
"enableSubclassImplementation" SerializablePermission when invoked (either
directly or indirectly) by a 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 Object Input Stream/ Object Output Stream 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.
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 Javatechnology-enabled platform
without recompilation. The Java programming language iscompletely specified
and, by definition, a Java technology-enabled platform must supporta 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 Javaprogramming language in conjunction with JDBC provides a truly portable
solution twriting 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. Clearlythe driver is
what makes it all work. There are four different driver types, which
ardiscussed in the JDK (Java Development Kit) documentation at JDBC Driver
Types. This course uses type 4 drivers because of their nearly zero
installation requirements anddynamic nature. Another driver type may make more
sense for your particular projecMost database vendors now provide drivers to
implement the JDBC API for theirparticular systems..
JDBC 1.0
The JDBC 1.0 API provided the basic
framework for data access, consisting primarily of the following interfaces and
classes:
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 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 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
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.
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 Getting Started Guide to
help you through the installation.
An existing
Access database file (.mdb) on the Windows machine.
FIG
5.1 (JOB) server on a supported Windows platform
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 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.
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:
Connect to a data source, like a database
Send queries and update statements to the database
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.
Comments
Post a Comment