KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > objectweb > cjdbc > scenario > standalone > sql > request > UpdateRequestTest


1 /**
2  * C-JDBC: Clustered JDBC.
3  * Copyright (C) 2002-2004 French National Institute For Research In Computer
4  * Science And Control (INRIA).
5  * Contact: c-jdbc@objectweb.org
6  *
7  * This library is free software; you can redistribute it and/or modify it
8  * under the terms of the GNU Lesser General Public License as published by the
9  * Free Software Foundation; either version 2.1 of the License, or any later
10  * version.
11  *
12  * This library is distributed in the hope that it will be useful, but WITHOUT
13  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
14  * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
15  * for more details.
16  *
17  * You should have received a copy of the GNU Lesser General Public License
18  * along with this library; if not, write to the Free Software Foundation,
19  * Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.
20  *
21  * Initial developer(s): Mathieu Peltier
22  * Contributor(s): ______________________________________.
23  */

24
25 package org.objectweb.cjdbc.scenario.standalone.sql.request;
26
27 import java.io.File JavaDoc;
28 import java.io.FileReader JavaDoc;
29 import java.io.IOException JavaDoc;
30 import java.sql.SQLException JavaDoc;
31 import java.util.ArrayList JavaDoc;
32 import java.util.Arrays JavaDoc;
33 import java.util.Comparator JavaDoc;
34 import java.util.HashMap JavaDoc;
35 import java.util.Iterator JavaDoc;
36 import java.util.StringTokenizer JavaDoc;
37
38 import org.objectweb.cjdbc.common.sql.ParsingGranularities;
39 import org.objectweb.cjdbc.common.sql.UpdateRequest;
40 import org.objectweb.cjdbc.common.sql.schema.DatabaseTable;
41 import org.objectweb.cjdbc.common.sql.schema.TableColumn;
42 import org.objectweb.cjdbc.scenario.templates.NoTemplate;
43 import org.objectweb.cjdbc.scenario.tools.databases.AbstractDatabase;
44 import org.objectweb.cjdbc.scenario.tools.databases.RUBiSDatabase;
45 import org.objectweb.cjdbc.scenario.tools.util.MyBufferedReader;
46
47 /**
48  * @author <a HREF="mailto:Mathieu.Peltier@inrialpes.fr">Mathieu Peltier </a>
49  * org.objectweb.cjdbc.common.sql..UpdateRequest
50  */

