GETTING STARTED WITH JAVA WEB SERVICES USING NETBEANS IDE – Develop Java Web Services to Access Databases

9.4  GETTING STARTED WITH JAVA WEB SERVICES USING NETBEANS IDE

In the following sections, we will develop and build different Java Web services projects based on our Oracle Database XE 18c database system with different consuming projects to perform desired database operations.

By adding different operations or methods to our Web service projects to access and manipulate data in Tables, such as the Faculty and Course Tables, in our sample Oracle database, we can perform the following data queries and manipulations:

1) Query data from the Faculty Table in our Oracle database with QueryFaculty().
2) Insert data into the Faculty Table in our Oracle database with InsertFaculty().
3) Update and delete data against the Faculty Table in our Oracle database with the
UpdateFaculty() and DeleteFaculty() operations.
4) Query data from the Course Table in our Oracle database with QueryCourse().

FIGURE 9.19  The run result of calling our Web service.

5) Query detailed course information from the Course Table in our Oracle database with
DetailCourse().

6) Update and delete data against the Course Table in our Oracle database with the
UpdateCourse() and DeleteCourse() operations.

For each Web services project, we need to build an associated client project to consume the Web services project to test its function. The following client projects will be built:

1) Window-based client project to consume the Web service to access the Faculty and Course Tables in our Oracle database.
2) Window-based client project to consume the Web service to insert data into the Faculty and Course Tables in our Oracle database.

3) Window-based client project to consume the Web service to update and delete data against the Faculty and Course Tables in our Oracle database.
4) Web-based-based client project to consume the Web service to access the Faculty and Course Tables in our Oracle database.

5) Web-based-based client project to consume the Web service to insert data into the Faculty and Course Tables in our Oracle database.

6) Web-based-based client project to consume the Web service to update and delete data against the Faculty and Course Tables in our Oracle database.

In fact, we can develop any kind of client project to consume a Web service, either a standard Java desktop application, which is called a Window-based consume project, or a JSP page, which is called a Web-based consume project. We will develop and build different client projects to consume our Web services to enable our projects to meet real-world needs.

Let’s start with the query of the Faculty Table in our Oracle database.

BUILD JAVA WEB SERVICE PROJECTS TO ACCESS AND MANIPULATE THE FACULTY TABLE – Develop Java Web Services to Access Databases

9.5  BUILD JAVA WEB SERVICE PROJECTS TO ACCESS AND MANIPULATE THE FACULTY TABLE

In this section, we will discuss how to query and manipulate the Faculty Table against our Oracle database using Java Web services. To make our Web Services project simple, we will use the fol-lowing components to fulfill the query and manipulation actions:

  • Build different operations or methods in our Web services as interfaces to communicate with Web clients that will be built in the future to perform desired data actions.

FIGURE 9.20   The structure and components used in our Web services.

FIGURE 9.21   The finished Server and Settings wizard.

  • Use the runtime object method to actually access and query our sample Oracle database.
  • The structure and components used in our Web services are shown in Figure 9.20.
  • Now let’s create our first Web service project to perform data query and manipulation against our sample database.

9.5.1  Create a New Java Web Application Project, WebAppFaculty

When creating a new Web service application project, we need to select a desired container to deploy our Web service. Generally we can either deploy our Web service in a Web container or an EJB container. In this application, we prefer to use a Web container, since we are creating a Java EE 7 application.

Perform the following operations to create our Web application project, WebAppFaculty:

1) Launch NetBeans IDE 12.0 and choose File > New Project (Ctrl-Shift-N). Expand the Java with Ant folder, select Java Web under the Categories list and Web Application from the Projects list. Click on the Next button to continue.

2) Name the project WebAppFaculty and click on the Browse button to select a desired location for the project. In this application, we used C:\Class DB Projects\ Chapter 9 as our project location. Click on the Next button to continue.

