BaseLookupDispatchAction.java
001 package com.bea.medrec.actions;
002 
003 import com.bea.medrec.beans.ErrorBean;
004 import com.bea.medrec.utils.ClientException;
005 import com.bea.medrec.utils.MedRecLog4jFactory;
006 import com.bea.medrec.utils.MedRecMessageProperties;
007 import com.bea.medrec.utils.MedRecWebAppUtils;
008 import java.lang.reflect.Array;
009 import java.lang.reflect.Constructor;
010 import java.util.*;
011 import javax.servlet.http.HttpServletRequest;
012 import javax.servlet.http.HttpServletResponse;
013 import javax.servlet.http.HttpSession;
014 import org.apache.log4j.Logger;
015 import org.apache.struts.action.ActionForm;
016 import org.apache.struts.action.ActionForward;
017 import org.apache.struts.action.ActionMapping;
018 import org.apache.struts.actions.LookupDispatchAction;
019 
020 /**
021  <p>Base Action encapsulating common lookup dispatch functionality.
022  *    Use when form page contains mulitple submit buttons.</p>
023  *
024  @author Copyright (c) 2006 by BEA Systems. All Rights Reserved.
025  */
026 public abstract class BaseLookupDispatchAction extends LookupDispatchAction {
027   private static Logger logger =
028       MedRecLog4jFactory.getLogger(BaseLookupDispatchAction.class.getName());
029 
030   /**
031    <p>Process the specified HTTP request, and create the corresponding HTTP
032    * response (or forward to another web component that will create it).
033    * Return an <code>ActionForward</code> instance describing where and how
034    * control should be forwarded.
035    <br>
036    * Encapsulates common action functionality including error handling.
037    </p>
038    *
039    @param mapping  The ActionMapping used to select this instance
040    @param form  The optional ActionForm bean for this request (if any)
041    @param request  The HTTP request we are processing
042    @param response  The HTTP response we are creating
043    */
044   public ActionForward execute(ActionMapping mapping,
045                                ActionForm form,
046                                HttpServletRequest request,
047                                HttpServletResponse response)
048       throws Exception {
049     ActionForward forward;
050     try {
051       logger.debug("Mapping param = "+mapping.getParameter());
052       logger.debug("Button selected = "+request.getParameter(mapping.getParameter()));
053       if (request.getParameter(mapping.getParameter()) == null) {
054         logger.debug("Default method call.");
055         forward = defaultMethod(mapping, form, request, response);
056       else {
057         logger.debug("Executing LookupDispatchAction.");
058         forward = super.execute(mapping, form, request, response);
059         if (logger.isDebugEnabled()) printSessionContents(request);
060       }
061     catch (Exception e) {
062       return handleException(e, request, mapping);
063     }
064     return forward;
065   }
066 
067   /**
068    <p>All sub-classes must implement this method where if
069    * not action is supplied the defaultMethod implementation
070    * will be executed.</p>
071    *
072    @param mapping  The ActionMapping used to select this instance
073    @param form  The optional ActionForm bean for this request (if any)
074    @param request  The HTTP request we are processing
075    @param response  The HTTP response we are creating
076    */
077   public abstract ActionForward defaultMethod(ActionMapping mapping,
078                                               ActionForm form,
079                                               HttpServletRequest request,
080                                               HttpServletResponse response)
081       throws Exception;
082 
083 
084   /**
085    <p>Removes an attribute from HttpSession.</p>
086    *
087    @param req  The HTTP request we are processing
088    @param name  The name of the attribute to be removed.
089    */
090   protected void removeSessionAttribute(HttpServletRequest req, String name) {
091     logger.debug("Removing "+name+" from session.");
092     HttpSession session = req.getSession(false);
093     if (session != nullsession.removeAttribute(name);
094   }
095 
096   /**
097    <p>Sets an object to the HttpSession</p>
098    *
099    @param req  The HTTP request we are processing
100    @param name  The name key of object.
101    @param obj  The object to be set on HttpSession.
102    */
103   protected void setSessionAttribute(HttpServletRequest req,
104                                      String name,
105                                      Object obj) {
106     logger.debug("Setting "+name+" of type "
107        +obj.getClass().getName()+" on session.");
108     HttpSession session = req.getSession(false);
109     if (session != nullsession.setAttribute(name, obj);
110   }
111 
112   /**
113    <p>Retrieves an object from HttpSession.</p>
114    *
115    @param req  The HTTP request we are processing
116    @param name  The name of the attribute to be retrieved.
117    */
118   protected Object getSessionAttribute(HttpServletRequest req, String name) {
119     logger.debug("Getting "+name+" from session.");
120     Object obj = null;
121     HttpSession session = req.getSession(false);
122     if (session != nullobj = session.getAttribute(name);
123     return obj;
124   }
125 
126   /**
127    <p>Prints values set on the current HttpSession.</p>
128    *
129    @param req  The HTTP request we are processing
130    */
131   protected void printSessionContents(HttpServletRequest req) {
132     HttpSession session = req.getSession(false);
133     if (session != null) {
134       Enumeration enum_ = session.getAttributeNames();
135       StringBuffer strBuf = new StringBuffer();
136       strBuf.append("Session contents:");
137       int i = 0;
138       while (enum_.hasMoreElements()) {
139         String name = (String)enum_.nextElement();
140         Object obj = session.getAttribute(name);
141         strBuf.append("\n  "+(++i)+") name="+name+"; type="+
142             obj.getClass().getName());
143       }
144       logger.debug(strBuf.toString());
145     }
146   }
147 
148   /**
149    <p>Sets user's locale.</p>
150    *
151    @param request  The HTTP request we are processing
152    */
153   protected void setupLocale(HttpServletRequest request) {
154     logger.debug("Setup locale.");
155     Locale locale = MedRecWebAppUtils.getLocaleFromCookie(request);
156     if (locale == nulllocale = getLocale(request);
157     if (!MedRecWebAppUtils.isValidLocale(locale))
158       locale = new Locale("en""US");
159     logger.debug("Locale: "+locale);
160     setLocale(request, locale);
161   }
162 
163   /**
164    <p>Get localize message.</p>
165    *
166    @param key  The HTTP request we are processing
167    */
168   protected String getMessage(HttpServletRequest request, String key) {
169     Locale locale = getLocale(request);
170     return getResources(request).getMessage(locale, key);
171   }
172 
173   /**
174    <p>Get localize message.</p>
175    *
176    @param key  The HTTP request we are processing
177    */
178   protected String getMessage(HttpServletRequest request,
179                               Locale locale,
180                               String key) {
181     return getResources(request).getMessage(locale, key);
182   }
183 
184   /**
185    <p>Get instance of message properties.</p>
186    *
187    @param request  The HTTP request we are processing
188    */
189   protected MedRecMessageProperties getMessageProps(HttpServletRequest request) {
190     Locale locale = getLocale(request);
191     return MedRecMessageProperties.getInstance(locale, getResources(request));
192   }
193 
194   /**
195    <p>Formulates and throws client exception.<p>
196    *
197    @param th
198    @param mapping
199    @param redirect
200    @throws ClientException
201    */
202   protected void throwClientException(Throwable th,
203                                       ActionMapping mapping,
204                                       String redirect)
205       throws ClientException {
206     if (logger.isDebugEnabled()) th.printStackTrace();
207     else logger.error(th.getMessage());
208     String errorLink = MedRecWebAppUtils.getServletName(mapping, redirect);
209     logger.debug("errorLink: "+errorLink);
210     throw new ClientException(th, errorLink);
211   }
212 
213   /**
214    <p>Uniform way of handling exceptions.<p>
215    *
216    @param th
217    @param mapping
218    @param request
219    *
220    @return ActionForward
221    */
222   protected ActionForward handleException(Throwable th,
223                                           HttpServletRequest request,
224                                           ActionMapping mapping) {
225     if (th instanceof ClientException) {
226       logger.error(th);
227       if (logger.isDebugEnabled()) th.printStackTrace();
228       String redirectLink = ((ClientExceptionth).getLink();
229       logger.info("Redirect link: "+redirectLink);
230       ErrorBean errorBean = new ErrorBean(MedRecWebAppUtils.getRootErrMsg(th),
231           redirectLink);
232       request.setAttribute("errorBean", errorBean);
233       return mapping.findForward("error");
234     else {
235       logger.error(th);
236       if (logger.isDebugEnabled()) th.printStackTrace();
237       String link = MedRecWebAppUtils.getServletName(mapping, "home");
238       logger.info("Redirect link: "+link);
239       ErrorBean errorBean = new ErrorBean(MedRecWebAppUtils.getRootErrMsg(th),
240           link);
241       request.setAttribute("errorBean", errorBean);
242       return mapping.findForward("error");
243     }
244   }
245 
246   /**
247    <p>String null check.</p>
248    *
249    @param str
250    */
251   public boolean isNotEmpty(String str) {
252     return str != null && str.length() 0;
253   }
254 
255   /**
256    <p>String null check.</p>
257    *
258    @param str
259    */
260   public boolean isEmpty(String str) {
261     return !(isNotEmpty(str));
262   }
263 
264   /**
265    <p>Converts a array to array of given class.</p>
266    *
267    @param pObjArray Array of objects
268    @param pClazz Class of newly transformed array
269    @return Object Array of given Class objects
270    */
271   public Object toObjectBeanArray(Object[] pObjArray, Class pClazz) {
272     logger.debug("Converting incoming array to array of "+pClazz.getName());
273     if (pObjArray != null && pObjArray.length > 0) {
274       Class cl = pObjArray.getClass().getComponentType();
275       logger.debug("Incoming array contains the ojbects of type: "+
276           cl.getName());
277       Object newObjArray = Array.newInstance(pClazz, pObjArray.length);
278       for (int i=0; i<pObjArray.length; i++) {
279         try {
280           Constructor constr = pClazz.getConstructor(new Class[]{cl});
281           logger.debug("Calling the following constructor: "+constr.getName());
282           Array.set(newObjArray, i, constr.newInstance(new Object[]{pObjArray[i]}));
283         catch (Exception e) {
284           logger.error("Unable to transform value object array.", e);
285         }
286       }
287       return newObjArray;
288     else {
289       logger.debug("Incoming array null or len=0");
290       return Array.newInstance(pClazz, 0);
291     }
292   }
293 
294   /**
295    <p>Converts a array to array of given class.</p>
296    *
297    @param pObjArray Array of objects
298    @param pClazz Class of newly transformed array
299    @return Collection Collection of given Class objects
300    */
301   public Collection toCollectionBean(Object[] pObjArray, Class pClazz) {
302     logger.debug("Converting incoming array to Collection of "+pClazz.getName());
303     if (pObjArray != null && pObjArray.length > 0) {
304       Class cl = pObjArray.getClass().getComponentType();
305       logger.debug("Incoming array contains the ojbects of type: "+
306           cl.getName());
307       Collection<Object> newCollection = new ArrayList<Object>();
308       for (int i=0; i<pObjArray.length; i++) {
309         try {
310           Constructor constr = pClazz.getConstructor(new Class[]{cl});
311           logger.debug("Calling the following constructor: "+constr.getName());
312           newCollection.add(constr.newInstance(new Object[]{pObjArray[i]}));
313         catch (Exception e) {
314           logger.error("Unable to transform value object array.", e);
315         }
316       }
317       return newCollection;
318     else {
319       logger.debug("Incoming array null or len=0");
320       return new ArrayList<Object>();
321     }
322   }
323 
324   /**
325    <p>Converts a Collection to array of given class.</p>
326    *
327    @param objCol Collection of objects
328    @param pClazz Class of newly transformed array
329    @return Object Array of given Class objects
330    */
331   protected Object toArray(Collection objCol, Class pClazz) {
332     logger.debug("Converting incoming collection to array of "+pClazz.getName());
333     if (objCol != null && objCol.size() 0) {
334       Object newObjArray = null;
335       Constructor constr = null;
336       try {
337         newObjArray = Array.newInstance(pClazz, objCol.size());
338         Iterator itr = objCol.iterator();
339         Object obj = (Objectitr.next();
340         Class cl = obj.getClass();
341         logger.debug("Incoming collection contains the ojbects of type: "+
342             cl.getName());
343         logger.debug("Calling the following constructor: "+constr.getName());
344         constr = pClazz.getConstructor(new Class[]{cl});
345         int i = 0;
346         while (itr.hasNext()) {
347           obj = (Objectitr.next();
348           Array.set(newObjArray, i, constr.newInstance(new Object[]{obj}));
349           i++;
350         }
351       catch (Exception e) {
352           logger.error("Unable to transform value object array", e);
353       }
354       return newObjArray;
355     else {
356       logger.debug("Incoming array null or len=0");
357       return Array.newInstance(pClazz, 0);
358     }
359   }
360 }