001: /*-
002: * See the file LICENSE for redistribution information.
003: *
004: * Copyright (c) 1997,2008 Oracle. All rights reserved.
005: *
006: * $Id: AccessExample.java,v 1.22.2.2 2008/01/07 15:13:59 cwl Exp $
007: */
008:
009: package collections.access;
010:
011: import java.io.File;
012: import java.io.FileNotFoundException;
013: import java.io.IOException;
014: import java.io.InputStreamReader;
015: import java.io.PrintStream;
016: import java.util.Iterator;
017: import java.util.Map;
018: import java.util.SortedMap;
019:
020: import com.sleepycat.bind.ByteArrayBinding;
021: import com.sleepycat.collections.StoredSortedMap;
022: import com.sleepycat.collections.TransactionRunner;
023: import com.sleepycat.collections.TransactionWorker;
024: import com.sleepycat.je.Database;
025: import com.sleepycat.je.DatabaseConfig;
026: import com.sleepycat.je.DatabaseException;
027: import com.sleepycat.je.Environment;
028: import com.sleepycat.je.EnvironmentConfig;
029:
030: /**
031: * AccesssExample mirrors the functionality of a class by the same name
032: * used to demonstrate the com.sleepycat.je Java API. This version makes
033: * use of the new com.sleepycat.collections.* collections style classes to make
034: * life easier.
035: *
036: *@author Gregory Burd <gburd@sleepycat.com>
037: *@created October 22, 2002
038: */
039: public class AccessExample implements Runnable {
040:
041: // Class Variables of AccessExample class
042: private static boolean create = true;
043: private static final int EXIT_FAILURE = 1;
044:
045: public static void usage() {
046:
047: System.out.println("usage: java "
048: + AccessExample.class.getName() + " [-r] [database]\n");
049: System.exit(EXIT_FAILURE);
050: }
051:
052: /**
053: * The main program for the AccessExample class
054: *
055: *@param argv The command line arguments
056: */
057: public static void main(String[] argv) {
058:
059: boolean removeExistingDatabase = false;
060: String databaseName = "access.db";
061:
062: for (int i = 0; i < argv.length; i++) {
063: if (argv[i].equals("-r")) {
064: removeExistingDatabase = true;
065: } else if (argv[i].equals("-?")) {
066: usage();
067: } else if (argv[i].startsWith("-")) {
068: usage();
069: } else {
070: if ((argv.length - i) != 1)
071: usage();
072: databaseName = argv[i];
073: break;
074: }
075: }
076:
077: try {
078:
079: EnvironmentConfig envConfig = new EnvironmentConfig();
080: envConfig.setTransactional(true);
081: if (create) {
082: envConfig.setAllowCreate(true);
083: }
084: Environment env = new Environment(new File("."), envConfig);
085: // Remove the previous database.
086: if (removeExistingDatabase) {
087: env.removeDatabase(null, databaseName);
088: }
089:
090: // create the app and run it
091: AccessExample app = new AccessExample(env, databaseName);
092: app.run();
093: } catch (DatabaseException e) {
094: e.printStackTrace();
095: System.exit(1);
096: } catch (FileNotFoundException e) {
097: e.printStackTrace();
098: System.exit(1);
099: } catch (Exception e) {
100: e.printStackTrace();
101: System.exit(1);
102: }
103: System.exit(0);
104: }
105:
106: private Database db;
107: private SortedMap map;
108: private Environment env;
109:
110: /**
111: * Constructor for the AccessExample object
112: *
113: *@param env Description of the Parameter
114: *@exception Exception Description of the Exception
115: */
116: public AccessExample(Environment env, String databaseName)
117: throws Exception {
118:
119: this .env = env;
120:
121: //
122: // Lets mimic the db.AccessExample 100%
123: // and use plain old byte arrays to store the key and data strings.
124: //
125: ByteArrayBinding keyBinding = new ByteArrayBinding();
126: ByteArrayBinding dataBinding = new ByteArrayBinding();
127:
128: //
129: // Open a data store.
130: //
131: DatabaseConfig dbConfig = new DatabaseConfig();
132: if (create) {
133: dbConfig.setAllowCreate(true);
134: }
135: this .db = env.openDatabase(null, databaseName, dbConfig);
136:
137: //
138: // Now create a collection style map view of the data store
139: // so that it is easy to work with the data in the database.
140: //
141: this .map = new StoredSortedMap(db, keyBinding, dataBinding,
142: true);
143: }
144:
145: /**
146: * Main processing method for the AccessExample object
147: */
148: public void run() {
149: //
150: // Insert records into a Stored Sorted Map DatabaseImpl, where
151: // the key is the user input and the data is the user input
152: // in reverse order.
153: //
154: final InputStreamReader reader = new InputStreamReader(
155: System.in);
156:
157: for (;;) {
158: final String line = askForLine(reader, System.out,
159: "input> ");
160: if (line == null) {
161: break;
162: }
163:
164: final String reversed = (new StringBuffer(line)).reverse()
165: .toString();
166:
167: log("adding: \"" + line + "\" : \"" + reversed + "\"");
168:
169: // Do the work to add the key/data to the HashMap here.
170: TransactionRunner tr = new TransactionRunner(env);
171: try {
172: tr.run(new TransactionWorker() {
173: public void doWork() {
174: try {
175: if (!map
176: .containsKey(line.getBytes("UTF-8")))
177: map.put(line.getBytes("UTF-8"),
178: reversed.getBytes("UTF-8"));
179: else
180: System.out.println("Key " + line
181: + " already exists.");
182: } catch (Exception e) {
183: System.err.println("doWork: " + e);
184: }
185: }
186: });
187: } catch (com.sleepycat.je.DatabaseException e) {
188: System.err.println("AccessExample: " + e);
189: System.exit(1);
190: } catch (java.lang.Exception e) {
191: System.err.println("AccessExample: " + e);
192: System.exit(1);
193: }
194: }
195: System.out.println("");
196:
197: // Do the work to traverse and print the HashMap key/data
198: // pairs here get iterator over map entries.
199: Iterator iter = map.entrySet().iterator();
200: System.out.println("Reading data");
201: while (iter.hasNext()) {
202: Map.Entry entry = (Map.Entry) iter.next();
203: log("found \"" + new String((byte[]) entry.getKey())
204: + "\" key with data \""
205: + new String((byte[]) entry.getValue()) + "\"");
206: }
207: }
208:
209: /**
210: * Prompts for a line, and keeps prompting until a non blank line is
211: * returned. Returns null on error.
212: *
213: *@param reader stream from which to read user input
214: *@param out stream on which to prompt for user input
215: *@param prompt prompt to use to solicit input
216: *@return the string supplied by the user
217: */
218: String askForLine(InputStreamReader reader, PrintStream out,
219: String prompt) {
220:
221: String result = "";
222: while (result != null && result.length() == 0) {
223: out.print(prompt);
224: out.flush();
225: result = getLine(reader);
226: }
227: return result;
228: }
229:
230: /**
231: * Read a single line. Gets the line attribute of the AccessExample object
232: * Not terribly efficient, but does the job. Works for reading a line from
233: * stdin or a file.
234: *
235: *@param reader stream from which to read the line
236: *@return either a String or null on EOF, if EOF appears in the
237: * middle of a line, returns that line, then null on next call.
238: */
239: String getLine(InputStreamReader reader) {
240:
241: StringBuffer b = new StringBuffer();
242: int c;
243: try {
244: while ((c = reader.read()) != -1 && c != '\n') {
245: if (c != '\r') {
246: b.append((char) c);
247: }
248: }
249: } catch (IOException ioe) {
250: c = -1;
251: }
252:
253: if (c == -1 && b.length() == 0) {
254: return null;
255: } else {
256: return b.toString();
257: }
258: }
259:
260: /**
261: * A simple log method.
262: *
263: *@param s The string to be logged.
264: */
265: private void log(String s) {
266:
267: System.out.println(s);
268: System.out.flush();
269: }
270: }
|