3) Select GlassFish Server as our Web container and Java EE 7 Web as the Java EE version. Your finished Server and Settings wizard should match the one shown in Figure 9.21. Click on the Finish button to complete the new application creation process.

Now that a Web application has been created with a selected Web container, next we can create our new Web service project, WebServiceFaculty.

Create a New Java SOAP-Based Web Service Project WebServiceFaculty 2 – Develop Java Web Services to Access Databases

A. The java.sql library is first imported, since we need to use some of its components to con-nect to and implement in our sample Oracle database.

B. First a class-level variable, con, is created. This variable is used to hold the connection instance to our sample Oracle database, CSE _ DEPT.

C. An ArrayList instance, result, is created and used to collect and store our query result and return to the consuming project. The reason we used an ArrayList and not a List is that the former is a concrete class, but the latter is an abstract class, and a runtime exception may be encountered if an abstract class is used as a returned object to the calling method.

D. The data query statement is created with a positional parameter as the dynamic parameter for the query criterion faculty _ name.
E. The user-defined method DBConnection() that will be built later is called to setup a connection between our Web service and our sample database. A connection instance, con, is returned after the execution of this method.
F. A new PreparedStatement instance, pstmt, is declared and created to perform the query.
G. The setString() method is used to setup the actual value that is our input faculty name for the positional parameter faculty _ name.
H. The query is performed by calling the executeQuery() method, and the query result is returned and stored in a ResultSet object, rs.

FIGURE 9.24   The code for the new operation, QueryFaculty().

I. To get more related information about the queried database, the getMetaData() method is executed, and the result is stored in a ResultSetMetaData instance, rsmd.
J. while() and for() loops are used to pick up each column from the queried result that is stored in the ResultSet object rs. In fact, the while() loop only runs one time since only one matching faculty row will be returned. The getColumnCount() method is used as the upperbound of the for() loop, but this upper bound must be decreased by 1 since totally there are eight (8) columns in the Faculty Table, but we only need to query and pick up the first seven (7) columns. The last column is the faculty image object, but it can-not be added into the ArrayList as a String object. Thus, this query only returns the first seven columns in a matching faculty row.

K. The close() method is executed to disconnect from our sample database.

L. The queried result is returned to the calling method.
M. The catch block is used to track and display any exception during the data query process, and a null will be returned if one occurs.

During the coding process, you may encounter some runtime compiling errors. The main reason for those errors is that some packages are missing. To fix these errors, just right-click on any space inside this code window, and select the Fix Imports item to add those miss-ing packages.

Now let’s build our user-defined method, DBConnection(), to setup a connection to our sam-ple database from our Web service project.

FIGURE 9.25   The code for the user-defined method DBConnection().

Create a New Java SOAP-Based Web Service Project WebServiceFaculty – Develop Java Web Services to Access Databases

9.5.2  Create a New Java SOAP-Based Web Service Project WebServiceFaculty

The function of this Web service is to perform data queries and manipulations to our sample Oracle 18c XE database and return the result. Perform the following operations to create this new Web service project, WebServiceFaculty:

1) In the opened Projects window, right-click on our new created project, WebApp Faculty, and select the New > Other menu item to open the New File wizard.
2) Select Web Services from the Categories list and Web Service from the File Types list, and click on the Next button.
3) Name the Web service WebServiceFaculty and type org.ws.oracle into the
Package field. Leave Create Web Service from Scratch selected.

Your finished Name and Location wizard should match the one shown in Figure 9.22. Click on the Finish button to complete this process.

Next let’s handle adding new operations and code for the operations or methods in our Web service.

9.5.3  Add the First Web Operation to Our Web Services to Perform a Data Query

The main purpose of using the Web service in this section is to query data from the Faculty Table in our sample database; thus, we need to add a new operation, QueryFaculty(). Perform the fol-lowing steps to add QueryFaculty() into our Web service project:

