Creating and Using Web Services

57
1. Creating and Using Web Services 2. Purpose This OBE tutorial describes how to create and use Web services with Oracle JDeveloper 10g. 3. Topics The tutorial discusses the following: Overview Prerequisites Locating and Using an Existing Web Service Creating and Using a Modeled Web Service Creating and Using a PL/SQL Web Service Using the TCP Packet Monitor to Examine the Web Service Summary Time to complete 90 minutes 4. Viewing Screenshots Move your mouse over this icon to show all screenshots. You can also move your mouse over each individual icon to see only the screenshot associated with it. 5. Overview Web services are discrete reusable software components that can be incorporated into applications. They build upon the existing XML and HTTP protocols and use the following standards: WSDL (Web Services Description Language) SOAP (Simple Object Access Protocol) UDDI (Universal Description, Discovery, and Integration)

description

Creating and Using Web Services

Transcript of Creating and Using Web Services

1. Creating and Using Web Services2. PurposeThis OBE tutorial describes how to create and use Web services with Oracle JDeveloper 10g.3. TopicsThe tutorial discusses the following:Overview

Prerequisites

Locating and Using an Existing Web Service

Creating and Using a Modeled Web Service

Creating and Using a PL/SQL Web Service

Using the TCP Packet Monitor to Examine the Web Service

Summary

Time to complete90 minutes4. Viewing ScreenshotsMove your mouse over this icon to show all screenshots. You can also move your mouse over each individual icon to see only the screenshot associated with it.

5. OverviewWeb services are discrete reusable software components that can be incorporated into applications. They build upon the existing XML and HTTP protocols and use the following standards:WSDL (Web Services Description Language)

SOAP (Simple Object Access Protocol)

UDDI (Universal Description, Discovery, and Integration)

JDeveloper provides many features to help you to create and deploy Web services and to find existing Web services to use in your applications. This tutorial shows you how to use some of JDeveloper's Web service tools.Back to Topic List6. ScenarioIn developing Web applications with JDeveloper, you often find a need for functions such as stock quotes or currency conversion. You know that Web services are available to incorporate these functions as components in your application, but you are not sure where to find such services or how to use them. In addition to availing yourself of existing services, you would like to develop Web components that you deploy as Web services for such common functions as accessing employee information by supplying the employee identification number.7. PrerequisitesBack to Topic ListIn order for this lesson to work successfully, you will need to have performed the following:1.Install Oracle JDeveloper 10g.

2.Install the sample schemas and create a connection to the HR or HR8 schema to use in this lesson. SeeInstalling the Sample Schemas and Establishing a Database Connection. For this tutorial, name the connectionHRconn; do not use an underscore in the connection name

3.You must have SQL*Plus installed on your local machine.

4.To use the instance of OC4J that comes with JDeveloper as an external server on which to deploy the Web services you create, you need to install and start OC4J:To install, from the Command Prompt navigate to/j2ee/home, whereis the folder in which you installed JDeveloper, then issue the following command:start java -jar oc4j.jar -installWhen prompted, enter anadminpassword, such aswelcome.To start OC4J, issue the command:start java -jar oc4j.jarKeep this window open (you can minimize it if desired).

5.You need to create an application server connection to the instance of OC4J that you installed and started, so that you can deploy Web services to it. To create such a connection:

Open the Connections Navigator, right-click the Application Server node, and chooseNewApplication Server Connectionfrom the context menu to launch the Create New Application Server Connection wizard.

If the Welcome page is displayed, clickNextto display the Type page.

Change the Connection Name fromAppServerConnection1toWSConnectionand leave the connection type asStandalone OC4J. ClickNext.

On the Authentication Page, leave theUsernameas admin, and enter thePasswordyou used when you installed OC4J. SelectDeploy Password, and clickNextto display the Connection page.

Leave the defaults, and clickNextto display the Test page.

