Advertisment

Web Services Exposed

author-image
PCQ Bureau
New Update

For a long time, there's been a lot of noise about web services and service

oriented architecture. These have been two buzzwords that just about every large

software vendor is talking about and promoting. Unfortunately, the number of

successful deployments of either of these is fairly limited in the country. This

is possibly because most people are still not very clear about the concepts

behind web services and service oriented architecture. Even if they understand

the technology, they face a roadblock on implementing it. That's why, this time,

we decided to let you experience the best of both worlds. We've broken this

story into two parts. The first part explains what web services and service

oriented architecture are all about, in simple terms, and with examples. The

second part takes you through the actual steps to follow for publishing a web

service using a variety of tools. This is also more in tune with the spirit of

web services. They're supposed to help an organization combine the business

logic with technology to truly leverage IT for better business. We'll also give

you both business and technology perspectives to web services, so that you can

leverage them better.

Advertisment

Having said that, let's now try to understand what web services are really

all about. For this, it's important to understand how the IT setups have evolved

in every organization. The IT setup in an organization isn't built over night.

It takes many years of hard work. Unfortunately, as it's come up over many

years, it has many heterogeneous systems and applications. As long as these

systems and applications work independently, they're fine, but the world is not

so simple. There are many times when it's critical that different systems talk

to each other. To take an example, a bank has many different applications for

its various functions, like loans, deposits, credit cards, ATM, etc. Now suppose

that the bank needed to find out the credit rating of a customer before offering

him/her a loan. The bank would obviously avoid giving a loan to a customer with

poor credit rating. In this case, the loan application needs to pull out credit

rating data from the credit card application. As both applications support their

own proprietary methods of handling data, getting them to talk to each other

becomes a very difficult task. The field of Enterprise Application Integration,

or EAI deals with such challenges. It allows different applications built on

completely different applications to talk to each other. For a long time, this

job was done by technologies like CORBA, DCOM, etc. Anybody who's worked with

these technologies will tell you how difficult it is to use them. That's where

web services come into the picture.

Understanding web services



A web service would allow both the loan and credit card application to talk

to each other, irrespective of which platform they're running on. It would do it

using a set of open standards. Today, the most widely accepted web services

standards are from W3C. So basically, what happens is that the credit card

application exposes its customer credit rating data as a web service. As this is

based on open standards, anybody a developer can use it to integrate it with the

loan application. Not only that, but other applications can also use this web

service. So essentially, the organization has just developed reusable code. This

saves a lot time, money, and effort.

Advertisment

Let's take another example. Suppose there's a manufacturing firm that's

running an ERP package. This ERP package maintains the inventory levels of the

organization, among other things. What if the organization wanted a way to

inform its suppliers about shortage of raw materials the moment it happens? One

way would be to allow the suppliers to access the ERP system directly to pull

out this information. This however, would be a major security risk as you would

also be exposing company confidential information to them. The other is to

figure out which supply chain management package is each supplier running and

then try to integrate them with your ERP. This would prove to be a mammoth task,

especially if different suppliers are running different SCM software. The best

way out is to expose your inventory level data as a web service. This standard

information can then be -picked up by all your suppliers and integrated with

their SCM applications. This example can be taken in another way. Suppose that

your organization's top management wanted to find out critical information from

the ERP system no matter where they are.

The biggest benefit of doing this is that you've just saved yourself the cost

of recreating software every time you need to do application integration. For

organizations who are already overwhelmed with hundreds of applications, this

can be a real life saver. Once a web service has been created, it can be used by

any other application.

Understanding SOA



A services oriented architecture is an application that's been built by

taking data from multiple web services. It's a complete shift from the

traditional way of developing applications and therefore requires a different

level of thinking. In fact, if you look around, you'll find examples of SOA all

around you. If you have a DVD player, then it will accept any DVD movie you want

to watch. That's because the formats and standards for both the DVD and player

have been defined. It's not as if you need a different player for every DVD you

buy. Unfortunately, in the traditional software applications, tight binding

takes place making them inflexible. In the SOA world however, there's loose

coupling between different applications. It doesn't matter which platform,

software or hardware is the application running on. As long as it's able to

expose a web service, it can be integrated with other applications.

Advertisment

The challenge now is to find out what kind of web services do you really need

to expose? Let's go back to our ERP example. Suppose you wanted your management

to know about significant variations in any of the data provided by the ERP

system. For instance, the moment there's a drop in production, you want your