1) Click on the Design button at the top of the window to open the Design View of our Web service project, WebServiceFaculty.java.
2) First let’s remove the default hello operation by right-clicking on it, and select Remove Operation item from the popup menu.

FIGURE 9.22  The finished Name and Location wizard.

FIGURE 9.23  The finished Add Operation wizard.

3) Click on the Add Operation button to open the Add Operation wizard.
4) Enter QueryFaculty into the Name field and click on the Browse button next to the Return Type combo box. Type ArrayList into the Type Name field, select the item ArrayList (java.util) from the list and click on the OK button.

5) Click on the Add button and enter fname into the Name parameter field. Keep the default type java.lang.String unchanged and click on the OK button to complete the new operation creation process.

Your finished Add Operation wizard should match the one shown in Figure 9.23.
Click on the Source button at the top of this window to open the code window of our Web ser-vice project. Let’s develop the code for this new operation.
In the opened code window, enter the code shown in Figure 9.24 into the new operation. Let’s have a closer look at this piece of code to see how it works.

Build the User-Defined Method DBConnection() 2 – Develop Java Web Services to Access Databases

A. Some useful packages are first imported into the source window for this operation. You can right-click on the code window and select Fix Imports from the popup menu if you do not want to declare these packages yourself when this piece of code is done.

B. Some local objects and variables are declared here; the bimg is a Blob object since we need to retrieve a desired faculty image from the Faculty Table and the image is a Blob format in our database column. fimg is a type of Image object since this type of object can be used as a returned object from the Web Service project. Since this object belongs to the java.awt.Image class, a full package name is used.

C. The query string is declared with faculty _ name as an input position parameter.
D. A try-catch block is used to perform the image query operation. First a connection method, DBConnection(), which will be built in the next section, is executed to connect to our sample database, CSE _ DEPT.

E. A new PreparedStatement instance, pstmt, is declared and created to perform the query. F. The setString() method is used to set up the actual value that is our input faculty name
for the positional parameter faculty _ name.
G. The image query is performed by calling the executeQuery() method, and the query result is returned and stored in a ResultSet object, rs.

H. To get more detailed information about the queried database, the getMetaData() method is executed, and the result is stored in a ResultSetMetaData instance rsmd.

FIGURE 9.27  The code for the second operation QueryImage().

I. while() and for() loops are used to pick up the queried faculty image stored in the ResultSet object rs. In fact, the while() loop only runs one time since only one match-ing faculty row will be returned. The getColumnCount() method is used as the upper-bound of the for loop, and it should be equal to 8, since the eighth column in the Faculty Table stores the desired faculty image.

J. An if selection structure is used to check if the eighth column has been retrieved. If it is, the getBlob() method is executed to pick up the image in that column and assign it to the local object bimg, which is a Blob-type object.

K. The system method getBinaryStream() is used to convert the Blob object to an Image object, fimg, with another system method, read(), that belongs to the ImageIO class.
L. Then a break instruction skips out and terminates this for loop.

M. A sequence of cleaning jobs is performed to close all used objects, and the queried faculty image is returned.

N. The catch block is used to catch and display any possible error during the image query.

At this point, we have finished all code development for our Web service used to perform queries to our Faculty Table. Prior to building and running our project to test its functions, we need first to set up the Oracle JDBC driver and our correct Java platform.

Build the User-Defined Method DBConnection() – Develop Java Web Services to Access Databases

9.5.4  Build the User-Defined Method DBConnection()

To make our Web service project simple, we will use the Java runtime object method to per-form the database connection function. In the opened code window of our Web service project, WebServiceFaculty.java, enter the code shown in Figure 9.25 to create and define the con-nection method DBConnection().
Let’s have a closer look at this piece of code to see how it works.

A. A try-catch block is used to perform the database connection function. First the Oracle JDBC driver is loaded using the forName() method.
B. The catch block is used to track and detect any possible exception for the JDBC driver loading process. The debug information will be displayed using the System.out. println() method if an exception occurs.

