View Javadoc
1   /*
2    * $Id$
3    *
4    * Licensed to the Apache Software Foundation (ASF) under one
5    * or more contributor license agreements.  See the NOTICE file
6    * distributed with this work for additional information
7    * regarding copyright ownership.  The ASF licenses this file
8    * to you under the Apache License, Version 2.0 (the
9    * "License"); you may not use this file except in compliance
10   * with the License.  You may obtain a copy of the License at
11   *
12   *  http://www.apache.org/licenses/LICENSE-2.0
13   *
14   * Unless required by applicable law or agreed to in writing,
15   * software distributed under the License is distributed on an
16   * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
17   * KIND, either express or implied.  See the License for the
18   * specific language governing permissions and limitations
19   * under the License.
20   */
21  
22  
23  package org.apache.struts.webapp.example2;
24  
25  
26  import java.lang.reflect.InvocationTargetException;
27  
28  import jakarta.servlet.ServletException;
29  import jakarta.servlet.http.HttpServletRequest;
30  import jakarta.servlet.http.HttpServletResponse;
31  import jakarta.servlet.http.HttpSession;
32  
33  import org.apache.commons.beanutils.PropertyUtils;
34  import org.apache.struts.action.Action;
35  import org.apache.struts.action.ActionErrors;
36  import org.apache.struts.action.ActionForm;
37  import org.apache.struts.action.ActionForward;
38  import org.apache.struts.action.ActionMapping;
39  import org.apache.struts.action.ActionMessage;
40  import org.apache.struts.apps.mailreader.dao.User;
41  import org.apache.struts.apps.mailreader.dao.UserDatabase;
42  import org.slf4j.Logger;
43  import org.slf4j.LoggerFactory;
44  
45  
46  /**
47   * Implementation of <strong>Action</strong> that validates and creates or
48   * updates the user registration information entered by the user.  If a new
49   * registration is created, the user is also implicitly logged on.
50   *
51   * @author Craig R. McClanahan
52   * @version $Rev$ $Date$
53   */
54  
55  public final class SaveRegistrationAction extends Action {
56      private static final long serialVersionUID = -7931388143259911830L;
57  
58  
59      // ----------------------------------------------------- Instance Variables
60  
61  
62      /**
63       * The {@code Log} instance for this class.
64       */
65      private final static Logger LOG =
66          LoggerFactory.getLogger(SaveRegistrationAction.class);
67  
68  
69      // --------------------------------------------------------- Public Methods
70  
71  
72      /**
73       * Process the specified HTTP request, and create the corresponding HTTP
74       * response (or forward to another web component that will create it).
75       * Return an <code>ActionForward</code> instance describing where and how
76       * control should be forwarded, or <code>null</code> if the response has
77       * already been completed.
78       *
79       * @param mapping The ActionMapping used to select this instance
80       * @param form The optional ActionForm bean for this request (if any)
81       * @param request The HTTP request we are processing
82       * @param response The HTTP response we are creating
83       *
84       * @exception Exception if the application business logic throws
85       *  an exception
86       */
87      public ActionForward execute(ActionMapping mapping,
88                   ActionForm form,
89                   HttpServletRequest request,
90                   HttpServletResponse response)
91      throws Exception {
92  
93          // Extract attributes and parameters we will need
94          HttpSession session = request.getSession();
95          RegistrationForm regform = (RegistrationForm) form;
96          String action = regform.getAction();
97          if (action == null) {
98              action = "Create";
99          }
100         UserDatabase database = (UserDatabase)
101         servlet.getServletContext().getAttribute(Constants.DATABASE_KEY);
102         LOG.debug("SaveRegistrationAction:  Processing {} action",
103             action);
104 
105         // Is there a currently logged on user (unless creating)?
106         User user = (User) session.getAttribute(Constants.USER_KEY);
107         if (!"Create".equals(action) && (user == null)) {
108             LOG.trace(" User is not logged on in session {}",
109                 session.getId());
110             return (mapping.findForward("logon"));
111         }
112 
113         // Was this transaction cancelled?
114         if (isCancelled(request)) {
115             LOG.trace(" Transaction '{}' was cancelled",
116                 action);
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         LOG.trace(" Checking transactional control token");
124         if (!isTokenValid(request)) {
125             errors.add(ActionErrors.GLOBAL_MESSAGE,
126                 new ActionMessage("error.transaction.token"));
127         }
128         resetToken(request);
129 
130         // Validate the request parameters specified by the user
131         LOG.trace(" Performing extra validations");
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             LOG.trace(" User '{}' logged on in session {}",
193                 user.getUsername(), session.getId());
194         }
195 
196         // Remove the obsolete form bean
197         if (mapping.getAttribute() != null) {
198             if ("request".equals(mapping.getScope()))
199                 request.removeAttribute(mapping.getAttribute());
200             else
201                 session.removeAttribute(mapping.getAttribute());
202         }
203 
204         // Forward control to the specified success URI
205         LOG.trace(" Forwarding to success page");
206         return (mapping.findForward("success"));
207     }
208 }