KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > collections > access > AccessExample


1 /*-
2  * See the file LICENSE for redistribution information.
3  *
4  * Copyright (c) 1997,2006 Oracle. All rights reserved.
5  *
6  * $Id: AccessExample.java,v 1.22 2006/10/31 19:56:10 mark Exp $
7  */

8
9 package collections.access;
10
11 import java.io.File JavaDoc;
12 import java.io.FileNotFoundException JavaDoc;
13 import java.io.IOException JavaDoc;
14 import java.io.InputStreamReader JavaDoc;
15 import java.io.PrintStream JavaDoc;
16 import java.util.Iterator JavaDoc;
17 import java.util.Map JavaDoc;
18 import java.util.SortedMap JavaDoc;
19
20 import com.sleepycat.bind.ByteArrayBinding;
21 import com.sleepycat.collections.StoredSortedMap;
22 import com.sleepycat.collections.TransactionRunner;
23 import com.sleepycat.collections.TransactionWorker;
24 import com.sleepycat.je.Database;
25 import com.sleepycat.je.DatabaseConfig;
26 import com.sleepycat.je.DatabaseException;
27 import com.sleepycat.je.Environment;
28 import com.sleepycat.je.EnvironmentConfig;
29
30 /**
31  * AccesssExample mirrors the functionality of a class by the same name
32  * used to demonstrate the com.sleepycat.je Java API. This version makes
33  * use of the new com.sleepycat.collections.* collections style classes to make
34  * life easier.
35  *
36  *@author Gregory Burd <gburd@sleepycat.com>
37  *@created October 22, 2002
38  */

39 public class AccessExample
40          implements Runnable JavaDoc {
41
42     // Class Variables of AccessExample class
43
private static boolean create = true;
44     private static final int EXIT_FAILURE = 1;
45
46     public static void usage() {
47
48     System.out.println("usage: java " + AccessExample.class.getName() +
49             " [-r] [database]\n");
50     System.exit(EXIT_FAILURE);
51     }
52
53     /**
54      * The main program for the AccessExample class
55      *
56      *@param argv The command line arguments
57      */

58     public static void main(String JavaDoc[] argv) {
59
60     boolean removeExistingDatabase = false;
61     String JavaDoc databaseName = "access.db";
62
63     for (int i = 0; i < argv.length; i++) {
64         if (argv[i].equals("-r")) {
65         removeExistingDatabase = true;
66         } else if (argv[i].equals("-?")) {
67         usage();
68         } else if (argv[i].startsWith("-")) {
69         usage();
70         } else {
71         if ((argv.length - i) != 1)
72             usage();
73         databaseName = argv[i];
74         break;
75         }
76     }
77
78         try {
79
80             EnvironmentConfig envConfig = new EnvironmentConfig();
81             envConfig.setTransactional(true);
82             if (create) {
83                 envConfig.setAllowCreate(true);
84             }
85             Environment env = new Environment(new File JavaDoc("."), envConfig);
86         // Remove the previous database.
87
if (removeExistingDatabase) {
88                 env.removeDatabase(null, databaseName);
89             }
90
91             // create the app and run it
92
AccessExample app = new AccessExample(env, databaseName);
93             app.run();
94         } catch (DatabaseException e) {
95             e.printStackTrace();
96             System.exit(1);
97         } catch (FileNotFoundException JavaDoc e) {
98             e.printStackTrace();
99             System.exit(1);
100         } catch (Exception JavaDoc e) {
101             e.printStackTrace();
102             System.exit(1);
103         }
104         System.exit(0);
105     }
106
107
108     private Database db;
109     private SortedMap JavaDoc map;
110     private Environment env;
111
112
113     /**
114      * Constructor for the AccessExample object
115      *
116      *@param env Description of the Parameter
117      *@exception Exception Description of the Exception
118      */

119     public AccessExample(Environment env, String JavaDoc databaseName)
120     throws Exception JavaDoc {
121
122         this.env = env;
123
124         //
125
// Lets mimic the db.AccessExample 100%
126
// and use plain old byte arrays to store the key and data strings.
127
//
128
ByteArrayBinding keyBinding = new ByteArrayBinding();
129         ByteArrayBinding dataBinding = new ByteArrayBinding();
130
131         //
132
// Open a data store.
133
//
134
DatabaseConfig dbConfig = new DatabaseConfig();
135         if (create) {
136             dbConfig.setAllowCreate(true);
137         }
138         this.db = env.openDatabase(null, databaseName, dbConfig);
139
140         //
141
// Now create a collection style map view of the data store
142
// so that it is easy to work with the data in the database.
143
//
144
this.map = new StoredSortedMap(db, keyBinding, dataBinding, true);
145     }
146
147
148     /**
149      * Main processing method for the AccessExample object
150      */

151     public void run() {
152         //
153
// Insert records into a Stored Sorted Map DatabaseImpl, where
154
// the key is the user input and the data is the user input
155
// in reverse order.
156
//
157
final InputStreamReader JavaDoc reader = new InputStreamReader JavaDoc(System.in);
158
159         for (; ; ) {
160             final String JavaDoc line = askForLine(reader, System.out, "input> ");
161             if (line == null) {
162                 break;
163             }
164
165             final String JavaDoc reversed =
166         (new StringBuffer JavaDoc(line)).reverse().toString();
167
168             log("adding: \"" +
169         line + "\" : \"" +
170         reversed + "\"");
171
172             // Do the work to add the key/data to the HashMap here.
173
TransactionRunner tr = new TransactionRunner(env);
174             try {
175                 tr.run(
176                new TransactionWorker() {
177                public void doWork() {
178                                try {
179                                    if (!map.containsKey(line.getBytes("UTF-8")))
180                                        map.put(line.getBytes("UTF-8"),
181                                                reversed.getBytes("UTF-8"));
182                                    else
183                                        System.out.println("Key " + line +
184                                                           " already exists.");
185                                } catch (Exception JavaDoc e) {
186                                    System.err.println("doWork: " + e);
187                                }
188                }
189                });
190             } catch (com.sleepycat.je.DatabaseException e) {
191                 System.err.println("AccessExample: " + e);
192                 System.exit(1);
193             } catch (java.lang.Exception JavaDoc e) {
194                 System.err.println("AccessExample: " + e);
195                 System.exit(1);
196             }
197         }
198         System.out.println("");
199
200         // Do the work to traverse and print the HashMap key/data
201
// pairs here get iterator over map entries.
202
Iterator JavaDoc iter = map.entrySet().iterator();
203         System.out.println("Reading data");
204         while (iter.hasNext()) {
205             Map.Entry JavaDoc entry = (Map.Entry JavaDoc) iter.next();
206             log("found \"" +
207                 new String JavaDoc((byte[]) entry.getKey()) +
208                 "\" key with data \"" +
209                 new String JavaDoc((byte[]) entry.getValue()) + "\"");
210         }
211     }
212
213
214     /**
215      * Prompts for a line, and keeps prompting until a non blank line is
216      * returned. Returns null on error.
217      *
218      *@param reader stream from which to read user input
219      *@param out stream on which to prompt for user input
220      *@param prompt prompt to use to solicit input
221      *@return the string supplied by the user
222      */

223     String JavaDoc askForLine(InputStreamReader JavaDoc reader, PrintStream JavaDoc out,
224                       String JavaDoc prompt) {
225
226         String JavaDoc result = "";
227         while (result != null && result.length() == 0) {
228             out.print(prompt);
229             out.flush();
230             result = getLine(reader);
231         }
232         return result;
233     }
234
235
236     /**
237      * Read a single line. Gets the line attribute of the AccessExample object
238      * Not terribly efficient, but does the job. Works for reading a line from
239      * stdin or a file.
240      *
241      *@param reader stream from which to read the line
242      *@return either a String or null on EOF, if EOF appears in the
243      * middle of a line, returns that line, then null on next call.
244      */

245     String JavaDoc getLine(InputStreamReader JavaDoc reader) {
246
247         StringBuffer JavaDoc b = new StringBuffer JavaDoc();
248         int c;
249         try {
250             while ((c = reader.read()) != -1 && c != '\n') {
251                 if (c != '\r') {
252                     b.append((char) c);
253                 }
254             }
255         } catch (IOException JavaDoc ioe) {
256             c = -1;
257         }
258
259         if (c == -1 && b.length() == 0) {
260             return null;
261         } else {
262             return b.toString();
263         }
264     }
265
266
267     /**
268      * A simple log method.
269      *
270      *@param s The string to be logged.
271      */

272     private void log(String JavaDoc s) {
273
274         System.out.println(s);
275         System.out.flush();
276     }
277 }
278
Popular Tags