C. Our sample Oracle database connection URL is defined and used to set up a connection to our sample database. Refer to Section 6.3.3.2 in Chapter 6 to get more details about the connection URL.

D. Another try-catch block is used to set up a connection to our sample database using the getConnection() method that belongs to the DriverManager class with the username and password as arguments.

E. The catch block is used to detect and display any possible exception during this connec-tion process.

F. The established connection object is returned to the calling method.

Next let’s add the second Web operation to our Web Service project to query and get a matching faculty image for the selected faculty member.

9.5.5  Add the Second Operation to Our Web Service to Query the Faculty Image

Perform the following operations to add a new operation, QueryImage(), into our Web service:

1) Click on the Design button at the top of the window to open the Design View of our Web service project file, WebServiceFaculty.java.
2) Click on the Add Operation button to open the Add Operation wizard.

FIGURE 9.26  The finished Add Operation wizard.

3) Enter QueryImage into the Name field and click on the Browse button next to the Return Type combo box. Type Image into the Type Name field, select the item Image (java.awt) from the list and click on the OK button.

4) Click on the Add button and enter fname in the Name parameter field. Keep the default type java.lang.String unchanged and click on the OK button.
Your finished Add Operation wizard should match the one shown in Figure 9.26. Click on the OK button again to complete the second add operation process.

Click on the Source button at the top of this window to open the code window of our Web service project. In the opened code window, enter the code shown in Figure 9.27 into the new added operation.
Let’s have a closer look at this piece of code to see how it works.

Setup the Correct JDBC Driver and Java Platform for Our Web Service – Develop Java Web Services to Access Databases

9.5.6  Setup the Correct JDBC Driver and Java Platform for Our Web Service

Perform the following steps to complete the JDBC Driver setup process:

1) Right-click on our project, WebAppFaculty, in the Projects window and select the Properties item to open the project properties wizard.
2) Click on the Libraries node and click on the Add JAR/Folder button to open the Windows Explorer to locate our installed JDBC Driver for Oracle 18c XE, ojdbc8.jar.

3) Browse to the location where the JDBC Driver is installed (refer to Appendix H to down-load this driver). In our case, it is C:\Temp. Click the file ojdbc8.jar to select it and click on the Open and OK buttons to add it into our project.

4) Click on the drop-down arrow on the right of the Java Platform box, select JDK 1.8 and click on the Change Platform button in the popup menu to make this change valid.

Your finished Project Properties wizard should match the one shown in Figure 9.28.

Click on the OK button to complete the JDBC driver addition operation.

9.5.7  Deploy the Web Service Project and Test the Data Query Function

Perform the following operations to build and deploy our Web service project:

1) Click on the Clean and Build Main Project button to build our Web service.
2) Right-click on our Web application, WebAppFaculty, and select the Deploy item to deploy our Web service. If everything is fine, a successful deployment result should be displayed, as shown in Figure 9.29.

3) To test this Web service, right-click on our target service output file, WebServiceFaculty, under the Web Services node in our project, and select the Test Web Service item.
4) The tested page is opened and displayed. Then enter a desired faculty name such as Ying Bai into the text field and click on the queryFaculty button to call our Web service. The run result is shown in Figure 9.30.

FIGURE 9.28  The finished Project Properties wizard.

FIGURE 9.29  The deployment result of our Web service project.

FIGURE 9.30  The test result of our Web service project.

It can be seen that all seven pieces of queried faculty information for the selected faculty member have been retrieved and displayed in the tester. Our data query for our Faculty Table is successful using our Web service.

Now let’s continue to test the second operation, QueryImage(), by clicking on the Back button to return to the original test page. Enter a desired faculty name such as Ying Bai in the text field and click on the queryImage button. The selected faculty image is [B@66c557e1.

Next we can develop a Windows or Web client project to consume this Web service to per-form a data query from the Faculty Table in our sample database. In fact, as we discussed in Section 9.3.5, we can develop different kinds of client projects to consume a Web service. In the fol-lowing sections, we will discuss two popular client projects, Window-based and Web-based clients, to consume our Web service to perform queries to our Faculty Table.

First let’s discuss how to build a Window-based client project to consume our Web service.

BUILD A WINDOW-BASED CLIENT PROJECT TO CONSUME THE WEB SERVICE – Develop Java Web Services to Access Databases

9.6  BUILD A WINDOW-BASED CLIENT PROJECT TO CONSUME THE WEB SERVICE

To save time and space, we can use the Window-based project OracleSelectFaculty we developed in Section 6.3 in Chapter 6 to build our new client project, WinClientFaculty _ Select. That project can be found in the folder Class DB Projects\Chapter 6, which is located in the Students folder on the CRC Press ftp site (refer to Figure 1.2 in Chapter 1).

9.6.1  Copy the FacultyFrame and MsgDialog Components as GUIs

Perform the following operations to create a GUI for our Window-based client project,
WinClientFaculty _ Select, to consume our Web service:

1) Launch NetBeans IDE 12.0 and choose File > New Project.
2) Select Java with Ant and Java Application from the Categories and
Projects lists, respectively. Click on the Next button.
3) Name the project WinClientFaculty _ Select and select a desired folder to save this project. Uncheck the Create Main Class checkbox. Your finished Name and Location wizard should match the one shown in Figure 9.31. Click on the Finish button to create this project.

FIGURE 9.31   The finished Name and Location wizard.

FIGURE 9.32   The finished Copy Class wizard.

4) Go to the Students folder on the CRC Press ftp site and load and open the project OracleSelectFaculty from the folder Class DB Projects\Chapter 6.
5) In the opened project, right-click on the Faculty Frame file FacultyFrame.java under the project package node, and select the Refactor > Copy item to copy this form file.

Copy Class—FacultyFrame wizard, select our new project,
WinClientFaculty _ Select, from the Project combo box and remove the 1 FacultyFrame from the New Name field. Your finished Copy Class wiz-6)Intheopenedafterthe ard is shown in Figure 9.32.
7) Click on the Refactor button to make a refactored copy of the frame file.
8) Return to our new project, WinClientFaculty _ Select, and you can see that a copied FacultyFrame.java file has been pasted in the default package in our project.
Perform a similar Refactor operation to copy the MsgDialog.java file and paste it into our new client project. Next let’s develop the code to call our Web service to perform the faculty data query. However, before we can begin the coding process, we must first setup or create a Web service reference for our WinClientFaculty _ Select project to enable our project to recognize the Web service and call it when it is instructed to do so.

Create a Web Service Reference for Our Window-Based Client Project 3 – Develop Java Web Services to Access Databases

A. Some local objects are declared first, which include a byte[] array object, bimg, and an Image object, img, and both objects are used to hold the created byte[] image array and converted Image object. Both integer variables, imgId and timeout, are used to keep the image ID and timeout value when displaying this image in the Canvas object in our client.

B. A try-catch block is used to call our Web service to perform the faculty data query operation. First a new Web service instance, service, is created based on our Web ser-vice class WebServiceFaculty _ Service. Starting with NetBeans IDE 7, a keyword _ Service must be appended after the Web Service name to create a new service object.

C. The getWebServiceFacultyPort() method is executed to get the current port used by our Web service. This port is returned and assigned to a new port instance, port.

D. Now our Web Service operation, QueryImage(), is called with the selected faculty name as the argument to retrieve the selected faculty image from our sample database and assign it to our local variable bimg. One issue is that this returned object is an Image type when it is defined in our Web Service, but now we are using a byte[] array data type to hold this image. The reason for that is the default conversion by NetBeans IDE.

E. Two code lines in this section are used to convert the data type of this returned image from byte[] to Image. A ByteArrayInputStream object and ImageIO.read() method must be used for this conversion.