production floor manager to know. The moment there's a huge drop in sales target

achievement, your sales director needs to know. The moment there's a major

shortfall in collections, you'd like your commercial director to know. Further

still, you want them to find out about this no matter where they are and on the

device they're using. If it's a cellphone, then they should know via SMS. If

they're using a smartphone or PDA, then they should be informed by email. If the

managers receive this kind of critical data on time, then it can really prove to

be beneficial for the business. All this can happen if the ERP system can expose

this data as standard web services. This data can then be fed to a unified

communications platform to deliver the right information to the right person at

the right time. Such kinds of solutions have started emerging. Avaya for

instance, has tied up with SAP to offer this kind of functionality. Similarly,

there are many other successful examples that are available online of SOA and

web services. An airline exposing its reservation system as web services for

travel agents for instance. Likewise, a bank exposing its key customer names and

telephone numbers to a call center, whom its outsourced some work to. The call

center can then integrate this web service with its own CRM application easily.

Likewise, there can be hundreds of examples where SOA can prove beneficial. It

ends where your imagination does.

The critical requirement for SOA and web services to be successful is that

organizations must be in a position to expose certain parts of their

applications as web services for others to use. For that, they must invest in

certain technologies. Unless this investment shows concrete returns, it will not

happen. In the pages to follow, we've given some examples of how to publish web

services on various platforms, which include WebSphere, ASP.Net, and Java.

Anil Chopra, Rahul Sah, Sanjay Majumder, Vinod Unny

Advertisment

Web Services on ASP.NET

Web services have become an integral part of the development world these

days. Thanks to the platform agnostic nature as well as standardized document

format (XML) and transport mechanism (HTTP), it has become a staple requirement

for the SOA model. In this article we shall examine how you can publish data

used in enterprises as a Web service using ASP.NET and then consume it from any

other application that understands Web services as well.

So let's define what we're going to do in this. In our fictitious

organization we wish to have a set of Web services that will provide a list of

current employees to any application requesting it as well as doing other jobs

with this. Assume we have tables (A and B) stored in an enterprise level

database.

Advertisment

Let's first create a Web service that lists out the details of the employees.

For this, fire up Visual Studio 2005 and select File>New Website>ASP.NET Web

Application>Visual C#. Choose a location for creating the site. Once the site is

created, delete the Default.aspx file and right click the solution name and

select 'Add new item...'. In the dialog box select Web service and give it the

name 'EmployeeService'. ASP.NET will by default give all Web services an

extension of 'asmx.' Once the template is created, add the following two lines

of code at the top.

using System.Data;

using System.Data.SqlClient;

Advertisment

Now, add a new function to the service as follows:

public DataSet GetEmployeeList()

Advertisment

{

SqlConnection cn = new SqlConnection(" String>");

String SQL = "select * from tblEmployees";

SqlDataAdapter da = new SqlDataAdapter(SQL, cn);

DataSet ds = new DataSet();

da.Fill(ds);

return (ds);

}



A



tblEmployees

EmployeeID Int
EmployeeName nVarChar
EmployeeLevel Int



B



tblSalaryBonus

EmployeeLevel Int
BonusPercent Float

Replace the with the connection string to your database. This

simple method returns a list of all the employees in the table using a Web

service. You can even test it out by running the code and viewing the XML

results in a browser. Let's also add another function to this Web service that

calculates the final salary of an employee given a set of inputs-the ID of the

employee as well as the salary total so far.



C


Control

Name

Text
Listbox lstEmployees
Label Employees List
Label Basic
Label HRA
Textbox txtBasic
Textbox txtHRA
Button Calculate Salary
Label txtSalary

public String GetFinalSalary(Int16 EmployeeID,

Single SalaryTotal)

