CPE5009 – Tutorial 1

searchcoilSoftware and s/w Development

Aug 15, 2012 (5 years and 2 months ago)

273 views

FIT5030



Tutorial
5


Writing a client for consuming a publicly available web service


This tutorial applies the concepts learnt from the lectures on SOAP and WSDL and
teaches you how to write a client application that consumes/uses a publicly available
we
b service with a published WSDL. You will write a client form the web service
provided for spell checking
CDYNE Corporation.

CDYNE develops, markets and supports
a comprehensive suite of data enhanceme
nt, data quality and data analysis web
services and business intelligence integration. The spell checker web service is one of
the web services provided by CDYNE. Note that the strength of an application based
on one or more web services depends on the ava
ilability and reliability of the web
services. However, CDYNE's
FAQ

points out that it has a "100% availability
objective" and that in the event of "natural disaster, act of terror, or other
catastroph
e, web service traffic is transferred to our secondary data center".


This tutorial is based on the exercises specified at:
http://www.netbeans.org/kb/60/websvc/client.html


Consuming the S
pell Checker Web Service

To use a web service over a network, which is called "consuming" a web service, you
need to create a web service client. For the creation of web service clients, NetBeans
IDE 6.1 and 6.0 provide a client creation facility, which is

the Web Service Client
wizard that generates code for looking up a web service. It also provides facilities for
developing the created web service client, a work area consisting of nodes in the
Projects window. These facilities are part of the standard Ne
tBeans IDE installation,
they're available straight out of the box and no plug
-
ins are needed.


Creating the Client

In this section, you use a wizard to generate Java objects from the web service's
WSDL file.

1.

Choose File > New Project (Ctrl
-
Shift
-
N). Under

Categories, choose Java Web
or Web. Under Projects, choose Web Application. Click Next. Name the project
SpellCheckService

and make sure that you specify an appropriate server as
your target server. (Refer to the "Getting Started" section for details.) Le
ave
all other options at default and click Finish.

2.

In the Projects window, right
-
click the
SpellCheckService

project node and
choose New > Other. In the New File wizard choose Web Services > Web
Service Client. In the Web Service Client wizard, specify th
e URL to the web
service:

http://ws.cdyne.com/SpellChecker/check.asmx?wsdl

If you are behind a firewall, you might need to specify a proxy server

otherwise the WSDL file cannot be downloaded. To
specify the proxy server,
click Proxy Settings in the Web Service Client wizard and set your proxy host
and port number.

3.

Leave the package name blank. In NetBeans IDE 6.1 and 6.5 you are not
allowed to specify a package name. By default the client class pa
ckage name
is taken from the WSDL. In this case is
com.cdyne.ws
.

4.

In NetBeans IDE 6.1 or 6.5, select JAX version JAX
-
WS (Some older services
require JAX
-
RPC clients). Click Finish.

5.

In the Projects window, within the Web Service References node, you see th
e
following:


The Projects window shows that a web service called 'check' has made the operation
'CheckTextBody' available to your applicatio
n. The 'CheckTextBody' operation checks
a string for spelling errors and returns data to be processed by the client. You will
use this operation throughout this tutorial.

In the Files window, within the
build

node, you see the following:


The Files window shows the client stubs that were generated by the JAX
-
WS Web
Service Client wizard.

Developing the Client

There are many ways to implement a web

service client. The web service's WSDL file
restricts the type of information that you can send to the web service, and it restricts
the type of information you receive in return. However, the WSDL file lays no
restrictions on
how
you pass the information

it needs, nor on
what

the user interface
consists of. The client implementation you build below consists of a JSP page which
allows the user to enter text to be checked and a servlet which passes the text to the
web service and then produces a report cont
aining the result.

Coding the JSP Page

Our JSP page will consist of a text area, where the user will enter text, and a button
for sending the text to the web service.

1.

In the Projects window, expand the Web Pages node of the
SpellCheckService

project and do
uble
-
click
index.jsp

so that it opens in
the Source Editor.

2.

Copy the following code and paste it over the
<body>

tags in
index.jsp
:

3.

<body>

4.


<form name="Test" method="post" action="SpellCheckServlet">

5.


<p>Enter the text you want to check:</p>

6.


<p
>

7.


<p><textarea rows="7" name="TextArea1" cols="40"
ID="Textarea1"></textarea></p>

8.


<p>

9.


<input type="submit" value="Spell Check"
name="spellcheckbutton">

10.


</form>


</body>

The previously listed code specifies that when the submit b
utton is clicked,
the content of the
textarea

is posted to a servlet called
SpellCheckServlet
.

Creating and Coding the Servlet

In this section you create a servlet that will interact with the web service. However,
the code that performs the interaction wi
ll be provided by the IDE. As a result, you
only need to deal with the business logic, that is, the preparation of the text to be
sent and the processing of the result.

1.

Right
-
click the
SpellCheckService

project node in the Projects window,
choose New > Oth
er and then choose Web > Servlet. Click Next. Name the
servlet
SpellCheckServlet

and type
clientservlet

in the Package drop
-
down. Click Next. Note that the URL mapping for this servlet is
/SpellCheckServlet
, as shown below:


Click Finish. The servlet opens in the Source Editor.


2.

Put your cursor inside the Source Editor, inside the
processRequest

method,
add some new lines right at the top of the method
.

3.

Right
-
click in the space that you created in the previous step, and choose
Web Service Client Resources > Call Web Service Operation. Click the
CheckTextBody

operation in the "Select Operation to Invoke" dialog box,as
shown below:


Click OK.

Note:

