Advertisment

Make Java and .NET apps talk to each other using Web services

author-image
PCQ Bureau
New Update

For two systems to connect and talk to each other to share information successfully, a lot of conditions, such as talking the same 'language' over the same communication 'lines', need to be met. Unless this happens the information remains stuck in one system only. Take for example an information system written in, say, Java. Within the system, the data flows without any hitches. However, in case a different system needs access to the information stored or generated by the first one, it would also need to be written using Java and its associated technologies such as RMI and IIOP. This problem is not only in the Java world. In the Windows world, too, DCOM and DNA have their own proprietary interfaces. And open-source software, though open, have not even had a standard within themselves to share information.

Advertisment

The explosive growth of the Web required information to come from many different sources. Unfortunately, the differences in protocols and implementations did not make life easy for developers who required to pick up information from these disparate sources of data. As an example, consider the case of a developer of an intranet solution for his company. As part of his tasks, he needs to write a module that collates headlines from different websites and displays them in a consistent manner using the company intranet template on the local home page. There are different ways he can do this.

  • Request the source sites for access to their database. The problem with this approach is that, one, the sites most probably will not give such access and, second, the data required may not be stored but may be generated on the fly based on some internal business processes.
  • Connect to different platforms and technologies. This is one of the major problems. It will always happen that the developer would require to work with and connect to different platforms and technologies to get the required data. For instance, if the intranet is being developed, say in .NET, he would need to connect to sites that use Java technologies, OSS technologies and, if he is very lucky, .NET technologies. This problem occurs no matter what the platform is on either side. As long as the developer needs to work with different ones, he will face compatibility problems and would need to devise ways of making one platform talk to another.
  • Security is yet another concern. Most proprietary technologies use their own ways of talking to each other. In case the developer in question needs to work with RMI, IIOP, DCOM, MTS, and so on, the corporate firewall would need to allow such type of packets to go through. This also means that the company's network has a larger attack surface due to the loosening of the firewall. This is something that most system administrators would not allow.
  • Remote communication protocols are complex. Consider writing an application in DCOM, RMI, IIOP or

    CORBA. Each of these methods is extremely complex, and if you need to make them talk not just to other components of the same type, but also to other protocols, the level of complexity increases exponentially.

Web services provide a standard way for

different platforms and devices to access the same information

Advertisment

So what does a developer do to solve all these problems? This is where Web services come in. This is a new standard that has been developed by Microsoft, IBM, Sun and others who describe a way that applications can communicate with each other using standard protocols and methods. This means that an application written in, say, Java will be able to communicate with and utilize a service created in .NET or vice versa. These technologies are, of course, only indicative. Almost all new development platforms and technologies support Web services intrinsically and can talk to any other one that also understands this standard.

The backbone of the magic behind Web services is called SOAP (Simple Object Access Protocol). This is a W3C standard standing currently at version 1.2. This standard defines SOAP to be a stateless, one-way message exchange method using XML for encoding and describing the data within the message. Implementations of the SOAP standard usually extend this to allow 'conversation' style messages to be passed back and forth from a 'SOAP Sender' and 'SOAP Receiver'. The standard also does not talk about how the SOAP message is to be routed, firewall traversing, reliable data transfer, etc. This is left up to the implementation of the SOAP transport.

However, the standard does give two examples of usage, one by binding a SOAP message to the HTTP protocol and the other to SMTP. The SOAP HTTP binding has become the de facto method by which SOAP messages are transported across the network due to the prevalence of the HTTP service. This is also the reason that the service is popularly known as Web service rather than say e-mail service. However, it is important to remember that the SOAP backbone does not require it to be sent using the Web protocol.

Advertisment

If one looks at the messaging platform now, it consists of the following standards: SOAP, XML and HTTP. All these can be easily implemented by any vendor and can be used by any developer since XML and HTTP are popular and standard. This leads to standards-based implementation where a developer can create and consume Web services regardless of the source and target platforms.

There are, of course, many different associated technologies for Web services, such as WSDL, UDDI and more.



Now, we'll create a simple web service in .NET and Java, which will be consumed across.

Interpop with Java and .NET



We created an application in Java and .NET to get the stock price for a company from an MS SQL database running on a private IP adderss, 172.16.1.84. We hosted the Java application on Tomcat application server running on PCQLinux 2004 and the .NET one on IIS 6.0 Web server running on a Win XP Pro machine.

Advertisment

The name of the SQL Server database was Stocks and it contained a simple table called CoStock whose structure is as follows.

CoID was set as 'identity column' and 'primary key'. The VB.NET Stock application has a method (function) called dotnetGetStockPrice( ) and the Java application has a method called javaGetStockPrice( ) which accepts the name of the company (CoName) as a parameter and returns the stock price (StockPrice) as a single (in VB.NET) and float (in Java). This method was exposed as a Web service.

