View Javadoc

1   /*
2    * Copyright (c) 2002-2014, Mairie de Paris
3    * All rights reserved.
4    *
5    * Redistribution and use in source and binary forms, with or without
6    * modification, are permitted provided that the following conditions
7    * are met:
8    *
9    *  1. Redistributions of source code must retain the above copyright notice
10   *     and the following disclaimer.
11   *
12   *  2. Redistributions in binary form must reproduce the above copyright notice
13   *     and the following disclaimer in the documentation and/or other materials
14   *     provided with the distribution.
15   *
16   *  3. Neither the name of 'Mairie de Paris' nor 'Lutece' nor the names of its
17   *     contributors may be used to endorse or promote products derived from
18   *     this software without specific prior written permission.
19   *
20   * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
21   * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22   * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23   * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE
24   * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
25   * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
26   * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
27   * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
28   * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
29   * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
30   * POSSIBILITY OF SUCH DAMAGE.
31   *
32   * License 1.0
33   */
34  package fr.paris.lutece.portal.util.mvc.admin;
35  
36  import fr.paris.lutece.portal.service.admin.AccessDeniedException;
37  import fr.paris.lutece.portal.service.i18n.I18nService;
38  import fr.paris.lutece.portal.service.template.AppTemplateService;
39  import fr.paris.lutece.portal.service.util.AppException;
40  import fr.paris.lutece.portal.util.mvc.admin.annotations.Controller;
41  import fr.paris.lutece.portal.util.mvc.utils.MVCMessage;
42  import fr.paris.lutece.portal.util.mvc.utils.MVCUtils;
43  import fr.paris.lutece.portal.web.admin.PluginAdminPageJspBean;
44  import fr.paris.lutece.util.ErrorMessage;
45  import fr.paris.lutece.util.beanvalidation.ValidationError;
46  import fr.paris.lutece.util.html.HtmlTemplate;
47  import fr.paris.lutece.util.url.UrlItem;
48  import java.io.IOException;
49  import java.io.Serializable;
50  import java.lang.reflect.InvocationTargetException;
51  import java.lang.reflect.Method;
52  import java.util.ArrayList;
53  import java.util.HashMap;
54  import java.util.List;
55  import java.util.Locale;
56  import java.util.Map;
57  import java.util.Map.Entry;
58  import javax.servlet.http.HttpServletRequest;
59  import javax.servlet.http.HttpServletResponse;
60  import org.apache.log4j.Logger;
61  import org.springframework.util.ReflectionUtils;
62  
63  
64  /**
65   * MVC Admin JspBean implementation let use MVC model to develop admin feature.
66   */
67  public abstract class MVCAdminJspBean extends PluginAdminPageJspBean implements Serializable
68  {
69      private static final String MARK_ERRORS = "errors";
70      private static final String MARK_INFOS = "infos";
71      
72      private static Logger _logger = MVCUtils.getLogger(  );
73      
74      private List<ErrorMessage> _listErrors = new ArrayList<ErrorMessage>(  );
75      private List<ErrorMessage> _listInfos = new ArrayList<ErrorMessage>(  );
76      private Controller _controller = getClass(  ).getAnnotation( Controller.class );
77      private HttpServletResponse _response;
78  
79      /**
80       * Process request as a controller
81       * @param request The HTTP request
82       * @param response The HTTP response
83       * @return The page content
84       * @throws AccessDeniedException If the user's has no right
85       */
86      public String processController( HttpServletRequest request, HttpServletResponse response )
87          throws AccessDeniedException
88      {
89          _response = response;
90          init( request, _controller.right(  ) );
91  
92          Method[] methods = ReflectionUtils.getAllDeclaredMethods( getClass(  ) );
93  
94          try
95          {
96              // Process views
97              Method m = MVCUtils.findViewAnnotedMethod( request, methods );
98  
99              if ( m != null )
100             {
101                 return (String) m.invoke( this, request );
102             }
103 
104             // Process actions
105             m = MVCUtils.findActionAnnotedMethod( request, methods );
106 
107             if ( m != null )
108             {
109                 return (String) m.invoke( this, request );
110             }
111 
112             // No view or action found so display the default view
113             m = MVCUtils.findDefaultViewMethod( methods );
114 
115             return (String) m.invoke( this, request );
116         }
117         catch ( InvocationTargetException e )
118         {
119             if ( e.getTargetException( ) instanceof AccessDeniedException )
120             {
121                 throw (AccessDeniedException) e.getTargetException( );
122             }
123 
124             throw new AppException( "MVC Error dispaching view and action ", e );
125         }
126         catch ( IllegalAccessException e )
127         {
128             throw new AppException( "MVC Error dispaching view and action ", e );
129         }
130     }
131 
132     ////////////////////////////////////////////////////////////////////////////
133     // Page utils 
134 
135     /**
136      * Add an error message
137      * @param strMessage The message
138      */
139     protected void addError( String strMessage )
140     {
141         _listErrors.add( new MVCMessage( strMessage ) );
142     }
143 
144     /**
145      * Add an error message
146      * @param strMessageKey The message
147      * @param locale The locale
148      */
149     protected void addError( String strMessageKey, Locale locale )
150     {
151         _listErrors.add( new MVCMessage( I18nService.getLocalizedString( strMessageKey, locale ) ) );
152     }
153 
154     /**
155      * Add an info message
156      * @param strMessage The message
157      */
158     protected void addInfo( String strMessage )
159     {
160         _listInfos.add( new MVCMessage( strMessage ) );
161     }
162 
163     /**
164      * Add an info message
165      * @param strMessageKey The message key
166      * @param locale The locale
167      */
168     protected void addInfo( String strMessageKey, Locale locale )
169     {
170         _listInfos.add( new MVCMessage( I18nService.getLocalizedString( strMessageKey, locale ) ) );
171     }
172 
173     /**
174     * Fill the model with commons objects used in templates
175     * @param model The model
176     */
177     protected void fillCommons( Map<String, Object> model )
178     {
179         List<ErrorMessage> listErrors = new ArrayList<ErrorMessage>( _listErrors );
180         List<ErrorMessage> listInfos = new ArrayList<ErrorMessage>( _listInfos );
181         model.put( MARK_ERRORS, listErrors );
182         model.put( MARK_INFOS, listInfos );
183         _listErrors.clear(  );
184         _listInfos.clear(  );
185     }
186 
187     /**
188      * Get a model Object filled with default values
189      * @return The model
190      */
191     protected Map<String, Object> getModel(  )
192     {
193         Map<String, Object> model = new HashMap<String, Object>(  );
194         fillCommons( model );
195 
196         return model;
197     }
198 
199     /**
200      * Return the page content
201      * @param strTemplate The template
202      * @return The page
203      */
204     protected String getPage( String strTemplate )
205     {
206         String strPageTitleProperty = _controller.pageTitleProperty(  );
207 
208         return getPage( strPageTitleProperty, strTemplate, getModel(  ) );
209     }
210 
211     /**
212      * Return the page content
213      * @param strPageTitleProperty The page title property
214      * @param strTemplate The template
215      * @return The page
216      */
217     protected String getPage( String strPageTitleProperty, String strTemplate )
218     {
219         return getPage( strPageTitleProperty, strTemplate, getModel(  ) );
220     }
221 
222     /**
223      * Return the page content
224      * @param strPageTitleProperty The page title property
225      * @param strTemplate The template
226      * @param model The model
227      * @return The page
228      */
229     protected String getPage( String strPageTitleProperty, String strTemplate, Map<String, Object> model )
230     {
231         setPageTitleProperty( strPageTitleProperty );
232 
233         HtmlTemplate template = AppTemplateService.getTemplate( strTemplate, getLocale(  ), model );
234 
235         return getAdminPage( template.getHtml(  ) );
236     }
237 
238     /**
239      * Validate a bean
240      * @param <T> The bean class
241      * @param bean The bean
242      * @param strPrefix The prefix
243      * @return true if validated otherwise false
244      */
245     protected <T> boolean validateBean( T bean, String strPrefix )
246     {
247         List<ValidationError> errors = validate( bean, strPrefix );
248 
249         if ( errors.isEmpty(  ) )
250         {
251             return true;
252         }
253 
254         for ( ValidationError errorValidation : errors )
255         {
256             MVCMessage error = new MVCMessage(  );
257             error.setMessage( errorValidation.getMessage(  ) );
258             _listErrors.add( error );
259         }
260 
261         return false;
262     }
263 
264     ////////////////////////////////////////////////////////////////////////////
265     // Redirect utils
266 
267     /**
268      * Return the JSP name used as controller
269      * @return The JSP name
270      */
271     protected String getControllerJsp(  )
272     {
273         return _controller.controllerJsp(  );
274     }
275 
276     /**
277      * Return the path of the JSP used as controller
278      * @return The controller path
279      */
280     protected String getControllerPath(  )
281     {
282         return _controller.controllerPath(  );
283     }
284 
285     /**
286      * Redirect to requested page
287      *
288      * @param request the http request
289      * @param strTarget the targeted page
290      * @return null. The page should be redirected
291      */
292     protected String redirect( HttpServletRequest request, String strTarget )
293     {
294         try
295         {
296             _logger.debug( "Redirect :" + strTarget );
297             _response.sendRedirect( strTarget );
298         }
299         catch ( IOException e )
300         {
301             _logger.error( "Unable to redirect : " + strTarget + " : " + e.getMessage(  ), e );
302         }
303 
304         return null;
305     }
306 
307     /**
308      * Redirect to an url defined by given parameters
309      * @param request The HTTP request
310      * @param strView The View name
311      * @param strParameter The additional parameter
312      * @param nValue The additional parameter's value
313      * @return The redirection result
314      */
315     protected String redirect( HttpServletRequest request, String strView, String strParameter, int nValue )
316     {
317         UrlItem url = new UrlItem( getViewUrl( strView ) );
318         url.addParameter( strParameter, nValue );
319 
320         return redirect( request, url.getUrl(  ) );
321     }
322 
323     /**
324      * Redirect to an url defined by given parameters
325      * @param request The HTTP request
326      * @param strView The View name
327      * @param strParameter1 The first additional parameter
328      * @param nValue1 The first additional parameter's value
329      * @param strParameter2 The second additionnal parameter
330      * @param nValue2 The second additionnal parameter's value
331      * @return The redirection result
332      */
333     protected String redirect( HttpServletRequest request, String strView, String strParameter1, int nValue1,
334         String strParameter2, int nValue2 )
335     {
336         UrlItem url = new UrlItem( getViewUrl( strView ) );
337         url.addParameter( strParameter1, nValue1 );
338         url.addParameter( strParameter2, nValue2 );
339 
340         return redirect( request, url.getUrl(  ) );
341     }
342 
343     /**
344      * Redirect to an url defined by given parameters
345      * @param request The HTTP request
346      * @param strView The View name
347      * @param additionalParameters A map containing parameters to add to the
348      *            URL. Keys of the map are parameters name, and values are
349      *            parameters values
350      * @return The XPage redirected
351      */
352     protected String redirect( HttpServletRequest request, String strView, Map<String, String> additionalParameters )
353     {
354         UrlItem url = new UrlItem( getViewUrl( strView ) );
355 
356         if ( additionalParameters != null )
357         {
358             for ( Entry<String, String> entry : additionalParameters.entrySet( ) )
359             {
360                 url.addParameter( entry.getKey( ), entry.getValue( ) );
361             }
362         }
363         return redirect( request, url.getUrl( ) );
364     }
365 
366     /**
367      * Redirect to requested view
368      *
369      * @param request the http request
370      * @param strView the targeted view
371      * @return The redirection result
372      */
373     protected String redirectView( HttpServletRequest request, String strView )
374     {
375         return redirect( request, getViewUrl( strView ) );
376     }
377 
378     /**
379      * Get a View URL
380      * @param strView The view name
381      * @return The URL
382      */
383     protected String getViewUrl( String strView )
384     {
385         UrlItem url = new UrlItem( getControllerJsp(  ) );
386         url.addParameter( MVCUtils.PARAMETER_VIEW, strView );
387 
388         return url.getUrl(  );
389     }
390 
391     /**
392      * Gets the view URL with the JSP path
393      * @param strView The view
394      * @return The URL
395      */
396     protected String getViewFullUrl( String strView )
397     {
398         return getControllerPath(  ) + getViewUrl( strView );
399     }
400 
401     /**
402      * Get Action URL
403      * @param strAction The view name
404      * @return The URL
405      */
406     protected String getActionUrl( String strAction )
407     {
408         UrlItem url = new UrlItem( getControllerPath(  ) + getControllerJsp(  ) );
409         url.addParameter( MVCUtils.PARAMETER_ACTION, strAction );
410 
411         return url.getUrl(  );
412     }
413 }