aboutsummaryrefslogtreecommitdiff
path: root/src/com/benlinskey/grdbc/LexiconCreator.java
blob: 5da0e6c854c3ba4764c82c27f0b9653169ba1ed5 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
/* Copyright 2013 Benjamin Linskey
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.benlinskey.grdbc;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import javax.xml.parsers.ParserConfigurationException;

import org.xml.sax.SAXException;

/**
 * Reads in an XML file containing a Greek lexicon and stores entries in an
 * SQLite database.
 * <p>
 * The entries in the XML file are not properly alphabetized, so we first read
 * them into a temporary table and then alphabetize them and copy them into the
 * final table in alphabetical order.
 * 
 * @author Ben Linskey
 */
public class LexiconCreator {
    private final static String FILE = "../xml/Perseus_text_1999.04.0058.xml";
    private final static String DB = "lexicon.db";
    private final static String TEMP_TABLE_NAME = "temp";
    private final static String FINAL_TABLE_NAME = "lexicon";
    private Connection connection;
    private PreparedStatement tempInsertStatement;
    private PreparedStatement finalInsertStatement;

    /**
     * Class constructor.
     */
    public LexiconCreator() {
        // Load driver.
        try {
            Class.forName("org.sqlite.JDBC");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
            System.exit(1);
        }

        // Connect to database.
        try {
            connection = DriverManager.getConnection("jdbc:sqlite:" + DB);
        } catch (SQLException e) {
            e.printStackTrace();
            System.exit(1);
        }

        // Use batch inserts for speed.
        try {
            connection.setAutoCommit(false);
        } catch (SQLException e) {
            e.printStackTrace();
            System.exit(1);
        }

        createDatabase();

        // Create a prepared statement to use when inserting entries.
        try {
            tempInsertStatement = connection.prepareStatement("INSERT INTO "
                    + TEMP_TABLE_NAME + " VALUES (?, ?, ?, ?, ?, ?)");
            finalInsertStatement = connection.prepareStatement("INSERT INTO "
                    + FINAL_TABLE_NAME + " VALUES (NULL, ?, ?, ?, ?, ?, ?)");
        } catch (SQLException e) {
            e.printStackTrace();
            System.exit(1);
        }
    }

    /**
     * Creates the lexicon database.
     */
    public void run() {
        addEntries();
        alphabetize();
        dropTempTable();
        createIndex();
        vacuum();
        try {
            connection.close();
        } catch (SQLException e) {
            e.printStackTrace();
            System.exit(1);
        }
        System.out.println("Done.");
    }

    /**
     * Resets the database if it already exists and creates a new, empty
     * database.
     */
    private void createDatabase() {
        System.out.println("Creating lexicon database...");
        try {
            String dropTempTable = "DROP TABLE IF EXISTS " + TEMP_TABLE_NAME;
            String createTempTable = "CREATE TABLE " + TEMP_TABLE_NAME + " ("
                    + "betaNoSymbols 	VARCHAR(100), "
                    + "betaSymbols 	VARCHAR(100), "
                    + "greekFullWord 	VARCHAR(100), "
                    + "greekNoSymbols 	VARCHAR(100), "
                    + "greekLowercase VARCHAR(100), " + "entry			TEXT)";
            String dropFinalTable = "DROP TABLE IF EXISTS " + FINAL_TABLE_NAME;
            String createFinalTable = "CREATE TABLE " + FINAL_TABLE_NAME + " ("
                    + "_id          INTEGER PRIMARY KEY, "
                    + "betaNoSymbols    VARCHAR(100), "
                    + "betaSymbols  VARCHAR(100), "
                    + "greekFullWord    VARCHAR(100), "
                    + "greekNoSymbols   VARCHAR(100), "
                    + "greekLowercase VARCHAR(100), " + "entry          TEXT)";
            Statement statement = connection.createStatement();
            statement.executeUpdate(dropTempTable);
            statement.executeUpdate(createTempTable);
            statement.executeUpdate(dropFinalTable);
            statement.executeUpdate(createFinalTable);
            connection.commit();
            statement.close();
        } catch (SQLException e) {
            e.printStackTrace();
            System.exit(1);
        }
    }

