HomeDigital EditionSys-Con RadioSearch Java Cd
Advanced Java AWT Book Reviews/Excerpts Client Server Corba Editorials Embedded Java Enterprise Java IDE's Industry Watch Integration Interviews Java Applet Java & Databases Java & Web Services Java Fundamentals Java Native Interface Java Servlets Java Beans J2ME Libraries .NET Object Orientation Observations/IMHO Product Reviews Scalability & Performance Security Server Side Source Code Straight Talking Swing Threads Using Java with others Wireless XML

"Building Applications with Berkeley DB Java Edition"
Vol. 9, Issue 9, p. 49


Listing 1: BoothBinding

public void
objectToEntry(Object object, TupleOutput to)
    throws IOException
  Booth booth = (Booth)object;
  for (int i = 0; i < 4; ++i)

public Object
entryToObject(TupleInput ti)
    throws IOException
  byte[] address = new byte[4];
  for (int i = 0; i < 4; ++i)
    address[i] = ti.readByte();
  return new Booth(address,

Listing 2: Creating a secondary key

public boolean createSecondaryKey(
    SecondaryDatabase db,
    DatabaseEntry keyEntry,
    DatabaseEntry dataEntry,
    DatabaseEntry resultEntry)
    throws DatabaseException
  // (Error handling code skipped)

  // The vote is in a dataEntry. Use
  // the dataBinding passed in to this
  // SecondaryKeyCreator's constructor
  // to convert it into a Vote object.
  Vote vote = (Vote)dataBinding

  // Create a string key
  String key = "" + vote.race + ':'
    + vote.candidateParty;

  // Convert the key string to a byte
  // array and give it to resultEntry,
  // which is the DatabaseEntry we're
  // supposed to fill with the secondary
  // key.

  return true;

Listing 3: Creating and opening a database

private Database
openDatabase(boolean readOnly,
             String databaseName)
  DatabaseConfig config =
    new DatabaseConfig();
  Database db = null;
  try {
    // If transactional, will use
    // auto-commit during the open
    db = dbEnvironment
      .openDatabase(null, databaseName, config);
  catch (DatabaseException dbe) {
    // ...
  return db;

Listing 4: Transactions

Transaction txn = null;
try {
  txn = dbEnvironment.getEnv()
    .beginTransaction(null, null);
  storeBooth(txn, booth);
  for (Iterator iter =
       iter.hasNext(); )
    storeVote(txn, (Vote)iter.next());
catch (Exception e) {
  // DatabaseException or IOException
  try { if (txn != null) txn.abort(); }
  catch (DatabaseException dbe2) {}
  // Handle original exception

Listing 5: Storing votes from a voting booth

protected void
storeVote(Transaction txn, Vote vote)
  throws DatabaseException, IOException
    byte[] keyBytes =
    DatabaseEntry key =
      new DatabaseEntry(keyBytes);

  DatabaseEntry data =
    new DatabaseEntry();
  VoteBinding binding =
    new VoteBinding();
  binding.objectToEntry(vote, data);

  // Store the vote
    .put(txn, key, data);

Listing 6: Simple key lookup

// A vote key that's known to exist
String voteKey = "";
byte[] keyBytes =
DatabaseEntry key =
  new DatabaseEntry(keyBytes);

DatabaseEntry data =
  new DatabaseEntry();

OperationStatus status = dbEnvironment
  .getVoteDb().get(null, key, data, null);
if (status == OperationStatus.SUCCESS) {
  Vote vote = (Vote)new VoteBinding()
  // (print the vote here)
else // handle error

Listing 7: Booths by state using a cursor

Cursor cursor = dbEnvironment
  .getBoothByStateDb().openCursor(null, null);

// key is the state string as a byte
// array
DatabaseEntry foundKey =
  new DatabaseEntry(key);
DatabaseEntry foundData =
  new DatabaseEntry();
BoothBinding binding =
  new BoothBinding();

OperationStatus status =
  cursor.getSearchKey(foundKey, foundData, null);
while (status
       == OperationStatus.SUCCESS)
  // Cursor keeps going past selected
  // state, so stop when we see a
  // different state.
  String foundState =
    new String(foundKey.getData());
  if (!state.equals(foundState))

  Booth booth = (Booth)binding
  // (print the booth here)
  status = cursor.getNext(foundKey, foundData, null);

Listing 8: Booths by state using an Iterator

// Get a map over the vote database.
StoredMap map =
  new StoredMap(dbEnvironment
                new ByteArrayBinding(),
                new BoothBinding(),

Collection booths = map.duplicates(key);
Iterator iter;
for (iter = booths.iterator();
     iter.hasNext(); )
  Booth booth = (Booth)iter.next();
  // (print the booth here)

// Remember to close the iterator.

Listing 9: Counting records using a Map

// Get a map over the vote secondary
// database.
StoredMap map =
  new StoredMap(dbEnvironment
                new ByteArrayBinding(),
                new VoteBinding(),

// Pass in the raw data, not a
// DatabaseEntry
int race = Vote.RACE_PRESIDENT;
Collection votes =
// (print map.size() here)

All Rights Reserved
Copyright ©  2004 SYS-CON Media, Inc.
  E-mail: [email protected]

Java and Java-based marks are trademarks or registered trademarks of Sun Microsystems, Inc. in the United States and other countries. SYS-CON Publications, Inc. is independent of Sun Microsystems, Inc.