Develop a Java*-Based Client for a .NET* Web Service

by Nitin Gupta
Intel Corporation

Introduction

To demonstrate Web services interoperability, Intel engineer, Nitin Gupta, writes a client using the Java Web Services Developer Pack.*

In the last article, Embrace Cross Platform Interoperability with Web Services, we developed a .NET-based Web service. We could proceed to easily write a client in .NET to consume this Web service. Instead, to demonstrate the Web services interoperability, we will write a client in Java using the Java Web Services Developer Pack (Java WSDP*).


Java Web Services Developer Pack

The Java WSDP is an integrated toolset that, in conjunction with the Java platform, allows Java developers to build, test, and deploy XML applications, Web services, and Web applications. It provides Java standard implementations of existing key Web services standards including WSDL, SOAP, ebXML, and UDDI, as well as important Java standard implementations for Web application development such as JavaServer Pages (JSPs)* and the JSP Standard Tag Library*.

The Java WSDP is not a product, but rather a reference implementation of Web services standards in a convenient, easy-to-install package. The package is comprised of a combination of production-ready implementations, along with several components that should only be used for testing purposes.

The Java WSDP includes the following components and technologies:

  • Java XML Pack Release*, which includes the following:
    • Java API for XML Messaging (JAXM)*
    • Java API for XML Processing (JAXP)*
    • Java API for XML Registries (JAXR)*
    • Java API for XML-based RPC (JAX-RPC)*
    • SOAP with Attachments API for Java (SAAJ)*
  • JavaServer Pages Standard Tag Library (JSTL)*
  • Java WSDP Registry Server*
  • Web Application Deployment Tool*
  • Ant Build Tool*
  • Apache Tomcat* container

 

The Java API for XML-based RPC (JAX-RPC) enables Java technology developers to develop SOAP-based interoperable and portable Web services. JAX-RPC provides the core API for developing and deploying Web services on the Java platform.

Some advantages include the following:

  • Portable and interoperable Web services.
  • Ease of development of Web services endpoints and clients.
  • Increased developer productivity.
  • Support for open standards: XML, SOAP, WSDL.
  • Standard API developed under Java Community Process.
  • Support for tools.
  • RPC programming model with support for attachments.
  • Support for SOAP message processing model and extensions.
  • Secure Web services.
  • Extensible type mapping.

 

Commercial implementations of JAX-RPC are already available from some vendors, including SilverStream Software* and BEA Systems*.

To get started on this example, download and install the Java WSDP from:

http://java.sun.com/webservices/downloads/previous/index.jsp*

Make sure that you can access various tools available in the <jwsdp_install_dir>bin directory by modifying your PATH environment variable.


Generate Client-Side Stubs for a Java-Based Client

