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.plugins.directory.modules.pdfproducerarchive.utils;
35  
36  import fr.paris.lutece.plugins.directory.business.Directory;
37  import fr.paris.lutece.plugins.directory.business.EntryFilter;
38  import fr.paris.lutece.plugins.directory.business.IEntry;
39  import fr.paris.lutece.plugins.directory.business.PhysicalFile;
40  import fr.paris.lutece.plugins.directory.business.PhysicalFileHome;
41  import fr.paris.lutece.plugins.directory.business.Record;
42  import fr.paris.lutece.plugins.directory.business.RecordField;
43  import fr.paris.lutece.plugins.directory.business.RecordHome;
44  import fr.paris.lutece.plugins.directory.modules.pdfproducer.utils.PDFUtils;
45  import fr.paris.lutece.plugins.directory.service.DirectoryPlugin;
46  import fr.paris.lutece.plugins.directory.service.DirectoryResourceIdService;
47  import fr.paris.lutece.plugins.directory.utils.DirectoryUtils;
48  import fr.paris.lutece.portal.business.user.AdminUser;
49  import fr.paris.lutece.portal.service.admin.AccessDeniedException;
50  import fr.paris.lutece.portal.service.admin.AdminUserService;
51  import fr.paris.lutece.portal.service.plugin.Plugin;
52  import fr.paris.lutece.portal.service.plugin.PluginService;
53  import fr.paris.lutece.portal.service.rbac.RBACService;
54  import fr.paris.lutece.portal.service.util.AppLogService;
55  import fr.paris.lutece.portal.service.util.AppPathService;
56  import fr.paris.lutece.portal.service.util.AppPropertiesService;
57  
58  import java.io.File;
59  import java.io.FileNotFoundException;
60  import java.io.FileOutputStream;
61  import java.io.IOException;
62  import java.util.List;
63  
64  import javax.servlet.http.HttpServletRequest;
65  
66  import org.apache.commons.io.IOUtils;
67  import org.apache.commons.lang.StringUtils;
68  
69  
70  /**
71   * FilesUtils
72   *
73   */
74  public final class FilesUtils
75  {
76      private static final String PROPERTY_PATH_FILES_GENERATED = "directory.zipbasket.root.path.repository.filesgenerated";
77      private static final String MESSAGE_DELETE_ERROR = "Error deleting file or directory";
78      private static final String MESSAGE_CREATE_ERROR = "Error creating directory";
79      private static final int MAX_LIMIT_NAME_DIRECTORY = 50;
80  
81      /**
82       * Constructor
83       */
84      private FilesUtils(  )
85      {
86      }
87  
88      /**
89       * method to clean a specific repository
90       * @param strTempDirectory name of repository
91       */
92      public static void cleanTemporyZipDirectory( String strTempDirectory )
93      {
94          File file = new File( strTempDirectory );
95  
96          if ( file.isDirectory(  ) )
97          {
98              File[] entries = file.listFiles(  );
99              int sz = entries.length;
100 
101             for ( int j = 0; j < sz; j++ )
102             {
103                 cleanTemporyZipDirectory( entries[j].getPath(  ) );
104             }
105 
106             if ( !file.delete(  ) )
107             {
108                 AppLogService.error( MESSAGE_DELETE_ERROR );
109             }
110 
111             file.deleteOnExit(  );
112         }
113 
114         if ( file.isFile(  ) )
115         {
116             if ( !file.delete(  ) )
117             {
118                 AppLogService.error( MESSAGE_DELETE_ERROR );
119             }
120         }
121     }
122 
123     /**
124      * method to create a specific repository
125      * @param strPath repository path
126      */
127     public static void createTemporyZipDirectory( String strPath )
128     {
129         File file = new File( strPath );
130 
131         if ( !file.isDirectory(  ) )
132         {
133             if ( !file.mkdirs(  ) )
134             {
135                 AppLogService.error( MESSAGE_CREATE_ERROR );
136             }
137         }
138     }
139 
140     /**
141      * Thie method get all recorded files
142      * @param request request
143      * @param strTempDirectoryExtract the temporary directory for extraction
144      * @param listIdEntryConfig config list of id entry
145      * @param nIdRecord the id record
146      */
147     @Deprecated
148     public static void getAllFilesRecorded( HttpServletRequest request, String strTempDirectoryExtract,
149             List<Integer> listIdEntryConfig, int nIdRecord )
150     {
151         getAllFilesRecorded( AdminUserService.getAdminUser( request ), strTempDirectoryExtract, listIdEntryConfig,
152                 nIdRecord );
153     }
154 
155     /**
156      * Thie method get all recorded files
157      * @param adminUser The adminUser
158      * @param locale The locale
159      * @param strTempDirectoryExtract the temporary directory for extraction
160      * @param listIdEntryConfig config list of id entry
161      * @param nIdRecord the id record
162      */
163     public static void getAllFilesRecorded( AdminUser adminUser, String strTempDirectoryExtract,
164             List<Integer> listIdEntryConfig, int nIdRecord )
165     {
166         Plugin plugin = PluginService.getPlugin( DirectoryPlugin.PLUGIN_NAME );
167         EntryFilter filter;
168 
169         Record record = RecordHome.findByPrimaryKey( nIdRecord, plugin );
170 
171         if ( ( record == null ) ||
172                 !RBACService.isAuthorized( Directory.RESOURCE_TYPE,
173                     Integer.toString( record.getDirectory(  ).getIdDirectory(  ) ),
174                     DirectoryResourceIdService.PERMISSION_VISUALISATION_RECORD, adminUser ) )
175         {
176             try
177             {
178                 throw new AccessDeniedException(  );
179             }
180             catch ( AccessDeniedException e )
181             {
182                 AppLogService.error( e );
183             }
184         }
185 
186         filter = new EntryFilter(  );
187         filter.setIdDirectory( record.getDirectory(  ).getIdDirectory(  ) );
188         filter.setIsGroup( EntryFilter.FILTER_TRUE );
189 
190         List<IEntry> listEntry = DirectoryUtils.getFormEntries( record.getDirectory(  ).getIdDirectory(  ), plugin,
191                 adminUser );
192 
193         for ( IEntry entry : listEntry )
194         {
195             if ( entry.getEntryType(  ).getGroup(  ) && ( entry.getChildren(  ) != null ) )
196             {
197                 for ( IEntry child : entry.getChildren(  ) )
198                 {
199                     if ( ( listIdEntryConfig.isEmpty(  ) ||
200                             listIdEntryConfig.contains( Integer.valueOf( child.getIdEntry(  ) ) ) ) )
201                     {
202                         doExtractFiles( strTempDirectoryExtract, plugin, nIdRecord, listEntry, child );
203                     }
204                 }
205             }
206             else
207             {
208                 if ( ( listIdEntryConfig.isEmpty(  ) ||
209                         listIdEntryConfig.contains( Integer.valueOf( entry.getIdEntry(  ) ) ) ) )
210                 {
211                     doExtractFiles( strTempDirectoryExtract, plugin, nIdRecord, listEntry, entry );
212                 }
213             }
214         }
215     }
216 
217     /**
218      * Thie method extracts the file to temp directory
219      * @param strTempDirectoryExtract temp directory
220      * @param plugin plugin
221      * @param nIdRecord id record
222      * @param listEntry list of entry
223      * @param entry entry
224      */
225     private static void doExtractFiles( String strTempDirectoryExtract, Plugin plugin, int nIdRecord,
226         List<IEntry> listEntry, IEntry entry )
227     {
228         for ( RecordField recordField : DirectoryUtils.getMapIdEntryListRecordField( listEntry, nIdRecord, plugin )
229                                                       .get( String.valueOf( entry.getIdEntry(  ) ) ) )
230         {
231             String strTempPathExtract = strTempDirectoryExtract.concat( File.separator );
232             if ( StringUtils.isNotBlank( entry.getTitle(  ) ) )
233             {
234             	strTempPathExtract = strTempPathExtract.concat( limitLengthName( PDFUtils.doPurgeNameFile( entry.getTitle(  ) ) ) );
235             }
236 
237             if ( recordField.getFile(  ) != null )
238             {
239                 createTemporyZipDirectory( strTempPathExtract );
240                 doExtracFile( plugin, recordField, strTempPathExtract );
241             }
242 
243             if ( entry instanceof fr.paris.lutece.plugins.directory.business.EntryTypeDownloadUrl &&
244                     StringUtils.isNotBlank( recordField.getValue(  ) ) )
245             {
246                 createTemporyZipDirectory( strTempPathExtract );
247                 doDownloadUrl( recordField.getValue(  ), strTempPathExtract );
248             }
249         }
250     }
251 
252     /**
253      * This method extract a specific file
254      * @param plugin plugin
255      * @param recordField recordField
256      * @param strTempDirectoryExtract the temporary directory for extraction
257      */
258     private static void doExtracFile( Plugin plugin, RecordField recordField, String strTempDirectoryExtract )
259     {
260         FileOutputStream out = null;
261 
262         try
263         {
264             out = new FileOutputStream( strTempDirectoryExtract + File.separator +
265                     recordField.getFile(  ).getTitle(  ) );
266 
267             if ( recordField.getFile(  ) != null )
268             {
269                 PhysicalFile physicalFile = PhysicalFileHome.findByPrimaryKey( recordField.getFile(  ).getPhysicalFile(  )
270                                                                                           .getIdPhysicalFile(  ), plugin );
271 
272                 if ( ( physicalFile != null ) && ( physicalFile.getValue(  ) != null ) )
273                 {
274                     out.write( physicalFile.getValue(  ) );
275                 }
276             }
277 
278             out.close(  );
279         }
280         catch ( FileNotFoundException e )
281         {
282             AppLogService.error( e );
283         }
284         catch ( IOException e )
285         {
286             AppLogService.error( e );
287         }
288         finally
289         {
290             IOUtils.closeQuietly( out );
291         }
292     }
293 
294     /**
295      * Download the file
296      * @param strUrl url to download
297      * @param strTempDirectoryExtract the file path
298      */
299     private static void doDownloadUrl( String strUrl, String strTempDirectoryExtract )
300     {
301         String strFilePath = strTempDirectoryExtract + File.separator + DirectoryUtils.getFileName( strUrl );
302         DirectoryUtils.doDownloadFile( strUrl, strFilePath );
303     }
304 
305     /**
306      * build path name to generate files
307      * @param nIdAdminUser id admin user
308      * @param nIdDirectory id directory
309      * @return strPathBasket
310      */
311     public static String builNamePathBasket( int nIdAdminUser, int nIdDirectory )
312     {
313         String strRootPathFilesGenerate = AppPathService.getAbsolutePathFromRelativePath( AppPropertiesService.getProperty( 
314                     PROPERTY_PATH_FILES_GENERATED ) );
315         String strPathBasket = strRootPathFilesGenerate + Integer.toString( nIdAdminUser ) + "_" +
316             Integer.toString( nIdDirectory );
317 
318         return strPathBasket;
319     }
320     
321     /**
322      * Method to limit the name length by 50 caracters
323      * @param strPathName name of directory
324      * @return the new limited name
325      */
326     private static String limitLengthName( String strPathName )
327     {
328     	return StringUtils.substring( strPathName, 0, MAX_LIMIT_NAME_DIRECTORY );
329     }
330 }