/*
 * @(#)DataSourceRefTag.java
 *
 * Copyright 2001-2002 by Oracle Corporation,
 * 500 Oracle Parkway, Redwood Shores, California, 94065, U.S.A.
 * All rights reserved.
 *
 * This software is the confidential and proprietary information
 * of Oracle Corporation.
 */

package oracle.jbo.html.jsp.datatags;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.PageContext;
import javax.servlet.jsp.tagext.Tag;
import javax.servlet.jsp.tagext.TagSupport;
import oracle.jbo.JboException;
import oracle.jbo.html.DataSource;

public class DataSourceRefTag extends TagSupport
{
   String sReference;

   public DataSourceRefTag()
   {
      super();
      reset();
   }

   public void setReference(String sReference)
   {
      this.sReference = sReference;
   }

   /**
      * Process the start tag for this instance.
      *
      * The doStartTag() method assumes that all setter methods have been
      * invoked before.
      *
      * When this method is invoked, the body has not yet been invoked.
      *
      * @returns EVAL_BODY_INCLUDE if the tag wants to process body, SKIP_BODY if it
      * does ont want to process it.
      */
   public int doStartTag() throws JspException
   {
      DataSource ds = null;

      if (sReference != null)
      {
         // Use the REQUEST_SCOPE variable to get the datasource instance
         ds = (DataSource) pageContext.getAttribute(sReference, PageContext.REQUEST_SCOPE);

         if (ds == null)
         {
            if (sReference.indexOf('.') >=0)
            {
               ds = Utils.getDataSourceFromContext(pageContext, sReference);
            }
            
            if (ds == null)
            {
               throw new JboException(Res.format(Res.DATASOURCEREF_CANT_FIND_DS, sReference));
            }
         }
      }
      
      // Set the attribute on the pageContext for the scriptable variable (PAGE_SCOPE)
      pageContext.setAttribute(id, ds);
      
      return Tag.EVAL_BODY_INCLUDE;
   }

   private void reset()
   {
      sReference = null;
   }
   
   /**
     * release() called after doEndTag() to reset state
     */
   public void release()
   {
      super.release();
      reset();
   }

}
