Integrating Jetty with RESTEasy - java

Any links on how to integrate Jetty and RESTEasy? I am kinda stuck trying to configure RESTEasy with Jetty together....and there seems to be no credible help on the web.
public static void main(String[] args) throws Exception
{
Server server = new Server(8080);
WebAppContext context = new WebAppContext();
context.setDescriptor("../WEB-INF/web.xml");
context.setResourceBase("../src/webapp");
context.setContextPath("/");
context.setParentLoaderPriority(true);
server.setHandler(context);
server.start();
server.join();
}
My Web.xml is copied directly from:
http://docs.jboss.org/resteasy/docs/1.0.0.GA/userguide/html/Installation_Configuration.html
The error I get back is a HTTP 404 when I try to open up a link in my resource file. Everything looks reasonable on the surface, any suggestions?
My resource file looks like:
package webapp;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
#Path("/*")
public class Resource {
#GET
public String hello() {
return "hello";
}
#GET
#Path("/books")
public String getBooks() {
return "books";
}
#GET
#Path("/book/{isbn}")
public String getBook(#PathParam("isbn") String id) {
return "11123";
}
}
This is the prints that I see when Jetty starts up:
2012-04-10 09:54:27.163:INFO:oejs.Server:jetty-8.1.1.v20120215 2012-04-10 09:54:27.288:INFO:oejw.StandardDescriptorProcessor:NO JSP Support for /, did not find org.apache.jasper.servlet.JspServlet 2012-04-10 09:54:27.319:INFO:oejsh.ContextHandler:started o.e.j.w.WebAppContext{/,file:/C:/Users/xyz/Anotherproj1/src/webapp} 2012-04-10 09:54:27.319:INFO:oejsh.ContextHandler:started o.e.j.w.WebAppContext{/,file:/C:/Users/xyz/Anotherproj1/src/webapp} 2012-04-10 09:54:27.381:INFO:oejs.AbstractConnector:Started SelectChannelConnector#0.0.0.0:8080

