0
votes

I am just about to give up on JBoss and go back to Tomcat but I thought I would ask the wise world of stackoverflow before jumping ship. My apologies as there will be a lot of code/xml/logs pasted here. There must be something simple that I am missing?

I have started a new Resteasy project on JBoss 7.1.1 and currently have 2 endpoints as seen below.

@Named
@Path("/v1/users")
@Produces(MediaType.APPLICATION_JSON)
public class UserResource {

    @Inject
    private UserService userService;

    @GET
    public Response getUsers() {
        User user = new User();
        user.setUsername("someUsername");
        user.setEmail("[email protected]");
        user.setPassword("thepassword");
        Response.ResponseBuilder responseBuilder = Response.ok(user);

        return responseBuilder.build();
    }

    @POST
    @Consumes(MediaType.APPLICATION_JSON)
    public Response createUser(User user) {
        Response.ResponseBuilder responseBuilder = null;

        try {
            userService.register(user);
            responseBuilder = Response.created(null);
        } catch (UserException ue) {
            if (ue.getMessage().equals(ErrorCode.USER_REGISTRATION_FIELD_MISSING)) {
                responseBuilder = Response.status(Response.Status.fromStatusCode(422));
                responseBuilder.entity(ue.getMessage());
            } else {
                responseBuilder = Response.serverError();
                responseBuilder.entity(ue.getMessage());
            }
        }

        return responseBuilder.build();
    }
}

The @Get /v1/users works fine. My problem is that the userService is not injected and I am getting NullPointerExceptions when calling @POST /v1/users at the userService.register(user) call. Stack trace below

17:17:05,669 ERROR [org.apache.catalina.core.ContainerBase.[jboss.web].[default-host].[/api].[Resteasy]] (http--127.0.0.1-8080-1) Servlet.service() for servlet Resteasy threw exception: org.jboss.resteasy.spi.UnhandledException: java.lang.NullPointerException
at org.jboss.resteasy.core.SynchronousDispatcher.handleApplicationException(SynchronousDispatcher.java:340) [resteasy-jaxrs-2.3.2.Final.jar:]
... JBoss/Resteasy attempting to handle exception, left out to reduce bloat

Caused by: java.lang.NullPointerException
at au.com.codecave.api.UserResource.createUser(UserResource.java:48) [classes:]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) [rt.jar:1.7.0_25]
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) [rt.jar:1.7.0_25]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) [rt.jar:1.7.0_25]
at java.lang.reflect.Method.invoke(Method.java:606) [rt.jar:1.7.0_25]
at org.jboss.resteasy.core.MethodInjectorImpl.invoke(MethodInjectorImpl.java:155) [resteasy-jaxrs-2.3.2.Final.jar:]
at org.jboss.resteasy.core.ResourceMethod.invokeOnTarget(ResourceMethod.java:257) [resteasy-jaxrs-2.3.2.Final.jar:]
at org.jboss.resteasy.core.ResourceMethod.invoke(ResourceMethod.java:222) [resteasy-jaxrs-2.3.2.Final.jar:]
at org.jboss.resteasy.core.ResourceMethod.invoke(ResourceMethod.java:211) [resteasy-jaxrs-2.3.2.Final.jar:]
at org.jboss.resteasy.core.SynchronousDispatcher.getResponse(SynchronousDispatcher.java:525) [resteasy-jaxrs-2.3.2.Final.jar:]
... 19 more

I followed this JBoss documentation to setup my web.xml and have setup my context.xml files as I normally do.

Web.xml

