Package org.sf.mustru.utils

Source Code of org.sf.mustru.utils.DbTools

package org.sf.mustru.utils;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.apache.log4j.Logger;
import org.sf.mustru.docs.StoreAbleInterface;

//import com.sleepycat.je.CheckpointConfig;
import com.sleepycat.bind.tuple.TupleBinding;
import com.sleepycat.je.Cursor;
import com.sleepycat.je.Database;
import com.sleepycat.je.DatabaseConfig;
import com.sleepycat.je.DatabaseEntry;
import com.sleepycat.je.DatabaseException;
import com.sleepycat.je.Environment;
import com.sleepycat.je.EnvironmentConfig;
import com.sleepycat.je.LockMode;
import com.sleepycat.je.OperationStatus;
import com.sleepycat.je.SecondaryConfig;
import com.sleepycat.je.SecondaryCursor;
import com.sleepycat.je.SecondaryDatabase;
import com.sleepycat.je.SecondaryKeyCreator;

/**
* A collection of methods to manage the Berkeley database.
* <ul>
* <li> closeDB    Close the current primary database<br>
* <li> closeEnv  Release all environment resources<br>
* <li> closeSecDB  Close the current sec. database<br>
* <li> createDB  Create a primary database with optional duplicate flag parms<br>
* <li> createSecDB  Create a sec. database<br>
* <li> delete    Delete an entry from the database<br>
* <li> dropDB    Drop the primary database<br>
* <li> dropSecDB  Drop the secondary database<br>
* <li> exists    Check if an entry exists with the specified key<br>
* <li> existsDB  Check if a database exists with passed name<br>
* <li> fetch    Fetch an entry with specified key<br>
* <li> fetchArray  Fetch an array of entries with a partial key<br>
* <li> fetchSec  Fetch an entry with the specified sec. key<br>
* <li> fetchSecArray  Fetch an array of sec. entries with a partial sec. key<br>
* <li> getNextKey  Get the next key for the database<br>
* <li> insert    Add an entry to the database<br>
* <li> openDB    Open the primary database<br>
* <li> openEnv    Open an environment<br>
* <li> update    Update the database with new entry<br>
* </ul>
*/

public class DbTools
{
static Logger logger = Logger.getLogger(DbTools.class.getName());
private Environment env = null;          //*-- handle to the environment
private String DBDIR = "";            //*-- dir containing the environment
private HashMap<String,Database> dbMap = null;          //*-- hash of database names tp databases in the environment
private Database currentDB = null;        //*-- current database handle
private SecondaryDatabase secDB = null;      //*-- secondary database handle

/**
  * Create the database environment based on the read only flag
  * @param dirname Name of directory
  * @param readOnly boolean indicating read only
  * @return boolean
  */
public synchronized boolean openEnv(String dirname, boolean readOnly)
{
  this.DBDIR = dirname;
  if (env != null) return false;
  try
  {
   EnvironmentConfig econfig = new EnvironmentConfig();
   econfig.setAllowCreate(!readOnly); econfig.setReadOnly(readOnly);
   //econfig.setTransactional(true);
   env = new Environment( new File (dirname), econfig);

   //*-- initializes the database hash with the list of databases in the environment
   dbMap = new HashMap<String,Database>();
   List dbList = env.getDatabaseNames();
   for (int i = 0; i < dbList.size(); i++) dbMap.put ( (String) dbList.get(i), null);
  }
  catch (DatabaseException dbe)
  { logger.error("Could not create DB environment " + dbe.getMessage()); return false; }
  return true;
}

/**
  * Release the environment resources
  * @return boolean
  */
public synchronized boolean closeEnv()
{
  try
  { if (env == null) return false;  
  List dbnames = env.getDatabaseNames();
  for (int i = 0; i < dbnames.size(); i++)
  { String dbname = (String) dbnames.get(i);
  Database dbHandle = (Database) dbMap.get(dbname);
  if (dbHandle != null) try { dbHandle.close(); } catch (DatabaseException de) { }
  }
  env.sync(); env.close();
  /*  boolean anyCleaned = false;
     while (env.cleanLog() > 0) anyCleaned = true;
     if (anyCleaned)
      { CheckpointConfig force = new CheckpointConfig();
        force.setForce(true);
        env.checkpoint(force);
      }*/
  env = null;
  }
  catch (DatabaseException dbe) { return false; }

  return true;
}

public synchronized boolean createDB(String dbname, boolean createFlag)
{ return (createDB(dbname, createFlag, false) ); }

/**
  * Create a database using the passed name for a db that does not currently exist.
  * @param dbname String Name of the database
  * @param createFlag boolean Create a database, even one exists with the same name
  * @param dupFlag boolean Duplicate flag (optional)
  * @return boolean
  */
public synchronized boolean createDB(String dbname, boolean createFlag, boolean dupFlag)
{

  if  ( (dbname == null) || (dbname.equals("") ) )  return false;      
  try
  {
   //*-- open the environment
   if (env == null)  { openEnv(DBDIR, false); if (env == null) return false; }

   //*-- create the primary database handle
   DatabaseConfig dbconfig = new DatabaseConfig();
   dbconfig.setAllowCreate(true);        //*-- allow creation of database 
   dbconfig.setSortedDuplicates(dupFlag);     //*-- no dups
   dbconfig.setExclusiveCreate(createFlag);   //*-- if true, disallow opening of an existing database
   dbconfig.setReadOnly(false);          //*-- set r/w status of the database
   //dbconfig.setTransactional(true);
   currentDB = env.openDatabase(null, dbname, dbconfig);
   dbMap.put(dbname, currentDB );
  }
  catch (DatabaseException dbe)
  { logger.error("Failed to create DB " + dbname + " " + dbe.getMessage() ); return false; }

  return true;
}

/**
  * Drop an existing database
  * @param dbname String Name of database
  * @return boolean
  */
public synchronized boolean dropDB(String dbname)
{
  boolean retval = false;
  try
 
   //*-- first, get the environment
   if (env == null) { openEnv(DBDIR, false); if (env == null) return retval; }
   if (!(existsDB(dbname))) return retval;

   setCurrentDB(dbname);
   Database dbe = (Database) dbMap.get(dbname);
   if (dbe != null)
   { dbe.close();
   List secDBList = dbe.getSecondaryDatabases();
   for (int i = 0; i < secDBList.size(); i++)
   { String secDBname = (String) secDBList.get(i);
   dropSecDB(secDBname);
   }
   }
   env.removeDatabase(null,  dbname);  
   dbMap.remove(dbname);

   retval = true;
  }
  catch (DatabaseException dbe) { logger.error("Failed to drop " +  dbname + " " + dbe.getMessage())}

  return retval;
}
/**
  * Check if a database exists in the environment
  * @param dbname String Name of database
  * @return boolean
  */
public synchronized boolean existsDB(String dbname)
{
  boolean retval = false;

  try
  {
   //*-- first, get the environment
   if (env == null) { openEnv(DBDIR, false); if (env == null) return retval; }
   List dbnames = env.getDatabaseNames();
   for (int i = 0; i < dbnames.size(); i++)
   { String db = (String) dbnames.get(i);
   if (db.equalsIgnoreCase(dbname)) return true;
   }
  }
  catch (DatabaseException dbe)
  { logger.error("Could not get a list of DB names" + dbe.getMessage() ); }
  return retval;
}

/**
  * Create a secondary DB handle for the current database
  * @param secDbname Name of the secondary database name
  * @param readOnly Flag indicating read only status
  * @param skc Secondary key creator object
  */