    /**
     * Parses the XML file, modifies the lexicon entries, and inserts the
     * modified entries into the database.
     */
    private void addEntries() {
        System.out.println("Inserting entries...");

        try {
            BufferedReader in = new BufferedReader(new FileReader(FILE));
            StringBuilder xml = new StringBuilder();

            // Extract the XML for each lexicon entry, then process it.
            while (in.ready()) {
                String line = in.readLine();
                if (line.startsWith("<entry ")) {
                    xml.delete(0, xml.length()); // Reset XML.
                    xml.append(line); // Add this line to new chunk of XML.
                } else if (line.startsWith("</entry>")) {
                    xml.append(line);
                    processEntry(xml.toString());
                } else {
                    xml.append(line);
                }
            }
            in.close();

            tempInsertStatement.executeBatch();
            connection.commit();

            tempInsertStatement.close();
        } catch (FileNotFoundException e) {
            System.err.println("Error: Lexicon file not found.");
            System.exit(1);
        } catch (IOException e) {
            e.printStackTrace();
            System.exit(1);
        } catch (SQLException e) {
            e.printStackTrace();
            System.exit(1);
        }
    }

    /**
     * Modifies the specified entry and inserts it into the database.
     * 
     * @param xml
     *            the XML containing the entry to process
     */
    private void processEntry(String xml) {
        try {
            LexiconParser parser = new LexiconParser(xml);
            tempInsertStatement.setString(1, parser.getBetaNoSymbols());
            tempInsertStatement.setString(2, parser.getBetaSymbols());
            tempInsertStatement.setString(3, parser.getGreekFullWord());
            tempInsertStatement.setString(4, parser.getGreekNoSymbols());
            tempInsertStatement.setString(5, parser.getGreekLowercase());
            tempInsertStatement.setString(6, parser.getEntry());
            tempInsertStatement.addBatch();
        } catch (ParserConfigurationException e) {
            e.printStackTrace();
            System.exit(1);
        } catch (SAXException e) {
            e.printStackTrace();
            System.exit(1);
        } catch (IOException e) {
            e.printStackTrace();
            System.exit(1);
        } catch (SQLException e) {
            e.printStackTrace();
            System.exit(1);
        }
    }

    /**
     * Copies the entries from the temporary table into the final table in
     * alphabetical order.
     */
    private void alphabetize() {
        try {
            String query = "SELECT * FROM " + TEMP_TABLE_NAME
                    + " ORDER BY greekLowercase ASC";
            Statement statement = connection.createStatement();
            ResultSet rs = statement.executeQuery(query);
            while (rs.next()) {
                finalInsertStatement.setString(1, rs.getString(1));
                finalInsertStatement.setString(2, rs.getString(2));
                finalInsertStatement.setString(3, rs.getString(3));
                finalInsertStatement.setString(4, rs.getString(4));
                finalInsertStatement.setString(5, rs.getString(5));
                finalInsertStatement.setString(6, rs.getString(6));
                finalInsertStatement.addBatch();
            }

            finalInsertStatement.executeBatch();
            connection.commit();

            statement.close();
            finalInsertStatement.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    /**
     * Drops the temporary table.
     */
    private void dropTempTable() {
        String sql = "DROP TABLE " + TEMP_TABLE_NAME;
        try {
            Statement statement = connection.createStatement();
            statement.executeUpdate(sql);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    /**
     * Creates an index on the database to speed up searches.
     */
    private void createIndex() {
        System.out.println("Creating index...");

        // Create an index on the three columns matched against search queries.
        String sql = "CREATE INDEX searchIndex ON " + FINAL_TABLE_NAME
                + " (betaNoSymbols, betaSymbols, greekNoSymbols, "
                + "greekLowercase)";
        try {
            Statement statement = connection.createStatement();
            statement.executeUpdate(sql);
            statement.close();
            connection.commit();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    /**
     * Rebuilds the database in order to reduce its size.
     */
    private void vacuum() {
        System.out.println("Rebuilding database...");
        try {
            connection.setAutoCommit(true);
            Statement statement = connection.createStatement();
            statement.executeUpdate("VACUUM");
            statement.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}