1

My web services are made in jersy (restful java) and I am using Hibernate for communicating with mysql database.

In day time I perform load testing, and other functionality testing , every thing works and we leave our work at around 5 pm in evening, when we test the web services again next morning my web service through http 500 exception,when we restart the tomcat on which it is hosted,my web services resumes without making any change in source code or hibernate configuration file.

I am using same Hibernate configuration file which is been used by other web services which are working fine

here is my hibernate configuration file:

    <?xml version="1.0" encoding="UTF-8"?> 
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd"> 
<hibernate-configuration> 
<session-factory> 
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property> 
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/offerstest</property> 
<property name="hibernate.connection.username">root</property> 
<property name="show_sql">true</property> 
<property name="connection.password">password</property> 
<property name="hibernate.c3p0.min_size">5</property>
<property name="hibernate.c3p0.max_size">20</property> 
<property name="hibernate.c3p0.acquire_increment">1</property>
<property name="hibernate.c3p0.timeout">300</property>
<property name="hibernate.c3p0.idle_test_period">3000</property>
<property name="hibernate.c3p0.max_statements">50</property>
<property name="hibernate.jdbc.batch_size">20</property>
<property name="hibernate.cache.use_second_level_cache">false</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property> 
<property name="hbm2ddl.auto">update</property>
<property name="dynamic-update">true</property>
<mapping resource="person.hbm.xml"/>
<mapping resource="vendor.hbm.xml"/>
<mapping resource="coupons.hbm.xml"/>
<mapping resource="binding.hbm.xml"/>
</session-factory> 
</hibernate-configuration>

This is my web service class in which Http 500 error comes

   @Path("/offers")
public class VendorOffers {

    VendorCRUD vendorCRUD;
    BindingCRUD bindingCRUD;

    public VendorOffers() {
        // TODO Auto-generated constructor stub
    }

    @PostConstruct
    public void init() {
        vendorCRUD = CommunicationSingleton.getInstance().getVendorCRUD();
        bindingCRUD = CommunicationSingleton.getInstance().getBindingCRUD();
    }

    @GET
    @Produces(MediaType.APPLICATION_JSON)
    // @Produces(MediaType.APPLICATION_XML)
    @Path("{mac}/coupons")
    public Response getOffers(@PathParam("mac") String mac) {

        List<Offer> list = new ArrayList<Offer>();
        // get all the offers (Bindings) for the given mac
        List<Binding> bindings = bindingCRUD.getMACOffers(mac);
        if (bindings != null) {

            for (Binding binding : bindings) {
                Offer offer = new Offer();

                offer.setCoupon_no(binding.getCoupon_no());
                offer.setMac(binding.getMac());
                offer.setStartDate(binding.getStartdate());
                offer.setEndDate(binding.getEnddate());
                long vendorid = binding.getVendor_coupon_id();
                Vendor vendor = new Vendor();

                vendor.setApk("/rest/downloadfile/" + vendorid + "/getapk");// from
                                                                            // service
                vendor.setArtwork1("/rest/downloadfile/" + vendorid
                        + "/getArt1");// from service
                vendor.setArtwork2("/rest/downloadfile/" + vendorid
                        + "/getArt2");// from service
                vendor.setIcon("/rest/downloadfile/" + vendorid + "/getIco");// from
                                                                                // service
                vendor.setRedeem_doc("/rest/downloadfile/" + vendorid
                        + "/getHtm");// from service




                com.learning.CRUDModel.Vendor localvendor = vendorCRUD
                        .getVendorById(vendorid);

                System.out.println("localvendor.getCountry()"+localvendor.getCountry());
                vendor.setCountry(localvendor.getCountry()); // from database
                vendor.setDescription(localvendor.getDescription());// from
                                                                    // database
                vendor.setHeading(localvendor.getHeading());// from database
                vendor.setName(localvendor.getName());// from database
                vendor.setPkg_name(localvendor.getPkg_name());// from database
                vendor.setVendor_coupon_id(vendorid);// from database
                offer.setVendor(vendor);
                list.add(offer);
            }

            GenericEntity<List<Offer>> entity = new GenericEntity<List<Offer>>(list) {};
            Response response = Response.ok(entity).build();
            return response;
        } else {
            Response response = Response.noContent().build();
            return response;
        }

    }
}

error which is generated is as follows:

    Aug 22, 2013 10:07:02 AM com.sun.jersey.spi.container.ContainerResponse mapMappableContainerException
