haul 02/03/15 07:23:43 Added: src/scratchpad/src/org/apache/cocoon/acting/modular DatabaseAction.java DatabaseAddAction.java DatabaseDeleteAction.java DatabaseSelectAction.java DatabaseUpdateAction.java TestAction.java Log: Move ModularDatabaseActions and friends to a new home -> org.apache.cocoon.acting.modular.Database*Action Former helpers from ModularDatabaseAccess moved to -> org.apache.cocoon.components.modules Revision Changes Path 1.1 xml-cocoon2/src/scratchpad/src/org/apache/cocoon/acting/modular/DatabaseAction.java Index: DatabaseAction.java =================================================================== /* ============================================================================ The Apache Software License, Version 1.1 ============================================================================ Copyright (C) 1999-2002 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. This software consists of voluntary contributions made by many individuals on behalf of the Apache Software Foundation and was originally created by Stefano Mazzocchi <[EMAIL PROTECTED]>. For more information on the Apache Software Foundation, please see <http://www.apache.org/>. */ package org.apache.cocoon.acting.modular; import java.io.IOException; import java.io.InputStream; import java.lang.Class; import java.net.URL; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.Statement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Timestamp; import java.util.ArrayList; import java.util.Iterator; import java.util.Map; import java.util.List; import java.util.LinkedList; import java.util.ListIterator; import java.util.Enumeration; import java.util.Collections; import java.util.Set; import java.util.SortedSet; import java.util.TreeSet; import java.io.IOException; import org.apache.avalon.framework.activity.Disposable; import org.apache.avalon.framework.component.Component; import org.apache.avalon.framework.component.ComponentException; import org.apache.avalon.framework.component.ComponentSelector; import org.apache.avalon.framework.configuration.Configurable; import org.apache.avalon.framework.configuration.Configuration; import org.apache.avalon.framework.configuration.ConfigurationException; import org.apache.avalon.framework.configuration.DefaultConfiguration; import org.apache.avalon.framework.context.Context; import org.apache.avalon.framework.context.ContextException; import org.apache.avalon.framework.context.Contextualizable; import org.apache.avalon.framework.parameters.Parameters; import org.apache.avalon.framework.parameters.ParameterException; import org.apache.avalon.framework.thread.ThreadSafe; import org.apache.avalon.excalibur.component.RoleManager; import org.apache.avalon.excalibur.component.DefaultRoleManager; import org.apache.avalon.excalibur.datasource.DataSourceComponent; import org.apache.cocoon.Constants; import org.apache.cocoon.ProcessingException; import org.apache.cocoon.components.classloader.RepositoryClassLoader; import org.apache.cocoon.components.url.URLFactory; import org.apache.cocoon.environment.ObjectModelHelper; import org.apache.cocoon.environment.Request; import org.apache.cocoon.environment.Redirector; import org.apache.cocoon.environment.SourceResolver; import org.apache.cocoon.generation.ImageDirectoryGenerator; import org.apache.cocoon.util.ClassUtils; import org.apache.cocoon.util.HashMap; import org.apache.cocoon.selection.Selector; import org.apache.cocoon.acting.AbstractDatabaseAction; import org.apache.cocoon.components.modules.database.AutoIncrementModule; import org.apache.cocoon.components.modules.input.InputModule; import org.apache.cocoon.components.modules.output.OutputModule; /** * Abstract action for common function needed by database actions. * The difference to the other Database*Actions is, that the actions * in this package use additional components ("modules") for reading * and writing parameters. In addition the descriptor format has * changed to accomodate the new features. * * <p>This action is heavily based upon the original DatabaseAddAction * and relies on the AbstractDatabaseAction.</p> * * <p>Modes have to be configured in cocoon.xconf. Mode names from * descriptor.xml file are looked up in the component service. Default * mode names can only be set during action setup. </p> * * <table> * <tr><td colspan="2">Configuration options (setup):</td></tr> * <tr><td>input </td><td>default mode name for reading values</td></tr> * <tr><td>autoincrement </td><td>default mode name for obtaining values from autoincrement columns</td></tr> * </table> * * <table> * <tr><td colspan="2">Configuration options (setup and per invocation):</td></tr> * <tr><td>throw-exception </td><td>throw an exception when an error occurs (default: false)</td></tr> * <tr><td>descriptor </td><td>file containing database description</td></tr> * <tr><td>table-set </td><td>table-set name to work with </td></tr> * <tr><td>output </td><td>mode name for writing values </td></tr> * </table> * * @author <a href="mailto:[EMAIL PROTECTED]">Christian Haul</a> * @version CVS $Id: DatabaseAction.java,v 1.1 2002/03/15 15:23:43 haul Exp $ * @see org.apache.cocoon.modules.input * @see org.apache.cocoon.modules.output * @see org.apache.cocoon.modules.database */ public abstract class DatabaseAction extends AbstractDatabaseAction { // ======================================================================== // constants // ======================================================================== static final Integer MODE_AUTOINCR = new Integer( 0 ); static final Integer MODE_OTHERS = new Integer( 1 ); static final Integer MODE_OUTPUT = new Integer( 2 ); static final String ATTRIBUTE_KEY = "org.apache.cocoon.action.modular.DatabaseAction.outputModeName"; // These can be overidden from cocoon.xconf static final String inputHint = "request"; // default to request parameters static final String outputHint = "attribute"; // default to request attributes static final String databaseHint = "manual"; // default to manual auto increments static final String INPUT_MODULE_SELECTOR = InputModule.ROLE + "Selector"; static final String OUTPUT_MODULE_SELECTOR = OutputModule.ROLE + "Selector"; static final String DATABASE_MODULE_SELECTOR = AutoIncrementModule.ROLE + "Selector"; // ======================================================================== // instance vars // ======================================================================== protected HashMap defaultModeNames = new HashMap( 3 ); protected final HashMap cachedQueryData = new HashMap(); // ======================================================================== // inner helper classes // ======================================================================== /** * Structure that takes all processed data for one column. */ protected class Column { boolean isKey = false; boolean isSet = false; boolean isAutoIncrement = false; String mode = null; Configuration modeConf = null; Configuration columnConf = null; } /** * Structure that takes all processed data for a table depending * on current default modes */ protected class CacheHelper { /** * Generated query string */ public String queryString = null; /** * if a set is used, column number which is used to determine * the number of rows to insert. */ public int setMaster = -1; public boolean isSet = false; public int noOfKeys = 0; public Column[] columns = null; public CacheHelper( int cols ) { this(0,cols); } public CacheHelper( int keys, int cols ) { noOfKeys = keys; columns = new Column[cols]; for ( int i=0; i<cols; i++ ) { columns[i] = new Column(); } } } /** * Structure that takes up both current mode types for database * operations and table configuration data. Used to access parsed * configuration data. */ protected class LookUpKey { public Configuration tableConf = null; public Map modeTypes = null; public LookUpKey( Configuration tableConf, Map modeTypes ) { this.tableConf = tableConf; this.modeTypes = modeTypes; } } // set up default modes // <input/> // <output/> // <autoincrement/> // // all other modes need to be declared in cocoon.xconf // no need to declare them per action (anymore!) public void configure(Configuration conf) throws ConfigurationException { super.configure(conf); if (this.settings != null) { this.defaultModeNames.put(MODE_OTHERS, (String) this.settings.get("input", inputHint)); this.defaultModeNames.put(MODE_OUTPUT, (String) this.settings.get("output", outputHint)); this.defaultModeNames.put(MODE_AUTOINCR, (String) this.settings.get("autoincrement", databaseHint)); } } // ======================================================================== // protected utility methods // ======================================================================== /** * override super's method since we prefer to get the datasource * from defaults first or from sitemap parameters rather than from * descriptor file. */ protected DataSourceComponent getDataSource( Configuration conf, Parameters parameters ) throws ComponentException { String sourceName = parameters.getParameter( "connection", (String) settings.get( "connection" ) ); if ( sourceName == null ) { return getDataSource( conf ); } else { if (getLogger().isDebugEnabled()) getLogger().debug("Using datasource: "+sourceName); return (DataSourceComponent) this.dbselector.select(sourceName); } } /** * Store a key/value pair in the request attributes. We prefix the key * with the name of this class to prevent potential name collisions. * This method overrides super class' method to allow an OutputModule * to take care of what to do with the values. */ protected void setRequestAttribute(Request request, String key, Object value) { ComponentSelector outputSelector = null; OutputModule output = null; String outputMode = null; try { outputSelector=(ComponentSelector) this.manager.lookup(OUTPUT_MODULE_SELECTOR); outputMode = (String) request.getAttribute(ATTRIBUTE_KEY); if (outputMode != null && outputSelector != null && outputSelector.hasComponent(outputMode)){ output = (OutputModule) outputSelector.select(outputMode); } output.setAttribute( null, request, key, value ); } catch (Exception e) { if (getLogger().isWarnEnabled()) getLogger() .warn( "Could not select output mode " + (String) outputMode + ":" + e.getMessage() ); } finally { if (outputSelector != null) { if (output != null) outputSelector.release(output); this.manager.release(outputSelector); } } } /** * Retrieve a value from the request attributes. * This method overrides super class' method to allow an OutputModule * to take care of where to get the values. */ // FIXME: OutputModule doesn't provide getAttribute anymore protected Object getRequestAttribute(Request request, String key) { if (getLogger().isErrorEnabled()) getLogger() .error("getRequestAttribute not supported"); return null; } // ======================================================================== // main method // ======================================================================== /** * Add a record to the database. This action assumes that * the file referenced by the "descriptor" parameter conforms * to the AbstractDatabaseAction specifications. */ public Map act( Redirector redirector, SourceResolver resolver, Map objectModel, String source, Parameters param ) throws Exception { DataSourceComponent datasource = null; Connection conn = null; Map results = new HashMap(); // read global parameter settings boolean reloadable = Constants.DESCRIPTOR_RELOADABLE_DEFAULT; Request request = ObjectModelHelper.getRequest(objectModel); // call specific default modes apart from output mode are not supported // set request attribute String outputMode = param.getParameter("output", (String) defaultModeNames.get(MODE_OUTPUT)); request.setAttribute(ATTRIBUTE_KEY, outputMode); if (this.settings.containsKey("reloadable")) reloadable = Boolean.getBoolean((String) this.settings.get("reloadable")); // read local parameter settings try { Configuration conf = this.getConfiguration(param.getParameter("descriptor", (String) this.settings.get("descriptor")), resolver, param.getParameterAsBoolean("reloadable",reloadable)); // get database connection and try to turn off autocommit datasource = this.getDataSource(conf, param); conn = datasource.getConnection(); if (conn.getAutoCommit() == true) { try { conn.setAutoCommit(false); } catch (Exception ex) { String tmp = param.getParameter("use-transactions",(String) this.settings.get("use-transactions",null)); if (tmp != null && (tmp.equalsIgnoreCase("no") || tmp.equalsIgnoreCase("false") || tmp.equalsIgnoreCase("0"))) { if (getLogger().isErrorEnabled()) getLogger().error("This DB connection does not support transactions. If you want to risk your data's integrity by continuing nonetheless set parameter \"use-transactions\" to \"no\"."); throw ex; } } } // find tables to work with Configuration[] tables = conf.getChildren("table"); String tablesetname = param.getParameter("table-set", (String) this.settings.get("table-set")); Map set_tables = null; // default to old behaviour HashMap modeTypes = null; if (tablesetname != null) { // new set based behaviour Configuration[] tablesets = conf.getChildren("table-set"); String setname = null; boolean found = false; // find tables contained in tableset int j = 0; for (j=0; j<tablesets.length; j++) { setname = tablesets[j].getAttribute ("name", ""); if (tablesetname.trim().equals (setname.trim ())) { found = true; break; } } if (!found) { throw new IOException(" given set " + tablesetname + " does not exists in a description file."); } Configuration[] set = tablesets[j].getChildren("table"); // construct a Map that contains the names of the tables // contained in the requested tableset set_tables = new HashMap(set.length); for (int i=0; i<set.length; i++) { // look for alternative mode types modeTypes = new HashMap(2); modeTypes.put( MODE_AUTOINCR, set[i].getAttribute( "autoincr-mode", "autoincr" ) ); modeTypes.put( MODE_OTHERS, set[i].getAttribute( "others-mode", "others" ) ); set_tables.put(set[i].getAttribute("name",""), modeTypes); } } else { modeTypes = new HashMap(2); modeTypes.put( MODE_AUTOINCR, "autoincr" ); modeTypes.put( MODE_OTHERS, "others" ); }; for (int i=0; i<tables.length; i++) { if ( set_tables == null || set_tables.containsKey( tables[i].getAttribute( "name" ) ) || ( tables[i].getAttribute( "alias", null ) != null && set_tables.containsKey( tables[i].getAttribute( "alias" ) ) ) ) { if (tablesetname != null) { modeTypes = (HashMap) set_tables.get(tables[i].getAttribute("name")); } processTable( tables[i], conn, request, results, modeTypes ); } } if (conn.getAutoCommit()==false) conn.commit(); // obtain output mode module and rollback output ComponentSelector outputSelector = null; OutputModule output = null; try { outputSelector=(ComponentSelector) this.manager.lookup(OUTPUT_MODULE_SELECTOR); if (outputMode != null && outputSelector != null && outputSelector.hasComponent(outputMode)){ output = (OutputModule) outputSelector.select(outputMode); } output.commit( null, request ); } catch (Exception e) { if (getLogger().isWarnEnabled()) getLogger() .warn( "Could not select output mode " + (String) outputMode + ":" + e.getMessage() ); } finally { if (outputSelector != null) { if (output != null) outputSelector.release(output); this.manager.release(outputSelector); } } } catch (Exception e) { if ( conn != null ) { try { if (getLogger().isDebugEnabled()) getLogger().debug( "Rolling back transaction. Caused by " + e.getMessage() ); conn.rollback(); // obtain output mode module and commit output ComponentSelector outputSelector = null; OutputModule output = null; try { outputSelector=(ComponentSelector) this.manager.lookup(OUTPUT_MODULE_SELECTOR); if (outputMode != null && outputSelector != null && outputSelector.hasComponent(outputMode)){ output = (OutputModule) outputSelector.select(outputMode); } output.rollback( null, request, e); } catch (Exception e2) { if (getLogger().isWarnEnabled()) getLogger() .warn( "Could not select output mode " + (String) outputMode + ":" + e2.getMessage() ); } finally { if (outputSelector != null) { if (output != null) outputSelector.release(output); this.manager.release(outputSelector); } } } catch (SQLException se) { if (getLogger().isDebugEnabled()) getLogger().debug("There was an error rolling back the transaction", se); } } //throw new ProcessingException("Could not add record :position = " + currentIndex, e); // don't throw an exception, an error has been signalled, that should suffice String throwException = (String) this.settings.get( "throw-exception", param.getParameter( "throw-exception", null ) ); if ( throwException != null && ( throwException.equalsIgnoreCase( "true" ) || throwException.equalsIgnoreCase( "yes" ) ) ) { throw new ProcessingException("Could not add record",e); } } finally { if (conn != null) { try { conn.close(); } catch (SQLException sqe) { getLogger().warn("There was an error closing the datasource", sqe); } } if (datasource != null) this.dbselector.release(datasource); } return Collections.unmodifiableMap(results); } /** * Inserts a row or a set of rows into the given table based on the * request parameters * * @param table the table's configuration * @param conn the database connection * @param request the request */ protected void processTable( Configuration table, Connection conn, Request request, Map results, HashMap modeTypes ) throws SQLException, ConfigurationException, Exception { PreparedStatement statement = null; try { LookUpKey luk = new LookUpKey(table, modeTypes); CacheHelper queryData = null; // get cached data // synchronize complete block since we don't want 100s of threads // generating the same cached data set. In the long run all data // is cached anyways so this won't cost much. synchronized (this.cachedQueryData) { queryData = (CacheHelper) this.cachedQueryData.get(luk,null); if (queryData == null) { queryData = this.getQuery( table, modeTypes, defaultModeNames ); this.cachedQueryData.put(luk,queryData); } }; if (getLogger().isDebugEnabled()) getLogger().debug("query: "+queryData.queryString); statement = conn.prepareStatement(queryData.queryString); Object[][] columnValues = this.getColumnValues( table, queryData, request ); int setLength = 1; if ( queryData.isSet ) { if ( columnValues[ queryData.setMaster ] != null ) { setLength = columnValues[ queryData.setMaster ].length; } else { setLength = 0; } } for ( int rowIndex = 0; rowIndex < setLength; rowIndex++ ) { if (getLogger().isDebugEnabled()) getLogger().debug( "====> row no. " + rowIndex ); processRow( request, conn, statement, table, queryData, columnValues, rowIndex, results ); } } finally { try { if (statement != null) { statement.close(); } } catch (SQLException e) {} } } /** * Choose a mode configuration based on its name. * @param conf Configuration (i.e. a column's configuration) that might have * several children configurations named "mode". * @param type desired type (i.e. every mode has a type * attribute), find the first mode that has a compatible type. * Special mode "all" matches all queried types. * @return configuration that has desired type or type "all" or null. */ protected Configuration getMode( Configuration conf, String type ) throws ConfigurationException { String modeAll = "all"; Configuration[] modes = conf.getChildren("mode"); Configuration modeConfig = null;; for ( int i=0; i<modes.length; i++ ) { String modeType = modes[i].getAttribute("type", "others"); if ( modeType.equals(type) || modeType.equals(modeAll)) { if (getLogger().isDebugEnabled()) getLogger().debug("requested mode was \""+type+"\" returning \""+modeType+"\""); modeConfig = modes[i]; break; }; } return modeConfig; } /** * compose name for output a long the lines of "table.column" */ protected String getOutputName ( Configuration tableConf, Configuration columnConf ) throws ConfigurationException { return getOutputName( tableConf, columnConf, -1 ); } /** * compose name for output a long the lines of "table.column[row]" or * "table.column" if rowIndex is -1. */ protected String getOutputName ( Configuration tableConf, Configuration columnConf, int rowIndex ) throws ConfigurationException { return ( tableConf.getAttribute("alias", tableConf.getAttribute("name") ) + "." + columnConf.getAttribute("name") + ( rowIndex == -1 ? "" : "[" + rowIndex + "]" ) ); } /* * Read all values for a column from an InputModule * * If the given column is an autoincrement column, an empty array * is returned, otherwise if it is part of a set, all available * values are fetched, or only the first one if it is not part of * a set. * */ protected Object[] getColumnValue( Configuration tableConf, Column column, Request request ) throws ConfigurationException, ComponentException { if ( column.isAutoIncrement ) { return new Object[1]; } else { Object[] values; String cname = getOutputName( tableConf, column.columnConf ); // obtain input module and read values ComponentSelector inputSelector = null; InputModule input = null; try { inputSelector=(ComponentSelector) this.manager.lookup(INPUT_MODULE_SELECTOR); if (column.mode != null && inputSelector != null && inputSelector.hasComponent(column.mode)){ input = (InputModule) inputSelector.select(column.mode); } if ( column.isSet ){ if (getLogger().isDebugEnabled()) getLogger().debug( "Trying to set column " + cname +" using getAttributeValues method"); values = input.getAttributeValues( cname, column.modeConf, request ); } else { if (getLogger().isDebugEnabled()) getLogger().debug( "Trying to set column " + cname +" using getAttribute method"); values = new Object[1]; values[0] = input.getAttribute( cname, column.modeConf, request ); } if ( values != null ) { for ( int i = 0; i < values.length; i++ ) { if (getLogger().isDebugEnabled()) getLogger().debug( "Setting column " + cname + " [" + i + "] " + values[i] ); } } } finally { if (inputSelector != null) { if (input != null) inputSelector.release(input); this.manager.release(inputSelector); } } return values; } } /** * Setup parsed attribute configuration object */ protected void fillModes ( Configuration[] conf, boolean isKey, HashMap defaultModeNames, HashMap modeTypes, CacheHelper set ) throws ConfigurationException { String setMode = null; int setMaster = -1; String setMastersMode = null; boolean manyrows = false; int offset = ( isKey ? 0: set.noOfKeys); for ( int i = offset; i < conf.length + offset; i++ ) { if (getLogger().isDebugEnabled()) getLogger().debug("i="+i); set.columns[i].columnConf = conf[ i - offset ]; set.columns[i].isSet = false; set.columns[i].isKey = isKey; set.columns[i].isAutoIncrement = false; if ( isKey & this.honourAutoIncrement() ) { String autoIncrement = set.columns[i].columnConf.getAttribute("autoincrement","false"); if ( autoIncrement.equalsIgnoreCase("yes") || autoIncrement.equalsIgnoreCase("true") ) { set.columns[i].isAutoIncrement = true; } } set.columns[i].modeConf = getMode( set.columns[i].columnConf, selectMode( set.columns[i].isAutoIncrement, modeTypes ) ); set.columns[i].mode = ( set.columns[i].modeConf != null ? set.columns[i].modeConf.getAttribute( "name", selectMode( isKey, defaultModeNames ) ) : selectMode( isKey, defaultModeNames ) ); // Determine set mode for a whole column ... setMode = set.columns[i].columnConf.getAttribute("set", null); // master vs slave vs null if ( setMode == null && set.columns[i].modeConf != null ) { // ... or for each mode individually setMode = set.columns[i].modeConf.getAttribute("set", null); } if ( setMode != null ) { manyrows = true; set.columns[i].isSet = true; set.isSet = true; if ( setMode.equals("master") ) { set.setMaster = i; } } } } /** * Put key values into request attributes. */ protected void storeKeyValue( Configuration tableConf, Column key, int rowIndex, Connection conn, Statement statement, Request request, Map results ) throws SQLException, ConfigurationException, ComponentException { ComponentSelector autoincrSelector = null; AutoIncrementModule autoincr = null; try { autoincrSelector=(ComponentSelector) this.manager.lookup(DATABASE_MODULE_SELECTOR); if (key.mode != null && autoincrSelector != null && autoincrSelector.hasComponent(key.mode)){ autoincr = (AutoIncrementModule) autoincrSelector.select(key.mode); } if (!autoincr.includeAsValue()) { String keyname = getOutputName( tableConf, key.columnConf, rowIndex ); Object value = autoincr.getPostValue( tableConf, key.columnConf, key.modeConf, conn, statement, request ); if (getLogger().isDebugEnabled()) getLogger().debug( "Retrieving autoincrement for " + keyname + "as " + value ); setRequestAttribute( request, keyname, value ); results.put( keyname, String.valueOf( value ) ); } } finally { if (autoincrSelector != null) { if (autoincr != null) autoincrSelector.release(autoincr); this.manager.release(autoincrSelector); } } } /** * Sets the key value on the prepared statement for an autoincrement type. * * @param table the table's configuration object * @param column the key's configuration object * @param currentIndex the position of the key column * @param rowIndex the position in the current row set * @param conn the database connection * @param statement the insert statement * @param request the request object * @param result sitemap result object * @return the number of columns by which to increment the currentIndex */ protected int setKeyAuto ( Configuration table, Column column, int currentIndex, int rowIndex, Connection conn, PreparedStatement statement, Request request, Map results ) throws ConfigurationException, SQLException, ComponentException, Exception { int columnCount = 0; ComponentSelector autoincrSelector = null; AutoIncrementModule autoincr = null; try { autoincrSelector=(ComponentSelector) this.manager.lookup(DATABASE_MODULE_SELECTOR); if (column.mode != null && autoincrSelector != null && autoincrSelector.hasComponent(column.mode)){ autoincr = (AutoIncrementModule) autoincrSelector.select(column.mode); } if ( autoincr.includeInQuery() ) { if ( autoincr.includeAsValue() ) { Object value = autoincr.getPreValue( table, column.columnConf, column.modeConf, conn, request ); String keyname = this.getOutputName( table, column.columnConf, rowIndex ); if (getLogger().isDebugEnabled()) getLogger().debug( "Setting key " + keyname + " to " + value ); statement.setObject( currentIndex, value ); setRequestAttribute( request, keyname, value ); results.put( keyname, String.valueOf( value ) ); columnCount = 1; } } else { if (getLogger().isDebugEnabled()) getLogger().debug( "Automatically setting key" ); } } finally { if (autoincrSelector != null) { if (autoincr != null) autoincrSelector.release(autoincr); this.manager.release(autoincrSelector); } } return columnCount; } // ======================================================================== // abstract methods // ======================================================================== /** * set all necessary ?s and execute the query * * This method is intended to be overridden by classes that * implement other operations e.g. delete */ protected abstract void processRow( Request request, Connection conn, PreparedStatement statement, Configuration table, CacheHelper queryData, Object[][] columnValues, int rowIndex, Map results ) throws SQLException, ConfigurationException, Exception; /** * determine which mode to use as default mode * * This method is intended to be overridden by classes that * implement other operations e.g. delete */ protected abstract String selectMode( boolean isAutoIncrement, HashMap modes ); /** * determine whether autoincrement columns should be honoured by * this operation. This is usually snsible only for INSERTs. * * This method is intended to be overridden by classes that * implement other operations e.g. delete */ protected abstract boolean honourAutoIncrement(); /** * Fetch all values for all columns that are needed to do the * database operation. * * This method is intended to be overridden by classes that * implement other operations e.g. delete */ abstract Object[][] getColumnValues( Configuration tableConf, CacheHelper queryData, Request request ) throws ConfigurationException, ComponentException; /** * Get the String representation of the PreparedStatement. This is * mapped to the Configuration object itself, so if it doesn't exist, * it will be created. * * This method is intended to be overridden by classes that * implement other operations e.g. delete * * @param table the table's configuration object * @return the insert query as a string */ protected abstract CacheHelper getQuery( Configuration table, HashMap modeTypes, HashMap defaultModeNames ) throws ConfigurationException, ComponentException; } 1.1 xml-cocoon2/src/scratchpad/src/org/apache/cocoon/acting/modular/DatabaseAddAction.java Index: DatabaseAddAction.java =================================================================== /* ============================================================================ The Apache Software License, Version 1.1 ============================================================================ Copyright (C) 1999-2002 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. This software consists of voluntary contributions made by many individuals on behalf of the Apache Software Foundation and was originally created by Stefano Mazzocchi <[EMAIL PROTECTED]>. For more information on the Apache Software Foundation, please see <http://www.apache.org/>. */ package org.apache.cocoon.acting.modular; import java.util.Map; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.SQLException; import org.apache.cocoon.util.HashMap; import org.apache.avalon.framework.component.ComponentException; import org.apache.avalon.framework.component.ComponentSelector; import org.apache.avalon.framework.configuration.Configuration; import org.apache.avalon.framework.configuration.ConfigurationException; import org.apache.cocoon.environment.Request; import org.apache.cocoon.components.modules.database.AutoIncrementModule; /** * Adds record in a database. The action can update one or more * tables, and can add more than one row to a table at a time. See * {@see DatabaseAction} for details. * * @author <a href="mailto:[EMAIL PROTECTED]">Christian Haul</a> * @version CVS $Id: DatabaseAddAction.java,v 1.1 2002/03/15 15:23:43 haul Exp $ */ public class DatabaseAddAction extends DatabaseAction { /** * set all necessary ?s and execute the query */ protected void processRow ( Request request, Connection conn, PreparedStatement statement, Configuration table, CacheHelper queryData, Object[][] columnValues, int rowIndex, Map results ) throws SQLException, ConfigurationException, Exception { int currentIndex = 1; for (int i = 0; i < queryData.columns.length; i++) { Column col = queryData.columns[i]; if ( col.isAutoIncrement && col.isKey ) { currentIndex += setKeyAuto( table, col, currentIndex, rowIndex, conn, statement, request, results ); } else { this.setColumn( statement, currentIndex, request, col.columnConf, getOutputName( table, col.columnConf, rowIndex ), columnValues[ i ][ ( col.isSet ? rowIndex : 0 ) ], rowIndex); currentIndex++; } } statement.execute(); // get resulting ids for autoincrement columns for (int i = 0; i < queryData.columns.length; i++) { if ( queryData.columns[i].isAutoIncrement && queryData.columns[i].isKey ) { storeKeyValue( table, queryData.columns[i], rowIndex, conn, statement, request, results ); } } } /** * determine which mode to use as default mode * here: INSERT * highly specific to operation INSERT / UPDATE / DELETE / SELECT */ protected String selectMode ( boolean isAutoIncrement, HashMap modes ) { if ( isAutoIncrement ) return (String) modes.get( MODE_AUTOINCR ); else return (String) modes.get( MODE_OTHERS ); } /** * determine whether autoincrement columns should be honoured by * this operation. This is usually snsible only for INSERTs. */ protected boolean honourAutoIncrement() { return true; } /** * Fetch all values for all columns that are needed to do the * database operation. */ protected Object[][] getColumnValues( Configuration tableConf, CacheHelper queryData, Request request ) throws ConfigurationException, ComponentException { Object[][] columnValues = new Object[ queryData.columns.length ][]; for ( int i = 0; i < queryData.columns.length; i++ ){ columnValues[i] = this.getColumnValue( tableConf, queryData.columns[i], request ); } return columnValues; } /** * Get the String representation of the PreparedStatement. This is * mapped to the Configuration object itself, so if it doesn't exist, * it will be created. * @param table the table's configuration object * @return the insert query as a string */ protected CacheHelper getQuery( Configuration table, HashMap modeTypes, HashMap defaultModeNames ) throws ConfigurationException, ComponentException { LookUpKey lookUpKey = new LookUpKey( table, modeTypes ); CacheHelper queryData = null; synchronized( this.cachedQueryData ) { queryData = (CacheHelper) this.cachedQueryData.get( lookUpKey ); if (queryData == null) { Configuration[] values = table.getChild("values").getChildren("value"); Configuration[] keys = table.getChild("keys").getChildren("key"); queryData = new CacheHelper( keys.length, keys.length + values.length ); fillModes( keys, true, defaultModeNames, modeTypes, queryData ); fillModes( values, false, defaultModeNames, modeTypes, queryData ); StringBuffer queryBuffer = new StringBuffer("INSERT INTO "); StringBuffer valueBuffer = new StringBuffer(") VALUES ("); AutoIncrementModule dah; queryBuffer.append(table.getAttribute("name")); queryBuffer.append(" ("); int actualColumns = 0; for (int i = 0; i < queryData.columns.length; i++) { if ( actualColumns > 0 ) { queryBuffer.append( ", " ); valueBuffer.append( ", " ); } if ( queryData.columns[i].isKey && queryData.columns[i].isAutoIncrement ) { ComponentSelector autoincrSelector = null; AutoIncrementModule autoincr = null; try { autoincrSelector=(ComponentSelector) this.manager.lookup(DATABASE_MODULE_SELECTOR); if (queryData.columns[i].mode != null && autoincrSelector != null && autoincrSelector.hasComponent(queryData.columns[i].mode)){ autoincr = (AutoIncrementModule) autoincrSelector.select(queryData.columns[i].mode); } if ( autoincr.includeInQuery() ) { actualColumns++; queryBuffer.append( queryData.columns[i].columnConf.getAttribute( "name" ) ); if ( autoincr.includeAsValue() ) { valueBuffer.append( "?" ); } else { valueBuffer.append( autoincr.getSubquery( table, queryData.columns[i].columnConf, queryData.columns[i].modeConf ) ); } } } finally { if (autoincrSelector != null) { if (autoincr != null) autoincrSelector.release(autoincr); this.manager.release(autoincrSelector); } } } else { actualColumns++; queryBuffer.append( queryData.columns[i].columnConf.getAttribute( "name" ) ); valueBuffer.append( "?" ); } } valueBuffer.append(")"); queryBuffer.append(valueBuffer); queryData.queryString = queryBuffer.toString(); this.cachedQueryData.put( lookUpKey, queryData ); } } return queryData; } } 1.1 xml-cocoon2/src/scratchpad/src/org/apache/cocoon/acting/modular/DatabaseDeleteAction.java Index: DatabaseDeleteAction.java =================================================================== /* ============================================================================ The Apache Software License, Version 1.1 ============================================================================ Copyright (C) 1999-2002 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. This software consists of voluntary contributions made by many individuals on behalf of the Apache Software Foundation and was originally created by Stefano Mazzocchi <[EMAIL PROTECTED]>. For more information on the Apache Software Foundation, please see <http://www.apache.org/>. */ package org.apache.cocoon.acting.modular; import java.util.Map; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.SQLException; import org.apache.cocoon.util.HashMap; import org.apache.avalon.framework.component.ComponentException; import org.apache.avalon.framework.configuration.Configuration; import org.apache.avalon.framework.configuration.ConfigurationException; import org.apache.cocoon.environment.Request; /** * Updates a record in a database. The action can update one or more * tables, and can update more than one row to a table at a time. The * form descriptor semantics for this are still in a bit of a state of * flux. * * @author <a href="mailto:[EMAIL PROTECTED]">Christian Haul</a> * @version CVS $Id: DatabaseDeleteAction.java,v 1.1 2002/03/15 15:23:43 haul Exp $ */ public class DatabaseDeleteAction extends DatabaseAction { /** * determine which mode to use as default mode * here: DELETE * highly specific to operation INSERT / UPDATE / DELETE / SELECT */ protected String selectMode ( boolean isAutoIncrement, HashMap modes ) { return (String) modes.get( MODE_OTHERS ); } /** * determine whether autoincrement columns should be honoured by * this operation. This is usually snsible only for INSERTs. */ protected boolean honourAutoIncrement() { return false; } /** * Fetch all values for all key columns that are needed to do the * database operation. */ protected Object[][] getColumnValues( Configuration tableConf, CacheHelper queryData, Request request ) throws ConfigurationException, ComponentException { Object[][] columnValues = new Object[ queryData.columns.length ][]; for ( int i = 0; i < queryData.columns.length; i++ ){ if ( queryData.columns[i].isKey ) { columnValues[i] = this.getColumnValue( tableConf, queryData.columns[i], request ); } else { // columnValues[i] = new Object[1]; // this should not be needed } } return columnValues; } /** * Get the String representation of the PreparedStatement. This is * mapped to the Configuration object itself, so if it doesn't exist, * it will be created. * * @param table the table's configuration object * @return the insert query as a string */ protected CacheHelper getQuery( Configuration table, HashMap modeTypes, HashMap defaultModeNames ) throws ConfigurationException, ComponentException { LookUpKey lookUpKey = new LookUpKey( table, modeTypes ); CacheHelper queryData = null; synchronized( this.cachedQueryData ) { queryData = (CacheHelper) this.cachedQueryData.get( lookUpKey ); if (queryData == null) { Configuration[] keys = table.getChild("keys").getChildren("key"); queryData = new CacheHelper( keys.length, keys.length ); fillModes( keys, true, defaultModeNames, modeTypes, queryData ); StringBuffer queryBuffer = new StringBuffer("DELETE FROM "); queryBuffer.append(table.getAttribute("name")).append(" WHERE "); for (int i = 0; i < queryData.columns.length; i++) { if ( i > 0 ) { queryBuffer.append(" AND "); } queryBuffer .append( queryData.columns[i].columnConf.getAttribute( "name" ) ) .append( "= ?" ); } queryData.queryString = queryBuffer.toString(); this.cachedQueryData.put( lookUpKey, queryData ); } } return queryData; } /** * set all necessary ?s and execute the query */ protected void processRow ( Request request, Connection conn, PreparedStatement statement, Configuration table, CacheHelper queryData, Object[][] columnValues, int rowIndex, Map results ) throws SQLException, ConfigurationException, Exception { int currentIndex = 1; // ordering is different for DELETE just needs keys for (int i = 0; i < queryData.columns.length; i++) { Column col = queryData.columns[i]; if ( col.isKey ) { this.setColumn( statement, currentIndex, request, col.columnConf, getOutputName( table, col.columnConf, rowIndex ), columnValues[ i ][ ( col.isSet ? rowIndex : 0 ) ], rowIndex); currentIndex++; } } statement.execute(); } } 1.1 xml-cocoon2/src/scratchpad/src/org/apache/cocoon/acting/modular/DatabaseSelectAction.java Index: DatabaseSelectAction.java =================================================================== /* ============================================================================ The Apache Software License, Version 1.1 ============================================================================ Copyright (C) 1999-2002 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. This software consists of voluntary contributions made by many individuals on behalf of the Apache Software Foundation and was originally created by Stefano Mazzocchi <[EMAIL PROTECTED]>. For more information on the Apache Software Foundation, please see <http://www.apache.org/>. */ package org.apache.cocoon.acting.modular; import java.util.Map; import java.sql.Connection; import java.sql.Clob; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Struct; import java.sql.Types; import java.io.InputStream; import java.io.BufferedInputStream; import org.apache.cocoon.util.HashMap; import org.apache.avalon.framework.component.ComponentException; import org.apache.avalon.framework.configuration.Configuration; import org.apache.avalon.framework.configuration.ConfigurationException; import org.apache.cocoon.environment.Request; import org.apache.cocoon.acting.AbstractDatabaseAction; /** * Selects a record from a database. The action can select one or more * tables, and can select from more than one row of a table at a * time. The form descriptor semantics for this are still in a bit of * a state of flux. * * @author <a href="mailto:[EMAIL PROTECTED]">Christian Haul</a> * @version CVS $Id: DatabaseSelectAction.java,v 1.1 2002/03/15 15:23:43 haul Exp $ */ public class DatabaseSelectAction extends DatabaseAction { /** * determine which mode to use as default mode * here: SELECT * highly specific to operation INSERT / UPDATE / DELETE / SELECT */ protected String selectMode ( boolean isAutoIncrement, HashMap modes ) { return (String) modes.get( MODE_OTHERS ); } /** * determine whether autoincrement columns should be honoured by * this operation. This is usually snsible only for INSERTs. */ protected boolean honourAutoIncrement() { return false; } /** * Get the String representation of the PreparedStatement. This is * mapped to the Configuration object itself, so if it doesn't exist, * it will be created. * * @param table the table's configuration object * @return the insert query as a string */ protected CacheHelper getQuery( Configuration table, HashMap modeTypes, HashMap defaultModeNames ) throws ConfigurationException, ComponentException { LookUpKey lookUpKey = new LookUpKey( table, modeTypes ); CacheHelper queryData = null; synchronized( this.cachedQueryData ) { queryData = (CacheHelper) this.cachedQueryData.get( lookUpKey ); if (queryData == null) { Configuration[] keys = table.getChild("keys").getChildren("key"); Configuration[] values = table.getChild("values").getChildren("value"); queryData = new CacheHelper( keys.length, keys.length ); fillModes( keys, true, defaultModeNames, modeTypes, queryData ); fillModes( values, false, defaultModeNames, modeTypes, queryData ); StringBuffer queryBuffer = new StringBuffer("SELECT "); queryBuffer.append(table.getAttribute("name")).append(" WHERE "); for (int i = 0; i < queryData.columns.length; i++) { if ( !queryData.columns[i].isKey ) { if ( i > 0 ) { queryBuffer.append(", "); } queryBuffer .append( queryData.columns[i].columnConf.getAttribute( "name" ) ); } } queryBuffer.append(" FROM ").append(table.getAttribute("name")).append(" WHERE "); for (int i = 0; i < queryData.columns.length; i++) { if ( queryData.columns[i].isKey ) { if ( i > 0 ) { queryBuffer.append(" AND "); } queryBuffer .append( queryData.columns[i].columnConf.getAttribute( "name" ) ) .append( "= ?"); } } queryData.queryString = queryBuffer.toString(); this.cachedQueryData.put( lookUpKey, queryData ); } } return queryData; } /** * Fetch all values for all key columns that are needed to do the * database operation. */ protected Object[][] getColumnValues( Configuration tableConf, CacheHelper queryData, Request request ) throws ConfigurationException, ComponentException { Object[][] columnValues = new Object[ queryData.columns.length ][]; for ( int i = 0; i < queryData.columns.length; i++ ){ if ( queryData.columns[i].isKey ) { columnValues[i] = this.getColumnValue( tableConf, queryData.columns[i], request ); } else { // columnValues[i] = new Object[1]; // this should not be needed } } return columnValues; } /** * set all necessary ?s and execute the query */ protected void processRow ( Request request, Connection conn, PreparedStatement statement, Configuration table, CacheHelper queryData, Object[][] columnValues, int rowIndex, Map results ) throws SQLException, ConfigurationException, Exception { int currentIndex = 1; // ordering is different for SELECT just needs keys for (int i = 0; i < queryData.columns.length; i++) { Column col = queryData.columns[i]; if ( col.isKey ) { this.setColumn( statement, currentIndex, request, col.columnConf, getOutputName( table, col.columnConf, rowIndex ), columnValues[ i ][ ( col.isSet ? rowIndex : 0 ) ], rowIndex); currentIndex++; } } statement.execute(); // retrieve values ResultSet resultset = statement.getResultSet(); rowIndex = -1; while ( resultset.next() ){ if ( ! ( rowIndex == -1 && resultset.isLast() ) ) { rowIndex++; } for (int i = 0; i < queryData.columns.length; i++) { if ( !queryData.columns[i].isKey ) { Object value = this.getColumn( resultset, queryData.columns[i].columnConf ); String param = getOutputName( table, queryData.columns[i].columnConf, rowIndex ); this.setRequestAttribute( request, param, value ); } } } } /** * Get the Statement column so that the results are mapped correctly. * (this has been copied from AbstractDatabaseAction and modified slightly) */ protected Object getColumn(ResultSet set, Configuration column ) throws Exception { Integer type = (Integer) AbstractDatabaseAction.typeConstants.get(column.getAttribute("type")); String dbcol = column.getAttribute("name"); Object value = null; switch (type.intValue()) { case Types.CLOB: Clob dbClob = set.getClob(dbcol); int length = (int) dbClob.length(); InputStream asciiStream = new BufferedInputStream(dbClob.getAsciiStream()); byte[] buffer = new byte[length]; asciiStream.read(buffer); String str = new String(buffer); asciiStream.close(); value = str; break; case Types.BIGINT: value = set.getBigDecimal(dbcol); break; case Types.TINYINT: value = new Byte(set.getByte(dbcol)); break; case Types.VARCHAR: value = set.getString(dbcol); break; case Types.DATE: value = set.getDate(dbcol); break; case Types.DOUBLE: value = new Double(set.getDouble(dbcol)); break; case Types.FLOAT: value = new Float(set.getFloat(dbcol)); break; case Types.INTEGER: value = new Integer(set.getInt(dbcol)); break; case Types.NUMERIC: value = new Long(set.getLong(dbcol)); break; case Types.SMALLINT: value = new Short(set.getShort(dbcol)); break; case Types.TIME: value = set.getTime(dbcol); break; case Types.TIMESTAMP: value = set.getTimestamp(dbcol); break; case Types.ARRAY: value = set.getArray(dbcol); // new Integer(set.getInt(dbcol)); break; case Types.BIT: value = new Integer(set.getInt(dbcol)); break; case Types.CHAR: value = new Integer(set.getInt(dbcol)); break; case Types.STRUCT: value = (Struct) set.getObject(dbcol); break; case Types.OTHER: value = set.getObject(dbcol); break; default: // The blob types have to be requested separately, via a Reader. value = ""; break; } return value; } } 1.1 xml-cocoon2/src/scratchpad/src/org/apache/cocoon/acting/modular/DatabaseUpdateAction.java Index: DatabaseUpdateAction.java =================================================================== /* ============================================================================ The Apache Software License, Version 1.1 ============================================================================ Copyright (C) 1999-2002 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. This software consists of voluntary contributions made by many individuals on behalf of the Apache Software Foundation and was originally created by Stefano Mazzocchi <[EMAIL PROTECTED]>. For more information on the Apache Software Foundation, please see <http://www.apache.org/>. */ package org.apache.cocoon.acting.modular; import java.util.Map; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.SQLException; import org.apache.cocoon.util.HashMap; import org.apache.avalon.framework.component.ComponentException; import org.apache.avalon.framework.configuration.Configuration; import org.apache.avalon.framework.configuration.ConfigurationException; import org.apache.cocoon.environment.Request; /** * Updates a record in a database. The action can update one or more * tables, and can update more than one row to a table at a time. The * form descriptor semantics for this are still in a bit of a state of * flux. * * @author <a href="mailto:[EMAIL PROTECTED]">Christian Haul</a> * @version CVS $Id: DatabaseUpdateAction.java,v 1.1 2002/03/15 15:23:43 haul Exp $ */ public class DatabaseUpdateAction extends DatabaseAction { /** * determine which mode to use as default mode * here: UPDATE * highly specific to operation INSERT / UPDATE / DELETE / SELECT */ protected String selectMode ( boolean isAutoIncrement, HashMap modes ) { return (String) modes.get( MODE_OTHERS ); } /** * determine whether autoincrement columns should be honoured by * this operation. This is usually snsible only for INSERTs. */ protected boolean honourAutoIncrement() { return false; } /** * Fetch all values for all columns that are needed to do the * database operation. */ protected Object[][] getColumnValues( Configuration tableConf, CacheHelper queryData, Request request ) throws ConfigurationException, ComponentException { Object[][] columnValues = new Object[ queryData.columns.length ][]; for ( int i = 0; i < queryData.columns.length; i++ ){ columnValues[i] = this.getColumnValue( tableConf, queryData.columns[i], request ); } return columnValues; } /** * Get the String representation of the PreparedStatement. This is * mapped to the Configuration object itself, so if it doesn't exist, * it will be created. * * @param table the table's configuration object * @return the insert query as a string */ protected CacheHelper getQuery( Configuration table, HashMap modeTypes, HashMap defaultModeNames ) throws ConfigurationException, ComponentException { LookUpKey lookUpKey = new LookUpKey( table, modeTypes ); CacheHelper queryData = null; synchronized( this.cachedQueryData ) { queryData = (CacheHelper) this.cachedQueryData.get( lookUpKey ); if (queryData == null) { Configuration[] keys = table.getChild("keys").getChildren("key"); Configuration[] values = table.getChild("values").getChildren("value"); queryData = new CacheHelper( keys.length, keys.length + values.length ); fillModes( keys, true, defaultModeNames, modeTypes, queryData ); fillModes( values, false, defaultModeNames, modeTypes, queryData ); StringBuffer queryBuffer = new StringBuffer("UPDATE "); queryBuffer.append(table.getAttribute("name")).append(" SET "); int cols = 0; for (int i = 0; i < queryData.columns.length; i++) { if ( !queryData.columns[i].isKey ) { if ( cols > 0 ) { queryBuffer.append(", "); } cols++; queryBuffer .append( queryData.columns[i].columnConf.getAttribute( "name" ) ) .append( "= ?" ); } } queryBuffer.append(" WHERE "); for (int i = 0; i < queryData.columns.length; i++) { if ( queryData.columns[i].isKey ) { if ( i > 0 ) { queryBuffer.append(" AND "); } queryBuffer .append( queryData.columns[i].columnConf.getAttribute( "name" ) ) .append( "= ?" ); } } queryData.queryString = queryBuffer.toString(); this.cachedQueryData.put( lookUpKey, queryData ); } } return queryData; } /** * set all necessary ?s and execute the query */ protected void processRow ( Request request, Connection conn, PreparedStatement statement, Configuration table, CacheHelper queryData, Object[][] columnValues, int rowIndex, Map results ) throws SQLException, ConfigurationException, Exception { int currentIndex = 1; // ordering is different for UPDATE than for INSERT: values, keys for (int i = 0; i < queryData.columns.length; i++) { Column col = queryData.columns[i]; if ( !col.isKey ) { this.setColumn( statement, currentIndex, request, col.columnConf, getOutputName( table, col.columnConf, rowIndex ), columnValues[ i ][ ( col.isSet ? rowIndex : 0 ) ], rowIndex); currentIndex++; } } for (int i = 0; i < queryData.columns.length; i++) { Column col = queryData.columns[i]; if ( col.isKey ) { this.setColumn( statement, currentIndex, request, col.columnConf, getOutputName( table, col.columnConf, rowIndex ), columnValues[ i ][ ( col.isSet ? rowIndex : 0 ) ], rowIndex); currentIndex++; } } statement.execute(); } } 1.1 xml-cocoon2/src/scratchpad/src/org/apache/cocoon/acting/modular/TestAction.java Index: TestAction.java =================================================================== /* ============================================================================ The Apache Software License, Version 1.1 ============================================================================ Copyright (C) 1999-2002 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. This software consists of voluntary contributions made by many individuals on behalf of the Apache Software Foundation and was originally created by Stefano Mazzocchi <[EMAIL PROTECTED]>. For more information on the Apache Software Foundation, please see <http://www.apache.org/>. */ package org.apache.cocoon.acting.modular; import org.apache.avalon.framework.activity.Initializable; import org.apache.avalon.framework.configuration.Configuration; import org.apache.avalon.framework.configuration.ConfigurationException; import org.apache.avalon.framework.parameters.Parameterizable; import org.apache.avalon.framework.parameters.ParameterException; import org.apache.avalon.framework.parameters.Parameters; import org.apache.avalon.framework.thread.ThreadSafe; import org.apache.avalon.framework.component.ComponentSelector; import org.apache.cocoon.Constants; import org.apache.cocoon.acting.ComposerAction; import org.apache.cocoon.environment.Redirector; import org.apache.cocoon.environment.Request; import org.apache.cocoon.environment.Session; import org.apache.cocoon.environment.SourceResolver; import org.apache.cocoon.components.modules.input.InputModule; import org.apache.cocoon.components.modules.output.OutputModule; import java.util.Enumeration; import java.util.Map; import java.util.HashMap; /** Demo action that uses componentized input / output layer. In order * to stop combinatorial explosion of actions, matchers, and selectors * they should instead use components to access their inputs and * outputs. Available components include request parameters, * attributes, headers, and session attributes. Which component to use * can be specified from sitemap via "input" and "output" parameters. * * This particular action copies all available parameters obtained * from the input component to the output component. * */ public class TestAction extends ComposerAction implements Parameterizable, ThreadSafe { String INPUT_MODULE_ROLE = InputModule.ROLE; String OUTPUT_MODULE_ROLE = OutputModule.ROLE; String INPUT_MODULE_SELECTOR = INPUT_MODULE_ROLE+"Selector"; String OUTPUT_MODULE_SELECTOR = OUTPUT_MODULE_ROLE+"Selector"; String inputHint = "request"; // default to request parameters String outputHint = "attribute"; // default to request attributes public void parameterize(Parameters parameters) throws ParameterException { if (parameters != null) { this.inputHint = parameters.getParameter("input", inputHint); this.outputHint = parameters.getParameter("output", outputHint); } } public Map act( Redirector redirector, SourceResolver resolver, Map objectModel, String source, Parameters param ) throws Exception { // general setup Request request = (Request) objectModel.get(Constants.REQUEST_OBJECT); if (request == null) { getLogger().error("no request object!"); return(null); } InputModule input = null; OutputModule output = null; ComponentSelector inputSelector = null; ComponentSelector outputSelector = null; String inputName = param.getParameter("input", this.inputHint); String outputName = param.getParameter("output", this.outputHint); try { if (getLogger().isDebugEnabled()) getLogger().debug("start..."); // obtain input and output components inputSelector=(ComponentSelector) this.manager.lookup(INPUT_MODULE_SELECTOR); if (inputName != null && inputSelector != null && inputSelector.hasComponent(inputName)){ input = (InputModule) inputSelector.select(inputName); } outputSelector=(ComponentSelector) this.manager.lookup(OUTPUT_MODULE_SELECTOR); if (outputName != null && outputSelector != null && outputSelector.hasComponent(outputName)){ output = (OutputModule) outputSelector.select(outputName); } if (input != null && output != null) { if (getLogger().isDebugEnabled()) getLogger().debug("got input and output adaptors"); // do something // for a test, read all parameters from input and write them to outout Enumeration enum = input.getAttributeNames(null,request); while (enum.hasMoreElements()) { String parameterName = (String) enum.nextElement(); Object value = input.getAttribute(parameterName, null, request); if (getLogger().isDebugEnabled()) getLogger().debug("["+parameterName+"] = ["+value+"]"); output.setAttribute(null, request, parameterName, value); } output.commit(null,request); if (getLogger().isDebugEnabled()) getLogger().debug("done commit"); } } catch (Exception e) { throw e; } finally { // release components if (getLogger().isDebugEnabled()) getLogger().debug("releasing components"); if (outputSelector != null) { if (output != null) outputSelector.release(output); this.manager.release(outputSelector); } if (inputSelector != null) { if (input != null) inputSelector.release(input); this.manager.release(inputSelector); } if (getLogger().isDebugEnabled()) getLogger().debug("... end"); } return this.EMPTY_MAP; } }
---------------------------------------------------------------------- In case of troubles, e-mail: [EMAIL PROTECTED] To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED]