
// Copyright (c) 1999, 2000 Oracle Corporation
package oracle.jbo.html.jsp.datatags;

import javax.servlet.jsp.tagext.*;
import javax.servlet.jsp.*;
import oracle.jdeveloper.html.*;
import oracle.jbo.*;
import java.io.*;
import oracle.jbo.html.jsp.*;

/**
 * A Class class.
 * <P>
 * @author Juan Oropeza
 */
public class DynamicViewObjectTag extends BodyTagSupport
{
   String sAppName;
   String sViewObject;
   String sQuery = null;
   int    nRangeSize = 0;
   
  /**
   * Constructor
   */
  public DynamicViewObjectTag()
  {
  }

  public void setRangesize(String sValue) throws JspException
  {
   try
   {
      nRangeSize = Integer.parseInt(sValue);
   }
   catch(Exception ex)
   {
      throw new JspException(ex.getMessage());
   }
  }

  public void setAppid(String sAppName)
  {
    this.sAppName = sAppName;
  }

  public void setName(String sViewObject)
  {
    this.sViewObject = sViewObject;
  }

   /**
   * doEndTag
   * @return int
   * @exception javax.servlet.jsp.JspException
   */
   public int doEndTag() throws JspException
   {
      try
      {
         if(this.bodyContent != null)
         {
              StringWriter strout = new StringWriter();

              bodyContent.writeOut(strout);

              this.sQuery = strout.toString();

              // get appmodule instance
              ApplicationModule am = JSPApplicationRegistry
                 .getInstance()
                 .getAppModuleFromContexts(sAppName, pageContext.getSession(), pageContext);

              if(am == null)
              {
                   throw new RuntimeException("Unable to get Application Module instance[" + sAppName + "]");
              }

              ViewObject view = am.findViewObject(sViewObject);

              if(view != null)
              {
                  // remove the old instance
                  view.remove();
              }

              view = am.createViewObjectFromQueryStmt(sViewObject, sQuery);

              if(view == null)
              {
                  throw new RuntimeException("Unable to create view object[" + sViewObject + "]");
              }

              RowSet rs = view.getRowSet();

              if(nRangeSize != 0)
              {
               rs.setRangeSize(nRangeSize);
              }

         }
      }
      catch(Exception ex)
      {
         throw new JspException(ex.getMessage());
      }
      return Tag.EVAL_PAGE;
   }

  /**
   * doStartTag
   * @return int
   * @exception javax.servlet.jsp.JspException
   */
  public int doStartTag() throws JspException {

    return BodyTag.EVAL_BODY_TAG;
  }

  /**
     * release() called after doEndTag() to reset state
     */
  public void release()
  {
    super.release();

    sAppName = null;
    sViewObject = null;
    sQuery = null;
    nRangeSize = 0;
  }
}