SEVERE: The RuntimeException could not be mapped to a response, re-throwing to the HTTP container
java.lang.NullPointerException
    at com.avilyne.rest.resource.VendorOffers.getOffers(VendorOffers.java:71)
    at sun.reflect.GeneratedMethodAccessor106.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at com.sun.jersey.spi.container.JavaMethodInvokerFactory$1.invoke(JavaMethodInvokerFactory.java:60)
    at com.sun.jersey.server.impl.model.method.dispatch.AbstractResourceMethodDispatchProvider$ResponseOutInvoker._dispatch(AbstractResourceMethodDispatchProvider.java:205)
    at com.sun.jersey.server.impl.model.method.dispatch.ResourceJavaMethodDispatcher.dispatch(ResourceJavaMethodDispatcher.java:75)
    at com.sun.jersey.server.impl.uri.rules.HttpMethodRule.accept(HttpMethodRule.java:288)
    at com.sun.jersey.server.impl.uri.rules.RightHandPathRule.accept(RightHandPathRule.java:147)
    at com.sun.jersey.server.impl.uri.rules.ResourceClassRule.accept(ResourceClassRule.java:108)
    at com.sun.jersey.server.impl.uri.rules.RightHandPathRule.accept(RightHandPathRule.java:147)
    at com.sun.jersey.server.impl.uri.rules.RootResourceClassesRule.accept(RootResourceClassesRule.java:84)
    at com.sun.jersey.server.impl.application.WebApplicationImpl._handleRequest(WebApplicationImpl.java:1483)
    at com.sun.jersey.server.impl.application.WebApplicationImpl._handleRequest(WebApplicationImpl.java:1414)
    at com.sun.jersey.server.impl.application.WebApplicationImpl.handleRequest(WebApplicationImpl.java:1363)
    at com.sun.jersey.server.impl.application.WebApplicationImpl.handleRequest(WebApplicationImpl.java:1353)
    at com.sun.jersey.spi.container.servlet.WebComponent.service(WebComponent.java:414)
    at com.sun.jersey.spi.container.servlet.ServletContainer.service(ServletContainer.java:537)
    at com.sun.jersey.spi.container.servlet.ServletContainer.service(ServletContainer.java:708)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99)
    at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:947)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1009)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589)
    at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:312)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
    at java.lang.Thread.run(Unknown Source)

At line number 71 this was written :

com.learning.CRUDModel.Vendor localvendor = vendorCRUD
                        .getVendorById(vendorid);

here is the vendorCRUD class:

public class VendorCRUD {
    Session session = HibernateUtil.getSession();

    public String getVendorApk(String vendor_id){
        long id = 0;
        try {
            id = Long.parseLong(vendor_id);
        } catch (NumberFormatException e) {
            e.printStackTrace();
        }
        String apk_path = "not available";

        System.out.println("Vendor Id Value:" + vendor_id);
        try {
            Query query = session.createQuery("from Vendor where Vendor_Coupon_id = :Vendor_Coupon_id ");
            query.setParameter("Vendor_Coupon_id",id);
            List <Vendor>list = query.list();
            if (list.size() > 0) {

                apk_path = list.get(0).getApk();

            }
        } catch (HibernateException ex) {
            ex.printStackTrace();
        } catch(Exception ex){
            ex.printStackTrace();
        }

        return apk_path;
    }

    public String getVendorgetArt1(String vendor_id){
        long id = 0;
        try {
            id = Long.parseLong(vendor_id);
        } catch (NumberFormatException e) {
            e.printStackTrace();
        }
        String art1_path = "not available";
        System.out.println("Vendor Id Value:" + vendor_id);
        try {
            Query query = session.createQuery("from Vendor where Vendor_Coupon_id = :Vendor_Coupon_id ");
            query.setParameter("Vendor_Coupon_id", id);
            List <Vendor>list = query.list();
            if (list.size() > 0) {
                art1_path = list.get(0).getArtwork1();
            }
        } catch (HibernateException ex) {
            ex.printStackTrace();
        } catch(Exception ex){
            ex.printStackTrace();
        }


        return art1_path;
    }


    public String getVendorgetArt2(String vendor_id){
        long id = 0;
        try {
            id = Long.parseLong(vendor_id);
        } catch (NumberFormatException e) {
            e.printStackTrace();
        }
        String art1_path = "not available";
        System.out.println("Vendor Id Value:" + id);
        try {
            Query query = session.createQuery("from Vendor where Vendor_Coupon_id = :Vendor_Coupon_id ");
            query.setParameter("Vendor_Coupon_id", id);
            List <Vendor>list = query.list();
            if (list.size() > 0) {
                art1_path = list.get(0).getArtwork2();
            }
        } catch (HibernateException ex) {
            ex.printStackTrace();
        } catch(Exception ex){
            ex.printStackTrace();
        }
        return art1_path;
    }

    public String getVendorgetIco(String vendor_id){
        long id = 0;
        try {
            id = Long.parseLong(vendor_id);
        } catch (NumberFormatException e) {
            e.printStackTrace();
        }
        String ico_path = "not available";
        System.out.println("Vendor Id Value:" + vendor_id);
        try {
            Query query = session.createQuery("from Vendor where Vendor_Coupon_id = :Vendor_Coupon_id ");
            query.setParameter("Vendor_Coupon_id", id);
            List <Vendor>list = query.list();
            if (list.size() > 0) {
                ico_path = list.get(0).getIco();
            }
        } catch (HibernateException ex) {
            ex.printStackTrace();
        } catch(Exception ex){
            ex.printStackTrace();
        }
        return ico_path;
    }

