RESTEasy + JBOSS 7 Hello world application

RESTEasy is JBOSS provided implementation of JAX-RS specification for building RESTful Web Services and RESTful Java applications. Though this is not limited to be used in JBOSS only, and you can use with other servers also. In this post, I am building such a hello world application in JBOSS AS7 server.

Environment used:

  1. RESTEasy 2.3.1.GA
  2. Jboss AS7
  3. JDK 1.6

Follow below steps to build a demo application.

1) Create a maven project and convert to eclipse web project

mvn archetype:generate -DgroupId=com.howtodoinjava -DartifactId=RESTfulDemoApplication 
-DarchetypeArtifactId=maven-archetype-webapp -DinteractiveMode=false

mvn eclipse:eclipse -Dwtpversion=2.0

2) Update runtime dependencies in pom.xml

You need to define only compile time dependencies. Even better, if you can identify and include the jars from jboss distribution package.

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.howtodoinjava</groupId>
  <artifactId>RESTfulDemoApplication</artifactId>
  <packaging>war</packaging>
  <version>1.0-SNAPSHOT</version>
  <name>RESTfulDemoApplication Maven Webapp</name>
  <url>http://maven.apache.org</url>
  	<repositories>
	   	<repository>
	      <id>jboss</id>
	      <url>http://repository.jboss.org/maven2</url>
	   	</repository>
	</repositories>
  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>
    <!-- core library -->
	<dependency>
		<groupId>org.jboss.resteasy</groupId>
		 <artifactId>resteasy-jaxrs</artifactId>
		<version>2.3.1.GA</version>
		<scope>compile</scope>
	</dependency>
   <!-- JAXB support -->
   <dependency>
      <groupId>org.jboss.resteasy</groupId>
      	<artifactId>resteasy-jaxb-provider</artifactId>
      <version>2.3.1.GA</version>
      <scope>compile</scope>
   </dependency>
   <!-- multipart/form-data and multipart/mixed support -->
   <dependency>
      <groupId>org.jboss.resteasy</groupId>
      	<artifactId>resteasy-multipart-provider</artifactId>
      <version>2.3.1.GA</version>
      <scope>compile</scope>
   </dependency>
   <dependency>
		<groupId>net.sf.scannotation</groupId>
		<artifactId>scannotation</artifactId>
		<version>1.0.2</version>
		<scope>compile</scope>
	</dependency>
  </dependencies>
  <build>
    <finalName>RESTfulDemoApplication</finalName>
  </build>
</project>

3) Create a blank web.xml file

JBOSS’s inbuilt support RESTeasy makes it a perfect combo for RESTFul web application. The minimum configuration to build such application is none. Yes, a blank web.xml file.

<!DOCTYPE web-app PUBLIC
 "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
 "http://java.sun.com/dtd/web-app_2_3.dtd" >

<web-app>
  <display-name>Restful Web Application</display-name>
</web-app>

5) Register the application path

You will need to extend javax.ws.rs.core.Application class and provide @ApplicationPath annotation.

<img src="//howtodoinjava.com/wp-content/uploads/jboss+resteasy1.png" alt="JBOSS 7+ RESTEasy demo application" width="453" height="225" class="size-full wp-image-2033" /> JBOSS 7+ RESTEasy demo applicationpackage com.howtodoinjava;

import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;

import javax.ws.rs.ApplicationPath;
import javax.ws.rs.core.Application;

import com.howtodoinjava.service.UserService;

@ApplicationPath("/")
public class ApplicationConfig extends Application {
    @SuppressWarnings("unchecked")
	public Set<Class<?>> getClasses() {
        return new HashSet<Class<?>>(Arrays.asList(UserService.class));
    }
}

4) Write a service class having @Path annotations

package com.howtodoinjava.service;

import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;

import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.DefaultValue;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Response;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

import com.howtodoinjava.model.User;
import com.howtodoinjava.model.Users;

@XmlAccessorType(XmlAccessType.NONE)
@XmlRootElement(name = "user-management")
@Path("/user-management")
public class UserService {
	@XmlElement(name = "users")
	private String uri1 = "/user-management/users";

	@XmlElement(name = "report")
	private String uri2 = "/user-managemet/generate-report";

	public String getUri1() {
		return uri1;
	}

	public void setUri1(String uri1) {
		this.uri1 = uri1;
	}

	public String getUri2() {
		return uri2;
	}

	public void setUri2(String uri2) {
		this.uri2 = uri2;
	}

	@GET
	@Path("/")
	@Produces("application/vnd.com.demo.user-management+xml;charset=UTF-8;version=1")
	public UserService getServiceInfo() {
		return new UserService();
	}

