Announcement Announcement Module
Collapse
No announcement yet.
spring web services with mysql database connection Page Title Module
Move Remove Collapse
X
Conversation Detail Module
Collapse
  • Filter
  • Time
  • Show
Clear All
new posts

  • spring web services with mysql database connection

    Hi,
    I am using spring web services and jaxb for generating the wsdl and the mysql for connecting the database .

    <SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/">
    <SOAP-ENV:Header/>
    <SOAP-ENV:Body>
    <SOAP-ENV:Fault>
    <faultcode>SOAP-ENV:Server</faultcode>
    <faultstring xml:lang="en">java.lang.NullPointerException</faultstring>
    </SOAP-ENV:Fault>
    </SOAP-ENV:Body>
    </SOAP-ENV:Envelope>

    I have developed the project using spring web services and wsdl generated automatically..when i tested wsdl using soap ui tool getting the above error.The response has to get from the database.I am using mysql for the connection.for the databse connection i am facing the problem.please help me for database connection in web services and what are the classes required for connection.In the console it is shown as like below but the response in soapui is failed.


    FrameworkServlet 'geoveggie-ws': initialization started
    - Refreshing org.springframework.web.context.support.XmlWebAppl icationContext@18bbf55: display name [WebApplicationContext for namespace 'geoveggie-ws-servlet']; startup date [Tue Mar 19 11:53:44 IST 2013]; root of context hierarchy
    - Loading XML bean definitions from ServletContext resource [/WEB-INF/geoveggie-ws-servlet.xml]
    - Bean factory for application context [org.springframework.web.context.support.XmlWebAppl icationContext@18bbf55]: org.springframework.beans.factory.support.DefaultL istableBeanFactory@12dd538
    - Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultL istableBeanFactory@12dd538: defining beans [org.springframework.ws.server.endpoint.mapping.Pay loadRootAnnotationMethodEndpointMapping#0,org.spri ngframework.ws.server.endpoint.adapter.GenericMars hallingMethodEndpointAdapter#0,marshaller,geoveggi e,buyer,BuyerServiceImpl,seller]; root of factory hierarchy
    - Creating JAXBContext with classes to be bound [class com.onevega.geoveggie.jaxb.geo.BuyerAvailabelityRe quest,class com.onevega.geoveggie.jaxb.geo.FlagResponse,class com.onevega.geoveggie.jaxb.geo.BuyerLoginRequest,c lass com.onevega.geoveggie.jaxb.geo.BuyerLoginResponse, class com.onevega.geoveggie.jaxb.geo.SellerLoginRequest, class com.onevega.geoveggie.jaxb.geo.SellerLoginResponse ,class com.onevega.geoveggie.jaxb.geo.SellerAvailabelityR equest,class com.onevega.geoveggie.jaxb.geo.BuyerRegistrationRe quest,class com.onevega.geoveggie.jaxb.geo.SellerRegistrationR equest]
    - Creating SAAJ 1.3 MessageFactory with SOAP 1.1 Protocol
    - FrameworkServlet 'geoveggie-ws': initialization completed in 672 ms
    **********Bean injected********


    Thanks in advance and waiting for the solution, pls help to solve this problem.

    Regards
    sowmya.R

  • #2
    Please use [ code][/code ] tags when posting code/xml/stacktraces...

    You haven't provided any useful information so not much that we can advice or do.

    Check your server log, there must be a stracktrace somewhere on your server... My guess is youir configuration is wrong.

    Comment


    • #3
      Hi marten ,

      In the stack trace i am getting this error.

      org.springframework.beans.factory.BeanInitializati onException: Could not load properties; nested exception is java.io.FileNotFoundException: class path resource [file/jdbc.properties] cannot be opened because it does not exist
      at org.springframework.beans.factory.config.PropertyR esourceConfigurer.postProcessBeanFactory(PropertyR esourceConfigurer.java:78)
      at org.springframework.context.support.AbstractApplic ationContext.invokeBeanFactoryPostProcessors(Abstr actApplicationContext.java:553)
      at org.springframework.context.support.AbstractApplic ationContext.invokeBeanFactoryPostProcessors(Abstr actApplicationContext.java:527)
      at org.springframework.context.support.AbstractApplic ationContext.refresh(AbstractApplicationContext.ja va:362)
      at org.springframework.web.servlet.FrameworkServlet.c reateWebApplicationContext(FrameworkServlet.java:4 02)
      at org.springframework.web.servlet.FrameworkServlet.i nitWebApplicationContext(FrameworkServlet.java:316 )
      at org.springframework.web.servlet.FrameworkServlet.i nitServletBean(FrameworkServlet.java:282)
      at org.springframework.web.servlet.HttpServletBean.in it(HttpServletBean.java:126)
      at javax.servlet.GenericServlet.init(GenericServlet.j ava:160)
      at org.apache.catalina.core.StandardWrapper.initServl et(StandardWrapper.java:1228)
      at org.apache.catalina.core.StandardWrapper.loadServl et(StandardWrapper.java:1147)
      at org.apache.catalina.core.StandardWrapper.allocate( StandardWrapper.java:836)
      at org.apache.catalina.core.StandardWrapperValve.invo ke(StandardWrapperValve.java:135)
      at org.apache.catalina.core.StandardContextValve.invo ke(StandardContextValve.java:185)
      at org.apache.catalina.authenticator.AuthenticatorBas e.invoke(AuthenticatorBase.java:472)
      at org.apache.catalina.core.StandardHostValve.invoke( StandardHostValve.java:151)
      at org.apache.catalina.valves.ErrorReportValve.invoke (ErrorReportValve.java:100)
      at org.apache.catalina.valves.AccessLogValve.invoke(A ccessLogValve.java:929)
      at org.apache.catalina.core.StandardEngineValve.invok e(StandardEngineValve.java:118)
      at org.apache.catalina.connector.CoyoteAdapter.servic e(CoyoteAdapter.java:405)
      at org.apache.coyote.http11.Http11Processor.process(H ttp11Processor.java:269)


      i have provided the xml file also;
      Geoveggie-ws-servlet.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:sws="http://www.springframework.org/schema/web-services"
      xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schem...-beans-2.5.xsd
      http://www.springframework.org/schema/web-services http://www.springframework.org/schema/web-services/web-services-2.0.xsd">

      <!-- sws:annotation-driven/ -->

      <bean class="org.springframework.ws.server.endpoint.mapp ing.PayloadRootAnnotationMethodEndpointMapping" />


      <bean class="org.springframework.ws.server.endpoint.adap ter.GenericMarshallingMethodEndpointAdapter">
      <property name="marshaller" ref="marshaller" />
      <property name="unmarshaller" ref="marshaller" />
      </bean>

      <bean id="marshaller"
      class="org.springframework.oxm.jaxb.Jaxb2Marshalle r">
      <property name="classesToBeBound">
      <list>
      <value>com.onevega.geoveggie.jaxb.geo.BuyerAvailab elityRequest</value>
      <value>com.onevega.geoveggie.jaxb.geo.FlagResponse </value>
      <value>com.onevega.geoveggie.jaxb.geo.BuyerLoginRe quest</value>
      <value>com.onevega.geoveggie.jaxb.geo.BuyerLoginRe sponse</value>
      <value>com.onevega.geoveggie.jaxb.geo.SellerLoginR equest</value>
      <value>com.onevega.geoveggie.jaxb.geo.SellerLoginR esponse</value>
      <value>com.onevega.geoveggie.jaxb.geo.SellerAvaila belityRequest</value>
      <value>com.onevega.geoveggie.jaxb.geo.BuyerRegistr ationRequest</value>
      <value>com.onevega.geoveggie.jaxb.geo.SellerRegist rationRequest</value>

      </list>
      </property>
      </bean>


      <bean id="geoveggie"
      class="org.springframework.ws.wsdl.wsdl11.DynamicW sdl11Definition">
      <property name="builder">
      <bean class="org.springframework.ws.wsdl.wsdl11.builder. XsdBasedSoap11Wsdl4jDefinitionBuilder">
      <property name="schema" value="/WEB-INF/xsd/geoveggie.xsd" />
      <property name="portTypeName" value="geoveggieService" />
      <property name="locationUri"
      value="http://localhost:8080/geoveggieService/services" />
      <property name="targetNamespace" value="http://onevega.com/gv/schemas" />
      </bean>
      </property>
      </bean>

      <bean id="buyer"
      class="com.onevega.geoveggie.endpoints.BuyerEndpoi nt" />

      <bean id="BuyerServiceImpl"
      class="com.onevega.geoveggie.services.buyer.BuyerS erviceImpl"> </bean>


      <bean id="seller"
      class="com.onevega.geoveggie.endpoints.SellerEndpo int" />

      </beans>


      Please see and tell me what i can change.

      Thanks in advance

      Regards
      sowmya

      Comment


      • #4
        As mentioend before please use [ code][/code ] tags when posting code/xml/stacktraces that way it remains readable ...

        Have you READ the stacktrace...

        Judging from it you are using a PropertyPlaceHolderConfigurer to configure your datasource from a properties file, but this file is nowhere to be found...

        Comment


        • #5
          spring-ws with databse connection

          Hi,

          sorry, now i am adding codes with quotes.please suggest me to help.
          Already i have put geoveggie-ws-servlet.xml in previous message.

          BuyerDAOImpl.java
          Code:
          public class BuyerDaoImpl implements BuyerDao
          {
          static final Logger logger = Logger.getLogger(BuyerDaoImpl.class);
          public BuyerDaoImpl() { }
           public boolean validateUserID(String buserID) throws BuyerDaoExecption{
             logger.debug((new StringBuilder()).append("-->validateBuyerID Buyer id =").append(buserID).toString());
                 String loginid = null;
                  boolean returnFlag = false;
                  Connection conn = null;
                  ResultSet rs = null;
                  PreparedStatement stmt = null;
                  try {
           conn = DBConnection.getConnection();
          stmt = conn.prepareStatement("SELECT BUYER_LOGINID FROM BUYER_LOGIN_DETAILS WHERE BUYER_LOGINID = ?");
          stmt.setString(1, buserID.toUpperCase());
                     for(rs = stmt.executeQuery(); rs.next();){
                          loginid = rs.getString("BUYER_LOGINID");
                      }
          returnFlag = loginid == null;
                  }
                  catch(SQLException e){
           throw new BuyerDaoExecption(e, (new StringBuilder()).append("SqlException @ DAO layer while checking user id =").append(buserID).toString());
                  }
                  catch(DBConnectionException e)
                  {throw new BuyerDaoExecption(e, (new StringBuilder()).append("SqlException @ DAO layer while checking user id =").append(buserID).toString());
                  }
                  finally{
          try{ DBConnection.close(conn, stmt, rs);}
          catch(DBConnectionException e){
             throw new BuyerDaoExecption(e, (new StringBuilder()).append("SqlException @ DAO layer while checking user id =").append(buserID).toString());} }
                  logger.debug((new StringBuilder()).append("<--validateBuyrerID User id =").append(buserID).toString());
                  return returnFlag;
              }
           public BuyerLoginResponse validateLogin(BuyerLoginRequest request)
                  throws BuyerDaoExecption
              {
                  logger.debug((new StringBuilder()).append("-->validateLogin buyer id DAO Layer=").append(request.getBuserId().toUpperCase()).toString());
                  BuyerLoginResponse outputResponceDTOobj = new BuyerLoginResponse();
                  String isLoginID = null;
                  String isPaswword = null;
                  //boolean isAdmin = false;
                  Connection conn = null;
                  ResultSet rs = null;
                  PreparedStatement stmt = null;
                  try
                  {conn = DBConnection.getConnection();
                   stmt = conn.prepareStatement("SELECT BUYER_LOGINID,BUYER_PASSWORD FROM BUYER_LOGIN_DETAILS WHERE BUYER_LOGINID = ? AND" +
          " BUYER_PASSWORD = ?"
          );
                      stmt.setString(1, request.getBuserId().toUpperCase());
                      stmt.setString(2, request.getBpassword());
                      for(rs = stmt.executeQuery(); rs.next();)
                      {
                          isLoginID = rs.getString("BUYER_LOGINID");
                          isPaswword = rs.getString("BUYER_PASSWORD");
                      }
           if(isLoginID != null && isLoginID.equals(request.getBuserId().toUpperCase()) && isPaswword != null && isPaswword.equals(request.getBpassword()))
                      {outputResponceDTOobj.setIsBuser(true);} else
                      {outputResponceDTOobj.setIsBuser(false); }
                  }catch(SQLException e)
                  {throw new BuyerDaoExecption(e, "SQLException @ DAO layer while validating user credentials");
                  }catch(DBConnectionException e)
                  {throw new BuyerDaoExecption(e, "SQLException @ DAO layer while validating user credentials");
                  }finally
                  { try{
                  DBConnection.close(conn, stmt, rs);
                     } catch(DBConnectionException e){ throw new BuyerDaoExecption(e, "SQLException @ DAO layer while validating user credentials");
              } }
                  logger.debug((new StringBuilder()).append("<--validateLogin User id =").append(request.getBuserId()).toString());
                  return outputResponceDTOobj;
              }......
          BuyerEndpoint.java
          Code:
          public class BuyerEndpoint 
          {
          static final Logger logger = Logger.getLogger(BuyerEndpoint.class);
          public BuyerEndpoint() { }
             @PayloadRoot(localPart = "BuyerLoginRequest", namespace = "http://onevega.com/gv/schemas")
              @ResponsePayload
              public BuyerLoginResponse validateLogin(@RequestPayload BuyerLoginRequest request)
              {
                  logger.debug((new StringBuilder()).append("--> validateLogin buyer ID=").append(request.getBuserId()).toString());
                  BuyerLoginResponse resp = null;
                  try
                  {
                      resp = SpringServicesBeanPool.getBuyerService().validateLogin(request);
                  }
                  catch(BuyerServiceException e)
                  {
                      logger.error("Exception at service layer while validating the buyer login", e);
                  }
                  logger.debug((new StringBuilder()).append("<-- validateLogin buyer ID=").append(request.getBuserId()).toString());
                  return resp;
              }
              @PayloadRoot(localPart = "BuyerRegistrationRequest", namespace = "http://onevega.com/gv/schemas")
              @ResponsePayload
              public FlagResponse registerBuyer(@RequestPayload BuyerRegistrationRequest request)
              {
                  logger.debug((new StringBuilder()).append("--> registerBuyer buyer ID=").append(request.getBuserId()).toString());
                  FlagResponse resp = null;
                  try
                  {
                      resp = SpringServicesBeanPool.getBuyerService().registerBuyer(request);
                  }
                  catch(BuyerServiceException e)
                  {
                      logger.error("Exception at service layer while registering user", e);
                  }
                  logger.debug((new StringBuilder()).append("<-- registerBuyer user ID=").append(request.getBuserId()).toString());
                  return resp;
              }........
          For connection i am using this class
          Pooledconnection.java
          Code:
          public class PooledConnection
          {
           public static PoolingDataSource dataSource = null;
              private static Properties properties = null;
              static final Logger logger = Logger.getLogger(PooledConnection.class);
          private PooledConnection(){ }
          
          public static void setupDataSource()
                  throws IOException{
                  loadProperties();
                  try {
                      Class.forName("com.mysql.jdbc.Driver").newInstance();
                  }
                  catch(InstantiationException e1)
                  {e1.printStackTrace();}
                  catch(IllegalAccessException e1)
                  { e1.printStackTrace(); }
                  catch(ClassNotFoundException e1)
                  { e1.printStackTrace();}
                  System.out.println("propertiest loaded");
                  GenericObjectPool connectionPool = new GenericObjectPool(null);
                  connectionPool.setMaxIdle(30);
                  connectionPool.setMaxActive(100);
                  System.out.println("creating connetcion factory");
                  org.apache.commons.dbcp.ConnectionFactory connectionFactory = new       DriverManagerConnectionFactory("jdbc:mysql://localhost:3306/new_geoveggie", "root", "");
              PoolableConnectionFactory poolableConnectionFactory = new PoolableConnectionFactory(connectionFactory, connectionPool, null, null, false, true);
                  dataSource = new PoolingDataSource(connectionPool);
                  try{System.out.println(dataSource.getConnection());}
                  catch(SQLException e)
                  {e.printStackTrace();}}
          
            private static void loadProperties()
                  throws IOException
              {
                  File f = new File("deatils.properties");
                  System.out.println(DBinitializer.CONTEXT_ROOT);
                  logger.debug((new StringBuilder()).append("Context root = ").append(DBinitializer.CONTEXT_ROOT).toString());
                  if(f.exists())
                  {
                      properties = new Properties();
                      FileInputStream in = new FileInputStream(f);
                      properties.load(in);
                      System.out.println(properties.getProperty("connection.url"));
                  } else
                  {
                      System.out.println("details.properties file not found");
                  }
              }
          public static Connection getConnection()
                  throws SQLException {
                  return dataSource.getConnection();}
          public static void main(String args[])
                  throws IOException, SQLException
              {
                  setupDataSource();
                  Connection con = getConnection();
                  System.out.println(con.getMetaData().getDatabaseProductName());
              }
          }
          BuyerserviceImpl.java
          Code:
          public class BuyerServiceImpl implements BuyerService
          
          {
          static final Logger logger = Logger.getLogger(BuyerServiceImpl.class);
             
              private BuyerDao buyerDao;
          
              public BuyerServiceImpl() {}
          public BuyerLoginResponse validateLogin(BuyerLoginRequest request)
                  throws BuyerServiceException
              {
                  logger.debug((new StringBuilder()).append("-->validateLogin buyer id =").append(request.getBuserId()).toString());
                  BuyerLoginResponse resp = null;
                  try
                  {
                      resp = buyerDao.validateLogin(request);
                  }
                  catch(BuyerDaoExecption e)
                  {
                      throw new BuyerServiceException(e, "Exception at service layer while validating user in the databse");
                  }
                  logger.debug((new StringBuilder()).append("<--validateLogin User id =").append(request.getBuserId()).toString());
                  return resp;
              }
          
              public FlagResponse registerBuyer(BuyerRegistrationRequest obj)
                  throws BuyerServiceException
              {
                  logger.debug((new StringBuilder()).append("-->registerBuyer Buyer id =").append(obj.getBuserId()).toString());
                  FlagResponse resp = new FlagResponse();
                  try
                  { resp.setFlag(buyerDao.registerBuyer(obj));
                  }
                  catch(BuyerDaoExecption e)
                  {  throw new BuyerServiceException(e, "Exception at service layer while registering buyer in the databse");
                  }
                  logger.debug((new StringBuilder()).append("<--registerBuyer buyer id =").append(obj.getBuserId()).toString());
                  return resp;
              }
          please find and tell me what i can add for the connection.why m getting the soap-fault in response.

          provide any examples for database connectio with spring-ws.
          Regards
          sowmya

          Comment


          • #6
            Why are you using spring?! In your code you do everything not to use spring...

            Start by fixing your configuration and use spring properly.

            1. Configure your datasource in a spring xml file (or javaconfig)
            2. Use dependency injection instead of ugly lookups
            3. Instead of plain JDBC use a JdbcTemplate
            4. Please sanity your code and remove the StringBuilders, they only make your code unreadable without any added benefit (no you don't get any performance gains by using it not in this case).
            4a (Use slf4j as a logging facede instead of commons logging that can do the concat for you by using placeholders.

            Currently I have no idea not without seeing the whole codebase and how everything works.

            Comment

            Working...
            X