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.ActionForm;
36  import org.apache.struts.action.ActionForward;
37  import org.apache.struts.action.ActionMapping;
38  import org.apache.struts.apps.mailreader.dao.Subscription;
39  import org.apache.struts.apps.mailreader.dao.User;
40  import org.apache.struts.apps.mailreader.dao.UserDatabase;
41  import org.apache.struts.util.MessageResources;
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 mail subscription entered by the user.
49   *
50   * @author Craig R. McClanahan
51   * @version $Rev$ $Date$
52   */
53  
54  public final class SaveSubscriptionAction extends Action {
55      private static final long serialVersionUID = 4515607066751024871L;
56  
57  
58      // ----------------------------------------------------- Instance Variables
59  
60  
61      /**
62       * The {@code Log} instance for this class.
63       */
64      private final static Logger LOG =
65          LoggerFactory.getLogger(SaveSubscriptionAction.class);
66  
67  
68      // --------------------------------------------------------- Public Methods
69  
70  
71      /**
72       * Process the specified HTTP request, and create the corresponding HTTP
73       * response (or forward to another web component that will create it).
74       * Return an <code>ActionForward</code> instance describing where and how
75       * control should be forwarded, or <code>null</code> if the response has
76       * already been completed.
77       *
78       * @param mapping The ActionMapping used to select this instance
79       * @param form The optional ActionForm bean for this request (if any)
80       * @param request The HTTP request we are processing
81       * @param response The HTTP response we are creating
82       *
83       * @exception Exception if the application business logic throws
84       *  an exception
85       */
86      public ActionForward execute(ActionMapping mapping,
87                   ActionForm form,
88                   HttpServletRequest request,
89                   HttpServletResponse response)
90      throws Exception {
91  
92      // Extract attributes and parameters we will need
93      MessageResources messages = getResources(request);
94      HttpSession session = request.getSession();
95      SubscriptionForm subform = (SubscriptionForm) form;
96      String action = subform.getAction();
97      if (action == null) {
98          action = "?";
99      }
100     LOG.debug("SaveSubscriptionAction:  Processing {} action",
101         action);
102 
103     // Is there a currently logged on user?
104     User user = (User) session.getAttribute(Constants.USER_KEY);
105     if (user == null) {
106         LOG.trace(" User is not logged on in session {}",
107             session.getId());
108         return (mapping.findForward("logon"));
109     }
110 
111     // Was this transaction cancelled?
112     if (isCancelled(request)) {
113         LOG.trace(" Transaction '{}' was cancelled",
114             action);
115         session.removeAttribute(Constants.SUBSCRIPTION_KEY);
116         return (mapping.findForward("success"));
117     }
118 
119     // Is there a related Subscription object?
120     Subscription subscription =
121         (Subscription) session.getAttribute(Constants.SUBSCRIPTION_KEY);
122         if ("Create".equals(action)) {
123             LOG.trace(" Creating subscription for mail server '{}'",
124                 subform.getHost());
125             subscription =
126                 user.createSubscription(subform.getHost());
127         }
128     if (subscription == null) {
129         LOG.trace(" Missing subscription for user '{}'",
130             user.getUsername());
131         response.sendError(HttpServletResponse.SC_BAD_REQUEST,
132                            messages.getMessage("error.noSubscription"));
133         return (null);
134     }
135 
136     // Was this transaction a Delete?
137     if (action.equals("Delete")) {
138         LOG.trace(" Deleting mail server '{}' for user '{}'",
139             subscription.getHost(), user.getUsername());
140         user.removeSubscription(subscription);
141         session.removeAttribute(Constants.SUBSCRIPTION_KEY);
142         try {
143             UserDatabase database = (UserDatabase)
144                 servlet.getServletContext().
145                 getAttribute(Constants.DATABASE_KEY);
146             database.save();
147         } catch (Exception e) {
148             LOG.error("Database save", e);
149         }
150         return (mapping.findForward("success"));
151     }
152 
153     // All required validations were done by the form itself
154 
155     // Update the persistent subscription information
156     LOG.trace(" Populating database from form bean");
157     try {
158         PropertyUtils.copyProperties(subscription, subform);
159     } catch (InvocationTargetException e) {
160         Throwable t = e.getTargetException();
161         if (t == null)
162             t = e;
163         LOG.error("Subscription.populate", t);
164         throw new ServletException("Subscription.populate", t);
165     } catch (Throwable t) {
166         LOG.error("Subscription.populate", t);
167         throw new ServletException("Subscription.populate", t);
168     }
169 
170     try {
171         UserDatabase database = (UserDatabase)
172             servlet.getServletContext().
173             getAttribute(Constants.DATABASE_KEY);
174         database.save();
175     } catch (Exception e) {
176         LOG.error("Database save", e);
177     }
178 
179     // Remove the obsolete form bean and current subscription
180     if (mapping.getAttribute() != null) {
181         if ("request".equals(mapping.getScope()))
182             request.removeAttribute(mapping.getAttribute());
183         else
184             session.removeAttribute(mapping.getAttribute());
185     }
186     session.removeAttribute(Constants.SUBSCRIPTION_KEY);
187 
188     // Forward control to the specified success URI
189     LOG.trace(" Forwarding to success page");
190     return (mapping.findForward("success"));
191 
192     }
193 }