Chapter 18. Creating Web Services with IBM WebSphere

IBM has been an active participant in the formation of Web services standards from the beginning. In fact, most of the current proposed standards that we discuss in the latter hours of the book were created with heavy IBM involvement.

In this hour, you will learn about IBM’s WebSphere Studio Application Developer (WSAD). We will pay particular attention to the features of this product that pertain to the creation of Web services. In particular, you will learn

  • How to use WSAD to create a Web service

  • How to generate a trial client application

  • How to run the trial application to verify that your Web service works

IBM and Web Services

IBM became involved with Web services in its early stages. It has provided strong support for the activities of all the major standards bodies for several years. IBM is also closely allied with Sun Microsystems in the area of Java and J2EE. IBM joined with Microsoft in submitting SOAP 1.1 to the World Wide Web Consortium (W3C).

IBM’s product offerings are less well known than those of Microsoft and BEA. This is primarily because IBM doesn’t actively market its development tools to independent consultants. IBM’s major marketing efforts are aimed at Fortune 500 companies. Most of its marketing efforts seem to be focused on getting these clients to use its flagship development product, WebSphere Application Developer.

WebSphere Studio Application Developer

WebSphere Studio Application Developer

IBM’s WebSphere Studio Application Developer (WSAD) is a full-service Java development environment that is based on the Eclipse code base. The value that it adds to the Eclipse code is found in the wizards that it includes for creating projects of a specific type. Later in this hour, you will use these wizards to create a simple Web service and other wizards to generate a sample application.

WSAD’s primary advantage is in a large development team. Each installation contains its own test version of WebSphere Application Server that allows an individual programmer to test his code before deploying it to the team’s server. This means that two different developers can test their changes to the same part of the application without fear of interfering with each other.

WebSphere Application Server is built upon the foundation of the Apache products. This provides WebSphere with both a Web server and a SOAP engine. These products are so heavily wrapped in the user interface that you might not even realize you are running them if no one told you about it.

Developing a Web Service with WSAD

The WSAD approach to creating a Web service is very Java-centric. It is based on the creation of a Java class that fits into the basic bean pattern with private variables that come with a full set of get() and set() methods, along with any other logic that is required. One or more public methods is defined as the interface into the Web service. WSAD generates all the code needed to turn this class into a Web service.

The scenario that we will use is a new customer scenario. We will create two classes—a new customer class that contains the data and a CustomerManager class that keeps track of all the customers. No database will be used in order to keep the complexity of the example to a minimum.

Creating the Project

The first step is to create the project. You do this by starting up WSAD and then choosing New, Project from the File menu. This will bring up the New Project dialog box. Choose Web, Web Project, Next. A dialog box similar to the one shown in Figure 18.1 will appear.

WebSphere Studio Application Developer requires that a project be created.

Figure 18.1. WebSphere Studio Application Developer requires that a project be created.

Name the project CustomerManagement, accept all the defaults on this page, and click Next. Name the Enterprise Application project CustomerManagementEAR as shown in Figure 18.2.

WebSphere Studio Application Developer also requires that an Enterprise project be created.

Figure 18.2. WebSphere Studio Application Developer also requires that an Enterprise project be created.

The Enterprise project will manage the server instances that are created to run your application. Make sure that the New radio button is selected and accept the defaults for everything else. Click Finish. Two projects, the Web and EAR projects, will appear in the Navigator pane. Right-click on the CustomerManagement project in the Navigator pane and choose Properties from the context menu that appears. Selecting Java Build Path on the left and Libraries on the right will show a dialog box that looks like Figure 18.3.

The Libraries tab allows you to add jar files to the Build Path for your project.

Figure 18.3. The Libraries tab allows you to add jar files to the Build Path for your project.

The Build Path is a set of all directories and jar files that will be used to locate the classes needed by your project. The default Web project doesn’t need either Xerces or SOAP, so these jar files are not included by default. You add them by clicking on the Add External JARs button and then using the File dialog box to locate soap.jar and xerces.jar. The version of WSAD that we ran had them stored in

C:Program FilesIBMWebSphere Studio
untimesase_v5lib

Locate both of them and click on the OK button.

Adding the Code

As we stated earlier in the hour, WSAD builds Web services by using Java classes as input. We now need to create the Java classes that will be used in this process. The first class that we will create will be called Customer. In WSAD, the appearance of the IDE changes depending on your choice of “perspective.” You choose a perspective to suit the role that you are filling at any given moment. Until now, you were creating a Web project, so you were in the Web perspective. Now you want to be a Java developer for a while, so you change your perspective by selecting Open Perspective, Java from the Window menu. This will transform the IDE to look like Figure 18.4.

