Main Page | Class Hierarchy | Data Structures | Directories | File List | Data Fields | Related Pages

BtRecExample.java

00001 /*-
00002  * See the file LICENSE for redistribution information.
00003  *
00004  * Copyright (c) 1997-2005
00005  *      Sleepycat Software.  All rights reserved.
00006  *
00007  * $Id: BtRecExample.java,v 12.2 2005/06/16 20:22:47 bostic Exp $
00008  */
00009 
00010 
00011 package db;
00012 
00013 import com.sleepycat.db.*;
00014 import java.io.BufferedReader;
00015 import java.io.File;
00016 import java.io.FileNotFoundException;
00017 import java.io.FileReader;
00018 import java.io.InputStreamReader;
00019 import java.io.IOException;
00020 import java.io.PrintStream;
00021 
00022 public class BtRecExample {
00023     static final String progname =  "BtRecExample"; // Program name.
00024     static final String database =  "access.db";
00025     static final String wordlist =  "../test/wordlist";
00026 
00027     BtRecExample(BufferedReader reader)
00028         throws DatabaseException, IOException, FileNotFoundException {
00029 
00030         OperationStatus status;
00031 
00032         // Remove the previous database.
00033         File f = new File(database);
00034         f.delete();
00035 
00036         DatabaseConfig config = new DatabaseConfig();
00037 
00038         config.setErrorStream(System.err);
00039         config.setErrorPrefix(progname);
00040         config.setPageSize(1024);           // 1K page sizes.
00041 
00042         config.setBtreeRecordNumbers(true);
00043         config.setType(DatabaseType.BTREE);
00044         config.setAllowCreate(true);
00045         db = new Database(database, null, config);
00046 
00047         //
00048         // Insert records into the database, where the key is the word
00049         // preceded by its record number, and the data is the same, but
00050         // in reverse order.
00051         //
00052 
00053         for (int cnt = 1; cnt <= 1000; ++cnt) {
00054             String numstr = String.valueOf(cnt);
00055             while (numstr.length() < 4)
00056                 numstr = "0" + numstr;
00057             String buf = numstr + '_' + reader.readLine();
00058             StringBuffer rbuf = new StringBuffer(buf).reverse();
00059 
00060             StringEntry key = new StringEntry(buf);
00061             StringEntry data = new StringEntry(rbuf.toString());
00062 
00063             status = db.putNoOverwrite(null, key, data);
00064             if (status != OperationStatus.SUCCESS &&
00065                 status!= OperationStatus.KEYEXIST)
00066                 throw new DatabaseException("Database.put failed " + status);
00067         }
00068     }
00069 
00070     void run() throws DatabaseException {
00071         int recno;
00072         OperationStatus status;
00073 
00074         // Acquire a cursor for the database.
00075         cursor = db.openCursor(null, null);
00076 
00077         //
00078         // Prompt the user for a record number, then retrieve and display
00079         // that record.
00080         //
00081         InputStreamReader reader = new InputStreamReader(System.in);
00082 
00083         for (;;) {
00084             // Get a record number.
00085             String line = askForLine(reader, System.out, "recno #> ");
00086             if (line == null)
00087                 break;
00088 
00089             try {
00090                 recno = Integer.parseInt(line);
00091             } catch (NumberFormatException nfe) {
00092                 System.err.println("Bad record number: " + nfe);
00093                 continue;
00094             }
00095 
00096             //
00097             // Start with a fresh key each time, the db.get() routine returns
00098             // the key and data pair, not just the key!
00099             //
00100             RecnoStringEntry key = new RecnoStringEntry(recno, 100);
00101             RecnoStringEntry data = new RecnoStringEntry(100);
00102 
00103             status = cursor.getSearchRecordNumber(key, data, null);
00104             if (status != OperationStatus.SUCCESS)
00105                 throw new DatabaseException("Cursor.setRecno failed: " + status);
00106 
00107             // Display the key and data.
00108             show("k/d\t", key, data);
00109 
00110             // Move the cursor a record forward.
00111             status = cursor.getNext(key, data, null);
00112             if (status != OperationStatus.SUCCESS)
00113                 throw new DatabaseException("Cursor.getNext failed: " + status);
00114 
00115             // Display the key and data.
00116             show("next\t", key, data);
00117 
00118             RecnoStringEntry datano = new RecnoStringEntry(100);
00119 
00120             //
00121             // Retrieve the record number for the following record into
00122             // local memory.
00123             //
00124             status = cursor.getRecordNumber(datano, null);
00125             if (status != OperationStatus.SUCCESS &&
00126                 status != OperationStatus.NOTFOUND &&
00127                 status != OperationStatus.KEYEMPTY)
00128                 throw new DatabaseException("Cursor.get failed: " + status);
00129             else {
00130                 recno = datano.getRecordNumber();
00131                 System.out.println("retrieved recno: " + recno);
00132             }
00133         }
00134 
00135         cursor.close();
00136         cursor = null;
00137     }
00138 
00139     //
00140     // Print out the number of records in the database.
00141     //
00142     void stats() throws DatabaseException {
00143         BtreeStats stats;
00144 
00145         stats = (BtreeStats)db.getStats(null, null);
00146         System.out.println(progname + ": database contains " +
00147                stats.getNumData() + " records");
00148     }
00149 
00150     void show(String msg, RecnoStringEntry key, RecnoStringEntry data)
00151         throws DatabaseException {
00152 
00153         System.out.println(msg + key.getString() + ": " + data.getString());
00154     }
00155 
00156     public void shutdown() throws DatabaseException {
00157         if (cursor != null) {
00158             cursor.close();
00159             cursor = null;
00160         }
00161         if (db != null) {
00162             db.close();
00163             db = null;
00164         }
00165     }
00166 
00167     public static void main(String[] argv) {
00168         try {
00169             // Open the word database.
00170             FileReader freader = new FileReader(wordlist);
00171 
00172             BtRecExample app = new BtRecExample(new BufferedReader(freader));
00173 
00174             // Close the word database.
00175             freader.close();
00176             freader = null;
00177 
00178             app.stats();
00179             app.run();
00180         } catch (FileNotFoundException fnfe) {
00181             System.err.println(progname + ": unexpected open error " + fnfe);
00182             System.exit (1);
00183         } catch (IOException ioe) {
00184             System.err.println(progname + ": open " + wordlist + ": " + ioe);
00185             System.exit (1);
00186         } catch (DatabaseException dbe) {
00187             System.err.println("Exception: " + dbe);
00188             System.exit(dbe.getErrno());
00189         }
00190 
00191         System.exit(0);
00192     }
00193 
00194     // Prompts for a line, and keeps prompting until a non blank
00195     // line is returned.  Returns null on erroror.
00196     //
00197     public static String askForLine(InputStreamReader reader,
00198                                     PrintStream out, String prompt) {
00199         String result = "";
00200         while (result != null && result.length() == 0) {
00201             out.print(prompt);
00202             out.flush();
00203             result = getLine(reader);
00204         }
00205         return result;
00206     }
00207 
00208     // Not terroribly efficient, but does the job.
00209     // Works for reading a line from stdin or a file.
00210     // Returns null on EOF.  If EOF appears in the middle
00211     // of a line, returns that line, then null on next call.
00212     //
00213     public static String getLine(InputStreamReader reader) {
00214         StringBuffer b = new StringBuffer();
00215         int c;
00216         try {
00217             while ((c = reader.read()) != -1 && c != '\n') {
00218                 if (c != '\r')
00219                     b.append((char)c);
00220             }
00221         } catch (IOException ioe) {
00222             c = -1;
00223         }
00224 
00225         if (c == -1 && b.length() == 0)
00226             return null;
00227         else
00228             return b.toString();
00229     }
00230 
00231     private Cursor cursor;
00232     private Database db;
00233 
00234     // Here's an example of how you can extend DatabaseEntry in a
00235     // straightforward way to allow easy storage/retrieval of strings.
00236     // We've declared it as a static inner class, but it need not be.
00237     //
00238     static class StringEntry extends DatabaseEntry {
00239         StringEntry() {}
00240 
00241         StringEntry(String value) {
00242             setString(value);
00243         }
00244 
00245         void setString(String value) {
00246             byte[] data = value.getBytes();
00247             setData(data);
00248             setSize(data.length);
00249         }
00250 
00251         String getString() {
00252             return new String(getData(), 0, getSize());
00253         }
00254     }
00255 
00256     // Here's an example of how you can extend DatabaseEntry to store
00257     // (potentially) both recno's and strings in the same structure.
00258     //
00259     static class RecnoStringEntry extends DatabaseEntry {
00260         RecnoStringEntry(int maxsize) {
00261             this(0, maxsize);     // let other constructor do most of the work
00262         }
00263 
00264         RecnoStringEntry(int value, int maxsize) {
00265             arr = new byte[maxsize];
00266             setData(arr);                // use our local array for data
00267             setUserBuffer(maxsize, true);
00268             setRecordNumber(value);
00269         }
00270 
00271         RecnoStringEntry(String value) {
00272             byte[] data = value.getBytes();
00273             setData(data);                // use our local array for data
00274             setUserBuffer(data.length, true);
00275         }
00276 
00277         void setString(String value) {
00278             byte[] data = value.getBytes();
00279             setData(data);
00280             setSize(data.length);
00281         }
00282 
00283         String getString() {
00284             return new String(getData(), getOffset(), getSize());
00285         }
00286 
00287         byte[] arr;
00288     }
00289 }

Generated on Sun Dec 25 12:14:27 2005 for Berkeley DB 4.4.16 by  doxygen 1.4.2