KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > struts > webapp > example2 > SaveRegistrationAction


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 JavaDoc;
22 import java.util.Locale JavaDoc;
23 import javax.servlet.ServletException JavaDoc;
24 import javax.servlet.http.HttpServletRequest JavaDoc;
25 import javax.servlet.http.HttpServletResponse JavaDoc;
26 import javax.servlet.http.HttpSession JavaDoc;
27 import org.apache.commons.beanutils.PropertyUtils;
28 import org.apache.commons.logging.Log;
29 import org.apache.commons.logging.LogFactory;
30 import org.apache.struts.action.Action;
31 import org.apache.struts.action.ActionError;
32 import org.apache.struts.action.ActionErrors;
33 import org.apache.struts.action.ActionForm;
34 import org.apache.struts.action.ActionForward;
35 import org.apache.struts.action.ActionMapping;
36 import org.apache.struts.util.MessageResources;
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: 55303 $ $Date: 2004-10-22 03:56:53 +0100 (Fri, 22 Oct 2004) $
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 JavaDoc request,
82                  HttpServletResponse JavaDoc response)
83     throws Exception JavaDoc {
84
85     // Extract attributes and parameters we will need
86
Locale JavaDoc locale = getLocale(request);
87     MessageResources messages = getResources(request);
88     HttpSession JavaDoc session = request.getSession();
89     RegistrationForm regform = (RegistrationForm) form;
90     String JavaDoc action = regform.getAction();
91     if (action == null) {
92         action = "Create";
93         }
94         UserDatabase database = (UserDatabase)
95       servlet.getServletContext().getAttribute(Constants.DATABASE_KEY);
96         if (log.isDebugEnabled()) {
97             log.debug("SaveRegistrationAction: Processing " + action +
98                       " action");
99         }
100
101     // Is there a currently logged on user (unless creating)?
102
User user = (User) session.getAttribute(Constants.USER_KEY);
103     if (!"Create".equals(action) && (user == null)) {
104             if (log.isTraceEnabled()) {
105                 log.trace(" User is not logged on in session "
106                           + session.getId());
107             }
108         return (mapping.findForward("logon"));
109         }
110
111     // Was this transaction cancelled?
112
if (isCancelled(request)) {
113             if (log.isTraceEnabled()) {
114                 log.trace(" Transaction '" + action +
115                           "' was cancelled");
116             }
117         session.removeAttribute(Constants.SUBSCRIPTION_KEY);
118         return (mapping.findForward("failure"));
119     }
120
121         // Validate the transactional control token
122
ActionErrors errors = new ActionErrors();
123         if (log.isTraceEnabled()) {
124             log.trace(" Checking transactional control token");
125         }
126         if (!isTokenValid(request)) {
127             errors.add(ActionErrors.GLOBAL_ERROR,
128                        new ActionError("error.transaction.token"));
129         }
130         resetToken(request);
131
132     // Validate the request parameters specified by the user
133
if (log.isTraceEnabled()) {
134             log.trace(" Performing extra validations");
135         }
136     String JavaDoc value = null;
137     value = regform.getUsername();
138     if (("Create".equals(action)) &&
139             (database.findUser(value) != null)) {
140             errors.add("username",
141                        new ActionError("error.username.unique",
142                                        regform.getUsername()));
143         }
144     if ("Create".equals(action)) {
145         value = regform.getPassword();
146         if ((value == null) || (value.length() <1)) {
147                 errors.add("password",
148                            new ActionError("error.password.required"));
149             }
150         value = regform.getPassword2();
151         if ((value == null) || (value.length() < 1)) {
152                 errors.add("password2",
153                            new ActionError("error.password2.required"));
154             }
155     }
156
157     // Report any errors we have discovered back to the original form
158
if (!errors.isEmpty()) {
159         saveErrors(request, errors);
160             saveToken(request);
161             return (mapping.getInputForward());
162     }
163
164     // Update the user's persistent profile information
165
try {
166             if ("Create".equals(action)) {
167                 user = database.createUser(regform.getUsername());
168             }
169             String JavaDoc oldPassword = user.getPassword();
170             PropertyUtils.copyProperties(user, regform);
171             if ((regform.getPassword() == null) ||
172                 (regform.getPassword().length() < 1)) {
173                 user.setPassword(oldPassword);
174             }
175         } catch (InvocationTargetException JavaDoc e) {
176             Throwable JavaDoc t = e.getTargetException();
177             if (t == null) {
178                 t = e;
179             }
180             log.error("Registration.populate", t);
181             throw new ServletException JavaDoc("Registration.populate", t);
182         } catch (Throwable JavaDoc t) {
183             log.error("Registration.populate", t);
184             throw new ServletException JavaDoc("Subscription.populate", t);
185         }
186
187         try {
188             database.save();
189         } catch (Exception JavaDoc e) {
190             log.error("Database save", e);
191         }
192
193         // Log the user in if appropriate
194
if ("Create".equals(action)) {
195         session.setAttribute(Constants.USER_KEY, user);
196             if (log.isTraceEnabled()) {
197                 log.trace(" User '" + user.getUsername() +
198                           "' logged on in session " + session.getId());
199             }
200     }
201
202     // Remove the obsolete form bean
203
if (mapping.getAttribute() != null) {
204             if ("request".equals(mapping.getScope()))
205                 request.removeAttribute(mapping.getAttribute());
206             else
207                 session.removeAttribute(mapping.getAttribute());
208         }
209
210     // Forward control to the specified success URI
211
if (log.isTraceEnabled()) {
212             log.trace(" Forwarding to success page");
213         }
214     return (mapping.findForward("success"));
215
216     }
217
218
219 }
220
Popular Tags