KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > hsqldb > test > TestCollation


1 /* Copyright (c) 2001-2005, The HSQL Development Group
2  * All rights reserved.
3  *
4  * Redistribution and use in source and binary forms, with or without
5  * modification, are permitted provided that the following conditions are met:
6  *
7  * Redistributions of source code must retain the above copyright notice, this
8  * list of conditions and the following disclaimer.
9  *
10  * Redistributions in binary form must reproduce the above copyright notice,
11  * this list of conditions and the following disclaimer in the documentation
12  * and/or other materials provided with the distribution.
13  *
14  * Neither the name of the HSQL Development Group nor the names of its
15  * contributors may be used to endorse or promote products derived from this
16  * software without specific prior written permission.
17  *
18  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
19  * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
20  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
21  * ARE DISCLAIMED. IN NO EVENT SHALL HSQL DEVELOPMENT GROUP, HSQLDB.ORG,
22  * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
23  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
24  * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
25  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
26  * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
28  * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29  */

30
31
32 package org.hsqldb.test;
33
34 import junit.framework.TestCase;
35 import junit.framework.TestResult;
36
37 /**
38  * Test HSQLDBs collation capabilities
39  * @author frank.schoenheit@sun.com
40  */

41 public class TestCollation extends TestBase {
42
43     java.sql.Statement JavaDoc statement;
44     java.sql.Connection JavaDoc connection;
45     org.hsqldb.Collation collation;
46     org.hsqldb.lib.Iterator collIterator;
47     org.hsqldb.lib.Iterator localeIterator;
48
49     /** Creates a new instance of TestCollation */
50     public TestCollation(String JavaDoc name) {
51
52         super(name);
53
54         super.isNetwork = false;
55     }
56
57     protected void setUp() {
58
59         super.setUp();
60
61         try {
62             connection = super.newConnection();
63             statement = connection.createStatement();
64         } catch (Exception JavaDoc e) {}
65
66         collation = new org.hsqldb.Collation();
67         collIterator = collation.getCollationsIterator();
68         localeIterator = collation.getLocalesIterator();
69     }
70
71     protected void tearDown() {
72
73         try {
74             statement = connection.createStatement();
75
76             statement.execute("SHUTDOWN");
77         } catch (Exception JavaDoc e) {}
78
79         super.tearDown();
80     }
81
82     /**
83      * checks whether expected locales are present and selectable
84      */

85     public void verifyAvailability() {
86
87         // let's check whether unknown collation identifiers are rejected
88
try {
89             statement.execute(
90                 getSetCollationStmt(
91                     "ThisIsDefinatelyNoValidCollationIdentifier"));
92             fail("database did not reject invalid collation name");
93         } catch (java.sql.SQLException JavaDoc e) {}
94
95         // let's check whether the DB accepts all known collations
96
int count = 0;
97
98         while (collIterator.hasNext()) {
99             String JavaDoc collationName = (String JavaDoc) collIterator.next();
100
101             try {
102                 statement.execute(getSetCollationStmt(collationName));
103             } catch (java.sql.SQLException JavaDoc e) {
104                 fail("could not set collation '" + collationName
105                      + "'\n exception message: " + e.getMessage());
106             }
107
108             ++count;
109         }
110
111         System.out.println("checked " + count
112                            + " collations for availability.");
113
114         // even if the above worked, we cannot be sure that all locales are really supported.
115
// The fact that SET DATABASE COLLATION succeeeded only means that a Collator could
116
// be instantiated with a Locale matching the given collation name. But what if
117
// Locale.Instance(...) lied, and returned a fallback Locale instance?
118
//
119
// Hmm, looking at the documentation of Locale.getAvailableLocales, I'm not sure
120
// whether it is really feasible. The doc states "returns a list of all installed Locales".
121
// The "installed" puzzles me - maybe this is really different per installation, and not only
122
// per JDK version?
123
java.util.Locale JavaDoc[] availableLocales =
124             java.util.Locale.getAvailableLocales();
125         org.hsqldb.lib.Set existenceCheck = new org.hsqldb.lib.HashSet();
126
127         for (int i = 0; i < availableLocales.length; ++i) {
128             String JavaDoc availaleName = availableLocales[i].getLanguage();
129
130             if (availableLocales[i].getCountry().length() > 0) {
131                 availaleName += "-" + availableLocales[i].getCountry();
132             }
133
134             existenceCheck.add(availaleName);
135         }
136
137         String JavaDoc notInstalled = "";
138         int expected = 0,
139                failed = 0;
140
141         while (localeIterator.hasNext()) {
142             String JavaDoc localeName = (String JavaDoc) localeIterator.next();
143
144             ++expected;
145
146             if (!existenceCheck.contains(localeName)) {
147                 if (notInstalled.length() > 0) {
148                     notInstalled += "; ";
149                 }
150
151                 notInstalled += localeName;
152
153                 ++failed;
154             }
155         }
156
157         if (notInstalled.length() > 0) {
158             fail("the following locales are not installed:\n "
159                  + notInstalled + "\n (" + failed + " out of " + expected
160                  + ")");
161         }
162     }
163
164     /**
165      * checks whether sorting via a given collation works as expected
166      */

167     public void verifyCollation() {
168
169         String JavaDoc failedCollations = "";
170         String JavaDoc failMessage = "";
171
172         while (collIterator.hasNext()) {
173             String JavaDoc collationName = (String JavaDoc) collIterator.next();
174             String JavaDoc message = checkSorting(collationName);
175
176             if (message.length() > 0) {
177                 if (failedCollations.length() > 0) {
178                     failedCollations += ", ";
179                 }
180
181                 failedCollations += collationName;
182                 failMessage += message;
183             }
184         }
185
186         if (failedCollations.length() > 0) {
187             fail("test failed for following collations:\n" + failedCollations
188                  + "\n" + failMessage);
189         }
190     }
191
192     /**
193      * returns an SQL statement to set the database collation
194      */

195     protected final String JavaDoc getSetCollationStmt(String JavaDoc collationName) {
196
197         final String JavaDoc setCollationStmtPre = "SET DATABASE COLLATION \"";
198         final String JavaDoc setCollationStmtPost = "\"";
199
200         return setCollationStmtPre + collationName + setCollationStmtPost;
201     }
202
203     /**
204      * checks sorting a table with according to a given collation
205      */

206     protected String JavaDoc checkSorting(String JavaDoc collationName) {
207
208         String JavaDoc prepareStmt =
209             "DROP TABLE WORDLIST IF EXISTS;"
210             + "CREATE TEXT TABLE WORDLIST ( ID INTEGER, WORD VARCHAR );"
211             + "SET TABLE WORDLIST SOURCE \"" + collationName
212             + ".csv;encoding=UTF-8\"";
213         String JavaDoc selectStmt = "SELECT ID, WORD FROM WORDLIST ORDER BY WORD";
214         String JavaDoc returnMessage = "";
215
216         try {
217
218             // set database collation
219
statement.execute(getSetCollationStmt(collationName));
220             statement.execute(prepareStmt);
221
222             java.sql.ResultSet JavaDoc results = statement.executeQuery(selectStmt);
223
224             while (results.next()) {
225                 int expectedPosition = results.getInt(1);
226                 int foundPosition = results.getRow();
227
228                 if (expectedPosition != foundPosition) {
229                     String JavaDoc word = results.getString(2);
230
231                     return "testing collation '" + collationName
232                            + "' failed\n" + " word : " + word
233                            + "\n" + " expected position : "
234                            + expectedPosition + "\n"
235                            + " found position : " + foundPosition + "\n";
236                 }
237             }
238         } catch (java.sql.SQLException JavaDoc e) {
239             return "testing collation '" + collationName
240                    + "' failed\n exception message: " + e.getMessage()
241                    + "\n";
242         }
243
244         return "";
245     }
246
247     public static void main(String JavaDoc[] argv) {
248
249         TestResult result = new TestResult();
250         TestCase availability = new TestCollation("verifyAvailability");
251
252         availability.run(result);
253
254         TestCase sorting = new TestCollation("verifyCollation");
255
256         sorting.run(result);
257
258         if (result.failureCount() != 0) {
259             System.err.println("TestCollation encountered errors:");
260
261             java.util.Enumeration JavaDoc failures = result.failures();
262
263             while (failures.hasMoreElements()) {
264                 System.err.println(failures.nextElement().toString());
265             }
266         } else {
267             System.out.println("TestCollation: all fine.");
268         }
269     }
270 }
271
Popular Tags