View Javadoc

1   /*
2    * Copyright 1999-2002,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 java.lang.reflect.InvocationTargetException;
22  import javax.servlet.ServletException;
23  import javax.servlet.http.HttpServletRequest;
24  import javax.servlet.http.HttpServletResponse;
25  import javax.servlet.http.HttpSession;
26  import org.apache.commons.beanutils.PropertyUtils;
27  import org.apache.commons.logging.Log;
28  import org.apache.commons.logging.LogFactory;
29  import org.apache.struts.action.Action;
30  import org.apache.struts.action.ActionMessage;
31  import org.apache.struts.action.ActionErrors;
32  import org.apache.struts.action.ActionForm;
33  import org.apache.struts.action.ActionForward;
34  import org.apache.struts.action.ActionMapping;
35  
36  
37  /***
38   * Implementation of <strong>Action</strong> that validates and creates or
39   * updates the user registration information entered by the user.  If a new
40   * registration is created, the user is also implicitly logged on.
41   *
42   * @author Craig R. McClanahan
43   * @version $Rev: 421494 $ $Date: 2006-07-12 20:55:17 -0700 (Wed, 12 Jul 2006) $
44   */
45  
46  public final class SaveRegistrationAction extends Action {
47  
48  
49      // ----------------------------------------------------- Instance Variables
50  
51  
52      /***
53       * The <code>Log</code> instance for this application.
54       */
55      private Log log =
56          LogFactory.getLog("org.apache.struts.webapp.Example");
57  
58  
59      // --------------------------------------------------------- Public Methods
60  
61  
62      /***
63       * Process the specified HTTP request, and create the corresponding HTTP
64       * response (or forward to another web component that will create it).
65       * Return an <code>ActionForward</code> instance describing where and how
66       * control should be forwarded, or <code>null</code> if the response has
67       * already been completed.
68       *
69       * @param mapping The ActionMapping used to select this instance
70       * @param form The optional ActionForm bean for this request (if any)
71       * @param request The HTTP request we are processing
72       * @param response The HTTP response we are creating
73       *
74       * @exception Exception if the application business logic throws
75       *  an exception
76       */
77      public ActionForward execute(ActionMapping mapping,
78  				 ActionForm form,
79  				 HttpServletRequest request,
80  				 HttpServletResponse response)
81  	throws Exception {
82  
83  	// Extract attributes and parameters we will need
84  	HttpSession session = request.getSession();
85  	RegistrationForm regform = (RegistrationForm) form;
86  	String action = regform.getAction();
87  	if (action == null) {
88  	    action = "Create";
89          }
90          UserDatabase database = (UserDatabase)
91  	  servlet.getServletContext().getAttribute(Constants.DATABASE_KEY);
92          if (log.isDebugEnabled()) {
93              log.debug("SaveRegistrationAction:  Processing " + action +
94                        " action");
95          }
96  
97  	// Is there a currently logged on user (unless creating)?
98  	User user = (User) session.getAttribute(Constants.USER_KEY);
99  	if (!"Create".equals(action) && (user == null)) {
100             if (log.isTraceEnabled()) {
101                 log.trace(" User is not logged on in session "
102                           + session.getId());
103             }
104 	    return (mapping.findForward("logon"));
105         }
106 
107 	// Was this transaction cancelled?
108 	if (isCancelled(request)) {
109             if (log.isTraceEnabled()) {
110                 log.trace(" Transaction '" + action +
111                           "' was cancelled");
112             }
113 	    session.removeAttribute(Constants.SUBSCRIPTION_KEY);
114 	    return (mapping.findForward("failure"));
115 	}
116 
117         // Validate the transactional control token
118 	ActionErrors errors = new ActionErrors();
119         if (log.isTraceEnabled()) {
120             log.trace(" Checking transactional control token");
121         }
122         if (!isTokenValid(request)) {
123             errors.add(ActionErrors.GLOBAL_MESSAGE,
124                        new ActionMessage("error.transaction.token"));
125         }
126         resetToken(request);
127 
128 	// Validate the request parameters specified by the user
129         if (log.isTraceEnabled()) {
130             log.trace(" Performing extra validations");
131         }
132 	String value = null;
133 	value = regform.getUsername();
134 	if (("Create".equals(action)) &&
135             (database.findUser(value) != null)) {
136             errors.add("username",
137                        new ActionMessage("error.username.unique",
138                                        regform.getUsername()));
139         }
140 	if ("Create".equals(action)) {
141 	    value = regform.getPassword();
142 	    if ((value == null) || (value.length() <1)) {
143                 errors.add("password",
144                            new ActionMessage("error.password.required"));
145             }
146 	    value = regform.getPassword2();
147 	    if ((value == null) || (value.length() < 1)) {
148                 errors.add("password2",
149                            new ActionMessage("error.password2.required"));
150             }
151 	}
152 
153 	// Report any errors we have discovered back to the original form
154 	if (!errors.isEmpty()) {
155 	    saveErrors(request, errors);
156             saveToken(request);
157             return (mapping.getInputForward());
158 	}
159 
160 	// Update the user's persistent profile information
161         try {
162             if ("Create".equals(action)) {
163                 user = database.createUser(regform.getUsername());
164             }
165             String oldPassword = user.getPassword();
166             PropertyUtils.copyProperties(user, regform);
167             if ((regform.getPassword() == null) ||
168                 (regform.getPassword().length() < 1)) {
169                 user.setPassword(oldPassword);
170             }
171         } catch (InvocationTargetException e) {
172             Throwable t = e.getTargetException();
173             if (t == null) {
174                 t = e;
175             }
176             log.error("Registration.populate", t);
177             throw new ServletException("Registration.populate", t);
178         } catch (Throwable t) {
179             log.error("Registration.populate", t);
180             throw new ServletException("Subscription.populate", t);
181         }
182 
183         try {
184             database.save();
185         } catch (Exception e) {
186             log.error("Database save", e);
187         }
188 
189         // Log the user in if appropriate
190 	if ("Create".equals(action)) {
191 	    session.setAttribute(Constants.USER_KEY, user);
192             if (log.isTraceEnabled()) {
193                 log.trace(" User '" + user.getUsername() +
194                           "' logged on in session " + session.getId());
195             }
196 	}
197 
198 	// Remove the obsolete form bean
199 	if (mapping.getAttribute() != null) {
200             if ("request".equals(mapping.getScope()))
201                 request.removeAttribute(mapping.getAttribute());
202             else
203                 session.removeAttribute(mapping.getAttribute());
204         }
205 
206 	// Forward control to the specified success URI
207         if (log.isTraceEnabled()) {
208             log.trace(" Forwarding to success page");
209         }
210 	return (mapping.findForward("success"));
211 
212     }
213 
214 
215 }