    public String getVendorgetHtm(String vendor_id){
        long id = 0;
        try {
            id = Long.parseLong(vendor_id);
        } catch (NumberFormatException e) {
            e.printStackTrace();
        }
        String htm_path = "not available";
        System.out.println("Vendor Id Value:" + vendor_id);
        try {
            Query query = session.createQuery("from Vendor where Vendor_Coupon_id = :Vendor_Coupon_id ");
            query.setParameter("Vendor_Coupon_id", id);
            List <Vendor>list = query.list();
            if (list.size() > 0) {
                htm_path = list.get(0).getRedeem_doc();
            }
        } catch (HibernateException ex) {
            ex.printStackTrace();
        } catch(Exception ex){
            ex.printStackTrace();
        }
        return htm_path;
    }

    public List<Vendor> getVendorsForCountry(String country){
        List<Vendor> vendors = null;
        try {
            Query query = session.createQuery("from Vendor where Country = :Country ");
            query.setParameter("Country", country);
            List <Vendor>list = query.list();
            if (list.size() > 0) {
                vendors = list;
            }
        } catch (HibernateException ex) {
            ex.printStackTrace();
        }catch(Exception ex){
            ex.printStackTrace();
        }

        return vendors;     
    }

    public Vendor getVendorById(long vendorid) {
        Vendor uniquevendor = null;
        try {
            Query query = session.createQuery("from Vendor where Vendor_Coupon_id = :Vendor_Coupon_id ");
            query.setParameter("Vendor_Coupon_id", vendorid);
            List <Vendor>list = query.list();
            if (list.size() > 0) {
                uniquevendor = list.get(0);
            }
        } catch (HibernateException ex) {
            ex.printStackTrace();
        } catch(Exception ex){
            ex.printStackTrace();
        }
        return uniquevendor;
    }

}
devnull
  • 118,548
  • 33
  • 236
  • 227
focode
  • 648
  • 1
  • 16
  • 39
  • how is vendor offers instantiated, looks like you have threading issues with your cruds – NimChimpsky Aug 22 '13 at 08:57
  • I don't understand what you want to know, as far as I can understand I have created singleton class from which I get the object of vendorCRUD – focode Aug 22 '13 at 09:06
  • I have done lot of load testing, no problem comes in load testing from JMeter, problem happens only when we leave the work in evening and In morning we try to hit the service it says http 500 exception – focode Aug 22 '13 at 09:09
  • 1
    Shot in the dark here. I had a similiar problem but it was my connection pool dying in the middle of the night. It might be the same problem. – Namphibian Aug 22 '13 at 09:12
  • so please tell me the solution what changes you made – focode Aug 22 '13 at 09:14
  • I made sure that my connections where validated before use. Start here http://stackoverflow.com/questions/7350680/dbcp-returns-closed-connections and here http://stackoverflow.com/questions/7277760/connection-pool-exception-cannot-get-a-connection-pool-error-timeout-waiting-f I cant remember the exact error and I am not at the office now. But essntially ensuring the connections are validated before use will resolve this issue. I – Namphibian Aug 22 '13 at 09:30
  • @NimChimpsky vendoroffer is initiated when request is made to the url :8080/FirstTimeExpTest/rest/offers/00:18:00:01:86:70/coupons – focode Aug 23 '13 at 07:22

1 Answers1

1

If this line is throwing a NPE:

    com.learning.CRUDModel.Vendor localvendor = vendorCRUD
                    .getVendorById(vendorid);

that means one thing and one thing only. The value of vendorCrud was null when the NPE was thrown.

It is not possible to say how that happened. However, I would note that vendorCrud is mutable and it is accessible to any class in the same package as your VendorOffers class. So there is potentially a lot of normal Java code that could change it. Then there is the possibility that something is calling the init() method ...


Based on your followup comments, my guess is that something in your stack is not dealing with expired MySQL connections. By default, MySQL will break connections that have been idle for a long time (I think the default is 10 hours). One way to deal with this is to change the timeout to something very large. There's a database-side configuration parameter for this. However, it would be better to figure out how / why this results in VendorCRUD references ... and fix that.

The key here is that you need to understand what is happening, by applying your Java programming and debugging skills to the problem.

Stephen C
  • 698,415
  • 94
  • 811
  • 1,216
  • I am always using Singleton class to get the object of all my CRUD classes, is it right approach of doing this, can this be the problem – focode Aug 23 '13 at 07:19
  • Its something that get expires, I have verified my hibernate and database their is no problem in them, problem lies with my services,problem happens only when we leave the application for long time say 6-7 hours – focode Aug 23 '13 at 07:38
  • I highly appreciate your feedback, I have already increased the time duration of interactive_timeout and wait_timeout from 8 hours to 11 days and made provision in my hibernate configuration file for handling it, my this particular web service consist of two services 1. Takes data from client and stores in database 2. Based on data from 1 service my second service produces some information for same client. When I see error in my second service (the same I have posted above) I am able to execute my first service without any problem. – focode Aug 23 '13 at 08:42
  • @focode - I understand your frustration, but you need to get to the bottom of this problem yourself. We can only offer random guesses. Like I suggested above, find out *why* that variable contains `null`. – Stephen C Aug 23 '13 at 09:40