Hmmmm. No attachment. Code inserted below instead: -----Original Message----- From: Kevin Brown [mailto:[EMAIL PROTECTED] Sent: Thursday, November 13, 2003 4:42 PM To: Struts Developers List Subject: Scaffold FindForwardIndexed - FindForward for indexed properties
All, I wrote the attached FindForwardIndexed class (inspired by scaffold FindForward) which I find useful when I have a list of indexed properties and an action that can be take in each row. The class forwards based on the indexed property submitted, and appends the index to the forward path (will append ${value} if path ends in "=" otherwise will append "index=${value}", where ${value} is the index. mappings look like so: <forward name="view[].x" path="/workingScenarioView.do"/> <forward name="modify[].x" path="/workingScenarioModify.do"/> <forward name="delete[].x" path="/deleteScenario.do?myindex="/> <forward name="approve" path="/approvePlan.do"/> <forward name="publish" path="/publishPlan.do"/> The test case attached is illustrative, but does not work properly because I have not gotten the mock objects to work properly. Enjoy. -Kevin ******************************************************************* package foo; import java.util.Map; import java.util.Iterator; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionMapping; import org.apache.struts.scaffold.BaseAction; import org.apache.log4j.Category; import org.apache.oro.text.regex.*; /** * Scan request parameters for the name of a local or global * forward. If one is found, use it. If not, return null. * <p> * This class extends BaseAction to provide * cross-compatibility with Struts 1.1 and 1.0 * Inspired by the FindForwardAction by Dmitri Valdin and Ted Husted * * @author Kevin Brown * @version $Revision: 1.9 $ $Date: 2003/10/21 19:32:38 $ */ public final class FindForwardIndexedAction extends BaseAction { static Category cat = Category.getInstance(FindForwardIndexedAction.class.getName()); //regex helper function private String replaceFirst(String input, String regex, String replacement){ //return input.replaceFirst(regex, replacement); //can simply use this for jdk1.4.x String result=null; PatternMatcher matcher = new Perl5Matcher(); PatternCompiler compiler = new Perl5Compiler(); Pattern pattern = null; try { pattern = compiler.compile(regex); cat.debug("substitute regex: " + regex); } catch(MalformedPatternException e){ cat.error("Bad pattern.",e); throw new IllegalArgumentException("malformed regex:"+e.getMessage()); } //Search a string for a pattern and substitute only the first occurence of the pattern. /*TODO: docs recommeneded to keep a Perl5Substitution around rather recreating each time could probably create a method that uses the precomipled pattern to wmathc as well*/ result = Util.substitute(matcher, pattern, new Perl5Substitution(replacement, Perl5Substitution.INTERPOLATE_ALL), //TODO: interpoleate =1 suffficient? input); cat.debug("result: " + result); return result; } /** * Scan request parameters for the name of a local or global * forward, allowing for forwards from indexed properties ending with "[]". * Index of index property [n] is added to forward (with a parameter named index, * or a user specifed parameter name) * If one is found, use it. If not, return null. * * @param mapping The ActionMapping used to select this instance * @param form The optional ActionForm bean for this request (if any) * @param request The HTTP request we are processing * @param response The response we are creating */ protected ActionForward findSuccess( ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) { if (cat.isDebugEnabled()){ cat.debug("---begin: parameter map---"); Map parameterMap = request.getParameterMap(); for (Iterator i = parameterMap.entrySet().iterator(); i.hasNext();){ Map.Entry entry = (Map.Entry) i.next(); cat.debug("key: "+ entry.getKey() + "value:"+entry.getValue()); } cat.debug("---end: parameter map---"); cat.debug("---begin: forwards---"); String[] forwards = mapping.findForwards(); for (int i=0; i< forwards.length; i++){ cat.debug("forward:"+forwards[i]); } cat.debug("---end: forwards---"); } ActionForward forward=null; //might take a while, but... Map parameterMap = request.getParameterMap(); cat.debug("---begin: looking for matching forward---"); for (Iterator i = parameterMap.entrySet().iterator(); i.hasNext();){ Map.Entry entry = (Map.Entry) i.next(); if (cat.isDebugEnabled()){ cat.debug("key: "+ entry.getKey() + " value:"+entry.getValue()); } String key = (String) entry.getKey(); String modifiedKey = replaceFirst(key, "\\[.\\]", "[]"); cat.debug("modifiedKey;"+modifiedKey); ActionForward mappingForward = mapping.findForward(modifiedKey); if (mappingForward!=null){ cat.debug("found forward"+mappingForward); //key.matches is not matching!!! //if (key.matches("\\[.\\]")){ //Note: an optimization might be to compile pattern outside of loop // Get stub URI from mapping (/do/whatever?paramName=) String path0 = mappingForward.getPath(); //original path StringBuffer path = new StringBuffer(path0); //"?index=".length() < 16 added to initial capacity //TODO: use oro regex class if not using jdk1.4.x String index = replaceFirst(key, ".*\\[(.)\\].*", "$1"); //add index to path cat.debug("index:"+index); if (index!=null && index.length()!=0) { //look for '?' already cat.debug("unmodified path:"+path); if (path0.indexOf("?") > 0) { //no StringBuffer.indexOf in jdk1.3... if (path.charAt(path.length()-1)=='=') { //path looks like "somepath?foo=bar&index=" and we just append index value path.append(index); } else { //path looks like "somepath?foo=bar" and we just another value path.append("&index="); path.append(index); } } else { //path looks like "somepath" path.append("?index="); //TODO: allow mapping to specify what parameter? e.g., ?index= ro something path.append(index); } } //else just a normal non-Indexed forward // Return a new forward based on stub+value forward = new ActionForward(path.toString()); cat.debug("new forward:"+forward + "path: "+path.toString()); break; } cat.debug("---end: looking for matching forward---"); } if (forward==null){ cat.error("forward==null"); } return forward; } } // end FindForwardAction /* * $Header: /u10/cvs/src/master/MPI/app/src/com/revenuetech/mpi/web/actions/utility/Find ForwardIndexedAction.java,v 1.9 2003/10/21 19:32:38 kevin Exp $ * $Revision: 1.9 $ * $Date: 2003/10/21 19:32:38 $ * * ==================================================================== * * The Apache Software License, Version 1.1 * * Copyright (c) 2002 The Apache Software Foundation. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, 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 acknowlegement: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowlegement may appear in the software itself, * if and wherever such third-party acknowlegements normally appear. * * 4. The names "The Jakarta Project", "Tomcat", 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 names without prior written * permission of the Apache Group. * * 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 (INCLUDING, 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. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ ******************************************************************* package foo; import com.mockrunner.struts.ActionTestCaseAdapter; import com.mockrunner.mock.web.MockForwardConfig; import org.apache.struts.scaffold.NullForm; import org.apache.struts.action.ActionMapping; import java.util.*; /** * Created by IntelliJ IDEA. * User: kbrown * Date: Oct 6, 2003 * Time: 3:32:43 PM * To change this template use Options | File Templates. */ public class FindForwardIndexedActionTest extends ActionTestCaseAdapter { /* private static class IndexedPropertiesActionForm extends ActionForm { private String strAry[]={ "String 0", "String 1", "String 2", "String 3", "String 4" }; public String getStringIndexed(int index) { return (strAry[index]); } public void setStringIndexed(int index, String value) { strAry[index] = value; } } private static class SimpleForm extends ActionForm { private String string; public String getString() { return string; } public void setString(String string) { this.string = string; } } */ // private MockOrderManager orderManager; //private ActionForm indexedPropertiesForm; //private ActionForm simpleForm; protected void setUp() throws Exception { super.setUp(); //orderManager = new MockOrderManager(); // ServletContext context = getMockObjectFactory().getMockServletContext(); //context.setAttribute(OrderManager.class.getName(), orderManager); //some forms we will use //simpleForm = new FindForwardIndexedActionTest.SimpleForm(); //indexedPropertiesForm= new FindForwardIndexedActionTest.IndexedPropertiesActionForm(); //set up our action mapping /*<action path="/reviewpublish" type="blah.actions.utility.FindForwardIndexedAction" name="reviewPublishForm" scope="session"> <forward name="view[].x" path="/workingScenarioView.do"/> <forward name="modify[].x" path="/workingScenarioModify.do"/> <forward name="delete[].x" path="/deleteScenario.do"/> <forward name="approve" path="/approvePlan.do"/> <forward name="publish" path="/publishPlan.do"/> </action> */ //set up action mapping ActionMapping actionMapping = getMockActionMapping(); actionMapping.addForwardConfig(new MockForwardConfig("view[].x","/view.do", false)); actionMapping.addForwardConfig(new MockForwardConfig("modify[].x","/modify.do?myindex=", false)); actionMapping.addForwardConfig(new MockForwardConfig("delete[].x","/delete.do?foo=bar", false)); actionMapping.addForwardConfig(new MockForwardConfig("approve","/approve.do", false)); actionMapping.addForwardConfig(new MockForwardConfig("publish","/publish.do", false)); //set up request setDoPopulate(false); //true wouldn't work quite right with indexed properties I don't think setValidate(false); } public void testUnindexedProperty() { //set up request this.getWebMockObjectFactory().getMockRequest().setupAddParameter("approve", "approve"); //Map parameterMap = this.getWebMockObjectFactory().getWrappedRequest().getParameterMap(); //parameterMap.put("approve","approve"); //actionPerform(FindForwardIndexedAction.class, new NullForm()); actionPerform(new FindForwardIndexedAction(), new NullForm()); verifyNoActionErrors(); verifyNoActionMessages(); verifyForward("/approve.do"); } //path looks like "somepath" public void testIndexedPropertyNoQueryString() { //set up request Map parameterMap = this.getWebMockObjectFactory().getWrappedRequest().getParameterMap(); parameterMap.put("view[32].x","215"); actionPerform(FindForwardIndexedAction.class, new NullForm()); verifyNoActionErrors(); verifyNoActionMessages(); verifyForward("/view.do?index=32"); } //path looks like "somepath?foo=bar" and we just another value public void testIndexedPropertyQueryString() { //set up request Map parameterMap = this.getWebMockObjectFactory().getWrappedRequest().getParameterMap(); parameterMap.put("modify[32].x","215"); actionPerform(FindForwardIndexedAction.class, new NullForm()); verifyNoActionErrors(); verifyNoActionMessages(); verifyForward("/modify.do?myindex=32"); } //path looks like "somepath?foo=bar&index=" and we just append index value public void testIndexedPropertyQueryStringEqualTerminated() { //set up request Map parameterMap = this.getWebMockObjectFactory().getWrappedRequest().getParameterMap(); parameterMap.put("delete[32].x","215"); actionPerform(FindForwardIndexedAction.class, new NullForm()); verifyNoActionErrors(); verifyNoActionMessages(); verifyForward("/delete.do?foo=bar&index=32"); } } --------------------------------------------------------------------- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED]