coliver     2003/03/03 10:50:26

  Modified:    src/java/org/apache/cocoon/components/flow/javascript
                        JSCocoon.java JavaScriptInterpreter.java
  Added:       src/java/org/apache/cocoon/components/flow/javascript
                        ScriptableConnection.java ScriptableResult.java
  Log:
  Cocoon Flow Layer Database API a la jstl
  
  Revision  Changes    Path
  1.19      +30 -0     
xml-cocoon2/src/java/org/apache/cocoon/components/flow/javascript/JSCocoon.java
  
  Index: JSCocoon.java
  ===================================================================
  RCS file: 
/home/cvs/xml-cocoon2/src/java/org/apache/cocoon/components/flow/javascript/JSCocoon.java,v
  retrieving revision 1.18
  retrieving revision 1.19
  diff -u -r1.18 -r1.19
  --- JSCocoon.java     3 Mar 2003 18:39:37 -0000       1.18
  +++ JSCocoon.java     3 Mar 2003 18:50:25 -0000       1.19
  @@ -77,6 +77,9 @@
   import org.apache.avalon.framework.component.ComponentException;
   import org.apache.avalon.framework.component.Component;
   
  +import org.apache.avalon.excalibur.datasource.DataSourceComponent;
  +
  +
   /**
    * JavaScript interface to various Cocoon abstractions.
    *
  @@ -189,6 +192,33 @@
     {
       return manager;
     }
  +
  +    /**
  +     * Get a Scriptable JDBC Connection
  +     * @param selector 
  +     * @return instance of ScriptableConnection
  +     */
  +
  +    public Object jsFunction_getConnection(String selectorValue) 
  +     throws Exception {
  +     ComponentSelector selector = 
  +         (ComponentSelector)manager.lookup(DataSourceComponent.ROLE + "Selector");
  +     try {
  +         DataSourceComponent ds = 
  +             (DataSourceComponent)selector.select(selectorValue);
  +         if (ds == null) {
  +             return null;
  +         }
  +         ScriptableConnection conn = 
  +             new ScriptableConnection(getTopLevelScope(this), ds.getConnection());
  +         conn.setPrototype(getClassPrototype(this, conn.getClassName()));
  +         conn.setParentScope(getTopLevelScope(this));
  +         return conn;
  +     } finally {
  +         manager.release(selector);
  +     }
  +    }
  +
   
     /**
      * Load the file specified as argument. Registers the file with the
  
  
  
  1.23      +4 -0      
xml-cocoon2/src/java/org/apache/cocoon/components/flow/javascript/JavaScriptInterpreter.java
  
  Index: JavaScriptInterpreter.java
  ===================================================================
  RCS file: 
/home/cvs/xml-cocoon2/src/java/org/apache/cocoon/components/flow/javascript/JavaScriptInterpreter.java,v
  retrieving revision 1.22
  retrieving revision 1.23
  diff -u -r1.22 -r1.23
  --- JavaScriptInterpreter.java        3 Mar 2003 14:51:17 -0000       1.22
  +++ JavaScriptInterpreter.java        3 Mar 2003 18:50:25 -0000       1.23
  @@ -168,6 +168,10 @@
         // Wrapper for WebContinuation
         ScriptableObject.defineClass(scope, JSWebContinuation.class);
   
  +      // Wrapper for JDBC 
  +      ScriptableObject.defineClass(scope, ScriptableConnection.class);
  +      ScriptableObject.defineClass(scope, ScriptableResult.class);
  +
         // Define some functions on the top level scope
         String[] names = { "print" };
         try {
  
  
  
  1.1                  
xml-cocoon2/src/java/org/apache/cocoon/components/flow/javascript/ScriptableConnection.java
  
  Index: ScriptableConnection.java
  ===================================================================
  /*
  
   ============================================================================
                     The Apache Software License, Version 1.1
   ============================================================================
  
   Copyright (C) 1999-2003 The Apache Software Foundation. All rights reserved.
  
   Redistribution and use in source and binary forms, with or without modifica-
   tion, are permitted provided that the following conditions are met:
  
   1. Redistributions of  source code must  retain the above copyright  notice,
      this list of conditions and the following disclaimer.
  
   2. Redistributions in binary form must reproduce the above copyright notice,
      this list of conditions and the following disclaimer in the documentation
      and/or other materials provided with the distribution.
  
   3. The end-user documentation included with the redistribution, if any, must
      include  the following  acknowledgment:  "This product includes  software
      developed  by the  Apache Software Foundation  (http://www.apache.org/)."
      Alternately, this  acknowledgment may  appear in the software itself,  if
      and wherever such third-party acknowledgments normally appear.
  
   4. The names "Apache Cocoon" and  "Apache Software Foundation" must  not  be
      used to  endorse or promote  products derived from  this software without
      prior written permission. For written permission, please contact
      [EMAIL PROTECTED]
  
   5. Products  derived from this software may not  be called "Apache", nor may
      "Apache" appear  in their name,  without prior written permission  of the
      Apache Software Foundation.
  
   THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
   INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
   FITNESS  FOR A PARTICULAR  PURPOSE ARE  DISCLAIMED.  IN NO  EVENT SHALL  THE
   APACHE SOFTWARE  FOUNDATION  OR ITS CONTRIBUTORS  BE LIABLE FOR  ANY DIRECT,
   INDIRECT, INCIDENTAL, SPECIAL,  EXEMPLARY, OR CONSEQUENTIAL  DAMAGES (INCLU-
   DING, BUT NOT LIMITED TO, PROCUREMENT  OF SUBSTITUTE GOODS OR SERVICES; LOSS
   OF USE, DATA, OR  PROFITS; OR BUSINESS  INTERRUPTION)  HOWEVER CAUSED AND ON
   ANY  THEORY OF LIABILITY,  WHETHER  IN CONTRACT,  STRICT LIABILITY,  OR TORT
   (INCLUDING  NEGLIGENCE OR  OTHERWISE) ARISING IN  ANY WAY OUT OF THE  USE OF
   THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  
  */
  package org.apache.cocoon.components.flow.javascript;
  import org.mozilla.javascript.*;
  import java.sql.*;
  
  /**
   * Wraps a JDBC connection and provides an API similar to JSTL
   * A ScriptableConnection provides two methods:
   *
   * <UL>
   * <LI>query([String] sql, [Number] startRow, [Number] maxRows)</LI>
   * <LI>update([String] sql)</LI>
   * </UL>
   * The object returned by <code>query</code> contains the following
   * properties:
   * <UL>
   * <LI>[Array] rows - an array of row objects</LI>
   * <LI>[Array] rowsByIndex - An array with an array per row of column values</LI>
   * <LI>[Array] columnNames - An array of column names</LI>
   * <LI>[Number] rowCount - Number of rows returned</LI>
   * <LI>[Boolean] limitedByMaxRows - true if not all rows are included due to 
matching a maximum value </LI>
   * </UL>
   */
  
  public class ScriptableConnection extends ScriptableObject {
  
      Connection connection;
      Scriptable wrapper;
  
      static Object wrap(final Scriptable wrapper, 
                       final Scriptable wrapped,
                       Object obj) {
        if (obj instanceof Function) {
            return wrap(wrapper, wrapped, (Function)obj);
        }
        return obj;
      }
  
      static Function wrap(final Scriptable wrapper, 
                         final Scriptable wrapped, 
                         final Function fun) {
        return new Function() {
                public Object call(Context cx, Scriptable scope, Scriptable thisObj,
                                   Object[] args)  throws JavaScriptException {
                    if (thisObj == wrapper) {
                        thisObj = wrapped;
                    }
                    return fun.call(cx, scope, thisObj, args);
                }
  
                public Scriptable construct(Context cx, Scriptable scope, 
                                            Object[] args)
                    throws JavaScriptException {
                    return fun.construct(cx, scope, args);
                }
  
                public String getClassName() {
                    return fun.getClassName();
                }
                
                public Object get(String name, Scriptable start) {
                    return fun.get(name, fun);
                }
  
                public Object get(int index, Scriptable start) {
                    return fun.get(index, fun);
                }
  
                public boolean has(String name, Scriptable start) {
                    return fun.has(name, start);
                }
  
                public boolean has(int index, Scriptable start) {
                    return fun.has(index, start);
                }
  
  
                public void put(String name, Scriptable start, Object value) {
                    fun.put(name, start, value);
                }
  
                public void put(int index, Scriptable start, Object value) {
                    fun.put(index, start, value);
                }
  
                public void delete(String name) {
                    fun.delete(name);
                }
  
                public void delete(int index) {
                    fun.delete(index);
                }
  
                public Scriptable getPrototype() {
                    return fun.getPrototype();
                }
  
                public void setPrototype(Scriptable prototype) {
                }
  
                public Scriptable getParentScope() {
                    return fun.getParentScope();
                }
  
                public void setParentScope(Scriptable parent) {
                }
  
                public Object[] getIds() {
                    return fun.getIds();
                }
  
                public Object getDefaultValue(Class hint) {
                    return fun.getDefaultValue(hint);
                }
  
                public boolean hasInstance(Scriptable instance) {
                    return fun.hasInstance(instance);
                }
  
            };
      }
  
      public String getClassName() {
        return "Database";
      }
  
      public ScriptableConnection() {
      }
  
      public static void finishInit(Scriptable proto) {
      }
  
      public static Scriptable jsConstructor(Context cx, Object[] args,
                                           Function ctorObj, 
                                           boolean inNewExpr)
        throws Exception {
        Connection conn = null;
        if (args.length > 0) {
            Object arg = args[0];
            if (arg instanceof Wrapper) {
                arg = ((Wrapper)arg).unwrap();
            }
            if (arg instanceof Connection) {
                conn = (Connection)arg;
            }
        }
        if (conn == null) {
            throw new JavaScriptException("expected an instance of 
java.sql.Connection");
        }
        ScriptableConnection result = new ScriptableConnection(ctorObj, conn);
        return result;
      }
  
  
      public ScriptableConnection(Scriptable parent, Connection conn) {
        this.connection = conn;
        this.wrapper = Context.toObject(connection, parent);
      }
  
      public Object jsFunction_query(String sql, 
                                   int startRow, 
                                   int maxRows) throws Exception {
        Statement stmt = connection.createStatement();
        ResultSet rs = stmt.executeQuery(sql);
        if (maxRows == 0) {
            maxRows = -1;
        }
        ScriptableResult s = new ScriptableResult(this, rs, 
                                                  startRow, maxRows);
        s.setParentScope(getTopLevelScope(this));
        s.setPrototype(getClassPrototype(this, s.getClassName()));
        return s;
      }
  
      public int jsFunction_update(String sql) throws Exception {
        Statement stmt = connection.createStatement();
        stmt.execute(sql);
        return stmt.getUpdateCount();
      }
  
      public Object get(String name, Scriptable start) {
        if (wrapper != null) {
            if (name.equals("createStatement")) {
                return super.get(name, start);
            }
            if (name.equals("createJDBCStatement")) {
                return super.get(name, start);
  
            }
            Object result = wrapper.get(name, wrapper);
            if (result != NOT_FOUND) {
                return wrap(this, wrapper, result);
            }
        }
        return super.get(name, start);
      }
  
      public boolean has(String name, Scriptable start) {
        if (wrapper != null) {
            if (wrapper.has(name, wrapper)) {
                return true;
            }
        }
        return super.has(name, start);
      }
  
      public boolean has(int index, Scriptable start) {
        if (wrapper != null) {
            if (wrapper.has(index, start)) {
                return true;
            }
        }
        return super.has(index, start);
      }
  
      public Object get(int index, Scriptable start) {
        if (wrapper != null) {
            Object result = wrapper.get(index, start);
            if (result != NOT_FOUND) {
                return wrap(this, wrapper, result);
            }
        }
        return super.get(index, start);
      }
  
      public void put(String name, Scriptable start, Object value) {
        if (wrapper != null) {
            wrapper.put(name, wrapper, value);
            return;
        }
        super.put(name, start, value);
      }
  
  }
  
  
  
  
  
  
  1.1                  
xml-cocoon2/src/java/org/apache/cocoon/components/flow/javascript/ScriptableResult.java
  
  Index: ScriptableResult.java
  ===================================================================
  /*
  
   ============================================================================
                     The Apache Software License, Version 1.1
   ============================================================================
  
   Copyright (C) 1999-2003 The Apache Software Foundation. All rights reserved.
  
   Redistribution and use in source and binary forms, with or without modifica-
   tion, are permitted provided that the following conditions are met:
  
   1. Redistributions of  source code must  retain the above copyright  notice,
      this list of conditions and the following disclaimer.
  
   2. Redistributions in binary form must reproduce the above copyright notice,
      this list of conditions and the following disclaimer in the documentation
      and/or other materials provided with the distribution.
  
   3. The end-user documentation included with the redistribution, if any, must
      include  the following  acknowledgment:  "This product includes  software
      developed  by the  Apache Software Foundation  (http://www.apache.org/)."
      Alternately, this  acknowledgment may  appear in the software itself,  if
      and wherever such third-party acknowledgments normally appear.
  
   4. The names "Apache Cocoon" and  "Apache Software Foundation" must  not  be
      used to  endorse or promote  products derived from  this software without
      prior written permission. For written permission, please contact
      [EMAIL PROTECTED]
  
   5. Products  derived from this software may not  be called "Apache", nor may
      "Apache" appear  in their name,  without prior written permission  of the
      Apache Software Foundation.
  
   THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
   INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
   FITNESS  FOR A PARTICULAR  PURPOSE ARE  DISCLAIMED.  IN NO  EVENT SHALL  THE
   APACHE SOFTWARE  FOUNDATION  OR ITS CONTRIBUTORS  BE LIABLE FOR  ANY DIRECT,
   INDIRECT, INCIDENTAL, SPECIAL,  EXEMPLARY, OR CONSEQUENTIAL  DAMAGES (INCLU-
   DING, BUT NOT LIMITED TO, PROCUREMENT  OF SUBSTITUTE GOODS OR SERVICES; LOSS
   OF USE, DATA, OR  PROFITS; OR BUSINESS  INTERRUPTION)  HOWEVER CAUSED AND ON
   ANY  THEORY OF LIABILITY,  WHETHER  IN CONTRACT,  STRICT LIABILITY,  OR TORT
   (INCLUDING  NEGLIGENCE OR  OTHERWISE) ARISING IN  ANY WAY OUT OF THE  USE OF
   THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  
  */
  package org.apache.cocoon.components.flow.javascript;
  import org.mozilla.javascript.*;
  import java.sql.*;
  
  public class ScriptableResult extends ScriptableObject {
  
      public String getClassName() {
        return "Result";
      }
      
      public ScriptableResult() {
      }
  
      public static class Row extends ScriptableObject {
  
        public String getClassName() {
            return "Row";
        }
  
        public Object get(String name, Scriptable start) {
            return super.get(name.toUpperCase(), start);
        }
        
        public void put(String name, Scriptable start, Object value) {
            super.put(name.toUpperCase(), start, value);
        }
      }
  
      ScriptableResult(Scriptable scope, 
                     ResultSet rs, int startRow, int maxRows) 
        throws SQLException, PropertyException, NotAFunctionException, 
JavaScriptException {
        Context cx = Context.getCurrentContext();
          Scriptable rowMap = cx.newObject(scope, "Array");
        put("rows", this, rowMap);
          Scriptable rowByIndex = cx.newObject(scope, "Array");
        put("rowsByIndex", this, rowByIndex);
  
          ResultSetMetaData rsmd = rs.getMetaData();
          int noOfColumns = rsmd.getColumnCount();
  
          // Create the column name array
          Scriptable columnNames = cx.newObject(scope, 
                                              "Array", 
                                              new Object[] {new Integer(noOfColumns)});
        put("columnNames", this, columnNames);
          for (int i = 1; i <= noOfColumns; i++) {
              columnNames.put(i-1, columnNames, rsmd.getColumnName(i));
          }
  
          // Throw away all rows upto startRow
          for (int i = 0; i < startRow; i++) {
              rs.next();
          }
  
          // Process the remaining rows upto maxRows
          int processedRows = 0;
        int index = 0;
        boolean isLimited = false;
          while (rs.next()) {
              if ((maxRows != -1) && (processedRows == maxRows)) {
                  isLimited = true; 
                  break;
              }
              Scriptable columns = cx.newObject(scope, "Array",
                                              new Object[] {new Integer(noOfColumns)});
            Scriptable columnMap = new Row();
            columnMap.setParentScope(columns.getParentScope());
            columnMap.setPrototype(getObjectPrototype(scope));
  
              // JDBC uses 1 as the lowest index!
              for (int i = 1; i <= noOfColumns; i++) {
                  Object value =  rs.getObject(i);
                  if (rs.wasNull()) {
                      value = null;
                  }
                  columns.put(i-1, columns, value);
                  columnMap.put(rsmd.getColumnName(i), columnMap, value);
              }
              rowMap.put(index, rowMap, columnMap);
              rowByIndex.put(index, rowByIndex, columns);
              processedRows++;
            index++;
          }
        put("rowCount", this, new Integer(index));
        put("isLimitedByMaxRows", this, new Boolean(isLimited));
      }
  }
  
  
  
  
  

Reply via email to