ClickTest Connection. The results of testing are shown in the test window. If the test does not succeed, go back and check that you have entered the correct password.If you are working with DHCP, you may find that the connection works only if you use your IP number as part of the URL on the Connection page.When the test succeeds, clickFinish.

6.You need to create a workspace to hold the projects you will create as you work through this lesson. To create a workspace and project:

In the Applications Navigator, right-click Applications and chooseNew Application Workspacefrom the context menu.

In the Create Application Workspace dialog, rename the applicationApplication1toWebServiceOBE. Notice that the directory name changes to be the same.

From the list of available application templates, selectNo Template [All Technologies], then clickOK. TheWebServiceOBEapplication is created and displayed as a node in the navigator, and a project is automatically created.

7.You must have access to the Internet to locate Web services in a public UDDI registry. If you are behind a firewall, you must change JDeveloper's proxy settings so that it can access the Internet through the firewall. To change the proxy settings:

ChooseTools >Preferencesto open the Preferences dialog.

SelectWeb Browser\Proxyfrom the list, and selectUse HTTP Proxy Server. Enter appropriate values for the host name and port number.

8. Locating and Using an Existing Web ServiceBack to Topic ListThis topic tells you how to locate and use a Web service that is available on the Internet. You will learn how to use the Find Web Services wizard in JDeveloper to locate a Web service, then use the Create Web Service Stub/Skeleton wizard to create a stub to the service. This topic covers the following subtopics:Browsing a UDDI Registry

Creating a Stub to Use the Web Service

9. Browsing a UDDI RegistryFirst you will rename the project so that your work is separate from your work in the other Web service topics. Then you will use the Find Web Service wizard to locate a Web service.Back to List1.Expand theWebServiceOBEnode in the Applications Navigator and selectProject.

2.ChooseFile > Rename, and in the Rename dialog, change the file name fromProject.jprtoFindWebService.jprand clickSave.

3.In the Connections Navigator, expand theUDDI Registryfolder. JDeveloper comes with connections to three public UDDI registries.

4.Select theIBM Public UDDI v2 Registry, right-click and chooseFind Web Servicesfrom the context menu to launch the Find Web Services wizard.

5.ClickNexton the Welcome page to begin.

6.In the Search Kind page, make sure thatNameis selected and clickNextto display the Search Criteria page.

You can search by category, but when you are just trying out the UDDI browser, it can be easier to get a result if you search by name.

7.In the Search Criteria page, you specify the criteria to use in searching for tModels. A tModel is a technical specification that enables a client to determine if the Web service complies with a particular behavior or programming interface.InSearch For, enter a search string such asab%(% is a wild card). ClickNext. This searches the UDDI registry for tModels that start with the letters "ab".

If you get an error at this stage, make sure that you have a connection to the Internet and that JDeveloper's proxy settings are correct. For more information, refer to Step 7 ofPrerequisites.

8.The tModels that fit the search criteria are displayed. Those that use a WSDL have a tick in theIs WSDL?column. Select one of the tModels that has a tick, and clickNextto display the Service page. (You do not have to wait for all of the descriptions to load before selecting the one you want and clickingNext.) This example usesAbove All Software Test Service.

9.The Service page of the wizard shows the services that implement the tModel you selected.It is possible that you will get a message at this point, saying that no service implements the tModel you selected, in which case clickBackand select another service. From the Service page, clickNextto display the Finish page.

10.The wizard displays a report of the Web service you have found. ClickFinishto display the Find Web Services wizard dialog.

11.LeaveGeneratestub code into project FindWebService.jpr to invoke this serviceselected, and clickOK. The Web Service Stub/Skeleton wizard is launched.

IfGeneratestub code to invoke this serviceis not displayed on the final dialog, it means that although the UDDI browser has located a Web service that appears to meet your requirements, it has failed the validation that the Web Services Stub/Skeleton wizard performs. There are a number of reasons why this can happen.The most obvious reason is that although the Web service is registered in the UDDI registry, there is no WSDL at the location specified. If this happens, click Cancel on the dialog, and use the Back button in the wizard to find another Web service.Another reason could be that the proxy settings in the browser do not match the proxy settings in JDeveloper.

