Retrieve data from the database with the rest (jersey)

advertisements

I am trying to retrieve data from mysql database with Spring jdbc and Jersey.My code is

The Dao is this one getUsers(). If i want to get all users it works fine i can show them on a jsp fine.

public List<User> getUsers() throws Exception {
    logger.info("Query DB for users");
     return jdbc.query("Select id,name,lname,username,"
        + "password,postcode,authority,email,"
        + "address,dateofbirth,city,country,"
        + "gender "
        + " from Users", new RowMapper<User>() {

        public User mapRow(ResultSet rs, int rowNum) throws SQLException {
            logger.debug(" query the user");
            User user = new User();
            user.setId(rs.getInt("id"));
            user.setName(rs.getString("name"));
            user.setLname(rs.getString("lname"));
            user.setUsername(rs.getString("username"));
            user.setPassword(rs.getString("password"));
            user.setPostcode(rs.getString("postcode"));
            user.setAuthority(rs.getString("authority"));
            user.setEmail(rs.getString("email"));
            user.setAddress(rs.getString("address"));
            user.setDateofbirth(rs.getString("dateofbirth"));
            user.setCity(rs.getString("city"));
            user.setCountry(rs.getString("country"));
            user.setGender(rs.getString("gender"));
            return user;
        }

    });
}

Here is the resource class

   @Path("/user")
   public class UserResource {
      UserServiceWS userServicews = new UserServiceWS();

@GET
@Produces(MediaType.APPLICATION_XML)
public List<User> getUserData() throws Exception {
    return userServicews.getUsers();
}
 }

so then here is my UserService Class

public class UserServiceWS {

@Autowired
UserDao userDao ;

public UserServiceWS() {
    try {
        getUsers();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

public List<User> getUsers() throws Exception {
    return new ArrayList<User>(userDao.getUsers());
}
 }

So the problem is that i get nul pointer exception on userDao.getUsers(). What am i missing ? here is the error code

HTTP Status 500 - java.lang.NullPointerException

type Exception report

message java.lang.NullPointerException

description The server encountered an internal error that prevented it from fulfilling this request.

exception

javax.servlet.ServletException: java.lang.NullPointerException org.glassfish.jersey.servlet.WebComponent.service(WebComponent.java:397) org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:381) org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:344) org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:221) org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52) org.netbeans.modules.web.monitor.server.MonitorFilter.doFilter(MonitorFilter.java:393)

root cause

java.lang.NullPointerException com.org.projectClient.wsService.UserServiceWS.getUsers(UserServiceWS.java:29) com.org.projectClient.resource.UserResource.getUserData(UserResource.java:23) sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) java.lang.reflect.Method.invoke(Unknown Source) org.glassfish.jersey.server.model.internal.ResourceMethodInvocationHandlerFactory$1.invoke(ResourceMethodInvocationHandlerFactory.java:81) org.glassfish.jersey.server.model.internal.AbstractJavaResourceMethodDispatcher$1.run(AbstractJavaResourceMethodDispatcher.java:151) org.glassfish.jersey.server.model.internal.AbstractJavaResourceMethodDispatcher.invoke(AbstractJavaResourceMethodDispatcher.java:172) org.glassfish.jersey.server.model.internal.JavaResourceMethodDispatcherProvider$TypeOutInvoker.doDispatch(JavaResourceMethodDispatcherProvider.java:195) org.glassfish.jersey.server.model.internal.AbstractJavaResourceMethodDispatcher.dispatch(AbstractJavaResourceMethodDispatcher.java:104) org.glassfish.jersey.server.model.ResourceMethodInvoker.invoke(ResourceMethodInvoker.java:384) org.glassfish.jersey.server.model.ResourceMethodInvoker.apply(ResourceMethodInvoker.java:342) org.glassfish.jersey.server.model.ResourceMethodInvoker.apply(ResourceMethodInvoker.java:101) org.glassfish.jersey.server.ServerRuntime$1.run(ServerRuntime.java:271) org.glassfish.jersey.internal.Errors$1.call(Errors.java:271) org.glassfish.jersey.internal.Errors$1.call(Errors.java:267) org.glassfish.jersey.internal.Errors.process(Errors.java:315) org.glassfish.jersey.internal.Errors.process(Errors.java:297) org.glassfish.jersey.internal.Errors.process(Errors.java:267) org.glassfish.jersey.process.internal.RequestScope.runInScope(RequestScope.java:297) org.glassfish.jersey.server.ServerRuntime.process(ServerRuntime.java:254) org.glassfish.jersey.server.ApplicationHandler.handle(ApplicationHandler.java:1030) org.glassfish.jersey.servlet.WebComponent.service(WebComponent.java:377) org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:381) org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:344) org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:221) org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52) org.netbeans.modules.web.monitor.server.MonitorFilter.doFilter(MonitorFilter.java:393)

