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