Sunday, November 11, 2012

javax.servlet.ServletException: java.sql.SQLException: Closed Connection

When using JSTL setDataSource:

<sql:setDataSource var="domainds" driver="${DS_JDBCDRIVER}" url="${DS_URL}" user="${DS_USERNAME}" password="${DS_ENCRYPTED_PASSWORD}" scope="session"/>

as documented here

http://docs.oracle.com/javaee/5/jstl/1.1/docs/tlddocs/sql/setDataSource.html

and then I use the var datasource as in:

<sql:query var="rsMessageCount" dataSource="${domainds}" scope="request"> select DATA_VALUE from ${datatable} where MSG_GUID='${theMSGGUIDvalue}' </sql:query>

it all works fine until I try to do a

 java.sql.Blob blob = (java.sql.Blob)((org.apache.taglibs.standard.tag.common.sql.ResultImpl)(request.getAttribute("rsMessageCount"))).getRowsByIndex()[0][0];
 if (blob != null) {
  byte[] bdata = blob.getBytes(1, (int) blob.length());
  String text = new String(bdata);



When I do the blob.getBytes bit, I get a

java.sql.SQLException: Closed Connection oracle.sql.BLOB.getDBAccess(BLOB.java:1087) oracle.sql.BLOB.getBytes(BLOB.java:331) oracle.sql.BLOB.getBytes(BLOB.java:217)

This ONLY if I use setDataSource. If I use a datasource declared in the context.xml file, I have no issue.

This is the only way I managed to make it work:



    public static String getBlobData(String driver, String url, String username, String password, String sqlQuery) throws Exception {
 String result = "";
 Class.forName(driver);
 Connection conn = DriverManager.getConnection(url, username, password);
 try {
     Statement stmt = conn.createStatement();
     try {
  ResultSet rset = stmt.executeQuery(sqlQuery);
  try {
      rset.next();
      java.sql.Blob blob = (java.sql.Blob) rset.getBlob(1);
      if (blob != null) {
   byte[] bdata = blob.getBytes(1, (int) blob.length());
   String text = new String(bdata);
   text = text.replace("<", "<"); // the second is ampersand followed by lt;
   result = text;
      } else {
   result = "empty body";
      }

  } finally {
      try {
   rset.close();
      } catch (Exception e) {
   e.printStackTrace();
      }
  }
     } finally {
  try {
      stmt.close();
  } catch (Exception e) {
      e.printStackTrace();
  }
     }
 } finally {
     try {
  conn.close();
     } catch (Exception e) {
  e.printStackTrace();
     }
 }
 return result;
    }




No comments: