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)
    to.writeByte(booth.address[i]);
  to.writeString(booth.state);
  to.writeString(booth.city);
  to.writeString(booth.district);
}

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,
                   ti.readString(),
                   ti.readString(),
                   ti.readString());
}

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
    .entryToObject(dataEntry);

  // 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.
  resultEntry
    .setData(key.getBytes("UTF-8"));

  return true;
}

Listing 3: Creating and opening a database

private Database
openDatabase(boolean readOnly,
             String databaseName)
{
  DatabaseConfig config =
    new DatabaseConfig();
  config.setAllowCreate(!readOnly);
  config.setTransactional(!readOnly);
  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 =
         booth.votes.iterator();
       iter.hasNext(); )
    storeVote(txn, (Vote)iter.next());
  txn.commitNoSync();
}
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 =
      vote.key.getBytes("UTF-8");
    DatabaseEntry key =
      new DatabaseEntry(keyBytes);

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

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

Listing 6: Simple key lookup

// A vote key that's known to exist
String voteKey = "192.168.0.3:1";
byte[] keyBytes =
  voteKey.getBytes("UTF-8"));
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()
    .entryToObject(data);
  // (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))
    break;

  Booth booth = (Booth)binding
    .entryToObject(foundData));
  // (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
                .getBoothByStateDb(),
                new ByteArrayBinding(),
                new BoothBinding(),
                false);

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.
StoredIterator.close(iter);

Listing 9: Counting records using a Map

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

// Pass in the raw data, not a
// DatabaseEntry
int race = Vote.RACE_PRESIDENT;
Collection votes =
  map.duplicates(Util.intToBytes(race));
// (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.