Now that you have used JDeveloper's UDDI browser functions to locate a Web service, you can use the Web Service Stub/Skeleton wizard to create a stub to that service.10. Creating a Stub to Use the Web ServiceBack to ListThe next step is to use the Web Service Stub/Skeleton wizard to create a proxy or stub to the service. To create a stub, perform the following:1.In the Generate Web Services Stub/Skeleton wizard, if the Welcome page is displayed, clickNextto display the Select Web Service Description page.

2.The URL of the Web service description (the WSDL Document URL) is already entered. Do not change it. LeaveGenerateClient-Side Stubsselected, and selectGenerateMain Method into Stub. This will make it easy for you to test your stub. ClickNextto display the Select Stubs/Skeletons to Generate page.

3.Click on the Web service (the second line in the pane identified by). TheServiceNameis displayed, and defaults are shown for thePackageand theClass Namefor the generated stub. Accept the defaults, and clickFinish.

The business providing the service is added to the Connections Navigator under the UDDI registry you used, and the stub to implement the service, which is calledStub.java, is added to the Applications Navigator under theFindWebServiceproject. Depending on the Web service you chose, JDeveloper may add other Java classes, which are JavaBeans to implement any complex types that it finds in the Web service.

4.In the Applications Navigator, double-click the stubStub.javato open it in the Code Editor, and scroll down until you find

// Add your own code here.Immediately below that line, add some code that will return a value from the Web service. For example, look for a method in the stub that returns a String, then add the code:

System.out.println(stub.());

Then right-click the Code Editor and chooseMaketo make the stub.Note: Depending on the Web Service that you choose, you may receive a compilation error stating that the class UnknownType is not found. If you receive this error, add the following import statement to the stub and then recompile:import com.sun.corba.se.interceptor.UnknownType;Right-click the Code Editor again and chooseRunto run the stub. The stub connects to the Web service, and returns a value which is displayed in the log window. If the Log Window is not visible, chooseView >Log.

11. Creating and Using a Modeled Web ServiceBack to Topic ListThis topic shows you how to create a Web service starting off with a modeled Web service. In a development environment, modeling the service on a class diagram enables you to easily visualize the elements in your application.This topic covers the following subtopics:Modeling a Web Service

Running the Web Service in the Embedded Server

Testing the Web Service

12. Modeling a Web ServiceBack to ListFirst you will create a new project for your work, then you will create a class diagram, and finally you will create a Web service from a modeled Java class.1.With theWebServicesOBEselected in the Application Navigator, right-click and chooseNewfrom the context menu to display the New Gallery.

2.In theCategorieslist, selectGeneral, and then in theItemslist, selectEmpty Project, and clickOKto open the Create Project dialog.

3.Change the name of the project fromProject1toModelWebServiceand clickOK. The new project is created and displayed in the navigator.

4.With the projectModelWebServiceselected in the navigator, right-click and chooseNewto open the New Gallery.

5.In theGeneralcategory, selectDiagrams, and then in theItemslist, selectJava Class Diagram. ClickOKto open the Create Java Class Diagram dialog.

6.Accept the defaults, and clickOK. An empty class diagram opens in JDeveloper.

7.The Component Palette, located in the right section of the JDeveloper window, enables you to select diagram elements for different palettes. If the Component Palette is not visible, chooseView > Component Palette.Have a look at the list to see the other palettes that are available. For this subtopic you will be using the Java palette, so ensure that it is the selected palette.

8.ClickJava classin the Component Palette, then click on the class diagram. This creates a modeled Java class. Resize it so that it is comfortable to work with.

9.Click below the second line on the class, in the methods compartment, and type+ getDate() : String

10.Examine the Java class that has been created. If necessary in the navigator, expandModelWebService, thenApplication Sources, thenmypackage1and double-clickJavaClass1.java. This opens the Java class in the Code Editor. You can also open the code editor by double-clicking on the class in the class diagram.

11.Edit the class so that the method is:

public static String getDate(){return (new java.util.Date()).toString();}

12.Return to the class diagram by clicking theJava Class Diagram1tab above the Code Editor. Right-click the modeled class and chooseGenerate >Web Servicefrom the context menu to fast create a Web service from it.

13.The new modeled Web service is displayed on the diagram, and the Web service containerMyJavaClass1WSis displayed in the Application Navigator.

You now have a class diagram with both a modeled Java class and a modeled Web service, and from that you have generated the files needed to try out thegetDate()method as a Web service in JDeveloper's embedded OC4J server, as you will do in the next step, or in any instance of OC4J.13. Running the Web Service in the Embedded ServerBack to ListRunning the Web service in JDeveloper's embedded server is a simple procedure. To run the Web service, do the following:1.On the diagram, right-click the modeled Web service and chooseRun EmbeddedServerfrom the context menu.Alternatively, in the navigator, right-clickMyJavaClass1WSand chooseRunfrom the context menu.

2.The Web service is deployed to JDeveloper's embedded OC4J server and the progress is recorded in the log window.

14. Testing the Web ServiceBack to ListNow that you have created your Web service and have it running in JDeveloper's embedded server, you can create a sample Java client to test that the service works as expected.To create a sample Java client for a Web service stub, perform the following steps:1.In the navigator, right-click the Web service container,MyJavaClass1WSto invoke the context menu. Alternatively, you can right-click the Web service in the class diagram to invoke the context menu.SelectGenerateSample Java Clientfrom the context menu .This createsEmbeddedMyJavaClass1WSStub.javawhich is listed in the navigator. The Java class opens in the Code Editor.

2.Scroll down until you find:// Add your own code here.Immediately below that line, add:System.out.println("The date and time is " + stub.getDate());

3.Right-click in the Code Editor and chooseMaketo make the class.

4.Right-click again and chooseRunto run the class. The log window shows the current date and time which has been returned from the Web service.

If the log window shows an error at this point it is probably because the stub is not able to connect to the Web service running in the embedded OC4J server. This can happen if you are running DHCP.Go toTools >Preferencesand selectWeb Browser/Proxyto see the current settings. The list of proxy server exceptions includes 127.0.0.1 and localhost. However, if you look at the stub you have just generated, at the line starting "private String _endpoint", the actual IP address of your machine is used. The port is 8988, the port for the embedded OC4J server.To get the stub to work, you can do one of the following:Add your machine's IP address to the list of proxy server exceptions. Go toTools >Preferencesand selectWeb Browser/Proxy. Add your IP address to the end ofExceptions.orTurn off the proxy server in the dialog, but remember to turn it back on again for the next topic.

15. Creating and Using a PL/SQL Web ServiceBack to Topic ListIn this topic you learn to create a Web service based on program units in a PL/SQL package that is stored in an Oracle database.This topic covers the following subtopics:Creating the PL/SQL Package in the Database

Creating the PL/SQL Web Service

Deploying the PL/SQL Web Service

Creating a Stub to Use the Web Service

Creating the PL/SQL Package in the DatabaseBack to ListThis subtopic tells you how to create a package in the database that contains the program unit for which you will create a Web service.It assumes that you have already defined a database connection to the HR or HR8 user, as described inPrerequisites, and that you have named that connectionHRconn. You will not be able to complete one of the later steps in this tutorial if you use a connection name that contains an underscore.1.To create a new project, right-click theWebServiceOBEworkspace in the navigator and chooseNewProjectto open the New Gallery withProjectsselected in theCategorieslist.

2.ChooseEmpty Projectfrom theItemslist and clickOK.

3.In the Create Project dialog, changeProject1toPLSQLWebServiceand clickOK.

4.To create the package in the database, withPLSQLWebServiceselected in the Application Navigator, right-click and chooseNewto open the New Gallery.

5.In the Categories list, expandDatabase Tierand selectDatabase Files, then selectSQL Filein theItemslist. ClickOK.

6.In the Create SQL File dialog, change theFile Nametowsobe.sqland clickOK. The new empty file opens in the code editor.

7.Copy the code below and paste it into the code editor: Running this SQL file against the Human Resources schema in the database creates an object type called EMP_REC and a package calledEMP_FETCHER.REMREM Create object EMP_RECREMCREATE or REPLACE type EMP_REC as object(employee_id number(6),last_name varchar2(25),job_id varchar2(10),manager_id number(6),hire_date date,salary number(8,2),commission_pct number(2,2),department_id number(4));/show errors;REMREM EMP_FETCHER package specREMCREATE or REPLACE package EMP_FETCHER asFUNCTION get_emp(emp_no IN NUMBER) RETURN emp_rec;END;/show errors;REMREM EMP_FETCHER package bodyREMCREATE or REPLACE package body EMP_FETCHER asFUNCTION get_emp(emp_no IN NUMBER) RETURN emp_rec ISemp_found employees%rowtype;emp_rtn emp_rec;BEGINSELECT *INTO emp_foundFROM employeesWHERE employees.employee_id=emp_no;

emp_rtn := emp_rec(emp_found.employee_id,emp_found.last_name,emp_found.job_id,emp_found.manager_id,emp_found.hire_date,emp_found.salary,emp_found.commission_pct,emp_found.department_id);RETURN emp_rtn;END;END;/show errors;Click theSavebutton to save the SQL file.

8.Right-clickwsobe.sqlin the navigator, and chooseRun in SQL*Plus > HRconn. (This assumes that you have already defined a database connection to theHRorHR8user, as described inPrerequisites. The example uses HRconn for the name of that connection, but if you have used a different name, just select the connection that you defined.) Running this SQL file against the Human Resources schema in the database creates an object type calledEMP_RECand a package calledEMP_FETCHER.

If this is the first time you have run a file in SQL*Plus from JDeveloper, a dialog is displayed for you to enter the path to the SQL*Plus Executable. In the SQL*Plus Executable dialog, enter the path or browse to the location of the SQL*Plus executable on your machine.

When you clickOK, or if you have already defined the path to the SQL*Plus executable, an Oracle SQL*Plus window opens, and the script is run. You should see the following messages:Type created.No errors.Package created.No errors.Package body created.No errors.Typeexitto close the SQL*Plus window.

9.In the Connections Navigator, expand theDatabasenode. Expand the connectionHRconn, thenHRorHR8, thenPackagesto find the new package,EMP_FETCHER. It is this that you will use to create the Web service.

Creating the PL/SQL Web ServiceBack to ListIn this subtopic you create a Web service directly from the new package in the Human Resources schema. To create the PL/SQL Web service, perform the following steps:1.In the Connections Navigator, expand theHRconnnode, then theHRorHR8node, then thePackagesnode. Right-click theEMP_FETCHERpackage and choosePublish asWeb Serviceto launch the Create PL/SQL Web Service wizard.

2.If the Welcome page is displayed, review the information and clickNextto open the Database Connection and Package page.

3.Ensure that theTarget ProjectisWebServiceOBE.jws/PLSQLWebService.jpr.You cannot change the database connection and database package because you started the wizard from a specific database package. If you launched the wizard by selecting a project and choosing the wizard from the New Gallery, you would be able to select the database connection and the package, but you would not be able to change the project.Accept the defaults, and clickNextto open the Program Units to Publish page.

4.Select theFUNCTION GET_EMP(IN NUMBER) RETURN EMP_RECprogram unit, then clickNextto open the Endpoint page.

5.Accept the defaults, and clickNextand thenFinish.

JDeveloper connects to the database and creates the Web service. This may take a few seconds.

The generated Web service is listed in the Application Navigator, and the WSDL document is opened in JDeveloper's XML Editor.

JDeveloper uses JPublisher to translate from PL/SQL to Java, a process which generates several files such as Java classes and beans to act as a Java wrapper to the PL/SQL. The files that are generated are displayed in the Structure Pane when you select the Web service in the Application Navigator.

Deploying the PL/SQL Web ServiceBack to ListDeploying a J2EE Web service is a simple procedure. To deploy the Web service:1.In the Applications Navigator, right-click theWebServices.deployfile and chooseDeploytoand selectWSConnection. If WSConnection is not shown, see steps 4 and 5 ofPrerequisites.

The Web service is deployed to the external instance of OC4J and the progress is recorded in the log window.

The final step in Web service development is to use a proxy or stub to the service to check that it works at its deployed location.Creating a Stub to Use the Web ServiceBack to ListNow that you have created and deployed your Web service, you can create a proxy or stub to the service.To create a stub, perform the following steps:1.With the projectPLSQLWebServiceselected in the Applications Navigator, chooseNewto open the New Gallery.

2.In theCategorieslist, expandBusiness Tierand chooseWeb Services. In theItemslist, selectWeb Service Stub/Skeletonand clickOKto launch the Web Service Stub/Skeleton wizard.

3.If the Welcome page is displayed, clickNextto display the Select Web Service Description page.

4.From the list, select the URL of the Web service,/MyWebService1.wsdl. LeaveGenerateClient-Side Stubsselected, and selectGenerateMain Method into Stub. ClickNextto display the Select Stubs/Skeletons to Generate page.

5.ClickFinish.

6.The new Java class,MyWebService1Stub.javais listed in the navigator and opened in the Code Editor. Scroll down until you find

// Add your own code here.Immediately below that line, add:

EmpRecUser1 emp = stub.getEmp(new BigDecimal(111));System.out.println("ID = "+ emp.getEmployeeId());System.out.println("NAME = "+ emp.getLastName());System.out.println("SALARY = "+ emp.getSalary());

7.Right-click the Code Editor and chooseMaketo make the stub. Then right-click again and chooseRunto run the stub.

The stub connects to the Web service in the external server using the employee id 111 as a parameter, and returns information about the employee, which is displayed in the log window.

16. Using the TCP Packet Monitor to Examine the Web ServiceBack to Topic ListThis topic shows you how to use the TCP Packet Monitor to examine the request/response packets sent and received by JDeveloper when you run a stub to a Web service. When you start the TCP Packet Monitor, it updates the proxy settings in JDeveloper so that all TCP data is sent through an intermediate port and then on to your original proxy, if one is defined. The proxy settings are restored when you turn the TCP packet monitor off, or when you exit JDeveloper.To use the TCP Packet Monitor, perform the following steps:1.Display the TCP Packet Monitor window by choosingView >TCP Packet Monitor. The TCP Packet Monitor window opens. By default it is docked at the lower right of JDeveloper's user interface.

2.Start monitoring the packets by clicking.

3.Run one of the Web service stubs you have already created. In the navigator, right-click the stub and chooseRun. The request/response packets are listed in the TCP Packet Monitor.

Note: If no message is shown in the TCP Packet Monitor, check the browser and proxy exception list and ensure that the local machine name is not listed.

4.To see the contents of a packet pair, select it in theHistorypage, then click theDatatab.

5.Use theandbuttons to examine other packet pairs.

6.When you are debugging a Web service, you can change the contents of a request packet and resend it so as to see the changes in the response packet. To try this, make the appropriate change to the request packet, and click.

The amended packet is sent and you can examine the response packet to see the change.

7.To stop the TCP Packet Monitor, click.

8.To close TCP Packet Monitor window, click the Close icon at the top right of the window.

You can use the TCP Packet Monitor to examine any HTTP traffic to and from JDeveloper.