Vous êtes sur la page 1sur 39

SERVICE ORIENTED ARCHITECTURE LAB SUBJECT CODE: IT2406

1. 2. 3. 4. 5. 6.

Develop at least 5 components such as Order Processing, Payment Processing, etc., using .NET component technology. Invoke .NET components as web services. Develop at least 5 components such as Order Processing, Payment Processing, etc., using EJB component technology. Develop a .NET client to access a J2EE web service. Develop a J2EE client to access a .NET web service. Invoke EJB components as web services.

I.

Develop at least 5 components such as Order Processing, Payment Processing, etc., using .NET component technology.

1. 2. 3. 4. 5.

Temperature Converter component Order Processing component Inventory component Result verification component Shipment Status verification component

1. Temparature Converter component Aim: Develop a component using .net for order processing. Procedure: Create a table Customer_Orders to store the order palced by Customers. Write a stored Procedure to store the orders in Customer_Orders Table Creating a Web Service under the IIS Root

Use Visual studio 2005/2008/2010 to create the new web service project as showb below

1. Open Visual Web Developer. 2. On the File menu, click New Web Site. 3. The New Web Site dialog box appears. 4. Under Visual Studio installed templates, click ASP.NET Web Service. 5. Click Browse. 6. Click Local IIS.

7. Click Default Web Site. 8. Click Create New Web Application. 9. Visual Web Developer creates a new IIS Web application. 10. Type the name TemperatureWebService. 11. Click Open. 12. The New Web Site dialog box appears, with the name of the new Web site in the rightmost Location list. The location includes the protocol (http://) and location (localhost). This indicates that you are working with a local IIS Web site. 13. In the Language list, click the programming language that you prefer to work in 14. Click OK. 15. Visual Web Developer creates the new Web service and opens a new class named Service, which is the default Web service.

To create the conversion methods


Add the following code inside the class, after the HelloWorld method:
[System.Web.Services.WebMethod()] public double FahrenheitToCelsius(double Fahrenheit) { return ((Fahrenheit - 32) * 5) / 9; } [System.Web.Services.WebMethod()] public double CelsiusToFahrenheit(double Celsius) { return ((Celsius * 9) / 5) + 32; }

After you have entered the functions, save the file.

To test the Web service 16. In Solution Explorer, click Convert.asmx, and then press CTRL+F5.

The Web service is invoked and a page appears in the browser that shows the methods that are exposed by the Web service. 17. Click CelsiusToFahrenheit, which invokes that method. A page appears that prompts you for parameter values for the CelsiusToFahrenheit method. 18. In the Celsius box, type 100, and then click Invoke. A new window appears that displays the XML that the Web service returns when the CelsiusToFahrenheit method is invoked. The value 212 appears in the XML. 19. Close the browser that contains the method results. 20. In the original browser, click Back to return to the list of methods. 21. Click FahrenheitToCelsius and test to make sure that the method is returning the results that you expect. If you type 212, the FahrenheitToCelsius method will return 100. 22. Close the browser.

2. Inventory component Aim: Develop a component using .net for Inventory component. Procedure:

Creating a web service


First let us create a new project in Visual Studio.NET for web service. Then add classes related to data access and write code for Web Service methods. 1. Start Visual studio.NET 2008/2005 2. Select File->New->Website. Select ASP.NET Web service as the type of the project and enter InventoryWS as the name of the project. Visual Studio provides Service.cs and Service.asmx files along with others. Delete these two files. 3. We add a new web service to the project using Website -> Add new item -> Web Service and enter name as InventoryService. Visual Studio creates InventoryService.aspx in root directory and InventoryService.cs in App_Code directory. We will write code for web service later. First let us create DAL to access database.

Creating Data Access Layer


Data Access Layer is set of classes used to access database. We centralize the entire data access to DAL. In this project we create two classes to represent data.

I am using PRODUCTS table, which is created by me in MSDB database of Sql Server Express Edition. You have to do the same in your system. Create PRODUCTS table with the following structure.
PRODID - int (Primary key) prodname - varchar (50) price - money qoh - int remarks - varchar (200) catcode - varchar (10)

Add some rows to PRODUCTS table.

Add a class to the project using Website-> Add New Item -> Class and enter name as Product. Here is the code for Product.cs.
using System; using System.Web.Services; using System.Runtime.Serialization; public class Product { private int prodid, qty;

private string name, remarks; private double price; public int Qty { get { return qty; } set { qty = value; } } public int Prodid { get { return prodid; } set { prodid = value; } } public string Remarks { get { return remarks; } set { remarks = value; } } public string Name { get { return name; } set { name = value; } } public double Price { get { return price; } set { price = value; } } }

Add connection string in connectionStrings section of web.config as follows.


<connectionStrings> <add name="msdbcs" connectionString="data source=localhost\sqlexpress;integrated security=true;Initial Catalog=msdb" providerName="System.Data.SqlClient" /> </connectionStrings >

Add Database.cs class and enter the following code.


using System.Web.Configuration; public class Database { public static string ConnectionString { get { return WebConfigurationManager.ConnectionStrings["msdbcs"].ConnectionString; } } }

Now create ProductDAL, which contains static methods for operations related to PRODUCTS table as follows.

using System; using System.Data; using System.Data.SqlClient; using System.Collections.Generic; public class ProductsDAL { public static List GetAllProducts() { SqlConnection con = new SqlConnection(Database.ConnectionString); con.Open(); SqlCommand cmd = new SqlCommand("select * from products", con); SqlDataReader dr = cmd.ExecuteReader(); List products = new List(); while (dr.Read()) { Product p = new Product(); p.Prodid = (int)dr["prodid"]; p.Name = dr["prodname"].ToString(); p.Remarks = dr["remarks"].ToString(); p.Qty = (int)dr["qoh"]; p.Price = Convert.ToDouble(dr["price"]); products.Add(p); } dr.Close(); con.Close(); return products; } public static Product GetProduct(int prodid) { SqlConnection con = new SqlConnection(Database.ConnectionString); con.Open(); SqlCommand cmd = new SqlCommand("select * from products where prodid = @prodid", con); cmd.Parameters.AddWithValue("@prodid", prodid); SqlDataReader dr = cmd.ExecuteReader(); if (dr.Read()) { Product p = new Product(); p.Prodid = (int) dr["prodid"]; p.Name = dr["prodname"].ToString(); p.Remarks = dr["remarks"].ToString(); p.Qty = (int) dr["qoh"]; p.Price = Convert.ToDouble (dr["price"]); return p; } else } } // product not found return null;

Using DAL in Web Service


Now let us write code in web service, which makes use of DAL. It is always better you separate data access code into DAL so that other parts of the application do not depend on data access. They access database through DAL.

Write the following code in InventoryService.cs.


using System; using System.Web.Services; using System.Collections.Generic; [WebService(Namespace = "http://www.srikanthtechnologies.com/")] [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] public class InventoryService : System.Web.Services.WebService { [WebMethod( Description ="Returns Details Of All Products")] public List GetAllProducts() { return ProductsDAL.GetAllProducts(); } [WebMethod(Description = "Returns Details Of A Single Product ")] public Product GetProduct(int prodid) { return ProductsDAL.GetProduct(prodid); } }

Now we are through our web service creation. Select web service - InventoryService.asmx and select View In Browser option from context menu (right click). From the page displayed in browser, click on methods and invoke them to test them.

Custom classes and WSDL


Click on Service Description link and you get WSDL for the web service. The following section in that is of interest.
<s:complexType name="ArrayOfProduct"> <s:sequence> <s:element minOccurs="0" maxOccurs="unbounded" name="Product" nillable="true" type="tns:Product" /> </s:sequence> </s:complexType> <s:complexType name="Product"> <s:sequence> <s:element minOccurs="1" maxOccurs="1" name="Qty" type="s:int" /> <s:element minOccurs="1" maxOccurs="1" name="Prodid" type="s:int" /> <s:element minOccurs="0" maxOccurs="1" name="Remarks" type="s:string" /> <s:element minOccurs="0" maxOccurs="1" name="Name" type="s:string" /> <s:element minOccurs="1" maxOccurs="1" name="Price" type="s:double" /> </s:sequence> </s:complexType>

II.

Invoke .NET components as web services. 1. 2. 3. 4. 5. Invoke Temperature Converter component Invoke Order Processing component Invoke Payment Processing component Invoke Result verification component Invoke Shipment Status verification

1. Invoke Temperature Converter component Aim: Develop a client application using .net to invoke temperature Converter component Procedure:

Adding the Web Service as a Component

the URL list, enter the following URL for the Web service, and then click Go: http://localhost/TemperatureWebService/Convert.asmx

When Visual Web Developer finds the Web service, information about the Web service appears in the Add Web References dialog box. one of the method links. The test page for the method appears. Add Reference. Visual Web Developer creates an App_WebReferences folder and adds a folder to it for the new Web reference. By default, Web references are assigned a namespace corresponding to their server name (in this case, localhost). Make a note of the name for the Web reference namespace. In the folder, Visual Web Developer adds a .wsdl file that references the Web service. It also adds supporting files, such as discovery (.disco and .discomap) files, that include information about where the Web service is located. You can now use the Web service. In this walkthrough, you will add controls to Default.aspx, and then program the controls to convert a specified temperature to both Fahrenheit and Celsius. When the page is running, it will look something like the following illustration. Temperature conversion page

To call the Web service methods


1. Open the Default.aspx page and switch to Design view. 2. From the Standard group in the Toolbox, drag the following controls onto the page and set their properties as indicated:

Control Textbox

Properties ID: TemperatureTextbox Text: (empty) ID: ConvertButton

Button Text: Convert ID: FahrenheitLabel Label Text: (empty) ID: CelsiusLabel Label Text: (empty) , add text to the page for captions. For this walkthrough, the layout of the page is not important. -click ConvertButton to create an event handler for its Click event. sure your event handler code matches the code in the following example.
protected void ConvertButton_Click(object sender, EventArgs e) { localhost.Convert wsConvert = new localhost.Convert(); double temperature = System.Convert.ToDouble(TemperatureTextbox.Text); FahrenheitLabel.Text = "Fahrenheit To Celsius = " + wsConvert.FahrenheitToCelsius(temperature).ToString(); CelsiusLabel.Text = "Celsius To Fahrenheit = " + wsConvert.CelsiusToFahrenheit(temperature).ToString(); }

CTRL+F5 to run the page. the text box, type a value, such as 100, and then click Convert. The page displays the result of converting the temperature value into both Fahrenheit and Celsius.

Debugging the Web Service


To start, you must configure the Web site that contains the Web service to enable debugging. 1. 2. 3. 4. 5. 6. 7. 8. On the File menu, click Open Web Site. Click Local IIS. Click TemperatureWebService, and then click Open. On the Website menu, click ASP.NET Configuration to open the Web Site Administration Tool. Click Application, and then click Application Configuration. Under Debugging and Tracing, click Configure debugging and tracing. Select the Enable debugging check box. The Web Site Administration Tool creates a Web.config file for the Web site and sets a configuration option to enable debugging.

8. Close the Web Site Administration Tool. You must now enable debugging for the Web site that uses the Web service.

To enable debugging in the Web site


1. Open the TemperatureWeb site. 2. On the Website menu, click ASP.NET Configuration to open the Web Site Administration Tool. 3. Click Application, click Application Configuration, under Debugging and Tracing, click Configure debugging and tracing, and then select the Enable debugging check box. 4. Close the Web Site Administration Tool. 5. In Solution Explorer, right-click Default.aspx, and then click View Code. 6. Visual Web Developer opens the code file for the page. 7. Position the pointer in the following line:
double temperature = System.Convert.ToDouble (TemperatureTextbox.Text);

Press F9 to set a breakpoint on the line.

Testing Debugging

Both the Web site and the Web service are configured for debugging, so that you can now try debugging. You will start in the Default.aspx page and step through the code until the code invokes the Web service. The debugger will switch to the Web service and continue stepping through the code.

1. Press F5 to run the Default.aspx page with debugging. The page appears in the browser. 2. In the box, type a value, such as 100, and then click Convert. Visual Web Developer starts running the code for the page, but stops and highlights the line with the breakpoint on it. 3. Press F11 to step to the next line. 4. Press F11 again. Because the next line invokes the Web service, the debugger steps into the Web service, stopping on the first line of the FahrenheitToCelsius method. 5. Continue pressing F11. The debugger steps through the rest of the method, and then returns to the calling page. If you continue stepping, the debugger will step back into the Web service and into the CelsiusToFahrenheit method. 6. Close the browser, which also closes the debugger.

III.

Develop at least 5 components such as Order Processing, Payment Processing, etc., using EJB component technology. 1. Calculator component 2. Temperature Converter component 3. Payment Processing component 4. Result verification component 5. Shipment Status verification component

1. Develop Calculator component Aim: Develop a component that performs few functions of calculator Procedure: Netbeans 6 provides vary easy and convenient way to develop web service. There are a few steps involved in developing a web service using it. These steps can be summarized as follows:
1. 2. 3. 4. 5. Create a web application project. Add web service to the project. Add operations to the web service. Implementing the web methodes. Deploy and test the web service.

Step 1. Create a web application project


i. ii. Start the Netbeans IDE; go to the New Project which is available under File menu. The New Project wizard opens. Select the web from categories options and web application from project section and then press the next button.

iii.

On the next screen mention the project name, select the project location. We can also mention the server name in which we want to deploy our web application as well we can change the default context path.

Here we mention the project name JSimpCalcWebService and keep the context path same as project name. We use GlassFish V2 application server for deployment.

iv.

Now, click the finish button.

Step 2. Add web service to the project


i. Right click on the project name in the Projects explorer window.

ii.

From the context menu options select the Web Service menu. A web service dialog opens.

iii.

Mention the web service name and the package name as mentioned in the image below, and then click the finish button.

In our example the web service name is JSimpCalcWebService and the package name is calc.ws.

Step 3. Add operations to the web service


After we add web service to our application, now it's time to add web service operation or WebMethod. We can do it in two possible ways one is through design mode and anather is through source mode. In our example we use design mode for creating skeleton of WebMethod in easiest way.

Figure Five: Add Operation To Web Service

i.

As we can see from highlighted section in the figure five we can add web service operations by clicking Add Operation button. It opens a Add Operation dialog box. Please refer to figure six.

ii. iii.

In the Add Operation dialog we must mention name (which is actually a WebMethod name). We can also enter parameter names and their types (these parameter are known as WebParam).

In the figure six we mention the WebMethod name as addition whose return type is java.lang.String and it takes two parameters (parameter1. and parameter2) of type double. Similarly we create other operations as well like subtraction, multiplication, division, power, maximum, minimum.

Step 4: Implementing the web methods


Once we finish step three, a basic structure of our web service should be ready. Then we switch from design mode to source mode as shown in figure seven to do rest of the implementation.

package calc.ws; import javax.jws.WebMethod; import javax.jws.WebParam; import javax.jws.WebService; import calc.util.NumberFormater; @WebService() public class JSimpCalcWebService { /** * Web service operation */ @WebMethod(operationName = "addition") public String addition(@WebParam(name = "parameter1") double parameter1, @WebParam(name = "parameter2") double parameter2) { //TODO write your implementation code here:

return NumberFormater.format((parameter1 + parameter2),0,6); } /** * Web service operation */ @WebMethod(operationName = "subtraction") public String subtraction(@WebParam(name = "parameter1") double parameter1, @WebParam(name = "parameter2") double parameter2) { //TODO write your implementation code here: return NumberFormater.format((parameter1 - parameter2),0,6); } /** * Web service operation */ @WebMethod(operationName = "multiplication") public String multiplication(@WebParam(name = "parameter1") double parameter1, @WebParam(name = "parameter2") double parameter2) { //TODO write your implementation code here: return NumberFormater.format((parameter1 * parameter2),0,6); } /** * Web service operation */ @WebMethod(operationName = "division") public String division(@WebParam(name = "parameter1") double parameter1, @WebParam(name = "parameter2") double parameter2) { //TODO write your implementation code here: return NumberFormater.format((parameter1 / parameter2),0,6); } /** * Web service operation */ @WebMethod(operationName = "power") public String power(@WebParam(name = "parameter1") double parameter1, @WebParam(name = "parameter2") double parameter2) { //TODO write your implementation code here: return NumberFormater.format(Math.pow(parameter1, parameter2),0,6); } /** * Web service operation */ @WebMethod(operationName = "maximum") public String maximum(@WebParam(name = "parameter1") double parameter1, @WebParam(name = "parameter2") double parameter2) { //TODO write your implementation code here: return NumberFormater.format(Math.max(parameter1, parameter2),0,6);

} /** * Web service operation */ @WebMethod(operationName = "minimum") public String minimum(@WebParam(name = "parameter1") double parameter1, @WebParam(name = "parameter2") double parameter2) { //TODO write your implementation code here: return NumberFormater.format(Math.min(parameter1, parameter2),0,6); } }

package calc.util; import java.text.NumberFormat; public class NumberFormater { public static String format(double number, int minFractionDigits, int maxFractionDigits) { NumberFormat format = NumberFormat.getInstance(); format.setMaximumFractionDigits(maxFractionDigits); format.setMinimumFractionDigits(minFractionDigits); return format.format(number); } }

Step 5. Deploy and test the web service


Now our web service is ready deployment and test. With Netbeans 6 it can achieved very with few steps. First make sure that the GlassFish server is running. To start the server we need to perform the following steps. i. ii. iii. iv. Go to Services explorer window. Expand the Servers node. Right click on the server name (in our case its GlassFish V2). A context menu pops up. Select Start from the menu options.

Now, as our server is running it's time to deploy the application and test the web service that we have developed. Netbeans does the deployment for us with few mouse clicks, mentioned as follows: i. ii. iii. iv. Go to Projects explorer window. Expand the Web Services node. Right click on the web services name (in our case its JSimpCalcWebService). A context menu pops up. Click the Test Web Service menu.

Figure Nine: Test Web Service

The above mentioned steps deploy the application and lunch the default browser in which the web service can be tested via SOAP request and response. Please refer to the figure ten for sample output. We can also view the WSDL (Web Services Description Language) file by clicking on the hyperlink.

Figure Ten: Test Web Service

Alternatively we can test the web service and view its WSDL document through our GlassFish application servers admin consol as shown in figure eleven.

Figure Eleven: Test Web Service via Admin Consol

Once we click on the View WSDL link we can view a XML file for describing our web service. The WSDL file should look like the figure twelve.

Figure Twelve: WSDL File

The URL shown at the address bar will require invoking the web service. We shall demonstrate its usage during creating of our web application using ASP.net.

IV.

Develop a .NET client to access a J2EE web service. 1. 2. 3. 4. 5. Invoke Calculator component Invoke Temperature component Payment Processing component Result verification component Shipment Status verification component

1. Develop a .net Application to Invoke J2EE calculator component Aim: Develop a .net application (Client) to access the J2EE component Calculator Procedure: Now, our web service is ready to get invoked from non-Java based development platform. In this article we develop a sample ASP.net based client. Using Visual Studio 2008 it can be achieved in few steps, which can be summarized as follows: 1. 2. 3. 4. Create ASP.net web site. Add web reference. Write code to invoke web service. Test web service client application.

Step 1. Create ASP.net web site


i. Start Visual Studio 2008; go to the New Web Site which is available under File menu.

Figure Thirteen: New Web Site Window

ii. iii. iv.

Select ASP.net Web Site. Select the folder in which we want to create the web site. In our case its
JSimpCalcWebServiceWebSite

Select the language Visual C# and click OK button.

Step 2. Add web reference


Now we need to mention the WSDL file in our web site. To add the web service reference we must perform the following steps: i. ii. iii. Go to Solution Explorer window. Right click on the project name (in our case its JSimpCalcWebServiceWebSite). A context menu pops up. Click the Add Web Reference menu. The Add Web Reference dialog opens.

Figure Fourteen: Add Web Reference Context Menu

iv.

Copy and paste the WSDL URL from our web browers address bar (refer to figure twelve) to Add Web Reference dialogs address bar and press go button (refer to figure fifteen).

Figure Fifteen: Add Web Reference Dialog

v.

We can see all the methods names of our web service. Give a name to the web reference (in this example its JSimpCalcWebService) and click the Add Reference button.

Step 3. Write code to invoke web service


Using C# we can very easily invoke the web service with few lines of code: i. ii. We first design an ASP.net page. The default fie name is Default.aspx (the source is available in zip file). Induce the web reference in to our code (i.e. Default.aspx.cs). For example:
using JSimpCalcWebServiceService;

iii.

Next, create the object of the web reference.


JSimpCalcWebServiceService.JSimpCalcWebServiceService proxy = new JSimpCalcWebServiceService.JSimpCalcWebServiceService();

iv.

Now, we can access the WebMethod like any other method call. For example:
proxy.addition (10, 20);

Figure Sixteen: Web Methods Invocation Code

V.

Develop a J2EE client to access a .NET web service. 1. 2. 3. 4. 5. To Invoke Inventory Component To Invoke Temperature Component To Invoke Payment Processing component To Invoke Result verification component To Invoke Shipment Status verification component

1. Develop a J2EE client to access .net Inventory component Aim: Develop a J2EE client program to access the .net web service for Inventory purpose Procedure: Product class is taken as complexType and its members are placed as sub elements. Collection of Products is taken as an ArrayOfProduct. When you need to access this web service from Java application, we create proxy in Java. Product element will become a class in Java and ArrayOfProduct becomes another class that contains a List of product objects. So, WSDL contains details about custom classes so that clients can generate these classes again on the client.

Creating Proxy in Java


Now, let us create a proxy in Java to access InventoryService Web Service. 1. Start NetBeans IDE 6.5. 2. Select File->New Project. Select Java in category and Java Application in projects. Click on Next. 3. Enter InventoryClient as the name of the application. Change name of the class in Create Main Class option to Client 4. Click on Finish. 5. Select InvenotryClient project in Projects window. Right click to invoke context menu. Select New->Other. Select Web service in categories and Web Service Client in File Types. 6. In the next window, select WSDL URL radio button (as shown below) and enter the URL at which InventoryService is running. Click on Finish. NetBeans creates required classes to access web service.

Write code in Java to call web service


Once proxy is created then we can write code to access web service methods from Java. In fact, NetBeans can do that for you. Follow the steps given below. 1. Open Client.java 2. Go into main function and click on right button. From context menu select Web Service Client Resources -> Call Web Service Operation... 3. A window pops up with operations in the web service (shown below).

Select GetProduct in InventoryServiceSoap12 section. NetBeans automatically writes code for you. Just assign product id 100 to prodid and change code regarding output, to complete the code.
try { // Call Web Service Operation com.srikanthtechnologies.InventoryService service = new com.srikanthtechnologies.InventoryService(); com.srikanthtechnologies.InventoryServiceSoap port = service.getInventoryServiceSoap12(); // TODO initialize WS operation arguments here int prodid = 100; // TODO process result here com.srikanthtechnologies.Product result = port.getProduct(prodid); System.out.println( result.getName()); } catch (Exception ex) { // TODO handle custom exceptions here }

Lines in bold are modified by me. The rest is provided by NetBeans. That's all you have to do to Call web service created in .NET from Java.

As you can see, NetBeans created a class Product for which information is provided in WSDL. Follow the same steps to call GetAllProducts method. Change the code as follows.
try { // Call Web Service Operation com.srikanthtechnologies.InventoryService service = new com.srikanthtechnologies.InventoryService(); com.srikanthtechnologies.InventoryServiceSoap port = service.getInventoryServiceSoap12(); // TODO process result here com.srikanthtechnologies.ArrayOfProduct result = port.getAllProducts(); List products = result.getProduct(); for(Product p : products) { System.out.println( p.getName() + " : " p.getPrice()); } } catch (Exception ex) { // TODO handle custom exceptions here } +

4. Now, run Client.java to see whether details of products are displayed from Java program.

VI.

Invoke EJB components as web services. 6. Temperature Converter component 7. Order Processing component 8. Payment Processing component 9. Result verification component 10. Shipment Status verification component

http://www.theserverside.com/news/1365614/Part-4-Web-Services-and-J2EE

Vous aimerez peut-être aussi