View Javadoc
1   /*
2    * Copyright (c) 2002-2022, City of 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.forms.export.pdf;
35  
36  import java.io.File;
37  import java.io.IOException;
38  import java.io.OutputStream;
39  import java.nio.file.Files;
40  import java.nio.file.Path;
41  import java.nio.file.Paths;
42  import java.util.ArrayList;
43  import java.util.HashMap;
44  import java.util.List;
45  import java.util.Map;
46  
47  import fr.paris.lutece.plugins.forms.business.FormResponse;
48  import fr.paris.lutece.plugins.forms.business.FormResponseHome;
49  import fr.paris.lutece.plugins.forms.business.MultiviewConfig;
50  import fr.paris.lutece.plugins.forms.business.form.FormItemSortConfig;
51  import fr.paris.lutece.plugins.forms.business.form.FormResponseItem;
52  import fr.paris.lutece.plugins.forms.business.form.column.IFormColumn;
53  import fr.paris.lutece.plugins.forms.business.form.filter.FormFilter;
54  import fr.paris.lutece.plugins.forms.business.form.panel.FormPanel;
55  import fr.paris.lutece.plugins.forms.service.MultiviewFormService;
56  import fr.paris.lutece.portal.service.util.AppLogService;
57  import fr.paris.lutece.portal.service.util.AppPropertiesService;
58  import fr.paris.lutece.util.file.FileUtil;
59  import fr.paris.lutece.util.html.HtmlTemplate;
60  
61  public class PdfFileGenerator extends AbstractPdfFileGenerator
62  {
63      private static final boolean ZIP_EXPORT = Boolean.parseBoolean( AppPropertiesService.getProperty( "forms.export.pdf.zip", "false" ) );
64      
65      private boolean _hasMultipleFiles = false;
66      
67      protected PdfFileGenerator( String formName, FormPanel formPanel, List<IFormColumn> listFormColumn, List<FormFilter> listFormFilter,
68              FormItemSortConfig sortConfig, String fileDescription )
69      {
70          super( FileUtil.normalizeFileName( formName ), formName, formPanel, listFormColumn, listFormFilter, sortConfig, fileDescription );
71      }
72  
73      @Override
74      public Path generateFile( ) throws IOException
75      {
76          Path directoryFile = Paths.get( TMP_DIR, _fileName );
77          if ( !directoryFile.toFile( ).exists( ) )
78          {
79              directoryFile.toFile( ).mkdir( );
80          }
81          writeExportFile( directoryFile );
82          if ( hasMultipleFiles( ) )
83          {
84              return directoryFile;
85          }
86          File [ ] files = directoryFile.toFile( ).listFiles( ( File f ) -> f.getName( ).endsWith( EXTENSION_PDF ) );
87          return files [0].toPath( );
88      }
89  
90      @Override
91      public String getDescription( )
92      {
93          return _fileDescription;
94      }
95  
96      @Override
97      public String getFileName( )
98      {
99          return _fileName + ( hasMultipleFiles( ) || isZippable( ) ? FileUtil.EXTENSION_ZIP : EXTENSION_PDF );
100     }
101 
102     @Override
103     public String getMimeType( )
104     {
105         return hasMultipleFiles( ) || isZippable( ) ? FileUtil.CONSTANT_MIME_TYPE_ZIP : CONSTANT_MIME_TYPE_PDF;
106     }
107 
108     @Override
109     public boolean isZippable( )
110     {
111         return ZIP_EXPORT;
112     }
113 
114     @Override
115     public boolean hasMultipleFiles( )
116     {
117         return _hasMultipleFiles;
118     }
119 
120     private void writeExportFile( Path directoryFile ) throws IOException
121     {
122         List<FormResponseItem> listFormResponseItems = MultiviewFormService.getInstance( ).searchAllListFormResponseItem( _formPanel, _listFormColumn,
123                 _listFormFilter, _sortConfig );
124         _hasMultipleFiles = listFormResponseItems.size( ) > 1;
125         
126         int intNumberOfFormResponsesPerPdf = MultiviewConfig.getInstance().getNumberOfFormResponsesPerPdf();
127         if (intNumberOfFormResponsesPerPdf > 1)
128         {
129         	generateMultipleFormResponsesPerFile(directoryFile, listFormResponseItems, intNumberOfFormResponsesPerPdf);
130         }
131         else
132         {
133         	generateOneFormResponsePerFile(directoryFile, listFormResponseItems);
134         }
135     }
136     
137     private void generateMultipleFormResponsesPerFile(Path directoryFile, List<FormResponseItem> listFormResponseItems, int intNumberOfFormResponsesPerPdf) throws IOException
138     {
139     	for (int intStartIndex = 0; intStartIndex < listFormResponseItems.size(); intStartIndex += intNumberOfFormResponsesPerPdf)
140     	{
141     		try {
142 				int intEndIndexExcluded = Math.min(intStartIndex + intNumberOfFormResponsesPerPdf, listFormResponseItems.size());
143 				List<FormResponseItem> subListFormResponseItems = listFormResponseItems.subList(intStartIndex, intEndIndexExcluded);
144 				List<FormResponse> subListFormResponse = new ArrayList<>();
145 				
146 				for(FormResponseItem responseItem : subListFormResponseItems)
147 				{
148 					FormResponse formResponse = FormResponseHome.findByPrimaryKey( responseItem.getIdFormResponse( ) );
149 					subListFormResponse.add(formResponse);
150 				}
151 				
152 				Map<String, Object> model = new HashMap<>( );
153 				HtmlTemplate htmltemplate = generateHtmlMultipleFormResponsesFromTemplate(model, subListFormResponse);
154 				
155 				String generatedName = generateMultiFormResponsesFileName(subListFormResponse, intStartIndex + 1, intEndIndexExcluded);
156 				generatePdfFile(directoryFile, htmltemplate, generatedName);
157 			} catch (IOException e) {
158 				AppLogService.error( LOG_ERROR_PDF_EXPORT_GENERATION, e );
159 				throw e;
160 			} catch (Exception e) {
161 				AppLogService.error( LOG_ERROR_PDF_EXPORT_GENERATION, e );
162 			}
163     	}
164     }
165     
166     private void generateOneFormResponsePerFile(Path directoryFile, List<FormResponseItem> listFormResponseItems) throws IOException
167     {
168     	for ( FormResponseItem responseItem : listFormResponseItems )
169         {
170         	try {
171 				Map<String, Object> model = new HashMap<>( );
172 				
173 				FormResponse formResponse = FormResponseHome.findByPrimaryKey( responseItem.getIdFormResponse( ) );
174 				HtmlTemplate htmltemplate = generateHtmlSingleFormResponsesFromTemplate(model, formResponse);
175 				
176 				String generatedName = generateFileName(formResponse);
177 				generatePdfFile(directoryFile, htmltemplate, generatedName);
178 			} catch (IOException e) {
179 				AppLogService.error( LOG_ERROR_PDF_EXPORT_GENERATION, e );
180 				throw e;
181 			} catch (Exception e) {
182 				AppLogService.error( LOG_ERROR_PDF_EXPORT_GENERATION, e );
183 			}
184         }
185     }
186 
187 }