public synchronized boolean createSecDB ( String secDbname, boolean readOnly, SecondaryKeyCreator skc)
{
  if  ( (secDbname == null) || (secDbname.equals("") ) )  return false;
  try
  {
   //*-- open the environment
   if (env == null)  { openEnv(DBDIR, false); if (env == null) return false; }

   //*-- create the primary database handle
   SecondaryConfig secdbconfig = new SecondaryConfig();
   secdbconfig.setSortedDuplicates(true);
   secdbconfig.setAllowCreate(true);
   secdbconfig.setAllowPopulate(true);       //*-- allow auto-populate
   secdbconfig.setReadOnly(readOnly);      //*-- set r/w status of the database
   secdbconfig.setKeyCreator(skc);
   setSecDB( env.openSecondaryDatabase(null, secDbname, getCurrentDB(), secdbconfig) );
  }
  catch (DatabaseException dbe)
  { logger.error("Failed to create Sec. DB " + secDbname + " " + dbe.getMessage() ); return false; }

  return true;
}

/**
  * Drop an existing secondary database
  * @param dbname String Name of database
  * @return boolean
  */
public synchronized boolean dropSecDB(String dbname)
{
  boolean retval = false;
  try
 
   //*-- first, get the environment
   if (env == null) { openEnv(DBDIR, false); if (env == null) return retval; }
   SecondaryDatabase  dbe = getSecDB(); //if (dbe == null) return retval;
   if (dbe != null) dbe.close();  
   env.removeDatabase(null, dbname);   
   retval = true;
  }
  catch (DatabaseException dbe) { }

  return retval;
}

/**
  * Create the database handle after opening the environment.
  * Database must exist -- thru createDB
  * @param dbname String name of the database
  * @param readOnly boolean indicating if the database is read only
  * @return boolean
  */
public synchronized boolean openDB(String dbname, boolean readOnly)
{ return (openDB(dbname, readOnly, false) ); }

public synchronized boolean openDB(String dbname, boolean readOnly, boolean dupFlag)
{
  try
  {
   //*-- check for errors and open the environment
   if ( (dbname.equals("")) || (!(existsDB(dbname))) ) return false;
   if (env != null) { openEnv(DBDIR, readOnly); if (env == null) return false; }

   //*-- create the primary database handle
   DatabaseConfig dbconfig = new DatabaseConfig();
   dbconfig.setAllowCreate(false);      //*-- disallow creation of database 
   dbconfig.setSortedDuplicates(dupFlag);     //*-- flag for dups
   dbconfig.setExclusiveCreate(readOnly);     //*-- allow opening of an existing database
   dbconfig.setReadOnly(readOnly);      //*-- set r/w status of the database
   // dbconfig.setTransactional(true);
   currentDB = env.openDatabase(null, dbname, dbconfig);
   dbMap.put(dbname, currentDB );
  }
  catch (DatabaseException dbe) { logger.error("Failed to open DB " + dbname + " " + dbe.getMessage() ); return false; }

  return true;
}

public DbTools() { }

/**
  * release the database connection resources
  * @param dbname String name of the database
  * @return boolean
  */
public synchronized boolean closeDB(String dbname)
{ this.currentDB = (Database) dbMap.get(dbname);
   return (closeDB() );
}

public synchronized boolean closeDB()
{
  try { if (currentDB != null) { currentDB.close(); currentDB = null; } }
  catch (DatabaseException dbe)  { logger.error("Failed to close DB "+ " " + dbe.getMessage() ); return false; }
  return true;
}

public synchronized long sizeDB(String dbname)
{
  long size = 0;
  openDB(dbname, true);
  try { size = currentDB.count(); }
  catch (DatabaseException dbe) { logger.error("Could not get the size of the DB: " + dbe.getMessage()); }
  finally { closeDB(); }
  return (size);
}

/**
  * Create the sec. database handle after opening the environment.
  * Database must exist -- thru createDB
  * @param dbname String name of the database
  * @param readOnly boolean indicating if the database is read only
  * @param skc Secondary key creator object
  * @return boolean
  */
