RESTful web services with Coffee (Jersey / JAX-RS). This tutorial explains how to develop RESTful web services in Coffee. It uses the JAX-RS reference implementation Jersey. In this tutorial Eclipse four.7 (Oxygen), Coffee ane.8, Tomcat half-dozen.0 and JAX-RS 2.0 (with Bailiwick of jersey 2.11) is used.

ane. Residuum - Representational State Transfer

1.i. What is Balance?

Rest is an architectural way which is based on web-standards and the HTTP protocol. This style was initially described by Roy Fielding in 2000. In a REST based architecture everything is a resource. A resource is accessed via a common interface based on the HTTP standard methods. In a Balance based architecture you have a REST server which provides access to the resources. A REST client can access and modify the Residual resource.

Every resource should back up the HTTP mutual operations. Resources are identified by global IDs (which are typically URIs).

Residual allows that resources have different representations, e.g., text, XML, JSON etc. The Rest client tin enquire for a specific representation via the HTTP protocol (content negotiation).

1.2. HTTP methods

The PUT, GET, POST and DELETE methods are typical used in REST based architectures. The following tabular array gives an explanation of these operations.

  • Become defines a reading admission of the resource without side-effects. The resource is never inverse via a Go asking, e.g., the request has no side effects (idempotent).

  • PUT creates a new resource. It must also be idempotent.

  • DELETE removes the resources. The operations are idempotent. They can go repeated without leading to unlike results.

  • Mail service updates an existing resource or creates a new resources.

1.iii. RESTFul web services

A RESTFul web services are based on HTTP methods and the concept of REST. A RESTFul spider web service defines the base URI for the services, the supported MIME-types (XML, text, JSON, user-divers, …​). It also defines the set of operations (POST, GET, PUT, DELETE) which are supported.

2. Installation of Bailiwick of jersey

ii.one. Use Gradle

                  compile 'org.glassfish.bailiwick of jersey.containers:bailiwick of jersey-container-servlet:two.25.1'                

2.2. Manual setup of Jersey libraries in an Eclipse project

The zip contains the Jersey implementation JAR and its core dependencies. Information technology does not provide dependencies for third party JARs beyond those for JSON support and JavaDoc.

Copy all JARs from your Jersey download into the WEB-INF/lib binder.

jerseryfirst40

three. Web container

For this tutorial you can use whatever web container, for instance Tomcat or the Google App Engine.

If you desire to use Tomcat as servlet container please see Eclipse WTP and Apache Tomcat for instructions on how to install and utilize Eclipse WTP and Apache Tomcat.

The following description is based on a local Apache Tomcat installation.

4. Required setup for Gradle and Eclipse spider web projects

This section describes how to setup Eclipse WTP in a Gradle project. This is required for the following tutorials.

iv.1. Prerequisites

If you have non all the same created a Gradle project, you tin can follow the Buildship tutorial to create i.

4.2. Gradle setup

Open up the build.gradle file and add the following two lines.

                  apply plugin: 'war' utilise plugin: 'eclipse-wtp'                

Since we want to create a web application, we want a state of war file (and not a jar file which would exist created by Gradle with the Java plugin). The eclipse-wtp plugin helps you to generate the Eclipse WTP project files.

At present, add a new folder with the name WebContent to your projects root. To do and so, . Add some other folder with the name WEB-INF to your WebContent binder.

The next footstep is to add together a xml file with the name web.xml to the created Spider web-INF folder. To practice so menu: right click on the created folder name[New > Other…​] and select XML file.

Your folder structure should at present look something like this:

projectstructure

Now the newly created folders with the web.xml in it has to exist added to the build.gradle file by adding the post-obit line:

                  project.webAppDirName = 'WebContent'                

Perform a right-click on the project and select . This will add diverse new tasks to your Gradle Tasks view.

taskview

Run the eclipseWTP task to generate the Eclipse WTP project files and terminate the projection setup.

five. Prerequisites

The following clarification assumes that you are familiar with creating spider web applications in Eclipse. See Eclipse WTP evolution for an introduction into creating web applications with Eclipse.

6. Create your showtime RESTful Webservice

6.ane. Create a new Gradle project and configure bailiwick of jersey usage and Eclipse WTP

Create a new Gradle project named com.vogella.jersey.get-go with com.vogella.jersey.first as the top-level package proper noun and configure Eclipse WTP. You can follow Required setup for Gradle and Eclipse web projects to become started.

To import the Jersey dependencies, add the post-obit dependency to your build.gradle file.

                  compile 'org.glassfish.jersey.containers:jersey-container-servlet:2.25.1'                

6.2. Coffee Class

