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

AccessExample.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: AccessExample.java,v 12.2 2005/06/16 20:22:16 bostic Exp $
00008  */
00009 
00010 package collections.access;
00011 
00012 import java.io.File;
00013 import java.io.FileNotFoundException;
00014 import java.io.IOException;
00015 import java.io.InputStreamReader;
00016 import java.io.PrintStream;
00017 import java.util.Iterator;
00018 import java.util.Map;
00019 import java.util.SortedMap;
00020 
00021 import com.sleepycat.bind.ByteArrayBinding;
00022 import com.sleepycat.collections.StoredIterator;
00023 import com.sleepycat.collections.StoredSortedMap;
00024 import com.sleepycat.collections.TransactionRunner;
00025 import com.sleepycat.collections.TransactionWorker;
00026 import com.sleepycat.db.Database;
00027 import com.sleepycat.db.DatabaseConfig;
00028 import com.sleepycat.db.DatabaseException;
00029 import com.sleepycat.db.DatabaseType;
00030 import com.sleepycat.db.Environment;
00031 import com.sleepycat.db.EnvironmentConfig;
00032 
00042 public class AccessExample
00043          implements Runnable {
00044 
00045     // Class Variables of AccessExample class
00046     private static boolean create = true;
00047     private static final int EXIT_SUCCESS = 0;
00048     private static final int EXIT_FAILURE = 1;
00049 
00050     public static void usage() {
00051 
00052         System.out.println("usage: java " + AccessExample.class.getName() +
00053             " [-r] [database]\n");
00054         System.exit(EXIT_FAILURE);
00055     }
00056 
00062     public static void main(String[] argv) {
00063 
00064         boolean removeExistingDatabase = false;
00065         String databaseName = "access.db";
00066 
00067         for (int i = 0; i < argv.length; i++) {
00068             if (argv[i].equals("-r")) {
00069                 removeExistingDatabase = true;
00070             } else if (argv[i].equals("-?")) {
00071                 usage();
00072             } else if (argv[i].startsWith("-")) {
00073                 usage();
00074             } else {
00075                 if ((argv.length - i) != 1)
00076                     usage();
00077                 databaseName = argv[i];
00078                 break;
00079             }
00080         }
00081 
00082         try {
00083 
00084             EnvironmentConfig envConfig = new EnvironmentConfig();
00085             envConfig.setTransactional(true);
00086             envConfig.setInitializeCache(true);
00087             envConfig.setInitializeLocking(true);
00088             if (create) {
00089                 envConfig.setAllowCreate(true);
00090             }
00091             Environment env = new Environment(new File("."), envConfig);
00092             // Remove the previous database.
00093             if (removeExistingDatabase) {
00094                 env.removeDatabase(null, databaseName, null);
00095             }
00096 
00097             // create the app and run it
00098             AccessExample app = new AccessExample(env, databaseName);
00099             app.run();
00100         } catch (DatabaseException e) {
00101             e.printStackTrace();
00102             System.exit(1);
00103         } catch (FileNotFoundException e) {
00104             e.printStackTrace();
00105             System.exit(1);
00106         } catch (Exception e) {
00107             e.printStackTrace();
00108             System.exit(1);
00109         }
00110         System.exit(0);
00111     }
00112 
00113 
00114     private Database db;
00115     private SortedMap map;
00116     private Environment env;
00117 
00118 
00125     public AccessExample(Environment env, String databaseName)
00126         throws Exception {
00127 
00128         this.env = env;
00129 
00130         //
00131         // Lets mimic the db.AccessExample 100%
00132         // and use plain old byte arrays to store the key and data strings.
00133         //
00134         ByteArrayBinding keyBinding = new ByteArrayBinding();
00135         ByteArrayBinding dataBinding = new ByteArrayBinding();
00136 
00137         //
00138         // Open a data store.
00139         //
00140         DatabaseConfig dbConfig = new DatabaseConfig();
00141         if (create) {
00142             dbConfig.setAllowCreate(true);
00143             dbConfig.setType(DatabaseType.BTREE);
00144         }
00145         this.db = env.openDatabase(null, databaseName, null, dbConfig);
00146 
00147         //
00148         // Now create a collection style map view of the data store
00149         // so that it is easy to work with the data in the database.
00150         //
00151         this.map = new StoredSortedMap(db, keyBinding, dataBinding, true);
00152     }
00153 
00154 
00158     public void run() {
00159         //
00160         // Insert records into a Stored Sorted Map DatabaseImpl, where
00161         // the key is the user input and the data is the user input
00162         // in reverse order.
00163         //
00164         final InputStreamReader reader = new InputStreamReader(System.in);
00165 
00166         for (; ; ) {
00167             final String line = askForLine(reader, System.out, "input> ");
00168             if (line == null) {
00169                 break;
00170             }
00171 
00172             final String reversed =
00173                 (new StringBuffer(line)).reverse().toString();
00174 
00175             log("adding: \"" +
00176                 line + "\" : \"" +
00177                 reversed + "\"");
00178 
00179             // Do the work to add the key/data to the HashMap here.
00180             TransactionRunner tr = new TransactionRunner(env);
00181             try {
00182                 tr.run(
00183                        new TransactionWorker() {
00184                            public void doWork() {
00185                                if (!map.containsKey(line.getBytes()))
00186                                    map.put(line.getBytes(),
00187                                            reversed.getBytes());
00188                                else
00189                                    System.out.println("Key " + line +
00190                                                       " already exists.");
00191                            }
00192                        });
00193             } catch (com.sleepycat.db.DatabaseException e) {
00194                 System.err.println("AccessExample: " + e.toString());
00195                 System.exit(1);
00196             } catch (java.lang.Exception e) {
00197                 System.err.println("AccessExample: " + e.toString());
00198                 System.exit(1);
00199             }
00200         }
00201         System.out.println("");
00202 
00203         // Do the work to traverse and print the HashMap key/data
00204         // pairs here get iterator over map entries.
00205         Iterator iter = map.entrySet().iterator();
00206         try {
00207             System.out.println("Reading data");
00208             while (iter.hasNext()) {
00209                 Map.Entry entry = (Map.Entry) iter.next();
00210                 log("found \"" +
00211                     new String((byte[]) entry.getKey()) +
00212                     "\" key with data \"" +
00213                     new String((byte[]) entry.getValue()) + "\"");
00214             }
00215         } finally {
00216             // Ensure that all database iterators are closed.  This is very
00217             // important.
00218             StoredIterator.close(iter);
00219         }
00220     }
00221 
00222 
00232     String askForLine(InputStreamReader reader, PrintStream out,
00233                       String prompt) {
00234 
00235         String result = "";
00236         while (result != null && result.length() == 0) {
00237             out.print(prompt);
00238             out.flush();
00239             result = getLine(reader);
00240         }
00241         return result;
00242     }
00243 
00244 
00254     String getLine(InputStreamReader reader) {
00255 
00256         StringBuffer b = new StringBuffer();
00257         int c;
00258         try {
00259             while ((c = reader.read()) != -1 && c != '\n') {
00260                 if (c != '\r') {
00261                     b.append((char) c);
00262                 }
00263             }
00264         } catch (IOException ioe) {
00265             c = -1;
00266         }
00267 
00268         if (c == -1 && b.length() == 0) {
00269             return null;
00270         } else {
00271             return b.toString();
00272         }
00273     }
00274 
00275 
00281     private void log(String s) {
00282 
00283         System.out.println(s);
00284         System.out.flush();
00285     }
00286 }

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