public synchronized boolean openSecDB(String dbname, boolean readOnly, SecondaryKeyCreator skc)
{
  try
  {
   if (dbname.equals("")) return false;

   //*-- open the environment
   if (env != null) { openEnv(DBDIR, readOnly); if (env == null) return false; }

   //*-- create the primary database handle
   SecondaryConfig secdbconfig = new SecondaryConfig();
   secdbconfig.setAllowPopulate(true);        //*-- recreate secondary from primary
   secdbconfig.setSortedDuplicates(true);       //*-- allow dups
   secdbconfig.setExclusiveCreate(readOnly);     //*-- allow opening of an existing database
   secdbconfig.setReadOnly(readOnly);        //*-- set r/w status of the database
   secdbconfig.setKeyCreator(skc);

   //secdbconfig.setTransactional(true);
   setSecDB( env.openSecondaryDatabase(null, dbname, getCurrentDB(), secdbconfig) );
  }
  catch (DatabaseException dbe)
  { logger.error("Failed to open DB " + dbname + " " + dbe.getMessage() ); return false; }

  return true;
}

/**
  * release the secdatabase connection resources
  * @return boolean
  */
public synchronized boolean closeSecDB()
{
  try if (secDB != null) { secDB.close(); secDB = null; } }
  catch (DatabaseException dbe)  { logger.error("Failed to close Sec. DB "+ " " + dbe.getMessage() ); return false; }
  return true;
}

/**
  * Return the key of the last record entered in the database
  * @return  String Numeric value of next key
  */

public synchronized String getNextKey() throws DatabaseException
{
  String lastKey = "0"; Cursor cursor = null;
  cursor = getCurrentDB().openCursor(null, null);
  DatabaseEntry key = new DatabaseEntry(); DatabaseEntry data = new DatabaseEntry();
  if (cursor.getLast(key, data, LockMode.DEFAULT) == OperationStatus.SUCCESS)
   lastKey = new String(key.getData())
  cursor.close();

  int i = new Integer(lastKey).intValue() + 1;
  String keyString = "" + i; 
  String padKeyString = StringTools.fillin( keyString, 10, false, '0', 10 - keyString.length());
  return padKeyString;
}

public synchronized boolean insert (String key, StoreAbleInterface data)
{ return insert(key, data, false); }

/**
  * Insert an entry into the database
  * @param key String containing the key of the record
  * @param data StoreAbleInterface object to be stored
  * @param dups Flag indicating if duplicate objects should be stored or not
  * @return boolean
  */
public synchronized boolean insert ( String key, StoreAbleInterface data, boolean dups)
{

  boolean valid = false;
  try
  { key = key.trim();
  DatabaseEntry dbKey = new DatabaseEntry( key.getBytes("UTF-8") );
  DatabaseEntry  dbData = new DatabaseEntry();
  data.getBdbBinding().objectToEntry(data, dbData);
  OperationStatus ost = (dups) ? getCurrentDB().put(null, dbKey, dbData):
   getCurrentDB().putNoOverwrite(null, dbKey, dbData)

  if (ost != OperationStatus.KEYEXIST) valid = true;
  }
  catch (DatabaseException e)
  { logger.error(" " + e.getMessage()); }
  catch (UnsupportedEncodingException ue)
  { logger.error("Unsupported encoding" + ue.getMessage()); }

  return (valid);

}

/**
  * Fetch an entry from the database
  * @param key String key to the row
  * @param dbData Object returned for the row
  * @return boolean
  */
