View Javadoc

1   package org.appfuse.webapp.action;
2   
3   import org.apache.commons.beanutils.BeanComparator;
4   import org.apache.commons.collections.comparators.NullComparator;
5   import org.apache.commons.collections.comparators.ReverseComparator;
6   import org.apache.commons.logging.Log;
7   import org.apache.commons.logging.LogFactory;
8   import org.appfuse.Constants;
9   import org.appfuse.model.User;
10  import org.appfuse.service.MailEngine;
11  import org.appfuse.service.UserManager;
12  import org.springframework.mail.SimpleMailMessage;
13  
14  import javax.faces.context.FacesContext;
15  import javax.servlet.ServletContext;
16  import javax.servlet.http.HttpServletRequest;
17  import javax.servlet.http.HttpServletResponse;
18  import javax.servlet.http.HttpSession;
19  import java.io.Serializable;
20  import java.text.MessageFormat;
21  import java.util.ArrayList;
22  import java.util.Collections;
23  import java.util.Comparator;
24  import java.util.HashMap;
25  import java.util.List;
26  import java.util.Map;
27  import java.util.ResourceBundle;
28  
29  public class BasePage {
30      protected final Log log = LogFactory.getLog(getClass());
31      protected UserManager userManager;
32      protected MailEngine mailEngine;
33      protected SimpleMailMessage message;
34      protected String templateName;
35      protected FacesContext facesContext;
36      protected String sortColumn;
37      protected boolean ascending = true;
38      protected boolean nullsAreHigh;
39      
40      public FacesContext getFacesContext() {
41          return FacesContext.getCurrentInstance();
42      }
43  
44      public void setUserManager(UserManager userManager) {
45          this.userManager = userManager;
46      }
47  
48      // Convenience methods ====================================================
49      public String getParameter(String name) {
50          return getRequest().getParameter(name);
51      }
52  
53      public Map getCountries() {
54          CountryModel model = new CountryModel();
55          return model.getCountries(getRequest().getLocale());
56      }
57  
58      public String getBundleName() {
59          return getFacesContext().getApplication().getMessageBundle();
60      }
61  
62      public ResourceBundle getBundle() {
63          ClassLoader classLoader =  Thread.currentThread().getContextClassLoader();
64          return ResourceBundle.getBundle(getBundleName(), getRequest().getLocale(), classLoader);
65      }
66  
67      public String getText(String key) {
68          String message;
69  
70          try {
71              message = getBundle().getString(key);
72          } catch (java.util.MissingResourceException mre) {
73              log.warn("Missing key for '" + key + "'");
74              return "???" + key + "???";
75          }
76  
77          return message;
78      }
79  
80      public String getText(String key, Object arg) {
81          if (arg == null) {
82              return getText(key);
83          }
84  
85          MessageFormat form = new MessageFormat(getBundle().getString(key));
86  
87          if (arg instanceof String) {
88              return form.format(new Object[] { arg });
89          } else if (arg instanceof Object[]) {
90              return form.format(arg);
91          } else {
92              log.error("arg '" + arg + "' not String or Object[]");
93  
94              return "";
95          }
96      }
97  
98      @SuppressWarnings("unchecked")
99      protected void addMessage(String key, Object arg) {
100         List<String> messages = (List) getSession().getAttribute("messages");
101 
102         if (messages == null) {
103             messages = new ArrayList<String>();
104         }
105 
106         messages.add(getText(key, arg));
107         getSession().setAttribute("messages", messages);
108     }
109 
110     protected void addMessage(String key) {
111         addMessage(key, null);
112     }
113 
114     @SuppressWarnings("unchecked")
115     protected void addError(String key, Object arg) {
116         List<String> errors = (List) getSession().getAttribute("errors");
117 
118         if (errors == null) {
119             errors = new ArrayList<String>();
120         }
121 
122         // if key contains a space, don't look it up, it's likely a raw message
123         if (key.contains(" ") && arg == null) {
124             errors.add(key);
125         } else {
126             errors.add(getText(key, arg));
127         }
128 
129         getSession().setAttribute("errors", errors);
130     }
131 
132     protected void addError(String key) {
133         addError(key, null);
134     }
135     
136     /**
137      * Convenience method for unit tests.
138      * @return boolean indicator of an "errors" attribute in the session
139      */
140     public boolean hasErrors() {
141         return (getSession().getAttribute("errors") != null);
142     }
143 
144     /**
145      * Servlet API Convenience method
146      * @return HttpServletRequest from the FacesContext
147      */
148     protected HttpServletRequest getRequest() {
149         return (HttpServletRequest) getFacesContext().getExternalContext().getRequest();
150     }
151 
152     /**
153      * Servlet API Convenience method
154      * @return the current user's session
155      */
156     protected HttpSession getSession() {
157         return getRequest().getSession();
158     }
159 
160     /**
161      * Servlet API Convenience method
162      * @return HttpServletResponse from the FacesContext
163      */
164     protected HttpServletResponse getResponse() {
165         return (HttpServletResponse) getFacesContext().getExternalContext().getResponse();
166     }
167 
168     /**
169      * Servlet API Convenience method
170      * @return the ServletContext form the FacesContext
171      */
172     protected ServletContext getServletContext() {
173         return (ServletContext) getFacesContext().getExternalContext().getContext();
174     }
175 
176     /**
177      * Convenience method to get the Configuration HashMap
178      * from the servlet context.
179      *
180      * @return the user's populated form from the session
181      */
182     protected Map getConfiguration() {
183         Map config = (HashMap) getServletContext().getAttribute(Constants.CONFIG);
184 
185         // so unit tests don't puke when nothing's been set
186         if (config == null) {
187             return new HashMap();
188         }
189 
190         return config;
191     }
192 
193     /**
194      * Convenience message to send messages to users, includes app URL as footer.
195      * @param user the user to send the message to
196      * @param msg the message to send
197      * @param url the application's URL
198      */
199     protected void sendUserMessage(User user, String msg, String url) {
200         if (log.isDebugEnabled()) {
201             log.debug("sending e-mail to user [" + user.getEmail() + "]...");
202         }
203 
204         message.setTo(user.getFullName() + "<" + user.getEmail() + ">");
205 
206         Map<String, Serializable> model = new HashMap<String, Serializable>();
207         model.put("user", user);
208 
209         // TODO: once you figure out how to get the global resource bundle in
210         // WebWork, then figure it out here too.  In the meantime, the Username
211         // and Password labels are hard-coded into the template. 
212         // model.put("bundle", getTexts());
213         model.put("message", msg);
214         model.put("applicationURL", url);
215         mailEngine.sendMessage(message, templateName, model);
216     }
217 
218     public void setMailEngine(MailEngine mailEngine) {
219         this.mailEngine = mailEngine;
220     }
221 
222     public void setMessage(SimpleMailMessage message) {
223         this.message = message;
224     }
225 
226     public void setTemplateName(String templateName) {
227         this.templateName = templateName;
228     }
229 
230     // The following methods are used by p:dataTable for sorting.
231     public String getSortColumn() {
232         return sortColumn;
233     }
234 
235     public void setSortColumn(String sortColumn) {
236         this.sortColumn = sortColumn;
237     }
238 
239     public boolean isAscending() {
240         return ascending;
241     }
242 
243     public void setAscending(boolean ascending) {
244         this.ascending = ascending;
245     }
246 
247     /**
248      * Sort list according to which column has been clicked on.
249      * @param list the java.util.List to sort
250      * @return ordered list
251      */
252     @SuppressWarnings("unchecked")
253     protected List sort(List list) {
254         Comparator comparator = new BeanComparator(sortColumn, new NullComparator(nullsAreHigh));
255         if (!ascending) {
256             comparator = new ReverseComparator(comparator);
257         }
258         Collections.sort(list, comparator);
259         return list;
260     }
261 }