1

I've a Ajax post request form *input_graph.xhtml* which is backed by a View scoped bean InputTablePlot.java, I've an application scoped bean with eager=true, which creates a connection pool on application start. I have injected this application scoped bean as a managed property in InputTablePlot, and I retrieve connection object from it. The connection pool is available in partial submits but is NULL in submit method which is invoked by clicking a command button "Plot".

Input.xhtml

 <?xml version='1.0' encoding='UTF-8' ?>
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml"
        xmlns:ui="http://java.sun.com/jsf/facelets"
        xmlns:f="http://java.sun.com/jsf/core"
        xmlns:h="http://java.sun.com/jsf/html"
        xmlns:p="http://primefaces.org/ui">
    <f:view contentType="text/html">
        <h:head>
        </h:head>
        <h:body>
            <h:panelGroup id="container" style="background-color: white"
                layout="block">
                <h:panelGroup id="center" class="column" layout="block">
                    <h:form>
                        <p:messages id="validations" />
                        <p:panelGrid columns="2" styleClass="panelgrid">
                            <h:outputLabel for="ip" value="Source:"></h:outputLabel>
                            <p:selectManyMenu id="ip" value="#{inputTablePlot.ipAddress}"
                                required="true" requiredMessage="Enter Source">
                                <f:selectItems value="#{inputTablePlot.ipAddressList}" />
                                <p:ajax listener="#{inputTablePlot.populateDstn}" event="change" 
                                    update="dstn" process="@this"/>
                            </p:selectManyMenu>
                            <h:outputLabel for="dstn" value="Destination:"></h:outputLabel>
                            <p:selectManyMenu id="dstn" value="#{inputTablePlot.m_destination}"
                                required="true" requiredMessage="Enter Destination">
                                <f:selectItems value="#{inputTablePlot.m_destinationMenu}" />
                            </p:selectManyMenu>
                            <h:outputLabel for="start_date">Start Date/Time:</h:outputLabel>
                            <p:calendar id="start_date" value="#{inputTablePlot.startDtTime}"
                                navigator="true" pattern="MM/dd/yyyy hh:mm:ss a" required="true"
                                requiredMessage="Enter Start Date/Time" effect="fadeIn">
                            </p:calendar>
                            <h:outputLabel for="stop_date">Stop Date/Time:</h:outputLabel>
                            <p:calendar id="stop_date" value="#{inputTablePlot.stopDtTime}"
                                navigator="true" pattern="MM/dd/yyyy hh:mm:ss a" required="true"
                                requiredMessage="Enter Stop Date/Time" effect="fadeIn">
                            </p:calendar>
                            <h:outputLabel>Period:</h:outputLabel>
                            <p:selectOneMenu value="#{inputTablePlot.selPeriodType}"
                                required="true" requiredMessage="Enter Period">
                                <f:selectItems value="#{inputTablePlot.periodType}" />
                                <p:ajax listener="#{inputTablePlot.modifyperiod}" event="change"
                                     process="@this" partialSubmit="true"/>
                            </p:selectOneMenu>
                            <p:inputText id="txt1" value="#{inputTablePlot.period}" />
                            <p:slider for="txt1" id="slider"/>
                            <h:commandButton value="Plot" action="#{inputTablePlot.submit}"
                                styleClass="button" id="bt2"></h:commandButton>
                            <h:commandButton value="Clear" action="#{inputTablePlot.clear}"
                                styleClass="button"></h:commandButton>
                        </p:panelGrid>
                        <p:defaultCommand target="bt2" />
                    </h:form>
                </h:panelGroup>
            </h:panelGroup>
        </h:body>
    </f:view>
    </html>

InputTablePlot.java

@ManagedBean
@ViewScoped
     public class InputTablePlot implements Serializable
        {
            private List<Long> m_ipAddress;
            private Map<String, Long> m_ipAddrMenu;
            private List<Long> m_destination;
            private Map<String, Long> m_destinationMenu;
            private List<Long> m_ssrc;
            private Map<String, Long> m_ssrcMenu;
            private Date m_startDtTime;
            private Date m_stopDtTime;
            private int m_period;
            private List<String> m_periodType;
            private String m_selectedPrdType;

            @ManagedProperty("#{analyzerUIDatabase}")
            private transient AnalyzerUIDatabase m_analyzerUIDatabase;
            private List<List<PeriodStats>> m_results;
            private StringBuilder m_query;


            public InputTablePlot()
            {
                m_ipAddrMenu = new LinkedHashMap<String, Long>();
                m_destinationMenu = new LinkedHashMap<String, Long>();
                m_periodType = new ArrayList<String>();
                m_results = new ArrayList<List<PeriodStats>>();
                m_period = 10;
                m_query = new StringBuilder();
            }

            @PostConstruct
            public void init()
            {
                m_ipAddrMenu.clear();// Removing existing sources
                m_destinationMenu.clear();// Removing existing destinations
                m_periodType.clear();// Removing existing period types

                m_periodType.add("Seconds");
                m_periodType.add("Minutes");
                m_periodType.add("Hours");
                m_periodType.add("Days");

                try
                {
                    Connection m_connection = null;
                    ResultSet m_rs = null;
                    PreparedStatement m_pst_query = null;
                    m_query.setLength(0);
                    m_connection = m_analyzerUIDatabase.getConnection();
                    //process query
                    m_pst_query = m_connection.prepareStatement(m_query.toString());
                    m_rs = m_pst_query.executeQuery();
                    while (m_rs.next())
                    {
                        m_ipAddrMenu.put(ipLongToString(m_rs.getLong("IPADDRESS")), m_rs.getLong("IPADDRESS"));
                    }
                    m_rs.close();
                    m_query.setLength(0);
                    m_pst_query.close();
                    m_connection.close();
                }
                catch (SQLException e)
                {
                    e.printStackTrace();
                }
            }



        > //Getters and Setters

            public String submit()
            {
                System.out.println("In Submit >>>>>>>> ");
                log(m_analyzerUIDatabase); // <-- 

        > Returning NULL

                log(m_startDtTime);
                log(m_stopDtTime);
                log(m_selectedPrdType);
                log(m_period);
                log(m_ipAddress);
                log(m_destination);


                if (m_startDtTime.after(m_stopDtTime))
                {
                    FacesContext facesContext = FacesContext.getCurrentInstance();
                    FacesMessage facesMessage = new FacesMessage("Stop Date/Time should be after Start Date/Time");
                    facesContext.addMessage("tableplot:validations", facesMessage);
                    return "FAILURE";
                }
                else if (m_selectedPrdType.equalsIgnoreCase("Seconds") && m_period < 10)
                {
                    FacesContext facesContext = FacesContext.getCurrentInstance();
                    FacesMessage facesMessage = new FacesMessage("Minimum Period in Seconds is 10");
                    facesContext.addMessage("tableplot:validations", facesMessage);
                    return "FAILURE";
                }
                else
                {
                    Connection m_connection = null;
                    ResultSet m_rs = null;
                    PreparedStatement m_pst_query = null;

                    for (int i = 0; i < m_ipAddress.size(); i++)
                    {
        // Execute some logic
                    Flash flash = FacesContext.getCurrentInstance().getExternalContext().getFlash();
                    flash.put("m_results", m_results);
                    flash.put("resultJSON", resultJSON);
                    return "SUCCESS";
                }
            }

            public void populateDstn()
            {

                System.out.println("ipaddr : " + this.m_ipAddress);
                Connection m_connection = null;
                ResultSet m_rs = null;
                PreparedStatement m_pst_query = null;

                try
                {
                    m_destinationMenu.clear();
                    m_connection = m_analyzerUIDatabase.getConnection();
                    //execute some logic
                    m_rs.close();
                    m_query.setLength(0);
                    ipAddress.setLength(0);
                    m_pst_query.close();
                    m_connection.close();
                }
                catch (SQLException e)
                {
                    FacesContext.getCurrentInstance().addMessage("tableplot:validations", new FacesMessage("Problem fetching Destinations"));
                    e.printStackTrace();
                }

            }

            private void log(Object object)
            {
                String methodName = Thread.currentThread().getStackTrace()[2].getMethodName();
                System.out.println("MyBean " + methodName + ": " + object);
            }

        }

StackTrace

START PHASE RESTORE_VIEW 1
userAgent ::: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/28.0.1500.72 Safari/537.36   accept :: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
userAgent ::: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/28.0.1500.72 Safari/537.36   accept :: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
userAgent ::: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/28.0.1500.72 Safari/537.36   accept :: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
END PHASE RESTORE_VIEW 1
START PHASE APPLY_REQUEST_VALUES 2
END PHASE APPLY_REQUEST_VALUES 2
START PHASE PROCESS_VALIDATIONS 3
MyBean getIpAddress: [168821850]
MyBean getIpAddress: [168821850]
MyBean getM_destination: null
MyBean getM_destination: null
END PHASE PROCESS_VALIDATIONS 3
START PHASE UPDATE_MODEL_VALUES 4
MyBean setIpAddress: [168821850]
MyBean setM_destination: [168821876]
END PHASE UPDATE_MODEL_VALUES 4
START PHASE INVOKE_APPLICATION 5
In Submit >>>>>>>> 
MyBean submit: null
MyBean submit: Wed Jul 17 00:00:00 CDT 2013
MyBean submit: Fri Jul 19 00:00:00 CDT 2013
MyBean submit: Seconds
MyBean submit: 10
MyBean submit: [168821850]
MyBean submit: [168821876]
java.lang.NullPointerException
at com.InputTablePlot.submit(InputTablePlot.java:298)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:601)
    at com.sun.el.parser.AstValue.invoke(AstValue.java:234)
    at com.sun.el.MethodExpressionImpl.invoke(MethodExpressionImpl.java:297)
    at com.sun.faces.facelets.el.TagMethodExpression.invoke(TagMethodExpression.java:105)
    at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:88)
    at com.sun.faces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:102)
    at javax.faces.component.UICommand.broadcast(UICommand.java:315)
    at javax.faces.component.UIViewRoot.broadcastEvents(UIViewRoot.java:794)
    at javax.faces.component.UIViewRoot.processApplication(UIViewRoot.java:1259)
    at com.sun.faces.lifecycle.InvokeApplicationPhase.execute(InvokeApplicationPhase.java:81)
    at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
    at com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:118)
    at javax.faces.webapp.FacesServlet.service(FacesServlet.java:593)
    at org.eclipse.jetty.servlet.ServletHolder.handle(ServletHolder.java:681)
    at org.eclipse.jetty.servlet.ServletHandler.doHandle(ServletHandler.java:452)
    at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:138)
    at org.eclipse.jetty.security.SecurityHandler.handle(SecurityHandler.java:564)
    at org.eclipse.jetty.server.session.SessionHandler.doHandle(SessionHandler.java:213)
    at org.eclipse.jetty.server.handler.ContextHandler.doHandle(ContextHandler.java:1083)
    at org.eclipse.jetty.servlet.ServletHandler.doScope(ServletHandler.java:379)
    at org.eclipse.jetty.server.session.SessionHandler.doScope(SessionHandler.java:175)
    at org.eclipse.jetty.server.handler.ContextHandler.doScope(ContextHandler.java:1017)
    at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:136)
    at org.eclipse.jetty.server.handler.HandlerWrapper.handle(HandlerWrapper.java:97)
    at org.eclipse.jetty.server.Server.handle(Server.java:445)
    at org.eclipse.jetty.server.HttpChannel.handle(HttpChannel.java:260)
    at org.eclipse.jetty.server.HttpConnection.onFillable(HttpConnection.java:225)
    at org.eclipse.jetty.io.AbstractConnection$ReadCallback.run(AbstractConnection.java:358)
    at org.eclipse.jetty.util.thread.QueuedThreadPool.runJob(QueuedThreadPool.java:596)
    at org.eclipse.jetty.util.thread.QueuedThreadPool$3.run(QueuedThreadPool.java:527)
    at java.lang.Thread.run(Thread.java:722)
END PHASE INVOKE_APPLICATION 5
START PHASE RENDER_RESPONSE 6
MyBean getIpAddress: [168821850]
MyBean getIpAddress: [168821850]
MyBean getM_destination: [168821876]
MyBean getM_destination: [168821876]
END PHASE RENDER_RESPONSE 6
FiendFyre
  • 157
  • 3
  • 17
  • Read on what `transient` means. – BalusC Jul 29 '13 at 16:22
  • BalusC I've made m_analyzerUIDatabase transient since org.h2.jdbcx.JdbcConnectionPool is not Serializable and ViewScoped Bean requires its instance variables to be Serializable. – FiendFyre Jul 29 '13 at 16:30
  • Okay, you have thus already the answer why you got a `NullPointerException`. – BalusC Jul 29 '13 at 16:35
  • I get it, Could you please guide me in getting a database connection in viewscoped bean? – FiendFyre Jul 29 '13 at 16:40
  • 1
    The container should manage the connection pool itself, not you. Usually, JPA and EJB are been used to bring it all down to oneliners in slick classes whose instances are managed by the container. If your container doesn't support JPA/EJB (because it's a poor man's servletcontainer like Tomcat/Jetty, not a full fledged Java EE container like Glassfish/JBoss), then you'd need to lookup the DAO pattern. Also here, connections are still supposed to be managed by the container itself. You should grab the `DataSource` from JNDI then. – BalusC Jul 29 '13 at 16:44
  • Thanks a lot for the pointer, I will check on implementing DAO pattern – FiendFyre Jul 29 '13 at 17:49

0 Answers0