As Published In
Oracle Magazine
March/April 2014

TECHNOLOGY: Oracle ADF

  

REST for Everyone

By Frank Nimphius

 

Build and consume database-bound RESTful web services with ease, using Oracle JDeveloper 12c and Oracle ADF.

Addressing the popularity of RESTful web services in application development, the new Oracle JDeveloper 12c integrated development environment (IDE) provides declarative support for building and consuming Representational State Transfer (REST) services in Java. In addition, the new Oracle Application Development Framework (Oracle ADF) release includes a new data control for REST services that are to be used as business services for Oracle ADF web applications.

This article provides an overview of REST service development in Oracle JDeveloper 12c and, in its hands-on instructions, steps you through building and consuming a database-bound REST service in Oracle ADF.

REST in a Nutshell

To work with REST in Oracle JDeveloper 12c and to follow the hands-on instructions in this article, you don’t need to be a REST web services expert. This section introduces the basic REST concepts and principles you’ll need, providing enough information that you’ll be able to easily follow and understand the hands-on instructions.

Working with REST is all about working with resources addressed by URLs. The term resource is abstract in REST and can refer to anything from a person, an order, or a booking to a list of employees, rows queried from a database table, and more. The key principle in REST is that no state is kept on the client or the server and all context information is encoded in the request or contained in the response payload. Another important concept in REST, Hypermedia as the Engine of Application State (HATEOAS), means that the response to a request contains enough information that the client can determine how to continue working with the application.

For the client to communicate with the server, REST defines an extremely simple contract that allows create, read, update, and delete (CRUD) operations to be encoded only through the HTTP methods GET, PUT, POST, and DELETE on a specific server-side resource. Compared to traditional SOAP-based web services that require you to define hundreds of operations such as getEmployees or updateOrder, the REST API is relatively easy to use.

Because of this simplicity, REST services are lightweight and provide flexibility in their implementations that developers can easily explore. For example, each server-side resource and how it is represented (its format) are negotiable between the client and the server. Well-known formats include XML, JavaScript Object Notation (JSON), and HTML.

In the hands-on part of this article, you will create and work with two resources: department and employee. To have them work with the Oracle ADF REST data control, the resources will be formatted as XML.

Note: The department and employee entities in the hands-on steps in this article use Java Architecture for XML Binding (JAXB) annotations to produce the XML representation. JAXB can also be used to produce JSON, but JSON will not be explored here.

REST in Java

REST services and REST clients can be developed according to the Java API for RESTful Web Services (JAX-RS) standard. The Reference Implementation of the JAX-RS standard is the Jersey open source project, which is also the technology used in Oracle JDeveloper 12c for building and consuming REST services in Java.

JAX-RS defines annotations that enable developers to bind a uniform resource identifier (URI) to Java methods in a plain old Java object (POJO), based on the HTTP method being used in the request. To bind a Java method to a URI, the @Path annotation is used. The optional @ParamName and @QueryPram annotations are used for extracting parameters from the request URI.

To associate a Java method with a specific HTTP method used with a REST URI, JAX-RS defines the following annotations:

In addition, @Produces and @Consumes annotations are used for a Java method to define the payload format of a request as well as the format of the response so that clients and the server can negotiate the contract of their communication.

As you will see, with Oracle JDeveloper 12c, you can build Java-based REST services declaratively by using a configuration wizard that adds all these annotations for you.

Sample Application Overview

In following this article’s hands-on instructions, you will build a master-detail Oracle ADF web application that queries data from the database through Enterprise JavaBeans (EJB)–backed REST services; Figure 1 shows the application. To limit the scope of the Oracle JDeveloper 12c application you will build, some parts of the hands-on application have been prebuilt for you.

o24adf-f1

Figure 1: Master-detail view of the completed sample application

Note: To access the departments and employees data, you’ll use two classes—DepartmentService and EmployeeService—to implement the REST web services. For the purposes of this article and the hands-on activity, the code within each class will be abbreviated. In a real-world implementation, you would typically support the full CRUD methods for each resource.

Getting Ready

The two Oracle JDeveloper 12c workspaces required for the hands-on instructions in this article, one for the REST service and one for the sample application, are contained in the o24adf-2065567.zip file.

Download the zip file and unzip it into a directory whose name does not contain blank-space characters.

The OraMagEjbRestService workspace contains a ready-made EJB Model project and a project to expose the EJB model as a REST service. It requires access to the Oracle Database HR sample database schema. To prepare this workspace for your environment, you must configure the database connection for the workspace. To configure the connection, do the following:
  1. In Oracle JDeveloper 12c, select File -> Open and navigate to the directory containing the unpacked sample application zip file content.
  2. Open the oramag030414/starter/OraMagEjbRestService folder, and select the OraMagEjbRestService.jws file. Click Open to load the workspace.
  3. Select Window -> Database -> Databases, and expand the OraMagEjbRestService node to display the hrconn node.
  4. Right-click hrconn, and select Properties from the menu. Edit the database connection information to work with your database setup. Test the changes (click Test), and click OK.
Next, start the Oracle WebLogic Server instance integrated with Oracle JDeveloper. To start the Oracle WebLogic Server, select Run -> Start Server Instance. If this is the first time you’ve run the integrated Oracle WebLogic Server, a Create Default Domain dialog box will open. Create a password for the default Oracle WebLogic Server domain.

Note: To ensure that the integrated Oracle WebLogic Server listens for localhost and the IP address of your computer, don’t select an address from Listen Address.

Click OK to save your changes and to create and configure the default domain for Oracle ADF. The Oracle WebLogic Server will create a default domain and start the server.

Note: Wait for the integrated Oracle WebLogic Server to start before proceeding to the steps in the next section. The first time you start the server, it builds the Oracle WebLogic Server domain, which may take several minutes.

Creating the Department REST Service

To create the department REST service, begin by selecting Window -> Applications. The OraMagEjbRestService workspace contains two projects: 

  • The Model project uses Oracle TopLink and an EJB session bean to query and update the Departments and Employees tables in the HR schema.
  • The RestService project references the EJB session bean in the Model project from two JavaBeans—DepartmentService.java and EmployeeService.java—to read and write data. The two JavaBeans represent the resources you will now expose as REST services. 
To create the department service, do the following:
  1. In the Application Navigator, expand the RestService project node, Application Sources, oramag.sample.one, two, fourteen, and rservice.
  2. Right-click the DepartmentService.java file entry, and choose Create RESTful Service.
  3. In the Create RESTful Service from Java Class dialog box, change the Root Path input field text to oramag/department to define the base URI to access the department source.
  4. In the Configure HTTP Methods table (note that you may need to resize the dialog box to see the full label string), select the getAll entry. The getAll() public method in DepartmentService.java accesses the EJB business service to query a list of departments from the Departments table in the HR schema and returns the result as an XML response.
  5. Because read requests in REST are Get requests, select GET from the Type column for the getAll entry.
  6. No input arguments are required, so leave the Consumes field empty.
  7. Click the … button to the right of the Produces field, select application/xml, and click OK.
  8. Double-click in the Path field, and add a forward slash (/) as a value. This way a list of departments is queried and returned whenever a Get request is issued to the REST root URI (oramag/department).
  9. Click Next.
  10. Click OK in the Return Type Warning dialog box. The hands-on sample uses JAXB annotations added to the EJB entities to parse Java objects to XML and vice versa, so you can ignore this dialog box.
  11. Click Finish. Oracle JDeveloper opens the DepartmentService.java class in the Java code editor. The class shows the getAll method annotated with
    @GET
    @Produces("application/xml")
    @Path("/") 


    The DepartmentService class itself is annotated with @Path to identify the root URI for this REST resource: 

    @Path("oramag/department")
      
    
  12. Right-click the DepartmentService.java file, and choose Test Web Service to test the REST service in the HTTP Analyzer.
  13. Click Send Request in the opened HTTP Analyzer window to issue a Get request for the REST web service base URI and obtain a list of departments, as shown in Figure 2.

     o24adf-f2

    Figure 2: HTTP Analyzer displaying the result for the GET request

  14. The log window shows a REST service base URL that looks similar to http://127.0.0.1:7101/hr- restservice-context-root/resources/oramag/department/.
  15. Make a note of the actual REST URL—you will need it later.
What you just did: You used Oracle JDeveloper’s wizard for creating RESTful services to REST-enable the DepartmentService class and to expose the public getAll() method for GET access. The REST-specific annotations added to the Java file are from Jersey, the Java EE 6 JAX-RS REST Reference Implementation bundled with Oracle JDeveloper. Finally, you tested the REST service, using Oracle JDeveloper’s integrated HTTP Analyzer.

 

Creating the Employee REST Service

Next, configure the EmployeeService class as a REST service, which requires more configuration, because it includes support for update and delete operations.

  1. In the Application Navigator, in RestService, Application Sources, oramag.sample.one, two, fourteen, and rservice, right-click the EmployeeService.java class and choose Create RESTful Service.
  2. In the Create RESTful Service from Java Class dialog box, change the Root Path input field to oramag/employee.
  3. In the Configure HTTP Methods table, edit the methods as follows:

    Name getByDepartmentId Type GET Consumes Produces application/xml Path /{departmentId} Name update Type POST Consumes application/xml Produces Path / Name removeById Type DELETE Consumes Produces Path /{employeeId}

  4. Next, select the GetByDepartmentId method and edit the Configure Parameters table as follows: Name departmentId Data Type int Annotation PathParam Parameter departmentId Default Encoded
  5. Next, select the removeById method and edit the Configure Parameters table as follows: Name employeeId Data Type int Annotation PathParam Parameter employeeId Default Encoded
  6. Click Finish and OK to confirm the Return Type Warning.
  7. To test the service, right-click the EmployeeService class and choose Test Web Service.
  8. Change the URL field value in the HTTP Analyzer to http://localhost:7101/hr-restservice-context-root/resources/oramag/employee/60, and confirm the change by pressing the Enter key.
  9. Click Send Request to see the list of employees for department 60.
  10. Make a note of the service root URL, http://127.0.0.1:7101/hr- restservice-context-root/resources/oramag/employee.
What you just did: You successfully configured the two JavaBeans in the RestService project as services. Each service represents a resource: a department or an employee. In this section, you performed a more complex configuration that included input arguments defined for methods.

The getByDepartmentId and removeById methods both required a single input argument. Adding /{name} to the REST URI path adds an annotation that enables the request to reference a resource, such as a department, by a unique locator.

So the annotated method would know where to get the required input argument, you added the PathParam annotation with the name of the variable in the request. The name of the variable is the same as the variable name added to the REST path, such as departmentId in /{departmentId}.

Note: The Oracle JDeveloper log window (Window -> Log) shows the URL for the REST Web Application Description Language (WADL) file. Clicking this link opens the WADL file in a tab panel, showing all resource URIs and their HTTP methods defined for the service.

Creating the Department REST Data Controls

REST services are consumed in Oracle ADF by use of the new REST service data control (REST DC). To create the REST DC model,

  1. In Oracle JDeveloper, select File -> Open and navigate to the directory containing the unpacked sample application zip file content.
  2. Open the oramag030414/starter/OraMagRestClientApp folder, and select the OraMagRestClientApp.jws file.
  3. Click Open to load the workspace.
  4. Select the Model project, and choose File -> New -> From Gallery -> Business Tier -> Web Services -> Web Service Data Control (SOAP / REST) from the Oracle JDeveloper menu and the New Gallery dialog box, and click OK.
  5. In the Create Web Service Data Control dialog box, enter DepartmentRestDC in the Name field.
  6. Select REST.
  7. Click the green plus (+) icon next to the Connection field.
  8. In the Create URL Connection dialog box, enter DepartmentsRestConn in the Name field.
  9. Enter http://127.0.0.1:7101/hr-restservice-context-root/resources/oramag/department in the URL Endpoint field.

    Note: The URL Endpoint URL does not have an ending slash. 

  10. Click OK, and then click Next in the Create Web Service Data Control dialog box.
  11. Click the green plus (+) icon next to the Resource Paths label.
  12. Change the Resource Paths value from /path0 to /, and select GET.
  13. Enter getAllDepartments as the Method Display Name value for GET.
  14. Click Next.
  15. Select getAllDepartments under Resource Methods, and click the browse button (magnifier icon) next to the Response XSD field.
  16. In the dialog box, open the xsd folder, select the DepartmentsList.xsd file, and click Open. If no XML Schema Definition (XSD) file is provided, Oracle JDeveloper will generate one when verifying the REST URIs. Note: Because generated files usually require some editing, this sample application provides predefined XSD files. Due to a known issue in Oracle JDeveloper 12.1.2.0, however, it is recommended that you use generated XSD files in your own application development. 
  17. Click Next and then Test URL Connection.
  18. Click Finish when the test is successful. Otherwise, check and correct the provided REST URI.
