4ae5980550412a592da2c9f0771a25ff28faf022
[phpeclipse.git] / archive / net.sourceforge.phpeclipse.wiki / src / net / sourceforge / phpeclipse / wiki / sql / WikipediaDB.java
1 package net.sourceforge.phpeclipse.wiki.sql;
2
3 import java.sql.Connection;
4 import java.sql.DriverManager;
5 import java.sql.PreparedStatement;
6 import java.sql.ResultSet;
7 import java.sql.ResultSetMetaData;
8 import java.sql.SQLException;
9 import java.sql.Statement;
10 import java.util.ArrayList;
11 import java.util.List;
12
13 import net.sourceforge.phpeclipse.wiki.editor.WikiEditorPlugin;
14 import net.sourceforge.phpeclipse.wiki.internal.ConfigurationManager;
15 import net.sourceforge.phpeclipse.wiki.internal.IConfiguration;
16 import net.sourceforge.phpeclipse.wiki.preferences.Util;
17
18 public class WikipediaDB {
19
20   public static void dump(ResultSet rs) throws SQLException {
21
22     // the order of the rows in a cursor
23     // are implementation dependent unless you use the SQL ORDER statement
24     ResultSetMetaData meta = rs.getMetaData();
25     int colmax = meta.getColumnCount();
26     int i;
27     Object o = null;
28
29     // the result set is a cursor into the data. You can only
30     // point to one row at a time
31     // assume we are pointing to BEFORE the first row
32     // rs.next() points to next row and returns true
33     // or false if there is no next row, which breaks the loop
34     for (; rs.next();) {
35       for (i = 0; i < colmax; ++i) {
36         o = rs.getObject(i + 1); // Is SQL the first column is indexed
37         // with 1 not 0
38         System.out.print(o.toString() + " ");
39       }
40
41       System.out.println(" ");
42     }
43   }
44
45   public static ArrayList getResultAsString(ResultSet rs) throws SQLException {
46     ArrayList list = new ArrayList();
47     int maxProposals = 500;
48     // the order of the rows in a cursor
49     // are implementation dependent unless you use the SQL ORDER statement
50     ResultSetMetaData meta = rs.getMetaData();
51     int colmax = meta.getColumnCount();
52     int i;
53     Object o = null;
54
55     // the result set is a cursor into the data. You can only
56     // point to one row at a time
57     // assume we are pointing to BEFORE the first row
58     // rs.next() points to next row and returns true
59     // or false if there is no next row, which breaks the loop
60     for (; rs.next();) {
61       for (i = 0; i < colmax; ++i) {
62         o = rs.getObject(i + 1); // Is SQL the first column is indexed
63         // with 1 not 0
64         list.add(o.toString());
65         maxProposals--;
66         if (maxProposals <= 0) {
67           return list;
68         }
69       }
70     }
71     return list;
72   }
73
74   public static String getFirstRow(ResultSet rs) throws SQLException {
75     // the order of the rows in a cursor
76     // are implementation dependent unless you use the SQL ORDER statement
77     ResultSetMetaData meta = rs.getMetaData();
78     int colmax = meta.getColumnCount();
79     int i;
80     Object o = null;
81
82     // the result set is a cursor into the data. You can only
83     // point to one row at a time
84     // assume we are pointing to BEFORE the first row
85     // rs.next() points to next row and returns true
86     // or false if there is no next row, which breaks the loop
87     for (; rs.next();) {
88       for (i = 0; i < colmax; ++i) {
89         o = rs.getObject(i + 1); // Is SQL the first column is indexed
90         // with 1 not 0
91         return o.toString();
92       }
93     }
94     return null;
95   }
96
97   public static void main(String[] args) {
98     WikipediaDB db = null;
99
100     try {
101       db = new WikipediaDB();
102     } catch (Exception ex1) {
103       ex1.printStackTrace(); // could not start db
104       return; // bye bye
105     }
106
107     try {
108       // do a query
109       ArrayList list = db.queryPrefixTexts("Programming:PHP");
110       //      db.query("SELECT * FROM cur WHERE cur_title like 'Programming:PHP%'"); // WHERE num_col < 250");
111       for (int i = 0; i < list.size(); i++) {
112         System.out.println(list.get(i).toString());
113       }
114       // at end of program
115       db.shutdown();
116     } catch (SQLException ex3) {
117       ex3.printStackTrace();
118     }
119   }
120
121   //  private static void readFile(WikipediaDB db, String filename) {
122   //    FileReader fileReader;
123   //    try {
124   //      BufferedReader bufferedReader = new BufferedReader(new FileReader(filename));
125   //      // String line;
126   //      LineTokenizer lineTokenizer = new LineTokenizer();
127   //      StringBuffer line = new StringBuffer(1024);
128   //      while (lineTokenizer.getToken(line, bufferedReader)) {
129   //        if (line.length() == 0) {
130   //          // this should not happen
131   //        } else {
132   //          // try {
133   //          // db.update("INSERT INTO wp_titles(title) VALUES('" + line + "')");
134   //          System.out.println(line);
135   //          line.delete(0, line.length());
136   //          // addLine(line);
137   //          // } catch (SQLException ex3) {
138   //          //// ex3.printStackTrace();
139   //          // }
140   //        }
141   //      }
142   //      bufferedReader.close();
143   //    } catch (FileNotFoundException e) {
144   //      // ignore this
145   //      // TODO DialogBox which asks the user if she/he likes to build new index?
146   //    } catch (IOException e) {
147   //      // TODO Auto-generated catch block
148   //      e.printStackTrace();
149   //    }
150   //  }
151
152   private final Connection conn;
153
154   private final PreparedStatement fGetPrefixTitles;
155
156   private final PreparedStatement fGetPrefixTexts;
157
158   private final PreparedStatement fGetExactText;
159
160   public WikipediaDB() throws Exception // note more general exception
161   {
162
163     // Load the Database Engine JDBC driver
164     // mysql-connector.jar should be in the class path or made part of the current jar
165     Class.forName("com.mysql.jdbc.Driver");
166
167     // determine the first SQL configuration
168     IConfiguration configuration = null;
169     try {
170       List allConfigsList = ConfigurationManager.getInstance().getConfigurations();
171       ArrayList configsList = new ArrayList();
172       for (int i = 0; i < allConfigsList.size(); i++) {
173         configuration = (IConfiguration) allConfigsList.get(i);
174         if (configuration.getType().equals(WikiEditorPlugin.WIKIPEDIA_SQL)) {
175           break;
176         }
177         configuration = null;
178       }
179     } catch (Throwable th) {
180       // 
181     }
182
183     // connect to the database. This will load the db files and start the
184     // database if it is not alread running.
185     // db_file_name_prefix is used to open or create files that hold the state
186     // of the db.
187     // It can contain directory names relative to the
188     // current working directory
189     if (configuration != null) {
190       conn = DriverManager.getConnection(configuration.getURL(), configuration.getUser(), configuration.getPassword());
191     } else {
192       // default configuration for XAMPP distribution
193       conn = DriverManager.getConnection("jdbc:mysql://localhost/wikidb", // filenames
194           "root", // username
195           ""); // password
196     }
197     fGetPrefixTitles = conn.prepareStatement("SELECT cur_title FROM cur WHERE LOWER( cur_title ) like ?");
198     fGetPrefixTexts = conn.prepareStatement("SELECT cur_text FROM cur WHERE LOWER( cur_title ) like ?");
199     fGetExactText = conn.prepareStatement("SELECT cur_text FROM cur WHERE cur_title = ?");
200   }
201
202   //use for SQL commands CREATE and SELECT
203   public synchronized void query(String expression) throws SQLException {
204
205     Statement st = null;
206     ResultSet rs = null;
207
208     st = conn.createStatement(); // statement objects can be reused with
209     // repeated calls to execute but we
210     // choose to make a new one each time
211     rs = st.executeQuery(expression); // run the query
212
213     // do something with the result set.
214     dump(rs);
215     st.close(); // NOTE!! if you close a statement the associated ResultSet is
216     // closed too
217     // so you should copy the contents to some other object.
218     // the result set is invalidated also if you recycle an Statement
219     // and try to execute some other query before the result set has been
220     // completely examined.
221   }
222
223   public synchronized ArrayList queryPrefixTitle(String prefix) throws SQLException {
224     fGetPrefixTitles.setString(1, prefix.toLowerCase() + '%');
225     ResultSet rs = null;
226     rs = fGetPrefixTitles.executeQuery(); // run the query
227     // do something with the result set.
228     ArrayList list = getResultAsString(rs);
229     if (list != null) {
230       // convert to editor format
231       for (int i = 0; i < list.size(); i++) {
232         list.set(i, Util.db2TitleLink((String) list.get(i)));
233       }
234     }
235     return list;
236     //    st.close(); // NOTE!! if you close a statement the associated ResultSet is
237   }
238
239   public synchronized ArrayList queryPrefixTexts(String prefix) throws SQLException {
240     fGetPrefixTexts.setString(1, prefix.toLowerCase() + '%');
241     ResultSet rs = null;
242     rs = fGetPrefixTexts.executeQuery(); // run the query
243     // do something with the result set.
244     return getResultAsString(rs);
245     //    st.close(); // NOTE!! if you close a statement the associated ResultSet is
246   }
247
248   public synchronized String queryExactText(String prefix) throws SQLException {
249     fGetExactText.setString(1, prefix);
250     ResultSet rs = null;
251     rs = fGetExactText.executeQuery(); // run the query
252     // do something with the result set.
253     return getFirstRow(rs);
254     //    st.close(); // NOTE!! if you close a statement the associated ResultSet is
255   }
256
257   public static String getExactText(String prefix) {
258     WikipediaDB db = null;
259
260     try {
261       db = new WikipediaDB();
262     } catch (Exception ex1) {
263       ex1.printStackTrace(); // could not start db
264       return null; // bye bye
265     }
266
267     try {
268       String text = db.queryExactText(prefix);
269       db.shutdown();
270       return text;
271     } catch (SQLException ex3) {
272       ex3.printStackTrace();
273     }
274     return null;
275   }
276
277   public void shutdown() throws SQLException {
278
279     conn.close(); // if there are no other open connection
280     // db writes out to files and shuts down
281     // this happens anyway at garbage collection
282     // when program ends
283   }
284
285   //use for SQL commands DROP and INSERT and UPDATE
286   public synchronized void update(String expression) throws SQLException {
287
288     Statement st = null;
289
290     st = conn.createStatement(); // statements
291
292     int i = st.executeUpdate(expression); // run the query
293
294     if (i == -1) {
295       System.out.println("db error : " + expression);
296     }
297
298     st.close();
299   }
300 }