F. A catch block is used to detect and report any error for the conversion process.

G. In order to store our retrieved faculty image in our current project folder, the system method getProperty() with our current directory (user.dir) is used, and the current folder is assigned to a local string variable, imgPath.

H. To get the selected faculty image, we need to get the current selected or queried faculty name from the Faculty Name combo box, convert this item to a string and attach “.jpg” to the image file name. We need to use the name of this faculty image later to store and display this selected faculty image in the Canvas.

I. To save this converted faculty image in our current project folder, a new File object is gen-erated with the image path and name. A system method, ImageIO.write(), is used to complete this image-saving job.

J. To display the selected faculty image, the getImage() method that belongs to the abstract class Toolkit is executed to load the selected image. Since the Toolkit class is an abstract class, we use the getToolkit() method to create it instead of generating it by invoking its constructor. The getGraphics() method is called to get a Graphics context, and our ImageCanvas works as an image holder for this faculty image.

K. The addImage() method that belongs to the MediaTracker class is called to add our image with its ID into the tracking system.

L. A try-catch block is used to begin a tracking process, and the waitForID() method is called to execute the tracking. If a timeout occurs for the tracking process, which means

that the selected faculty image has not been loaded into the project, a warning message is displayed using our MsgDialog object, and a False is returned to indicate this error.
M. Any other possible exception or error will be caught by the catch block and be displayed in our msgDlg dialog.

N. If no timeout error happens, which means that the selected faculty image has been loaded into our project and is ready to be displayed, the drawImage() method is executed to dis-play it in the FacultyFrame Form window. We want to display this image starting from the origin of the Canvas object, which is the upper-left corner of the canvas (0, 0), with a width and height that are identical to those of the canvas. Therefore, the getWidth() and getHeight() methods are called to get both of them from the canvas object. A true is returned to the main program to indicate that the execution of this method is successful.

Before we can build and run our client project to test this faculty query, add one more code line, System.exit(0); to the bottom of the BackButtonActionPerformed() handler or method in the Source window of the FacultyFrame class to terminate our project if the Back button is clicked.

Now we are ready to build and run our client project to test its function to call our Web service to perform the faculty data query.

Create a Web Service Reference for Our Window-Based Client Project 2 – Develop Java Web Services to Access Databases

D. Before we can call our Web service, make sure that our ArrayList object al is empty by executing the clear() method.

E. The queryFaculty() method defined in our Web service is called to perform this fac-ulty data query. Two points to be noted are: 1) the argument of this method is a selected faculty name obtained from the getSelectedItem() method from the Faculty Name combo box ComboName. Since this method returns an object, a toString() method must be attached to convert it to a string. 2) An ArrayList cast must be used to make sure that the returned query result is an ArrayList type since an ArrayList type is used
in our Web service project. The query result is assigned to our ArrayList instance, al.
F. A for() loop is used to pick up each column from the query result using the get() method. Two points to be noted are: 1) the argument of the get() method indicates the index of each column in the returned query result is a single row, and the data type of this method is an object. Therefore, a toString() method must be attached to convert it to a string. 2) To assign each column to each item in the f _ field array, the setText() method must be used.

G. The catch block is used to track and display any possible exception during the Web ser-vice calling process.

H. Another try-catch block is used to call a user-defined method, ShowFaculty(), that will be built later to call our Web method to query and display a selected faculty image.

I. The user-defined method ShowFaculty() is modified by removing its argument. The code for this method will be built later.

Now let’s build the code for our user-defined method ShowFaculty() to get and display a selected faculty image by calling another operation, QueryImage(), built in our Web Service.

In the opened FacultyFrame.java file, browse to the ShowFaculty() method and replace all original code with the code shown in Figure 9.35.

FIGURE 9.35   The modified code for the ShowFaculty() method.

Let’s have a closer look at the modified code to see how it works.