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.example;
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.ActionForm;
36  import org.apache.struts.action.ActionForward;
37  import org.apache.struts.action.ActionMapping;
38  import org.apache.struts.action.ActionMessage;
39  import org.apache.struts.action.ActionMessages;
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 = -8108970888606534899L;
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", action);
116         session.removeAttribute(Constants.SUBSCRIPTION_KEY);
117         return (mapping.findForward("failure"));
118     }
119 
120         // Validate the transactional control token
121     ActionMessages errors = new ActionMessages();
122     LOG.trace(" Checking transactional control token");
123     if (!isTokenValid(request)) {
124         errors.add(ActionMessages.GLOBAL_MESSAGE,
125             new ActionMessage("error.transaction.token"));
126     }
127     resetToken(request);
128 
129     // Validate the request parameters specified by the user
130     LOG.trace(" Performing extra validations");
131     String value = null;
132     value = regform.getUsername();
133     if (("Create".equals(action)) &&
134             (database.findUser(value) != null)) {
135             errors.add("username",
136                        new ActionMessage("error.username.unique",
137                                        regform.getUsername()));
138         }
139     if ("Create".equals(action)) {
140         value = regform.getPassword();
141         if ((value == null) || (value.length() <1)) {
142                 errors.add("password",
143                            new ActionMessage("error.password.required"));
144             }
145         value = regform.getPassword2();
146         if ((value == null) || (value.length() < 1)) {
147                 errors.add("password2",
148                            new ActionMessage("error.password2.required"));
149             }
150     }
151 
152     // Report any errors we have discovered back to the original form
153     if (!errors.isEmpty()) {
154         saveErrors(request, errors);
155             saveToken(request);
156             return (mapping.getInputForward());
157     }
158 
159     // Update the user's persistent profile information
160         try {
161             if ("Create".equals(action)) {
162                 user = database.createUser(regform.getUsername());
163             }
164             String oldPassword = user.getPassword();
165             PropertyUtils.copyProperties(user, regform);
166             if ((regform.getPassword() == null) ||
167                 (regform.getPassword().length() < 1)) {
168                 user.setPassword(oldPassword);
169             }
170         } catch (InvocationTargetException e) {
171             Throwable t = e.getTargetException();
172             if (t == null) {
173                 t = e;
174             }
175             LOG.error("Registration.populate", t);
176             throw new ServletException("Registration.populate", t);
177         } catch (Throwable t) {
178             LOG.error("Registration.populate", t);
179             throw new ServletException("Subscription.populate", t);
180         }
181 
182         try {
183             database.save();
184         } catch (Exception e) {
185             LOG.error("Database save", e);
186         }
187 
188     // Log the user in if appropriate
189     if ("Create".equals(action)) {
190         session.setAttribute(Constants.USER_KEY, user);
191         LOG.trace(" User '{}' logged on in session {}",
192             user.getUsername(), session.getId());
193     }
194 
195     // Remove the obsolete form bean
196     if (mapping.getAttribute() != null) {
197             if ("request".equals(mapping.getScope()))
198                 request.removeAttribute(mapping.getAttribute());
199             else
200                 session.removeAttribute(mapping.getAttribute());
201         }
202 
203     // Forward control to the specified success URI
204     LOG.trace(" Forwarding to success page");
205     return (mapping.findForward("success"));
206 
207     }
208 }