Skip to main content

If you don't have an IBM ID and password, register here.

By clicking Submit, you agree to the developerWorks terms of use.

The first time you sign into developerWorks, a profile is created for you. This profile includes the first name, last name, and display name you identified when you registered with developerWorks. Select information in your developerWorks profile is displayed to the public, but you may edit the information at any time. Your first name, last name (unless you choose to hide them), and display name will accompany the content that you post.

All information submitted is secure.

The first time you sign in to developerWorks, a profile is created for you, so you need to choose a display name. Your display name accompanies the content you post on developerworks.

Please choose a display name between 3-31 characters. Your display name must be unique in the developerWorks community and should not be your email address for privacy reasons.

By clicking Submit, you agree to the developerWorks terms of use.

All information submitted is secure.

Developing web services, Part 2: Developing file download web service with JAX-WS.

Kuntal Ganguly (kuntalganguly86@gmail.com), Jr. Developer, Protech Infosystems Pvt. Ltd
Kuntal Ganguly
Currently associated as a Junior Developer at Protech Infosystems Pvt. Ltd, Kolkata. Kuntal has expertise in using a wide range of open source and commercial tools (WAS CE, Eclipse, Mule ESB, EZlegacy , Active MQ , Birt , and DB2 express C) and technologies(GWT and Android).
Partha Goswami (partha.ext@gmail.com), Jr. Developer, Protech Infosystems Pvt. Ltd
Partha Goswami
Currently associated as a Junior Developer at Protech Infosystems Pvt. Ltd, Kolkata. Has expertise in using a wide range of open source and commercial tools (WASCE, Eclipse, Mule ESB, EZlegacy , Active MQ , Birt , and DB2 express C) and technologies(GWT and RSS).

Summary:  This tutorial demonstrate how to develop Hello User web service and followed by File Download web service development using JAX-WS. Finally developing a SAAJ client for processing Product Catalog web service.

View more content in this series

Date:  15 Jun 2011
Level:  Intermediate

Comments:  

Configuration and development

Example I – Hello User Web service

This is a very simple example "Hello World" web service, which will display the string passed as a parameter, invoked from a POJO client. To setup and run this example one need to know few things given below.

Eclipse IDE: An integrated development environment (IDE) is an all-in-one tool for writing, editing, compiling, and running computer programs. And Eclipse provides an excellent integrated development environment. You can find the latest release of eclipse in www.eclipse.org.

JAX-WS: This project develops and evolves the code base for the reference implementation of the Java API for XML Web Services (JAX-WS) specification. The current code base supports JAX-WS 2.0 and JAXWS 2.1 but the project will track future versions of the JAX-WS specifications.. You can download the latest release of Tomcat from http://jax-ws.java.net/2.2.3/.

Set up the Environment

  1. Install JDK 1.5 or above in your system and we will further refer it as <JAVA_HOME>.
  2. After downloading the Jax-ws ,extract it to a directory. After extracting click on the JAXWS2.1.2-20070917.jar file and it will create jaxws-ri directory containing all the necessary tools and jars to successfully develop and deploy the web service. [We will referred the jaxws-ri directory as <JAXWS_HOME>] (Make sure <JAVA_HOME>bin| is set to user Path Variable as shown below in Figure 2).

Figure 2. Setting Java bin to Path
Setting Java bin to Path

Developing Hello User web service in Eclipse IDE with JAX-WS library

  1. Create File > New > Java Project name 'JaxWSHelloService' in Eclipse.
  2. Create a package com.ibm.hello inside JaxWSHelloService|src folder.
  3. Select the 'JaxWSHelloService' project and Create New>Folder lib as shown below in Figure 3.

Figure 3. Creating Hello Service lib folder
Creating Hello Service lib folder
  1. Now copy all the jars from <JAXWS_HOME>lib| and paste it in the lib folder created above.
  2. Now Select the JaxWSHelloService Project and Configure the build path as shown below in Figure 4.

Figure 4. Hello Service Configure Build path
Hello Service Configure Build path