public boolean fetch (String key, DatabaseEntry dbData)
{
  boolean retval = false;
  try
  { key = key.trim();
  DatabaseEntry dbKey = new DatabaseEntry( key.getBytes("UTF-8") );

  //*-- use the key to fetch the data from the primary database
  if ( getCurrentDB().get(null, dbKey, dbData, LockMode.DEFAULT== OperationStatus.SUCCESS) retval = true;
  }
  catch (RuntimeException e)
  { logger.error("Could not fetch document with key: " + key + " Error: " +  e.getMessage() )}
  catch (UnsupportedEncodingException ue)
  { logger.error(" Unsupported encoding error " + key + ue.getMessage() )}
  catch (DatabaseException de)
  { logger.error(" Database error " + key + de.getMessage() )}

  return (retval);
}

/**
  * Fetch an entry from the database
  * @param key String key to the matching rows
  * @return DatabaseEntry[] Array data from the matching rows
  */
public DatabaseEntry[] fetchArray (String key)
{ return fetchArray(key, false, 10); }

public DatabaseEntry[] fetchArray (String key, boolean rangeFlag)
{ return fetchArray(key, rangeFlag, 10); }

public DatabaseEntry[]  fetchArray (String key, boolean rangeFlag, int RANGE)
{
  ArrayList<DatabaseEntry> al = new ArrayList<DatabaseEntry>();
  Cursor cursor = null;
  DatabaseEntry[] dbData = null;
  try
  {
   DatabaseEntry dbKey = new DatabaseEntry( key.getBytes("UTF-8") );
   DatabaseEntry dbe = new DatabaseEntry();
   cursor = getCurrentDB().openCursor(null, null);
   OperationStatus ostat = (rangeFlag) ? cursor.getSearchKeyRange(dbKey, dbe, LockMode.DEFAULT):
                            cursor.getSearchKey(dbKey, dbe, LockMode.DEFAULT);

   int numRecords = 0;
   if (cursor.count() >= 1)
   { while ( (ostat == OperationStatus.SUCCESS) && (numRecords < RANGE) )
   { al.add(dbe); dbe = new DatabaseEntry();
   ostat = (rangeFlag) ? cursor.getNext(dbKey, dbe, LockMode.DEFAULT):
    cursor.getNextDup(dbKey, dbe, LockMode.DEFAULT);
   numRecords++;
   }
   }
   else { al.add(dbe);
  }
  catch (RuntimeException re)
  { logger.error("Runtime error: Could not fetch documents with key " + key + " " + re.getMessage())}
  catch (UnsupportedEncodingException ue)
  { logger.error("Unsupported encoding: Could not fetch documents with key " + key + " " + ue.getMessage())}
  catch (DatabaseException de)
  { logger.error("Database error: Could not fetch documents with key " + key + " " + de.getMessage())}
  finally
  { try {if (cursor != null) cursor.close(); } catch (DatabaseException dbe) { } }

  if (al.size() >= 1)
  { dbData = new DatabaseEntry[al.size()];
  for (int i = 0; i < al.size(); i++) dbData[i] = (DatabaseEntry) al.get(i);
  }

  return (dbData);
}
/**
  * Fetch an entry from the Secondary database
  * @param key String Sec. key to the row
  * @return DatabaseEntry data from the row
  */
public DatabaseEntry fetchSec (String key)
{
  DatabaseEntry dbData = new DatabaseEntry();
  try
  {
   key = key.trim();
   DatabaseEntry dbKey = new DatabaseEntry( key.getBytes("UTF-8") );
   DatabaseEntry py = new DatabaseEntry();

   //*-- use the key to fetch the data from the primary database
   OperationStatus os = getSecDB().get(null, dbKey, py, dbData, LockMode.DEFAULT);
   if (os != OperationStatus.SUCCESS) dbData = null;
  }
  catch (RuntimeException re)
  { logger.error("Runtime error: Could not fetch sec. document with key " + key + " " + re.getMessage());
  dbData = null; }
  catch (UnsupportedEncodingException ue)
  { logger.error("Unsupported encoding: Could not fetch sec. document with key " + key + " " + ue.getMessage());
  dbData = null; }
  catch (DatabaseException de)
  { logger.error("Database error: Could not fetch sec. document with key " + key + " " + de.getMessage());
  dbData = null; }

  return (dbData);
}

/**
  * Fetch all matching entries from the database
  * @param key String Sec. key to matching rows
  * @return DatabaseEntry Array data from the matching rows
  */
public DatabaseEntry[] fetchSecArray (String key)
{ return fetchSecArray(key, false, 10); }

public DatabaseEntry[] fetchSecArray (String key, boolean rangeFlag)
{ return fetchSecArray(key, rangeFlag, 10); }

public DatabaseEntry[] fetchSecArray (String key, boolean rangeFlag, int RANGE)
{
  ArrayList<DatabaseEntry> al = new ArrayList<DatabaseEntry>();
  SecondaryCursor secCursor = null;
  DatabaseEntry[] dbData = null;
  try
 
   DatabaseEntry dbKey = new DatabaseEntry( key.getBytes("UTF-8") );
   DatabaseEntry dbe = new DatabaseEntry();
   secCursor = getSecDB().openSecondaryCursor(null, null);
   OperationStatus ostat = (rangeFlag) ? secCursor.getSearchKeyRange(dbKey, dbe, LockMode.DEFAULT):
    secCursor.getSearchKey(dbKey, dbe, LockMode.DEFAULT);

   int numRecords = 0;
   if (secCursor.count() >= 1)
   { while ( (ostat == OperationStatus.SUCCESS) && (numRecords < RANGE) )
   { al.add(dbe); dbe = new DatabaseEntry();
   ostat = (rangeFlag) ? secCursor.getNext(dbKey, dbe, LockMode.DEFAULT):
    secCursor.getNextDup(dbKey, dbe, LockMode.DEFAULT);
   numRecords++;
   }
   }
   else { al.add(dbe);
  }
  catch (RuntimeException re)
  { logger.error("Runtime error: Could not fetch documents with sec. key " + key + " " + re.getMessage())}
  catch (UnsupportedEncodingException ue)
  { logger.error("Unsupported encoding: Could not fetch documents with sec. key " + key + " " + ue.getMessage())}
  catch (DatabaseException de)
  { logger.error("Database error: Could not fetch documents with sec. key " + key + " " + de.getMessage())}
  finally
  { try { if (secCursor != null) secCursor.close(); } catch (DatabaseException dbe) { } }

  if (al.size() >= 1)
  { dbData = new DatabaseEntry[al.size()];
  for (int i = 0; i < al.size(); i++) dbData[i] = (DatabaseEntry) al.get(i);
  }

  return (dbData);
}
/**
  * Delete an entry from the database
  * @param key Key String of the record to be deleted
  * @return boolean
  */
public synchronized boolean delete (String key)
{
  try
  { DatabaseEntry dbe = new DatabaseEntry( key.getBytes("UTF-8"));
  if ( getCurrentDB().delete(null, dbe) == OperationStatus.NOTFOUND) return false; }
  catch (UnsupportedEncodingException ue) { return false; }
  catch (DatabaseException e) { return false;}
  return true;
}

/**
  * Remove an existing entry from the database and replace with a new one
  * @param key Key string of the record to be updated
  * @param data The data object that will replace the row data
  * @return boolean
  */
public boolean update (String key, StoreAbleInterface data)
{
  delete(key);
  return (insert(key, data) );
}

/**
  * Check if a row exists in the primary database with the passed key
  * @param key Key string of the record
  * @return boolean
  */
public synchronized boolean exists(String key) throws DatabaseException
{

  Cursor cursor = null;
  boolean retval = false;
  try
  { cursor = getCurrentDB().openCursor(null, null);
    DatabaseEntry dkey = new DatabaseEntry(key.getBytes("UTF-8") );
    DatabaseEntry data = new DatabaseEntry();
    if (
    cursor.getSearchKey(dkey, data, LockMode.DEFAULT) ==
      OperationStatus.SUCCESS ) retval = true;
  }
  catch (UnsupportedEncodingException e)
  { logger.error("Invalid encoding " + e.getMessage() )}
  finally { if (cursor != null) cursor.close(); }
  return (retval);
}


/**
  * preload a database into a passed HashMap
  * @param dbName String Name of the database to preload
  * @param tpb TupleBinding to store the records
  * @param size The size of the pre-loaded database, no. of records
  * @return HashMap<String, String> Hashmap containing keys and row contents
  */
public HashMap<String, String> preLoadDB(String dbName, TupleBinding tpb, int size)
{
  boolean readOnly = true; boolean dupFlag = false; Cursor cursor = null;
  HashMap<String, String> hash = new HashMap<String, String> (size, (float) 0.95);
  try
  { openDB(dbName, readOnly, dupFlag);
    cursor = getCurrentDB().openCursor(null, null);
    DatabaseEntry key = new DatabaseEntry(); DatabaseEntry data = new DatabaseEntry();
    while (cursor.getNext(key, data, LockMode.DEFAULT) == OperationStatus.SUCCESS)
     { String skey = new String(key.getData(), "UTF-8");
       String sdata = tpb.entryToObject(data).toString();
       hash.put( skey, sdata );
     }
  }
  catch (DatabaseException de) { logger.error("Database error " + de.getMessage() ); }
  catch (UnsupportedEncodingException ue) { logger.error("Encoding error " + ue.getMessage() ); }
  finally {
   try { if (cursor != null) cursor.close(); closeDB(dbName); }
   catch (DatabaseException de) { logger.error("Ignore error"); } }
  return hash;  
}

/**
  * Dump the database to a file
  * @param dbName  Name of the database
  * @param tpb    Tuple binding for the record of the database
  * @param filename  Name of the file
  * @return boolean
  */
public boolean dumpDB(String dbName, TupleBinding tpb, String filename)
  boolean retval = true;
  boolean readOnly = true; boolean dupFlag = false;
  Cursor cursor = null; PrintWriter pw = null;
  try
  {
   pw = new PrintWriter( new BufferedOutputStream( new FileOutputStream(filename) ) );
   openDB(dbName, readOnly, dupFlag);
   cursor = getCurrentDB().openCursor(null, null);
   DatabaseEntry key = new DatabaseEntry(); DatabaseEntry data = new DatabaseEntry();
   while (cursor.getNext(key, data, LockMode.DEFAULT) == OperationStatus.SUCCESS)
   { String sdata = tpb.entryToObject(data).toString();
   pw.println(sdata);
   }
  }
  catch (DatabaseException de) { logger.error("Database error " + de.getMessage() ); retval = false; }
  catch (FileNotFoundException fe) { logger.error("Could not find file " + dbName + " " + fe.getMessage()); }
  finally {
   try
   { if (pw != null) pw.close();
   if (cursor != null) cursor.close();
   closeDB(dbName);
   }
   catch (DatabaseException de) { logger.error("Ignore error"); }
  }
  return (retval);
}

public synchronized void syncEnv()
{ try { env.sync(); }
catch (DatabaseException de) { logger.error("Database error " + de.getMessage() )}
}

/**
  * Return a list of database names in this environment
  * @return List of database names
  */
public synchronized List fetchDBnames()
{ List list = null;
try { list =  env.getDatabaseNames(); }
catch (DatabaseException de) { logger.error("Database error " + de.getMessage() )}
return (list);
}

//*-- getter and setter methods
public synchronized Database getCurrentDB()
{ return currentDB; }

public synchronized void setCurrentDB(Database currentDB)
{ this.currentDB = currentDB;  }

public synchronized boolean setCurrentDB(String dbname)
{ if ( (dbname.equals("")) || (!(existsDB(dbname))) ) return false;
this.currentDB = (Database) dbMap.get(dbname);
return true;
}

public synchronized SecondaryDatabase getSecDB()
{ return secDB; }

public synchronized void setSecDB(SecondaryDatabase secDB)
{ this.secDB = secDB; }

}
TOP

Related Classes of org.sf.mustru.utils.DbTools

TOP
Copyright © 2018 www.massapi.com. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.