The follwing works for me:
web.xml:
<web-app xmlns:javaee="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<context-param>
<param-name>resteasy.scan</param-name>
<param-value>true</param-value>
</context-param>
<context-param>
<param-name>resteasy.resources</param-name>
<param-value>webapp.Resource</param-value>
</context-param>
<context-param>
<param-name>javax.ws.rs.core.Application</param-name>
<param-value>webapp.MyApplicationConfig</param-value>
</context-param>
<!-- set this if you map the Resteasy servlet to something other than /*
<context-param>
<param-name>resteasy.servlet.mapping.prefix</param-name>
<param-value>/resteasy</param-value>
</context-param>
-->
<!-- if you are using Spring, Seam or EJB as your component model, remove the ResourceMethodSecurityInterceptor -->
<context-param>
<param-name>resteasy.resource.method-interceptors</param-name>
<param-value>
org.jboss.resteasy.core.ResourceMethodSecurityInterceptor
</param-value>
</context-param>
<listener>
<listener-class>org.jboss.resteasy.plugins.server.servlet.ResteasyBootstrap</listener-class>
</listener>
<servlet>
<servlet-name>Resteasy</servlet-name>
<servlet-class>org.jboss.resteasy.plugins.server.servlet.HttpServletDispatcher</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Resteasy</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
</web-app>
With
public class MyApplicationConfig extends Application {
private static final Set<Class<?>> CLASSES;
static {
HashSet<Class<?>> tmp = new HashSet<Class<?>>();
tmp.add(Resource.class);
CLASSES = Collections.unmodifiableSet(tmp);
}
#Override
public Set<Class<?>> getClasses(){
return CLASSES;
}
}
Resource
package webapp;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
#Path("/")
#Produces("text/plain")
public class Resource {
#GET
public String hello() {
return "hello";
}
#GET
#Path("/books")
public String getBooks() {
return "books";
}
#GET
#Path("/book/{isbn}")
public String getBook(#PathParam("isbn") String id) {
return "11123";
}
}
and Main Class
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.webapp.WebAppContext;
import org.jboss.resteasy.plugins.server.servlet.ResteasyBootstrap;
public class Main {
public static void main(String[] args) throws Exception
{
Server server = new Server(8080);
WebAppContext context = new WebAppContext();
context.setDescriptor("./src/main/webapp/WEB-INF/web.xml");
context.setResourceBase("./src/main/webapp");
context.setContextPath("/");
context.setParentLoaderPriority(true);
server.setHandler(context);
server.start();
server.join();
}
}

Are you sure that #Path("/*") is correct path. Try #Path("/") maybe this * is a problem. As far as I know path expressions does not accept regexps.
EDIT
I was wrong, you can use regexps in #Path, at least RESTEasy supports that.

To get RESTEasy and Jetty to work together without a web.xml ensure you have a dependency on resteasy-servlet-initializer in your pom.xml.
This may help (JBoss RESTEasy documentation): https://docs.jboss.org/resteasy/docs/3.0.4.Final/userguide/html/Installation_Configuration.html#d4e111

Related

Add a Controller class to a Servlet using Jersey Annotation getting 404

In the web.xml is defined this servlet mapping:
<servlet>
<servlet-name>JAX-RS External REST Servlet</servlet-name>
<servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
<init-param>
<param-name>javax.ws.rs.Application</param-name>
<param-value>xxx.rest.external.XxxExternalRestApplication</param-value>
</init-param>
<init-param>
<param-name>com.sun.jersey.config.feature.DisableWADL</param-name>
<param-value>true</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>JAX-RS External REST Servlet</servlet-name>
<url-pattern>/external/rest/*</url-pattern>
</servlet-mapping>
I cannot modify the web.xml.
I have created a WebAppplicationInitializer in order to get the registered Servlet on the path /external/rest
Here is the code:
package com.xxx.extended.base.config.sailpoint;
import com.xxx.extended.controllers.IRestControllerMarker;
import com.xxx.extended.controllers.LocalManagedEntitlementsRestController;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.glassfish.jersey.server.ServerProperties;
import org.glassfish.jersey.servlet.ServletProperties;
import org.springframework.web.WebApplicationInitializer;
import javax.servlet.ServletContext;
/**
* Uses to extend parameter of external rest api to include custom controllers
*/
public class XxxExternalRestWebApplicationInitializer implements WebApplicationInitializer
{
private static final Logger log = LogManager.getLogger(XxxExternalRestWebApplicationInitializer.class);
/**
* Rest api servlet name
*/
private static final String REST_SERVLET_NAME = "JAX-RS External REST Servlet";
#Override
public void onStartup(ServletContext servletContext) {
log.debug("Try to get external servlet by name:[{}]", REST_SERVLET_NAME);
var registration = servletContext.getServletRegistration(REST_SERVLET_NAME);
if (registration == null) {
log.error("Could not find external servlet registration. External api will not work!!!!");
return;
}
registration.setInitParameter(ServerProperties.PROVIDER_PACKAGES, LocalManagedEntitlementsRestController.class.getPackageName());
log.debug("Registered the controllers from this package: [{}]",IRestControllerMarker.class.getPackage().getName());
}
}
After the startup of the application the WebApplicationInitializer is actually recognized, but when I am sending a GET request to the controller I get a 404 Not Found, I pretty sure the URL is fine.
Actually it seems not scanning the package to fetch the controllers to show.
My feeling is that because in the Application defined:
xxx.rest.external.XxxExternalRestApplication
the controllers class are registed sigularly, it is not going scan packages.
Here the simplified code of the controller I'm trying to use:
#Path("custom")
public class LocalManagedEntitlementsRestController extends BaseResource
{
private static final Logger log = LogManager.getLogger(LocalManagedEntitlementsRestController.class);
#GET
#Path("/")
public String sayHello()
{
return "Welcome to the world of REST";
}
}

How to resolve resource is not available in Restful WebService

