title: retrieve p7m file from db2 blob field
body: <p>I need to retrieve a p7m pdf file stored in blob field and put it for direct download by pointing a specific url.</p>
  
  <p>Now I'm using the following code for retrieve and publish pdf, but opening the file saved with a tool for view digital signature the signature is not valid and the pdf seems like corrupted.</p>
  
  <pre><code>public byte[] getPdfOrdini(String xxx, String tipo) throws Exception, SQLException {
      Blob pdf;
      byte[] pdfData = null;
      Connection conn = new test().getConnectionOrdini();
      PreparedStatement pstmt = null;
  
      // Query
      if(tipo.equalsIgnoreCase("pnf"))
          pstmt = conn.prepareStatement("Select ... From .. Where ..");
      if(tipo.equalsIgnoreCase("pf"))
          pstmt = conn.prepareStatement("Select ... From .. Where .. = ?");
      pstmt.setString(1, xxx);
      ResultSet rset = pstmt.executeQuery();
  
      if(tipo.equalsIgnoreCase("pnf")){
  
          while (rset.next()) {
              pdf = rset.getBlob(1);
              pdfData = pdf.getBytes(1, (int) pdf.length());
          }
  
          //System.out.println("dimensione blob --&gt; " + pdfData.length);
      }else{
          while (rset.next()) {
              pdf = rset.getBlob(1);
              pdfData = pdf.getBytes(1, (int) pdf.length());
          }
      }
      rset.close();
      pstmt.close();
  
      return pdfData;
  }
  </code></pre>
  
  <p>and this code for publish pdf for download:</p>
  
  <pre><code>&lt;jsp:useBean id="PDF" class="pdf.test" scope="session" /&gt;
  &lt;%
  Connection conn = null;
  
  if ( request.getParameter("protocollo") != null )
  {
  
  String protocollo = request.getParameter("xxx") ;
  String tipo = request.getParameter("type");   
  
  try
  {  
     String downloadFileName = "O" + xxx + ".pdf.p7m";
     conn = new pdf.test().getConnection();
     conn.setAutoCommit (false);  
  
     // get the image from the database
     byte[] pdfData = PDF.getPdfOrdini(xxx, tipo);   
     // display the image
  
     File pdf = new File(downloadFileName);
     FileOutputStream fos = new FileOutputStream(pdf);
     fos.write(pdfData);
     fos.flush();
     fos.close();
  
     response.setContentType( "application/x-download" );
     response.setHeader( "Content-Disposition", "attachment; filename=" + downloadFileName );
     conn.close();
  }
  catch (IllegalStateException il){
  }
  catch (Exception e)
  {
    e.printStackTrace();
    throw e;
  }
  finally
  {
  
  }  
  }
  %&gt;
  </code></pre>
  
  <p>any help is appreciated.</p>