Column Name Data Type Size
CoID int 4
CoName varchar 20
StockPrice float 8
Advertisment

The client machines included a Win XP Pro and a PCQLinux 2004 machine, wherein we coded and ran simple Web-based and command-line client applications to consume a function/method of the Stock application, which was exposed as a Web service. The setup diagram on the next page further explains our setup.

The remaining article will take you through coding, deploying and consuming Web services in Java, .NET and the interop world.

Java Web service



PCQLinux 2004 bundles Java SDK and Tomcat application server, which are required to compile and deploy a Web service. We assume that you have selected them to install during the PCQLinux 2004 installation. Tomcat gets installed into the directory /opt/tomcat. We will call this directory Tomcat's installation directory. There are more than one

methods/toolkits/implementations to deploy and consume Web services in Java. For this article we have selected one of them, a package called Axis. Download Axis from http://apache.mirrors.hoobly.com/ws/axis/1_1 /axis-1_1.tar.gz. To install and set up Axis refer to the article, Web Services on PCQLinux 2004 (page 76, April 2004, PCQuest). Don't forget to set up the environment variable AXISCLASSPATH as explained in the article.

Advertisment

Before exposing the Stock application as a Web service, we need to deploy it as a web application on Tomcat. We have posted all the code for this article at forums.pcquest.com. Download the zipped directory of the Web application called stockws from the 'Developer Stuff' section at

forums.pcquest.com.

Service Interface

and Description WSDL
Service Discovery,

Publication and Registry UDDI
Wire and Messaging Protocol

Service Invocation



SOAP
Lingua Franca

XML
Network and Transport Protocols

TCP/IP HTTP FTP SMTP JMS

Copy the zip file called stockws.zip to the directory /opt/tomcat/webapps and unzip it as:

Advertisment

unzip stockws.zip

This will produce a directory named stockws under webapps.






Stop and start Tomcat as:

/etc/rc.d/init.d/tomcat stop



/etc/rc.d/init.d/tomcat start

The processing logic of the Web application is in the file called Stock.java found in the WEB-INF/classes subdirectory. This file contains nothing but a simple Java class called Stock with a public method called javaGetStockPrice( ). As said before we will expose this method as a Web service. For this, write a WSDD file (Web Service Deployment Descriptor) file that looks as follows.



xmlns:java="http://xml.apache.org/axis/wsdd/providers/java">














The Web services' setup at CyberMedia Labs

Save the file as deploy.wsdd. For more on WSDD refer to the article Java-based Web Services (page 88, May 2004, PCQuest). Note that the name of the Web service is StockPriceWebPrice. Deploy the Web service as:

java -cp $AXISCLASSPATH org.apache.axis.client.AdminClient -l http://127.0.0.1:8080/stockws/services deploy.wsdd

To see whether the Web service has been deployed successfully, go to http://127.0.0.1:8080/ stockws/services. You should be able to see the following

StockPriceWebService (wsdl)



l javaGetStockPrice

