Skip to main content

REST Service on JBoss 7 (using RESTEasy) - Part 3

In the last post we learnt how to output JSON from a REST service. Here is the sample JSON output that we got in the last post.

[
    {
        "name": "Java The Complete Reference, 8th Edition",
        "author": "Herbert Schildt",
        "price": 479
    },
    {
        "name": "Jboss As 7 Configuration, Deployment, And Administration",
        "author": "Francesco Marchioni",
        "price": 450
    },
    {
        "name": "RESTful Java with JAX-RS 2.0 2ed",
        "author": "Bill Burke",
        "price": 2018
    }
]

RESTEasy (default JAX-RS provider for JBoss AS 7) uses Jackson as the JSON provider. What if your clients are using Jettison for parsing the response from your REST service?

Hold on. What is the difference between Jackson and Jettison? Here are a few differences.
  • Jettison relies on JAXB annotation (such as @XmlRootElememt); doesnt need any JSON specific annotation. Jackson uses its own annotations (such as @JsonIgnore, etc). What this means is, by simply using JAXB annotation you will be able to generate same response in XML and JSON format if you use Jettison. You need additional annotations to achieve this if you use Jackson.
  • Jettison produces XML compliant JSON content; Jackson does not. If you look at the above JSON, there is no root element (remember a valid XML document requires one root element)
Output produced by one of them, can't be consumed by the other.

Many times you may not have the control over what your clients use. Let's see how we can use Jettison as our JSON provider.

1. Since we needed a root element, let add a class to wrap the list of books. Let's call it as BookResponse. Copy paste the following contents into it.
package org.jbosstest.jbosstest;

import java.io.Serializable;
import java.util.List;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElementWrapper;
import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement(name = "bookResponse")
public class BookResponse implements Serializable {

    private List<Book> books;

    public BookResponse() {
    }

    public BookResponse(List<Book> books) {
        this.books = books;
    }

    @XmlElementWrapper(name = "books")
    @XmlElement(name = "book")
    public List<Book> getBooks() {
        return books;
    }

    public void setBooks(List<Book> books) {
        this.books = books;
    }
}

2. Modify the Book class as below
package org.jbosstest.jbosstest;

import java.io.Serializable;
import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement(name = "book")
public class Book implements Serializable {

    private String name;
    private String author;
    private float price;

    public Book() {
    }

    public Book(String name, String author, float price) {
        this.name = name;
        this.author = author;
        this.price = price;

    }

    // getter-setter methods
}

3. Modify the LibraryService class as follows.
package org.jbosstest.jbosstest;

import java.util.ArrayList;
import java.util.List;
import javax.ejb.LocalBean;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;

@LocalBean
@Path("/library")
public class LibraryService {

    @GET
    @Path("available-books")
    @Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
    public BookResponse getAvailableBooks() {
        List<Book> books = new ArrayList<Book>();
        books.add(new Book("Java The Complete Reference, 8th Edition", "Herbert Schildt", 479));
        books.add(new Book("Jboss As 7 Configuration, Deployment, And Administration", "Francesco Marchioni", 450));
        books.add(new Book("RESTful Java with JAX-RS 2.0 2ed", "Bill Burke", 2018));
        return new BookResponse(books);
    }
}

4. Now we need to include Jettison and exclude Jackson from the list of providers. Create a file called jboss-deployment-structure.xml under WEB-INF folder and paste the following contents into it.
<?xml version="1.0" encoding="UTF-8"?>

<jboss-deployment-structure  xmlns="urn:jboss:deployment-structure:1.2">
    <deployment>
        <exclusions>
            <module name="org.jboss.resteasy.resteasy-jackson-provider"/>
        </exclusions>
        <dependencies>
            <module name="org.jboss.resteasy.resteasy-jaxb-provider" services="import"/>
            <module name="org.jboss.resteasy.resteasy-jettison-provider" services="import"/>
            <module name="org.codehaus.jettison"/>
        </dependencies>
    </deployment>
</jboss-deployment-structure>


5. Build and run the project.
6. This time let's use postman, a chrome/chromium plugin, to test both JSON and XML output. So let's open chromium postman as follows and specify accept-header value as application/xml and the URL as http://localhost:8080/JbossTest/webresources/library/available-books and hit Send.



 7. Change the accept-header value to application/json and hit Send again.

 



Comments

  1. Many Umrah Packages include guided tours to historical and religious sites. These tours provide valuable insights into the cultural and historical significance of the places visited.

    ReplyDelete

Post a Comment

Popular posts from this blog

Installing GoDaddy certificate in Wildfly/Keycloak

In the previous post we saw how to set up Keycloak . Here we will see how to generate and install GoDaddy.com certificate in Keycloak. The steps are similar for Wildfly as well. Step 1: Generate CSR file Run the following commands in your terminal. <mydomain.com> has to be replaced with your actual domain name. keytool -genkey -alias mydomain_com -keyalg RSA -keysize 2048 -keystore mydomain_com.jks keytool -certreq -alias mydomain_com -file mydomain_com.csr -keystore mydomain_com.jks Step 2: Generate certificate Upload  mydomain_com . csr  file content into GoDaddy.com, generate and download certificate for tomcat server (steps to generating SSL certificate is beyond the scope of this article). If you unzip the file, you will see the following files. gd_bundle-g2-g1.crt ..5f8c...3a89.crt   #some file with alphanumeric name gdig2.crt Files 1 and 2 are of our interest. Third file is not required. Step 3: Import certificate to key store Download r

Using Nginx as proxy server for Keycloak

I have used Keycloak  in its very early stage ( when it is was in 2.x version). But now it has come a long way (at this time of writing it is in 21.x) In this article let's configure Keycloak behind Nginx. Here are the points to consider.  If you want to configure Apache2 as a proxy server for your java application, please check  this article . We are going to use a domain name other than localhost Anything other than localhost will require Keycloak to run in production mode which requires SSL configurations etc. Or it requires a proxy server. Lets begin. Requirements Keycloak distribution Ubuntu 22.04 server Configuring Keycloak 1. Download Keycloak from here . 2. Extract it using tar -xvzf  keycloak-21.0.1.tar.gz 3. Create a script file called keycloak.sh with the following contents #!/bin/bash export KEYCLOAK_ADMIN=<admin-username-here> export KEYCLOAK_ADMIN_PASSWORD=<admin-password-here> nohup keycloak-21.0.0/bin/kc.sh start-dev --proxy edge --hostname-strict=fa

Hibernate & Postgresql

If you are using Hibernate 3.5 or above to talk to Postgresql database, have you ever tried to store a byte array? Let's take an example. Here is the mapping which will store and read byte[] from the database. @Lob @Column(name = "image") private byte[] image; Here is the JPA mapping file configuration. <persistence version="2.0"  xmlns="http://java.sun.com/xml/ns/persistence"  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">   <persistence-unit name="testPU" transaction-type="JTA">     <provider>org.hibernate.ejb.HibernatePersistence</provider>     <jta-data-source>test</jta-data-source>     <properties>     </properties>   </persistence-unit> </persistence> When you try to save your entity you will get t

Dynamic SOAP Service Client

If you have written SOAP service client, you might know that you need the WSDL file; need to generate Java code for that,compile that Java classes and add it as dependency for your module. What would you do if you have to incorporate your code with a new SOAP service every now and then? What would you do if all you need is to consume the service and do a little processing on the output, i.e., you need the data in XML format? What would you do if you don't have a complete WSDL? What would you do if your service is in .NET whose WSDL is having problem while generating Java classes? Is there a way to write a dynamic client which can consume any SOAP service? .... YES!... there is a way. Let's quickly write a web (SOAP) service. Software used: Java 7 NetBeans IDE 7.4 GlassFish 4.0 Maven Create a web project and choose Glassfish as server. Now add web service (not a rest service) as below. Edit the SimpleService.java as follows. package com.mycom

REST Service on JBoss 7 (using CXF) - Part 4

In the last three posts we have been seeing how to host a RESTful service on JBoss 7 by defaulting to the container implementation of JAX-RS, i.e., RESTEasy . However you can use any other implementation with JBoss 7. In fact JBoss 7 itself uses RESTEasy as JAX-RS (RESTful service) implementation and CXF as JAX-WS (SOAP service) implementation. But what you will miss if you use other implementations such as CXF or other containers such as Spring , is the container management/injection. That is, you can inject any resource such as CDI bean, EJB, Persistence context, transaction, etc into our LibraryService (using annotation/xml configuration) that we saw in the last post . Where as you need to lookup them manually if you use CXF or use any other dependency injection provider such as Spring. Generally it is less hassle to leave it to the app server to manage these resources; but if you dont have a choice (when other teams are using different library or the feature you need is not sup