Webservices

  • June 2020
  • PDF

This document was uploaded by user and they confirmed that they have the permission to share it. If you are author or own the copyright of this book, please report to us by using this DMCA report form. Report DMCA


Overview

Download & View Webservices as PDF for free.

More details

  • Words: 8,402
  • Pages: 45
ervice Oriented Architecture or SOA for short is a new architecture for the development of loosely coupled distributed applications. In fact service-oriented architecture is collection of many services in the network. These services communicate with each other and the communications involves data exchange & even service coordination. Earlier SOA was based on the DCOM or Object Request Brokers (ORBs). Nowadays SOA is based on the Web Services. Broadly SOA can be classified into two terms: Services and Connections.

Services: A service is a function or some processing logic or business processing that is well-defined, selfcontained, and does not depend on the context or state of other services. Example of Services are Loan Processing Services, which can be self-contained unit for process the Loan Applications. Other example may be Weather Services, which can be used to get the weather information. Any application on the network can use the service of the Weather Service to get the weather information.

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. The following figure is a typical example of the service-oriented architecture. It shows how a service consumer sends a service request to a service provider. After accepting the request, service provider send a message to the service consumer. In this case a service provider can also be a service consumer.

Different Technologies Used: 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 )

Term service

Definition / Comment (Ideally) a self-contained, stateless business function which accepts one or more requests and returns one or more responses through a well-defined, standard interface. Services can also perform discrete units of work such as editing and

processing a transaction. Services should not depend on the state of other functions or processes. The technology used to provide the service, such as a programming language, does not form part of this definition. orchestration Sequencing services and providing additional logic to process data. Does not include data presentation. stateless Not depending on any pre-existing condition. In a SOA, services should not depend on the condition of any other service. They receive all information needed to provide a response from the request. Given the statelessness of services, service consumers can sequence (orchestrate) them into numerous flows (sometimes referred to as pipelines) to perform application logic. provider The function which performs a service in response to a request from a consumer. consumer The function which consumes the result of a service supplied by a provider. discovery Service oriented architecture relies on the ability to identify services and their capabilities. Therefore, a SOA depends on a directory which describes the services available in its domain. binding The relationship between a service provider and consumer is dynamic; it is established at runtime by a binding mechanism.

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. Historically speaking, remote access to binary units required platform-specific and sometimes language-specific protocols. For example, DCOM clients access remote COM types using tightly coupled RPC calls. CORBA requires the use of tightly coupled protocol referred to as Internet Inter-ORB Protocol (IIOP), to activate remote types. Enterprise JavaBeans (EJBs) requires a Remote Method Invocation (RMI) Protocol and by and large a specific language (Java). Thus each of these remote invocation architectures needs proprietary protocols, which typically require a tight connection to the remote source. 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. What is a Web Service Web services constitute a distributed computer architecture made up of many different computers trying to communicate over the network to form one system. They consist of a set of standards that allow developers to implement distributed applications - using radically different tools provided by many different vendors - to create applications that use a combination of software modules called from systems in disparate departments or from other companies. A Web service contains some number of classes, interfaces, enumerations and structures that provide black box functionality to remote clients. Web services typically define business objects that execute a unit of work (e.g., perform a calculation, read a data source, etc.) for the consumer and wait for the next request. Web service consumer does not necessarily need to be a browserbased client. Console-baed and Windows Forms-based clients can consume a Web service. In each case, the client indirectly interacts with the Web service through an intervening proxy. The proxy looks and feels like the real remote type and exposes the same set of methods. Under the hood, the proxy code really forwards the request to the Web service using standard HTTP or optionally SOAP messages. Web Service Standards 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. Universal Description, Discovery, and Integration (UDDI) is a protocol for describing available Web services components. This standard allows businesses to register with an Internet directory that will help them advertise their services, so companies can find one another and conduct transactions over the Web. This registration and lookup task is done using XML and HTTP(S)-based mechanisms. 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. Implementing Web Services Here comes a brief step-by-step on how a Web service is implemented. •

A service provider creates a Web service



The service provider uses WSDL to describe the service to a UDDI registry



The service provider registers the service in a UDDI registry and/or ebXML registry/repository.



Another service or consumer locates and requests the registered service by querying UDDI and/or ebXML registries.



The requesting service or user writes an application to bind the registered service using SOAP in the case of UDDI and/or ebXML



Data and messages are exchanged as XML over HTTP

Web Service Infrastructure 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 Web Services Technologies and Tools 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 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 datatypes, and a convention for representing remote procedure calls and responses. Apache Axis is an Open Source SOAP server and client. SOAP is a mechanism for interapplication 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. 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. Why Web Services? Here are the benefits of using Web Services: 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. Connecting Different Applications: Web Services allows different applications to talk to each other and share data and services among themselves. Other applications can also use the services of the web services. For example VB or .NET application can talk to java web services and vice versa. So, Web services is used to make the application platform and technology independent. 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).

Loosely Coupled Applications: Web Services are self-describing software modules which encapsulates discrete functionality. Web Services are accessible via standard Internet communication protocols like XML and SOAP. These Web Services can be developed in any technologies (like c++, Java, .NET, PHP, Perl etc.) and any application or Web Services can access these services. So, the Web Services are loosely coupled application and can be used by applications developed in any technologies. For example, I have heard of people developing Web Services using Java technologies and using the Web Services in VB or .NET applications. Web Services Sharing: These days due to complexness of the business, organizations are using different technologies like EAI, EDI, B2B, Portals etc. for distributing computing. Web Services supports all these technologies, thus helping the business to use existing investments in other technologies. 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 Attachments are becoming increasingly popular in the web service development especially in the world of interoperable environment where the language is not at all a barrier and thanks to the Service Oriented Architecture (SOA). DIME attachments are used with a lot of web services developed in C# in the .NET world. Using DIME attachments we can send various binary files, XML fragments and other SOAP messages. These attachments are becoming increasingly popular often with the Health Insurance and Life Insurance sectors that follow the ACORD standards for transferring the prescription data in XML. As a developer very often one faces the following challenges in the context of J2EE web service development with attachments: 1. Developing a web service that handles the attachments. 2. Developing a client for accessing such web service. 3. Develop the code to deal with the attachments used in such web services. 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.

Web Service Implementation 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. Listing 1. Method signatures in the web service public Object getDimeData(DataHandler dh) throws InputValidationException, AttachmentServiceException public Object getMimeData(DataHandler dh) throws InputValidationException, AttachmentServiceException

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. Listing 2. Checking the DIME attachment MessageContext msgContext = MessageContext.getCurrentContext(); Message rspmsg = msgContext.getResponseMessage(); log.info("org.apache.axis.attachments.At tachments.SEND_TYPE_DIME : " + org.apache.axis.attachments.Attachments. SEND_TYPE_DIME); int inputAttachmentType = rspmsg.getAttachmentsImpl().getSendType( ); 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); }

Listing 3 shows the code to handle the MIME attachment. Listing 3. Checking the MIME attachment MessageContext msgContext = MessageContext.getCurrentContext(); Message rspmsg = msgContext.getResponseMessage(); log.info("org.apache.axis.attachments.At tachments.SEND_TYPE_MIME : " + org.apache.axis.attachments.Attachments. SEND_TYPE_MIME); int inputAttachmentType = rspmsg.getAttachmentsImpl().getSendType( ); 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. Listing 4. Getting the byte array from any attachment public static byte[] getBytesFromDataHandler(DataHandler data) throws IOException {

InputStream in = null; byte out[] = null; in = data.getInputStream(); if(in != null) { out = new byte[in.available()]; in.read(out); } else { out = new byte[0]; } return out; }

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. Listing 5. Getting the client's input String from 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. Listing 6. Sending output as a DIME attachment. log.info("setting the DIME type of attachment as the sender sends it as DIME."); rspmsg.getAttachmentsImpl().s etSendType(org.apache.axis.at tachments.Attachments.SEND_TY PE_DIME); ByteArrayDataSource dataSource = new ByteArrayDataSource(result, "UTF-8"); dh = new DataHandler(dataSource); return dh;

Listing 7 shows the procedure to send the output String as a DIME attachment. Listing 7. Sending output as a MIME attachment. log.info("setting the MIME type of attachment as the sender sends it as MIME.");

rspmsg.getAttachmentsImpl() .setSendType(inputAttachmen tType); // Create temp file. File temp = File.createTempFile("MimeOu tput", 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));

You might be wondering why a temporary file is used in case of a MIME attachment. Technically whether it is a DIME or MIME the same code should work in the context of creating an output DataHandler object. But, when using the Apache axis implementation it will not work for MIME attachment. If we use the same procedure we will get javax.mail.MessagingException. I observed this problem with Apache AXIS, you might not get the problem with other implementations and in that case you can use the same code for both DIME and as well as MIME attachments. This might be a bug in one of the open source implementation and the work around for this is to use a temporary file for constructing DataHandler and of course these temporary files will be deleted whenever the server restarts if you use the above code.

Deployment of web Service 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. Listing 8. Contents of deploy.wsdd file. <deployment xmlns="http://xml.apach e.org/axis/wsdd/" xmlns:java="http://xml.

apache.org/axis/wsdd/pr oviders/java" xmlns:ns1="AttachmentSe rvice"> <service name="AttachmentService " provider="java:RPC"> <parameter name="className" value="webservices.atta chments.AttachmentServi ce"/> <parameter name="allowedMethods" value="getDimeData,getM imeData"/> <parameter name="dh" type="ns1:DataHandler"/ > <parameter name="dh" type="ns1:DataHandler"/ >

After installing axis application on Tomcat web server, execute the following command in /src/conf/ directory. On Windows java -cp %AXISCLASSPATH% org.apache.axis.client.AdminClien t -lhttp://localhost:8080/axis /services/AdminService deploy.wsdd On UNIX java -cp $AXISCLASSPATH org.apache.axis.client.AdminClien t -lhttp://localhost:8080/axis /services/AdminService deploy.wsdd

