DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones AWS Cloud
by AWS Developer Relations
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones
AWS Cloud
by AWS Developer Relations

Pippo and Jersey (JAX-RS): A Match Made in Heaven

See how you can use Pippo, a micro web framework, and Jersey can be combined to render HTML and RESTfully utilize web services.

Decebal Suiu user avatar by
Decebal Suiu
·
Nov. 16, 16 · Tutorial
Like (8)
Save
Tweet
Share
6.42K Views

Join the DZone community and get the full member experience.

Join For Free

For the last few, days I have been playing with Pippo and Jersey (JAX-RS) and I wanted to share my experience with you. The result (a very good one) and the details of my experiment are materialized in this article — along with a demo application.

To begin with, I would like to say a few words about the main actors:

  • Pippo is a micro web framework in Java with minimal dependencies and a quick learning curve, and it's easy to use and hack.

  • Jersey is the JAX-RS (Java API for RESTful web services) reference implementation.

The demo application contains two parts:

  • The web application that renders HTML (using Pippo).

  • The RESTful that contains the web services (using Jersey).

First, we will create in Pippo our application that renders an HTML page with all contacts.

import ro.pippo.core.Application;
import ro.pippo.demo.common.Contact;
import ro.pippo.demo.common.ContactService;
import ro.pippo.demo.common.InMemoryContactService;

public class DemoApplication extends Application {

    private ContactService contactService;

    @Override
    protected void onInit() {
        // add routes for static content
        addPublicResourceRoute();
        addWebjarsResourceRoute();

        // add "contacts" route
        GET("/contacts", routeContext -> {
            Map<String, Object> model = new HashMap<>();
            model.put("contacts", getContactService().getContacts());
            // render "resources/templates/contacts.ftl"
            response.render("contacts", model);
        });
    }

    public final ContactService getContactService() {      
        if (contactService == null) {
            contactService = createContactService();
        }

        return contactService;
    }

    public void setContactService(ContactService contactService) {
        this.contactService = contactService;
    }

    protected ContactService createContactService() {
        return new InMemoryContactService();
    }

}

The application is very simple. Iit contains the ContactService that includes the business (operations with contacts) and the /contacts  route that renders a template as a response to a request.

It is worth clarifying the following two lines:

addPublicResourceRoute();
addWebjarsResourceRoute();

The above two lines add some resources (from  public  folder and from  webjars) to application.

The project has a standard Maven layout:

$ tree src
src
├── main
│   ├── java
│   │   └── ro
│   │       └── pippo
│   │           └── demo
│   │               └── jersey
│   │                   ├── ContactResource.java
│   │                   ├── HelloResource.java
│   │                   ├── DemoApplication.java
│   │                   ├── Demo.java
│   │                   └── JerseyInitializer.java
│   └── resources
│       ├── conf
│       │   ├── application.properties
│       ├── logging.properties
│       ├── public
│       │   └── css
│       │       └── style.css
│       └── templates
│           ├── base.ftl
│           └── contacts.ftl
└── test
    └── java
        └── ro
            └── pippo
                └── demo
                    └── jersey
                        └── AppTest.java

The public static resources are stored in  public  folder and all templates are stored in templates folder.

In this demo, I use Freemarker as template engine because it is popular.

The contacts HTML template (contacts.ftl) looks like this:

<#import "base.ftl" as base/>
<@base.page title="Contacts">
    <div class="page-header">
        <h2><i class="fa fa-users"> Contacts</i></h2>
    </div>

    <table id="contacts" class="table table-striped table-bordered table-hover">
        <thead>
        <tr>
            <th>#</th>
            <th>Name</th>
            <th>Phone</th>
            <th colspan='2'>Address</th>
        </tr>
        </thead>
        <tbody>
            <#list contacts as contact>
            <tr>
                <td>${contact_index + 1}</td>
                <td>${contact.name}</td>
                <td>${contact.phone}</td>
                <td>${contact.address}</td>
            </tr>
            </#list>
        </tbody>
    </table>
</@base.page>

And it extends the base HTML template (base.ftl):