51 public class UpdateRequestTest extends NoTemplate
52 {
53   /** File name containing the requests to test. */
54   private static final String JavaDoc RUBIS_UPDATE_REQUESTS_FILE = getTextPath("RUBiS-update-requests.txt");
55
56   /** Null value to used in the requests file if needed. */
57   private static final String JavaDoc EMPTY_VALUE = "null";
58
59   /** Database on which the requests are performed. */
60   private AbstractDatabase database;
61
62   /** List of <code>ParsingResult</code> objects. */
63   private ArrayList JavaDoc results;
64
65   static boolean inited = false;
66
67   /**
68    * @see junit.framework.TestCase#setUp()
69    */

70   protected void setUp()
71   {
72     synchronized (this)
73     {
74       if (inited)
75         return;
76
77       database = new RUBiSDatabase();
78       results = new ArrayList JavaDoc();
79
80       String JavaDoc request = null, tableName, columnList, updatedValues, updatedPk, errorMessage;
81       boolean isUnique = false;
82
83       try
84       {
85         File JavaDoc file = new File JavaDoc(RUBIS_UPDATE_REQUESTS_FILE);
86         MyBufferedReader in = new MyBufferedReader(new FileReader JavaDoc(file),
87             "requests");
88
89         String JavaDoc line;
90         while ((line = in.readLine()) != null)
91         {
92           if (line.trim().equals("") || line.startsWith("//"))
93             continue;
94
95           // Get the request
96
request = null;
97           request = in.readSQLRequest(line);
98
99           // Get expected results for this request
100
if (in.readBoolean())
101           {
102             // Valid request
103
tableName = in.readString("table name");
104             columnList = in.readString("column list");
105
106             isUnique = in.readBoolean();
107
108             updatedValues = in.readString("updated values");
109             if (updatedValues.equals(EMPTY_VALUE))
110               updatedValues = null;
111
112             updatedPk = in.readString("updated pk");
113             if (updatedPk.equals(EMPTY_VALUE))
114               updatedPk = null;
115
116             results.add(new ParsingResult(request, tableName, columnList,
117                 isUnique, updatedValues, updatedPk));
118           }
119           else
120           {
121             // invalid request
122
errorMessage = in.readString("errorMessage");
123             results.add(new ParsingResult(request, errorMessage));
124           }
125         }
126       }
127       catch (IOException JavaDoc e)
128       {
129         String JavaDoc error = "An error occurs while parsing requests file: " + e;
130         if (request != null)
131           error += " (request: '" + request + "')";
132         fail(error);
133       }
134       inited = true;
135     }
136   }
137
138   /**
139    * org.objectweb.cjdbc.common.sql.UpdateRequest#parse(DatabaseSchema, int,
140    * boolean)
141    */

142   public void testParse()
143   {
144     Iterator JavaDoc it = results.iterator();
145     while (it.hasNext())
146     {
147       parse((ParsingResult) it.next(), false);
148     }
149   }
150
151   /**
152    * Perfoms the parsing test.
153    *
154    * @param result expected result
155    * @param isCaseSensitive <code>true</code> if the parsing must be case
156    * sensitive.
157    */

158   private void parse(ParsingResult result, boolean isCaseSensitive)
159   {
160     String JavaDoc sql = result.request.toLowerCase().trim();
161     System.out.println("Parsing:"+sql);
162     UpdateRequest req = null;
163     try
164     {
165       req = new UpdateRequest(sql, false, 0, System
166           .getProperty("line.separator"), database.getSchema(),
167           ParsingGranularities.COLUMN_UNIQUE, isCaseSensitive);
168     }
169     catch (SQLException JavaDoc e)
170     {
171       if (result.isValid)
172       {
173         fail("Exception thrown with valid request '" + result.request + "' ("
174             + e + ")");
175       }
176       else
177       {
178         assertEquals(
179             "Incorrect error message found while parsing this DELETE statement: '"
180                 + result.request + "'", result.errorMessage, e.getMessage());
181         return;
182       }
183     }
184
185     if (!result.isValid)
186       fail("SQLException not thrown with invalid request: '" + result.request
187           + "'");
188     else
189     {
190       // Check table
191
assertEquals("Incorrect table found", req.getTableName(), result.table
192           .getName());
193
194       // Check columns ArrayList (the parsing does not guaranty the order so
195
// we don't compare directly the ArrayList)
196
TableColumn c;
197       Iterator JavaDoc it = result.columns.iterator();
198       while (it.hasNext())
199       {
200         c = (TableColumn) it.next();
201         assertTrue("'" + c.getColumnName()
202             + "' column not selected by parsing for request: '" + sql + "'",
203             req.getColumns().contains(c));
204       }
205
206       // Check unicity
207
assertEquals("Unicity not correct for request: '" + sql + "'",
208           result.isUnique, req.isUnique());
209
210       // Check updated values
211
if (result.updatedValues != null)
212       {
213         HashMap JavaDoc hash = req.getUpdatedValues();
214         ArrayList JavaDoc al = new ArrayList JavaDoc(req.getUpdatedValues().keySet());
215         Object JavaDoc[] obs = al.toArray();
216         Arrays.sort(obs, new MyComparator());
217         al = new ArrayList JavaDoc(Arrays.asList(obs));
218         StringBuffer JavaDoc buf = new StringBuffer JavaDoc();
219         for (int i = 0; i < al.size(); i++)
220         {
221           if (i != 0)
222             buf.append(",");
223           buf.append(al.get(i) + "=" + hash.get(al.get(i)));
224         }
225         //System.out.println("GOT:" + buf.toString());
226
//System.out.println("EXPECTED:" + result.updatedValues);
227
assertEquals("Incorrect updatedValues for request: '" + sql + "'", buf
228             .toString(), result.updatedValues);
229       }
230       else
231       {
232         assertNull("Incorrect not null updatedValues for request: '" + sql
233             + "'", req.getUpdatedValues());
234       }
235
236       // Check updated pk
237
//System.out.println("PK:" + req.getPk());
238
assertEquals("Incorrect updated pk for request: '" + sql + "'", req
239           .getPk(), result.updatedPk);
240     }
241   }
242
243   class MyComparator implements Comparator JavaDoc
244   {
245     /**
246      * Compare two <code>TableColumn</code> objects
247      */

248     public int compare(Object JavaDoc o1, Object JavaDoc o2)
249     {
250       if (o1 instanceof TableColumn && o2 instanceof TableColumn)
251         return ((TableColumn) o1).getColumnName().compareTo(
252             ((TableColumn) o2).getColumnName());
253       else
254         return (o1.toString().compareTo(o2.toString()));
255     }
256   }
257
258   /**
259    * Stores the expected result of the call to
260    * {@link org.objectweb.cjdbc.common.sql.UpdateRequest#parse(DatabaseSchema, int, boolean)}
261    * method.
262    *
263    * @author <a HREF="mailto:Mathieu.Peltier@inrialpes.fr">Mathieu Peltier </a>
264    */

265   protected class ParsingResult
266   {
267     /** Request to test. */
268     protected String JavaDoc request;
269
270     /** <code>true</code> if the request is valid. */
271     protected boolean isValid;
272
273     /** Database table to create if the request is valid. */
274     protected DatabaseTable table;
275
276     /** <code>ArrayList</code> of <code>TableColumn</code> objects. */
277     protected ArrayList JavaDoc columns;
278
279     /** <code>true</code> if this query only concerns a single row. */
280     protected boolean isUnique;
281
282     /** Values updated */
283     protected String JavaDoc updatedValues;
284
285     /** Updated pk */
286     protected String JavaDoc updatedPk;
287
288     /** Error message if the request is invalid. */
289     protected String JavaDoc errorMessage;
290
291     /**
292      * Creates a new <code>ParsingResult</code> instance for valid request.
293      *
294      * @param request valid request to test.
295      * @param tableName database name to test.
296      * @param columnList column list (eg: col1.unique col2 col3). '.unique'
297      * means that the column is unique.
298      * @param isUnique <code>true</code> if this query only concerns a single
299      * row.
300      */

301     protected ParsingResult(String JavaDoc request, String JavaDoc tableName,
302         String JavaDoc columnList, boolean isUnique, String JavaDoc updatedValues,
303         String JavaDoc updatedPk)
304     {
305       this.request = request;
306       isValid = true;
307
308       // Get table
309
table = database.getSchema().getTable(tableName);
310       if (table == null)
311         fail("Possible syntax error in sql requests file: '" + tableName
312             + "' not found in database schema");
313
314       // Parse columns
315
columns = new ArrayList JavaDoc();
316       String JavaDoc columnName;
317       StringTokenizer JavaDoc tokenizer = new StringTokenizer JavaDoc(columnList.trim(), " ");
318       while (tokenizer.hasMoreTokens())
319       {
320         columnName = tokenizer.nextToken();
321         if (table.getColumn(columnName) != null)
322           columns.add(new TableColumn(tableName, columnName));
323         else
324           fail("Possible syntax error in sql requests file: '" + columnName
325               + "' not found in table '" + tableName + "'");
326       }
327
328       this.isUnique = isUnique;
329       this.updatedValues = (updatedValues == null) ? null : updatedValues
330           .trim();
331       this.updatedPk = updatedPk;
332     }
333
334     /**
335      * Creates a new <code>ParsingResult</code> instance for invalid request.
336      *
337      * @param request invalid request to test.
338      * @param errorMessage error message.
339      */

340     protected ParsingResult(String JavaDoc request, String JavaDoc errorMessage)
341     {
342       this.request = request;
343       isValid = false;
344       this.errorMessage = errorMessage;
345     }
346   }
347 }
Popular Tags