The Java perspective provides you with a set of tools that are designed for Java development.

Figure 18.4. The Java perspective provides you with a set of tools that are designed for Java development.

The primary areas of the Java perspective are the Package Explorer on the left, the Editor pane in the middle, and the Task pane on the bottom. The Task pane shows you errors and warnings.

Note

The Java perspective provides you with a set of tools that are designed for Java development.

WSAD perspectives can be thought of as different but complimentary products in the same IDE. The Server perspective is for running the application, the Debug perspective is for debugging, the Java perspective is for editing and compiling code, and so on.

We need a couple of classes for this example. First, we need a class to represent the customer. You create a new Java class by right-clicking on the Java Source folder in the Navigator Pane. This will bring up the dialog shown in Figure 18.5.

The Java perspective provides you with tools to create Java classes.

Figure 18.5. The Java perspective provides you with tools to create Java classes.

Name the package com.mycompany and the class Customer. Click Finish to generate the code. This will generate a Stub of a class called Customer. Complete the class by adding the code in Listing 18.1.

Example 18.1. The Customer.java File

package com.mycompany;

import java.util.Date;
import java.lang.String;


/**
 * @author Steve Potts
 */

public class Customer
{
     private int customerNumber;
     private String customerName;
     private String street;
     private String city;
     private String state;
     private String zip;

     static int nextCustomerNumber = 1000;

     //constructor
     public Customer()
     {
          this.customerNumber = nextCustomerNumber;
          nextCustomerNumber++;
     }

     //getters

     public String getCustomerName()
     {
          return this.customerName;
     }

     public String getStreet()
     {
          return this.street;
     }

     public String getCity()
     {
          return this.city;
     }

     public String getState()
     {
          return this.state;
     }

     public String getZip()
     {
          return this.zip;
     }

     public int getCustomerNumber()
     {
          return this.customerNumber;
     }

//Setters

     public void setCustomerName(String customerName)
     {
          this.customerName = customerName;
     }

     public void setStreet(String street)
     {
          this.street = street;
     }

     public void setCity(String city)
     {
          this.city = city;
     }

     public void setState(String state)
     {
          this.state = state;
     }

     public void setZip(String zip)
     {
          this.zip = zip;
     }

}

This class is a garden-variety Java class. The static variable allows us to keep up with the customer numbers that have already been given out.

   //constructor
   public Customer()
   {
        this.customerNumber = nextCustomerNumber;
        nextCustomerNumber++;
   }

The constructor allocates the next number.

We also need another class to provide method calls for the Web service. This class, the CustomerManager class, is shown in Listing 18.2.

Example 18.2. The CustomerManager.java File

package com.mycompany;

import java.util.Date;
import java.util.Vector;
import java.lang.String;

/**
 * @author Steve Potts
 *
*/
public class CustomerManager
{

      static Vector customers = new Vector();

      public int createNewCustomer(
      String customerName,
      String street,
      String city,
      String state,
      String zip)
      {
         Customer newOne = new Customer();

         newOne.setCustomerName(customerName);
         newOne.setStreet(street);
         newOne.setCity(city);
         newOne.setState(state);
         newOne.setZip(zip);

         customers.addElement(newOne);

         return newOne.getCustomerNumber();
     }
}

Cut and paste Listings 18.1 and 18.2 into WebSphere, and continue with the exercise. This class is very ordinary, by design, so that your attention will be on the creation of the Web service itself.

customers.addElement(newOne);

After the customer is created, you add it to the customers vector.

Generating the Web Service

Your next task is to generate the Web service from these classes. Choose New, Other from the File menu. When the dialog box shown in Figure 18.6 appears, choose Web Services in the left pane and Web Service in the right pane and click Next.

Web services are created by the IDE.

Figure 18.6. Web services are created by the IDE.

This will bring up the dialog box shown in Figure 18.7.

The Web service that we are creating is of type Java Bean.

Figure 18.7. The Web service that we are creating is of type Java Bean.

Choose Java Bean Web Service as the Web service type, check the boxes as shown in the figure, and click on Next.

Note

The Web service that we are creating is of type Java Bean.

The term “Java Bean Web Service” is one that is generated from a class that follows the Java Bean pattern. You can also use WSAD to generate a Web service from an EJB.