<#macro page title>
<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <meta content="IE=edge" http-equiv="X-UA-Compatible">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">

        <title>${title}</title>

        <link href="${webjarsAt('bootstrap/css/bootstrap.min.css')}" rel="stylesheet">
        <link href="${webjarsAt('font-awesome/css/font-awesome.min.css')}" rel="stylesheet">
        <link href="${publicAt('css/style.css')}" rel="stylesheet">
    </head>
    <body>
        <div class="container">
            <#nested/>

            <script src="${webjarsAt('jquery/jquery.min.js')}"></script>
            <script src="${webjarsAt('bootstrap/js/bootstrap.min.js')}"></script>
        </div>
    </body>
</html>
</#macro>

From the above snippet, you can see that Pippo supports context-aware URL generation for your classpath resources using the  webjarsAt  and publicAt  methods.

The webjars are declared in your pom.xml file:

<!-- Webjars -->
<dependency>
  <groupId>org.webjars</groupId>
  <artifactId>bootstrap</artifactId>
  <version>3.3.1</version>
</dependency>

<dependency>
  <groupId>org.webjars</groupId>
  <artifactId>font-awesome</artifactId>
  <version>4.2.0</version>
</dependency>

Of course that you are not forced to use webjars, but I prefer to use them in my applications if they are available.

Now that the application is ready, it's time to run it using a simple Java class that contains a main method:

import ro.pippo.core.Pippo;

public class Demo extends Pippo {

    public Demo() {
        super(new DemoApplication());

        // set pippo filter path (optional)
        getServer().setPippoFilterPath("/pippo/*");
    }

    public static void main(String[] args) {
        new Demo().start();
    }

}

That's all, simple and straightforward. The application is available in the web browser (http://localhost:8338/pippo/contacts) and this is how the result looks:

Contacts

Now we have a simple web application and we want to add some RESTful flavor using Jersey.

The first step in this direction is to add two web resources in our application, HelloResource and ContactResource:

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;

@Path("/")
public class HelloResource {

    @GET
    @Path("hello")
    @Produces(MediaType.TEXT_PLAIN)
    public String helloWorld() {
        return "Hello from Jersey!";
    }

}
import ro.pippo.core.WebServer;
import ro.pippo.demo.common.Contact;
import ro.pippo.demo.common.ContactService;

import javax.servlet.ServletContext;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;

@Path("/contact")
public class ContactResource {

    @Context
    private ServletContext servletContext;

    @GET
    @Path("{id}")
    @Produces(MediaType.APPLICATION_JSON)
    public Contact getContact(@PathParam("id") int id ) {
        return getContactService().getContact(id);
    }

    private ContactService getContactService() {
        // retrieve contact service from the application instance
        return ((JerseyApplication) servletContext.getAttribute(WebServer.PIPPO_APPLICATION)).getContactService();
    }

}

Please note how the ContactService is retrieved from ServletContext in the method getContactService().

The next step is to "inject" Jersey into our application. To accomplish this task we can use two methods:

  • Using  addListener(ServletContextListener listener)  from WebServer 

  • Using WebServerInitializer  

In this demo, I will choose the second method:

import org.glassfish.jersey.server.ResourceConfig;
import org.glassfish.jersey.servlet.ServletContainer;
import org.kohsuke.MetaInfServices;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import ro.pippo.core.WebServerInitializer;

import javax.servlet.ServletContext;
import javax.servlet.ServletRegistration;

@MetaInfServices
public class JerseyInitializer implements WebServerInitializer {

    private final Logger logger = LoggerFactory.getLogger(getClass());

    @Override
    public void init(ServletContext servletContext) {
        ResourceConfig resourceConfig = createResourceConfig();

        // add jersey filter
        ServletRegistration.Dynamic jerseyServlet = servletContext.addServlet("jersey", new ServletContainer(resourceConfig));
        jerseyServlet.setLoadOnStartup(1);
        jerseyServlet.addMapping("/jersey/*");

        logger.debug("Jersey initialized");
    }

    @Override
    public void destroy(ServletContext servletContext) {
        // do nothing
    }

    private ResourceConfig createResourceConfig() {
        ResourceConfig resourceConfig = new ResourceConfig();
        resourceConfig.register(HelloResource.class);
        resourceConfig.register(ContactResource.class);

        return resourceConfig;
    }

}

