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.appcenter.modules.support.service;
35  
36  import javax.servlet.http.HttpServletRequest;
37  import javax.servlet.http.HttpSession;
38  
39  import fr.paris.lutece.plugins.asynchronousupload.service.AbstractAsynchronousUploadHandler;
40  import fr.paris.lutece.portal.service.i18n.I18nService;
41  import fr.paris.lutece.portal.service.spring.SpringContextService;
42  import fr.paris.lutece.portal.service.util.AppException;
43  import fr.paris.lutece.portal.service.util.AppPropertiesService;
44  import fr.paris.lutece.util.filesystem.UploadUtil;
45  
46  import java.util.ArrayList;
47  import java.util.Iterator;
48  import java.util.List;
49  import java.util.Locale;
50  import java.util.Map;
51  import java.util.concurrent.ConcurrentHashMap;
52  
53  import org.apache.commons.fileupload.FileItem;
54  import org.apache.commons.lang.StringUtils;
55  
56  public class SupportAsynchronousUploadHandler extends AbstractAsynchronousUploadHandler
57  {
58      private static final String PREFIX_ENTRY_ID = "upload_value_";
59      private static final String HANDLER_NAME = "supportAsynchronousUploadHandler";
60  
61      // Error messages
62      private static final String ERROR_MESSAGE_UNKNOWN_ERROR = "module.appcenter.support.error.unknownError";
63      private static final String ERROR_MESSAGE_MAX_FILE = "module.appcenter.support.error.uploading_file.max_files";
64      private static final String ERROR_MESSAGE_MAX_SIZE_FILE = "module.appcenter.support.error.uploading_file.file_max_size";
65      
66      private static final String BEAN_SUPPORT_ASYNCHRONOUS_UPLOAD_HANDLER = "appcenter.supportAsynchronousUploadHandler";
67  
68      // PROPERTIES
69      private static final String PROPERTY_MAX_FILE =  "appcenter.upload.file.max_number";
70      private static final String PROPERTY_MAX_FILE_SIZE = "module.appcenter.support.upload.file.max_size";
71      
72      private static final int MAX_FILE =  AppPropertiesService.getPropertyInt( PROPERTY_MAX_FILE , 10 );
73      private static final int MAX_FILE_SIZE =  AppPropertiesService.getPropertyInt( PROPERTY_MAX_FILE_SIZE , 5242880 );
74  
75      /** <sessionId,<fieldName,fileItems>> */
76      /** contains uploaded file items */
77      private static Map<String, Map<String, List<FileItem>>> _mapAsynchronousUpload = new ConcurrentHashMap<String, Map<String, List<FileItem>>>( );
78  
79      /**
80       * Get the handler
81       * 
82       * @return the handler
83       */
84      public static SupportAsynchronousUploadHandler getHandler( )
85      {
86          return SpringContextService.getBean( BEAN_SUPPORT_ASYNCHRONOUS_UPLOAD_HANDLER );
87      }
88  
89      /**
90       * {@inheritDoc}
91       */
92      @Override
93      public String canUploadFiles( HttpServletRequest request, String strFieldName, List<FileItem> listFileItemsToUpload, Locale locale )
94      {
95          if ( StringUtils.isNotBlank( strFieldName ) && ( strFieldName.length( ) > PREFIX_ENTRY_ID.length( ) ) )
96          {
97              initFileItemsList( request.getSession( ).getId( ), strFieldName );
98  
99              List<FileItem> list = getListUploadedFiles( strFieldName, request.getSession( ) );
100             
101             long size = 0;
102 
103             for ( FileItem fileItem : listFileItemsToUpload )
104             {
105                 if ( fileItem.getSize( ) > MAX_FILE_SIZE )
106                 {
107                     size = fileItem.getSize( );
108                     break;
109                 }
110             }
111 
112             if ( size > 0 )
113             {
114                 Object [ ] tabRequiredFields = { MAX_FILE_SIZE };
115 
116                 return I18nService.getLocalizedString( ERROR_MESSAGE_MAX_SIZE_FILE, tabRequiredFields, locale );
117             }
118 
119             if ( MAX_FILE <= list.size( ) )
120             {
121                 Object [ ] tabRequiredFields = { MAX_FILE };
122 
123                 return I18nService.getLocalizedString( ERROR_MESSAGE_MAX_FILE, tabRequiredFields, locale );
124             }
125 
126             return null;
127         }
128 
129         return I18nService.getLocalizedString( ERROR_MESSAGE_UNKNOWN_ERROR, locale );
130     }
131 
132     /**
133      * {@inheritDoc}
134      */
135     @Override
136     public List<FileItem> getListUploadedFiles( String strFieldName, HttpSession session )
137     {
138         if ( StringUtils.isBlank( strFieldName ) )
139         {
140             throw new AppException( "id field name is not provided for the current file upload" );
141         }
142 
143         initFileItemsList( session.getId( ), strFieldName );
144 
145         // find session-related files in the map
146         Map<String, List<FileItem>> mapFileItemsSession = _mapAsynchronousUpload.get( session.getId( ) );
147 
148         return mapFileItemsSession.get( strFieldName );
149     }
150 
151     /**
152      * {@inheritDoc}
153      */
154     @Override
155     public void addFileItemToUploadedFilesList( FileItem fileItem, String strFieldName, HttpServletRequest request )
156     {
157         // This is the name that will be displayed in the form. We keep
158         // the original name, but clean it to make it cross-platform.
159         String strFileName = UploadUtil.cleanFileName( fileItem.getName( ).trim( ) );
160 
161         initFileItemsList( request.getSession( ).getId( ), strFieldName );
162 
163         // Check if this file has not already been uploaded
164         List<FileItem> uploadedFiles = getListUploadedFiles( strFieldName, request.getSession( ) );
165 
166         if ( uploadedFiles != null )
167         {
168             boolean bNew = true;
169 
170             if ( !uploadedFiles.isEmpty( ) )
171             {
172                 Iterator<FileItem> iterUploadedFiles = uploadedFiles.iterator( );
173 
174                 while ( bNew && iterUploadedFiles.hasNext( ) )
175                 {
176                     FileItem uploadedFile = iterUploadedFiles.next( );
177                     String strUploadedFileName = UploadUtil.cleanFileName( uploadedFile.getName( ).trim( ) );
178                     // If we find a file with the same name and the same
179                     // length, we consider that the current file has
180                     // already been uploaded
181                     bNew = !( StringUtils.equals( strUploadedFileName, strFileName ) && ( uploadedFile.getSize( ) == fileItem.getSize( ) ) );
182                 }
183             }
184 
185             if ( bNew )
186             {
187                 uploadedFiles.add( fileItem );
188             }
189         }
190     }
191 
192     /**
193      * {@inheritDoc}
194      */
195     @Override
196     public void removeFileItem( String strFieldName, HttpSession session, int nIndex )
197     {
198         // Remove the file (this will also delete the file physically)
199         List<FileItem> uploadedFiles = getListUploadedFiles( strFieldName, session );
200 
201         if ( ( uploadedFiles != null ) && !uploadedFiles.isEmpty( ) && ( uploadedFiles.size( ) > nIndex ) )
202         {
203             // Remove the object from the Hashmap
204             FileItem fileItem = uploadedFiles.remove( nIndex );
205             fileItem.delete( );
206         }
207     }
208 
209     /**
210      * Removes all files associated to the session
211      * 
212      * @param strSessionId
213      *            the session id
214      */
215     public void removeSessionFiles( String strSessionId )
216     {
217         _mapAsynchronousUpload.remove( strSessionId );
218     }
219 
220     /**
221      * Build the field name from a given id entry i.e. : form_1
222      * 
223      * @param strIdEntry
224      *            the id entry
225      * @return the field name
226      */
227     public String buildFieldName( HttpServletRequest request )
228     {
229         initFileItemSessionMap( request.getSession( ).getId( ) );
230         
231         Map<String, List<FileItem>> mapFileItemsSession = _mapAsynchronousUpload.get( request.getSession( ).getId( ) );
232         
233         String strId = Integer.toString( mapFileItemsSession.size( ) );
234         
235         initFileItemsList( request.getSession( ).getId( ), PREFIX_ENTRY_ID + strId );
236         
237         return PREFIX_ENTRY_ID + strId;
238     }
239 
240     /**
241      * Init the list containing File Items
242      * 
243      * @param strSessionId
244      *            the session id
245      * @param strFieldName
246      *            the field name
247      */
248     private void initFileItemsList( String strSessionId, String strFieldName )
249     {
250         initFileItemSessionMap( strSessionId );
251 
252         // find session-related files in the map
253         Map<String, List<FileItem>> mapFileItemsSession = _mapAsynchronousUpload.get( strSessionId );
254 
255         List<FileItem> listFileItems = mapFileItemsSession.get( strFieldName );
256 
257         if ( listFileItems == null )
258         {
259             listFileItems = new ArrayList<FileItem>( );
260             mapFileItemsSession.put( strFieldName, listFileItems );
261         }
262     }
263 
264     /**
265      * Init the map
266      * 
267      * @param strSessionId
268      *            the session id
269      * @param strFieldName
270      *            the field name
271      */
272     private void initFileItemSessionMap( String strSessionId )
273     {
274         // find session-related files in the map
275         Map<String, List<FileItem>> mapFileItemsSession = _mapAsynchronousUpload.get( strSessionId );
276 
277         // create map if not exists
278         if ( mapFileItemsSession == null )
279         {
280             synchronized( this )
281             {
282                 // Ignore double check locking error : assignation and instanciation of objects are separated.
283                 mapFileItemsSession = _mapAsynchronousUpload.get( strSessionId );
284 
285                 if ( mapFileItemsSession == null )
286                 {
287                     mapFileItemsSession = new ConcurrentHashMap<String, List<FileItem>>( );
288                     _mapAsynchronousUpload.put( strSessionId, mapFileItemsSession );
289                 }
290             }
291         }
292 
293     }
294 
295     @Override
296     public String getHandlerName( )
297     {
298         return HANDLER_NAME;
299     }
300 }