/*
 * @(#)WebBeanTag.java
 *
 * Copyright 2000-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 java.io.PrintWriter;
import java.io.StringWriter;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspTagException;
import javax.servlet.jsp.tagext.Tag;
import javax.servlet.jsp.tagext.TagSupport;
import oracle.jbo.common.JBOClass;
import oracle.jbo.html.WebBean;

public class WebBeanTag extends TagSupport
{
   protected String sClass;
   protected WebBean wb;

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

   public void setWbclass(String sClass)
   {
      this.sClass = sClass;
   }

   protected void initializeBean()
      throws Exception
   {
      wb.initialize(pageContext);
   }

   /**
      * 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
   {
      try
      {
         Class wbClass = JBOClass.forName(sClass);
         wb = (WebBean) wbClass.newInstance();
      }
      catch (Exception ex)
      {
         throw new JspTagException(ex.getMessage());
      }
      
      
      ((WebBean)wb).setUsedInTag(true);

      pageContext.setAttribute(id, wb);
      
      return Tag.EVAL_BODY_INCLUDE;
   }

   /**
      * Process the end tag. This method will be called on all Tag objects.
      *
      * All instance state associated with this instance must be reset.
      */
   public int doEndTag() throws JspException
   {
      try
      {
         initializeBean();
      }
      catch (Exception ex)
      {
         StringWriter writer = new StringWriter();
         PrintWriter prn = new PrintWriter(writer);

         ex.printStackTrace(prn);
         prn.flush();

         throw new JspTagException(writer.toString());
      }

      return super.doEndTag();
   }

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

}