Create the following class.

                                      packet                    com.vogella.jersey.start                    ;                    import                    javax.ws.rs.Go                    ;                    import                    javax.ws.rs.Path                    ;                    import                    javax.ws.rs.Produces                    ;                    import                    javax.ws.rs.core.MediaType                    ;                    // Plainly old Java Object it does not extend every bit class or implements                    // an interface                    // The course registers its methods for the HTTP Become request using the @GET annotation.                    // Using the @Produces annotation, information technology defines that it can deliver several MIME types,                    // text, XML and HTML.                    // The browser requests per default the HTML MIME type.                    //Sets the path to base URL + /hullo                    @Path                    (                    "/hi"                    )                    public                    grade                    Hello                    {                    // This method is called if TEXT_PLAIN is asking                    @Go                    @Produces                    (                    MediaType                    .                    TEXT_PLAIN                    )                    public                    String                    sayPlainTextHello                    ()                    {                    return                    "Hullo Jersey"                    ;                    }                    // This method is called if XML is request                    @Become                    @Produces                    (                    MediaType                    .                    TEXT_XML                    )                    public                    String                    sayXMLHello                    ()                    {                    return                    "<?xml version=\"ane.0\"?>"                    +                    "<hello> Hello Bailiwick of jersey"                    +                    "</hi>"                    ;                    }                    // This method is called if HTML is asking                    @Go                    @Produces                    (                    MediaType                    .                    TEXT_HTML                    )                    public                    String                    sayHtmlHello                    ()                    {                    return                    "<html> "                    +                    "<title>"                    +                    "How-do-you-do Jersey"                    +                    "</title>"                    +                    "<body><h1>"                    +                    "Howdy Jersey"                    +                    "</body></h1>"                    +                    "</html> "                    ;                    }                    }                                  

This class annals itself as a go resource via the @GET note. Via the @Produces annotation information technology defines that it delivers the text and the HTML MIME types. It also defines via the @Path annotation that its service is bachelor nether the hi URL.

The browser volition always request the HTML MIME type. To see the text version, you tin use tool like curl.

6.3. Define Jersey Servlet dispatcher

You need to register Bailiwick of jersey every bit the servlet dispatcher for Residuum requests.

