1 16 package org.apache.cocoon.components.flow.javascript; 17 18 import java.sql.ResultSet ; 19 import java.sql.ResultSetMetaData ; 20 import java.sql.SQLException ; 21 22 import org.apache.commons.lang.BooleanUtils; 23 import org.mozilla.javascript.Context; 24 import org.mozilla.javascript.JavaScriptException; 25 import org.mozilla.javascript.NotAFunctionException; 26 import org.mozilla.javascript.PropertyException; 27 import org.mozilla.javascript.Scriptable; 28 import org.mozilla.javascript.ScriptableObject; 29 30 34 public class ScriptableResult extends ScriptableObject { 35 36 public String getClassName() { 37 return "Result"; 38 } 39 40 public ScriptableResult() { 41 } 42 43 public static class Row extends ScriptableObject { 44 45 public String getClassName() { 46 return "Row"; 47 } 48 49 public boolean has(String name, Scriptable start) { 50 return super.has(name.toUpperCase(), start); 51 } 52 53 public Object get(String name, Scriptable start) { 54 return super.get(name.toUpperCase(), start); 55 } 56 57 public void put(String name, Scriptable start, Object value) { 58 super.put(name.toUpperCase(), start, value); 59 } 60 } 61 62 ScriptableResult(Scriptable scope, 63 ResultSet rs, int startRow, int maxRows) 64 throws SQLException , PropertyException, NotAFunctionException, JavaScriptException { 65 Context cx = Context.getCurrentContext(); 66 Scriptable rowMap = cx.newObject(scope, "Array"); 67 put("rows", this, rowMap); 68 Scriptable rowByIndex = cx.newObject(scope, "Array"); 69 put("rowsByIndex", this, rowByIndex); 70 71 ResultSetMetaData rsmd = rs.getMetaData(); 72 int noOfColumns = rsmd.getColumnCount(); 73 74 Scriptable columnNames = cx.newObject(scope, 76 "Array", 77 new Object [] {new Integer (noOfColumns)}); 78 put("columnNames", this, columnNames); 79 for (int i = 1; i <= noOfColumns; i++) { 80 columnNames.put(i-1, columnNames, rsmd.getColumnName(i)); 81 } 82 83 for (int i = 0; i < startRow; i++) { 85 rs.next(); 86 } 87 88 int processedRows = 0; 90 int index = 0; 91 boolean isLimited = false; 92 while (rs.next()) { 93 if ((maxRows != -1) && (processedRows == maxRows)) { 94 isLimited = true; 95 break; 96 } 97 Scriptable columns = cx.newObject(scope, "Array", 98 new Object [] {new Integer (noOfColumns)}); 99 Scriptable columnMap = new Row(); 100 columnMap.setParentScope(columns.getParentScope()); 101 columnMap.setPrototype(getObjectPrototype(scope)); 102 103 for (int i = 1; i <= noOfColumns; i++) { 105 Object value = rs.getObject(i); 106 if (rs.wasNull()) { 107 value = null; 108 } 109 columns.put(i-1, columns, value); 110 columnMap.put(rsmd.getColumnName(i), columnMap, value); 111 } 112 rowMap.put(index, rowMap, columnMap); 113 rowByIndex.put(index, rowByIndex, columns); 114 processedRows++; 115 index++; 116 } 117 put("rowCount", this, new Integer (index)); 118 put("isLimitedByMaxRows", this, BooleanUtils.toBooleanObject(isLimited)); 119 } 120 } 121 122 123 | Popular Tags |