The first phase to developing a Java-based client is to generate the client-side stubs for the Web service we are interested in. We can do that by using a tool provided in the Java WSDP called xrpcc. This tool is available in the <jwsdp_install_dir>bin directory, and it can generate client-side stubs that internally use JAX-RPC to communicate with the Web service. To use this tool, follow this procedure:

  • Download and save the Web Services Description Language (WSDL) file for the PhoneService Web service as GetPhoneInfo.xml. You can retrieve the WSDL file for the service we have written by accessing this URL (assuming we are using .NET based Web service running on IIS): http://localhost/phonebook/GetPhoneInfo.asmx?wsdl
  • The xrpcc tool does not expect service definition files as input; instead, it expects as input the XML configuration file with information about the WSDL file. Now create a file called config.xml that has the following format: <?xml version="1.0" encoding="UTF-8"?>

    <configuration

    xmlns="http://java.sun.com/xml/ns/jax-rpc/ri/config">

    <wsdl location="GetPhoneInfo.xml"

    packageName="phonepackage">

    </wsdl>

    </configuration>

    For the WSDL model, the configuration file specifies two pieces of information:

    • Line 4 refers to the WSDL file for the PhoneService Web service for which we are developing the client (which we saved earlier). Alternatively, we may decide to specify the location as a URL, which in our case is the following: http://localhost/phonebook/GetPhoneInfo.asmx?wsdl
    • Line 5 refers to the fully qualified package name to which the client Java classes will belong.
  • Run the tool with the following command line: C:source>xrpcc -client -verbose config.xml

    You will see the following output:

    warning: ignoring port "PhoneServiceHttpGet": no SOAP address specified

    warning: ignoring port "PhoneServiceHttpPost": no SOAP address specified

    [ServiceInterfaceGenerator: creating service interface: phonepackage.PhoneService]

    [ServiceGenerator: creating service: phonepackage.PhoneService_Impl]

    [SerializerRegistryGenerator: creating serializer registry:

    phonepackage.PhoneService_SerializerRegistry]

    [CustomClassGenerator: generating JavaClass for: GetPhoneNumber]

    [CustomClassGenerator: wrote file: C:source.phonepackageGetPhoneNumber.java]

    [CustomClassGenerator: generating JavaClass for: GetPhoneNumbe rResponse]

    [CustomClassGenerator: wrote file:

    C:source.phonepackageGetPhoneNumberResponse.java]

    [LiteralObjectSerializerGenerator: writing serializer/deserializer for:

    GetPhoneNumber]

    [LiteralObjectSerializerGenerator: wrote file:

    C:source.phonepackageGetPhoneNumber_LiteralSerializer.java]

    [LiteralObjectSerializerGenerator: writing serializer/deserializer for:

    GetPhoneNumberResponse]

    [LiteralObjectSerializerGenerator: wrote file:

    C:source.phonepackageGetPhoneNumberResponse_LiteralSerializer.java]

    [done in 7922 ms]

 


Create the Java-Based Client

Now we have the client stubs ready to use. The next thing we need to do is to write the Java client code that uses this stub and invokes the Web service. Java WSDP provides multiple methods to create and invoke Web Services as listed below:

  • Stub-based programming model. This model involves code generation using the WSDL-to-Java mapping tool.
  • Dynamic Invocation Interface (DII). DII is a call interface that supports programmatic creation and invocation of an RPC request.
  • Dynamic proxies. A dynamic proxy class implements a list of interfaces specified at runtime when the class is created.

 

We will use the "Stub-based programming model" for our example.

Use a text editor and copy the following code to a file. Save this file as JavaPhoneClient.java:

package phonepackage;

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import phonepackage.*;

public class JavaPhoneClient implements ActionListener
{
   JFrame mainFrame;
   JPanel contentPanel;
   JLabel fnameLabel;
   JLabel lnameLabel;
   JTextField fnameField;
   JTextField lnameField;
   JButton button;
   JLabel dummyLabel;
   JLabel infoLabel;
   JLabel phoneLabel;

   // constructor
   public JavaPhoneClient ()
   {
      // Create the frame and container.
      mainFrame = new JFrame(".NET Web Services - Java Client");
      contentPanel = new JPanel();
      contentPanel.setLayout(new GridLayout(4, 2));

      fnameLabel = new JLabel("First Name");
      contentPanel.add(fnameLabel);

      fnameField = new JTextField() ;
      contentPanel.add(fnameField);

      lnameLabel = new JLabel("Last Name");
      contentPanel.add(lnameLabel);

      lnameField = new JTextField() ;
      contentPanel.add(lnameField);

      dummyLabel = new JLabel("");
      contentPanel.add(dummyLabel);

      button = new JButton("Get Phone Number ...");
      contentPanel.add(button);

      infoLabel = new JLabel("Phone number is : ");
      contentPanel.add(infoLabel);

      phoneLabel = new JLabel("");
      contentPanel.add(phoneLabel);

      button.addActionListener(this);

      // Add the panel to the frame.
      mainFrame.getContentPane().add(contentPanel, BorderLayout.CENTER);

      // Exit when the window is closed.
      mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

      // Show the frame
      mainFrame.pack();
      mainFrame.setVisible(true);
   }

   // Implementation of ActionListener interface.
   public void actionPerformed(ActionEvent event)
   {
      try
      {
         phoneLabel.setText("");
         PhoneServiceSoap_Stub stub = (PhoneServiceSoap_Stub)(new PhoneService_Impl().getPhoneServiceSoap());
         stub._setProperty(stub.ENDPOINT_ADDRESS_PROPERTY, "http://localhost/phonebook/GetPhoneInfo.asmx?wsdl");
         String phoneNumber = stub.getPhoneNumber(lnameField.getText(), fnameField.getText());
         phoneLabel.setText(phoneNumber);
      }
      catch ( Exception ex )
      {
         ex.printStackTrace();
      }
   }
   // main method
   public static void main(String[] args)
   {
      JavaPhoneClient client = new JavaPhoneClient();
   }
}

 

The first few lines of this code create the user interface for the Java Phone Client application.

Since we are using a stub-based programming model here, the first thing we do is to get a reference to the stub automatically created by the xrpcc tool. Next, we specify the service end point, where this service can be located in the next line. The next line calls the "getPhoneNumber" method implemented by our Web service and passes the person's first name and last name as two parameters. The result of this method call is then displayed in the application window.

Please note that the error handling in this Java client is very rudimentary.


Compile and Run the Java Client

Now compile the code using the following command line (assuming that JWSDP kit is installed at the location c:jwsdp-1_0_01). Please modify it according to your local installation location:

javac -classpath .;c:jwsdp-1_0_01commonlibjaxrpc-
api.jar;c:jwsdp-1_0_01commonlibjaxrpc-ri.jar JavaPh
oneClient.java

 

Copy the generated class file to the directory "phonepackage" created earlier that contains the auto-generated stub files.

Now run the application using the following command line:

java -verbose -classpath .;c:jwsdp-1_0_01commonlib
jaxrpc-api.jar;c:jwsdp-1_0_01
commonlibjaxrpc-ri.jar
;c:jwsdp-1_0_01commonlibsoap.jar;c:jwsdp-1_0_01
commonendorsedsax.jar
phonepackage.JavaPhoneClient

 

NOTE: Please modify the directory paths according to your local installation locations.

The following window will appear.



Now enter the first name and last name as shown below and click the "Get Phone Number" button.




The Java client will contact the Web Service and will retrieve the result and display it as shown below.



Conclusion and Additional Resources

This example demonstrates the flexibility and interoperability promised by the Web services programming paradigm. We even used a Java-based client to retrieve information from a Web service written in .NET.

This Java-based client provides the flexibility to use multiple platforms - like handheld computers, cellular phones, and desktop computers - for which Java infrastructure is already available. Thus, to integrate legacy or existing applications, consider exposing data using the Web services model.

In the next article in this series, we will look at the issues around securing Web services.

Intel, the world's largest chip maker, also provides an array of value-added products and information to software developers:

  • Intel® Software Partner Home provides software vendors with Intel's latest technologies, helping member companies to improve product lines and grow market share.
  • Intel® Developer Zone offers free articles and training to help software developers maximize code performance and minimize time and effort.
  • Intel Software Development Products include Compilers, Performance Analyzers, Performance Libraries and Threading Tools.
  • IT@Intel, through a series of white papers, case studies, and other materials, describes the lessons it has learned in identifying, evaluating, and deploying new technologies.
  • The Intel® Academic Community Educational Exchange provides a one-stop shop at Intel for training developers on leading-edge software-development technologies. Training consists of online and instructor-led courses covering all Intel® architectures, platforms, tools, and technologies.

About the Author


Nitin Gupta is a senior software engineer with the Enterprise Business Computing Group at Intel. Nitin holds a Masters degree in Computer Science from the University of Southern California. Nitin has over six years of programming and system design experience. He can be contacted at nitin.gupta@intel.com. Read his earlier Intel® Developer Services article, Embrace Cross Platform Interoperability with Web Services.


 

 

Web Series Articles by Nitin Gupta

 


Para obtener más información sobre las optimizaciones del compilador, consulte el aviso sobre la optimización.