View Javadoc
1   /*
2    * Copyright (c) 2002-2017, 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.deployment.uploadhandler;
35  
36  import java.util.ArrayList;
37  import java.util.Iterator;
38  import java.util.List;
39  import java.util.Locale;
40  import java.util.Map;
41  import java.util.concurrent.ConcurrentHashMap;
42  
43  import javax.servlet.http.HttpServletRequest;
44  import javax.servlet.http.HttpSession;
45  
46  import org.apache.commons.fileupload.FileItem;
47  import org.apache.commons.lang.StringUtils;
48  
49  import fr.paris.lutece.plugins.asynchronousupload.service.AbstractAsynchronousUploadHandler;
50  import fr.paris.lutece.portal.service.i18n.I18nService;
51  import fr.paris.lutece.portal.service.util.AppException;
52  import fr.paris.lutece.portal.service.util.AppPropertiesService;
53  import fr.paris.lutece.util.filesystem.UploadUtil;
54  
55  public class DeploymentUploadHandler extends AbstractAsynchronousUploadHandler
56  {
57      public static final String BEAN_NAME = "deployment.deploymentUploadHandler";
58      private static final int DEFAULT_MAX_FILE_SIZE = 2097152;
59      private static final String HANDLER_NAME = "deploymentUploadHandler";
60  
61      // Error messages
62      private static final String ERROR_MESSAGE_MULTIPLE_UPLOAD = "deployment.upload.message.multipleUpload";
63      private static final String ERROR_MESSAGE_UPLOAD_MAX_SIZE = "deployment.upload.message.uploadMaxSize";
64      private static final String ERROR_MESSAGE_NOT_SQL_FILE = "deployment.upload.message.uploadNotSqlFile";
65  
66      // PROPERTY
67      private static final String PROPERTY_UPLOAD_MAX_SIZE = "deployment.uploadMaxFileSize";
68  
69      /* contains uploaded file items */
70      private static Map<String, Map<String, List<FileItem>>> _mapAsynchronousUpload = new ConcurrentHashMap<String, Map<String, List<FileItem>>>( );
71  
72      @Override
73      public void addFileItemToUploadedFilesList( FileItem fileItem, String strFieldName, HttpServletRequest request )
74      {
75          // This is the name that will be displayed in the form. We keep
76          // the original name, but clean it to make it cross-platform.
77          String strFileName = UploadUtil.cleanFileName( fileItem.getName( ).trim( ) );
78  
79          initMap( request.getSession( ).getId( ), strFieldName );
80  
81          // Check if this file has not already been uploaded
82          List<FileItem> uploadedFiles = getListUploadedFiles( strFieldName, request.getSession( ) );
83  
84          if ( uploadedFiles != null )
85          {
86              boolean bNew = true;
87  
88              if ( !uploadedFiles.isEmpty( ) )
89              {
90                  Iterator<FileItem> iterUploadedFiles = uploadedFiles.iterator( );
91  
92                  while ( bNew && iterUploadedFiles.hasNext( ) )
93                  {
94                      FileItem uploadedFile = iterUploadedFiles.next( );
95                      String strUploadedFileName = UploadUtil.cleanFileName( uploadedFile.getName( ).trim( ) );
96                      // If we find a file with the same name and the same
97                      // length, we consider that the current file has
98                      // already been uploaded
99                      bNew = !( StringUtils.equals( strUploadedFileName, strFileName ) && ( uploadedFile.getSize( ) == fileItem.getSize( ) ) );
100                 }
101             }
102 
103             if ( bNew )
104             {
105                 uploadedFiles.add( fileItem );
106             }
107         }
108     }
109 
110     @Override
111     public String canUploadFiles( HttpServletRequest request, String strFieldName, List<FileItem> listFileItemsToUpload, Locale locale )
112     {
113         Long nMaxSize = AppPropertiesService.getPropertyLong( PROPERTY_UPLOAD_MAX_SIZE, DEFAULT_MAX_FILE_SIZE );
114 
115         // Check if this file has not already been uploaded
116         List<FileItem> uploadedFiles = getListUploadedFiles( strFieldName, request.getSession( ) );
117 
118         if ( uploadedFiles != null && uploadedFiles.size( ) >= 1 )
119         {
120             return I18nService.getLocalizedString( ERROR_MESSAGE_MULTIPLE_UPLOAD, request.getLocale( ) );
121         }
122 
123         for ( FileItem fileItem : listFileItemsToUpload )
124         {
125 
126             if ( fileItem.getName( ) != null && !fileItem.getName( ).endsWith( ".sql" ) )
127             {
128                 return I18nService.getLocalizedString( ERROR_MESSAGE_NOT_SQL_FILE, request.getLocale( ) );
129             }
130 
131             if ( fileItem.getSize( ) > nMaxSize )
132             {
133                 return I18nService.getLocalizedString( ERROR_MESSAGE_UPLOAD_MAX_SIZE, request.getLocale( ) );
134             }
135 
136         }
137 
138         return null;
139 
140     }
141 
142     @Override
143     public String getHandlerName( )
144     {
145         return HANDLER_NAME;
146     }
147 
148     @Override
149     public List<FileItem> getListUploadedFiles( String strFieldName, HttpSession session )
150     {
151         if ( StringUtils.isBlank( strFieldName ) )
152         {
153             throw new AppException( "id field name is not provided for the current file upload" );
154         }
155 
156         initMap( session.getId( ), strFieldName );
157 
158         // find session-related files in the map
159         Map<String, List<FileItem>> mapFileItemsSession = _mapAsynchronousUpload.get( session.getId( ) );
160 
161         return mapFileItemsSession.get( strFieldName );
162     }
163 
164     @Override
165     public void removeFileItem( String strFieldName, HttpSession session, int nIndex )
166     {
167         // Remove the file (this will also delete the file physically)
168         List<FileItem> uploadedFiles = getListUploadedFiles( strFieldName, session );
169 
170         if ( ( uploadedFiles != null ) && !uploadedFiles.isEmpty( ) && ( uploadedFiles.size( ) > nIndex ) )
171         {
172             // Remove the object from the Hashmap
173             FileItem fileItem = uploadedFiles.remove( nIndex );
174             fileItem.delete( );
175         }
176     }
177 
178     /**
179      * Init the map Copy paste from genericAttribute AbstractGenAttUploadHandler from
180      * http://wiki.lutece.paris.fr/lutece/jsp/site/Portal.jsp?page=wiki&page_name=asynchronous_upload&view=page
181      * 
182      * @param strSessionId
183      *            the session id
184      * @param strFieldName
185      *            the field name
186      */
187     private void initMap( String strSessionId, String strFieldName )
188     {
189         // find session-related files in the map
190         Map<String, List<FileItem>> mapFileItemsSession = _mapAsynchronousUpload.get( strSessionId );
191 
192         // create map if not exists
193         if ( mapFileItemsSession == null )
194         {
195             synchronized( this )
196             {
197                 // Ignore double check locking error : assignation and instanciation of objects are separated.
198                 mapFileItemsSession = _mapAsynchronousUpload.get( strSessionId );
199 
200                 if ( mapFileItemsSession == null )
201                 {
202                     mapFileItemsSession = new ConcurrentHashMap<String, List<FileItem>>( );
203                     _mapAsynchronousUpload.put( strSessionId, mapFileItemsSession );
204                 }
205             }
206         }
207 
208         List<FileItem> listFileItems = mapFileItemsSession.get( strFieldName );
209 
210         if ( listFileItems == null )
211         {
212             listFileItems = new ArrayList<FileItem>( );
213             mapFileItemsSession.put( strFieldName, listFileItems );
214         }
215     }
216 
217     /**
218      * Removes all files associated to the session
219      * 
220      * @param strSessionId
221      *            the session id
222      */
223     public void removeSessionFiles( String strSessionId )
224     {
225         _mapAsynchronousUpload.remove( strSessionId );
226     }
227 }