(Now click on Add JARs and select all the jars in the lib folder and then click OK as shown below in Figure 5).


Figure 5. Adding JARs to Hello service build path
Adding JARs to Hello service build path
  1. Create a class named HelloUser.java inside 'com.ibm.hello' package as shown below in Listing 1:

Listing 1. HelloUser web service
   
package com.ibm.hello;
import javax.jws.WebService;
import javax.jws.soap.SOAPBinding;
import javax.jws.soap.SOAPBinding.Style;
import javax.xml.ws.Endpoint;

@WebService
public class HelloUser {
	@SOAPBinding(style = Style.RPC)
	public String sayHello(String name) {
		return "Welcome"+ name;
			}

	public static void main(String[] args) {
		HelloUser server = new HelloUser();
		Endpoint endpoint = Endpoint.publish(
				"http://localhost:8091/wisequotes", server);
	}
}

  1. Now select HelloUser.java and Run As > Java Application.

[After you start your main program (HelloUser) the service should be up and running. And you can access it at http://localhost:8091/wisequotes?wsdl via a browser. You should see the WSDL of your server as shown below in Figure 6].


Figure 6. Hello Service WSDL
Hello Service WSDL

Developing JAX-WS Client for Hello Service - Generate the Stubs

  1. Open the Command Prompt and switch to empty directory and call the wsimport command line tool which is part of the JDK.
    OR
    Open Command prompt and move to <JAXWS_HOME>bin| and call the wsimport command line tool.
  2. Now type the following command as shown belowin Figure 7.
    wsimport -keep http://localhost:8091/wisequotes?wsdl

Figure 7. Hello Client Stub generation
Hello Client Stub generation

[This will generate the stubs for the Client to interface with the methods and factory of HelloUser web service].

Develop HelloClient in Eclipse

  1. Create File > New > Java Project name JAXWSClient in Eclipse.
  2. Create a package com.ibm.hello inside JAXWSClient|src folder as shown in figure 8.

Figure 8. Creating Hello Client package
Creating Hello Client package
  1. Now Copy and paste the stubs generated above in the com.ibm.hello package.
  2. Select the JAXWSClient project and Create New > Folder named 'lib'.
  3. Now copy all the jars from <JAXWS_HOME>lib| and paste it in the lib folder created above.
  4. Now Select the JAXWSClient Project and Configure the build path. (Now click on Add JARs and select all the jar in the lib folder and then click OK).
  5. Create a class named HelloClient.java inside 'com.ibm.hello' package.

Listing 2. HelloClient for HelloUser web service
   
package com.ibm.hello;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.io.*;
import javax.xml.namespace.QName;

public class HelloClient {
public static void main(String[] args) {
		
// Setting up the server connection
		
HelloUserService service = new HelloUserService();
HelloUser servicePort = service.getHelloUserPort();
		
// Calling the web service
		
System.out.println(servicePort.sayHello(" " +"" +"Kuntal"));
		

// Alternatively if you want to specific the URL directly
		
try {
URL url = new URL("http://localhost:8091/wisequotes?wsdl");
HelloUserService serviceWithUrl = new 
        HelloUserService(url,new QName("http://hello.ibm.com/","HelloUserService"));
HelloUser servicePortWithUrl = serviceWithUrl.getHelloUserPort();
			
// To Enter user name from Console

System.out.println("Enter your Name: ");
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);
String s = br.readLine();
System.out.println(servicePortWithUrl.sayHello(s));
			
} catch (MalformedURLException e) {
		e.printStackTrace();
} catch (IOException e) {
			e.printStackTrace();
	}

    }
}

  1. Select HelloClient.java and Run As > Java Application. (Now type your name in the console and Press Enter as shown in Figure 9).

Figure 9. Hello Service Output in console
Hello Service Output in console

Example II - File Download Web Service

This is a simple example of "File Download" web service, where client can download any file from web service and store in client's location. A complete JAX-WS SOAP-based example to show how to use Message Transmission Optimization Mechanism (MTOM) and XML-Binary Optimized Packaging (XOP) technique to send a attachment (.pdf or .text or .doc) file from server to client. Set up are similar to Hello User web service developed in Example I.

Developing File Download web service in Eclipse IDE with JAX-WS library

  1. Create File > New > Java Project name 'JAXWSDownload' in Eclipse.
  2. Create a package 'com.ibm.download.ws' inside 'JAXWSDownload|src' folder, where we will create the Download Service Interface, Download Service Implementation Class and Download Service Publisher Class as shown below:

Figure 10. JAXWS Download project directory structure
JAXWSDownload project directory structure
  1. Select the JAXWSDownload project and Create New>Folder lib.
  2. Now copy all the jars from <JAXWS_HOME>lib| and paste it in the lib folder created above.
  3. Now Select the JAXWSDownload Project and Configure the build path. (Now click on Add JARs and select all the jar in the lib folder and then click OK).
  4. Create a SEI (Service Endpoint Interface) named FileServer.java (see Listing 3) inside 'com.ibm.download.ws package'.

Listing 3. FileServer.java interface for Download Service
        
package com.ibm.download.ws;
import java.io.File;
import javax.activation.DataHandler;
import javax.jws.WebMethod;
import javax.jws.WebService;
import javax.jws.soap.SOAPBinding;
import javax.jws.soap.SOAPBinding.Style;
 
//Service Endpoint Interface

@WebService
@SOAPBinding(style = Style.RPC)
public interface FileServer{
 
	//download a File from server

	@WebMethod 
	public DataHandler downloadFile(String fileName);
 
	
}

  1. Create a Implementation class named FileServerImpl.java (see Listing 4) inside 'com.ibm.download.ws' package.

Listing 4. FileServerImpl.java Download implementation class
      
package com.ibm.download.ws;
import java.io.File;
import java.io.File;
import java.io.IOException;
import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.jws.WebService;
import javax.xml.ws.WebServiceException;
import javax.xml.ws.soap.MTOM;
 
//Service Implementation Bean

@MTOM
@WebService(endpointInterface = "com.ibm.download.ws.FileServer")
public class FileServerImpl implements FileServer{
 
@Override
public DataHandler downloadFile(String fileName) {
 
//Location of File in Web service
		
FileDataSource dataSource = new FileDataSource("c:/test/"+fileName);
 DataHandler fileDataHandler = new DataHandler(dataSource);
 return fileDataHandler;
	}
  }

  1. Create a Enpoint publisher named FilePublisher.java (see Listing 5) inside com.ibm.download.ws package.

Listing 5. FilePublisher.java endpoint publisher class
     
package com.ibm.download.ws;
import javax.xml.ws.Endpoint;
import com.ibm.download.ws.FileServerImpl;
 
//Endpoint publisher

