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.adminsql.business;
35  
36  import fr.paris.lutece.portal.service.database.PluginConnectionService;
37  import fr.paris.lutece.portal.service.plugin.Plugin;
38  import fr.paris.lutece.portal.service.plugin.PluginService;
39  import fr.paris.lutece.portal.service.util.AppException;
40  import fr.paris.lutece.portal.service.util.AppLogService;
41  import fr.paris.lutece.util.sql.DAOUtil;
42  
43  import java.sql.Connection;
44  import java.sql.PreparedStatement;
45  import java.sql.ResultSet;
46  import java.sql.ResultSetMetaData;
47  import java.sql.SQLException;
48  
49  import java.util.ArrayList;
50  import java.util.List;
51  import java.util.StringTokenizer;
52  
53  
54  /**
55   * Creates a new instance of DataDAO
56   */
57  public class DataDAO implements IDataDAO
58  {
59      //Constants
60      private static final String WHERE = " WHERE ";
61      private static final String VALUES = " VALUES ";
62      private static final String SELECT = " SELECT ";
63      private static final String FROM = " FROM ";
64      private static final String AND = " AND ";
65      private static final String UPDATE = "UPDATE ";
66      private static final String SET = " SET ";
67      private static final String STR_SQL_ERROR = "SQL Error executing command : ";
68      private static final String DELETE_FROM = "DELETE FROM ";
69  
70      //RequĂȘtes
71      private static final String SQL_QUERY_SELECT_ALL_DATA = "SELECT * FROM ";
72      private static final String SQL_QUERY_SELECT_A_ROW = "SELECT * FROM ";
73      private static final String SQL_QUERY_INSERT_VALUES = "INSERT INTO ";
74  
75      /**
76       * Selects and loads into the Data object all the data from the database
77       * @param strTableName the name of the table
78       * @param connectionService PluginConnectionService Object
79       * @return list of data
80       */
81      public List<List<String>> selectDataList( String strTableName, PluginConnectionService connectionService )
82      {
83          List<List<String>> listData = new ArrayList<List<String>>(  );
84  
85          try
86          {
87              listData = selectSqlQuery( SQL_QUERY_SELECT_ALL_DATA + strTableName, connectionService );
88          }
89          catch ( SQLException sql )
90          {
91              AppLogService.error( sql.getMessage(  ), sql );
92          }
93  
94          return listData;
95      }
96  
97      /**
98       * Selects and loads into the Data object all the data from the database in user request
99       * @param strPoolName the name of the pool
100      * @param strUserRequest user request
101      * @param connectionService PluginConnectionService Object
102      * @return list of data
103      */
104     public List<List<String>> selectDataListUserRequest( String strPoolName, String strUserRequest,
105         PluginConnectionService connectionService )
106     {
107         List<List<String>> listData = new ArrayList<List<String>>(  );
108         connectionService = new PluginConnectionService( strPoolName );
109         connectionService.setPool( strPoolName );
110 
111         try
112         {
113             listData = selectSqlQuery( strUserRequest, connectionService );
114         }
115         catch ( SQLException sql )
116         {
117             AppLogService.error( sql.getMessage(  ), sql );
118         }
119 
120         return listData;
121     }
122 
123     /**
124      * Insert data in table
125      * @param strPoolName the name of the pool
126      * @param strTableName the name of the table
127      * @param listData the list of data
128      * @param listFieldsNames list of fields names
129      * @param connectionService PluginConnectionService object
130      */
131     public void insert( String strPoolName, String strTableName, List<String> listData, List<String> listFieldsNames,
132         PluginConnectionService connectionService )
133     {
134         String strFieldsNames = "";
135         String strDataValues = "";
136 
137         for ( String strFieldName : listFieldsNames )
138         {
139             strFieldsNames = strFieldsNames + strFieldName + ", ";
140         }
141 
142         strFieldsNames = strFieldsNames.substring( 0, strFieldsNames.length(  ) - 2 );
143 
144         String strFieldsNameFinal = " (" + strFieldsNames + ") ";
145 
146         for ( String strDataValue : listData )
147         {
148             strDataValues += ( "'" + strDataValue + "'" + ", " );
149         }
150 
151         strDataValues = strDataValues.substring( 0, strDataValues.length(  ) - 2 );
152 
153         String strDataValuesFinal = " (" + strDataValues + ") ";
154         DAOUtil daoUtil = new DAOUtil( SQL_QUERY_INSERT_VALUES + strTableName + " " + strFieldsNameFinal + VALUES +
155                 strDataValuesFinal, changePool( strPoolName ) );
156         daoUtil.executeUpdate(  );
157         daoUtil.free(  );
158     }
159 
160     /**
161      * Store the data in tha table in a database
162      * @param strPoolName the name of the pool
163      * @param strTableName the name of the table
164      * @param listFieldValues the list fields values
165      * @param connectionService PluginConnectionService object
166      */
167     public void store( String strPoolName, String strTableName, List<FieldValues> listFieldValues,
168         PluginConnectionService connectionService )
169     {
170         String strAllDataToModify = "";
171         String strAllDataModified = "";
172 
173         for ( FieldValues fieldValues : listFieldValues )
174         {
175             strAllDataModified = strAllDataModified + "," + fieldValues.getFieldName(  ) + "=" + "'" +
176                 fieldValues.getNewValue(  ) + "'";
177             strAllDataToModify = strAllDataToModify + AND + fieldValues.getFieldName(  ) + "=" + "'" +
178                 fieldValues.getOldValue(  ) + "'";
179         }
180 
181         strAllDataModified = strAllDataModified.substring( 1 );
182         strAllDataToModify = strAllDataToModify.substring( 4 );
183 
184         DAOUtil daoUtil = new DAOUtil( UPDATE + strTableName + SET + strAllDataModified + WHERE + strAllDataToModify,
185                 changePool( strPoolName ) );
186         daoUtil.executeUpdate(  );
187         daoUtil.free(  );
188     }
189 
190     /**
191      * Delete a row in a table
192      * @param strPoolName the name of the pool
193      * @param strTableName the name of the table
194      * @param listConcatFieldNameAndData the list of concatenation of fields name and data
195      * @param connectionService PluginConnectionService object
196      */
197     public void delete( String strPoolName, String strTableName, List<String> listConcatFieldNameAndData,
198         PluginConnectionService connectionService )
199     {
200         String strAllDataToDelete = "";
201 
202         for ( String strConcatFieldNameAndData : listConcatFieldNameAndData )
203         {
204             strAllDataToDelete = strAllDataToDelete + AND + strConcatFieldNameAndData;
205         }
206 
207         strAllDataToDelete = strAllDataToDelete.substring( 4 );
208 
209         DAOUtil daoUtil = new DAOUtil( DELETE_FROM + strTableName + WHERE + strAllDataToDelete,
210                 changePool( strPoolName ) );
211         daoUtil.executeUpdate(  );
212         daoUtil.free(  );
213     }
214 
215     /**
216      * Insert the data with user request
217      * @param strUserRequest user request
218      * @param connectionService PluginConnectionService object
219      * @param strPoolName the name of the pool
220      */
221     public void insertWithUserRequest( String strUserRequest, PluginConnectionService connectionService,
222         String strPoolName )
223     {
224         DAOUtil daoUtil = new DAOUtil( strUserRequest, changePool( strPoolName ) );
225         daoUtil.executeUpdate(  );
226         daoUtil.free(  );
227     }
228 
229     /**
230      * Find the list of data of a table
231      * @param strTableName the name of the table
232      * @param strContatFieldNameAndData the list of concatenation of fields name and data
233      * @param listFields list of fields
234      * @param connectionService PluginConnectionService object
235      * @return list of the data
236      */
237     public List<List<String>> load( String strTableName, String strContatFieldNameAndData, List<Field> listFields,
238         PluginConnectionService connectionService )
239     {
240         DAOUtil daoUtil = new DAOUtil( SQL_QUERY_SELECT_A_ROW + strTableName + WHERE + strContatFieldNameAndData );
241         daoUtil.executeQuery(  );
242         List<List<String>> listDataValueSelectedByPK = new ArrayList(  );
243         return listDataValueSelectedByPK;
244     }
245 
246     /**
247      * Find the answer of the user query
248      * @param strRequest the request
249      * @param connectionService PluginConnectionService object
250      * @return list of the data
251      */
252     private List<List<String>> selectSqlQuery( String strRequest, PluginConnectionService connectionService )
253         throws SQLException
254     {
255         Connection connection = null;
256         PreparedStatement statement = null;
257 
258         try
259         {
260             connection = connectionService.getConnection(  );
261             statement = connection.prepareStatement( strRequest );
262 
263             ResultSet resultSet = statement.executeQuery(  );
264             ResultSetMetaData rsmd = resultSet.getMetaData(  );
265 
266             ArrayList listRow = new ArrayList(  );
267 
268             while ( resultSet.next(  ) )
269             {
270                 String strValue = null;
271                 ArrayList listLine = new ArrayList(  );
272 
273                 for ( int i = 1; i <= rsmd.getColumnCount(  ); i++ )
274                 {
275                     if ( resultSet.getObject( rsmd.getColumnName( i ) ) != null )
276                     {
277                         strValue = resultSet.getObject( rsmd.getColumnName( i ) ).toString(  );
278                     }
279                     else
280                     {
281                         strValue = " ";
282                     }
283 
284                     listLine.add( strValue );
285                 }
286 
287                 listRow.add( listLine );
288             }
289 
290             statement.close(  );
291             statement = null;
292 
293             return listRow;
294         }
295         finally
296         {
297             try
298             {
299                 if ( statement != null )
300                 {
301                     statement.close(  );
302                 }
303             }
304             catch ( SQLException e )
305             {
306                 throw new AppException( "SQL Error executing command : " + e.toString(  ) );
307             }
308 
309             connectionService.freeConnection( connection );
310         }
311     }
312 
313     /**
314      * Result of user request
315      * @param strUserRequest user request
316      * @param connectionService PluginConnectionService object
317      * @return  result of user request
318      */
319     public List<List<String>> findResultOfUserRequest( String strUserRequest, PluginConnectionService connectionService )
320     {
321         List<List<String>> listData = new ArrayList<List<String>>(  );
322         List<String> listFields = new ArrayList<String>(  );
323 
324         try
325         {
326             listData = selectSqlQuery( strUserRequest, connectionService );
327         }
328         catch ( SQLException sql )
329         {
330             AppLogService.error( sql.getMessage(  ), sql );
331         }
332 
333         return listData;
334     }
335 
336     /**
337      * Find the names of all columns
338      * @param strUserRequest user request
339      * @param connectionService PluginConnectionService object
340      * @param strPoolName the name of the pool
341      * @return list of all names of the columns
342      */
343     public List<String> selectColumnNames( String strUserRequest, PluginConnectionService connectionService,
344         String strPoolName )
345     {
346         List<String> listFields = new ArrayList(  );
347         DAOUtil daoUtil = new DAOUtil( strUserRequest, changePool( strPoolName ) );
348         daoUtil.executeQuery(  );
349 
350         for ( int i = 1; i <= getColumnCount( daoUtil ); i++ )
351         {
352             String columnName = getColumnName( i, daoUtil );
353             listFields.add( columnName );
354         }
355 
356         daoUtil.free(  );
357 
358         return listFields;
359     }
360 
361     private String getColumnName( int nColumn, DAOUtil daoUtil )
362     {
363         try
364         {
365             ResultSetMetaData rsmd = daoUtil.getResultSet(  ).getMetaData(  );
366 
367             return rsmd.getColumnName( nColumn );
368         }
369         catch ( SQLException e )
370         {
371             daoUtil.free(  );
372             throw new AppException( STR_SQL_ERROR + e.toString(  ) );
373         }
374     }
375 
376     private int getColumnCount( DAOUtil daoUtil )
377     {
378         try
379         {
380             ResultSetMetaData rsmd = daoUtil.getResultSet(  ).getMetaData(  );
381 
382             return rsmd.getColumnCount(  );
383         }
384         catch ( SQLException e )
385         {
386             daoUtil.free(  );
387             throw new AppException( STR_SQL_ERROR + e.toString(  ) );
388         }
389     }
390 
391     private Plugin changePool( String strPoolName )
392     {
393         Plugin plugin = PluginService.getPlugin( "adminsql" );
394         PluginConnectionService connectionService = new PluginConnectionService( strPoolName );
395         connectionService.setPool( strPoolName );
396         plugin.setConnectionService( connectionService );
397 
398         return plugin;
399     }
400 }