KickJava   Java API By Example, From Geeks To Geeks.

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


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.Iterator JavaDoc;
35 import java.util.StringTokenizer JavaDoc;
36
37 import org.objectweb.cjdbc.common.sql.InsertRequest;
38 import org.objectweb.cjdbc.common.sql.ParsingGranularities;
39 import org.objectweb.cjdbc.common.sql.schema.DatabaseTable;
40 import org.objectweb.cjdbc.common.sql.schema.TableColumn;
41 import org.objectweb.cjdbc.scenario.templates.NoTemplate;
42 import org.objectweb.cjdbc.scenario.tools.databases.AbstractDatabase;
43 import org.objectweb.cjdbc.scenario.tools.databases.RUBiSDatabase;
44 import org.objectweb.cjdbc.scenario.tools.util.MyBufferedReader;
45
46 /**
47  * @author <a HREF="mailto:Mathieu.Peltier@inrialpes.fr">Mathieu Peltier </a>
48  * org.objectweb.cjdbc.common.sql..InsertRequest
49  */

50 public class InsertRequestTest extends NoTemplate
51 {
52   /** File name containing the requests to test. */
53   private static final String JavaDoc RUBIS_INSERT_REQUESTS_FILE = getTextPath("RUBiS-insert-requests.txt");
54
55   /** Database on which the requests are performed. */
56   private AbstractDatabase database;
57
58   /** List of <code>ParsingResult</code> objects. */
59   private ArrayList JavaDoc results;
60
61   static boolean inited = false;
62
63   /**
64    * @see junit.framework.TestCase#setUp()
65    */

66   protected void setUp()
67   {
68     synchronized (this)
69     {
70       if (inited)
71         return;
72
73       database = new RUBiSDatabase();
74       results = new ArrayList JavaDoc();
75       String JavaDoc request = null, tableName, columnList, errorMessage;
76
77       try
78       {
79         File JavaDoc file = new File JavaDoc(RUBIS_INSERT_REQUESTS_FILE);
80         MyBufferedReader in = new MyBufferedReader(new FileReader JavaDoc(file),
81             "requests");
82
83         String JavaDoc line;
84         while ((line = in.readLine()) != null)
85         {
86           if (line.trim().equals("") || line.startsWith("//"))
87             continue;
88
89           // get the request
90
request = null;
91           request = in.readSQLRequest(line);
92
93           // get expected results for this request
94
if (in.readBoolean())
95           {
96             // valid request
97
tableName = in.readString("table name");
98             columnList = in.readString("column list");
99             results.add(new ParsingResult(request, tableName, columnList));
100           }
101           else
102           {
103             // invalid request
104
errorMessage = in.readString("error message");
105             results.add(new ParsingResult(request, errorMessage));
106           }
107         }
108       }
109       catch (IOException JavaDoc e)
110       {
111         String JavaDoc error = "An error occurs while parsing requests file: " + e;
112         if (request != null)
113           error += " (request: '" + request + "')";
114         fail(error);
115       }
116       inited = true;
117     }
118   }
119
120   /**
121    * org.objectweb.cjdbc.common.sql.InsertRequest#parse(DatabaseSchema, int,
122    * boolean)
123    */

124   public void testParse()
125   {
126     Iterator JavaDoc it = results.iterator();
127     while (it.hasNext())
128     {
129       parse((ParsingResult) it.next(), false);
130     }
131   }
132
133   /**
134    * Perfoms the parsing test.
135    *
136    * @param result expected result
137    * @param isCaseSensitive <code>true</code> if the parsing must be case
138    * sensitive.
139    */

140   private void parse(ParsingResult result, boolean isCaseSensitive)
141   {
142     String JavaDoc sql = result.request.toLowerCase().trim();
143     InsertRequest req = null;
144     try
145     {
146       req = new InsertRequest(sql, false, 0, System
147           .getProperty("line.separator"), database.getSchema(),
148           ParsingGranularities.COLUMN_UNIQUE, isCaseSensitive, false /* isRead */);
149     }
150     catch (SQLException JavaDoc e)
151     {
152       if (result.isValid)
153       {
154         fail("Exception thrown with valid request '" + result.request + "' ("
155             + e + ")");
156       }
157       else
158       {
159         assertEquals(
160             "Incorrect error message found while parsing this DELETE statement: '"
161                 + result.request + "'", result.errorMessage, e.getMessage());
162         return;
163       }
164     }
165
166     if (!result.isValid)
167       fail("SQLException not thrown with invalid request: '" + result.request
168           + "'");
169     else
170     {
171       // check table
172
assertEquals("Incorrect table found", req.getTableName(), result.table
173           .getName());
174
175       ArrayList JavaDoc al = req.getColumns();
176       Object JavaDoc[] obs = al.toArray();
177       Arrays.sort(obs, new MyComparator());
178       al = new ArrayList JavaDoc(Arrays.asList(obs));
179
180       req.getColumns();
181       ArrayList JavaDoc al2 = result.columns;
182       Object JavaDoc[] obs2 = al2.toArray();
183       Arrays.sort(obs2, new MyComparator());
184       al2 = new ArrayList JavaDoc(Arrays.asList(obs2));
185
186       //debugArrayList("GOT", al);
187
//debugArrayList("EXPECTED", al2);
188
assertEquals(al.toString() + System.getProperty("line.separator")
189           + al2.toString(), al, al2);
190     }
191   }
192
193   /**
194    * Sort the given ArrayList
195    *
196    * @param al the ArrayList to sort
197    * @return the sorted ArrayList
198    */

199   public ArrayList JavaDoc sortArrayList(ArrayList JavaDoc al)
200   {
201     Object JavaDoc[] obs = al.toArray();
202     Arrays.sort(obs, new MyComparator());
203     return new ArrayList JavaDoc(Arrays.asList(obs));
204   }
205
206   /**
207    * Print the given ArrayList prepended by a given header. Expects an ArrayList
208    * of TableColumn but will not fail if it is not.
209    *
210    * @param header header to display
211    * @param al ArrayList to display
212    */

213   public void debugArrayList(String JavaDoc header, ArrayList JavaDoc al)
214   {
215     StringBuffer JavaDoc buf = new StringBuffer JavaDoc();
216     for (int i = 0; i < al.size(); i++)
217     {
218       if (i != 0)
219         buf.append(",");
220       Object JavaDoc o = al.get(i);
221       if (o instanceof TableColumn)
222         buf.append(((TableColumn) o).getColumnName());
223       else
224         buf.append(o.toString());
225     }
226     System.out.println(header + ":" + buf.toString());
227   }
228
229   class MyComparator implements Comparator JavaDoc
230   {
231     /**
232      * Compare two <code>TableColumn</code> objects
233      */

234     public int compare(Object JavaDoc o1, Object JavaDoc o2)
235     {
236       if (o1 instanceof TableColumn && o2 instanceof TableColumn)
237         return ((TableColumn) o1).getColumnName().compareTo(
238             ((TableColumn) o2).getColumnName());
239       else
240         return (o1.toString().compareTo(o2.toString()));
241     }
242   }
243
244   /**
245    * Stores the expected result of the call to
246    * {@link org.objectweb.cjdbc.common.sql.InsertRequest#parse(DatabaseSchema, int, boolean)}
247    * method.
248    *
249    * @author <a HREF="mailto:Mathieu.Peltier@inrialpes.fr">Mathieu Peltier </a>
250    */

251   protected class ParsingResult
252   {
253     /** Request to test. */
254     protected String JavaDoc request;
255
256     /** <code>true</code> if the request is valid. */
257     protected boolean isValid;
258
259     /** Table concerned by the request. */
260     protected DatabaseTable table;
261
262     /**
263      * Columns concerned by the request: <code>ArrayList</code> of
264      * <code>TableColumn</code> objects.
265      */

266     protected ArrayList JavaDoc columns;
267
268     /** Error message if the request is invalid. */
269     protected String JavaDoc errorMessage;
270
271     /**
272      * Creates a new <code>ParsingResult</code> instance for valid request.
273      *
274      * @param request request to test.
275      * @param tableName table concerned by the request.
276      * @param columnList
277      */

278     protected ParsingResult(String JavaDoc request, String JavaDoc tableName, String JavaDoc columnList)
279     {
280       this.request = request;
281       isValid = true;
282
283       // Get table
284
table = database.getSchema().getTable(tableName);
285       if (table == null)
286         fail("Possible syntax error in sql requests file: '" + tableName
287             + "' not found in database schema");
288
289       // Parse columns
290
columns = new ArrayList JavaDoc();
291       String JavaDoc columnName;
292       StringTokenizer JavaDoc tokenizer = new StringTokenizer JavaDoc(columnList.trim(), " ");
293       while (tokenizer.hasMoreTokens())
294       {
295         columnName = tokenizer.nextToken();
296         if (table.getColumn(columnName) != null)
297           columns.add(new TableColumn(tableName, columnName));
298         else
299           fail("Possible syntax error in sql requests file: '" + columnName
300               + "' not found in table '" + tableName + "'");
301       }
302     }
303
304     /**
305      * Creates a new <code>ParsingResult</code> instance for invalid request.
306      *
307      * @param request invalid request to test.
308      * @param errorMessage error message.
309      */

310     protected ParsingResult(String JavaDoc request, String JavaDoc errorMessage)
311     {
312       this.request = request;
313       isValid = false;
314       this.errorMessage = errorMessage;
315     }
316   }
317 }
Popular Tags