You can also drag and drop the operation node directly from the
Projects window into the editor, instead of calling up the dialog shown above.

A
t the top of the
processRequest

method you see a snippet of code that
invokes the web service, as shown below:

try { // Call Web Service Operation


com.cdyne.ws.Check service = new com.cdyne.ws.Check();


com.cdyne.ws.CheckSoap port = service.getC
heckSoap();


// TODO initialize WS operation arguments here


java.lang.String bodyText = "";


java.lang.String licenseKey = "";


// TODO process result here


com.cdyne.ws.DocumentSummary result =
port.checkTextBody(bodyText, licenseKey);



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

} catch (Exception ex) {


// TODO handle custom exceptions here

}

This method is all you need to invoke the operation on the web service. In
addition, the following lines of code are declared at the top of the
class:

@WebServiceRef(wsdlLocation =
"http://ws.cdyne.com/SpellChecker/check.asmx?WSDL")


private Check service;

4.

Replace the entire
processRequest

method with the code that follows. The
in
-
line comments throughout the code below explain the purpose

of each line.

protected void processRequest(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {


response.setContentType("text/html;charset=UTF
-
8");


PrintWriter out = response.getWriter();



try {




// Call Web Service Operation


String TextArea1 = request.getParameter("TextArea1");



com.cdyne.ws.Check service = new com.cdyne.ws.Check();


com.cdyne.ws.CheckSoap port = service.getCheckSoap();



// TODO initialize WS
operation arguments here


java.lang.String bodyText = TextArea1;


java.lang.String licenseKey = "0";



// TODO process result here


com.cdyne.ws.DocumentSummary doc = port.checkTextBody(bodyText,
licenseKey);


String allc
ontent = doc.getBody();



//From the retrieved document summary,


//identify the number of wrongly spelled words:


int no_of_mistakes = doc.getMisspelledWordCount();



//From the retrieved document summary,


//identify th
e array of wrongly spelled words:


List allwrongwords = doc.getMisspelledWord();



out.println("<html>");


out.println("<head>");



//Display the report's name as a title in the browser's
titlebar:


out.println("<title>Sp
ell Checker Report</title>");


out.println("</head>");


out.println("<body>");



//Display the report's name as a header within the body of the
report:


out.println("<h2><font color='red'>Spell Checker
Report</font></h2>");




//Display all the content (correct as well as incorrectly
spelled) between quotation marks:


out.println("<hr><b>Your text:</b>
\
"" + allcontent + "
\
"" +
"<p>");



//For every array of wrong words (one array per wrong word),


//id
entify the wrong word, the number of suggestions, and


//the array of suggestions. Then display the wrong word and the
number of suggestions and


//then, for the array of suggestions belonging to the current
wrong word, display each


/
/suggestion:


for (int i = 0; i < allwrongwords.size(); i++) {


String onewrongword = ((Words)
allwrongwords.get(i)).getWord();


int onewordsuggestioncount = ((Words)
allwrongwords.get(i)).getSuggestionCount();


List

allsuggestions = ((Words)
allwrongwords.get(i)).getSuggestions();


out.println("<hr><p><b>Wrong word:</b><font color='red'> " +
onewrongword + "</font>");


out.println("<p><b>" + onewordsuggestioncount + "
suggestions:</b><br>");



for (int k = 0; k < allsuggestions.size(); k++) {


String onesuggestion = (String) allsuggestions.get(k);


out.println(onesuggestion);


}


}



//Display a line after each array of wrong words:


out.println("<hr>");



//Summarize by providing the number of errors and display them:


out.println("<font color='red'><b>Summary:</b> " +
no_of_mistakes + " mistakes (");


for (int i = 0; i < allwrongwords.size(); i++) {



String onewrongword = ((Words)
allwrongwords.get(i)).getWord();


out.println(onewrongword);


}



out.println(").");


out.println("</font>");


out.println("</body>");


out.println("</html>");


out
.close();



} catch (Exception ex) {


System.out.println("exception" + ex);


out.println("exception" + ex);


}



out.println("</body>");


out.println("</html>");


out.close();

}

5.

You see a number of error bars and warning icons,

indicating classes that are
not found. To fix imports after pasting the code, either press Ctrl
-
I, or right
-
click anywhere, which opens a context menu, and select Fix Imports. (You
have a choice of List classes to import. Accept the default java.util.List
.) The
full list of imported classes follows:

import com.cdyne.ws.Check;

import com.cdyne.ws.Words;

import java.io.IOException;

import java.io.PrintWriter;

import java.util.List;

import javax.servlet.ServletException;

import javax.servlet.http.HttpServlet
;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;


import javax.xml.ws.WebServiceRef;


Note that error handling has not been dealt with in the previously listed code. See
Applying What You Have Learned

for details.


Deploying the Client

The IDE uses an Ant build script to build and run your application. The IDE generates
the build script b
ased on the options you entered when creating the project. You can
fine tune these options in the project's Project Properties dialog box (right
-
click the
project node in the Projects window and choose Properties).

1.

Right
-
click the project node and choose
Run. After a while, the application
deploys and displays the JSP page that you coded in the previous section.

2.

Enter some text, making sure that some of it is incorre
ctly spelled:


3.

Click Spell Check and see the result:




Applying What You Have Learned

Now that you have compl
eted your first web service client in the IDE, it is time to stretch your skills
and extend the application to be all that it was destined to be. Below are two suggested tasks to get
you started.

1.

Add error handling code to the servlet and

2.

rewrite the clie
nt so that the user can interact with the data returned from the web service.
For inspiration, see
the client implementation on the CDYNE site
. It looks like this: