Book Image

RESTful Java Web Services, Second Edition

Book Image

RESTful Java Web Services, Second Edition

Overview of this book

Table of Contents (17 chapters)
RESTful Java Web Services Second Edition
Credits
About the Author
Acknowledgments
About the Reviewers
www.PacktPub.com
Preface
Index

Using third-party entity provider frameworks with Jersey


We discussed about various frameworks for JSON processing (and binding) in Chapter 2, Java APIs for JSON Processing. In this section, we will see how to tell JAX-RS runtime to use a different entity provider (also known as binding framework) framework instead of the default one provided by the container.

When you deploy the JAX-RS 2.0 application on theWebLogic or GlassFish server, runtime automatically adds MOXy as the JSON binding framework for your application. Note that MOXy is EclipseLink's object-to-XML and object-to-JSON mapping provider. However, you can override the default JSON processor framework offered by runtime (Jersey) with the one that you may prefer for your application.

The following example overrides the default JSON framework used in the Jersey implementation with Jackson (https://github.com/FasterXML/jackson):

  1. The first step is to add dependency to the JSON processor framework that you want to use. For instance, to use Jackson, you need to add jackson-jaxrs-json-provider and jackson-databind jars to the application.

  2. Jersey allows you to disable the MOXy JSON framework by setting the jersey.config.disableMoxyJson configuration property to true. You can do this by overriding javax.ws.rs.core.Applicatio::getProperties(). This is shown in the code snippet given towards the end of this section.

  3. Next, is to register the Provider class. You can register the provider class as a singleton as this provider does not hold any state.

The following code snippet shows a configuration that you will need to make in the Application subclass to use JacksonJsonProvider as the JSON binding framework:

//Other imports are omitted for brevity
import javax.ws.rs.core.Application;
import javax.ws.rs.ext.Provider; 
import com.fasterxml.jackson.jaxrs.json.JacksonJsonProvider;

@javax.ws.rs.ApplicationPath("webresources")
public class HRApplication extends Application {

    @Override
    public Set<Class<?>> getClasses() {
        Set<Class<?>> resources = new java.util.HashSet<>();
        resources.add(HRService.class);
        return resources;
    }

   @Override
    public Set<Object> getSingletons() {
        Set<Object> set = new HashSet<>();
       // Register JacksonJsonProvider as a singleton 
       // to allow reuse of ObjectMapper:
        set.add(
           new com.fasterxml.jackson.jaxrs.json.
           JacksonJsonProvider());
        return set;
    }

    @Override
    public Map<String, Object> getProperties() {
        Map<String, Object> map = new HashMap<>();
        //Disables configuration of MOXy Json feature.
        map.put("jersey.config.disableMoxyJson.server", true);
        return map;
    }
}

Transforming the JPA model in to OData-enabled RESTful web services

Open Data Protocol (OData) is an open protocol for the web. We discussed the advantages of using OData with RESTful web APIs under the Using Open Data Protocol with RESTful web APIs section in Chapter 8, RESTful API Design Guidelines. In this section, we will see how to build OData services for the Java Persistence API (JPA) model.

Apache Olingo is an open source Java library that implements OData protocol. You can use the Apache Olingo framework to enable OData services for your JPA model. At the time of writing this book, the latest release of Olingo was based on the OData Version 2.0 specifications, and the support for OData Version 4.0 was underway.

With the Olingo framework, you can easily transform your JPA models into OData services using the OData JPA Processor Library.

High level steps for enabling OData 2 services for your JPA model are listed as follows:

  1. Build a web project to hold the RESTful web API components.

  2. Generate JPA entities as appropriate.

    The next step is to configure the application to use the Apache Olingo framework for generating OData services for the JPA model.

  3. Add dependency to the Olingo OData Library (Java) and the OData JPA Processor Library. The complete list of jars is listed at http://olingo.apache.org/doc/odata2/tutorials/CreateWebApp.html.

  4. Add a service factory implementation that provides a means for initializing the OData JPA Processors and data model provider (JPA entity). You can do this by adding a class that extends org.apache.olingo.odata2.jpa.processor.api.ODataJPAServiceFactory, as shown in the following:

    //Imports are removed for brevity
    public class ODataJPAServiceFactoryImpl extends  
        ODataJPAServiceFactory {
       //HR-PU is the persistence unit 
       //configured in persistence.xml for the JPA model
          final String PUNIT_NAME = "HR-PU";
       @Override
       public ODataJPAContext initializeODataJPAContext() 
          throws ODataJPARuntimeException {
         ODataJPAContext oDataJPAContext = 
              getODataJPAContext();
         oDataJPAContext.setEntityManagerFactory(
         JPAEntityManagerFactory
        .getEntityManagerFactory(PUNIT_NAME));
          oDataJPAContext.setPersistenceUnitName(PUNIT_NAME);
      return oDataJPAContext;
       }
      //Other methods are removed for brevity
    }
  5. Configure the web application by adding CXFNonSpringJaxrsServlet to web.xml. This servlet manages OData features for your JPA model. Specify the service factory implementation class that you created in the last step as one of the init parameters for this servlet. The web.xml configuration may look like the following lines:

    <servlet>
        <servlet-name>ODataEnabledJPAServlet</servlet-name>
        <servlet-class>
          org.apache.cxf.jaxrs.servlet.CXFNonSpringJaxrsServlet
        </servlet-class>
        <init-param>
          <param-name>javax.ws.rs.Application</param-name>
          <param-value>
            org.apache.olingo.odata2.core.rest.app.ODataApplication
          </param-value>
        </init-param>
        <init-param>
          <param-name>org.apache.olingo.odata2.service.factory</param-name>
          <param-value>com.packtpub.odata.ODataJPAServiceFactoryImpl</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
      <servlet-name>ODataEnabledJPAServlet</servlet-name>
      <url-pattern>/odata/*</url-pattern>
    </servlet-mapping>

Now you can build the application and deploy it to a JAX-RS container, such as the GlassFish server. The Olingo framework will automatically convert all the JPA entities into OData services. You can access the APIs via standard OData clients. To test the deployment, try accessing the OData service as follows: http://localhost:8080/<appname>/odata.

You can go through the tutorial to learn how to build a Java client for OData services at https://olingo.apache.org/doc/odata2/tutorials/OlingoV2BasicClientSample.html.

Tip

The complete source code for this example is available in the Packt website. You can download the example from the Packt website link that we mentioned at the beginning of this book, in the Preface section. In the downloaded source code, see the rest-appendix-odata/rest-appendix-odata-service project.