One of the boxes, Test the Generated Proxy, will cause the test application to be generated. This will bring up the dialog box shown in Figure 18.8.

We specify the name of the project containing the bean.

Figure 18.8. We specify the name of the project containing the bean.

The CustomerManagement class is chosen because it contains the Java code for the Web service. Clicking on Next brings up the dialog box shown in Figure 18.9, which allows us to specify the class containing the methods that we want to expose.

You specify the Java bean to be used to create the Web service.

Figure 18.9. You specify the Java bean to be used to create the Web service.

Click on Next to see the names of all the files that will be generated. This is shown in Figure 18.10.

You can modify the default locations of the files generated for the Web service.

Figure 18.10. You can modify the default locations of the files generated for the Web service.

Accept the defaults and click Next. This will bring up the dialog box shown in Figure 18.11.

The SOAP encoding is the default.

Figure 18.11. The SOAP encoding is the default.

Accept the defaults and click Next again. This will bring up the Binding Proxy Generation screen shown in Figure 18.12. The proxy is created so that we can test the Web service.

The proxy allows clients to communicate with the service.

Figure 18.12. The proxy allows clients to communicate with the service.

Click Next. The screen that comes up is shown in Figure 18.13. It asks whether you want to run the test application. Check the Test the Generated Proxy box, and click Next.

Testing the proxy is done by creating test JSPs that use the Web service.

Figure 18.13. Testing the proxy is done by creating test JSPs that use the Web service.

The dialog box in Figure 18.14 asks whether you want to publish the Web service to a UDDI registry. For this example, we will not publish it.

Publishing the Web service to a UDDI registry can be done at the same time.

Figure 18.14. Publishing the Web service to a UDDI registry can be done at the same time.

Clicking Finish will cause WSAD to go off and generate code, start up servers, and so on for several minutes.

Testing the Web Service

When WSAD finishes, it will display a browser in the center pane. Clicking on the createNewCustomer() method will display a generated form in the right panel. Entering data and pressing the Invoke key will produce a result like the one displayed in Figure 18.15.

The test program runs in the browser.

Figure 18.15. The test program runs in the browser.

You will see a different customer number in the bottom pane based on how many times you have executed the service. This magic effect was created by WSAD in a new project called CustomerManagementClient. The proxy file that was generated by WSAD is shown in Listing 18.3.

Example 18.3. The CustomerManagerProxy.java File

package proxy.soap;

import java.net.*;
import java.util.*;
import org.w3c.dom.*;
import org.apache.soap.*;
import org.apache.soap.encoding.*;
import org.apache.soap.encoding.soapenc.*;
import org.apache.soap.rpc.*;
import org.apache.soap.util.xml.*;
import org.apache.soap.messaging.*;
import org.apache.soap.transport.http.*;

public class CustomerManagerProxy
{
  private Call call;
  private URL url = null;
  private String stringURL =
    "http://localhost:9080/CustomerManagement/servlet/rpcrouter";
  private java.lang.reflect.Method setTcpNoDelayMethod;

  public CustomerManagerProxy()
  {
   try
   {
     setTcpNoDelayMethod = SOAPHTTPConnection.class.getMethod(
                     "setTcpNoDelay", new Class[]{ Boolean.class} );
    }
    catch (Exception e)
    {
    }
    call = createCall();
  }

  public synchronized void setEndPoint(URL url)
 {
    this.url = url;
  }

  public synchronized URL getEndPoint() throws MalformedURLException
 {
    return getURL();
  }

  private URL getURL() throws MalformedURLException
 {
    if (url == null && stringURL != null && stringURL.length() > 0)
    {
      url = new URL(stringURL);
    }
    return url;
  }

  public synchronized int createNewCustomer(
      java.lang.String customerName,java.lang.String street,
      java.lang.String city,java.lang.String state,java.lang.
                                 String zip) throws Exception
  {
  String targetObjectURI =
             "http://tempuri.org/com.mycompany.CustomerManager";
  String SOAPActionURI = "";

  if(getURL() == null)
  {
    throw new SOAPException(Constants.FAULT_CODE_CLIENT,
    "A URL must be specified via CustomerManagerProxy.setEndPoint(URL).");
  }

  call.setMethodName("createNewCustomer");
  call.setEncodingStyleURI(Constants.NS_URI_SOAP_ENC);
  call.setTargetObjectURI(targetObjectURI);
  Vector params = new Vector();
  Parameter customerNameParam = new Parameter(
         "customerName", java.lang.String.class, customerName,
                                                Constants.NS_URI_SOAP_ENC);
  params.addElement(customerNameParam);
  Parameter streetParam = new Parameter("street",
                    java.lang.String.class, street, Constants.NS_URI_SOAP_ENC);
  params.addElement(streetParam);
  Parameter cityParam = new Parameter("city",
                  java.lang.String.class, city, Constants.NS_URI_SOAP_ENC);
  params.addElement(cityParam);
  Parameter stateParam = new Parameter("state",
                   java.lang.String.class, state, Constants.NS_URI_SOAP_ENC);
  params.addElement(stateParam);
  Parameter zipParam = new Parameter("zip",
                    java.lang.String.class, zip, Constants.NS_URI_SOAP_ENC);
  params.addElement(zipParam);
  call.setParams(params);
  Response resp = call.invoke(getURL(), SOAPActionURI);

  //Check the response.
  if (resp.generatedFault())
  {
    Fault fault = resp.getFault();
    call.setFullTargetObjectURI(targetObjectURI);
    throw new SOAPException(fault.getFaultCode(),
                                      fault.getFaultString());
  }
  else
  {
    Parameter refValue = resp.getReturnValue();
    return ((java.lang.Integer)refValue.getValue()).intValue();
  }
 }

  protected Call createCall()
  {
    SOAPHTTPConnection soapHTTPConnection = new SOAPHTTPConnection();
    if ( setTcpNoDelayMethod != null)
    {
      try
      {
        setTcpNoDelayMethod.invoke(soapHTTPConnection,
                                          new Object[]{ Boolean.TRUE} );
      }
      catch (Exception ex)
      {
      }
    }
    Call call = new Call();
    call.setSOAPTransport(soapHTTPConnection);
    SOAPMappingRegistry smr = call.getSOAPMappingRegistry();
    return call;
  }
}

Note

The CustomerManagerProxy.java File

If you want to look at the generated code, choose the Web perspective. The code is located under the CustomerManagementClient project. Open the Java source folder, and then look in the proxy.soap package for the file.

You should not expect to understand everything that is included in this generated file, but you might notice some interesting parts.

 private Call call;
 private URL url = null;
 private String stringURL =
  "http://localhost:9080/CustomerManagement/servlet/rpcrouter";

The Call object is commonly used to represent the SOAP call. The URL is the actual servlet that routes the call to the call handler.

This Java file is called by a JSP that was also generated for you by WSAD. Listing 18.4 shows this JSP.

Example 18.4. The Result.jsp File

<HTML>
<HEAD>
<TITLE>Result</TITLE>
</HEAD>
<BODY>
<H1>Result</H1>

<jsp:useBean id="CustomerManagerid" scope="session"
                                class="proxy.soap.CustomerManagerProxy" />
<%!
public static String markup(String text) {
    if (text == null) {
        return null;
    }

    StringBuffer buffer = new StringBuffer();
    for (int i = 0; i < text.length(); i++) {
        char c = text.charAt(i);
        switch (c) {
            case '<':
                buffer.append("&lt;");
                break;
            case '&':
                buffer.append("&amp;");
                break;
            case '>':
                buffer.append("&gt;");
                break;
            case '"':
                buffer.append("&quot;");
                break;
            default:
                buffer.append(c);
                break;
        }

    }
    return buffer.toString();
}
%>


<%
String method = request.getParameter("method");
if (method == null) method = "";

boolean gotMethod = false;
try {
if (method.equals("setEndPoint(java.net.URL)")) {

        gotMethod = true;
        String url0id= markup(request.getParameter("url5"));
        java.net.URL url0idTemp = new java.net.URL(url0id);
        CustomerManagerid.setEndPoint(url0idTemp);
}else if (method.equals("getEndPoint()")) {

        gotMethod = true;
        java.net.URL mtemp = CustomerManagerid.getEndPoint();
if(mtemp == null){
%>
<%=mtemp %>
<%
} else{
        String tempResultresult8 = markup(mtemp.toString());
        %>
        <%= tempResultresult8 %>
        <%
}
}else if (method.equals("createNewCustomer(java.lang.String,java.lang.String,
                       java.lang.String,java.lang.String,java.lang.String)")) {

         gotMethod = true;
         String customerName1id= markup(request.getParameter("customerName13"));
         java.lang.String customerName1idTemp = customerName1id;
         String street2id= markup(request.getParameter("street15"));
         java.lang.String street2idTemp = street2id;
         String city3id= markup(request.getParameter("city17"));
         java.lang.String city3idTemp = city3id;
         String state4id= markup(request.getParameter("state19"));
         java.lang.String state4idTemp = state4id;
         String zip5id= markup(request.getParameter("zip21"));
         java.lang.String zip5idTemp = zip5id;
         int mtemp = CustomerManagerid.createNewCustomer(customerName1idTemp
                     ,street2idTemp,city3idTemp,state4idTemp,zip5idTemp);
         String tempResultresult11 = markup(String.valueOf(mtemp));
         %>
         <%= tempResultresult11 %>
         <%
}} catch (Exception e) {
%>
exception: <%= e %>
<%
return;
}
if(!gotMethod){
%>
result: N/A
<%
}
%>
</BODY>
</HTML>

 

You can locate this code in WSAD by going to the Web perspective and looking in the Navigator under the CustomerManagerClient project. The folder chain is Web content, sample, and then CustomerManager.

The actual call is shown here:

}else if (method.equals("createNewCustomer(java.lang.String,java.lang.String,
                       java.lang.String,java.lang.String,java.lang.String)")) {

      gotMethod = true;
      String customerName1id= markup(request.getParameter("customerName13"));
      java.lang.String customerName1idTemp = customerName1id;
      String street2id= markup(request.getParameter("street15"));
      java.lang.String street2idTemp = street2id;
      String city3id= markup(request.getParameter("city17"));
      java.lang.String city3idTemp = city3id;
      String state4id= markup(request.getParameter("state19"));
      java.lang.String state4idTemp = state4id;
      String zip5id= markup(request.getParameter("zip21"));
      java.lang.String zip5idTemp = zip5id;
      int mtemp = CustomerManagerid.createNewCustomer(customerName1idTemp
                  ,street2idTemp,city3idTemp,state4idTemp,zip5idTemp);
      String tempResultresult11 = markup(String.valueOf(mtemp));
      %>
      <%= tempResultresult11 %>
      <%

Notice that each of the values in the object is obtained from the request object.

The connection between this JSP file and the Web service is found in the useBean tag of the JSP.

<jsp:useBean id="CustomerManagerid" scope="session"
                                class="proxy.soap.CustomerManagerProxy" />

This JSP is declaring that it intends to use the proxy code to communicate with the Web service. You can cut and paste from this JSP to create an application that fits your requirements. Alternatively, you could write a Java application that uses this proxy to access the Web service also.

Another alternative would be to take the WSDL file generated for this project and use it to create a client using any number of tools such as WebLogic Workshop or Visual Studio .NET. The WSDL for this project is stored in

...IBMwsadworkspaceCustomerManagementWeb Contentwsdlcommycompany

The root of this is where you installed WSAD. Normally it is c:Program Files. The files in this directory can be combined to create a WSDL that can be used by any tool to communicate with this Web service.

Summary

In this hour, you learned about IBM’s entry into the Web services tools market. You first learned about IBM’s role in Web services. Next, you learned about its flagship Java Development tool, WebSphere Studio Application Developer. You then developed a business application in Java and transformed it into a Web service using WSAD. Finally, you used WSAD to create a JSP that can be used to test your Web service.

Q&A

Q

What isn’t WSAD more popular with independent consultants?

A

IBM’s marketing of WSAD tends to be aimed at large companies. It tends to be expensive compared to .NET and other comparable products.

Q

What type of resources are available for learning WSAD?

A

Unfortunately, they are limited. IBM offers some courses in WSAD. You can find articles on WSAD at www.ibm.com, but there are no “WSAD Unleashed” books on the market.

Workshop

The Workshop is designed to help you review what you’ve learned and to test your understanding of WebSphere.

Quiz

1.

What type of program is used to provide functionality for WSAD Web services?

2.

What type of Web services test program is generated by WSAD?

3.

What other types of programs besides Web services can be generated using WSAD?

Quiz Answers

1.

A Java Bean is used to hold data and an ordinary Java class is used to provide methods.

2.

A Java Server Page (JSP) is created for testing the Web service.

3.

WSAD is a full-service J2EE development environment that can be used to create servlets, EJBs, JSPs, and Java applications.

Activities

1.

Create a calculator Web service and a client on your computer using WSAD. Follow the same methodology that we used previously.

2.

Move the generated client to another computer and access the Web service from it. The same URL that you are using on your own computer will be used on that computer also.

 

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.137.218.230