	@GET
	@Path("/users")
	@Produces("application/vnd.com.demo.user-management.users+xml;charset=UTF-8;version=1")
	public Users getAllUsers() {
		User user1 = new User();
		user1.setId(1);
		user1.setFirstName("demo");
		user1.setLastName("user");
		user1.setUri("/user-management/users/1");

		User user2 = new User();
		user2.setId(2);
		user2.setFirstName("demo");
		user2.setLastName("user");
		user2.setUri("/user-management/users/2");

		Users users = new Users();
		users.setUsers(new ArrayList<User>());
		users.getUsers().add(user1);
		users.getUsers().add(user2);

		return users;
	}

	@GET
	@Path("/users/{id}")
	@Produces("application/vnd.com.demo.user-management.user+xml;charset=UTF-8;version=1")
	public User getUserById(@PathParam("id") int id) {
		User user = new User();
		user.setId(id);
		user.setFirstName("demo");
		user.setLastName("user");
		user.setUri("/user-management/users/" + id);
		return user;
	}

	@POST
	@Path("/users")
	@Consumes("application/vnd.com.demo.user-management.user+xml;charset=UTF-8;version=1")
	public Response createUser(User user,
			@DefaultValue("false") @QueryParam("allow-admin") boolean allowAdmin)
			throws URISyntaxException {
		System.out.println(user.getFirstName());
		System.out.println(user.getLastName());
		return Response.status(201)
				.contentLocation(new URI("/user-management/users/123")).build();
	}

	@PUT
	// @Path("/users/{id: [0-9]*}")
	@Path("/users/{id}")
	@Consumes("application/vnd.com.demo.user-management.user+xml;charset=UTF-8;version=1")
	@Produces("application/vnd.com.demo.user-management.user+xml;charset=UTF-8;version=1")
	public User updateUser(@PathParam("id") int id, User user)
			throws URISyntaxException {
		user.setId(id);
		user.setFirstName(user.getFirstName() + "updated");
		return user;
	}

	@DELETE
	@Path("/users/{id}")
	public Response deleteUser(@PathParam("id") int id)
			throws URISyntaxException {
		return Response.status(200).build();
	}
}

5) Run the application

When we deploy above built application in jboss and hit the URL: ” http://localhost:8080/RESTfulDemoApplication/user-management/users”, below is the response.

JBOSS 7+ RESTEasy demo application

JBOSS 7+ RESTEasy demo application

To download the source code of above example, click below link.

Download Source code

Happy Learning !!

Was this post helpful?

Join 7000+ Fellow Programmers

Subscribe to get new post notifications, industry updates, best practices, and much more. Directly into your inbox, for free.

17 thoughts on “RESTEasy + JBOSS 7 Hello world application”

  1. The application was deployed in JBoss eap 7.2 without any errors how ever, the rest endpoints are throwing 404, do we have to perform any setting to run these examples?

    Reply
  2. hi
    works fine..but i’m confusing with following things
    can you explain this line.no idea about the generated xml filename
    “application/vnd.com.demo.user-management.user+xml;charset=UTF-8;version=1”

    and why need “scannotation” dependency here and is it fine with jakson + restaesy

    why you use ApplicationConfig class over a listener and what is the reason for doing that

    and why servlet mappings and listeners are not required here

    and where you register your restful services

    please explain me as I am new to rest and there are may be alternative ways to do those stuffs which I’m not aware.

    thanks..!!!

    Reply
    • 1) The Scannotation library searches the class path using another library known as javassist to read class files looking for annotations. It literally reads every class in the class path so that there is no requirement to explicitly load the class first.
      2) In ApplicationConfig, I am registering the services. “javax.ws.rs.core.Application” needs that if you are configuring application using annotations only.
      3) why servlet mappings and listeners are not required here?? Because everything is/can be configured using annotations. Scannotation does it for you by scanning all classes for annotations.

      Reply
  3. when i call your service from jquery it gives me this error

    var request = {
    “countryid”:”12″,
    “countryname”:”india”
    };
    var jsondata = JSON.stringify(request);

    $.ajax({
    url: “http://localhost:8080/RESTfulDemoApplication/restservice/manage/post”,
    type: “POST”,
    data: jsondata,
    dataType: “html”,
    success: function (result) {
    $(‘#contactForm’).html(result);
    },
    error: function (jqXHR, tranStatus, errorThrown) {
    $(‘#contactForm’).html(“POST Error! Browser may not support”);
    }
    });

    XMLHttpRequest cannot load http://localhost:8080/RESTfulDemoApplication/restservice/manage/post. No ‘Access-Control-Allow-Origin’ header is present on the requested resource. Origin ‘null’ is therefore not allowed access.

    Reply
  4. Hi Lokesh, when I try to create a maven project, I get following errors

    [WARNING] The POM for org.apache.maven.plugins:maven-clean-plugin:jar:2.5 is missing, no dependency information available
    [WARNING] Failed to retrieve plugin descriptor for org.apache.maven.plugins:maven-clean-plugin:2.5: Plugin org.apache.maven.plugins:maven-clean-plugin:2.5 or one of its dependencies could not be resolved: Failure to find org.apache.maven.plugins:maven-clean-plugin:jar:2.5 in http://repo.maven.apache.org:80/maven2/ was cached in the local repository, resolution will not be reattempted until the update interval of central has elapsed or updates are forced
    [WARNING] The POM for org.apache.maven.plugins:maven-install-plugin:jar:2.4 is missing, no dependency information available
    [WARNING] Failed to retrieve plugin descriptor for org.apache.maven.plugins:maven-install-plugin:2.4: Plugin org.apache.maven.plugins:maven-install-plugin:2.4 or one of its dependencies could not be resolved: Failure to find org.apache.maven.plugins:maven-install-plugin:jar:2.4 in http://repo.maven.apache.org:80/maven2/ was cached in the local repository, resolution will not be reattempted until the update interval of central has elapsed or updates are forced
    [WARNING] The POM for org.apache.maven.plugins:maven-resources-plugin:jar:2.6 is missing, no dependency information available
    [WARNING] Failed to retrieve plugin descriptor for org.apache.maven.plugins:maven-resources-plugin:2.6: Plugin org.apache.maven.plugins:maven-resources-plugin:2.6 or one of its dependencies could not be resolved: Failure to find org.apache.maven.plugins:maven-resources-plugin:jar:2.6 in http://repo.maven.apache.org:80/maven2/ was cached in the local repository, resolution will not be reattempted until the update interval of central has elapsed or updates are forced
    [WARNING] The POM for org.apache.maven.plugins:maven-surefire-plugin:jar:2.12.4 is missing, no dependency information available
    [WARNING] Failed to retrieve plugin descriptor for org.apache.maven.plugins:maven-surefire-plugin:2.12.4: Plugin org.apache.maven.plugins:maven-surefire-plugin:2.12.4 or one of its dependencies could not be resolved: Failure to find org.apache.maven.plugins:maven-surefire-plugin:jar:2.12.4 in http://repo.maven.apache.org:80/maven2/ was cached in the local repository, resolution will not be reattempted until the update interval of central has elapsed or updates are forced
    [WARNING] The POM for org.apache.maven.plugins:maven-compiler-plugin:jar:2.5.1 is missing, no dependency information available
    [WARNING] Failed to retrieve plugin descriptor for org.apache.maven.plugins:maven-compiler-plugin:2.5.1: Plugin org.apache.maven.plugins:maven-compiler-plugin:2.5.1 or one of its dependencies could not be resolved: Failure to find org.apache.maven.plugins:maven-compiler-plugin:jar:2.5.1 in http://repo.maven.apache.org:80/maven2/ was cached in the local repository, resolution will not be reattempted until the update interval of central has elapsed or updates are forced
    [WARNING] The POM for org.apache.maven.plugins:maven-war-plugin:jar:2.2 is missing, no dependency information available
    [WARNING] Failed to retrieve plugin descriptor for org.apache.maven.plugins:maven-war-plugin:2.2: Plugin org.apache.maven.plugins:maven-war-plugin:2.2 or one of its dependencies could not be resolved: Failure to find org.apache.maven.plugins:maven-war-plugin:jar:2.2 in http://repo.maven.apache.org:80/maven2/ was cached in the local repository, resolution will not be reattempted until the update interval of central has elapsed or updates are forced
    [WARNING] The POM for org.apache.maven.plugins:maven-deploy-plugin:jar:2.7 is missing, no dependency information available
    [WARNING] Failed to retrieve plugin descriptor for org.apache.maven.plugins:maven-deploy-plugin:2.7: Plugin org.apache.maven.plugins:maven-deploy-plugin:2.7 or one of its dependencies could not be resolved: Failure to find org.apache.maven.plugins:maven-deploy-plugin:jar:2.7 in http://repo.maven.apache.org:80/maven2/ was cached in the local repository, resolution will not be reattempted until the update interval of central has elapsed or updates are forced
    [WARNING] The POM for org.apache.maven.plugins:maven-site-plugin:jar:3.3 is missing, no dependency information available
    [WARNING] Failed to retrieve plugin descriptor for org.apache.maven.plugins:maven-site-plugin:3.3: Plugin org.apache.maven.plugins:maven-site-plugin:3.3 or one of its dependencies could not be resolved: Failure to find org.apache.maven.plugins:maven-site-plugin:jar:3.3 in http://repo.maven.apache.org:80/maven2/ was cached in the local repository, resolution will not be reattempted until the update interval of central has elapsed or updates are forced
    [WARNING] The POM for org.apache.maven.plugins:maven-antrun-plugin:jar:1.3 is missing, no dependency information available
    [WARNING] Failed to retrieve plugin descriptor for org.apache.maven.plugins:maven-antrun-plugin:1.3: Plugin org.apache.maven.plugins:maven-antrun-plugin:1.3 or one of its dependencies could not be resolved: Failure to find org.apache.maven.plugins:maven-antrun-plugin:jar:1.3 in http://repo.maven.apache.org:80/maven2/ was cached in the local repository, resolution will not be reattempted until the update interval of central has elapsed or updates are forced
    [WARNING] The POM for org.apache.maven.plugins:maven-assembly-plugin:jar:2.2-beta-5 is missing, no dependency information available
    [WARNING] Failed to retrieve plugin descriptor for org.apache.maven.plugins:maven-assembly-plugin:2.2-beta-5: Plugin org.apache.maven.plugins:maven-assembly-plugin:2.2-beta-5 or one of its dependencies could not be resolved: Failure to find org.apache.maven.plugins:maven-assembly-plugin:jar:2.2-beta-5 in http://repo.maven.apache.org:80/maven2/ was cached in the local repository, resolution will not be reattempted until the update interval of central has elapsed or updates are forced
    [WARNING] The POM for org.apache.maven.plugins:maven-dependency-plugin:jar:2.8 is missing, no dependency information available
    [WARNING] Failed to retrieve plugin descriptor for org.apache.maven.plugins:maven-dependency-plugin:2.8: Plugin org.apache.maven.plugins:maven-dependency-plugin:2.8 or one of its dependencies could not be resolved: Failure to find org.apache.maven.plugins:maven-dependency-plugin:jar:2.8 in http://repo.maven.apache.org:80/maven2/ was cached in the local repository, resolution will not be reattempted until the update interval of central has elapsed or updates are forced
    [WARNING] The POM for org.apache.maven.plugins:maven-release-plugin:jar:2.3.2 is missing, no dependency information available
    [WARNING] Failed to retrieve plugin descriptor for org.apache.maven.plugins:maven-release-plugin:2.3.2: Plugin org.apache.maven.plugins:maven-release-plugin:2.3.2 or one of its dependencies could not be resolved: Failure to find org.apache.maven.plugins:maven-release-plugin:jar:2.3.2 in http://repo.maven.apache.org:80/maven2/ was cached in the local repository, resolution will not be reattempted until the update interval of central has elapsed or updates are forced
    Downloading: http://repo.maven.apache.org/maven2/org/codehaus/mojo/maven-metadata.xml
    Downloading: http://repo.maven.apache.org/maven2/org/apache/maven/plugins/maven-metadata.xml

    BR//Sunny

    Reply
  5. Hello,

    Do you have a tutorial on how to incorporate RestEasy into an EAR file and allow pass through from the URL directly to the EJB 3?

    That would help me a lot. I can’t find a lot of information on that.

    Thanks.

    Reply
    • “RestEasy into an EAR file” : Can’t understand what you really want. If any app uses RESTeasy and we make either .war file or .ear file, how RESTEasy will make any difference. So, .ear is more packaging specific. How to build application? There are plenty of tutorials in this blog.

      “From URL directly to the EJB 3” : RESTEasy works at view layer. Once you get the request with proper parameters passed in input, you are free to pass them to EJB or DAO or wherever you want.

      Am I making sense?

      Reply
  6. Include the below in the web.xml — and it should fix your 404 problem

    Restful Web Application

    resteasy.document.expand.entity.references
    false

    org.jboss.resteasy.plugins.server.servlet.ResteasyBootstrap

    Resteasy
    org.jboss.resteasy.plugins.server.servlet.HttpServletDispatcher

    javax.ws.rs.Application
    com.howtodoinjava.ApplicationConfig

    Resteasy
    /user-management/*

    Reply
  7. Hi….I got HTTP STATUS 404 message:

    HTTP Status 404 – /RESTfulDemoApplication/user-management/users
    type Status report
    message /RESTfulDemoApplication/user-management/users
    description The requested resource (/RESTfulDemoApplication/user-management/users) is not available.

    What should I do?

    Reply

Leave a Comment

HowToDoInJava

A blog about Java and its related technologies, the best practices, algorithms, interview questions, scripting languages, and Python.