in the output. Click on the wsdl link to take a look at the WSDL (refer to Web Service's Standards below) file for the StockPriceWebService. Note that the URL to the WSDL file is http://

127.0.0.1:8080/stockws/services/StockPriceWeb Service?wsdl.

.NET Web service



Now we'll see how you can create a new Web service using the .NET platform. It will follow with consuming the .NET Web service in a .NET application as well as a Java application.

If you are using VS.NET 2003, the first thing to do to create a Web service in VS.NET is to select the Web service project type from the New Project dialog box. Type in a URL where this service is to be created. For this example, we created the Web service on a local IIS in a virtual folder called StockService. This creates a Web service project by this name and a Web service by the name of Webservice1.asmx.

By default, the Web service comes in Design view. To facilitate coding, we will move on to Code view. The first thing you should do is rename the default Webservice1 to something more intuitive, such as the name we gave (Stocks). This also changes the class definition to the same name. The Web service that is displayed usually has a small 'Hello World' method defined. Typically, you'd want to delete this and create your own. We created a new Web service method called dotnetGetStockPrice, which accepts the name of a company as a parameter. It returns a floating-point number for the stock price of the requested company.

The following code details the Web service. Note that if you are using VS.NET, you only need to enter the part that starts from to the End Function. However, if you are using Notepad for creating the Web service, you must enter the full code in it as shown here. Simply save the file as

Inetpub\wwwroot\StockService\Stock.asmx.



<% WebService Language="VB" Class="Stock" %>



Imports System.Web


Imports System.Web.Services


Imports System.Web.Services.Protocols


Imports System.Data


Imports System.Data.SqlClient



Public Class Stock



Inherits System.Web.Services.WebService

_



Public Function dotnetGetStockPrice(ByVal CompanyName As String) As Single


Dim sSQL As String


Dim sConn As String

sSQL = String.Format("select StockPrice from costock where coname='{0}'", CompanyName)



sConn = "Server=edit07\pcqldb;User ID=sa;Password=pcqlabs;Database=Stocks"

Dim oConn As SqlConnection = New SqlConnection(sConn)



Dim oCmd As SqlCommand = New SqlCommand(sSQL, oConn)


oConn.Open()


Dim fStockPrice As Single = oCmd.ExecuteScalar()


Return fStockPrice


End Function



End Class



The Web service connects to the database and retrieves the stock price of the company passed as a parameter and displays it. To view what it looks like, browse to http://localhost/StockService/Stock.asmx. (If you had used VS.NET to create the service, remember to build the project first.) Click on the method name and enter a company name when prompted. Press the button called 'Invoke' to see the results of the Web service execution.

Consuming the Web service



With the Web service deployed and running on both the platforms, we now have a couple of combos to experiment with.

  • Java Web service and Java client
  • .NET Web service and Java client
  • .NET Web service and .NET client
  • Java Web service and .NET client

Consuming the Java Web service in a Java application



For the client we assume that you are running PCQLinux 2004 with JDK installed. Switch to the client machine and create a directory named javaclient. Copy and extract the downloaded Axis archive on this machine. Copy all the jar files found in the subdirectory webapps/axis/WEB-INF/lib to the javaclient directory. Also copy any additional jar files that you downloaded (when Axis complained about missing components) to the javaclient directory.

Change to the javaclient directory. Extract each of the jar files in the directory by issuing the following command.

jar -xvf

Next issue the following command.

java org.apache.axis.wsdl.WSDL2Java -p com.pcquest

http://172.16.2.68:8080/stockws/services/StockPriceWebService?wsdl

Axis' WSDL2JAVA will generate the required payload to access the Web service through a Java client program from a WSDL file. Note that we are supplying the URL to the WSDL file for the

StockPriceWebService.

You may like to substitute com.pcquest with your preferred package name. The client program to consume the StockPriceWebService will look as follows.

import com.pcquest.*;



public class StockWSClient {


public static void main(String <> args) throws Exception{


StockService service = new StockServiceLocator();


Stock stock = service.getStockPriceWebService();


float result = stock.javaGetStockPrice("xyz");


System.out.println("Result : " + result);


}


}






Simple code and so is its explanation. The lines

StockService service = new StockServiceLocator();



Stock stock = service.getStockPriceWebService();

are the only lines specific to using the Web service. The first line gets a reference to the service and the second line returns a Stock object from the service. Subsequently, the Stock object can be used as a normal

Java object.

How a simple Web service works

Consuming the .NET Web service in a Java application



Switch to the client machine and create a directory named dotnetclient. Copy and extract the downloaded Axis archive on this

machine. Copy all the jar files found in the subdirectory webapps/axis/WEB-INF/lib to the client directory.



Change to the dotnetclient directory. Extract each of the jar files in the directory by issuing the following command.

jar -xvf

Next issue the following command.

java org.apache.axis.wsdl.WSDL2Java -p com.pcquest

http://172.16.1.91/stockservice/Stock.asmx?WSDL

Axis' WSDL2JAVA will generate the required payload to access the Web service through a Java client program from a WSDL file. Note that we are supplying the URL to the WSDL file for the Web service hosted on Win XP.



You may like to substitute com.pcquest with your preferred package name. The client program to consume the Web service will look as follows.

import com.pcquest.*;



public class StockWSClient {


public static void main(String <> args) throws Exception{


StockLocator service = new StockLocator();


StockSoap stock = service.getStockSoap();


float result = stock.dotnetGetStockPrice("xyz");


System.out.println("Result : " + result);


}


}






Consuming the .NET Web service in a .NET application

In VS.NET, create a new Web application. Now, simply right-click on the project name and select Add Web Reference. Now type in the URL to the WSDL for the Web service just created. This will look like http://172.16.1.91 /StockService/Stock. asmx?WSDL. If VS.NET finds it, it will show you the methods of that service in the dialog. Give the Web service a name, such as dotnetService for future reference and press OK.

Now on the main Web page, drop a label control and double click on the page to get into the Page_load event handler. Write the following code there.

Dim dnWS as New dotnetService.Stock



Label1.Text = dnWS.dotnetGetStockPrice("XYZ")

Run the application to see the Web page talk to the .NET Web service and retrieve the data from it.

Consuming a Java Web service in a .NET application

You can follow the exact same procedure to consume a Java Web service sitting on another machine as well. However, as always, you also have a command-line version of generating a Web service proxy. To do this, go to the command prompt and change over to the folder where your application resides. Now you need to use the WSDL tool of the .NET Framework SDK to generate it. Simply issue the command:

WSDL http://172.16.2.68:8080/stockws/services/StockPriceWebService?wsdl

This will generate the proxy for you to use by the same name as the service. You can now use the new class in the Web page just as you could do it above.

As you can see, creating and consuming a Web service in .NET (whether the Web service has been created in .NET or Java) is equally easy. .NET is an excellent platform for both creating and using this technology.

Web Services' Standards



Web services allow a variety of heterogeneous systems, OSs and devices to communicate with each other. This is possible because Web services follow certain industry-accepted standards-anybody building or deploying Web services must adhere to these standards to create a truly open system. These standards define the handling of data, associated transactions and how the service works and is made available to others. Core Web services standard are XML, SOAP, WSDL and UDDI.

eXtensible Markup Language (XML)



XML specifications were developed to describe data that could be widely used for a variety of applications. Software is still needed to process the data. XML makes Web services accessible from any application, other Web services, windows and console applications. The first edition was XML 1.0, which had a few glitches-for example, it was difficult to connect other systems to legacy systems like the mainframe. To overcome this interoperability issue, the XML 1.1 specification was developed. The major difference between these two is support for Unicode. XML 1.1 was also designed to be compatible even with any future versions of the Unicode standard.

Simple Object Application Protocol (SOAP)



Web services require communication between applications without any obstacles. Traditionally, RPC (Remote Procedural Calls) was used for communication between applications, but it had problems going through firewalls, and other security issues. HTTP can easily pass through firewalls, but it was not designed for RPC. SOAP overcomes this and provides a uniform way to communicate in XML messages, irrespective of the communication or transport protocol.

SOAP supports communication in two ways: RPC and document. RPC requires the conversion of a request message into a SOAP message. Once done, the response message contains the return value and any response parameter. The document style assumes that SOAP messages are a well-formed XML document.

There are four elements in SOAP that makes the XML message: envelope, body, an optional header and fault element. The envelope identifies the XML document as a SOAP message and the body contains the request and response information. The fault element provides information about errors occurred while processing the message. You also need to specify how the message is expressed in XML. Either the message can be serialized according to XML schema or a particular encoding style, which is defined in the SOAP specification. SOAP 1.1 is the standard being followed. Its successor will be SOAP 1.2 once the specifications are finalized.

Web Service Descriptor Language (WSDL)



WSDL is an XML document describing the functioning of Web services. It has three elements, wherein the first covers what the Web service does, second how it communicates and third the location of the Web service. The first part, in turn, has three more elements: types, message and portType. Here, the type element uses the XML schema format to describe data types, such as integer and double. A unique name is then given to each data type used. As the data has to be exchanged between applications, the data types are identified with messages for this. The messages are then grouped into an operation, which is like function calls having a name and parameters. The parameters are the input and output messages as defined in the message. The portType is a set of related operations so that the operations can be treated as a single unit and represents the Web-service interface. This means that the Web service can have multiple portTypes with different operations.

The second part binds the portType to the transmission protocol to be used with SOAP. The binding should be given a unique name. You also have to specify the SOAP style and how the messages are to be expressed as described in the SOAP specification. The style is described by the 'style' attribute and message by the 'use' attribute.

Finally, the port name is to be specified where the service will be located through a URL. Currently, WSDL 1.1 specification is widely used and WSDL 1.2 is planned for a future release.

Universal Description, Discovery and Integration (UDDI)



You are familiar with yellow pages where the details of the service being offered by a company can be located. Similarly, UDDI manages information about a Web service provider, service implementations and service metadata. A Web-service provider can advertise

the service through UDDI. The users of the service need to discover the service they require and obtain the metadata. The Web service uses UDDI as a public or private registry. Private registry requires user authentication while public registry doesn't restrict access to the

Web service.

A UDDI directory is an XML file consisting of three parts: white pages, yellow pages and green pages. White pages provide contact information about the company offering the Web service, such as name and address. It also offers unique a business identifier for the company. Yellow pages offer business categorization (taxonomies), such as manufacturing or service industry, which allow discovering the Web service. Green pages give details about the interface for the Web service to be used. UDDI V2.0 is the most widely used specification. UDDI V3.0 specifications have been approved and vendors have started using UDDI V3.0. ¨

By Shekhar Govindarajan, Sushil Oswal, Vinod Unny

Testing Web services' performance

Building a Web-services' solution requires a lot of coding, which also leads to testing, debugging and optimizing the code for performance. LodeRunner software from Mercury is one such tool that can help you with this critical task. It can monitor the network, your application, Web and database servers irrespective of which platform they're on. It emulates multiple users and tries to stress the application for measuring the response time using dummy data. The analysis module in LoadRunner then allows you to probe the specific source of bottleneck and generate reports. The good part about Load Runner is that it is designed to work with both J2EE and .NET. You can find more information on this at www.mercury.com.


Advertisment