View Javadoc
1   /*
2    * Copyright (c) 2002-2018, 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.plugins.stock.modules.billetterie.web;
35  
36  import fr.paris.lutece.plugins.stock.commons.dao.PaginationProperties;
37  import fr.paris.lutece.plugins.stock.commons.dao.PaginationPropertiesImpl;
38  import fr.paris.lutece.plugins.stock.commons.exception.BusinessException;
39  import fr.paris.lutece.plugins.stock.commons.exception.FunctionnalException;
40  import fr.paris.lutece.plugins.stock.commons.exception.TechnicalException;
41  import fr.paris.lutece.plugins.stock.commons.exception.ValidationException;
42  import fr.paris.lutece.plugins.stock.modules.tickets.utils.constants.TicketsConstants;
43  import fr.paris.lutece.portal.service.i18n.I18nService;
44  import fr.paris.lutece.portal.service.message.SiteMessage;
45  import fr.paris.lutece.portal.service.message.SiteMessageException;
46  import fr.paris.lutece.portal.service.message.SiteMessageService;
47  import fr.paris.lutece.portal.service.security.LuteceUser;
48  import fr.paris.lutece.portal.service.security.SecurityService;
49  import fr.paris.lutece.portal.service.security.UserNotSignedException;
50  import fr.paris.lutece.portal.service.template.AppTemplateService;
51  import fr.paris.lutece.portal.service.util.AppPropertiesService;
52  import fr.paris.lutece.util.beanvalidation.BeanValidationUtil;
53  import fr.paris.lutece.util.html.HtmlTemplate;
54  import fr.paris.lutece.util.html.Paginator;
55  
56  import org.apache.commons.beanutils.BeanUtils;
57  import org.apache.commons.lang.StringUtils;
58  import org.apache.log4j.Logger;
59  
60  import java.lang.reflect.InvocationTargetException;
61  import java.util.ArrayList;
62  import java.util.HashMap;
63  import java.util.List;
64  import java.util.Map;
65  import java.util.Set;
66  
67  import javax.servlet.http.HttpServletRequest;
68  import javax.validation.ConstraintViolation;
69  
70  /**
71   * Abstract class for jsp bean
72   *
73   * @author abataille
74   */
75  public abstract class AbstractXPageApp
76  {
77      //Properties
78      private static final String PROPERTY_NOT_AUTHORIZED = "module.stock.billetterie.messages.notAuthorized";
79      public static final String PARAMETER_NB_ITEMS_PER_PAGE = "items_per_page";
80      public static final String DEFAULT_RESULTS_PER_PAGE = "10";
81      public static final String DEFAULT_PAGE_INDEX = "1";
82      public static final String PROPERTY_RESULTS_PER_PAGE = "search.nb.docs.per.page";
83      private static final String AUTHENTIFICATION_ERROR_MESSAGE = "Impossible de détecter une authentification.";
84      private static final String POPULATE_ERROR_MESSAGE = "Erreur lors de la recuperation des donnees du formulaire.";
85      private static final String ERROR_MESSAGE_KEY = "module.stock.billetterie.validation.error";
86      private static final String ERROR_TEMPLATE = "admin/plugins/stock/modules/billetterie/error.html";
87      private static final String FIELD_MESSAGE_PREFIX = "module.stock.billetterie.field.";
88      private static final String MARK_MESSAGE_LIST = "messageList";
89      private static final Logger LOGGER = Logger.getLogger( AbstractXPageApp.class );
90  
91      /**
92       * Populate a bean using parameters in http request
93       *
94       * @param bean
95       *            bean to populate
96       * @param request
97       *            http request
98       */
99      protected static void populate( Object bean, HttpServletRequest request )
100     {
101         try
102         {
103             BeanUtils.populate( bean, request.getParameterMap( ) );
104         }
105         catch( IllegalAccessException e )
106         {
107             LOGGER.error( POPULATE_ERROR_MESSAGE, e );
108         }
109         catch( InvocationTargetException e )
110         {
111             LOGGER.error( POPULATE_ERROR_MESSAGE, e );
112         }
113     }
114 
115     /**
116      * Validate a bean using jsr 303 specs.
117      *
118      * @param <T>
119      *            the generic type
120      * @param bean
121      *            to validate
122      * @throws ValidationException
123      *             exception containing informations about errors and the bean
124      */
125     protected <T> void validate( T bean ) throws ValidationException
126     {
127         Set<ConstraintViolation<T>> constraintViolations = BeanValidationUtil.validate( bean );
128 
129         if ( constraintViolations.size( ) > 0 )
130         {
131             ValidationException ve = new ValidationException( bean );
132 
133             for ( ConstraintViolation<T> constraintViolation : constraintViolations )
134             {
135                 ve.addConstraintViolation( constraintViolation );
136             }
137 
138             throw ve;
139         }
140     }
141 
142     /**
143      * Return authified user and throw technical exception if no user auth found.
144      *
145      * @param request
146      *            http request
147      * @return user lutece
148      * @throws TechnicalException
149      *             the technical exception
150      */
151     protected LuteceUser getUser( HttpServletRequest request ) throws TechnicalException
152     {
153         // CAS
154         try
155         {
156             return SecurityService.getInstance( ).getRemoteUser( request );
157         }
158         catch( UserNotSignedException e )
159         {
160             throw new TechnicalException( AUTHENTIFICATION_ERROR_MESSAGE, e );
161         }
162 
163         // DEBUT BOUCHON
164         // LuteceUser user = new BasicLuteceUser("abataille@sopragroup.com",
165         // new MultiLuteceAuthentication());
166         // user.setUserInfo(LuteceUser.NAME_GIVEN, "Alexis");
167         // user.setUserInfo(LuteceUser.NAME_FAMILY, "Bataille");
168         // user.setUserInfo(LuteceUser.HOME_INFO_ONLINE_EMAIL,
169         // "abataille@sopragroup.com");
170         // return user;
171         // FIN BOUCHON
172     }
173 
174     /**
175      * Return localized message.
176      *
177      * @param key
178      *            i18n key
179      * @param request
180      *            the request
181      * @return localized message
182      */
183     protected String getMessage( String key, HttpServletRequest request )
184     {
185         return I18nService.getLocalizedString( key, request.getLocale( ) );
186     }
187 
188     /**
189      * Return localized message with args.
190      *
191      * @param key
192      *            i18n key
193      * @param request
194      *            the request
195      * @param args
196      *            args
197      * @return localized message
198      */
199     protected String getMessage( String key, HttpServletRequest request, String... args )
200     {
201         return I18nService.getLocalizedString( key, args, request.getLocale( ) );
202     }
203 
204     /**
205      * Return html code for error message.
206      *
207      * @param e
208      *            the e
209      * @param request
210      *            the request
211      * @return html
212      */
213     protected String getHtmlError( FunctionnalException e, HttpServletRequest request )
214     {
215         Map<String, Object> model = new HashMap<String, Object>( );
216         List<String> messageList = new ArrayList<String>( );
217 
218         try
219         {
220             throw e;
221         }
222 
223         // Validation error
224         catch( ValidationException ve )
225         {
226             String typeName = ve.getBean( ).getClass( ).getSimpleName( );
227 
228             // Add a validation error message using value, field name and
229             // provided
230             // message
231             for ( ConstraintViolation<?> constraintViolation : ve.getConstraintViolationList( ) )
232             {
233                 String fieldName = getMessage( FIELD_MESSAGE_PREFIX + typeName + "." + constraintViolation.getPropertyPath( ), request );
234                 messageList.add( getMessage( ERROR_MESSAGE_KEY, request, String.valueOf( constraintViolation.getInvalidValue( ) ), fieldName,
235                         constraintViolation.getMessage( ) ) );
236             }
237         }
238 
239         // Business error
240         catch( BusinessException be )
241         {
242             messageList.add( getMessage( be.getCode( ), request, be.getArguments( ) ) );
243         }
244 
245         model.put( MARK_MESSAGE_LIST, messageList );
246 
247         HtmlTemplate template = AppTemplateService.getTemplate( ERROR_TEMPLATE, request.getLocale( ), model );
248 
249         return template.getHtml( );
250     }
251 
252     /**
253      * Manage functionnal exception.
254      *
255      * @param request
256      *            the request
257      * @param e
258      *            the e
259      * @param targetUrl
260      *            the target url
261      * @return the string
262      */
263     protected String manageFunctionnalException( HttpServletRequest request, FunctionnalException e, String targetUrl )
264     {
265         request.getSession( ).setAttribute( TicketsConstants.PARAMETER_ERROR, e );
266 
267         return targetUrl;
268     }
269 
270     /**
271      * Get validation error from session and remove from it
272      *
273      * @param request
274      *            http request
275      * @return validation exception
276      */
277     protected FunctionnalException getErrorOnce( HttpServletRequest request )
278     {
279         FunctionnalException fe = (FunctionnalException) request.getSession( ).getAttribute( TicketsConstants.PARAMETER_ERROR );
280 
281         if ( fe != null )
282         {
283             request.getSession( ).removeAttribute( TicketsConstants.PARAMETER_ERROR );
284         }
285 
286         return fe;
287     }
288 
289 
290     public static LuteceUser getLuteceUserAuthentication(HttpServletRequest request ) throws SiteMessageException
291     {
292 
293         LuteceUser user = null;
294 
295         if ( SecurityService.isAuthenticationEnable( ) )
296         { // myLutece not installed or disabled
297             user = SecurityService.getInstance( ).getRegisteredUser( request );
298 
299             if ( user == null ) // user is not logged
300             {
301                 SiteMessageService.setMessage( request, PROPERTY_NOT_AUTHORIZED, SiteMessage.TYPE_STOP );
302             }
303         }
304         else
305         {
306             SiteMessageService.setMessage( request, PROPERTY_NOT_AUTHORIZED, SiteMessage.TYPE_STOP );
307         }
308 
309         return user;
310     }
311 
312     /**
313      * Return a bean for pagination in service/dao using parameter in http request
314      *
315      * @param request
316      *            http request
317      * @return paginator the populate paginator
318      */
319     protected static PaginationProperties getPaginationProperties( HttpServletRequest request )
320     {
321         String strPageIndex = Paginator.getPageIndex( request, Paginator.PARAMETER_PAGE_INDEX, "1" );
322         int nCurrentPageIndex = 1;
323 
324         if ( StringUtils.isNotEmpty( strPageIndex ) )
325         {
326             nCurrentPageIndex = Integer.valueOf( strPageIndex );
327         }
328 
329         String strNbItemPerPage = request.getParameter( PARAMETER_NB_ITEMS_PER_PAGE );
330         String strDefaultNbItemPerPage = AppPropertiesService.getProperty( PROPERTY_RESULTS_PER_PAGE, DEFAULT_RESULTS_PER_PAGE );
331         strNbItemPerPage = ( strNbItemPerPage != null ) ? strNbItemPerPage : strDefaultNbItemPerPage;
332 
333         int nItemsPerPage = Integer.valueOf( strNbItemPerPage );
334 
335         return new PaginationPropertiesImpl( ( nCurrentPageIndex - 1 ) * nItemsPerPage, nItemsPerPage );
336     }
337 }