That's it! The Jersey's web services are up and running (for confirmation, check http://localhost:8338/jersey/contact/1). 

As an observation, we can implement in Pippo the same functionality as in Jersey with only two trivial routes:

public class DemoApplication extends Application {

    @Override
    protected void onInit() {
        ...

        GET("/hello", routeContext -> routeContext.text().send("Hello from Pippo!"));

        GET("/contact/{id}", routeContext -> {
            int id = routeContext.getParameter("id").toInt(); // read parameter "id"
            Contact contact = getContactService().getContact(id);
            routeContext.json().send(contact);
        });
    }

    ...

}


Both parts (Pippo and Jersey) share the same business:

  • Entity object (Contact class, a POJO)
import java.io.Serializable;

import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement
public class Contact implements Serializable {

    private static final long serialVersionUID = 1L;

    private int id;
    private String name;
    private String phone;
    private String address;

    public Contact() {
    }

    public Contact(int id) {
        this.id = id;
    }

    public int getId() {
        return id;
    }

    @XmlAttribute
    public Contact setId(int id) {
        this.id = id;

        return this;
    }

    public String getName() {
        return name;
    }

    @XmlElement
    public Contact setName(String name) {
        this.name = name;

        return this;
    }

    public String getPhone() {
        return phone;
    }

    @XmlElement
    public Contact setPhone(String phone) {
        this.phone = phone;

        return this;
    }

    public String getAddress() {
        return address;
    }

    @XmlElement
    public Contact setAddress(String address) {
        this.address = address;

        return this;
    }

}
  • Service ( ContactService class) 
public interface ContactService {

    List<Contact> getContacts();

    Contact getContact(int id);

    void delete(int id);

    Contact save(Contact contact);

}


As a bonus, the demo comes with some unit tests. The unit tests demonstrate:

  • The same PippoTest  class can be used to tests Jersey web services and Pippo routes.

  • How you can mock a service (ContactService) and inject the mock into an application.

import com.jayway.restassured.http.ContentType;
import com.jayway.restassured.response.Response;
import org.junit.Rule;
import org.junit.Test;
import org.mockito.Mockito;
import ro.pippo.demo.common.Contact;
import ro.pippo.demo.common.ContactService;
import ro.pippo.test.PippoRule;
import ro.pippo.test.PippoTest;

import static org.junit.Assert.assertEquals;

public class AppTest extends PippoTest {

    @Rule
    public PippoRule pippoRule = new PippoRule(new Demo());

    @Test
    public void testPippoHello() {
        // set base path for pippo routes
        basePath = "/pippo";

        Response response = get("/hello");
        response.then()
            .statusCode(200)
            .contentType(ContentType.TEXT);
        assertEquals("Hello from Pippo!", response.asString());
    }

    @Test
    public void testJerseyHello() {
        // set base path for jersey resources
        basePath = "/jersey";

        Response response = get("/hello");
        response.then()
            .statusCode(200)
            .contentType(ContentType.TEXT);
        assertEquals("Hello from Jersey!", response.asString());
    }

    @Test
    public void testPippoGetContact() {
        // mock service
        mockContactService();

        // test pippo (web) aspects below
        basePath = "/pippo";
        Response response = get("/contact/1");
        response.then()
            .statusCode(200)
            .contentType(ContentType.JSON);

        Contact contact = response.as(Contact.class);
        assertEquals("Maria", contact.getName());
    }

    @Test
    public void testJerseyGetContact() {
        // mock service
        mockContactService();

        // test pippo (web) aspects below
        basePath = "/jersey";
        Response response = get("/contact/1");
        response.then()
            .statusCode(200)
            .contentType(ContentType.JSON);

        Contact contact = response.as(Contact.class);
        assertEquals("Maria", contact.getName());
    }

    private void mockContactService() {
        ContactService contactService = Mockito.mock(ContactService.class);
        Contact contact = new Contact(1)
            .setName("Maria")
            .setPhone("0741200000")
            .setAddress("Sunflower Street, No. 3");
        Mockito.when(contactService.getContact(1)).thenReturn(contact);

        getApplication().setContactService(contactService);
    }

    private JerseyApplication getApplication() {
        return (JerseyApplication) pippoRule.getApplication();
    }

}


PippoTest is a tiny wrapper over RestAssured. It is starting your application in TEST mode on any random available HTTP port.

To conclude, Pippo and JAX-RS (Jersey in this case) are a perfect match and the integration process is very smooth.

The demo application is available on GitHub.

application

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • Practical Example of Using CSS Layer
  • Apache Kafka Is NOT Real Real-Time Data Streaming!
  • OpenVPN With Radius and Multi-Factor Authentication
  • Public Key and Private Key Pairs: Know the Technical Difference

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: