Thank you for visiting! If you liked the site, please add a bookmark, else add a critical comment! Would you like to visit Greece? Traditional Greek flag This real estate site is only available in Greek! The holy mountain

Sunday, 16 September 2012

Processing BLOBs via the ImageServlet

In this post an alternative code version to the traditional ImageServlet  will be given, supplementing the one presented in the book named Oracle Fusion Developer Guide (p.409), by F.Nimphius and L.Munsinger and other official Oracle aces' and employees' blogs. This alternative version will use the  EJB 3 way to get rid of the surplus database definition hard coded in the doGet() method. As an epilogue, further criticism will be provided, against using that technique of obtaining jdbc connections to the database.

Here is the modified code, with the original straight jdbc code commented out:

package actionbazaar.view.servlet;


import actionbazaar.buslogic.PlaceItem;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.OutputStream;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import oracle.jbo.domain.BlobDomain;

import org.apache.log4j.Logger;


public class ImageServlet extends HttpServlet {
    private static final String CONTENT_TYPE = "image/jpg; charset=utf-8";
    @SuppressWarnings("compatibility:988932384557339885")
    private static final long serialVersionUID = 1L;
    private Logger logger = Logger.getLogger(this.getClass().getName());
   
    public void init(ServletConfig config) throws ServletException {
        super.init(config);
    }

    public void doGet(HttpServletRequest request,
                      HttpServletResponse response) throws ServletException,
                                                           IOException {
        response.setContentType(CONTENT_TYPE);
        Long itemId = new Long(request.getParameter("itemId"));
        if (logger.isDebugEnabled())
            logger.debug("itemId = " + itemId);
        try {
                Context context = new InitialContext();
                PlaceItem placeItem = (PlaceItem)context.lookup("ejb3inaction-Model-PlaceItem#actionbazaar.buslogic.PlaceItem");
                byte[] image  = placeItem.getImageByItemId(itemId);

            if (image != null) {
                BlobDomain bld = new BlobDomain(image);

                OutputStream os = response.getOutputStream();
                BufferedInputStream in =  new BufferedInputStream(bld.getBinaryStream());
                int b;
                byte[] buffer = new byte[10240];

                while ((b = in.read(buffer, 0, 10240)) != -1) {
                    os.write(buffer, 0, b);
                }
                os.close();
            } else {
                    if (logger.isDebugEnabled())
                        logger.debug("No  image exists yet for itemId: " + itemId);
                }
        } catch (NamingException e){
            e.printStackTrace();   
        }
        catch (IOException e){
            e.printStackTrace();   
        }
       /*
        Connection conn = null;


        try {
            Context ctx = new InitialContext();

//Datasource as defined in <res-ref-name> element of weblogic.xml
            DataSource ds =
                (DataSource)ctx.lookup("jdbc/ActionBazaarEJB3inActionDS");

            conn = ds.getConnection();
            PreparedStatement statement =
                conn.prepareStatement("SELECT IMAGE " +
                                      " FROM ITEMS" +
                                    " WHERE ITEM_ID= ? ");
            statement.setInt(1, new Integer(itemId));
            ResultSet rs = statement.executeQuery();

            if (rs.next()) {
                Blob blob = rs.getBlob("IMAGE");

                BufferedInputStream in =
                    new BufferedInputStream(blob.getBinaryStream());
                int b;
                byte[] buffer = new byte[10240];

                while ((b = in.read(buffer, 0, 10240)) != -1) {
                    os.write(buffer, 0, b);
                }
                os.close();

            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (conn != null) {

                    conn.close();
                }

            } catch (SQLException sqle) {
                sqle.printStackTrace();

            }

        }*/
      
    }

   }


Besides hard coding the database connection string and the SQL query too, using doGet() instead of init() to setup a database connection and destroy() to close it, is not widely considered a good idea. Thus, a newer version of the servlet code  will be most welcome, due to performance reasons as well. Presenting that code would go beyond the scope of such a post, so I am turning once again to the Oracle experts mentioned above for another alternative solution!

References

http://tompeez.wordpress.com/2011/12/16/jdev11-1-2-1-0-handling-imagesfiles-in-adf-part-3/
http://www.baigzeeshan.com/2010/09/store-images-in-blob-in-oracle-adf.html
http://ranajitsahoo.blogspot.gr/2008/04/how-to-display-content-of-blob-column.html
http://www.javaranch.com/journal/200601/JDBCConnectionPooling.html