I have created a REST webservice 'JSONService' ( using Jersey implementation JAX-RS) with a POST method and created 'JerseyClientPost'.
What I am trying to achieve is to send a POST from my JerseyClientPost. Getting all values into a 'player' object and sending along with response back. But while trying to send the POST request from the postman, it throws
HTTP Status 404 - Not Found, The requested resource is not available.
Any pointers to address this problem will be much appreciated ?
Request Url : http://localhost:8080/WeekendSoccer/test/register/create
Following are my environment details:
JDK 1.7.0_79,
Tomcat Server v7.0,
Jersey (jaxrs-ri-2.25.1),
Web.xml
//REST Resource is given below
package webService;
import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.ResponseBuilder;
import dto.RegisterPlayer;
#Path("/register")
public class JSONService {
#POST
#Path("/create")
#Produces(MediaType.APPLICATION_JSON)
#Consumes(MediaType.APPLICATION_JSON)
public Response createPlayerInJSON(RegisterPlayer player) {
String result = "Player Created : " +player;
return Response.status(201).entity(result).build();
}
}
//Below is the Jersey Client Post
package dao;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Entity;
import javax.ws.rs.client.Invocation;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
public class JerseyClientPost {
public static void main(String[] args) {
try {
RegisterPlayer player = new RegisterPlayer();
player.setName("Link");
player.setEmail("link#test.com");
player.setCompany("Test Ltd");
Client client = ClientBuilder.newClient(new ClientConfig().register( LoggingFilter.class ));
WebTarget webTarget
= client.target("http://localhost:8080/WeekendSoccer/test");
WebTarget playerWebTarget
= webTarget.path("/register/create");
Invocation.Builder invocationBuilder
= playerWebTarget.request(MediaType.APPLICATION_JSON);
Response response
= invocationBuilder
.post(Entity.entity(player,MediaType.APPLICATION_JSON));
if (response.getStatus() != 201) {
throw new RuntimeException("Failed : HTTP error code : "
+ response.getStatus());
}
System.out.println(response.getStatus());
System.out.println(response.readEntity(String.class));
} catch (Exception e) {
e.printStackTrace();
}
}
}
// RegisterPlayer model class with getters, setters
public class RegisterPlayer implements Serializable{
private String name;
private String email;
private String company;
public RegisterPlayer()
{
}
public RegisterPlayer(String name, String email, String company)
{
super();
this.name = name;
this.email = email;
this.company = company;
}
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
....
}
// Web.xml
<?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.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
<display-name>WeekendSoccer</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>Register Service</servlet-name>
<servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
<init-param>
<param-name>jersey.config.server.provider.packages</param-name>
<param-value>webService</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Register Service</servlet-name>
<url-pattern>/rest/*</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>JSON Service</servlet-name>
<servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
<init-param>
<param-name>jersey.config.server.provider.packages</param-name>
<param-value>dao</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>JSON Service</servlet-name>
<url-pattern>/test/*</url-pattern>
</servlet-mapping>
</web-app>
//Listed all jars
aopalliance-repackaged-2.5.0-b32.jar
gson-2.2.2.jar
hk2-api-2.5.0-b32.jar
hk2-locator-2.5.0-b32.jar
hk2-utils-2.5.0-b32.jar
jackson-annotations-2.3.2.jar
jackson-core-2.3.2.jar
jackson-databind-2.3.2.jar
jackson-jaxrs-base-2.3.2.jar
jackson-jaxrs-json-provider-2.3.2.jar
jackson-module-jaxb-annotations-2.3.2.jar
javassist-3.20.0-GA.jar
javax.annotation-api-1.2.jar
javax.inject-2.5.0-b32.jar
javax.servlet-api-3.0.1.jar
javax.ws.rs-api-2.0.1.jar
jaxb-api-2.2.7.jar
jersey-client.jar
jersey-common.jar
jersey-container-servlet-core.jar
jersey-container-servlet.jar
jersey-entity-filtering-2.17.jar
jersey-guava-2.25.1.jar
jersey-media-jaxb.jar
jersey-media-json-jackson-2.17.jar
jersey-server.jar
mysql-connector-java-5.1.40-bin.jar
org.osgi.core-4.2.0.jar
osgi-resource-locator-1.0.1.jar
persistence-api-1.0.jar
validation-api-1.1.0.Final.jar
Firstly, I have never tested your client side code but I guess your problem is about server side and tested in Postman. you should add #XmlRootElement annotation in your pojo class RegisterPlayer like that:
#XmlRootElement
public class RegisterPlayer implements Serializable{
private String name;
private String email;
private String company;
public RegisterPlayer()
{
}
public RegisterPlayer(String name, String email, String company)
{
super();
this.name = name;
this.email = email;
this.company = company;
}
and added these dependencies in pom.xml
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.9.3</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.codehaus.jackson/jackson-mapper-asl -->
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-asl</artifactId>
<version>1.9.13</version>
</dependency>
If you already have these jars it is fine. It works for me right now. I hope it helps to you.
jackson-core-2.9.3.jar
jackson-mapper-asl-1.9.13.jar
jackson-core-asl-1.9.13.jar
asm-3.3.1.jar
jersey-bundle-1.19.4.jar
jsr311-api-1.1.1.jar
json-20170516.jar
jersey-server-1.19.4.jar
jersey-core-1.19.4.jar
jersey-multipart-1.19.4.jar
mimepull-1.9.3.jar
jackson-annotations-2.7.0.jar
jackson-databind-2.7.0.jar
I'm still not sure, why do you have following mapping in web.xml ? As theren't any servlet class associated with this servlet name. You should removed them
<servlet-mapping>
<servlet-name>JSON Service</servlet-name>
<url-pattern>/test/*</url-pattern>
</servlet-mapping>
I see you have following entries and they do have servlet class associated.
<servlet-mapping>
<servlet-name>Register Service</servlet-name>
<url-pattern>/rest/*</url-pattern>
</servlet-mapping>
That means, you target url should be
http://localhost:8080/WeekendSoccer/rest/register/create
instead of
http://localhost:8080/WeekendSoccer/test/register/create

the requested resource is not available. tomcat 7 spring mvc

I am following up this tutorial
https://www.javacodegeeks.com/2014/03/building-java-web-application-using-hibernate-with-spring.html
I am having this error >>>> the requested resource could not be found
web.xml file content
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<servlet>
<servlet-name>studentHibernateServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/config/servletConfig.xml</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>studentHibernateServlet</servlet-name>
<url-pattern>*.html</url-pattern>
</servlet-mapping>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:/jpaContext.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<display-name>Archetype Created Web Application</display-name>
</web-app>
The controller content
package com.github.elizabetht.controller;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.SessionAttributes;
import com.github.elizabetht.model.Student;
import com.github.elizabetht.model.StudentLogin;
import com.github.elizabetht.service.StudentService;
#Controller
#SessionAttributes("student")
public class StudentController {
#Autowired
private StudentService studentService;
#RequestMapping(value="/signup", method=RequestMethod.GET)
public String signup(Model model) {
Student student = new Student();
model.addAttribute("student", student);
return "signup";
}
#RequestMapping(value="/signup", method=RequestMethod.POST)
public String signup(#Valid #ModelAttribute("student") Student student, BindingResult result, Model model) {
if(result.hasErrors()) {
return "signup";
} else if(studentService.findByUserName(student.getUserName())) {
model.addAttribute("message", "User Name exists. Try another user name");
return "signup";
} else {
studentService.save(student);
model.addAttribute("message", "Saved student details");
return "redirect:login.html";
}
}
#RequestMapping(value="/login", method=RequestMethod.GET)
public String login(Model model) {
StudentLogin studentLogin = new StudentLogin();
model.addAttribute("studentLogin", studentLogin);
return "login";
}
#RequestMapping(value="/login", method=RequestMethod.POST)
public String login(#Valid #ModelAttribute("studentLogin") StudentLogin studentLogin, BindingResult result) {
if (result.hasErrors()) {
return "login";
} else {
boolean found = studentService.findByLogin(studentLogin.getUserName(), studentLogin.getPassword());
if (found) {
return "success";
} else {
return "failure";
}
}
}
}
Please assist me I a beginner
Your dispatcher servlet only listens to *.html. You can either call a url having this as its suffix, i.e.:
http://localhost::8080/[YourAppName]/[filename].html
Or you can change the servlet mapping to something more generic:
<servlet-mapping>
<servlet-name>studentHibernateServlet</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
and call i.e.:
http://localhost::8080/[YourAppName]/signup
Update
Your servlet version is set to 2.5 which is very old. Its 3.1 at the moment. You might want to update it, to at least 3.0 for Tomcat 7, for example. Therefore the tutorial is a little outdated too, search for Spring 4 MVC to find modern ones.

Wildfly resteasy javax.ws.rs.NotFoundException

i know that this post is duplicate and there are a lot of solutions yet, but i wasn't able to use them to resolve the problem.
I am trying to use spring + wildflyAS + resteasy. I have problems with resteasy integration, here is error which i am getting while trying to access controller:
javax.ws.rs.NotFoundException: Could not find resource for full path: http://localhost:8080/BQP/rest/student/test/1/pass/1
Controller:
#Controller
#RequestMapping(value = "student")
public class StudentController {
#Autowired
StudentService studentService;
public StudentController() {
}
#RequestMapping(value = "/test/{id}/pass/{testId}", method = RequestMethod.GET, produces = "application/json")
public
#ResponseBody
Response getCurrentTest(#PathVariable("id") String id,#PathVariable("testId") String testId){
TestDTO testDTO = studentService.getCurrentTest(id,testId);
return Response.status(200).entity(testDTO).build();
}
}
web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<display-name>BQP</display-name>
<!--Spring-->
<servlet>
<servlet-name>Spring MVC Servlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring-mvc-context.xml</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>Spring MVC Servlet</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
<!--/Spring-->
<!--RestEASY-->
<servlet>
<servlet-name>Resteasy</servlet-name>
<servlet-class>org.jboss.resteasy.plugins.server.servlet.HttpServletDispatcher</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Resteasy</servlet-name>
<url-pattern>/rest/*</url-pattern>
</servlet-mapping>
<context-param>
<param-name>javax.ws.rs.Application</param-name>
<param-value>com.bionic.rest.ApplicationConfiguration</param-value>
</context-param>
<context-param>
<param-name>resteasy.servlet.mapping.prefix</param-name>
<param-value>/rest</param-value>
</context-param>
<listener>
<listener-class>org.jboss.resteasy.plugins.server.servlet.ResteasyBootstrap</listener-class>
</listener>
<!--/RestEASY-->
ApplicationConfiguration:
package com.bionic.rest;
import javax.ws.rs.core.Application;
import java.util.HashSet;
import java.util.Set;
public class ApplicationConfiguration extends Application {
private Set<Object> singletons = new HashSet<Object>();
private Set<Class<?>> empty = new HashSet<Class<?>>();
public ApplicationConfiguration() {
singletons.add(new StudentController());
}
#Override
public Set<Class<?>> getClasses() {
return empty;
}
#Override
public Set<Object> getSingletons() {
return singletons;
}
}
Moreover, i can access this controller without /rest in url.

ExceptionMapper causes "No 'Access-Control-Allow-Origin' header is present on the requested resource" when handling an exception

I have an AngularJS client trying to consume a REST Web Service on Wildfly.
It works when the server returns an object, but when an exception is thrown, I'm getting the following message:
XMLHttpRequest cannot load
http://localhost:8080/ProdutosBackend-0.0.1-SNAPSHOT/rest/user/create.
No 'Access-Control-Allow-Origin' header is present on the requested
resource. Origin 'http://127.0.0.1:51647' is therefore not allowed
access. The response had HTTP status code 500.
I tried lots of combinations of headers and filters, but nothing can make this works.
Client code:
var user = {
email : $scope.signUpData.email,
password : $scope.signUpData.password,
name : $scope.signUpData.name
};
$http.post(
'http://localhost:8080/ProdutosBackend-0.0.1-SNAPSHOT/rest/user/create',
user).
then(function(data) {
console.log("It works!");
},
function(response) {
console.log(response);
});
Web Service
import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import br.com.produtos.business.UserBO;
import br.com.produtos.business.exceptions.BusinessException;
import br.com.produtos.entity.User;
import br.com.produtos.transaction.Transaction;
#Path("/user")
public class UserREST {
#POST
#Path("/create")
#Consumes(MediaType.APPLICATION_JSON)
#Produces({ MediaType.APPLICATION_JSON })
public User createAcount(#Context HttpServletRequest httpServletRequest, User user) throws BusinessException {
if (user.getEmail().equals("fff")) {
throw new BusinessException("Bussiness error.");
}
{...}
return user;
}
}
ExceptionMapper
import javax.ws.rs.core.Response;
import javax.ws.rs.ext.ExceptionMapper;
public class ThrowableMapper implements ExceptionMapper<Throwable> {
#Override
public Response toResponse(Throwable throwable) {
return Response.status(500).entity(throwable.getMessage()).build();
}
}
Application
#ApplicationPath("/rest")
public class ThisApplication extends Application {
public static CorsFilter cors;
private Set<Object> singletons = new HashSet<Object>();
private Set<Class<?>> empty = new HashSet<Class<?>>();
public ThisApplication() {
CorsFilter filter = new CorsFilter();
filter.getAllowedOrigins().add("*");
cors = filter;
singletons.add(filter);
singletons.add(new ThrowableMapper());
singletons.add(new UserREST());
}
public Set<Class<?>> getClasses() {
return empty;
}
public Set<Object> getSingletons() {
return singletons;
}
}
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
<display-name>ProdutosBackend</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
<context-param>
<param-name>javax.ws.rs.Application</param-name>
<param-value>br.com.produtos.rest.ThisApplication</param-value>
</context-param>
<context-param>
<param-name>resteasy.servlet.mapping.prefix</param-name>
<param-value>/rest</param-value>
</context-param>
<listener>
<listener-class>org.jboss.resteasy.plugins.server.servlet.ResteasyBootstrap</listener-class>
</listener>
<servlet>
<servlet-name>Resteasy</servlet-name>
<servlet-class>org.jboss.resteasy.plugins.server.servlet.HttpServletDispatcher</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Resteasy</servlet-name>
<url-pattern>/rest/*</url-pattern>
</servlet-mapping>
</web-app>
I solved the problem returning the message encapsulated into a json string.
public class ThrowableMapper implements ExceptionMapper<Throwable> {
#Override
public Response toResponse(Throwable throwable) {
return Response.status(500).entity("{ \"message\": \"" + throwable.getMessage() + "\" }").build();
}
}

Categories

Resources