public class FilePublisher{
public static void main(String[] args) {
Endpoint.publish("http://localhost:9899/ws/file", new FileServerImpl());
System.out.println("Server is published!");
 
    }
 
}

  1. Select FilePublisher.java and Run As>Java Application. (You will see Server is Published! In the console. Now open your browser and Paste the wsdl http://localhost:9899/ws/file?wsdl to view the FileDownload webservice WSDL as shown below in Figures 11 and 12).

Figure 11. File Download Service published in Console
File Download Service published in Console

Figure 12. File Download Service wsdl
File Download Service wsdl

Developing JAXWSClient for the FileDownload Web Service - Generate the Stubs

  1. Open Command Prompt and switch to empty directory and call the wsimport command line tool which is part of the JDK.
    OR
    Open Command prompt and move to <JAXWS_HOME>bin| and call the wsimport command line tool.
  2. Now type the following command as shown below in Figure 13.

wsimport -keep –verbose http://localhost:9899/ws/file?wsdl –p com.ibm.download.client


Figure 13. File Client Stub Generation
File Client Stub Generation

[This will generate the stubs for the Client to interface with the methods and factory of FileDownload web service].

Developing File Client in Eclipse

  1. Create a package named 'com.ibm.download.client' inside the JAXWSClient project created above as shown in Figure 14.

Figure 14. Creating package for File client
Creating package for File client
  1. Now Copy and paste the stubs generated above in the 'com.ibm.download.client' package.
  2. Create a class named FileClient.java inside com.ibm.download.client package

Listing 6. FileClient.java for File Download Service

package com.ibm.download.client;
import java.io.*;
import java.net.URL;
import javax.xml.namespace.QName;
import javax.xml.ws.BindingProvider;
import javax.xml.ws.Service;
import javax.xml.ws.soap.MTOMFeature;
import javax.xml.ws.soap.SOAPBinding;
import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import com.ibm.ws.download.FileServer;
 
public class FileClient{
public static void main(String[] args) throws Exception {
URL url = new URL("http://localhost:9899/ws/file?wsdl");
QName qname = new QName("http://ws.download.ibm.com/", "FileServerImplService");
Service service = Service.create(url, qname);
FileServer fileServer = service.getPort(FileServer.class);
 
DataHandler dh = fileServer.downloadPdf("test.pdf");

/*Location for downloading and storing in client’s machine*/

FileOutputStream outputStream = new FileOutputStream("E:/test.pdf");
dh.writeTo(outputStream);
outputStream.flush();
 System.out.println(" Download Successful!");
     }
 }

You still might get a type mis-match error in , this might be because the generated stub 'FileServer.java' has been having a 'byte[]' variable instead of having a 'DataHandler' variable. Change the byte[] to DataHander to resolve this problem. You should also import 'javax.activation.DataHandler' in it. See Figure 15.


Figure 15. File Server Stub modification
File Server Stub modification
  1. Select FileClient Run As > Java Application.

(You will see Download Successful! In the console and a File name test.pdf is downloaded from the web service and stored in clients Location).


Figure 16. File Client Output
File Client Output

Example III – SAAJ client invoke Product Catalog web service

This is a very simple example of a SAAJ(SOAP API FOR JAVA) client that will be developed to access the Product Catalog web service developed in Part 1 of these tutorial series using Axis2 with contract First approach.

Developing SAAJ Client for Product Catalog Service

  1. Create a package named 'com.ibm.saaj.client' inside the JAXWSClient Project created above as shown below in figure 17.

Figure 17. Creating package for Saaj Client
Creating package for Saaj Client
  1. Create a class named SaajClient.java inside 'com.ibm.saaj.client' package. See the listing 7 below how to invoke the Product Catalog service

Listing 7. SaajClient.java for invoking Product Catalog web service
       
package com.ibm.saaj.client;
import java.io.IOException;
import javax.xml.soap.MessageFactory;
import javax.xml.soap.SOAPBody;
import javax.xml.soap.SOAPConnection;
import javax.xml.soap.SOAPConnectionFactory;
import javax.xml.soap.SOAPElement;
import javax.xml.soap.SOAPEnvelope;
import javax.xml.soap.SOAPMessage;
import javax.xml.soap.SOAPPart;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.stream.StreamResult;

public class SaajClient {

// Method for creating the SOAP Request
         
private static SOAPMessage createSOAPRequest() throws Exception
{
 MessageFactory messageFactory = MessageFactory.newInstance();
 SOAPMessage soapMessage = messageFactory.createMessage();
 SOAPPart soapPart = soapMessage.getSOAPPart();
         
 //Construct SOAP Request Message:
                
 // SOAP Envelope

SOAPEnvelope envelope = soapPart.getEnvelope();
envelope.addNamespaceDeclaration("rt", "http://contract.axis2.ibm.com");

// SOAP Body
               
 SOAPBody soapBody = envelope.getBody();
 SOAPElement soapBodyElem = soapBody.addChildElement("getProductName", "rt");
 SOAPElement soapBodyElem1 = soapBodyElem.addChildElement("productNumber", "rt");
 soapBodyElem1.addTextNode("1");
 soapMessage.saveChanges();

  // Check the input

 System.out.println("Request SOAP Message for Product web service");
 soapMessage.writeTo(System.out);
 System.out.println();
 return soapMessage;
        }

// Method for receiving the SOAP Response
         
private static void printSOAPResponse(SOAPMessage soapResponse) throws Exception
    {
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
Source sourceContent = soapResponse.getSOAPPart().getContent();
System.out.println("\nResponse SOAP Message from Product web service : ");
StreamResult result = new StreamResult(System.out);
transformer.transform(sourceContent, result);
        }

 //Starting point for SaajClient
       
 public static void main(String args[])
       {
 try
       {

// Create SOAP Connection

SOAPConnectionFactory soapConnectionFactory = SOAPConnectionFactory.newInstance();
SOAPConnection soapConnection = soapConnectionFactory.createConnection();

//Sending SOAP Message to SOAP Server i.e, Product Catalog service

String url = "http://localhost:8080/axis2/services/Product?wsdl";
SOAPMessage soapResponse = soapConnection.call(createSOAPRequest(), url);
                        
 // Processing the SOAP Response
 
 printSOAPResponse(soapResponse);
 soapConnection.close();
       }
catch (Exception e)
        {
System.err.println("Error occurred while sending SOAP Request to Server");
       e.printStackTrace();
        }
 }
}

  1. Now select SaajClient.java, Run As > Java Application. [Make Sure your Product Catalog web service is running in Tomcat].

(You will see the following Soap Request and Soap Response in the console for the Product catalog Web Service).

Request SOAP Message for Product web service:

          
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:rt="http://contract.axis2.ibm.com">
<SOAP-ENV:Header/>
<SOAP-ENV:Body>
<rt:getProductName><rt:productNumber>1</rt:productNumber>
</rt:getProductName></SOAP-ENV:Body></SOAP-ENV:Envelope>

Response SOAP Message from Product web service:

        
<?xml version="1.0" encoding="UTF-8"?><soapenv:Envelope
xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
<soapenv:Body><ns1:getProductNameResponse
xmlns:ns1="http://contract.axis2.ibm.com">
<ns1:return>Colgate</ns1:return>
</ns1:getProductNameResponse></soapenv:Body>
</soapenv:Envelope>

3 of 7 | Previous | Next

Comments



Help: Update or add to My dW interests

What's this?

This little timesaver lets you update your My developerWorks profile with just one click! The general subject of this content (AIX and UNIX, Information Management, Lotus, Rational, Tivoli, WebSphere, Java, Linux, Open source, SOA and Web services, Web development, or XML) will be added to the interests section of your profile, if it's not there already. You only need to be logged in to My developerWorks.

And what's the point of adding your interests to your profile? That's how you find other users with the same interests as yours, and see what they're reading and contributing to the community. Your interests also help us recommend relevant developerWorks content to you.

View your My developerWorks profile

Return from help

Help: Remove from My dW interests

What's this?

Removing this interest does not alter your profile, but rather removes this piece of content from a list of all content for which you've indicated interest. In a future enhancement to My developerWorks, you'll be able to see a record of that content.

View your My developerWorks profile

Return from help

static.content.url=http://www.ibm.com/developerworks/js/artrating/
SITE_ID=1
Zone=SOA and web services
ArticleID=680502
TutorialTitle=Developing web services, Part 2: Developing file download web service with JAX-WS.
publish-date=06152011
author1-email=kuntalganguly86@gmail.com
author1-email-cc=
author2-email=partha.ext@gmail.com
author2-email-cc=

Tags

Help
Use the search field to find all types of content in My developerWorks with that tag.

Use the slider bar to see more or fewer tags.

Popular tags shows the top tags for this particular content zone (for example, Java technology, Linux, WebSphere).

My tags shows your tags for this particular content zone (for example, Java technology, Linux, WebSphere).

Use the search field to find all types of content in My developerWorks with that tag. Popular tags shows the top tags for this particular content zone (for example, Java technology, Linux, WebSphere). My tags shows your tags for this particular content zone (for example, Java technology, Linux, WebSphere).