View Javadoc

1   /*
2    * Copyright 1999-2001,2004 The Apache Software Foundation.
3    * 
4    * Licensed under the Apache License, Version 2.0 (the "License");
5    * you may not use this file except in compliance with the License.
6    * You may obtain a copy of the License at
7    * 
8    *      http://www.apache.org/licenses/LICENSE-2.0
9    * 
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS,
12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13   * See the License for the specific language governing permissions and
14   * limitations under the License.
15   */
16  
17  
18  package org.apache.struts.webapp.example;
19  
20  
21  import javax.servlet.http.HttpServletRequest;
22  import javax.servlet.http.HttpSession;
23  import javax.servlet.http.HttpServletResponse;
24  import org.apache.commons.logging.Log;
25  import org.apache.commons.logging.LogFactory;
26  import org.apache.struts.action.Action;
27  import org.apache.struts.action.ActionMessage;
28  import org.apache.struts.action.ActionMessages;
29  import org.apache.struts.action.ActionForm;
30  import org.apache.struts.action.ActionForward;
31  import org.apache.struts.action.ActionMapping;
32  
33  import org.apache.struts.util.ModuleException;
34  import org.apache.commons.beanutils.PropertyUtils;
35  
36  
37  /***
38   * Implementation of <strong>Action</strong> that validates a user logon.
39   *
40   * @author Craig R. McClanahan
41   * @version $Rev: 421493 $ $Date: 2006-07-12 20:52:31 -0700 (Wed, 12 Jul 2006) $
42   */
43  
44  public final class LogonAction extends Action {
45  
46  
47      // ----------------------------------------------------- Instance Variables
48  
49  
50      /***
51       * The <code>Log</code> instance for this application.
52       */
53      private Log log =
54          LogFactory.getLog("org.apache.struts.webapp.Example");
55  
56  
57      // --------------------------------------------------------- Public Methods
58  
59  
60      /***
61       * Process the specified HTTP request, and create the corresponding HTTP
62       * response (or forward to another web component that will create it).
63       * Return an <code>ActionForward</code> instance describing where and how
64       * control should be forwarded, or <code>null</code> if the response has
65       * already been completed.
66       *
67       * @param mapping The ActionMapping used to select this instance
68       * @param form The optional ActionForm bean for this request (if any)
69       * @param request The HTTP request we are processing
70       * @param response The HTTP response we are creating
71       *
72       * @exception Exception if business logic throws an exception
73       */
74      public ActionForward execute(ActionMapping mapping,
75  				 ActionForm form,
76  				 HttpServletRequest request,
77  				 HttpServletResponse response)
78  	throws Exception {
79  
80  	// Extract attributes we will need
81  	User user = null;
82  
83  	// Validate the request parameters specified by the user
84  	ActionMessages errors = new ActionMessages();
85  	String username = (String)
86              PropertyUtils.getSimpleProperty(form, "username");
87          String password = (String)
88              PropertyUtils.getSimpleProperty(form, "password");
89  	UserDatabase database = (UserDatabase)
90  	  servlet.getServletContext().getAttribute(Constants.DATABASE_KEY);
91  	if (database == null)
92              errors.add(ActionMessages.GLOBAL_MESSAGE,
93                         new ActionMessage("error.database.missing"));
94  	else {
95  	    user = getUser(database, username);
96  	    if ((user != null) && !user.getPassword().equals(password))
97  		user = null;
98  	    if (user == null)
99                  errors.add(ActionMessages.GLOBAL_MESSAGE,
100                            new ActionMessage("error.password.mismatch"));
101 	}
102 
103 	// Report any errors we have discovered back to the original form
104 	if (!errors.isEmpty()) {
105 	    saveErrors(request, errors);
106             return (mapping.getInputForward());
107 	}
108 
109 	// Save our logged-in user in the session
110 	HttpSession session = request.getSession();
111 	session.setAttribute(Constants.USER_KEY, user);
112         if (log.isDebugEnabled()) {
113             log.debug("LogonAction: User '" + user.getUsername() +
114                       "' logged on in session " + session.getId());
115         }
116 
117         // Remove the obsolete form bean
118 	if (mapping.getAttribute() != null) {
119             if ("request".equals(mapping.getScope()))
120                 request.removeAttribute(mapping.getAttribute());
121             else
122                 session.removeAttribute(mapping.getAttribute());
123         }
124 
125 	// Forward control to the specified success URI
126 	return (mapping.findForward("success"));
127 
128     }
129 
130 
131     // ------------------------------------------------------ Protected Methods
132 
133 
134     /***
135      * Look up the user, throwing an exception to simulate business logic
136      * rule exceptions.
137      *
138      * @param database Database in which to look up the user
139      * @param username Username specified on the logon form
140      *
141      * @exception AppException if a business logic rule is violated
142      */
143     public User getUser(UserDatabase database, String username)
144         throws ModuleException {
145 
146         // Force an ArithmeticException which can be handled explicitly
147         if ("arithmetic".equals(username)) {
148             throw new ArithmeticException();
149         }
150 
151         // Force an application-specific exception which can be handled
152         if ("expired".equals(username)) {
153             throw new ExpiredPasswordException(username);
154         }
155 
156         // Look up and return the specified user
157         return (database.findUser(username));
158 
159     }
160 
161 
162 }