What you just did: In this section, you created a REST data control for the department resource. The data control exposes a single method for the service GET request and expects an XML response to represent a list of departments. The XML response is defined by an XSD that has been created in preparation for this sample application with the File -> New -> From Gallery -> Business Tier -> TopLink/JPA -> JAXB XML Schema from Content Model option in the OraMagEjbRestService -> RestService project.

 

Creating the Employee REST Data Controls

The employee REST data control you will build next is a bit more complex than the department data control, because it exposes three REST HTTP methods—for GET, POST, and DELETE—and also needs to define input arguments for GET and DELETE. To create the employee REST data controls,

  1. With OraMagRestClientApp open in the Oracle JDeveloper Application Navigator, right-click the Model project and select New -> Web Service Data Control (SOAP / REST).
  2. In the Create Web Service Data Control dialog box, enter EmployeeRestDC in the Name field.
  3. Select REST.
  4. Click the green plus (+) icon next to the Connection field.
  5. In the Create URL Connection dialog box, enter EmployeesRestConn in the Name field.
  6. Enter http://127.0.0.1:7101/hr-restservice-context-root/resources/oramag/employee in the URL Endpoint field.
  7. Click OK and then Next in the Create Web Service Data Control dialog box.
  8. Click the green plus (+) icon next to the Resource Paths label.
  9. Change the Resource Paths value from /path0 to /##departmentId##, and select GET. Enter getEmployeesByDepartment as the Method Display Name value for GET.

    Note: The ##departmentId## flag defines parameters in the Oracle ADF REST data control. The parameter names will show as arguments to the methods in the data control panel. 

  10. Again, click the green plus (+) icon next to the Resource Paths label.
  11. Change the Resource Paths value from /path0 to /, and select POST. Enter updateEmployee as the value of Method Display Name for POST.
  12. Again, click the green plus (+) icon next to the Resource Paths label.
  13. Change the Resource Paths value from /path0 to /##employeeId##, and select DELETE. Enter removeEmployee as the value of Method Display Name for DELETE.
  14. Click Next.
  15. Select removeEmployee from the Resource Methods list, and enter a default value of 100 for employeeId (in the URL Parameters section). Note: The 100 value is used to verify that the REST method request is valid at design time. A later version of Oracle JDeveloper will make this check optional. (No delete will be processed, however.) 
  16. Select updateEmployee from the Resource Methods list, and click the browse button (magnifier icon) next to the Payload XSD field.
  17. In the Open dialog box, open the xsd folder, select the Employee.xsd file, and click Open. Note: The update method of the REST service has a single object argument of type Employee. Because this type is defined as a JAXB object, it can be marshaled and unmarshaled to and from XML. Therefore, you’ll provide the XML representation of the argument.
  18. Select getEmployeesByDepartment from the Resource Methods list and click the browse button (magnifier icon) next to the Response XSD field.
  19. In the Open dialog box, open the xsd folder, select the EmployeesList.xsd file, and click Open.
  20. Enter a default value of 60 for departmentId (in the URL Parameters section). Again, this is used for REST URI verification only at design time.
  21. Click Next, and then click Test URL Connection.
  22. Click Finish when the test is successful. Otherwise, check and correct the provided REST URI.
  23. In the Application Navigator, expand the Data Controls panel and refresh it by clicking the refresh button (icon with two arrows). The two data controls are now displayed. 
What you just did: In this section, you created a REST data control for the employee resource with three methods for read, update, and delete operations on the REST service. Using ##<name>##, you defined parameters to hold the values for the REST method calls. Note that the DELETE operation is not used in this sample application (but regard adding this operation as your homework). The POST operation—updateEmployee—is implemented for you in the completed sample application, explained at the end of this article.

 

Building a Master-Detail Page

With the REST services and the REST data controls created, the final step is to build a master-detail page. To create the master-detail page,

  1. With the OraMagRestClientApp workspace open, in the Application Navigator, expand the ViewController project and the Web Content -> pages node.
  2. Double-click the DeptEmp.jsf page to open it in the visual page editor.
  3. Expand the Data Controls panel and then the DepartmentRestDC -> getAllDepartments() -> Return -> departmentList node.
  4. Drag the alldepartments entry from the Data Controls panel, and drop it in the Departments area in the visual page editor.
  5. Choose ADF Form from the Create menu.
  6. Check Read-Only Form in the Create Form dialog box.
  7. In the Include Controls For section, select Row Navigation and click OK.
  8. In the Data Controls panel, expand the EmployeeRestDc -> getEmployeesByDepartment -> Return -> employeeList node.
  9. Drag the allemployees entry from the Data Controls panel, and drop it in the Employees area in the visual page editor.
  10. Choose Table/List View -> ADF Table from the Create menu.
  11. In the Create Table dialog box, select Single Row and Read-Only Table. Optionally, reorder the employee attributes so they’re in a more logical order if you like.
  12. Click OK.
  13. In the Edit Action Binding dialog box, enter #{bindings.departmentId.inputValue} as the departmentId value and click OK.
  14. Click the table in the Employees area of the visual editor. The bread crumb at the bottom of the visual editor should be the af:table#t1 crumb, highlighted (boldfaced), as the last element. If not, click the bread crumb to select the table.
  15. Open the Property Inspector (Window -> Properties), navigate to the PartialTriggers property under the Behavior category, and enter ::b1 ::b2 ::b3 ::b4. Note: ::b1 through ::b4 are the IDs of the navigation buttons that should trigger a table refresh. Whenever the user navigates the list of departments, the employee list will refresh to display only the employees of the selected department. 
  16. Save your work.
  17. In the Application panel, right-click the DepEmp.jsf file in the ViewController -> Web Content -> pages node and choose Run.
  18. Use the navigation buttons in the Departments section to change the display and watch the employee list refresh.
What you just did: In this section, you created and tested a master-detail page that uses the department REST service, the department REST data control, and the employee REST data control you created in previous sections.

 

RUNning the Completed Sample Application

A completed sample application is provided in the download for this article. In addition to the master-detail view, the completed sample application shows how to update data for a selected employee. To run the completed sample,

  1. In Oracle JDeveloper, open the OraMagEjbRestService.jws workspace in the oramag030414/completed/OraMagEjbRestService folder and configure the database connection to point to the HR sample schema.
  2. Run the service by right-clicking the DepartmentService.java file in the RestService project and choosing Test Web Service. This will deploy the service to the integrated Oracle WebLogic Server.
  3. Next, select File -> Open and navigate to the oramag030414/completed/ OraMagRestClientApp directory containing OraMagRestClientApp.jws. Select the file, and click Open.
  4. Finally, locate the DeptEmp.jsf page in the ViewController project, right-click it, and choose Run.

Next Steps 

 

 DOWNLOAD the sample application for this article

READ more about Oracle ADF
 oracle.com/technetwork/developer-tools/adf
 JAX-RS Reference Implementation—Jersey open source
 Developing Applications with Oracle ADF Data Controls: Chapter 5, “Exposing Web Services Using the ADF Model Layer

 WATCH the REST updatable forms video tutorial

With the DeptEmp.jsf page displayed in your browser, select an employee record and click Edit Selected Employee to test the update function. Provide changes to the employee record, and click Submit. Changes show in the employee table and—as committed data—in the database. Note: Building a REST-based update form with the Oracle ADF REST data control is an advanced topic that is not covered in this article.

 

Conclusion

With Oracle JDeveloper 12c, you can integrate a RESTful service into your Oracle ADF applications, using the REST service data control. This article showed how to build a master-detail browse page based on previously created REST services. An online video tutorial explains how to update remote REST services from Oracle ADF.


Frank Nimphius is a senior principal product manager for Oracle JDeveloper and Oracle ADF. He is a coauthor of Oracle Fusion Developer Guide: Building Rich Internet Applications with Oracle ADF Business Components and Oracle ADF Faces (McGraw-Hill). 

Send us your comments