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