user5313398
user5313398

Reputation: 753

Calling webservice should be same thread or separate thread?

Below I have a socket programme code snippet. What I am doing first if there is data then I process in the first section where I use the dbconn1. There after based on the data received I got a variable callWebService and if this is set to callWebService=1 then I have an if statement to make another new connection and call and external webservice. I have split them due to at times the web service is down and failed causing my whole my first section to be halted. I am not sure is this the correct method to do or should the section section should be split into a separate thread altogether? Which is more efficient to handle because I notice when the webservice is down it cause my resource to go up cause the database connection being hold up

BufferedWriter writer1 = null; 
Connection dbconn1 = null;  
Connection dbconn2 = null;  
    public void run() { // etc
    writer1 = null;
    String message="";
    BufferedReader reader1 = null; 
    try { 

        writer1 =  new BufferedWriter(new OutputStreamWriter(receivedSocketConn1.getOutputStream()));
        reader1 = new BufferedReader(new InputStreamReader(receivedSocketConn1.getInputStream()));
        receivedSocketConn1.setSoTimeout(60000);
        int nextChar=0;
        int callWebService=0;
        while ((nextChar=reader1.read()) != -1) {    
            message += (char) nextChar; 
            if (nextChar == '*'){

                try{   
                   System.out.println("\n\n Trying establish a new db connection ");
                   dbconn1 = connectionPool.getConnection();
                   dbconn1.setAutoCommit(false);
                   System.out.println("\n\n Checking db connection status "+dbconn1.isClosed());
                   if ((dbconn1 == null) || dbconn1.isClosed()) {
                        System.out.println("\n\n db connection status is closed");
                        dbconn1 = connectionPool.getConnection();
                        dbconn1.setAutoCommit(false);
//other codes follow here.

                        // e.g. the callWebService=1;
                        dbconn1.commit();
                   }
                }
                catch (SQLException ex){ 
                  System.out.println("Error SQL Exception : "+ex.toString());
                  ex.printStackTrace(System.out);
                  try{    
                    dbconn1.rollback();  
                  } 
                   catch (Exception rollback) {    
                    System.out.println("\nRollback dbconn1 :");  
                    rollback.printStackTrace(System.out);
                  }
               }
               catch (Exception e){
                  System.out.println("\nSQL Error here :");
                  e.printStackTrace(System.out);
                 try{    
                  dbconn1.rollback();  
                 } 
                 catch (Exception rollback) {    
                   System.out.println("\nRollback dbconn1 :");  
                   rollback.printStackTrace(System.out);
                 }
               }
               finally{
                  try {

                  if ( dbconn1 != null ) {
                    dbconn1.close();
                    System.out.println("\n\n dbConn1 is being closed");
                 }

                 }
                catch(SQLException ex){
                  System.out.println("SQLException has been caught for dbConn1 close");
                  ex.printStackTrace();
              }

             if(callWebService==1){

                 try{   
                     System.out.println("\n\n Trying establish a new db connection ");
                     dbconn2 = connectionPool.getConnection();
                     dbconn2.setAutoCommit(false);
                     sendIncomingData(dataID, dataString) 
                     dbconn2.commit();
                  }
                  catch (SQLException ex){ 
                     System.out.println("Error SQL Exception : "+ex.toString());
                     ex.printStackTrace(System.out);
                     try{    
                       dbconn2.rollback();  
                     } 
                      catch (Exception rollback) {    
                       System.out.println("\nRollback dbconn2 :");  
                       rollback.printStackTrace(System.out);
                     }
                  }
                  catch (Exception e){
                     System.out.println("\nSQL Error here :");
                     e.printStackTrace(System.out);
                    try{    
                     dbconn2.rollback();  
                    } 
                    catch (Exception rollback) {    
                      System.out.println("\nRollback dbconn2 :");  
                      rollback.printStackTrace(System.out);
                    }
                  }
                  finally{
                     try {

                     if ( dbconn2 != null ) {
                       dbconn2.close();
                       System.out.println("\n\n dbConn2 is being closed");
                    }

                    }
                   catch(SQLException ex){
                     System.out.println("SQLException has been caught for dbConn1 close");
                     ex.printStackTrace();
                 }
             }



            } 

          }
      }


     }
     catch (SocketTimeoutException ex){ 
          System.out.println("SocketTimeoutException has been caught ");
          ex.printStackTrace();
     }  
     catch (IOException ex) { 
          System.out.println("IOException has been caught ");
          ex.printStackTrace();
     }  
     catch (Exception ex) { 

          System.out.println("Exception has been caught");
          ex.printStackTrace(System.out);
     }      
     finally{

       try {
           if (writer1 != null ) {
               writer1.close();
           }               
       }
       catch(IOException ex){
          System.out.println("IOException has been caught for finally");
          ex.printStackTrace(System.out);
       }
     }
}

void sendIncomingData(int dataID, String dataString) throws Exception {

        try{
            SOAPConnectionFactory soapConnectionFactory = SOAPConnectionFactory.newInstance();
            SOAPConnection soapConnection = soapConnectionFactory.createConnection();
            String url = "http://**********/webservice.asmx?WSDL";
            SOAPMessage soapACK = soapConnection.call(soapCalling(dataID,dataString), url);
            printSOAP(soapACK,dataID); //do some sql insert/update in this function
           }
           catch (Exception e){
                 e.printStackTrace();
                 System.err.println(e.toString());
                 throw e;
           }

}
SOAPMessage createSOAPIncoming(int dataID,String dataString) throws Exception {
          MessageFactory messageFactory = MessageFactory.newInstance();
        SOAPMessage soapMessage = messageFactory.createMessage();
        SOAPPart soapPart = soapMessage.getSOAPPart();

        String serverURI = "http://*******";

        // SOAP Envelope
        SOAPEnvelope envelope = soapPart.getEnvelope();
        SOAPBody body = envelope.getBody();
        SOAPBodyElement element = body.addBodyElement(envelope.createName("*******"));
        element.addChildElement("dataID").addTextNode(dataID);
        element.addChildElement("dataString").addTextNode(dataString);
        MimeHeaders headers = soapMessage.getMimeHeaders();
        soapMessage.saveChanges();

        /* Print the request message */
        System.out.print("\n\n Request SOAP Message To ACK FOR  = ");
        soapMessage.writeTo(System.out);
        System.out.print("\n\n After Print  = ");
        System.out.println();

        return soapMessage;
}

Very often I get this error from the webservice if its down.

SEVERE: SAAJ0537: Invalid Content-Type. Could be an error message instead of a SOAP message
com.sun.xml.internal.messaging.saaj.SOAPExceptionImpl: com.sun.xml.internal.messaging.saaj.SOAPExceptionImpl: Invalid Content-Type:text/html. Is this an error message instead of a SOAP response?
at com.sun.xml.internal.messaging.saaj.client.p2p.HttpSOAPConnection.call(HttpSOAPConnection.java:148)
at sk1$ConnectionHandler.sendIncomingData(sk1.java:2753)
at sk1$ConnectionHandler.run(sk1.java:2057)
at java.lang.Thread.run(Thread.java:722)
Caused by: com.sun.xml.internal.messaging.saaj.SOAPExceptionImpl: Invalid Content-Type:text/html. Is this an error message instead of a SOAP response?
at com.sun.xml.internal.messaging.saaj.soap.MessageImpl.identifyContentType(MessageImpl.java:649)
at com.sun.xml.internal.messaging.saaj.soap.MessageFactoryImpl.createMessage(MessageFactoryImpl.java:85)
at com.sun.xml.internal.messaging.saaj.client.p2p.HttpSOAPConnection.post(HttpSOAPConnection.java:327)
at com.sun.xml.internal.messaging.saaj.client.p2p.HttpSOAPConnection.call(HttpSOAPConnection.java:144)

Upvotes: 0

Views: 616

Answers (1)

Uday Shankar
Uday Shankar

Reputation: 844

The solution to the problem is not multi threading but proper implementation of the business logic.

  • If both the call of web service and DB stuff you are doing are functionally independent then you can separate the functionality into independent blocks and release the connection or implement the functionality in another threads.
  • If both the call of web service and DB stuff are interdependent then you have to figure out a way to catch the web service down situation deal with the situation and release the connection.

Upvotes: 1

Related Questions