01: package com.mockrunner.example.struts;
02:
03: import javax.servlet.ServletContext;
04: import javax.servlet.http.HttpServletRequest;
05: import javax.servlet.http.HttpServletResponse;
06:
07: import org.apache.struts.action.Action;
08: import org.apache.struts.action.ActionErrors;
09: import org.apache.struts.action.ActionForm;
10: import org.apache.struts.action.ActionForward;
11: import org.apache.struts.action.ActionMapping;
12: import org.apache.struts.action.ActionMessage;
13: import org.apache.struts.action.ActionMessages;
14:
15: /**
16: * This example action simulates a simple authentication system
17: * and generates the approriate <code>ActionErrors</code> and
18: * <code>ActionMessages</code>. This action will be tested with
19: * {@link AuthenticationActionTest} in order
20: * to demonstrate the usage of {@link com.mockrunner.struts.ActionTestModule}.
21: */
22: public class AuthenticationAction extends Action {
23: public ActionForward execute(ActionMapping mapping,
24: ActionForm form, HttpServletRequest request,
25: HttpServletResponse response) throws Exception {
26: AuthenticationForm authForm = (AuthenticationForm) form;
27: String username = authForm.getUsername();
28: String password = authForm.getPassword();
29: boolean loginOk = getAuthenticationStrategy(request)
30: .authenticate(username, password);
31: if (loginOk) {
32: addOkMessage(request);
33: return mapping.findForward("success");
34: }
35: addLoginErrors(request, username);
36: return mapping.findForward("failure");
37: }
38:
39: private void addLoginErrors(HttpServletRequest request,
40: String username) {
41: ActionMessages errors = new ActionMessages();
42: if (!getAuthenticationStrategy(request).wasLastUserKnown()) {
43: ActionMessage error = new ActionMessage(
44: "auth.username.unknown", username);
45: errors.add(ActionMessages.GLOBAL_MESSAGE, error);
46: } else if (!getAuthenticationStrategy(request)
47: .wasLastPasswordOk()) {
48: ActionMessage error = new ActionMessage(
49: "auth.password.wrong");
50: errors.add(ActionErrors.GLOBAL_MESSAGE, error);
51: } else {
52: ActionMessage error = new ActionMessage(
53: "auth.general.error");
54: errors.add(ActionErrors.GLOBAL_MESSAGE, error);
55: }
56: saveErrors(request, errors);
57: }
58:
59: private void addOkMessage(HttpServletRequest request) {
60: ActionMessages messages = new ActionMessages();
61: messages.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage(
62: "auth.login.successful"));
63: saveMessages(request, messages);
64: }
65:
66: private AuthenticationStrategy getAuthenticationStrategy(
67: HttpServletRequest request) {
68: ServletContext context = request.getSession()
69: .getServletContext();
70: return (AuthenticationStrategy) context
71: .getAttribute(AuthenticationStrategy.class.getName());
72: }
73: }
|