KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > jcorporate > expresso > services > test > ControllerTestCase


1 /* ====================================================================
2  * The Jcorporate Apache Style Software License, Version 1.2 05-07-2002
3  *
4  * Copyright (c) 1995-2002 Jcorporate Ltd. All rights reserved.
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions
8  * are met:
9  *
10  * 1. Redistributions of source code must retain the above copyright
11  * notice, this list of conditions and the following disclaimer.
12  *
13  * 2. Redistributions in binary form must reproduce the above copyright
14  * notice, this list of conditions and the following disclaimer in
15  * the documentation and/or other materials provided with the
16  * distribution.
17  *
18  * 3. The end-user documentation included with the redistribution,
19  * if any, must include the following acknowledgment:
20  * "This product includes software developed by Jcorporate Ltd.
21  * (http://www.jcorporate.com/)."
22  * Alternately, this acknowledgment may appear in the software itself,
23  * if and wherever such third-party acknowledgments normally appear.
24  *
25  * 4. "Jcorporate" and product names such as "Expresso" must
26  * not be used to endorse or promote products derived from this
27  * software without prior written permission. For written permission,
28  * please contact info@jcorporate.com.
29  *
30  * 5. Products derived from this software may not be called "Expresso",
31  * or other Jcorporate product names; nor may "Expresso" or other
32  * Jcorporate product names appear in their name, without prior
33  * written permission of Jcorporate Ltd.
34  *
35  * 6. No product derived from this software may compete in the same
36  * market space, i.e. framework, without prior written permission
37  * of Jcorporate Ltd. For written permission, please contact
38  * partners@jcorporate.com.
39  *
40  * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
41  * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
42  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
43  * DISCLAIMED. IN NO EVENT SHALL JCORPORATE LTD OR ITS CONTRIBUTORS
44  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
45  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
46  * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
47  * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
48  * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
49  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
50  * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
51  * SUCH DAMAGE.
52  * ====================================================================
53  *
54  * This software consists of voluntary contributions made by many
55  * individuals on behalf of the Jcorporate Ltd. Contributions back
56  * to the project(s) are encouraged when you make modifications.
57  * Please send them to support@jcorporate.com. For more information
58  * on Jcorporate Ltd. and its products, please see
59  * <http://www.jcorporate.com/>.
60  *
61  * Portions of this software are based upon other open source
62  * products and are subject to their respective licenses.
63  */

64
65 package com.jcorporate.expresso.services.test;
66
67 import com.jcorporate.expresso.core.ExpressoConstants;
68 import com.jcorporate.expresso.core.controller.Controller;
69 import com.jcorporate.expresso.core.controller.ControllerException;
70 import com.jcorporate.expresso.core.controller.ControllerResponse;
71 import com.jcorporate.expresso.core.db.DBConnectionPool;
72 import com.jcorporate.expresso.core.misc.ConfigManager;
73 import com.jcorporate.expresso.core.misc.CookieUtil;
74 import com.jcorporate.expresso.core.misc.StringDOMParser;
75 import org.apache.cactus.ServletTestCase;
76 import org.apache.cactus.WebRequest;
77 import org.apache.cactus.WebResponse;
78 import org.apache.log4j.Category;
79 import org.apache.log4j.Logger;
80 import org.apache.struts.action.ActionForm;
81 import org.apache.struts.action.ActionForward;
82 import org.apache.struts.action.ActionMapping;
83 import org.apache.struts.action.ActionServlet;
84 import org.apache.struts.config.ActionConfig;
85 import org.apache.struts.util.RequestUtils;
86 import org.apache.xpath.XPathAPI;
87 import org.w3c.dom.Document JavaDoc;
88 import org.w3c.dom.NodeList JavaDoc;
89
90 import javax.servlet.ServletException JavaDoc;
91 import javax.servlet.http.HttpSession JavaDoc;
92 import java.io.IOException JavaDoc;
93 import java.net.HttpURLConnection JavaDoc;
94
95
96 /**
97  * Base class for testing controllers. Provides an integration with Expresso,
98  * JUnit and Cactus
99  *
100  * @author Michael Rimov
101  * @version $Revision: 1.17 $ $Date: 2004/11/17 20:48:22 $
102  */

