Professional Documents
Culture Documents
SOA and Web Services Tutorials in this site helps you learn more about service-
oriented architecture (SOA) and web services. So, why wait learn SOA & Web
Services now.
1. What is SOA (Service Oriented Architecture)?
An introduction to the Service Oriented Architecture.
2. Web Services - An Introduction
The next generation of distributed computing has arrived. A Web service is a unit
of managed code that can be remotely invoked using HTTP, that is, it can be
activated using HTTP requests.
3. Why Web Services?
In this section of WebServices tutorials series we will understand why Web
Services are developed and what are the benefits of using Web Services for the
development of Enterprise applications.
4. J2EE Web Service Development with Attachments Using Axis
This article discusses the development of a java web service that takes DIME or
MIME attachment as input and returns the output as an appropriate attachment.
(Author: Murthy Vaddiparthi)
Building a Simple Web Service by Jeevaraj Gnanaselvan Dhanaraj
(jeevaraj_1970@yahoo.com)
5. Developing Simple Web Service
In this tutorial we will create a simple web service and a client web application
using eclipse IDE along with Lomboz plug in. We will also deploy and test the
web service on Tomcat 5.5.4 web application server. This application, while
simple, provides a good introduction to Web service development and some of the
Web development tools available.
Web Services Tutorials by R.S.RAMASWAMY (rs.ramaswamy@gmail.com)
6. Exposing a javabean (jws) from Tomcat/Axis
In this experiment, we attempt exposing a javabean (jws) from Tomcat/Axis and
consuming that service in an ASP.net program.
7. Understanding Apache Axis
Apache Axis can be thought of as an improved implementation of Apache SOAP.
While Apache SOAP used DOM for XML parsing, Axis makes use of SAX and
hence it is more efficient and fast. Secondly, it supports automatic generation of
WSDL (Web Service Description Language) file.
8. Creating and testing an EJB in WebLogic Server
In this section you will learn how to create and test an EJB in WebLogic Server.
9. Drop-In Deployment in Apache AXIS
This tutorial discusses about drop-in deployment in Apache AXIS.
10. Apache AXIS-Deployment using WSDD File
In this part, we will follow the WSDD method. We have already created
sqlaxisbean.java as explained in the last article. We used it as sqlaxisbean.jws
(drop-in method). There was no necessity to compile this file.But in WSDD
method (web-service deployment descriptor), we should compile this file.Next,
we create the WSDD file. Then, we deploy this bean to tomcat. We may have to
restart the tomcat4.1 webserver.
11. Exposing EJB as XML-Webservice
In this web service tutorial you will learn how to expose an EJB as XML-
Webservice using Axis.
12. Accessing ejb-webservice through WAP
This tutorial discusses how to Access ejb-webservice using WAP (Wireles-
Application Protocol)
13. J2ME CLIENT FOR EJB & EJB-WEBSERVICE
In the previous section,we've dealt with how to write WAP client for accessing
ejb. In the same way, we are going to see how to write J2ME client for ejb.
Broadly SOA can be classified into two terms: Services and Connections.
Services:
Connections:
Connections means the link connecting these self-contained distributed services with
each other, it enable client to Services communications. In case of Web services SOAP
over HTTP is used to communicate the between services.
SOA is much different from point-to-point architectures. SOA comprise loosely coupled,
highly interoperable application services. These services can be developed in different
development technologies (such as Java, .NET, C++, PERL, PHP), the software
components become very reusable i.e. the same C# (C Sharp) service may be used by a
Java application and / or any other programming language. WSDL defines an standard,
which encapsulates / hides the vendor / language specific implementation from the
calling client / service.
SOA definitions
(From http://en.wikipedia.org/wiki/Service-oriented_architecture )
Why SOA?
SOA architecture enables seamless Enterprise Information Integration. Here are some of
the Benefits of the Service Oriented Architecture:
Due to its platform independence, it allows companies to use the software and
hardware of their choice .
There is no threat of vendor lock-in
SOA enables incremental development, deployment, and maintenance.
Companies can use the existing software (investments) and use SOA to build
applications without replacing existing applications
The training costs are low, so the available labor pool can be used for running the
applications
In this section of the Web Services tutorial you will be familiarized with the Web
Services.
Introduction
The next generation of distributed computing has arrived. A Web service is a unit of
managed code that can be remotely invoked using HTTP, that is, it can be activated using
HTTP requests.
One can access Web services using nothing but HTTP. Of all the protocols in existence
today, HTTP is the one specific wire protocol that all platforms tend to agree on. Thus ,
using Web services, a Web service developer can use any language he wish and a Web
service consumer can use standard HTTP to invoke methods a Web service provides. The
bottom line is that we have true language and platform integration . Simple Object
Access Protocol (SOAP) and XML are also two key pieces of the Web services
architecture.
Web services are registered and announced using the following services and protocols.
Many of these and other standards are being worked out by the UDDI project, a group of
industry leaders that is spearheading the early creation and design efforts.
Simple Object Access Protocol (SOAP) is a protocol for initiating conversations with a
UDDI Service. SOAP makes object access simple by allowing applications to invoke
object methods or functions, residing on remote servers. A SOAP application creates a
request block in XML, supplying the data needed by the remote method as well as the
location of the remote object itself.
Web Service Description Language (WSDL), the proposed standard for how a Web
service is described, is an XML-based service IDL (Interface Definitition Language) that
defines the service interface and its implementation characteristics. WSDL is referenced
by UDDI entries and describes the SOAP messages that define a particular Web service.
ebXML (e-business XML) defines core components, business processes, registry and
repository, messaging services, trading partner agreements, and security.
Even though Web services are being built using existing infrastructure, there exists a
strong necessity for a number of innovative infrastructures. The core architectural
foundation of Web services are XML, XML namespaces, and XML schema. UDDI,
SOAP, WSDL, ebXML and security standards are being developed in parallel by
different vendors
There are a number of mechanisms for constructing Web services. Microsoft has come
out with a new object-oriented language C# as the development language for Web
services and .NET framework. Microsoft has an exciting tool called Visual Studio .NET
in this regard. The back end database can be Microsoft SQL Server 2000 in Windows
2000 Professional.
Sun Microsystems has its own set of technologies and tools for facilitating Web services
development. Java Servlets, Java Server Pages (JSPs), Enterprise JavaBeans (EJB)
architecture and other Java 2 Enterprise Edition (J2EE) technologies play a very critical
role in developing Web services.
There are a number of tools for developing Web services. They are Forte Java IDE,
Oracle JDeveloper, and WebGain Studio.
Sun Microsystems has taken an initiative called Sun ONE (Open Network Environment)
and is planning to push Java forward as a platform for Web services. It is developing Java
APIs for XML-based remote procedure calls and for looking up services in XML
registries - two more JAX family APIs: JAX/RPC (Java API for XML Remote Procedure
Calls) and JAXR (Java API for XML Registries). These will wrap up implementations of
Web services standards, such as SOAP and UDDI.
IBM also for its part has already developed a suite of early-access tools for Web services
development. They are Web Services Toolkit (WSTK), WSDL Toolkit, and Web
Services Development Environment (WSDE).
Apache Axis is an Open Source SOAP server and client. SOAP is a mechanism for
inter-application communication between systems written in arbitrary languages, across
the Internet. SOAP usually exchanges messages over HTTP: the client POSTs a SOAP
request, and receives either an HTTP success code and a SOAP response or an HTTP
error code. Open Source means that you get the source, but that there is no formal support
organization to help you when things go wrong.
Conclusion
For the last few years, XML has enabled heterogeneous computing environments to share
information over the Web. It now offers a simplified means by which to share process as
well. From a technical perspective, the advent of Web services is not a revolution in
distributed computing. It is instead a natural evolution of XML application from
structured representation of information to structured representation of inter-application
messaging.
Prior to the advent of Web services, enterprise application integration (EAI) was very
difficult due to differences in programming languages and middleware used within
organizations. This led to the situation where interoperability was cumbersome and
painful. With the arrival of Web services, any application can be integrated as long as it
is Internet-enabled.
It is difficult to avoid the popularity and hype that is surrounding Web services. Each
software vendor has some initiative concerning Web services and there is always great
speculation about the future of the market for them. Whichever way it turns out, Web
service architectures provide a very different way of thinking about software
development. From client-server to n-tier systems, to distributed computing, Web service
applications represent the culmination of each of these architectures in combination with
the Internet.
Exposing the function on to network: A Web service is a unit of managed code that can
be remotely invoked using HTTP, that is, it can be activated using HTTP requests. So,
Web Services allows you to expose the functionality of your existing code over the
network. Once it is exposed on the network, other application can use the functionality of
your program.
Standardized Protocol: Web Services uses standardized industry standard protocol for
the communication. All the four layers (Service Transport, XML Messaging, Service
Description and Service Discovery layers) uses the well defined protocol in the Web
Services protocol stack. This standardization of protocol stack gives the business many
advantages like wide range of choices, reduction in the cost due to competition and
increase in the quality.
Low Cost of communication: Web Services uses SOAP over HTTP protocol for the
communication, so you can use your existing low cost internet for implementing Web
Services. This solution is much less costly compared to proprietary solutions like
EDI/B2B.
Support for Other communication means: Beside SOAP over HTTP, Web Services
can also be implemented on other reliable transport mechanisms. So, it gives flexibility
use the communication means of your requirement and choice. For example Web
Services can also be implemented using ftp protocol (Web services over FTP).
Web Services are Self Describing: Web Services are self describing applications, which
reduces the software development time. This helps the other business partners to quickly
develop application and start doing business. This helps business to save time and money
by cutting development time.
Automatic Discovery: Web Services automatic discovery mechanism helps the business
to easy find the Service Providers. This also helps your customer to find your services
easily. With the help of Web Services your business can also increase revenue by
exposing their own Web Services available to others.
Business Opportunity: Web Services has opened the door to new business opportunities
by making it easy to connect with partners.
Summary
This article discusses the development of a java web service that takes DIME or MIME
attachment as input and returns the output as an appropriate attachment. It also discusses
the client implementation for these web services. It uses the open source Apache Axis
implementation of the web services. The whole source code can be downloaded from
source zip file. Author expects that the intended audience for this article have a basic
understanding of J2EE web service development.
Introduction
As a developer very often one faces the following challenges in the context of J2EE web
service development with attachments:
In this article, I have shown the implementation for all the above three tasks by using
Apache Axis and Tomcat. I have used XML string as an attachment.
During the later half of last year I worked on a project implementing a client to access a
web service written in C# that takes a big chunk of XML string as a DIME attachment.
Recently I implemented a web service with attachments using Axis. While going through
the process I found that there is very little documentation using Apache Axis especially in
implementing the code that handles the attachments and I have decided to share my
experience with the rest of the community.
I have used Tomcat 5.x as the web server to install the web application and uses axis
1.2.1. To implement a web service that takes either a MIME or DIME attachment, we
have to define an operation that takes a parameter javax.activation.DataHandler as a
parameter. I have defined two operations -- one that handles a DIME attachment and
sends a DIME attachment and another one that handles a MIME attachment and sends a
MIME attachment as shown in Listing 1.
Whether it is a DIME attachment or MIME attachment the way we get the data from the
attachment is similar. But it is very important to make an input data validation at every
point. The very first step in the getDimeData() or getMimeData() is to check whether
the attachment we received is of correct type or not. If the attachment is not of the
expected type we can throw an InputValidationException. Listing 2 shows the code
to handle the DIME attachment.
MessageContext msgContext =
MessageContext.getCurrentContext();
Message rspmsg =
msgContext.getResponseMessage();
log.info("org.apache.axis.attachment
s.Attachments.SEND_TYPE_DIME : "
+
org.apache.axis.attachments.Attachme
nts.SEND_TYPE_DIME);
int inputAttachmentType =
rspmsg.getAttachmentsImpl().getSendT
ype();
log.info("inputAttachmentType : " +
inputAttachmentType);
if (inputAttachmentType !=
Attachments.SEND_TYPE_DIME){
String failMsg = "Attachment
passed is not a DIME attachment,
please check.";
throw new
InputValidationException("Invalid
input data error : " + failMsg);
}
MessageContext msgContext =
MessageContext.getCurrentContext();
Message rspmsg =
msgContext.getResponseMessage();
log.info("org.apache.axis.attachment
s.Attachments.SEND_TYPE_MIME : "
+
org.apache.axis.attachments.Attachme
nts.SEND_TYPE_MIME);
int inputAttachmentType =
rspmsg.getAttachmentsImpl().getSendT
ype();
log.info("inputAttachmentType : " +
inputAttachmentType);
if(inputAttachmentType !=
Attachments.SEND_TYPE_MIME){
String failMsg = "Attachment
passed is not a MIME attachment,
please check.";
throw new
InputValidationException("Invalid
input data error : " + failMsg);
}
After checking for the correct type of attachment, we need to some how
get the contents in the attachment. We need to get the byte array in the
attachment. Although attachment can be used to send images and various
other types of content, in our current problem we are just dealing with
an XML string. Listing 4 shows the code to get an array of bytes from the
DataHandler object. The procedure to get the byte array is similar what
ever may be the attachment.
Once we have the byte array it is easy to get the actual content if we
know the type of content. Since it is a String in the current scenario,
we can use UTF-8 charset to convert it to the original String. Listing 5
shows the code to get the input String passed by the client from the
attachment.
private String
getInputString(DataHandler dh)
throws InputValidationException {
String failMsg = null;
if (dh == null ) {
failMsg = "Attachment
is null -- missing attachment.";
throw new
InputValidationException("Invalid
data error : " + failMsg);
} else {
byte[] responseBytes
= null;
try {
responseBytes
= Utils.getBytesFromDataHandler(dh);
log.info("responseBytes
length : " + responseBytes.length);
} catch(IOException
e) {
failMsg =
"Error occured while parsing the
input XML, please check the input.";
throw new
InputValidationException("Invalid
input data error : " + failMsg);
}
if(responseBytes ==
null) {
failMsg =
"null data received while parsing
the input XML, please check the
input.";
throw new
InputValidationException("Invalid
input data error : " + failMsg);
}
String inputStr =
null;
try {
inputStr = new
String(responseBytes, "UTF-8");
log.info("inputStr : " +
inputStr);
}
catch(UnsupportedEncodingException
e) {
failMsg =
"Please check the encoding attribute
value of the input XML, it should be
UTF-8.";
throw new
InputValidationException("Invalid
input data error : " + failMsg);
}
return inputStr;
}
}
After getting the input String, we can use this input String to do the
necessary operations such as database retrieval or update. After
performing the necessary operations according to business need, we now
have an output file let's say output.xml. In this article I have used an
output String created from an output.xml for an illustration and in a
real application this output can be any String generated by any process.
Now our goal is to return this result to the client as an appropriate
attachment i.e., if the input is DIME attachment we have to return the
output String as a DIME attachment and if the input is a MIME attachment
we have to return output String as a MIME attachment. Listing 6 shows the
procedure to send the output String as a DIME attachment.
log.info("setting the
MIME type of attachment
as the sender sends it as
MIME.");
rspmsg.getAttachmentsImpl
().setSendType(inputAttac
hmentType);
// Create temp file.
File temp =
File.createTempFile("Mime
Output", null);
// Delete temp file when
program exits.
temp.deleteOnExit();
// Write to temp file
BufferedWriter out = new
BufferedWriter(new
FileWriter(temp));
out.write(result);
out.close();
dh = new DataHandler(new
FileDataSource(temp));
After developing the web service it is time to build the war file and deploy the
application. The src.zip file contains all the source code. The required jar files are
activation.jar, axis.jar, commons-discovery.jar, commons-logging.jar, jaxrpc.jar,
log4j.jar, saaj.jar, soap.jar and wsdl4j.jar. I used Maven to build the war file and you can
find more info on Maven at maven site. You can find the actual version of the jar files
used in project.xml in my source distribution. You can build the war file by using your
favorite build procedure, but make sure that you include all the required jar files in the
final war distribution. Once you have the war file, you can just deploy on any web server.
I have used Tomcat as the web server. After you deploy the war file in Tomcat, you will
see an error in the AttachmentService.log file saying 'unable to find the config file'. Do
not worry about it, we are going to create server-config.wsdd by using the deploy.wsdd
file. Listing 8 shows the contents of deploy.wsdd file.
<deployment
xmlns="http://xml.apa
che.org/axis/wsdd/"
xmlns:java="http://xm
l.apache.org/axis/wsd
d/providers/java"
xmlns:ns1="Attachment
Service">
<service
name="AttachmentServi
ce"
provider="java:RPC">
<parameter
name="className"
value="webservices.at
tachments.AttachmentS
ervice"/>
<parameter
name="allowedMethods"
value="getDimeData,ge
tMimeData"/>
<operation
name="getDimeData"
returnQName="returnqn
ame"
returnType="ns1:DataH
andler">
<parameter
name="dh"
type="ns1:DataHandler
"/>
</operation>
<operation
name="getMimeData"
returnQName="returnqn
ame"
returnType="ns1:DataH
andler">
<parameter
name="dh"
type="ns1:DataHandler
"/>
</operation>
<typeMapping
deserializer="org.apa
che.axis.encoding.ser
.JAFDataHandlerDeseri
alizerFactory"
languageSpecificType=
"java:javax.activatio
n.DataHandler"
qname="ns1:DataHandle
r"
serializer="org.apach
e.axis.encoding.ser.J
AFDataHandlerSerializ
erFactory"
encodingStyle="http:/
/schemas.xmlsoap.org/
soap/encoding/"/>
</service>
</deployment>
On Windows
java -cp %AXISCLASSPATH%
org.apache.axis.client.AdminCl
ient
-lhttp://localhost:8080/axis/s
ervices/AdminService
deploy.wsdd
On UNIX
java -cp $AXISCLASSPATH
org.apache.axis.client.AdminCl
ient
-lhttp://localhost:8080/axis/s
ervices/AdminService
deploy.wsdd
Please follow the guidelines listed on the axis user guide at Installing new
WebServices.
Client implementation
Once the web service is ready we can write a client application for accessing this. There
are two approaches for building the client application. One is to create some wrapper
classes using some utility classes provided by axis and using these wrapper classes you
can create simple main method. Another approach is to write a client application on your
own. I used the latter approach because it will be more useful in understanding what
parameters were actually passed to the Call object before invoking the web service.
Practically, I found it to be more useful to know what is happening rather than using the
wrapper classes generated by some utility classes.
Service service =
new Service();
Call call = (Call)
service.createCall
();
After creating the call object, set various parameters that are needed
before accessing the service as shown in Listing 10 :
call.setTargetEndpoint
Address(new
URL(WEB_SERVICE_URL));
//This is the
target services method
to invoke.
call.setOperationName(
new
QName(WEB_SERVICE_NAME
, operation));
QName
qnameAttachment = new
QName(WEB_SERVICE_NAME
, "DataHandler");
DataHandler
dhSource = new
DataHandler(new
FileDataSource(INPUT_X
ML));
call.registerTypeMappi
ng(dhSource.getClass()
, //Add serializer for
attachment.
qnameAttachment,
JAFDataHandlerSerializ
erFactory.class,
JAFDataHandlerDeserial
izerFactory.class);
call.addParameter("sou
rce", qnameAttachment,
ParameterMode.IN);
//Add the file.
call.setReturnType(qna
meAttachment);
try {
Object
ret = call.invoke(new
Object[]
{dhSource}); //Add the
attachment.
log.info("ret : " +
ret);
if(ret ==
null) {
log.info("null
response received.");
} else
if(ret instanceof
String) {
String
errorMsg =
(String)ret;
log.info("errorMsg : "
+ errorMsg);
} else
if(ret instanceof
DataHandler) {
DataHandler dh
= (DataHandler)ret;
log.info("dh.getName()
: " + dh.getName());
byte[]
responseBytes =
Utils.getBytesFromData
Handler(dh);
log.info("responseByte
s length : " +
responseBytes.length);
String
responseStr = new
String(responseBytes,
"UTF-8");
log.info("responseStr
: " + responseStr);
}
}
catch(RemoteException
e) {
log.error("AttachmentS
erviceException :" ,
e);
}
}
As seen in the client code in the source distribution, the only difference
between sending a DIME attachment and a MIME attachment is setting
Call.ATTACHMENT_ENCAPSULATION_FORMAT property.
Conclusion
As I have shown in this article, writing a web service that can handle attachments and the
client to access the web service using Apache Axis implementation is not a very difficult
task, but there is not enough documentation at one place to accomplish this complete
task. Even though this article talks about deploying in Tomcat web server, it should work
on any J2EE web server. All you need to do is to deploy the war file on the server and
create server-config.wsdd.
Download
Resources
For more information on Apache Axis and installation, refer to Axis Installation.
For more information on processing attachments using JAX-RPC handlers, refer
to Process attachments using JAX-RPC handlers.
For creating web services with Apache Axis, refer to Creating Web services with
Apache Axis.
(Jeeva has over 7 years of experience in designing and developing enterprise class
web applications using JAVA and J2EE technologies.
He currently works for Itreya Technologies, Bangalore, leading a team of over 10
programmers and designers, developing a multi-user, distributed, web-based
workflow application)
Introduction
In this tutorial we will create a simple web service and a client web application using
eclipse IDE along with Lomboz plug in. We will also deploy and test the web service on
Tomcat 5.5.4 web application server. This application, while simple, provides a good
introduction to Web service development and some of the Web development tools
available.
Environment
J2SDK 1.4.2
http://java.sun.com/
Eclipse 3.1
http://www.eclipse.org/
Tomcat 5.5.4
http://tomcat.apache.org/
Lomboz 3.1RC2
http://lomboz.objectweb.org/
Installation
Setting up
1. Set up the installed JRE in eclipse (Windows -> Preferences -> Java -> Installed JREs)
2. Set up the installed runtime for server in eclipse (Windows -> Preferences -> Server ->
Installed Runtimes)
3. Set up the Server view in eclipse (Windows -> Show View -> Other)
4. Set up the Tomcat Server by right clicking and selecting New -> Server option from the
Server view in eclipse
1. Create a new Dynamic Web Project in eclipse (File -> New -> Other)
3. Now create a new Java class from the Project Explorer (Dynamic Web Projects -> Java
Source -> New -> Class)
4. Enter name as “Hello” and package as “com.tutorial”.
}
11. Select or enter the Bean name as “com.tutorial.Hello”. This is the java class that we just
now created.
15. Verify the Tomcat folder and ensure the newly created web applications –
WebServiceTutorial, WebServiceTutorialClient.
16. We can also run the following url from the browser to access/test the Web service.
http://localhost:8080/WebServiceTutorialClient/sampleHelloProxy/TestClient.jsp
18. The browser displays the methods available in the web service.
19. Click on the sayHello(..) method, enter your name (for e.g. “Jeeva”) in the inputs section
and click “Invoke”.
21. The WSDL for the Hello Web service can be found in E:\Test\WebServiceTutorial\
WebContent\wsdl\Hello.wsdl. On double-click, the WSDL opens in a graphical editor.
22. Right-click on the WSDL file and explore the options to test the web service / publish the
WSDL file / generate client / etc.
Conclusion
In this tutorial we learned how to create a simple web service and a client web application
using eclipse IDE along with Lomboz plug in. We also deployed and tested the web service
on Tomcat 5.5.4 web application server. This application, while simple, provides a good
introduction to Web service development and some of the Web development tools available.
Inter-operability is one of the two aims of Xml-webservice paradigm,while the other aim
is tackling the firewall problem. (Since ASP.net runs only in Win2000, switch over to
Win2000. before beginning this experiment).The emphasis is on the procedure, in
laboratory experiment fashion).
Kindly , ensure that correct versions of software , are used, as mentioned.It is presumed
that DotNet SDK has already been installed and tested,for running asp.net programs.
c:\tomcat41\bin>startup
{
{
}
}
11) We start the browser and type the URL as:
'http://localhost:8080/axis/greeter.jws'
and we get a link to the wsdl file for the above service. When we click this link,
we get a wsdl file .
13) Our aim is to create a C# file from this wsdl file.
( carefully note that the name has been appended with 'Service')
The next step is to compile this source file into a dll.
14)..wwwroot>csc /t:library
/r:System.dll,System.Web.Services.dll,System.Xml.dll
greeterService.cs
15) Now copy this dll file to d:\inetpub\wwwroot\bin folder.
<script runat=server>
Response.Write(s);
}
</script>
<html>
<body>
<form runat=server>
<asp:Textbox id=’text1’ runat=server />
</form>
</body>
</html>
'http://localhost/greeterService.aspx'
Remember that the tomcat server is running and supplying the 'greeter.jws'.
After some delay ( due to compiling time), we get a form.Type your name in the textbox
( say, ‘sam’ )& click the button to invoke the service. We get 'How are you?…..sam’
message from the java web service. We get correct result . We can also create a
standalone C# client by just appending a main() to the greeterService.cs and naming it as
‘greeterConsole.cs’.
Visit http://in.geocities.com/rsramsam
We saw some simple examples for XML-RPC & SOAP in the March,2004 issue.
However, the latest technology is Axis from Apache Software Foundation.
In that lesson, we had created a simple bean and exposed that as web service in Axis.
In this tutorial, we will create a Stateless Session Bean EJB using WebLogic-7 Enterprise
server, first. For a change, we will be using simple query as business logic rather than the
customary ‘greeter’ bean. This will also help those readers who missed the earlier
installments of the EJB tutorial.
After developing the EJBean and deploying it in WebLogic-7 server, we will test it with a
standalone console-mode client. This is the correct step-by-step procedure in developing
programs. If it works well, we will create a JSP to access the EJBean. In all our previous
lessons, we had been using servlet as client for the EJB. This is the first time that we are
using JSP for accessing the EJB.
Normally, it is not a good practice to simply transfer the servlet code to JSP as scriplet,
because, in that case the business logic will be exposed to the web server administrator.
If it is a servlet, the developer is deploying the class file only in the web server. So the
web server’s administrator cannot see the source code for the business logic. But, if it is
a JSP with plain scriplet, without using ‘JSPbean’, the server administrator can see the
source code. It is normally observed that except in the OSF/FSF circles, business logic is
not meant to be exposed to others. That is why it is the standard practice to use a
JSPbean and refer to it in the JSP file. It also helps in partial separation of code and
presentation. (Readers can refer to the first installment of J2EE tutorial on page 110 of
DeveloperIQ, October 2003 issue, for details on JSP, JSPbean etc,available in
j2ee1a.htm) .
But, in the present case, we need not follow that procedure and unnecessarily complicate
things because the actual business logic is in EJB and not in JSP. The JSP is simply the
code for invoking the EJB. This will considerably simplify things. We will deploy the
JSP and test the JSP in tomcat3.2 server.The big question now is “Why not deploy the
JSP in weblogic server itself?”
After all, any J2EE container will have provision for running Servlets & JSP, as also
EJB. So it is possible and sometimes recommended. But, it is not always essential and is
sometimes to be avoided for the following reasons:
1. It may not be desirable to get tied down to any one Enterprise server for all our
requirements. By keeping the servlet/JSP part in tomcat and using weblogic for EJB
only, we achieve some degree of independent operation. If we decide to use JBoss3.2 or
JBoss4, later, we can just change a few lines of code in the reference of our file. This
type of flexibility may be necessary in real life. Certainly, there may be some
degradation in speed but what we lose in speed, we gain in simplicity & freedom of
choice. This is an architectural decision and opinions may differ.
2. Moreover, Apache themselves are reported to be working on the creation of an EJB
server and it is certain that there will be greater synergy between tomcat and Apache EJB
server when it appears.
3. Besides all these reasons, we have a much more important reason for using tomcat as
the web-tier. We want to expose our EJBean as an XML-webservice, using Axis and it
works fine in tomcat as both are from Apache.
Some people prefer to use simple JavaBeans in place of EJB. But, it is not advisable…
Scalability, security, load balancing, transaction support etc. are of paramount importance
in enterprise and it will be most unreasonable to forego all these built-in advantages of
EJBean and opt for plain bean.
There was an interesting posting in the web by Joshua Davis on this topic as follows:
(quoted below).
Misconception (1)
‘Java Server Pages are useful for creating HTML user interfaces quickly, but that’s about
it. Projects that attempt to ‘simplify J2EE’ by using JSPs and Servlets without using
EJBs inevitably end up having transaction management problems.’
Misconception (2)
‘EJBs do not need to add significant complexity. Stateless session EJBs are not difficult
to write, and provide a simple way to expose transaction-managed functionality from an
EJB server. Home interface, remote interface, EJB implementation and deployment
descriptor are easily made as templates, & no complex ‘persistence’ is coed
A reference has been made by Manoj Kothale who has written about such templates,
which can be found in DeveloperIQ, October 2003 issue. It is advisable to avoid BMP
beans and even CMP is being replaced gradually by JDO (Java Data Objects). Castor is
one such technology, which was covered by Manoj Kothale in DeveloperIQ, March ’04
issue & there was an article on JDO by Sivakumar (DeveloperIQ, July 2003
issue).Readers may get more information about this latest and elegant technology from
the book “Java Data Objects” from OReilly press,by David Jordan & Craig Russell..
So, we now proceed to study, how we can ‘expose’ our EJBean as an XML-webservice,
using Axis.
There are two methods, by which a bean can be exposed as a webservice in Axis. The
first method is just to write the java source code and save it as a file with *.jws extension
in Axis folder of tomcat ( as was done in the earlier article; please review the earlier
lesson on this technique as given on page 62, DeveloperIQ, Jan-2004 issue). This is
known as ‘Drop-in Deployment’.axis1.htm
But, this assumes that the java source file is available with us and secondly we do not
mind that source code to be visible to the tomcat administrator. Normally, it may not be
desirable but in the present case, the actual business logic is in the EJBean and the source
code that is placed in Axis folder of tomcat is only the code for the bean that calls the
EJBean! So, there is no problem at all! And this is an ultra-simple method of exposing
our EJB service as an XML-webservice!
We will do that in first demo. Once we place this jws file in tomcat, we can easily get the
automatically generated wsdl file. This can then be used in ASP.NET or a java program.
Microsoft cannot be wished away! Any serious enterprise has to interact with Microsoft
platform. Secondly, a number of such webservices can interact with each other
programmatically.
This is why Sun’s J2EE1.4 has made XML-webservice the cornerstone of its
implementation!
The second method is more involved and orthodox. This method is necessary if we do
not want our source code to be visible to anyone.
In this case, we create the Axis-bean, compile it and copy the class file to
Axis/web-inf/classes folder of tomcat. Then, we proceed to create a wsdd file (web
service deployment descriptor). This is an XML file. In the next step, we deploy the
bean in tomcat. After this, we can easily get the wsdl file.
Here again, we can either create a javabean to access our EJB and create a wsdd for that
or we can skip creating such a javabean and create a wsdd directly for the EJB. We will
demonstrate both the methods, but it is said that at present, neither stateful beans nor
Entity beans can be used in Axis. That may be a fact but if we adopt our method as
outlined above, i.e. accessing the EBJ by an Axis bean, it may be possible! And we will
also demonstrate how the web service can be accessed by a servlet and also by a
WAP/J2ME client. The book “J2EE Blue Prints” from Sun Micro Systems (Pearson-
Education), discusses all these possibilities.To ensure that the wsdl file works fine, we
create a console mode program in java for accessing the web service and test it.
This introductory note on what is about to be done is necessary since there are so many
files here and we are likely to get confused.
It is assumed that we have already created a simple Access database named ‘telephone’
and a table1 with just two fields (name and number)(both are strings). We should also
remember to register it in ODBC. As we have to first create the EJB, for it to be
deployed, we now proceed to do it.
We are using WEBLOGIC-7. That is being taken up in the next part of this seven part
tutorial, which follows.
Continued in axis2b.htm
Visit http://in.geocities.com/rsramsam
Creating and testing an EJB in WebLogic Server.Let us begin by creating our working
folder as
c:\sam.
sqlremote.java
sqlhome.java)
sqlbean.java
// sqlremote.java
import javax.ejb.*;
import java.rmi.*;
//sqlhome.java
import javax.ejb.*;
import java.rmi.*;
// sqlejbbean.java
import java.sql.*;
import javax.ejb.*;
import java.rmi.*;
import javax.naming.*;
public sqlejbbean()
{}
{
try{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
while(rs.next())
{
r=r+rs.getString(1)+"\n"+rs.getString(2)+"\n"+"-------";
}
return r;
}
}
Please note that Weblogic7 will work only in Windows 2000. So, we are now working in
Windows 2000.
c:\sam>set JAVA_HOME=d:\jdk1.4.2
c:\sam>set WL_HOME=d:\bea\weblogic700
d:\bea\weblogic700\server\bin;
c:\sam>set classpath=c:\sam;
d:\bea\weblogic700\server\lib\weblogic.jar;
c:\sam>javac *.java
c:\sam>md META-INF
c:\sam>cd META-INF
c:\sam\META-INF>
In META-INF folder, create the following two Deployment-Descriptor files (XML
files). These files are MOST IMPORTANT. XML files are case-sensitive.
// ejb-jar.xml
<?xml version="1.0"?>
"http://java.sun.com/dtd/ejb-jar_1_1.dtd">
<ejb-jar>
<enterprise-beans>
<session>
<ejb-name>sqlejbbean</ejb-name>
<home>sqlhome</home>
<remote>sqlremote</remote>
<ejb-class>sqlejbbean</ejb-class>
<session-type>Stateless</session-type>
<transaction-type>Container</transaction-type>
</session>
</enterprise-beans>
</ejb-jar>
//weblogic-ejb-jar.xml
<?xml version="1.0"?>
<weblogic-ejb-jar>
<weblogic-enterprise-bean>
<ejb-name>sqlejbbean</ejb-name>
<jndi-name>sqlejbJndi</jndi-name>
</weblogic-enterprise-bean>
</weblogic-ejb-jar>
This will create sql1.jar. We may get some warning messages, which can be ignored.
Finally, we get the message ‘ejbc successful’.
Startmenu->programs->
password: administrator
Wait till you get the message: ‘started for Running mode’. Minimize this window. That
completes the job of deployment in ejb server. We should now create a console-mode
client for the ejbean
// sqlConsoleClient.java
import java.ejb.*;
import java.rmi.*;
import javax.rmi.*;
import javax.naming.*;
import java.io.*;
import java.util.*;
{
try
{
props.put
(Context.INITIAL_CONTEXT_FACTORY,
"weblogic.jndi.WLInitialContextFactory");
props.put(Context.PROVIDER_URL,url);
System.out.println("context ok..");
sqlhome home=(sqlhome)context.lookup("sqlejbJndi");
System.out.println("home ok..");
System.out.println("remote ok..");
a=remote.showdata(s);
System.out.println(a);
}
catch(Exception e1)
{System.out.println(“”+e1);}
}
}
C:\sam>javac sqlConsoleClient.java
We will get a few names and numbers.We now proceed to create the jsp file .
// sqljspclient.jsp
<html>
<body>
<%@ page import=”javax.ejb.*” %>
<%
Out.println(“please wait”);
props.put
(Context.INITIAL_CONTEXT_FACTORY,
"weblogic.jndi.WLInitialContextFactory");
props.put(Context.PROVIDER_URL,url);
System.out.println("context ok..");
System.out.println("home ok..");
System.out.println("remote ok..");
a=remote.showdata(s);
out.println(a);
%>
</body>
</html>
// sqljspclient.htm
<html>
<body>
<form method=post
sql
<input type=submit>
</form>
</body>
</html>
e:\tomcat\bin>set JAVA_HOME=D:\JDK1.4.2
>SET CLASSPATH=%CLASSPATH%;c:\sam;
d:\bea\weblogic700\server\lib\weblogic.jar
>startup
This will start the webserver. Start the browser and type the URL
as:‘http://localhost:8080/sqljspclient.htm’. We get a form. Type the sql and submit. We
get the correct result (tested and found ok). Thus, we have created a stateless session
EJB, tested it in console mode and also as a jsp deployed in tomcat3.2. We now proceed
to expose our ejb as an XML-WebService, using AXIS by two methods:
First and foremost, we need to install Axis1.1 for Windows, in our system. The January
2004 issue of DeveloperIQ dealt with Apache and the CD also carried a lot of Apache
software. But ‘Axis1.1 for windows’ was missing there. So, we have to download it
from the Apache website (http://xml.apache.org).It has been installed as c:\axis11. (The
unzipped folder is about 30MB.).
Secondly, we need tomcat4.1, for deploying axis. (It has been given in the March-2003
CD of DeveloperIQ.) It has been installed as d:\tomcat41.
d:\tomcat41\webapps\axis\web-inf\lib’
(tomcat4.1\common\lib)
// sqlaxisbean.java
import java.sql.*;
import java.util.*;
import javax.ejb.*;
import javax.naming.*;
import java.rmi.*;
{
String a;
public sqlaxisbean()
{
a="";
}
{
try
{
props.put
(Context.INITIAL_CONTEXT_FACTORY,
"weblogic.jndi.WLInitialContextFactory");
props.put(Context.PROVIDER_URL,url);
System.out.println("context ok..");
sqlhome home=(sqlhome)context.lookup("sqlejbJndi");
System.out.println("home ok..");
System.out.println("remote ok..");
a=remote.showdata(s);
System.out.println(a);
return a;
}
As we are now studying ‘Drop-in Deployment’, we just copy this source file’ into: ‘d:\
tomcat41\webapps\axis’ folder as ‘sqlaxisClient.jws’ Carefully note that we have
changed the file extension from *.java to *.jws.
d:\tomcat41\bin>set JAVA_HOME=D:\JDK141
d:\tomcat41\bin>
set path=c:\windows\command;d:\jdk141\bin;
d:\tomcat41\bin>startup
After the tomcat server is fully started (you get the messages as ‘jk running’) we can test
out Axis installation over tomcat as follows: Start the browser and type the URL
as:‘http://localhost:8080/axis/index.html’.We get the Axis welcome page:
// sqlaxisbeanClient.java
import java.net.*;
import javax.xml.rpc.ParameterMode;
import org.apache.axis.client.Service;
import org.apache.axis.client.Call;
import org.apache.axis.encoding.XMLType;
import javax.xml.namespace.QName;
{
{
try
{
System.out.println("Start");
call.setTargetEndpointAddress(url);
call.setOperationName("callejb");
call.setReturnType(XMLType.XSD_STRING);
System.out.println(r);
}
}
}
We have to set correct classpath for the window to include a number of files required for
Axis.As it will be tedious to type it every time, we have created a batch file named
‘setcpath.bat’. Please note that it should be typed in a single line continuously as
given.
// setcpath.bat
set classpath=c:\sam; d:\bea\weblogic700\lib\weblogic.jar;
c:\axis11\lib\axis.jar;
c:\axis11\lib\jaxrpc.jar;
c:\axis11\lib\saaj.jar;
c:\axis11\lib\commons-logging.jar;
c:\axis11\lib\commons-discovery.jar;
c:\axis11\lib\wsdl4j.jar;
c:\tomcat4.1\common\lib\activation.jar;
c:\tomcat4.1\common\lib\xerces.jar
After creating this file, we can simply type at the prompt,sam> setcpath. This will
create the correct classpath for the working window. We will now be able to compile
jwsclient.java. After compiling, we can execute the program:>java jwsclient “select *
from table1”. We will get names and numbers. This was tested and found to be ok.Thus,
we have developed and ejb, and accessed it as an xml webservice!
In the next article of this seven-part tutorial, we will take up the wsdd method.
Continued in axis2d.htm
visit http://in.geocities.com/rsramsam
In this part, we will follow the WSDD method. We have already created
sqlaxisbean.java as explained in the last article. We used it as sqlaxisbean.jws (drop-in
method). There was no necessity to compile this file.But in WSDD method (web-service
deployment descriptor), we should compile this file.Next, we create the WSDD file.
Then, we deploy this bean to tomcat. We may have to restart the tomcat4.1 webserver.
We can then create a java-console client and test the webservice. So, this is the step-by-
step procedure. We will now go into the details involved here.We are now in c:\sam.
c:\axis11\lib\axis.jar;
c:\axis11\lib\jaxrpc.jar;
c:\axis11\lib\saaj.jar;
c:\axis11\lib\commons-
logging.jar;
c:\axis11\lib\commons-
discovery.jar;
c:\axis11\lib\wsdl4j.jar;
c:\tomcat4.1\common\lib\
activation.jar;
c:\tomcat4.1\common\lib\xerces.jar
// sqlaxisbean.java
import java.sql.*;
import java.util.*;
import javax.ejb.*;
import javax.naming.*;
import java.rmi.*;
String a;
public sqlaxisbean()
{
a="";
}
{
try
{
props.put
(Context.INITIAL_CONTEXT_FACTORY,
"weblogic.jndi.WLInitialContextFactory");
props.put(Context.PROVIDER_URL,url);
System.out.println("context ok..");
System.out.println("home ok..");
System.out.println("remote ok..");
a=remote.showdata(s);
System.out.println(a);
return a;
}
c:\sam>javac sqlaxisbean.java
so we get sqlaxisbean.class.
b. provider “java:RPC”
//c:\sam\sqlaxis.WSDD
<deployment
xmlns=”http://xml.apache.org/axis/WSDD/”
xmlns:java=”xml.apache.org/axis/WSDD/providers/java” >
<service name=”ejbsqlaxis”
</service>
<deployment>
In Axis, a provider (also known as a pivot handler) is used for invoking the webservice
class.
In the present demo, we are using RPC based provider.The next step is to deploy the bean
in tomcat server. Please refer to page 38 of Axis by Romin Irani & Geelani Basha.
WROX Press for further details.
c:\sam>java
org.apache.axis.client.AdminClientsqlaxis.WSDD
lhttp://localhost:8080/axis/services/AdminService
(Remember that tomcat should be running. If tomcat server is not running, this command
won’t work.)Wait till the message ‘Done Processing’ is displayed. It is essential to verify
whether the bean has really been deployed correctly by the following command:
–lhttp://localhost:8080/axis/services/AdminService
We will get the WSDD files of all the beans deployed. (If there are too many items, we
can send the result to log.txt by the command :> (as before)> log.txt .We can then see
log.txt and locate the ejbsqlaxis service, its classname and method name.Actually, our
job is over. We can, now checkup, whether the bean is available as a webservice typing
the URL in browser as: ‘http://localhost:8080/axis/services/Ejbsqlaxis?wsdl’
(ejbsqlaxis is the name given by us as the name of service in the WSDD file.) We will
get the wsdl file (an xml file).Search for the occurrence of the port-type name as
‘sqlaxisbean’ and operation name as ‘callejb’.If these are found, it means that everything
is fine.
Now we want to check up whether we can really use this service. For this, we create the
following java console-mode program .
style='background:maroon;border-collapse:collapse;border:none;mso-border-alt: solid
windowtext .5pt;mso-yfti-tbllook:480;mso-padding-alt:0in 5.4pt 0in 5.4pt; mso-border-
insideh:.5pt solid windowtext;mso-border-insidev:.5pt solid windowtext'>
// sqlaxisconsoleclient.java
import java.net.*;
import javax.xml.rpc.
ParameterMode;
import org.apache.axis.client.
Service;
import org.apache.axis.
client.Call;
import org.apache.axis.
encoding.XMLType;
import javax.xml.
namespace.QName;
public class
sqlaxisconsoleClient
public static
try
{
System.out.println
("Start");
System.out.println
("Service ready");
System.out.println
("call ready");
8080/axis
/services/ejbsqlaxis");
call.setTargetEndpointAddress(url);
call.setOperationName("callejb”);
call.addParameter
("something", XMLType.XSD_STRING,
ParameterMode.IN);
call.setReturnType
(XMLType.XSD_STRING);
String r=
(String)call.invoke(new Object[]
{args[0]});
System.out.println(r);
}
If you carefully compare this file with the earlier jwsclient.java, you will find that except
for the URL of the end-point, everything else is the same.We now compile this file.
c:\sam>javac sqlaxisconsoleclient.java
We get the correct result. Now just a little explanation for the code!
1. We begin by defining the endpoint URL, which specifies the actual location of
WEBSERVICE.
2. We specify the method name, then we create an instance of service and create CALL
object for a service. We set URL and method name for this CALL object.
That completes the fourth part of this tutorial. In the next month’s issue, we will directly
use the EJB class files in WSDD file and invoke the EJB as webservice without using
sqlaxisbean.
Continued in axis3.htm
Visit http://in.geocities.com/rsramsam
part-1 : Overview
a) java:RPC
In part-4, we created a javabean to accessthe EJB in weblogic enterprise server and usedit
in the wsdd file.This approach is preferable because, the best method is to use a stateless-
session bean to access other beans in the ejb-server.This is known as 'Facade pattern'.
"It is entirely possible to package your business logic into Java Beans and not worryabout
the EJB API.However,as your business logic becomes more complex ,requiring the
coupling of the logic with enterprise functionality like transactions,resource management
etc, the benefits of the EJB architecture rapidly become apparent.The EJB container can
provide all these system-level services(lifecycle management,connection
pooling,transations,etc)leaving the developer to concentrate on developing thebusiness
logic". Secondly, "Utilizing existing applications is the key inan enterprise scenario. It is
important thatexisting business functionality in EJB components within the J2EE
Application can be invoked in a seamless fashion."
This argument against using EJB, surfaces again and again from different quarters often.
For instance, Perl programmers who want to use XML-Webservice also argue that
simple functions will do. Hence, it is worthwhile
Business folks,on the other hand,tend to ask questions like,"How do I ensure that the
person using the service is really who they say they are?" or "How can we tie together
multiple web services into a workflow?" or "How can I ensure the realiability of web
service transactions?" Their questions typically address business concerns.
These tow perspectives go hand-in-hand with one another. Every business issue will
have a software-based solution. But the two perspectives are also at odds with each
other:the business processes demand completeness, trust, security, and reliability, which
may be in incompatible with the programmers goals of simplicity, performance, and
robustness.
The outcome is that tools for implementing webservices will do so from one of thesse
two angles,but rarely will they do so from both.For example ,SOAP::Lite,the perl based
SOAP implementation written by the coauthor of this book,Pavel kulchenko,is essentially
written for programmers.It provides a very simple set of tools for invoking Perl modules
using SOAP,XML-RPC,jabber,or any number of other protocols.
The important thing to keep in mind is that both tools implement many of the same set of
technologies(SOAP,WSDL,UDDI, and others,many of which we discuss later on),and so
they are capable of interoperating with each other.The differences are in the way they
interface with applications.This gives programmers a choice of how their web services is
implemented,without restricting the users of that service."
Reverting back to our main theme now, some developers prefer to use the Enterprise-
bean itself directly in the wsdd file as is about to be shown below.
(or)
First, we will demonstrate the java:RPC pivot-handler method . After that, we will create
another wsdd to use java:EJB pivot handler and test it .
in Weblogic7.
sqlRemote,sqlHome,sqlBean
path=c:\windows\command;
d:\jdk141\bin;
d:\bea\weblogic700\server\bin;
classpath=c:\sam;
d:\bea\weblogic700\server\
lib\weblogic.jar;
c:\axis11\lib\axis.jar;
c:\axis11\lib\jaxrpc.jar;
c:\axis11\lib\saaj.jar;
c:\axis11\lib\commons-logging.jar;
c:\axis11\lib\commons-discovery.jar;
c:\axis11\lib\wsdl4j.jar;
d:\tomcat 4.1\common\lib\activation.jar;
d:\tomcat 4.1\common\lib\xerces.jar;
<deployment
xmlns="http://xml.apache.org/axis/wsdd/"
xmlns:java="http://xml.apache.org/
<service name="sqlservice"
provider="java:RPC" >
<parameter name="beanJndiName"
<parameter name="homeInterfaceName"
<parameter name="remoteInterfaceName"
<parameter name="className"
<parameter name="allowedMethods"
value="*" />
</service>
</deployment>
The next step is to deploy the service in Axis.Remember, that Tomcat4.1 and
Weblogic7 , have already been started.
( as given in part-2).Secondly , preliminary steps for using Axis also have been already
performed.(please refer to opening remarks in part-3 of this tutorial in March-2004 issue).
( this should be typed in a continuous line). (note: if tomcat server is not running, this
command won't work)
<Done Processing>
We can also test the deployment by using the browser and typing the URL as:
http://localhost:8080/axis/services/sqlservice?wsdl
We will get a wsdl file. Now we've exposed our ejb as webservice.
b) servlet client.
// ejbaxisconsoleclient.java
import java.net.URL;
import org.apache.axis.client.Service;
import org.apache.axis.client.Call;
import org.apache.axis.encoding.XMLType;
import javax.xml.rpc.ParameterMode;
import javax.xml.namespace.QName;
{
try
{
call.setOperationName
call.addParameter("sql",XMLType.XSD_STRING,ParameterMode.IN);
call.setReturnType(XMLType.XSD_STRING);
System.out.println(s);
}
catch(Exception e1)
}
}
After it is complied successfully, run the program and pass the query as commandline
argument.
// ejbaxisservletclient.java
import java.net.URL;
import org.apache.axis.client.Service;
import org.apache.axis.client.Call;
import org.apache.axis.encoding.XMLType;
import javax.xml.rpc.ParameterMode;
import javax.xml.namespace.QName;
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
{
response.setContentType("text/html");
String sql =
request.getParameter("text1");
try{
call.setOperationName
call.addParameter
("sql",XMLType.XSD_STRING,ParameterMode.IN);
call.setReturnType(XMLType.XSD_STRING);
out.println(s);
}
catch(Exception e) { System.out.println(""+e); }
}
( we will be able to compile because classes required for compiling the servlet are
available in weblogic.jar , to which
copy c:\sam\ejbaxisservletclient.class to
Do not forget to edit web.xml in d:\tomcat 4.1\webapps\axis\web-inf folder( this is
very important in tomcat4.1).
<servlet>
<servlet-name>
ejbaxisservletclient
</servlet-name>
<servlet-class>
ejbaxisservletclient
</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>
ejbaxisservletclient
</servlet-name>
<url-pattern>
\servlet\ejbaxisservletclient
</url-pattern>
</servlet-mapping>
ejbaxisservletclient.htm
<html>
<body>
<input type=submit>
</form>
</body>
</html>
Make sure that tomcat server is running.Open IE and type url as 'http://localhost:8080/
axis/ejbaxisservletclient.htm' Enter sql query in the text box and submit it. we'll get the
resultset as per the query.
// directejbdeploy.wsdd
<deployment
xmlns="http://xml.apache.org/axis/wsdd/"
xmlns:java="http://xml.apache.org/axis/wsdd/providers/java"
xmlns:xsi="http://www.w3.org/2000/10/XMLSchema-instance">
<service name="dataejbservice"
provider="java:EJB">
<parameter name="beanJndiName"
<parameter name="homeInterfaceName"
<parameter name="jndiContextClass"
value="weblogic.jndi.WLInitialContextFactory" />
<parameter name="jndiURL"
value="t3://127.0.0.1:7001" />
</service>
</deployment>
If we carefully study the above file, we will note that the value for jndiContextClass and
jndiURL are just what we usually specify in the client file for ejb program!So, nothing
very special there!
All the classes referred to , are already available and after deploying this wsdd as usual ,
we are ready to use the service!--
( this should be typed in a continuous line). (note that it is exactly like what we did
previously, except that the name of wsdd file is different).
'http://localhost:8080/axis/services/dataejbservice?wsdl'
Please note that 'dataejbservice' is the name of service that we have given in the wsdd
file.As we have ensured that both tomcat4.1 &weblogic7 are running , without anything
being changed, we will get the corresponding wsdl. This shows that our webservice is
running correctly.
c:\sam , as usual.
// c:\sam\ directejbconsoleclient.java
//===============================
import java.net.URL;
import org.apache.axis.client.Service;
import org.apache.axis.client.Call;
import org.apache.axis.encoding.XMLType;
import javax.xml.rpc.ParameterMode;
import javax.xml.namespace.QName;
{
try
{
call.setOperationName
call.addParameter("sql",XMLType.XSD_STRING,ParameterMode.IN);
call.setReturnType(XMLType.XSD_STRING);
System.out.println(s);
}
}
So far we've accessed our ejb through console mode and servlet.Now Its time to write the
client program for wireless browsers.
Visit http://in.geocities.com/rsramsam
******************************************
//ejbaxiswapservlet.java
----------------------
import java.net.URL;
import org.apache.axis.client.Service;
import org.apache.axis.client.Call;
import org.apache.axis.encoding.XMLType;
import javax.xml.rpc.ParameterMode;
import javax.xml.namespace.QName;
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
{
response.setContentType("text/vnd.wap.wml");
try{
call.setOperationName
call.addParameter("sql",XMLType.XSD_STRING,ParameterMode.IN);
call.setReturnType(XMLType.XSD_STRING);
System.out.println(s);
out.println("<p>");
out.println(s);
out.println("</p>");
out.println("</card>");
out.println("</wml>");
}catch(Exception e)
{ System.out.println(""+e); }
}
********************************************
copy c:\sam\ejbaxiswapservlet.class to
<servlet>
<servlet-name>
ejbaxiswapservlet
</servlet-name>
<servlet-class>
ejbaxiswapservlet
</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>
ejbaxiswapservlet
</servlet-name>
<url-pattern>
\servlet\ejbaxiswapservlet
</url-pattern>
</servlet-mapping>
d:\tomcat 4.1\webapps\axis
***************************************************
ejbaxiswapservlet.wml
---------------------
<?xml version="1.0"?>
<wml>
<card id="card1">
<p>
<do type="accept">
</go>
</do>
</p>
</card>
</wml>
*************************************************
Make sure that tomcat is running. Enter sql query in the text box and submit it. we'll get
the resultset as per the query. But, WAP is no-longer, the favoured wireless client
because of limited functionality. Color graphics, games and animations are expected
today.
J2ME is the best solution for such apps, because,it is platform independent.
We now demonstrate how we can access an ejb-webservice from a j2me wireless client.
( continued in axis3-3.htm
In the previous section,we've dealt with how to write WAP client for accessing ejb. In
the same way, we are going to see how to write J2ME client for ejb.We divide this part
into two. They are
j2meServlet.java
import java.io.*;
import javax.ejb.*;
import java.rmi.*;
import javax.rmi.*;
import javax.naming.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
(HttpServletRequest request,
HttpServletResponse response)
{
response.setContentType("text/html");
try
{
props.put
(Context.INITIAL_CONTEXT_FACTORY,
"weblogic.jndi.WLInitialContextFactory");
props.put(Context.PROVIDER_URL,
"t3://localhost:7001");
System.out.println("Remote ok");
String s = request.getParameter("text1");
System.out.println(s);
String s1=s+"%";
String sql=
System.out.println(sql);
DataOutputStream out =
new DataOutputStream(response.getOutputStream());
out.writeUTF(msg);
System.out.println(msg);
}
catch(Exception e1)
}
}
Next step is to create a midlet for J2ME.Create ejbmidlet.java in our current working
folder.
//ejbmidlet.java
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
import javax.microedition.io.*;
import java.io.*;
public ejbmidlet()
{
form1.append(text1);
form1.setCommandListener(this);
}
{
display1.setCurrent(form1);
}
{
if(cmd==button1)
{
try
{
System.out.println(url);
HttpConnection hc =
(HttpConnection)Connector.open(url);
hc.setRequestMethod(HttpConnection.POST);
DataOutputStream dos =
dos.writeUTF(s);
dos.flush();
DataInputStream dis =
String msg=dis.readUTF();
System.out.println(msg);
System.out.println(s1);
form2.append(s1);
form2.addCommand(button2);
form2.setCommandListener(this);
display1.setCurrent(form2);
System.out.println("displayed");
}
{
}
}
It is taken care of by J2ME Wireless Toolkit. For running the toolkit from our working
folder set the path as below
c:\sam> ktoolbar
This will open the Toolkit window.Create a new Project by clicking the button 'New
project'.and give the project name as 'ejbdemo1' as project name.Just minimize the
window.
Now copy ejbmidlet.java from our working folder to 'src' folderof 'ejbdemo1'.
Click 'Build' for compilation. After source file is compiled successfuly, Click 'Run' button
and execute our midlet. (tomcat41 is running).
Type a letter 'a' in the textbox and click 'send'. Midlet program sends the letter to the
servlet which'll form sqlquery and contact ejb for fetching the result. Recordset for the
name starting with letter 'a' will be displayed in the wireless browser.Let us now create a
J2ME client accessing ejb webservice.create and complie j2meaxisservlet.java
j2meaxisservlet.java
import java.net.URL;
import org.apache.axis.client.Service;
import org.apache.axis.client.Call;
import org.apache.axis.encoding.XMLType;
import javax.xml.rpc.ParameterMode;
import javax.xml.namespace.QName;
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
{
response.setContentType("text/html");
try{
String sql="select * from table1 where name like '"+s1+"' ";
System.out.println("point1....call");
call.addParameter("sql",XMLType.XSD_STRING,ParameterMode.IN);
call.setReturnType(XMLType.XSD_STRING);
out1.writeUTF(s2);
System.out.println(s2);
}
copy j2meaxisservlet.class to
d:\tomcat 4.1\webapps\axis\web-inf\classes
Start tomcat4.1 server and do the procedure mentioned in the first part for deploying
midlet.
javaismidlet.java
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
import javax.microedition.io.*;
import java.io.*;
{
form1.append(text1);
form1.addCommand(button1);
form1.setCommandListener(this);
}
{
display1.setCurrent(form1);
}
{
if(cmd==button1)
{
try
{
System.out.println(url);
HttpConnection hc =
(HttpConnection)Connector.open(url);
hc.setRequestMethod(HttpConnection.POST);
DataOutputStream dos =
dos.writeUTF(s);
dos.flush();
DataInputStream dis =
String msg=dis.readUTF();
System.out.println(msg);
form2 = new Form("Get Result");
System.out.println(s1);
form2.append(s1);
form2.addCommand(button2);
form2.setCommandListener(this);
display1.setCurrent(form2);
System.out.println("displayed");
}
{
display1.setCurrent(form1);
}
}
That completes our rather long tutorial! Student-readers are requested to actually try all
the above lessons in this carefully crafted tutorial..
visit http://in.geocities.com/rsramsam
7. Web services-Axis:
Apache Axis is an implementation of the SOAP ("Simple Object Access
Protocol") submission to W3C.
From the draft W3C specification:
SOAP is a lightweight protocol for exchanging structured information in a
decentralized, distributed environment. It is an XML based protocol that consists
of three parts: an envelope that defines a framework for describing what is in a
message and how to process it, a set of encoding rules for expressing instances of
application-defined data types, and a convention for representing remote
procedure calls and responses.
This project is a follow-on to the Apache SOAP project.
Please see the Reference Library for a list of technical resources that should prove
useful.
8. Getting a Java Web service to work:
We're deploying an existing Web service application to a new JBoss server by
following the "Getting Started with JBoss" manual from www.jboss.org, but the
j2eetutorial examples file doesn't seem to match the documentation. The
application is ready for deployment, but we can't seem to get the right files in the
right places to make things work. Where can we find a JBoss example that works,
or some tools to automate the deployment?
The manual is written for JBoss Version 3.2.3 and Version 1.3.X of the Java
Software Development Kit (JSDK). The current production JBoss release is 3.2.4,
and using Version 1.4X of the JSDK is recommended.
9. Web Services ToolKit:
A software development environment for designing, developing, and executing
Web service technologies.WSTK has evolved into the ETTK for Web Services
and Autonomic Computing (ETTK-WS).
The Emerging technologies team is expanding the scope of the toolkit to include
autonomic and grid-related technologies and has therefore rebranded this
technology to "ETTK for Web Services and Autonomic Computing" (ETTK-WS)
in order to more accurately reflect its role in the new ETTK collection of
technologies and prototypes. The ETTK-WS will continue to offer leading-edge
prototyping of emerging Web services technologies for recently released
specifications. The ETTK-WS can be downloaded here at alphaWorks. The
ETTK-WS integrates emerging technologies from IBM Research Labs and IBM
Software Groups into a consolidated package to showcase leading-edge
technologies that may or may not make it into IBM products.
10. Internet Web Services:
Web services are the basis of distributed computing across the Internet. A Web
service consumer locates a Web service and invokes the operations it provides.
The Web service provider (the application implementing the Web service) can be
on the same Java virtual machine as the one using it, or it can be thousands of
miles away. Web services use standard Web protocols such as XML, SOAP, and
HTTP.
11. What is Web Services resource:
Many technologies must represent state in a standard fashion in a Web services
architecture, such as grid computing and distributed systems management. WSRF
is the emerging OASIS Web services standard for modeling and accessing stateful
resources using Web services.
WSRF for WAS was developed by the WebSphere Application Server (WAS)
development team. This technology extends the WAS Web Services run-time
environment to support the patterns defined by WSRF, and it enables a Web
service to have an association with instances of stateful resources, the composite
of which is a stateful "WS-Resource." A WS-Resource has an associated XML
document, called a resource properties document, that describes the state of the
resource. The resource properties document and the resource it describes may be
queried and updated through Web service message exchanges defined in the
WSRF specifications.
This technology includes a comprehensive sample application illustrating the
following:
the use of a stateful WS-Resource
the means through which its state is queried and updated
the well-defined life cycle of the state.
12. Web Services Language:
As expressed in the Statement of Mission and Objectives, the SWSI Language
Committee aims to develop computer language technology that will provide a
firm, long-term foundation for the future of Web services on the Internet. It is
desired that this foundation will support the most general approaches to service
deployment and use that are currently technically feasible.
The Committee seeks to develop a formal language that allows for rich
declarative specification of a wide variety of information about Web services,
which will support automation of a broad spectrum of activities related to Web
services, such as discovery, selection, composition, negotiation and contracting,
invocation, monitoring of progress, and recovery from failure.
The committee aims to build on the success of OWL-S, taking the existing
language as a starting point, while allowing scope for the revisions and additions
necessary to address these new requirements.
13. WSDL Editor:
The XMLSpy WSDL editor allows you to create, edit, visualize, and validate any
WSDL file. WSDL is a language for describing Web services and is ideally suited
as an interface definition language (IDL) for architecting Web services
applications. By first building an interface, client and server programmers can
implement their respective programming contract using any language or operating
system, avoiding interoperability problems. XMLSpy helps you write and validate
WSDL documents quickly and easily. The graphical WSDL editor displays the
WSDL file structure as well as the WSDL elements grouped by operations,
portTypes, bindings, and services. You can manipulate the file by dragging and
dropping elements, and context-sensitive windows and entry helpers provide
intelligent editing options.
14. Feature of WSDL Editor:
The WSDL Editor offers a rich set of features for programmers looking to create
and edit Web Services:
Intuitive graphical environment for viewing and editing WSDL files
Web Services creation wizard that automates the creation of service definitions,
port types, binding, template operations, and messages
Fully automated wizards for creating and editing XML schema, schema array,
complex types, simple types, and enumerations
Support for WSDL validation, where WSDL is tested against WSDL Schema
Support for WSDL profiling, so WSDL can be validated against customized
profiles for specific requirements such as standards compatibility (for example,
WS-I)
Support for advanced WSDL capabilities such as imports, faults, SOAP headers,
multiple bindings, and parameter ordering
WSDL 1.1 specification support
Retrieval of WSDL from across networks, UDDI repositories, or Internet
locations
Full support for WSDL documentation
15. Web Services Editor:
Cape Clear Software has debuted a free service-oriented architecture (SOA)
editor. It “provides programmers with a graphical environment that simplifies the
creation of standards-based Web Services, which can be deployed into an SOA-
based architecture,” Cape Clear says. The SOA Editor offers easy-to-use tools for
building services, including automated wizards for common development tasks,
support for Web Services standards, tools for testing code, support for XML
Schema, and detailed documentation to help programmers get up and running
quickly,” the vendor notes. “The SOA Editor is available for download
immediately.
16. X standard version:
XStandard is the leading standards-compliant plug-in WYSIWYG editor for
Windows desktop applications and browser-based content management systems
(IE/Mozilla/Firefox/Netscape). The editor generates clean XHTML Strict or 1.1,
uses CSS for formatting, and ensures the clean separation of content from
presentation. Markup generated by XStandard meets the most demanding
accessibility requirements. The editor's cool features include drag & drop file
upload, spell checking and an image library that integrates tightly with your CMS.
17. XML-Editor:
XML editor is a Java-based XML editor with support for XML, XSL, TXT, XSD
and DTD documents. Oxygen shows that Java should be the base of an XML
editor; this can be proved by the development dynamics of Oxygen and by the
availability on many platforms. It has Unicode support and the interface messages
are translated in English, French, German, Italian and Romanian. The main goal
of Oxygen is to be a tool easy to use and to make tasks shorter, thus it offers end
tag auto-completion and a powerful code insight that guide the user to write valid
XML content. The code insight can follow a DTD structure, an XML schema
structure or even can detect the structure of a partial edited document allowing the
rest of the document to be created about 5 times faster than before. A very
important thing is manipulating XML content and XSLT is the normal way to
this, thus XML and XSL documents can be easily associated one with the other
and the transformation results can be viewed through different views like text,
XML, HTML. An XPath console is present to assist the user in testing the results
of XPath expressions.
18. Web services with Axis2:
In simple terms, Axis2 is not just the next version of the Axis 1.x family; rather, it
is a revolutionary version of Axis 1.x. Axis2 is no longer bound to request-
response Web service invocation. As in the Axis 1.x family, there is no turning
point like the "pivot point" in Axis2, and Axis2 is built totally on keeping
asynchronous Web service invocation in mind. Axis2 acts as a pipe that carries
the SOAP message from one end to other. The entry point to the pipe is a
transport receiver, and the end point is a message receiver. After handing over the
message to the message receiver, Axis2 does not care about the message.
Therefore, it's up to the message receiver to invoke the service and send the
response, if any, so service implementation classes) need not always be a Java
class; it can be something else as well.
19. Secure Web Services via Oriented:
This article describes the exploitation of the pluggable transport infrastructure
provided as part of ASP.NET Web Services, which allows developers to deliver
Soap messages built in the document/literal format to be delivered to an end point
via mechanisms other than default HTTP transport. In this article, a framework
that supports the addition of alternative physical delivery mechanisms is
presented, and two such implementations are included – MSMQ and Websphere
MQ are chosen to illustrate a store-forward capability for a more 'guaranteed'
Web Services request delivery. The framework that will be developed integrates
the Web Services Enhancements (WSE) 1.0 for secure 2-way transport of
messages over non-HTTP mechanisms, thereby giving the developer a choice of
'trusted' (clear message) or 'untrusted' (secure message) delivery to the chosen
endpoint.
20. Microsoft Web Services:
The Microsoft.com Web service is an XML Web service that will enable you to
integrate information and services from MSDN, Technet, other Microsoft.com
sites, and Microsoft Support. In order to serve as a test for our new architecture,
Version 1.0 of the Microsoft.com Web service is limited to providing information
about top downloads from Microsoft.com. Future releases will build on this
architecture to provide access to a broader variety of Microsoft content and
services.
21. Web Services to J2EE :
The Java XML Pack is the first certified release of Web services tools for J2EE
(Java 2, Enterprise Edition), the server software platform that is based on the Java
programming language. Java developers already have some tools provided by the
open-source community that allow them to build XML-based Web services for
J2EE, said Karen Shipe, a product manager with Sun's Java XML group. But
Sun's release Monday is the first such technology that has gone through the Java
certification process.
22. Open SAML Web Services:
OpenSAML is a set of open-source libraries in Java and C++ which can be used
to build, transport, and parse SAML messages. OpenSAML is able to store the
individual information fields that make up a SAML message, build the correct
XML representation, and parse XML back into the individual fields before
handing it off to a recipient. OpenSAML supports the SOAP binding for the
exchange of SAML request and response objects (C++ supports requesting only).
It provides additional help in supporting the SAML browser/POST profile for
web single sign-on. It does not currently provide any additional support for the
artifact profile, but provides the machinery needed to implement it in other
software. All core SAML constructs are now supported to some
degree.OpenSAML has been produced by Internet2 members as part of their work
on the Shibboleth project ( http://shibboleth.internet2.edu/ )