<!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>
    <!-- Auto scan for REST services ad providers -->
    <context-param>
        <param-name>resteasy.scan</param-name>
        <param-value>true</param-value>
    </context-param>
    <context-param>
        <param-name>resteasy.scan.providers</param-name>
        <param-value>true</param-value>
    </context-param>
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/bizniz-context.xml</param-value>
    </context-param>

    <listener>
        <listener-class>org.jboss.resteasy.plugins.server.servlet.ResteasyBootstrap</listener-class>
    </listener>
    <listener>
        <listener-class>org.jboss.resteasy.plugins.spring.SpringContextLoaderListener</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>/*</url-pattern>
    </servlet-mapping>

</web-app>

bizniz-context.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">

    <import resource="persistence-context.xml" />
    <context:component-scan base-package="au.com.codecave.service"/>

</beans>

UserServiceImpl.java

@Named
public class UserServiceImpl implements UserService {

    private static final Logger log = LoggerFactory.getLogger(UserServiceImpl.class);

    @Inject
    private UserDao userDao;

    @Override
    public User register(User user) throws UserException {

        if (StringUtils.isEmpty(user.getEmail()) || StringUtils.isEmpty(user.getEmail())) {
            log.error("Mandatory registration field was empty.  Email: {}, Username: {}", user.getEmail(), user.getUsername());
            throw new UserException(ErrorCode.USER_REGISTRATION_FIELD_MISSING.getMessage());
        }

        try {
            userDao.create(user);
        } catch (DataException de) {
            throw new UserException(de);
        }

        return user;
    }

I don't see any exceptions in the startup log about instantiating any of the beans so I don't think that is the problem, and I am seeing the message below which I assume means Spring initialised correctly

17:16:46,003 INFO  [org.springframework.beans.factory.support.DefaultListableBeanFactory] (MSC service thread 1-4) Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@54287575: defining beans [userDaoImpl,org.springframework.context.annotation.internalConfigurationAnnotationProcessor,org.springframework.context.annotation.internalAutowiredAnnotationProcessor,org.springframework.context.annotation.internalRequiredAnnotationProcessor,org.springframework.context.annotation.internalCommonAnnotationProcessor,dataSource,jdbcTemplate,userServiceImpl,org.springframework.context.annotation.ConfigurationClassPostProcessor.importAwareProcessor]; root of factory hierarchy
17:16:46,121 INFO  [org.springframework.web.context.ContextLoader] (MSC service thread 1-4) Root WebApplicationContext: initialization completed in 783 ms

I have been scouring the web all day looking for a solution but just can not seem to find one. Version details below.

JBoss AS 7.1.1 Spring 3.2.8.RELEASE (Was 4 but realised resteasy Bootstrap only works with 3 see issue here) Resteasy-spring 3.0.8.Final

Please let me know if more information is required. Thanks all.

2
I am facing the same problem !! Could you please post how did you solve it ? - Tony

2 Answers

1
votes

I had the same kind of null pointer exception issue.

Step1: Instead of using the SpringContextLoaderListener try the default ContextLoaderListener from spring framework in web.xml

 <listener>
 <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
 </listener>

Step2: In POM file add the below 2 dependencies:

<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>4.2.0.RELEASE</version>
</dependency>

<dependency>
<groupId>org.jboss.resteasy</groupId>
<artifactId>resteasy-spring</artifactId>
<version>3.0.4.Final</version>
</dependency>

Step3: And in bizniz-context.xml add the below bean definition above component-scan

 <bean class="org.jboss.resteasy.plugins.spring.SpringBeanProcessorServletAware"/>

Hope this helps.

0
votes

Not exactly sure if this is the problem, but initialization JAX-RS in a JEE environment requires little manual configuration. Instead of configuring the servlet in the web.xml (which is to make it work on a non-JEE environment such as Tomcat), you simply need an Application class like this:

@ApplicationPath("/REST")  
public class JaxrsApplication extends Application {  
}

The existence of this class (annotated with ApplicationPath and extending Application) will trigger JBoss to initialize the JAX-RS subsystem. Name it as you want and map it to whatever URL you want of course.

Documentation:

https://docs.jboss.org/author/display/AS7/JAX-RS+Reference+Guide

But I see you use Spring, which makes me question if what I'm saying here is the whole truth.