103 public class ControllerTestCase
104         extends ServletTestCase {
105     private String JavaDoc theClass = null;
106     private Logger log = Logger.getLogger(ControllerTestCase.class);
107     private String JavaDoc theState = null;
108     boolean isInitialized = false;
109
110
111     /**
112      * Instantiates the ControllerTestCase.
113      *
114      * @param testName the name of the test. Usually handed down by the framework
115      * @param controllerName The classname of the controller that we're testing.
116      * @throws Exception if something happens in the system initialization or potentially
117      * if the controller name passed doesn't map to a real class
118      */

119     public ControllerTestCase(String JavaDoc testName, String JavaDoc controllerName)
120             throws Exception JavaDoc {
121         super(testName);
122         TestSystemInitializer.setUp();
123         theClass = controllerName;
124
125         //Check to make sure that the controllername is correct. Will initialize
126
//later, but this way the test case doesn't get off to even a start without
127
//the correct name.
128
Class.forName(controllerName);
129     }
130
131     /**
132      * Instantiates a Controller Test Case
133      *
134      * @param testName the name of the test. Usually handed down by the framework
135      * @param controllerClass The class of the controller to test
136      */

137     public ControllerTestCase(String JavaDoc testName, Class JavaDoc controllerClass)
138             throws Exception JavaDoc {
139         super(testName);
140         TestSystemInitializer.setUp();
141         theClass = controllerClass.getName();
142     }
143
144     /**
145      * returns a controller test case Log4j Category for your own easy logging
146      * without having to do special initialization etc.
147      *
148      * @return a log4j category that you can log to.
149      */

150     protected Category getLog() {
151         return log;
152     }
153
154     /**
155      * Uses the default setup that a blank database has the security of
156      * Admin User = Admin
157      * Admin Password = Blank
158      */

159     public void logIn(WebRequest theRequest)
160             throws Exception JavaDoc {
161         this.logIn(theRequest, "Admin", "");
162     }
163
164     /**
165      * Allows special capabilities of logging in using a specially defined username
166      * and password.
167      */

168     public void logIn(WebRequest theRequest, String JavaDoc userName, String JavaDoc password)
169             throws Exception JavaDoc {
170         String JavaDoc encryptedPassword;
171
172         if (password == null || password.length() == 0) {
173             encryptedPassword = "NONE";
174         } else {
175             encryptedPassword = CookieUtil.cookieEncode(password);
176         }
177
178         String JavaDoc encryptedUserName = CookieUtil.cookieEncode(userName);
179         theRequest.addCookie("UserName", encryptedUserName);
180         theRequest.addCookie("Password", encryptedPassword);
181         theRequest.addCookie("db", CookieUtil.cookieEncode(TestSystemInitializer.getTestContext()));
182     }
183
184     /**
185      * Called to set the appropriate states for the controller Also makes sure
186      * that parameters are set up so that the controller responds in unprocessed
187      * XML, and not standard HTML
188      */

189     public void setupParameters(String JavaDoc state, WebRequest request) {
190         theState = state;
191         request.addParameter("style", "xml");
192         request.addParameter("xsl", "none");
193         request.addParameter(Controller.STATE_PARAM_KEY, state);
194     }
195
196     /**
197      * parses the xml into an appropriate DOM document
198      *
199      * @deprecated
200      */

201     public Document JavaDoc parseResponse(WebResponse response)
202             throws Exception JavaDoc {
203         try {
204             int responseCode = response.getConnection().getResponseCode();
205
206             if (responseCode != HttpURLConnection.HTTP_OK) {
207                 fail("Failed to get OK Response code. Got " +
208                         Integer.toString(response.getConnection().getResponseCode()) +
209                         " instead");
210             }
211
212             String JavaDoc s = response.getText();
213             assertTrue("Some Real Content Returned",
214                     response.getConnection().getContentLength() > 4);
215
216             StringDOMParser sdom = new StringDOMParser();
217             Document JavaDoc d = sdom.parseString(s);
218             assertTrue("Reponse Returned Valid XML Document", d != null);
219
220             return d;
221         } catch (java.io.IOException JavaDoc ioe) {
222             log.error("IOException parsing response", ioe);
223             fail("IOException Parsing Reponse");
224
225             return null;
226         }
227     }
228
229     /**
230      * Build a ControllerResponse given an XML DOM document
231      *
232      * @param d The DOM document to parse. Root node must be controller-response
233      * @deprecated
234      */

235     public ControllerResponse buildControllerResponse(Document JavaDoc d) {
236         ControllerResponse cr = null;
237
238         try {
239             cr = ControllerResponse.fromXML(d);
240         } catch (ControllerException ce) {
241             log.error("ControllerException parsing response", ce);
242         }
243
244         assertTrue("Built a valid controller response object", cr != null);
245
246         return cr;
247     }
248
249     /**
250      * Takes the connection handed out by the framework in the endXXXX() methods
251      * and builds a full Controller Response document out of it.
252      *
253      * @deprecated
254      */

255     public ControllerResponse buildControllerResponse(WebResponse theConnection)
256             throws Exception JavaDoc {
257         Document JavaDoc d = parseResponse(theConnection);
258         assertTrue("XML Document Returned", d != null);
259
260         NodeList JavaDoc nl = getNodes(d, "controller-response");
261         assertTrue("controller-response node exists", nl.getLength() > 0);
262
263         return buildControllerResponse(d);
264     }
265
266     /**
267      * Run the target controller. Requires querying the struts framework to find
268      * out the controller, runs the controller, and then forwards the results
269      * to the XML servlet for formatting.
270      *
271      * @since Expresso 3.1
272      */

273     public ControllerResponse controllerProcess()
274             throws ServletException JavaDoc, IOException JavaDoc,
275             Exception JavaDoc {
276         try {
277             ActionServlet servlet = new ActionServlet();
278             servlet.init(config);
279
280             ActionConfig actionConfig = ConfigManager.getActionConfig(theClass, theState);
281             ActionForm form = RequestUtils.createActionForm(request, (ActionMapping) actionConfig,
282                     actionConfig.getModuleConfig(), servlet);
283             if (form != null) {
284                 if ("request".equals(actionConfig.getScope())) {
285                     request.setAttribute(actionConfig.getAttribute(), form);
286                 } else {
287                     HttpSession JavaDoc session = request.getSession();
288                     session.setAttribute(actionConfig.getAttribute(), form);
289                 }
290             }
291
292             Controller controller = null;
293
294             try {
295                 controller = ConfigManager.getControllerFactory().getController(theClass);
296             } catch (ControllerException ce) {
297                 log.error("ControllerException " + theClass, ce);
298                 throw new ServletException JavaDoc(ce);
299             }
300             try {
301                 if (log.isDebugEnabled()) {
302                     log.debug("forwarding to class: " +
303                             controller.getClass().getName());
304                 }
305
306                 ActionForward forward = controller.execute((ActionMapping) actionConfig, form,
307                         request, response);
308
309                 //null forward may be desired if a custom response had been set
310
//
311
if (forward == null) {
312                     return null;
313                 }
314
315                 assertTrue("ERROR: Redirected To Error Page. ",
316                         !(forward.getName().equals("error")));
317
318                 ControllerResponse res = null;
319
320                 try {
321                     res = (ControllerResponse) request.getAttribute(ExpressoConstants.CONTROLLER_RESPONSE_KEY);
322                 } catch (ClassCastException JavaDoc cce) {
323                     fail("Request Attribute Controller.RESPONSE_KEY was not a ControllerResponse Class");
324                 }
325                 if (res == null) {
326                     fail("Error: Controller returned a null controller response");
327                 }
328
329                 return res;
330             } catch (NullPointerException JavaDoc npe) {
331                 log.error("Null Pointer Exception", npe);
332                 throw npe;
333             }
334         } finally {
335
336             //We also need to stop the job queue and start it at the beginning
337
//of the test, but we don't have that ability yet.
338
DBConnectionPool dbcp = DBConnectionPool.getInstance(TestSystemInitializer.getTestContext());
339             dbcp.disconnectAll();
340         }
341     }
342
343     /**
344      * Returns a DOM NodeList given the xpath expression and the document given.
345      * Simply wrapper
346      *
347      * @deprecated
348      */

349     public NodeList JavaDoc getNodes(Document JavaDoc d, String JavaDoc xpath) {
350         NodeList JavaDoc nl = null;
351
352         try {
353             nl = XPathAPI.selectNodeList(d, xpath);
354         } catch (javax.xml.transform.TransformerException JavaDoc trex) {
355             log.error("Error performing transformation", trex);
356         }
357
358         return nl;
359     }
360 }
361
362
Popular Tags