001    package hirondelle.web4jtools.help;
002    
003    import java.util.logging.Logger;
004    import hirondelle.web4j.model.AppException;
005    import hirondelle.web4j.request.RequestParameter;
006    import hirondelle.web4j.request.RequestParser;
007    import hirondelle.web4j.action.ResponsePage;
008    import hirondelle.web4j.action.Action;
009    import hirondelle.web4j.util.Util;
010    
011    /**
012    * Toggle the display of help text, and redirect back to the original URI.
013    * 
014    *  <P>This class interacts with {@link ShowHelpTag} by placing an item in session scope, 
015    *  using a {@link hirondelle.web4jtools.help.ShowHelpTag#KEY} defined by that class.
016    *  
017    *  <P>The original URI is taken from a request parameter named 'OriginalURI', whose value in turn  
018    *  comes from an item named {@link hirondelle.web4j.Controller#CURRENT_URI}, placed in request 
019    *  scope by the Controller.
020    */
021    public final class ShowHelpAction implements Action {
022      
023      /** Constructor. */
024      public ShowHelpAction(RequestParser aRequestParser){
025        fRequestParser = aRequestParser;
026      }
027      
028      public static final RequestParameter ORIGINAL_URI = RequestParameter.withLengthCheck("OriginalURI"); 
029      
030      /** 
031      * Toggle the display of help text, and redirect back to original request.
032      * 
033      * <P>Toggles the value of a {@link Boolean} item in session scoped, identified by 
034      * {@link ShowHelpTag#KEY}.
035      */
036      public ResponsePage execute() throws AppException {
037        toggleDisplayOfHelp();
038        return new ResponsePage(getRedirect());
039      }
040      
041      // PRIVATE //
042      private final RequestParser fRequestParser;
043      private static final Logger fLogger = Util.getLogger(ShowHelpAction.class);
044      
045      private void toggleDisplayOfHelp() {
046        fLogger.fine("Toggling display of help.");
047        Boolean oldSetting = (Boolean)fRequestParser.getRequest().getSession().getAttribute(ShowHelpTag.KEY);
048        Boolean newSetting = null; 
049        if ( oldSetting == null || oldSetting == Boolean.FALSE ){
050          newSetting = Boolean.TRUE;
051        }
052        else {
053          newSetting = Boolean.FALSE;
054        }
055        fRequestParser.getRequest().getSession().setAttribute(ShowHelpTag.KEY, newSetting);
056      }
057      
058      private String getRedirect() {
059        fLogger.fine("Getting original URI.");
060        String result = fRequestParser.getRawParamValue(ORIGINAL_URI);
061        result = Util.replace(result, "&amp;", "&");
062        fLogger.fine("Redirecting to : " + result);
063        return result;
064      }
065    }