note The full stack trace of the root cause is available in the Apache Tomcat/7.0.68 logs. Apache Tomcat/7.0.68

the user class model

import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

import org.hibernate.validator.constraints.NotEmpty;
 import org.springframework.format.annotation.DateTimeFormat;

   @XmlRootElement
   public class User {

private int id;
@NotEmpty
@Size(max = 250)
private String username;
@NotEmpty
@Size(max = 250)
private String password;

       ...........

If i create a Map and add data there and retrieve i have no problem the web service works ok with no problem.? But if i query the database then i have nullpointer.What am i missing ? Thanks

after adding as 11thdimension writes @Autowired to

@Autowired

  private UserServiceWS userServicews;

and to

 @Component
  public class UserServiceWS {

    @Autowired  UserDao userDao ;

then i get

HTTP Status 500 - A MultiException has 3 exceptions. They are:

type Exception report

message A MultiException has 3 exceptions. They are:

description The server encountered an internal error that prevented it from fulfilling this request.

exception

javax.servlet.ServletException: A MultiException has 3 exceptions. They are: 1. org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.org.projectClient.wsService.UserServiceWS] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)} 2. java.lang.IllegalArgumentException: While attempting to resolve the dependencies of com.org.projectClient.resource.UserResource errors were found 3. java.lang.IllegalStateException: Unable to perform operation: resolve on com.org.projectClient.resource.UserResource

org.glassfish.jersey.servlet.WebComponent.service(WebComponent.java:397) org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:381) org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:344) org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:221) org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52) org.netbeans.modules.web.monitor.server.MonitorFilter.doFilter(MonitorFilter.java:393)

root cause

A MultiException has 3 exceptions. They are: 1. org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.org.projectClient.wsService.UserServiceWS] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)} 2. java.lang.IllegalArgumentException: While attempting to resolve the dependencies of com.org.projectClient.resource.UserResource errors were found 3. java.lang.IllegalStateException: Unable to perform operation: resolve on com.org.projectClient.resource.UserResource

org.jvnet.hk2.internal.Collector.throwIfErrors(Collector.java:88) org.jvnet.hk2.internal.ClazzCreator.resolveAllDependencies(ClazzCreator.java:252) org.jvnet.hk2.internal.ClazzCreator.create(ClazzCreator.java:360) org.jvnet.hk2.internal.SystemDescriptor.create(SystemDescriptor.java:471) org.glassfish.jersey.process.internal.RequestScope.findOrCreate(RequestScope.java:160) org.jvnet.hk2.internal.Utilities.createService(Utilities.java:2270) org.jvnet.hk2.internal.ServiceLocatorImpl.internalGetService(ServiceLocatorImpl.java:687) org.jvnet.hk2.internal.ServiceLocatorImpl.getService(ServiceLocatorImpl.java:652) org.glassfish.jersey.internal.inject.Injections.getOrCreate(Injections.java:169) org.glassfish.jersey.server.model.MethodHandler$ClassBasedMethodHandler.getInstance(MethodHandler.java:185) org.glassfish.jersey.server.internal.routing.PushMethodHandlerRouter.apply(PushMethodHandlerRouter.java:74) org.glassfish.jersey.server.internal.routing.RoutingStage._apply(RoutingStage.java:112) org.glassfish.jersey.server.internal.routing.RoutingStage._apply(RoutingStage.java:116) org.glassfish.jersey.server.internal.routing.RoutingStage._apply(RoutingStage.java:116) org.glassfish.jersey.server.internal.routing.RoutingStage._apply(RoutingStage.java:116) org.glassfish.jersey.server.internal.routing.RoutingStage.apply(RoutingStage.java:94) org.glassfish.jersey.server.internal.routing.RoutingStage.apply(RoutingStage.java:63) org.glassfish.jersey.process.internal.Stages.process(Stages.java:197) org.glassfish.jersey.server.ServerRuntime$1.run(ServerRuntime.java:263) org.glassfish.jersey.internal.Errors$1.call(Errors.java:271) org.glassfish.jersey.internal.Errors$1.call(Errors.java:267) org.glassfish.jersey.internal.Errors.process(Errors.java:315) org.glassfish.jersey.internal.Errors.process(Errors.java:297) org.glassfish.jersey.internal.Errors.process(Errors.java:267) org.glassfish.jersey.process.internal.RequestScope.runInScope(RequestScope.java:297) org.glassfish.jersey.server.ServerRuntime.process(ServerRuntime.java:254) org.glassfish.jersey.server.ApplicationHandler.handle(ApplicationHandler.java:1030) org.glassfish.jersey.servlet.WebComponent.service(WebComponent.java:377) org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:381) org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:344) org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:221) org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52) org.netbeans.modules.web.monitor.server.MonitorFilter.doFilter(MonitorFilter.java:393)

root cause

org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.org.projectClient.wsService.UserServiceWS] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)} org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoSuchBeanDefinitionException(DefaultListableBeanFactory.java:986) org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:856) org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:768) org.glassfish.jersey.server.spring.AutowiredInjectResolver.getBeanFromSpringContext(AutowiredInjectResolver.java:101) org.glassfish.jersey.server.spring.AutowiredInjectResolver.resolve(AutowiredInjectResolver.java:93) org.jvnet.hk2.internal.ClazzCreator.resolve(ClazzCreator.java:214) org.jvnet.hk2.internal.ClazzCreator.resolveAllDependencies(ClazzCreator.java:237) org.jvnet.hk2.internal.ClazzCreator.create(ClazzCreator.java:360) org.jvnet.hk2.internal.SystemDescriptor.create(SystemDescriptor.java:471) org.glassfish.jersey.process.internal.RequestScope.findOrCreate(RequestScope.java:160) org.jvnet.hk2.internal.Utilities.createService(Utilities.java:2270) org.jvnet.hk2.internal.ServiceLocatorImpl.internalGetService(ServiceLocatorImpl.java:687) org.jvnet.hk2.internal.ServiceLocatorImpl.getService(ServiceLocatorImpl.java:652) org.glassfish.jersey.internal.inject.Injections.getOrCreate(Injections.java:169) org.glassfish.jersey.server.model.MethodHandler$ClassBasedMethodHandler.getInstance(MethodHandler.java:185) org.glassfish.jersey.server.internal.routing.PushMethodHandlerRouter.apply(PushMethodHandlerRouter.java:74) org.glassfish.jersey.server.internal.routing.RoutingStage._apply(RoutingStage.java:112) org.glassfish.jersey.server.internal.routing.RoutingStage._apply(RoutingStage.java:116) org.glassfish.jersey.server.internal.routing.RoutingStage._apply(RoutingStage.java:116) org.glassfish.jersey.server.internal.routing.RoutingStage._apply(RoutingStage.java:116) org.glassfish.jersey.server.internal.routing.RoutingStage.apply(RoutingStage.java:94) org.glassfish.jersey.server.internal.routing.RoutingStage.apply(RoutingStage.java:63) org.glassfish.jersey.process.internal.Stages.process(Stages.java:197) org.glassfish.jersey.server.ServerRuntime$1.run(ServerRuntime.java:263) org.glassfish.jersey.internal.Errors$1.call(Errors.java:271) org.glassfish.jersey.internal.Errors$1.call(Errors.java:267) org.glassfish.jersey.internal.Errors.process(Errors.java:315) org.glassfish.jersey.internal.Errors.process(Errors.java:297) org.glassfish.jersey.internal.Errors.process(Errors.java:267) org.glassfish.jersey.process.internal.RequestScope.runInScope(RequestScope.java:297) org.glassfish.jersey.server.ServerRuntime.process(ServerRuntime.java:254) org.glassfish.jersey.server.ApplicationHandler.handle(ApplicationHandler.java:1030) org.glassfish.jersey.servlet.WebComponent.service(WebComponent.java:377) org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:381) org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:344) org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:221) org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52) org.netbeans.modules.web.monitor.server.MonitorFilter.doFilter(MonitorFilter.java:393)

note The full stack trace of the root cause is available in the Apache Tomcat/7.0.68 logs. Apache Tomcat/7.0.68 here is my xml

<!-- DispatcherServlet Context: defines this servlet's request-processing
        infrastructure -->

    <!-- Enables the Spring MVC @Controller programming model -->
    <annotation-driven />

    <!-- Handles HTTP GET requests for /resources/** by efficiently serving
        up static resources in the ${webappRoot}/resources directory -->
    <resources mapping="/resources/**" location="/resources/" />

    <!-- Resolves views selected for rendering by @Controllers to .jsp resources
        in the /WEB-INF/views directory -->
    <beans:bean
        class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <beans:property name="prefix" value="/WEB-INF/views/" />
        <beans:property name="suffix" value=".jsp" />
    </beans:bean>

    <context:component-scan base-package="com.org.projectClient" />

    <jee:jndi-lookup jndi-name="jdbc/testingdbs" id="dataSource"
        expected-type="javax.sql.DataSource">
    </jee:jndi-lookup>

    <!-- <beans:bean id="messages" class="org.springframework.context.support.ResourceBundleMessageSource">
        <beans:property name="basename" value="com.spring.project.demo.messages.messages.properties"
        /> </beans:bean> -->

....... so on


How do you connect to DB?I think there you have your problem.

You have to fix your database connection.

Something is wrong there and you cannot retrieve your data. It's not normal that you get data to a jsp and no data to your service.

Are you using Jndi or something else.Create a DaoManager to handle your connections.

Worst case create a simple open/close DB connection with password username driver details etc.

Only to test your connection.

After creating that try it if this works then you have no DB connection for your service.

For DAOManager look here DAOManager

for a simple connection look here Simple Database Connection

or here

Simple Database Connection 2.

Take care.