{

SqlConnection cn = new SqlConnection(" String>");

String SQL = String.Format("select

{0}*(1+BonusPercent/100) from tblSalaryBonus, tblEmployees where

tblSalaryBonus.EmployeeLevel=tblEmployees.EmployeeLevel

and EmployeeID={1}", SalaryTotal, EmployeeID);

SqlCommand cmd = new SqlCommand(SQL, cn);

cn.Open();

String sal =

Convert.ToString(cmd.ExecuteScalar());

return sal;

}

You can again test this out by running the Web service and viewing the

results in the browser as XML. This time you will also need to enter the

employee ID and the total salary.

Publishing Web Services on IBM WebSphere

IBM WebSphere is an application server that can publish Java applications as

a Web service. Not every Java application is ported to a Web application

directly; only those which are developed with WS-l compliance can be deployed as

a Web service. This compliance is followed by developer to make the applications

interpretable such that they can be deployed as a Web service in any application

server. Here we will take a look on how you can port Java applications as a Web

service on IBM WebSphere 6.1, and will also show how you can use hosted Web

service in your standalone applications. For this we used a sample application

'WS-1 complaint' which takes string as an input and gets the data from the

address book. We used an HTTP bound Web service, which uses wsdl file. Client

avails the hosted Web service using this file.

While hosting a Java application on

WebSphere you need to select the modules you want to expose as a Web

service. Java app could have multiple modules

Publish Web service on WebSphere 6.1



Deploying Web service on IBM WebSphere is very easy and straightforward; all

you need is a Java Web service application packaged in a file '.ear', in our

case the application name was Webservice.ear. To deploy this, open WebSphere

administrative console and select Application>Install new application, on the

right windowpane it will start a wizard that deploys the application as a Web

service. On the first screen of the wizard you will be asked to upload the

application that you want to deploy. Here give the path of the application that

you want to host (.ear file) and click Next. On the subsequent screen tick

'deploy Web service' and next. You will see a summary of all the options that

you have selected while going through the wizard. Finally select Finish and this

starts the process of deployment. The status of deployment is visible on your

browser screen. Once the process is complete, the application is

ready to be published as a Web service. But the application will be listed as

'inactive.' To activate it select the application and click 'start.' Next you

need to configure the HTTP endpoint so that a client can avail the Web service

on HTTP. For this select Applications>Enterprise Application from left pane of

the administrative console and on the right windowpane you will be shown a list

of hosted applications. Select the application that you have hosted as a Web

service and a configuration sheet of selected applications will open. Now under

Web Services Properties select 'Provide HTTP endpoint URL information' and on

the configuration sheet select 'default HTTP URL prefix.' Mark the modules that

you want to enable into your hosted Web service, click OK and then the 'save'

hyperlink to save the final settings. Now click 'Publish WSDL file.' If you find

a file with .zip extension it means your Web service has been deployed

successfully. Finally check whether the client can access the hosted Web service

or not. For this open a Web browser and point it toward your hosted Web service.

For example http://localhost: 9080/

AddressBookW2JE/services/AddressBook will give you an output as mentioned below:

{http://addr.webservices.samples.websphere.ibm.com}AddressBook

Hi there, this is a Web service!

Using Web service in application



While using the services from the hosted Web service you have to give HTTP

source of the Web service that you want to use. At present all development IDEs

offer Web service features in their development platform. We used Visual Studio

2005 to create a small application and used a Web service to query information

from Address Book service. For this create new project and select Visual Basic

Windows Application. To use external Web service in your project go to project

menu and select 'Add Web reference,' this will open a window where you need to

add the URL of hosted Web service. In our case the URL for the Web service

hosted on WebSphere application was http://localhost: 9080/AddressBookW2JE/

services/AddressBook? wsdl. Once connected, it will show the name of the hosted

service and the method name, which was 'getAddressFromName (name As string) As

Address.' You can even use this method to get the address book information such

as city, phone, state no., state name and zip code. On the form-1 we used a data

grid and connected it with the Web reference as its data source. Then we used a

text box to get the input data and also used a button to do the query. On the

click method of the button we attached a code (the one given on forums.pcquest.com) to fetch Address Book data from the hosted Web service. On

running the project, fill the string into the textbox and click button. The code

attached will call the method 'getAddressFromName' from the Web service and get

data from Web service and display fetch data on the data grid. In the same way,

you can write a code in Java, C#, C++, etc and use external methods offered by

hosted Web services. There are a few free Web services available which offer

features like weather forecast, horoscope, stock info, etc as Web service so

that developers can use the offerings in application development.

Web Services on Apache Tomcat

Today corporate world is moving toward integrating existing systems in a

standard way to make different implementations interoperable. Web service is one

such method through which integration can be achieved. A Web service is a unit

of managed code that can be remotely invoked using HTTP, i.e., it can be

activated using HTTP requests. So, Web services allow you to expose the

functionality of your existing code over the network. Once it is exposed on the

network, other applications can use the functionality of your program.

In the following article we will demonstrate how to create and test a Web

service on Apache Tomcat server. We will be using Eclipse as the standard IDE to

create the Web service.

Suppose you want to have a Web service that can be used to help convert

temperature in Celsius to Fahrenheit and vice versa. For this demonstration,

we'll use a simple application providing the service. We will be creating a Web

project targeting Tomcat 5.5 server. To do this first create a Dynamic Web

Project named 'WebTest' in Eclipse through File >New>Other. In the subsequent

screen select Dynamic Web Project under section 'Web.' On the New Dynamic Web

Project screen, name the project as 'WebTest,' choose the Target Runtime as

Tomcat and then click Finish. We will now add a class having methods for

temperature conversions. The 'celsius ToFahrenheit' method will convert the

passed data to equivalent Fahrenheit figure while 'fahrenheitToCelsius' method

will do vice versa. To create the Java class select your project in Project

Explorer window and right click on Java Resources and select New> Class. On the

new class form mention the package as pcq.test and class name as 'Convert'. Then

save the project. Our Convert.java class will be as follows:

In Client Type select Java Proxy and drag

pointer to Test Client. Under configuration check for Server typess

package pcq.test;

public class Convert {

public float celsiusToFahrenheit (float

celsius)

{

return (celsius * 9 / 5)+32;

}

public float fahrenheitToCelsius (float

fahrenheit)

{

return (fahrenheit - 32)*5 /9;

}

}

Through Eclipse's Web service's explorer we

can test the client Web service. The TCP/IP monitor shows various request

and responses and their SOAP formats

Web Service Creation



For the 'WebTest' project we will have to create a Web service, which can be

done in Eclipse through File>New>Other and then selecting Web service. On the

Web service form pass the pcq.test.Convert in Service Implementation box. Under

Client Type option, bring the pointer to Test client. Here you will observe that

the default client project has been named as WebTestClient. Also select the

option 'Monitor the Web service.' Continue the wizard by clicking Next and then

Finish. The Web service wizard takes some time for organizing the end-to-end

generation, assembly, deployment, installation and execution of the Web service,

Web service client and sample JSPs. After completing this, the WSDL for the

WebTest Web service can be found under WebContent folder of the WebTest Web

service project. Now when you browse through your web projects, 'WebTest' and 'WebTestClient',

you can see that some JSP files and some Java files have been created in client

Web service. There are classes created under WebTestClient that have following

functions:

On completion of Web service wizard, WSDL

file, java and jsp files get created on client web project
  • ServiceLocater class: The locator class has information about

    the Web service, most importantly the address by which the service can be

    invoked (the HTTP address). The locator class is populated based on the

    content of the Web service's WSDL file.
  • Service class: The service endpoints' interface that is a

    local representation of a Web service. Through this interface appropriate

    methods will be invoked.
  • SoapBindingStub class: The stub that implements remote invocation

    methods defined by ConvertService interface.

To test the Web service give the following URL in your browser:






http://localhost:8080/WebTestClient/sampleConvertProxy/TestClient.jsp

This will open the JSP page that shows the two methods we had created for

conversion of temperature units. Select 'celsiusToFahrenheit' method and test

for value 0. Upon invoking the method on the Results frame you will have 32 as

the output. Similarly, test for the other methods also. This shows that the Web

service is up and running.

Alternatively, as Monitor Web service option was selected while configuring

Web service wizard a TCP/IP monitor appears, which is a powerful facility

showing the data that are actually being exchanged between the Web service and

its client, thus simplifying problem analysis with the Web services

implementation. The right-top pane on the monitor includes a list of

interactions (requests/responses) placed in a chronological order. When a

developer clicks on a particular interaction, the system displays the time of

request, how long it took for the system to respond (in milliseconds), and the

type of protocol that was used (in our case HTTP). The right-bottom pane

displays the SOAP response envelope. Whenever we invoke a particular Web

service, this pane is populated with the response of the server in the SOAP

(XML-based) format.

Finally a Web service on Tomcat is created and tested for a client

application.

Web Service on JBoss

JBoss is an open-source Java EE-based application server which supports EJB

3.0. This functionality has made development and deployment of Web services on
JBoss possible. In the following article we will show you how to develop and

deploy a Web service on a JBoss application server.

We would be using NetBeans IDE 5.5 which has support for JBoss. Also you

would be required to add the JBoss Application Server and provide JDK5 as the

Java platform for the IDE. Add JBoss Application Server by right clicking on the

'Servers' node in 'Runtime' window of the NetBeans IDE.

Creating Web service and its client



We would be creating a simple Web service which will be based on JAX-WS

specifications. Since NetBeans does not have support for JAX-WS based Web

services for JBoss, we will be creating them on Tomcat that comes bundled with

NetBeans. But before actually deploying the Web service, we would change the

runtime server to JBoss.

For creating a new Web service in NetBeans, select Web Application option

from the 'Project' pane and name the project as 'PcqMainWebApp'. Uncheck the

checkbox 'Use JDK 1.4' and also select the bundled Tomcat as the server. To

create a Web service right click on the 'PcqMainWebApp' project node and then

select New>Web Service. Name the service as 'PcqMainWS' and define package as 'pcq.labs.'

To visualize the Web service expand the project 'PcqMainWebApp' node and the Web

service can be seen under the project node. Now we will switch to JBoss runtime,

for this right click on 'PcqMainWebApp' project and select Properties option. In

the following window select 'Run' and change the server option to JBoss in the

Server drop-down list. Don't forget to uncheck the JAX-WS option under

'Libraries' tab because NetBeans IDE does not support for JBoss' JAX-WS API. In

order to add some code to the Web service, right click on 'PcqMainWS' and select

'Add Operation' option from the menu that pops up. Name the method as 'sayHello,'

then click on 'Add' button, and in the following screen define the parameter as

'name' and click 'OK.' So, now we have created a method 'sayHello' for the

service body. In the code change the return value as defined below:

public String operation(@WebParam(name =

"name") String name) {

return "Hello Reader - "+ name;

}

As per the JSR-181 specifications we need to specify the endpoints, so that

our service could be accessed from any external service. Hence, select 'web.xml'

from 'Configuration Files' node and open it in the 'Editor' window. Here define

the tag value as 'pcq.labs.PcqMainWS' and delete the tag. Now we are ready to deploy the project, right click on 'PcqMainWebApp' and

select 'Deploy Project' option. To view the WSDL code generated after deployment

of the service, right click on the 'PcqMainWS' and select Properties. Properties

will display the URL of the WSDL file which when opened in a browser would

display the WSDL code.

Next create another Web application project and name it as 'PcqClientApp.'

Then select 'PcqMainWebApp' through File>New File option, select 'Web Service

Client' option under the 'Web Services' category. In the following screen

specify the location of Web service's WSDL file by clicking on 'Browse' button.

Select 'PcqMainWS' and define the package name as 'pcq.labs.' Click 'Finish' and

now you can see the client under 'Web Service References' node in the Projects

window.

EJB modules for Web service



With NetBeans IDE we cannot deploy JAX-WS Web service on JBoss, but as JBoss

supports EJB 3.0 we will be creating EJB modules corresponding to the Web

services we just created.

While creating the project do

make sure that option 'Use JKD 1.4' is unchecked and bundled Tomcat is

selected as server

For this create a new project named 'PcqMainEjb' through File>New Project and

select 'EJB Module' option under Enterprise category. Add a new Web service to

this project and name it as 'PcqEjbWS'. Now add a method to the service as we

did before and it has to be same as the 'sayHello' method. Deploy the project

'PcqMainEjb' and the WSDL code of the deployed service can be viewed through the

following URL:





http://localhost:8080/PcqMainEjb/PcqEjbWS?wsdl

Next we would create client EJB module. Start a new EJB module project and

name it as 'PcqClientEjb,' right click on this project in 'Project' window and

select New>Web Service Client option. Click on the 'Next' button and with it a

'New Web Service Client' screen pops up. For specifying WSDL paths, click

'Browse' button for 'Project' option and then define 'PcqEjbWS' as the path. For

WSDL URL paste the above URL path and click 'Finish.

Testing Web service



After creating the Web services and their corresponding EJB modules, let us

test if our implementation is successful.

Select the 'PcqClientApp' under the Projects window and expand it to find

index.jsp file. Open the file in Editor and select the commented area in the

page's body starting from <%-- This example......

Now right click on the selected portion and select 'Web Service Client

Resourses' option and then opt for 'Call Web Service Operation'. In 'Select

Operation to Invoke' screen select 'PcqMain WebApp' and expand it to find

'sayHello' operation and click 'OK.' The code will be generated on the page's

body. Find string 'java. lang.String name= “” '. Now place a test name within

the quotes.

Finally and most importantly change the project's server to JBoss from

bundled Tomcat-selected earlier from project's 'Properties' window. Now select

the main Web application, i.e. 'PcqMainWebApp,' right click on the project's

name and select 'Run Project' option. Upon successful execution the resulting

test page will be displayed on the browser.

Advertisment