Open the file web.xml and change it to the following.

                                      <?xml version="i.0" encoding="UTF-eight"?>                    <web-app                    xmlns:xsi=                    "http://www.w3.org/2001/XMLSchema-example"                    xmlns=                    "http://java.sun.com/xml/ns/javaee"                    xsi:schemaLocation=                    "http://java.dominicus.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"                    id=                    "WebApp_ID"                    version=                    "3.0"                    >                    <display-name>com.vogella.jersey.first</brandish-proper name>                    <servlet>                    <servlet-name>Jersey Remainder Service</servlet-proper name>                    <servlet-grade>org.glassfish.bailiwick of jersey.servlet.ServletContainer</servlet-class>                    <!-- Register resources and providers under com.vogella.bailiwick of jersey.offset parcel. -->                    <init-param>                    <param-name>jersey.config.server.provider.packages</param-name>                    <param-value>com.vogella.jersey.first</param-value>                    </init-param>                    <load-on-startup>1</load-on-startup>                    </servlet>                    <servlet-mapping>                    <servlet-proper name>Bailiwick of jersey Residuum Service</servlet-name>                    <url-blueprint>/residue/*</url-pattern>                    </servlet-mapping>                    </web-app>                                  

The parameter jersey.config.server.provider.packages defines in which package Jersey will wait for the web service classes. This property must indicate to your resources classes. The URL blueprint defines the part of the base URL your application will be placed.

6.4. Run your rest service

To run your web awarding in Eclipse, brand sure to run the gradle task eclipseWtp first. Afterwards, you should be able to run the application by

You should be able to access your resources nether the following URL:

http://localhost:8080/com.vogella.bailiwick of jersey.first/rest/hello

Result of the Jersey service

This URL is derived from the context root value in the projects properties Web Project Settings (by default, this is your application name), augmented with the servlet-mapping URL-pattern and the hullo @Path annotation from your form file. You should become the message "Hi Jersey".

As nosotros are using Gradle, if yous want to update the context root include the following in your build.gradle and update your spider web container ( in the Servers Eclipse View).

                                      eclipse                    {                    wtp                    {                    component                    {                    contextPath                    =                    '                    newName                    '                    }                    }                    }                                  

The browser requests the HTML representation of your resource. In the next chapter we are going to write a client which will read the XML representation.

vii. Create a REST customer

Bailiwick of jersey contains a REST client library which tin can be used for testing or to build a real client in Java. The usage of this library is demonstrated in the following tutorial.

Create a new Coffee gradle project with com.vogella.jersey.showtime.client every bit top-level package proper name and add together following dependency to your build.gradle file to import the Jersey dependencies.

                compile 'org.glassfish.jersey.containers:jersey-container-servlet:ii.25.1'              

Create the following test class.

                                  package                  com.vogella.bailiwick of jersey.first.client                  ;                  import                  java.internet.URI                  ;                  import                  javax.ws.rs.customer.Client                  ;                  import                  javax.ws.rs.client.ClientBuilder                  ;                  import                  javax.ws.rs.client.WebTarget                  ;                  import                  javax.ws.rs.core.MediaType                  ;                  import                  javax.ws.rs.core.Response                  ;                  import                  javax.ws.rs.core.UriBuilder                  ;                  import                  org.glassfish.jersey.customer.ClientConfig                  ;                  public                  course                  Test                  {                  public                  static                  void                  main                  (                  String                  []                  args                  )                  {                  ClientConfig                  config                  =                  new                  ClientConfig                  ();                  Client                  client                  =                  ClientBuilder                  .                  newClient                  (                  config                  );                  WebTarget                  target                  =                  customer                  .                  target                  (                  getBaseURI                  ());                  Cord                  response                  =                  target                  .                  path                  (                  "remainder"                  ).                  path                  (                  "howdy"                  ).                  asking                  ().                  accept                  (                  MediaType                  .                  TEXT_PLAIN                  ).                  get                  (                  Response                  .                  class                  )                  .                  toString                  ();                  String                  plainAnswer                  =                  target                  .                  path                  (                  "rest"                  ).                  path                  (                  "hullo"                  ).                  request                  ().                  accept                  (                  MediaType                  .                  TEXT_PLAIN                  ).                  get                  (                  String                  .                  course                  );                  Cord                  xmlAnswer                  =                  target                  .                  path                  (                  "rest"                  ).                  path                  (                  "howdy"                  ).                  request                  ().                  have                  (                  MediaType                  .                  TEXT_XML                  ).                  get                  (                  String                  .                  form                  );                  String                  htmlAnswer                  =                  target                  .                  path                  (                  "rest"                  ).                  path                  (                  "hello"                  ).                  request                  ().                  take                  (                  MediaType                  .                  TEXT_HTML                  ).                  get                  (                  Cord                  .                  class                  );                  Arrangement                  .                  out                  .                  println                  (                  response                  );                  System                  .                  out                  .                  println                  (                  plainAnswer                  );                  System                  .                  out                  .                  println                  (                  xmlAnswer                  );                  System                  .                  out                  .                  println                  (                  htmlAnswer                  );                  }                  private                  static                  URI                  getBaseURI                  ()                  {                  return                  UriBuilder                  .                  fromUri                  (                  "http://localhost:8080/com.vogella.jersey.first"                  ).                  build                  ();                  }                  }                              

eight. RESTful spider web services and JAXB

JAX-RS supports the automatic creation of XML and JSON via JAXB. For an introduction into XML please meet Java and XML - Tutorial. For an introduction into JAXB please see JAXB. You tin can go along this tutorial without reading these tutorials, merely they contain more background information.

8.ane. Create new Gradle project

Create a new Gradle projection named com.vogella.jersey.jaxb with com.vogella.jersey.jaxb equally the top-level package proper name and configure Eclipse WTP. You can follow Required setup for Gradle and Eclipse spider web projects to become started. To enable JSON support, add together the post-obit dependency to your build.gradle file. The second line automatically adds support for the media type awarding/json.

                                      compile                    '                    org                    .                    glassfish                    .                    jersey                    .                    containers                    :                    jersey                    -                    container                    -                    servlet:                    2.25                    .                    one                    '                    compile                    '                    org                    .                    glassfish                    .                    jersey                    .                    media                    :                    jersey                    -                    media                    -                    json                    -                    jackson:                    2.25                    .                    i                    '                                  

8.2. Create Java classes

Create your domain grade.

                                      package                    com.vogella.jersey.jaxb                    ;                    import                    javax.xml.bind.annotation.XmlRootElement                    ;                    @XmlRootElement                    // JAX-RS supports an automatic mapping from JAXB annotated form to XML and JSON                    // Isn't that absurd?                    public                    class                    Todo                    {                    private                    Cord                    summary                    ;                    individual                    String                    clarification                    ;                    public                    Cord                    getSummary                    ()                    {                    return                    summary                    ;                    }                    public                    void                    setSummary                    (                    String                    summary                    )                    {                    this                    .                    summary                    =                    summary                    ;                    }                    public                    String                    getDescription                    ()                    {                    return                    description                    ;                    }                    public                    void                    setDescription                    (                    String                    description                    )                    {                    this                    .                    clarification                    =                    description                    ;                    }                    }                                  

Create the following resource class. This class but returns an instance of the Todo class.

                                      bundle                    com.vogella.jersey.jaxb                    ;                    import                    javax.ws.rs.GET                    ;                    import                    javax.ws.rs.Path                    ;                    import                    javax.ws.rs.Produces                    ;                    import                    javax.ws.rs.core.MediaType                    ;                    @Path                    (                    "/todo"                    )                    public                    class                    TodoResource                    {                    // This method is chosen if XML is requested                    @GET                    @Produces                    ({                    MediaType                    .                    APPLICATION_XML                    })                    public                    Todo                    getXML                    ()                    {                    Todo                    todo                    =                    new                    Todo                    ();                    todo                    .                    setSummary                    (                    "Application XML Todo Summary"                    );                    todo                    .                    setDescription                    (                    "Application XML Todo Description"                    );                    render                    todo                    ;                    }                    // This method is chosen if JSON is requested                    @GET                    @Produces                    ({                    MediaType                    .                    APPLICATION_JSON                    })                    public                    Todo                    getJSON                    ()                    {                    Todo                    todo                    =                    new                    Todo                    ();                    todo                    .                    setSummary                    (                    "Application JSON Todo Summary"                    );                    todo                    .                    setDescription                    (                    "Awarding JSON Todo Description"                    );                    return                    todo                    ;                    }                    // This tin can be used to test the integration with the browser                    @Become                    @Produces                    ({                    MediaType                    .                    TEXT_XML                    })                    public                    Todo                    getHTML                    ()                    {                    Todo                    todo                    =                    new                    Todo                    ();                    todo                    .                    setSummary                    (                    "XML Todo Summary"                    );                    todo                    .                    setDescription                    (                    "XML Todo Description"                    );                    return                    todo                    ;                    }                    }                                  

Alter spider web.xml to the following.

                                      <?xml version="1.0" encoding="UTF-8"?>                    <web-app                    xmlns:xsi=                    "http://world wide web.w3.org/2001/XMLSchema-instance"                    xmlns=                    "http://coffee.sun.com/xml/ns/javaee"                    xsi:schemaLocation=                    "http://coffee.lord's day.com/xml/ns/javaee http://java.lord's day.com/xml/ns/javaee/spider web-app_3_0.xsd"                    id=                    "WebApp_ID"                    version=                    "3.0"                    >                    <brandish-name>com.vogella.bailiwick of jersey.jaxb</display-name>                    <servlet>                    <servlet-name>Jersey REST Service</servlet-name>                    <servlet-form>org.glassfish.jersey.servlet.ServletContainer</servlet-class>                    <!-- Register resources and providers nether com.vogella.jersey.first package. -->                    <init-param>                    <param-proper name>jersey.config.server.provider.packages</param-name>                    <param-value>com.vogella.jersey.jaxb</param-value>                    </init-param>                    <load-on-startup>ane</load-on-startup>                    </servlet>                    <servlet-mapping>                    <servlet-proper noun>Bailiwick of jersey REST Service</servlet-name>                    <url-pattern>/rest/*</url-pattern>                    </servlet-mapping>                    </web-app>                                  

Run you lot web awarding in Eclipse and validate that you can access your service. Your awarding should be available under the post-obit URL.

                  http://localhost:8080/com.vogella.bailiwick of jersey.jaxb/residual/todo                

8.3. Create a client

Create a new Java Gradle projection with com.vogella.jersey.jaxbclient every bit top-level bundle name and add the following dependencies to your build.gradle file to import the Jersey dependencies and enable JSON back up.

                  compile 'org.glassfish.jersey.containers:jersey-container-servlet:ii.25.1' compile 'org.glassfish.jersey.media:jersey-media-json-jackson:ii.25.one'                

Create the post-obit exam course.

                                      package                    com.vogella.jersey.jaxbclient                    ;                    import                    coffee.net.URI                    ;                    import                    javax.ws.rs.client.Customer                    ;                    import                    javax.ws.rs.customer.ClientBuilder                    ;                    import                    javax.ws.rs.client.WebTarget                    ;                    import                    javax.ws.rs.core.MediaType                    ;                    import                    javax.ws.rs.cadre.UriBuilder                    ;                    import                    org.glassfish.jersey.client.ClientConfig                    ;                    import                    com.fasterxml.jackson.jaxrs.annotation.JacksonFeatures                    ;                    public                    class                    TodoTest                    {                    public                    static                    void                    main                    (                    String                    []                    args                    )                    {                    ClientConfig                    config                    =                    new                    ClientConfig                    ();                    Customer                    client                    =                    ClientBuilder                    .                    newClient                    (                    config                    );                    WebTarget                    target                    =                    customer                    .                    target                    (                    getBaseURI                    ());                    // Become XML                    Cord                    xmlResponse                    =                    target                    .                    path                    (                    "rest"                    ).                    path                    (                    "todo"                    ).                    request                    ()                    .                    have                    (                    MediaType                    .                    TEXT_XML                    ).                    get                    (                    String                    .                    grade                    );                    // Become XML for application                    Cord                    xmlAppResponse                    =                    target                    .                    path                    (                    "rest"                    ).                    path                    (                    "todo"                    ).                    asking                    ()                    .                    accept                    (                    MediaType                    .                    APPLICATION_XML                    ).                    get                    (                    Cord                    .                    class                    );                    // Go JSON for application                    String                    jsonResponse                    =                    target                    .                    path                    (                    "rest"                    ).                    path                    (                    "todo"                    ).                    request                    ()                    .                    accept                    (                    MediaType                    .                    APPLICATION_JSON                    ).                    go                    (                    String                    .                    class                    );                    Organisation                    .                    out                    .                    println                    (                    xmlResponse                    );                    System                    .                    out                    .                    println                    (                    xmlAppResponse                    );                    System                    .                    out                    .                    println                    (                    jsonResponse                    );                    }                    individual                    static                    URI                    getBaseURI                    ()                    {                    return                    UriBuilder                    .                    fromUri                    (                    "http://localhost:8080/com.vogella.jersey.jaxb"                    ).                    build                    ();                    }                    }                                  

9. CRUD RESTful webservice

This section creates a CRUD (Create, Read, Update, Delete) restful web service. Information technology will allow to maintain a list of TODOs in your spider web application via HTTP calls.

9.i. Project

Create a new Gradle project called com.vogella.jersey.todo with com.vogella.jersey.todo as top-level package name. Add together the post-obit to dependency to your build.gradle file and make likewise sure, that yous enabled Eclipse WTP support past following Required setup for Gradle and Eclipse web projects.

                  compile 'org.glassfish.bailiwick of jersey.containers:jersey-container-servlet:2.25.1' compile 'javax.servlet:javax.servlet-api:4.0.0-b07'                

Change the web.xml file to the following.

                                      <?xml version="1.0" encoding="UTF-8"?>                    <web-app                    xmlns:xsi=                    "http://www.w3.org/2001/XMLSchema-instance"                    xmlns=                    "http://java.sun.com/xml/ns/javaee"                    xsi:schemaLocation=                    "http://java.dominicus.com/xml/ns/javaee http://java.dominicus.com/xml/ns/javaee/web-app_3_0.xsd"                    id=                    "WebApp_ID"                    version=                    "3.0"                    >                    <display-proper noun>com.vogella.jersey.todo</display-name>                    <servlet>                    <servlet-name>Jersey REST Service</servlet-name>                    <servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>                    <!-- Register resources and providers nether com.vogella.jersey.first package. -->                    <init-param>                    <param-name>jersey.config.server.provider.packages</param-name>                    <param-value>com.vogella.bailiwick of jersey.todo</param-value>                    </init-param>                    <load-on-startup>1</load-on-startup>                    </servlet>                    <servlet-mapping>                    <servlet-proper noun>Jersey REST Service</servlet-name>                    <url-blueprint>/remainder/*</url-design>                    </servlet-mapping>                    </spider web-app>                                  

Create the post-obit data model and a Singleton which serves equally the data provider for the model. We use the implementation based on an enumeration. Delight run across the link for details. The Todo class is annotated with a JAXB note. Encounter Java and XML to learn near JAXB.

                                      package                    com.vogella.jersey.todo                    ;                    import                    javax.xml.bind.notation.XmlRootElement                    ;                    @XmlRootElement                    public                    grade                    Todo                    {                    individual                    String                    id                    ;                    private                    String                    summary                    ;                    individual                    String                    description                    ;                    public                    Todo                    (){                    }                    public                    Todo                    (                    Cord                    id                    ,                    String                    summary                    ){                    this                    .                    id                    =                    id                    ;                    this                    .                    summary                    =                    summary                    ;                    }                    public                    Cord                    getId                    ()                    {                    return                    id                    ;                    }                    public                    void                    setId                    (                    Cord                    id                    )                    {                    this                    .                    id                    =                    id                    ;                    }                    public                    Cord                    getSummary                    ()                    {                    return                    summary                    ;                    }                    public                    void                    setSummary                    (                    String                    summary                    )                    {                    this                    .                    summary                    =                    summary                    ;                    }                    public                    Cord                    getDescription                    ()                    {                    render                    description                    ;                    }                    public                    void                    setDescription                    (                    String                    description                    )                    {                    this                    .                    description                    =                    description                    ;                    }                    }                                  
                                      package                    com.vogella.jersey.todo                    ;                    import                    java.util.HashMap                    ;                    import                    java.util.Map                    ;                    import                    com.vogella.bailiwick of jersey.todo.Todo                    ;                    public                    enum                    TodoDao                    {                    example                    ;                    private                    Map                    <                    String                    ,                    Todo                    >                    contentProvider                    =                    new                    HashMap                    <>();                    private                    TodoDao                    ()                    {                    Todo                    todo                    =                    new                    Todo                    (                    "1"                    ,                    "Acquire Remainder"                    );                    todo                    .                    setDescription                    (                    "Read https://world wide web.vogella.com/tutorials/REST/article.html"                    );                    contentProvider                    .                    put                    (                    "i"                    ,                    todo                    );                    todo                    =                    new                    Todo                    (                    "2"                    ,                    "Do something"                    );                    todo                    .                    setDescription                    (                    "Read consummate http://world wide web.vogella.com"                    );                    contentProvider                    .                    put                    (                    "2"                    ,                    todo                    );                    }                    public                    Map                    <                    String                    ,                    Todo                    >                    getModel                    (){                    return                    contentProvider                    ;                    }                    }                                  

9.2. Create a simple HTML class

The REST service can be used via HTML forms. The post-obit HTML form will allow to post new data to the service. Create the following page called create_todo.html in the WebContent folder.

                                      <!DOCTYPE html>                    <html>                    <caput>                    <title>Grade to create a new resources</championship>                    </caput>                    <body>                    <class                    action=                    "../com.vogella.jersey.todo/rest/todos"                    method=                    "POST"                    >                    <characterization                    for=                    "id"                    >ID</label>                    <input                    proper name=                    "id"                    />                    <br/>                    <label                    for=                    "summary"                    >Summary</characterization>                    <input                    proper noun=                    "summary"                    />                    <br/>                    Description:                    <TEXTAREA                    NAME=                    "description"                    COLS=                    40                    ROWS=                    vi                    ></TEXTAREA>                    <br/>                    <input                    type=                    "submit"                    value=                    "Submit"                    />                    </grade>                    </body>                    </html>                                  

9.iii. Rest Service

Create the following classes which will be used as REST resources.

                                      package                    com.vogella.jersey.todo                    ;                    import                    javax.ws.rs.Consumes                    ;                    import                    javax.ws.rs.DELETE                    ;                    import                    javax.ws.rs.GET                    ;                    import                    javax.ws.rs.PUT                    ;                    import                    javax.ws.rs.Produces                    ;                    import                    javax.ws.rs.cadre.Context                    ;                    import                    javax.ws.rs.cadre.MediaType                    ;                    import                    javax.ws.rs.core.Request                    ;                    import                    javax.ws.rs.core.Response                    ;                    import                    javax.ws.rs.core.UriInfo                    ;                    import                    javax.xml.bind.JAXBElement                    ;                    import                    com.vogella.jersey.todo.TodoDao                    ;                    import                    com.vogella.jersey.todo.Todo                    ;                    public                    class                    TodoResource                    {                    @Context                    UriInfo                    uriInfo                    ;                    @Context                    Request                    request                    ;                    String                    id                    ;                    public                    TodoResource                    (                    UriInfo                    uriInfo                    ,                    Request                    request                    ,                    String                    id                    )                    {                    this                    .                    uriInfo                    =                    uriInfo                    ;                    this                    .                    request                    =                    request                    ;                    this                    .                    id                    =                    id                    ;                    }                    //Awarding integration                    @Become                    @Produces                    ({                    MediaType                    .                    APPLICATION_XML                    ,                    MediaType                    .                    APPLICATION_JSON                    })                    public                    Todo                    getTodo                    ()                    {                    Todo                    todo                    =                    TodoDao                    .                    case                    .                    getModel                    ().                    go                    (                    id                    );                    if                    (                    todo                    ==                    null                    )                    throw                    new                    RuntimeException                    (                    "Get: Todo with "                    +                    id                    +                    " not found"                    );                    return                    todo                    ;                    }                    // for the browser                    @Become                    @Produces                    (                    MediaType                    .                    TEXT_XML                    )                    public                    Todo                    getTodoHTML                    ()                    {                    Todo                    todo                    =                    TodoDao                    .                    instance                    .                    getModel                    ().                    get                    (                    id                    );                    if                    (                    todo                    ==                    cypher                    )                    throw                    new                    RuntimeException                    (                    "Become: Todo with "                    +                    id                    +                    " not found"                    );                    render                    todo                    ;                    }                    @PUT                    @Consumes                    (                    MediaType                    .                    APPLICATION_XML                    )                    public                    Response                    putTodo                    (                    JAXBElement                    <                    Todo                    >                    todo                    )                    {                    Todo                    c                    =                    todo                    .                    getValue                    ();                    return                    putAndGetResponse                    (                    c                    );                    }                    @DELETE                    public                    void                    deleteTodo                    ()                    {                    Todo                    c                    =                    TodoDao                    .                    case                    .                    getModel                    ().                    remove                    (                    id                    );                    if                    (                    c                    ==                    nix                    )                    throw                    new                    RuntimeException                    (                    "Delete: Todo with "                    +                    id                    +                    " non found"                    );                    }                    individual                    Response                    putAndGetResponse                    (                    Todo                    todo                    )                    {                    Response                    res                    ;                    if                    (                    TodoDao                    .                    instance                    .                    getModel                    ().                    containsKey                    (                    todo                    .                    getId                    ()))                    {                    res                    =                    Response                    .                    noContent                    ().                    build                    ();                    }                    else                    {                    res                    =                    Response                    .                    created                    (                    uriInfo                    .                    getAbsolutePath                    ()).                    build                    ();                    }                    TodoDao                    .                    case                    .                    getModel                    ().                    put                    (                    todo                    .                    getId                    (),                    todo                    );                    return                    res                    ;                    }                    }                                  
                                      bundle                    com.vogella.jersey.todo                    ;                    import                    java.io.IOException                    ;                    import                    java.util.ArrayList                    ;                    import                    coffee.util.List                    ;                    import                    javax.servlet.http.HttpServletResponse                    ;                    import                    javax.ws.rs.Consumes                    ;                    import                    javax.ws.rs.FormParam                    ;                    import                    javax.ws.rs.GET                    ;                    import                    javax.ws.rs.POST                    ;                    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                    ;                    import                    javax.ws.rs.core.Request                    ;                    import                    javax.ws.rs.core.UriInfo                    ;                    import                    com.vogella.jersey.todo.TodoDao                    ;                    import                    com.vogella.jersey.todo.Todo                    ;                    // Will map the resource to the URL todos                    @Path                    (                    "/todos"                    )                    public                    form                    TodosResource                    {                    // Allows to insert contextual objects into the grade,                    // e.g. ServletContext, Request, Response, UriInfo                    @Context                    UriInfo                    uriInfo                    ;                    @Context                    Request                    request                    ;                    // Return the list of todos to the user in the browser                    @GET                    @Produces                    (                    MediaType                    .                    TEXT_XML                    )                    public                    List                    <                    Todo                    >                    getTodosBrowser                    ()                    {                    Listing                    <                    Todo                    >                    todos                    =                    new                    ArrayList                    <                    Todo                    >();                    todos                    .                    addAll                    (                    TodoDao                    .                    instance                    .                    getModel                    ().                    values                    ());                    return                    todos                    ;                    }                    // Return the listing of todos for applications                    @Go                    @Produces                    ({                    MediaType                    .                    APPLICATION_XML                    ,                    MediaType                    .                    APPLICATION_JSON                    })                    public                    List                    <                    Todo                    >                    getTodos                    ()                    {                    Listing                    <                    Todo                    >                    todos                    =                    new                    ArrayList                    <                    Todo                    >();                    todos                    .                    addAll                    (                    TodoDao                    .                    example                    .                    getModel                    ().                    values                    ());                    render                    todos                    ;                    }                    // retuns the number of todos                    // Apply http://localhost:8080/com.vogella.jersey.todo/remainder/todos/count                    // to go the full number of records                    @Go                    @Path                    (                    "count"                    )                    @Produces                    (                    MediaType                    .                    TEXT_PLAIN                    )                    public                    String                    getCount                    ()                    {                    int                    count                    =                    TodoDao                    .                    instance                    .                    getModel                    ().                    size                    ();                    render                    String                    .                    valueOf                    (                    count                    );                    }                    @Post                    @Produces                    (                    MediaType                    .                    TEXT_HTML                    )                    @Consumes                    (                    MediaType                    .                    APPLICATION_FORM_URLENCODED                    )                    public                    void                    newTodo                    (                    @FormParam                    (                    "id"                    )                    String                    id                    ,                    @FormParam                    (                    "summary"                    )                    String                    summary                    ,                    @FormParam                    (                    "description"                    )                    String                    description                    ,                    @Context                    HttpServletResponse                    servletResponse                    )                    throws                    IOException                    {                    Todo                    todo                    =                    new                    Todo                    (                    id                    ,                    summary                    );                    if                    (                    description                    !=                    null                    )                    {                    todo                    .                    setDescription                    (                    clarification                    );                    }                    TodoDao                    .                    instance                    .                    getModel                    ().                    put                    (                    id                    ,                    todo                    );                    servletResponse                    .                    sendRedirect                    (                    "../create_todo.html"                    );                    }                    // Defines that the next path parameter after todos is                    // treated equally a parameter and passed to the TodoResources                    // Allows to blazon http://localhost:8080/com.vogella.jersey.todo/remainder/todos/1                    // 1 will be treaded as parameter todo and passed to TodoResource                    @Path                    (                    "{todo}"                    )                    public                    TodoResource                    getTodo                    (                    @PathParam                    (                    "todo"                    )                    String                    id                    )                    {                    return                    new                    TodoResource                    (                    uriInfo                    ,                    request                    ,                    id                    );                    }                    }                                  

This TodosResource uses the @PathParam annotation to define that the id is inserted as parameter.

9.4. Run

Run your web application in Eclipse and examination the availability of your Balance service under:

http://localhost:8080/com.vogella.jersey.todo/rest/todos

Yous should encounter the XML representation of your TODO items.

todoserver10

To run across the count of TODO items use

http://localhost:8080/com.vogella.bailiwick of jersey.todo/rest/todos/count

to meet an existing TODO use

http://localhost:8080/com.vogella.bailiwick of jersey.todo/balance/todos/{id}", due east.thousand., http://localhost:8080/com.vogella.jersey.todo/rest/todos/ane

to run across the TODO with ID 1. We currently have only TODOs with the ids 1 and two, all other requests will consequence in an HTTP error lawmaking.

Delight note that with the browser you tin merely issue HTTP GET requests. The adjacent chapter will use the Jersey client libraries to consequence get, mail service and delete.

9.5. Create a client

To test your service you can create a new course in your server projection. This project has already all required libs in the classpath, then this is faster than creating a new project.

Create the following class.

                                      package                    com.vogella.jersey.todo                    ;                    import                    java.net.URI                    ;                    import                    javax.ws.rs.client.Customer                    ;                    import                    javax.ws.rs.client.ClientBuilder                    ;                    import                    javax.ws.rs.client.Entity                    ;                    import                    javax.ws.rs.client.WebTarget                    ;                    import                    javax.ws.rs.core.Form                    ;                    import                    javax.ws.rs.core.MediaType                    ;                    import                    javax.ws.rs.core.Response                    ;                    import                    javax.ws.rs.core.UriBuilder                    ;                    import                    org.glassfish.jersey.client.ClientConfig                    ;                    import                    com.vogella.jersey.todo.Todo                    ;                    public                    class                    Tester                    {                    public                    static                    void                    main                    (                    Cord                    []                    args                    )                    {                    ClientConfig                    config                    =                    new                    ClientConfig                    ();                    Client                    customer                    =                    ClientBuilder                    .                    newClient                    (                    config                    );                    WebTarget                    service                    =                    customer                    .                    target                    (                    getBaseURI                    ());                    // create one todo                    Todo                    todo                    =                    new                    Todo                    (                    "iii"                    ,                    "Blabla"                    );                    Response                    response                    =                    service                    .                    path                    (                    "rest"                    ).                    path                    (                    "todos"                    ).                    path                    (                    todo                    .                    getId                    ()).                    request                    (                    MediaType                    .                    APPLICATION_XML                    ).                    put                    (                    Entity                    .                    entity                    (                    todo                    ,                    MediaType                    .                    APPLICATION_XML                    ),                    Response                    .                    class                    );                    // Render code should be 201 == created resources                    System                    .                    out                    .                    println                    (                    response                    .                    getStatus                    ());                    // Become the Todos                    System                    .                    out                    .                    println                    (                    service                    .                    path                    (                    "residual"                    ).                    path                    (                    "todos"                    ).                    request                    ().                    accept                    (                    MediaType                    .                    TEXT_XML                    ).                    become                    (                    String                    .                    class                    ));                    //    // Get JSON for application (Make sure to add together the jersey-media-json-jackson dependency to add support for JSON)                    //    System.out.println(service.path("rest").path("todos").request().accept(MediaType.APPLICATION_JSON).get(String.form));                    // Become XML for application                    System                    .                    out                    .                    println                    (                    service                    .                    path                    (                    "rest"                    ).                    path                    (                    "todos"                    ).                    request                    ().                    accept                    (                    MediaType                    .                    APPLICATION_XML                    ).                    get                    (                    Cord                    .                    grade                    ));                    //Get Todo with id 1                    Response                    checkDelete                    =                    service                    .                    path                    (                    "rest"                    ).                    path                    (                    "todos/1"                    ).                    request                    ().                    have                    (                    MediaType                    .                    APPLICATION_XML                    ).                    get                    ();                    //Delete Todo with id 1                    service                    .                    path                    (                    "rest"                    ).                    path                    (                    "todos/1"                    ).                    asking                    ().                    delete                    ();                    //Get get all Todos id 1 should exist deleted                    Arrangement                    .                    out                    .                    println                    (                    service                    .                    path                    (                    "rest"                    ).                    path                    (                    "todos"                    ).                    request                    ().                    take                    (                    MediaType                    .                    APPLICATION_XML                    ).                    get                    (                    Cord                    .                    form                    ));                    //Create a Todo                    Form                    grade                    =                    new                    Course                    ();                    course                    .                    param                    (                    "id"                    ,                    "iv"                    );                    course                    .                    param                    (                    "summary"                    ,                    "Demonstration of the customer lib for forms"                    );                    response                    =                    service                    .                    path                    (                    "rest"                    ).                    path                    (                    "todos"                    ).                    request                    ().                    post                    (                    Entity                    .                    entity                    (                    form                    ,                    MediaType                    .                    APPLICATION_FORM_URLENCODED                    ),                    Response                    .                    class                    );                    System                    .                    out                    .                    println                    (                    "Form response "                    +                    response                    .                    getStatus                    ());                    //Get all the todos, id 4 should have been created                    Arrangement                    .                    out                    .                    println                    (                    service                    .                    path                    (                    "rest"                    ).                    path                    (                    "todos"                    ).                    request                    ().                    accept                    (                    MediaType                    .                    APPLICATION_XML                    ).                    get                    (                    String                    .                    class                    ));                    }                    individual                    static                    URI                    getBaseURI                    ()                    {                    return                    UriBuilder                    .                    fromUri                    (                    "http://localhost:8080/com.vogella.jersey.todo"                    ).                    build                    ();                    }                    }                                  

nine.6. Using the Residue service via HTML page

The above instance contains a form which calls a postal service method of your residual service.