Please follow the guidelines listed on the axis user guide at Installing new WebServices. Running the above command creates the server-config.wsdd file in the webapps/AttachmentServices/WEB-INF directory. If you have trouble creating WSDD file, you can just use the server-config.wsdd file included in the source distribution as it is. If you reached this stage means our web service is ready to be accessed for outside world. You can check WSDL file for this service at http://localhost:8080/AttachmentServices/services/AttachmentService?wsdl. If you encounter an error, it may be caused by problem during deployment of the war file or running the AdminClient. Double check all the steps listed in axis installation user guide.

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. First, create the org.apache.axis.client.Call object as shown in Listing 9 : Listing 9. Creating Call Object for the service. 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 : Listing 10. Client program to access the web service. private static void testDataRetrieval(Call call, String operation) throws IOException { //Set the target service host and service location. call.setTargetEndpointAd dress(new URL(WEB_SERVICE_URL)); //This is the target services method to invoke. call.setOperationName(ne w QName(WEB_SERVICE_NAME, operation)); QName qnameAttachment = new QName(WEB_SERVICE_NAME, "DataHandler"); DataHandler dhSource = new DataHandler(new FileDataSource(INPUT_XML )); call.registerTypeMap

ping(dhSource.getClass() , //Add serializer for attachment. qnameAttachment, JAFDataHandlerSerializer Factory.class, JAFDataHandlerDeserializ erFactory.class); call.addParameter("s ource", qnameAttachment, ParameterMode.IN); //Add the file. call.setReturnType(q nameAttachment); 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.getBytesFromDataHa ndler(dh);

log.info("responseBytes length : " + responseBytes.length); String responseStr = new String(responseBytes, "UTF-8"); log.info("responseStr : " + responseStr); } } catch(RemoteException e) { log.error("AttachmentSer viceException :" , 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 Download the source code of this article: Source Code 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.



For more information on DIME attachments, refer to an article on DIME attachments.

By Jeevaraj Gnanaselvan Dhanaraj ([email protected]) (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 Install JDK (in D:\j2sdk1.4.2_04) Install Tomcat (in E:\Tomcat5.5) Install Eclipse (in E:\Eclipse3.1) Install Lomboz (in E:\Eclipse3.1)



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



Creating a Web service 1. Create a new Dynamic Web Project in eclipse (File -> New -> Other)

2. Enter name as “WebServiceTutorial”, select project location as “E:\Test” and select Apache Tomcat v5.5 as the Target server.

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”.

5. Add a simple method in the “Hello” class as below. public String sayHello(String name){ return "Hello " + name; }

6. Save and build the project. 7. Create a new Web service in eclipse (File -> New -> Other)

8. Select Generate a proxy. 9. Select Test the Web service. 10. Select Overwrite files without warning.

11. Select or enter the Bean name as “com.tutorial.Hello”. This is the java class that we just now created.

12. Continue the wizard by clicking Next and finish. 13. On Finish, the Tomcat server starts up and launches the Test client. 14. Verify the generated contents. Look for Hello.class and the generated JSPs as below.

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 17. If servlet error “org.eclipse.jst.ws.util.JspUtils cannot be resolved or is not a type” is thrown on the browser, then copy the webserviceutils.jar file from the E:\Eclipse3.1\eclipse\plugins\org.eclipse.jst.ws.consumption_0.7.0 into the WEB-INF\lib folder of the WebServiceTutorialClient application and restart the Tomcat server. 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”.

20. The browser greets using the web service.

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.

WEBSERVICE USING APACHE AXIS TUTORIAL-1 Using Java XML-WEBSERVICE from ASP.net. ( published in DeveloperIQ January-2004)( www.developeriq.com) R.S.RAMASWAMY ([email protected])

Sri.Manoj Kothale, has written a fine piece in DeveloperIQ(Nov'03) on exposing an EJB as an XML-WebService, using Axis and JBOss. In this experiment, we attempt exposing a javabean (jws) from Tomcat/Axis and consuming that service in an ASP.net program.This is much simpler.

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. 1) axis1.1 was installed in c:\axis11 2) tomcat4.1 from march-2003 issue of Dev IQ. was installed as c:\tomcat41 3) We will find a folder named 'axis' in c:\axiss11\webapps. Copy this ('axis') folder to c:\tomcat41\webapps 4)

folder.

We must copy activation.jar to:

c:\tomcat41\webapps\axis\web-inf\lib folder. (This file is available in jboss3.2\server\all\lib folder and jboss3.2 was given in NovemberCD.) 5) We set JAVA_HOME for tomcat as follows: c:\tomcat41\bin>set JAVA_HOME=D:\jdk141 (because, we have installed jdk1.4.1 in D-drive). 6) We should uncomment the 'admin servlet' part in the web.xml file in c:\tomcat41\webapps\axis\web-inf folder. 7) We start tomcat server: c:\tomcat41\bin>startup 8) This starts tomcat4.1 and we wait till, it is fully started. 9) We create our own folder c:\axisdemo In this folder, we create a simple javabean

greeter.java as given below.

// c:\axisdemo\greeter.java public class greeter { public String greetme(String s) { return "How are you?……………….."+s; } } 10) we copy greeter.java as greeter.jws into

c:\tomcat41\webapps\axis

folder.

(we did this while tomcat41 was running!).No problem! 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 . (wsdl -> webservice description language). 12) We save this wsdl file in d:\inetpub\wwwroot folder as greeter.wsdl 13)

Our aim is to create a C# file from this wsdl file.

The following command does that. d:\inetpub\wwwroot>wsdl greeter.wsdl This command created greeterService.cs

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 (type this in continuous line). ( t -> target & r -> reference) This command created greeterService.dll 15) Now copy this dll file to d:\inetpub\wwwroot\bin folder. ( If there is no such 'bin' folder create it.). Now create greeterService.aspx as given below. ( in d:\inetpub\wwwroot

folder)

<%@ page language="c#" %> <script runat=server> public void job1(Object o, EventArgs e) { String a = text1.Text; greeterService

greeter = new greeterService();

String s = greeter.greetme(a); Response.Write(s); }
runat=server>


runat=server / rel="nofollow">

( Normally, IIS-5 will be running . If not, start it.) After this, type the URL in browser as: '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’. Ref: AXIS..by RominIrani & JeelaniBasha (wrox press). Tutorual-2 continues in axis2a.htm Visit http://in.geocities.com/rsramsam

WEBSERVICE USING APACHE AXIS -TUTORIAL-2 UNDERSTANDING APACHE AXIS (part-1)(published in DeveloperIQ..April,2004) (www.developeriq.com) R.S.RAMASWAMY ([email protected])

We saw some simple examples for XML-RPC & SOAP in the March,2004 issue. However, the latest technology is Axis from Apache Software Foundation. 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. We have already seen how this is done in an earlier tutorial on utilizing JWS from ASP.NET. (see axis1.htm ). 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) ‘J2EE = Java Server Pages’ ‘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 are too complex’ ‘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.. In Enterprise environment, the cost of and established server like WebLogic/WebSphere/JBoss, more than offsets the expenditure, by comprehensive support and reliability with advanced features. However, while EJB is essential for Enterprise level, it is equally important to provide for interoperability, for at least some of the business logic. It extends the reach of the business object to more clients. It is able to overcome firewalls and enables interaction between programs. And that is the topic of our present tutorial. 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 This is a very simple and quick method. 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

WEBSERVICE USING APACHE AXIS TUTORIAL-2 UNDERSTANDING APACHE AXIS (part-2) published in DeveloperIQ..April,2004) (www.developeriq.com) R.S.RAMASWAMY([email protected])

Creating and testing an EJB in WebLogic Server.Let us begin by creating our working folder as c:\sam. We then edit the three files for EJB in that folder. sqlremote.java sqlhome.java) sqlbean.java // sqlremote.java import javax.ejb.*; import java.rmi.*; public interface sqlremote extends EJBObject { public String showdata(String s) throws RemoteException; }

//sqlhome.java import javax.ejb.*; import java.rmi.*; public interface sqlhome extends EJBHome { public sqlremote create() throws RemoteException,CreateException; }

// sqlejbbean.java import java.sql.*; import javax.ejb.*; import java.rmi.*; import javax.naming.*; public class sqlejbbean implements SessionBean { public sqlejbbean() {} public String showdata(String s) { String r=" "; try{ Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); String url="jdbc:odbc:dbdemo"; Connection con=DriverManager.getConnection(url); Statement st=con.createStatement(); ResultSet rs=st.executeQuery(s); while(rs.next()) { r=r+rs.getString(1)+"\n"+rs.getString(2)+"\n"+"-------"; }

}catch(Exception e1) {System.out.println(" "+e1);} return r; } public void ejbCreate()

{}

public void ejbRemove()

{}

public void ejbActivate() {} public void ejbPassivate() {} public void setSessionContext(SessionContext sc) {} } Please note that Weblogic7 will work only in Windows 2000. So, we are now working in Windows 2000. Let us now set HOMEPATH & CLASSPATH. c:\sam>set JAVA_HOME=d:\jdk1.4.2 (We have installed jdk1.4.2 in d :\) c:\sam>set WL_HOME=d:\bea\weblogic700 c:\sam>set path=c:\windows\command;d:\ jdk1.4.2\bin; d:\bea\weblogic700\server\bin; c:\sam>set classpath=c:\sam; d:\bea\weblogic700\server\lib\weblogic.jar; We now compile files in c:\sam folder. c:\sam>javac

*.java

Create a subfolder named META-INF as follows: ( it should be capital letters!) 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

<ejb-jar> <enterprise-beans> <session> <ejb-name>sqlejbbean sqlhome sqlremote <ejb-class>sqlejbbean <session-type>Stateless Container

//weblogic-ejb-jar.xml <weblogic-ejb-jar> <weblogic-enterprise-bean> <ejb-name>sqlejbbean <jndi-name>sqlejbJndi Now, revert back to c:\sam folder. Create the jar file as follows: sam>jar cf sql.jar

*.class

META-INF\*.xml

This command will create sql.jar. The next step is to create sql1.jar for deployment in weblogic server. sam>java weblogic.ejbc

sql.jar sql1.jar

This will create sql1.jar. We may get some warning messages, which can be ignored. Finally, we get the message ‘ejbc successful’.

Now copy sql1.jar to the following folder: d:\bea\user_projects\mydomain\Applications Start weblogic server by the following procedure: Startmenu->programs-> bea weblogic platform->user projects->mydomain->startserver Give

username: system

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.*; public class sqlConsoleClient { public static void main(String args[]) { try { Properties

props=new Properties();

props.put (Context.INITIAL_CONTEXT_FACTORY, "weblogic.jndi.WLInitialContextFactory"); String url="t3://127.0.0.1:7001"; props.put(Context.PROVIDER_URL,url); Context context=new InitialContext(props); System.out.println("context ok.."); sqlhome home=(sqlhome)context.lookup("sqlejbJndi"); System.out.println("home ok.."); sqlremote remote=home.create(); System.out.println("remote ok..");

a=remote.showdata(s); System.out.println(a); }catch(Exception e1) {System.out.println(" "+e1);} } catch(Exception e1) {System.out.println(“”+e1);} } } Now compile the client file: C:\sam>javac sqlConsoleClient.java Let us now run the client program: >java sqlConsoleClient

“select * from table1”

We will get a few names and numbers.We now proceed to create the jsp file . // sqljspclient.jsp <%@ page import=”javax.ejb.*”

%>

<%@ page import=”java.rmi.*”

%>

<%@ page import=”javax.rmi.*”

%>

<%@ page import=”javax.naming.*” <%@ page import=”java.util.*”

%>

<%@ page import=”java.io.*”

%>

%>

<% String sql= request.getParameter(“text1”); Out.println(“please wait”); Properties

props=new Properties();

props.put (Context.INITIAL_CONTEXT_FACTORY, "weblogic.jndi.WLInitialContextFactory"); String url="t3://127.0.0.1:7001"; props.put(Context.PROVIDER_URL,url); Context context=new InitialContext(props);

System.out.println("context ok.."); sqlhome

home=(sqlhome)context.lookup("sqlejbJndi");

System.out.println("home ok.."); sqlremote remote=home.create(); System.out.println("remote ok.."); a=remote.showdata(s); out.println(a); %> Create the corresponding html file to invoke the above jsp. // sqljspclient.htm
sql
We have installed tomcat3.2 in e: drive. Copy sqljspclient.jsp & sqljspclient.htm to e:\tomcat\webapps\root. To start the tomcat server, cd to 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: a. as *.jws (known as Drop-in Deployment).( part-3) b. by using wsdd file etc.(part-4) The next article discusses these aspects in detail. Continued in axis2c.htm Visit http://in.geocities.com/rsramsam

Related Documents

Webservices
July 2020 7
Webservices
June 2020 6
Webservices-book
November 2019 9
Webservices Profiling
May 2020 11
Asp.net&webservices
December 2019 3