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