View Javadoc
1   /*
2    * Copyright (c) 2002-2015, 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.exportuserpreferences.utils;
35  
36  import au.com.bytecode.opencsv.CSVWriter;
37  
38  import fr.paris.lutece.plugins.exportuserpreferences.business.KeyHome;
39  import fr.paris.lutece.portal.service.i18n.I18nService;
40  import fr.paris.lutece.portal.service.util.AppPropertiesService;
41  
42  import org.apache.commons.beanutils.BeanUtils;
43  
44  import java.io.IOException;
45  import java.io.InputStream;
46  import java.io.OutputStream;
47  import java.io.OutputStreamWriter;
48  
49  import java.lang.reflect.InvocationTargetException;
50  
51  import java.util.ArrayList;
52  import java.util.HashMap;
53  import java.util.Locale;
54  import java.util.Map;
55  import java.util.Properties;
56  
57  
58  public class CsvUtils
59  {
60      private static final String PROPERTY_RESOURCES_LIBRARY_CSV_PROPERTIES;
61      private static final char PROPERTY_SEPARATEUR_CSV;
62      private static final String PROPERTY_ENCODING_CSV = "UTF-8";
63      private static final String PARAMETER_HEADER_CSV = ".entete";
64      private static final String PARAMETER_SPLIT_CSV = ",";
65      private static final String PARAMETER_FIELD_CSV = ".champs";
66  
67      static
68      {
69          PROPERTY_RESOURCES_LIBRARY_CSV_PROPERTIES = AppPropertiesService.getProperty( 
70                  "exportuserpreferences.csv.configuration.path" );
71          PROPERTY_SEPARATEUR_CSV = AppPropertiesService.getProperty( "exportuserpreferences.csv.separator", ";" )
72                                                        .charAt( 0 );
73      }
74  
75      public static Map<String, Integer> getHeaderLineOrder( String cle )
76      {
77          String nomDTO = cle;
78          Map<String, Integer> headers = new HashMap<String, Integer>(  );
79  
80          //Chargement du fichier de properties
81          InputStream isProprieteCsv = CsvUtils.class.getClassLoader(  )
82                                                     .getResourceAsStream( PROPERTY_RESOURCES_LIBRARY_CSV_PROPERTIES );
83  
84          if ( isProprieteCsv == null )
85          {
86              throw new RuntimeException( "Fichier " + PROPERTY_RESOURCES_LIBRARY_CSV_PROPERTIES + " non trouvé." );
87          }
88          else
89          {
90              try
91              {
92                  ArrayList<String> keysToExportList = (ArrayList<String>) KeyHome.getToExportKeysList(  );
93                  Properties proprieteCsv = new Properties(  );
94                  proprieteCsv.load( isProprieteCsv );
95                  ;
96  
97                  //Récupération des libellés des champs
98                  String sListeChamps = proprieteCsv.getProperty( nomDTO + PARAMETER_FIELD_CSV );
99                  String[] listeChamps = sListeChamps.split( PARAMETER_SPLIT_CSV );
100 
101                 int i = -1;
102 
103                 // the first field is the user ID, not a pref_key
104                 // the user ID is handled separately
105                 for ( String field : listeChamps )
106                 {
107                     if ( keysToExportList.contains( field ) )
108                     {
109                         headers.put( field, i );
110                     }
111 
112                     ++i;
113                 }
114             }
115             catch ( IOException e )
116             {
117                 throw new RuntimeException( "Problème lors de l'édition du fichier CSV : " + e.getMessage(  ), e );
118             }
119         }
120 
121         return headers;
122     }
123 
124     /**
125      * Ecrit sur la sortie passée en paramètre, les lignes de csv.
126      * Attention : ne gère pas l'écriture des en-têtes (content type par
127      * exemple) ni la fermeture du flux de sortie.
128      * @param cle
129      * @param <R> type du DTO résultat
130      * @param businessDTO
131      * @param listeResultat
132      * @param out
133      */
134     public static void ecrireCsv( String cle, Map<String, ArrayList<String>> listeResultat, OutputStream out,
135         Locale locale )
136     {
137         if ( listeResultat != null )
138         {
139             String nomDTO = cle;
140 
141             //Chargement du fichier de properties
142             InputStream isProprieteCsv = CsvUtils.class.getClassLoader(  )
143                                                        .getResourceAsStream( PROPERTY_RESOURCES_LIBRARY_CSV_PROPERTIES );
144 
145             if ( isProprieteCsv == null )
146             {
147                 throw new RuntimeException( "Fichier " + PROPERTY_RESOURCES_LIBRARY_CSV_PROPERTIES + " non trouvé." );
148             }
149             else
150             {
151                 try
152                 {
153                     Properties proprieteCsv = new Properties(  );
154                     proprieteCsv.load( isProprieteCsv );
155 
156                     CSVWriter csvWriter = new CSVWriter( new OutputStreamWriter( out, PROPERTY_ENCODING_CSV ),
157                             PROPERTY_SEPARATEUR_CSV );
158 
159                     //Récupération des libellés d'en-tête
160                     String sListeEntete = proprieteCsv.getProperty( nomDTO + PARAMETER_HEADER_CSV );
161                     String[] listeEntete = sListeEntete.split( PARAMETER_SPLIT_CSV );
162 
163                     for ( int i = 0; i < listeEntete.length; i++ )
164                     {
165                         listeEntete[i] = I18nService.getLocalizedString( listeEntete[i], locale );
166                     }
167 
168                     csvWriter.writeNext( listeEntete );
169 
170                     if ( !listeResultat.isEmpty(  ) )
171                     {
172                         //Récupération des libellés des champs
173                         String sListeChamps = proprieteCsv.getProperty( nomDTO + PARAMETER_FIELD_CSV );
174                         String[] listeChamps = sListeChamps.split( PARAMETER_SPLIT_CSV );
175 
176                         for ( Map.Entry<String, ArrayList<String>> entry : listeResultat.entrySet(  ) )
177                         {
178                             String[] ligneCsv = new String[listeChamps.length];
179 
180                             if ( listeChamps.length > 0 )
181                             {
182                                 ligneCsv[0] = entry.getKey(  );
183                             }
184 
185                             ArrayList<String> values = entry.getValue(  );
186 
187                             for ( int i = 0; i < values.size(  ); i++ )
188                             {
189                                 ligneCsv[i + 1] = entry.getValue(  ).get( i );
190                             }
191 
192                             csvWriter.writeNext( ligneCsv );
193                         }
194                     }
195 
196                     csvWriter.flush(  );
197                     csvWriter.close(  );
198                 }
199                 catch ( IOException e )
200                 {
201                     throw new RuntimeException( "Problème lors de l'édition du fichier CSV : " + e.getMessage(  ), e );
202                 }
203             }
204         }
205     }
206 }