Open environment failure "DB_RUNRECOVERY"

Hi BDB experts,
This a HA master environment, for some reason unknown, now open environment always returned DB_RUNRECOVERY. The environment was open with flag:
DB_INIT_TXN |   DB_INIT_LOCK |  DB_INIT_LOG |   DB_REGISTER |   DB_RECOVER |    DB_INIT_MPOOL | DB_THREAD |     DB_INIT_REP;
In this case, can the enviroment be recovered? What can be done for this error?
Could you tell me the causes of error "DB_RUNRECOVERY"?
Thanks,
Min

DB_RUNRECOVERY gets returned when there is a suspected issue in the database.      You need to run recovery.    Chap 11 of BDB Programmers Reference covers the procedures for running recovery.      In this case, I would suggest running the db_recover utility.    When you run the utility you should ensure that there are no processes connected to the environment and it is closed.
possible causes -- memory errors, disk errors, hw errors, application errors, power failures, cpu errors, human errors    There are many paths in the code that can throw this particular error.    To figure out the exact trigger for your case, this is something that Oracle support handles.  Have you purchased a support contract for BDB?
thanks
mike

Similar Messages

  • Open Environment error : Resource temporarily unavailable

    Hi,
    I use Berkeley DB 4.5.2 in a system with Intel PXA255, 64MB memory, 512MB USB disk. The system is Linux 2.4.18, compiler is arm-linux-gcc 2.95.3. I put database files on the USB disk (because the file size is more than 72MB), and the disk still got 70% free space (so I don't think the problem is caused by the disk space).
    The same program is run pretty well on PC, Intel P4 3.0, 512MB memory, Red hat Linux 4.2 Enterprise (Linux 2.6.9-22), compiler is gcc 4.3.3.
    But it could not even open the Environment on the board. One program shows error message:
    Environment open failed: Resource temporarily unavailable.
    The other program shows error message:
    unhandled page fault at pc=0x00019808, lr=0x000197f4 (bad address=0x000000dc, code 0)
    pc : [<00019808>] lr : [<000197f4>] Not tainted
    sp : bffff528 ip : bffff700 fp : bffff804
    r10: 402d62fc r9 : 402d5c88 r8 : 0001ee90
    r7 : 00000001 r6 : 00008a24 r5 : 4001e724 r4 : bffffce4
    r3 : 00000000 r2 : 00029cf0 r1 : bffff71c r0 : bffff700
    Flags: nzcv IRQs on FIQs on Mode USER_32 Segment user
    Control: 397F Table: A3DF8000 DAC: 00000015
    Segmentation fault
    They are using the same code:
    #define __DEBUG 1
    ret = db_env_create(&VitalEnv, 0);
    if (0 != ret)
    #if __DEBUG
    fprintf(stderr, "Error in creating environment handle: %s.\n", db_strerror(ret));
    #endif
    return ret
    }/*endif*/
    env_flags = DB_CREATE | DB_INIT_MPOOL;
    ret = VitalEnv->open(VitalEnv, "./Data", env_flags, 0);
    if (0 != ret)
    #if __DEBUG
    fprintf(stderr, "Environmet open failed: %s.\n", db_strerror(ret));
    #endif
    return ret;
    }/*endif*/
    The only difference is that I put these codes in a function called OpenDB() for the second program, and just put these codes in main() for the first program.
    And both of them could not open environment.
    I have put the arm version libdb-4.5.so on the USB disk. Everything I did but the problem is still there.

    Hi Lesslielee,
    We will try to fix first the "Resource temporarily unavailable" issue. Is not very clear for me which/what/where application/databases you had moved and when.
    Do you have Berkeley DB's additional error reporting turned on? With the error reporting turned on, do you see any additional error information when this exception is thrown? ( http://www.oracle.com/technology/documentation/berkeley-db/db/ref/debug/runtime.html )
    From what I understand, when you are storing the databases on the disk (not on the USB drive), the tests are running well, right? When you are moving the database files on the USB drive, are you also moving the environment files? Storing environment files on an NFS file system is not supported.
    When Berkeley DB database environment shared memory regions are backed by the filesystem, it is a common application error to create database environments backed by remote filesystems such as the Network File System (NFS), Windows network shares (SMB/CIFS) or the Andrew File System (AFS). Remote filesystems rarely support mapping files into process memory, and even more rarely support correct semantics for mutexes if the mapping succeeds. For this reason, we recommend database environment directories be created in a local filesystem.
    Does the problem occur when you run the application for the first time in the new configuration? How did you moved the databases? How did you closed the environment last time?
    For more information, please see the "Remote filesystems" section of the Berkeley DB Reference Guide, available in your download package or on our web site at: http://www.oracle.com/technology/documentation/berkeley-db/db/ref/env/remote.html
    Thanks,
    Bogdan Coman

  • Open Tunnel Failure Exception still if there APN settings in device

    Hi All,
    I have writen blackberry application for BB8100,it give me "Open Tunnel failure exception", Though i have write APN Setiing in Advanced options--->Tcp
    I am from india
    Carrier provides :Airtel
    APN:airtelgprs.com
    Uname:......
    Pass:......
    But still m not resolved this problem if any one have resolution please give me that,its really helpfull to me.
    Thanks in Advance
    Deepak 

    thanks but i haven't been able to find a ksoap specific forum! I have posted the same question on the blackberry forums but there are so many ksoap related issues there that nobody seems able to help.
    I was hoping that this issue was more a general error than a ksoap one!
    Alex

  • 2.3.10 -- Problem openning environment from command-line

    I am just starting to learn DB XML. I have downloaded and apparently successfully installed DB XML 2.3.10 (on a Ubuntu 6.06 Linux system). I am reading Danny Brian's book "The Definitive Guide to Bekeley DB XML". In Chapter 5, a command is shown to open/create an environment:
    <pre>
    $ dbxml -c -h myenv/
    dbxml> quit
    </pre>
    According to the book, I should expect to see 2 files in myenv/ --> __db.001 & __db.002
    I have created the directory myenv/ and set my defaullt to its parent. When I try this command, I get the error messages shown below:
    <pre>
    dbxml -c -h myenv/unable to initialize mutex: Function not implemented
    PANIC: Function not implemented
    unable to join the environment
    dbxml: error at lowest level: DbEnv::open: DB_RUNRECOVERY: Fatal error, run database recovery
    </pre>
    Adding a couple -vv's to the commands produced no more output! Have I successfully installed 2.3.10? Is there anything I'm doing wrong??
    Thanks,
    Denny

    I downloaded the 2.3.10 kit from the Oracle DBXML website a weekago. I unpacked the kit into /usr/local then ran sh buildall.sh!! (2.2.13 is also installed/build in /usr/local)
    I just now started another rebuild with the following commands (all while logged on as root:
    1. cd /usr/local
    2. rm -r dbxml-2.3.10
    3. tar -xvf <kit location>
    4. chown -R root:root dbxml-2.3.10 (was owned by cupsys:users??!!)
    5. sh buildall.sh
    This time, as all the checking messages came by, I noticed that selected mutex = x86/gcc-assembly
    There is one big difference between what I had been doing and this latest attempt: Previously, I unpacked the kit inot my home directory, then did:
    sudo mv <home copy of dbxml> /usr/local
    sudo chown -R root:root ......
    sudo sh buildall.sh
    Could using sudo been the cause of my problem??!!
    I just checked the db-4.5.20 config.log and saw
    db_cv_mutex=x86/gcc-assembly
    Earlier this week (as reported in an earlier response to this post), db_cv_mutex was set to POSIX-something!!??!!
    I am hopeful!!
    Denny

  • Error opening environment

    Hello,
    I have an application in Java that I deploy in Glassfish 3. The database is Berkeley DB XML.
    The application is used by several clients, so I have one environment for each client.
    When I deploy the application I run this code to each client, to open every environment.
    public class BdbxmlManager {
        //+++++++++++++++++++++++++++MAIN VARS++++++++++++++++++++++++++++++++++++++
        public String ENVIRONMENT_PATH = "";
        public static String LOGS_PATH_NAME = "";
        //public String ENVIRONMENT_LOGS_PATH = "";
        protected EnvironmentConfig ENVIRONMENT_CONFIG = null;
        protected Environment ENVIRONMENT = null;
        protected static XmlContainerConfig xmlContainerConfig = null;
        protected static XmlManagerConfig xmlManagerConfig = null;
        protected static SequenceConfig sequenceConfig = null;
        protected static DatabaseConfig sequenceDatabaseConfig = null;
        //protected static TransactionConfig transactionConfig = null;
        protected XmlContainer XML_CONTAINER = null;
        protected XmlContainer XML_CONTAINER_LOGS = null;
        protected XmlContainer XML_CONTAINER_ERROR_LOGS = null;
        protected XmlContainer XML_CONTAINER_MESSAGE = null;
        protected Database SEQUENCE_DATABASE = null;
        protected XmlManager XML_MANAGER = null;
        //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
        public static String SEQUENCE_DB_NAME = "";
        public static String SEQUENCE_DB_FILE_NAME = "";
        public static String CONTAINER_NAME = "";
        public static String MAIN_DOCUMENT_NAME = "";
        public static String MAIN_DOCUMENT_INITIAL_CONTENT = "";
        public static String CONTAINER_MESSAGE = "";
        public static String CONTAINER_NAME_LOGS = "";
        public static boolean USING_LOGS_DOCUMENT = false;
        public static String LOGS_DOCUMENT_NAME = "";
        public static String LOGS_DOCUMENT_INITIAL_CONTENT = "";
        public static String CONTAINER_NAME_ERROR_LOGS = "";
        public static boolean USING_ERROR_LOGS_DOCUMENT = false;
        public static String ERROR_LOGS_DOCUMENT_NAME = "";
        public static String ERROR_LOGS_DOCUMENT_INITIAL_CONTENT = "";
        public static int MAX_LOG_BUFFER_SIZE = 50 * 1024 * 1024;
        public static int MAX_CACHE_SIZE = 5 * 1024 * 1024;
         * max num of simultaneous active transactions
        public static int MAX_ACTIVE_TXNS = 10000;
        //---------------------DEFAULT ENVIRONMENT CONFIGURATION VALUES---------------------------------
        public static boolean RUN_RECOVERY_BY_DEFAULT = true;
        public static int CACHE_SIZE_BY_DEFAULT = 5 * 1024 * 1024;
        public static int MAX_ACTIVE_TXNS_BY_DEFAULT = 5000;
        public static int LOG_BUFFER_SIZE_BY_DEFAULT = 50 * 1024 * 1024;
        public static boolean ENVIRONMENT_LOG_IN_MEMORY = false;
        public static boolean ENVIRONMENT_LOG_AUTO_REMOVE = true;
        public static int ENVIRONMENT_LOG_REGION_SIZE = 3 * 1024 * 1024;
        public static boolean ENVIRONMENT_TRANSACTIONAL = true;
        public static boolean ENVIRONMENT_THREADED = true;
        public static int ENVIRONMENT_TXN_MAX_ACTIVE = 5000;
        public static int DEFAULT_MAX_LOCKS = 15000;//2000;
        public static int DEFAULT_MAX_LOCKERS = 15000;//2000;
        public static int DEFAULT_MAX_LOCK_OBJECTS = 15000;//2000;
        //--------------------SEQUENCE CONFIGURATION VALUES-------------------
        public static boolean ALLOW_CREATE_SEQUENCE_CONFIG = true;
        public static int SEQUENCE_CACHE_SIZE = 0;
        public static boolean DECREMENT_SEQUENCE_CONFIG = false;
        public static int SEQUENCE_MIN_VALUE = 0;
        public static int SEQUENCE_MAX_VALUE = 99999999;
        public static int SEQUENCE_INITIAL_VALUE = 0;
        public static boolean EXCLUSIVE_CREATE_SEQUENCE_CONFIG = false;
        public static boolean WRAP_SEQUENCE_CONFIG = false;
        //----------------------------------------------------------------------ç
        //--------------------XMLMANAGER CONFIGURATION VALUES-------------------
        public static boolean XML_MANAGER_LOG_ENABLED = false;
        public static int XML_MANAGER_LOG_LEVEL = XmlManager.LEVEL_ERROR;
        public static int XML_MANAGER_LOG_CATEGORY = XmlManager.CATEGORY_MANAGER;
        //--------------------XMLCONTAINER CONFIGURATION VALUES-------------------
        public static boolean XML_CONTAINER_INDEX_NODES_AND_STATISTICS_ENABLED = true;
        public static boolean XML_CONTAINER_ALLOW_VALIDATION = false;
        //--------------------SEQUENCE DATABASE CONFIGURATION VALUES-------------------
        public static boolean ALLOW_CREATE_SEQUENCE_DATABASE_CONFIG = true;
        public static boolean TRANSACTIONAL_SEQUENCE_DATABASE_CONFIG = true;
         *  Constructor
        public BdbxmlManager(String ENVIRONMENT_PATH_NAME) throws DatabaseException, FileNotFoundException, IOException, DbxmlException {
            this.ENVIRONMENT_PATH = ENVIRONMENT_PATH_NAME;
            //this.ENVIRONMENT_LOGS_PATH = ENVIRONMENT_LOGS_PATH_NAME;
            init(ENVIRONMENT_PATH);
            initXmlManager();
            initSequenceDataBase();
            //Container message
            File containerMessage = new File(ENVIRONMENT_PATH, CONTAINER_MESSAGE);
            System.out.println("pruebas");
            System.out.println("check container messsage "+containerMessage.getCanonicalPath());
            try{
                System.out.println("try");
                if (XML_MANAGER.existsContainer(containerMessage.getCanonicalPath()) != 0) {
                    System.out.println("try1");
                    System.out.println("Opening the container message: " + containerMessage + ".....");
                    XML_CONTAINER_MESSAGE = XML_MANAGER.openContainer(containerMessage.getCanonicalPath(), xmlContainerConfig);
                    //System.out.println("Container is transactional: " + XML_CONTAINER.getContainerConfig().getTransactional());
                    XML_CONTAINER_MESSAGE.setAutoIndexing(false);
                    System.out.println("Container message opened!");
                } else {
                    System.out.println("try2");
                    System.out.println("error open container");
                    throw new DbxmlException(DbxmlException.CONTAINER_DOES_NOT_EXIST);
            }catch(Exception e){
                System.out.println("EXCEPCION "+e.toString());
            //Container data
            File containerFile = new File(ENVIRONMENT_PATH, CONTAINER_NAME);
            System.out.println("check container "+containerFile.getCanonicalPath());
            if (XML_MANAGER.existsContainer(containerFile.getCanonicalPath()) != 0) {
                System.out.println("Opening the container: " + containerFile + ".....");
                XML_CONTAINER = XML_MANAGER.openContainer(containerFile.getCanonicalPath(), xmlContainerConfig);
                //System.out.println("Container is transactional: " + XML_CONTAINER.getContainerConfig().getTransactional());
                XML_CONTAINER.setAutoIndexing(false);
                System.out.println("Container opened!");
                try {
                    XmlDocument tempDoc = XML_CONTAINER.getDocument(MAIN_DOCUMENT_NAME);
                    //System.out.println("tempDoc no es nulo: " + tempDoc == null);
                } catch (XmlException e) {
                    if (e.getErrorCode() == XmlException.DOCUMENT_NOT_FOUND) {
                        //System.out.println("El documento " + MAIN_DOCUMENT_NAME + " no existe");
                        //System.out.println("Añadiendo documento....");
                        XML_CONTAINER.putDocument(MAIN_DOCUMENT_NAME, MAIN_DOCUMENT_INITIAL_CONTENT);
            } else {
                throw new DbxmlException(DbxmlException.CONTAINER_DOES_NOT_EXIST);
            //Container logs
            File containerFileLogs = new File(ENVIRONMENT_PATH, CONTAINER_NAME_LOGS);
            System.out.println("check container "+containerFileLogs.getCanonicalPath());
            if (XML_MANAGER.existsContainer(containerFileLogs.getCanonicalPath()) != 0) {
                System.out.println("Opening the container: " + containerFileLogs + ".....");
                XML_CONTAINER_LOGS = XML_MANAGER.openContainer(containerFileLogs.getCanonicalPath(), xmlContainerConfig);
                //System.out.println("Container is transactional: " + XML_CONTAINER.getContainerConfig().getTransactional());
                XML_CONTAINER_LOGS.setAutoIndexing(false);
                System.out.println("Container opened!");
                //---------------------------LOGS DOCUMENT INITIALIZATION----------------------------------
                try {
                    XML_CONTAINER_LOGS.getDocument(LOGS_DOCUMENT_NAME);
                    //System.out.println("logsDoc no es nulo: " + logsDoc == null);
                } catch (XmlException e) {
                    if (e.getErrorCode() == XmlException.DOCUMENT_NOT_FOUND) {
                        //System.out.println("El documento " + LOGS_DOCUMENT_NAME + " no existe");
                        //System.out.println("Añadiendo documento....");
                        XML_CONTAINER_LOGS.putDocument(LOGS_DOCUMENT_NAME, LOGS_DOCUMENT_INITIAL_CONTENT);
            } else {
                throw new DbxmlException(DbxmlException.CONTAINER_DOES_NOT_EXIST);
            //Container error logs
            File containerFileErrorLogs = new File(ENVIRONMENT_PATH, CONTAINER_NAME_ERROR_LOGS);
            System.out.println("check container "+containerFileErrorLogs.getCanonicalPath());
            if (XML_MANAGER.existsContainer(containerFileErrorLogs.getCanonicalPath()) != 0) {
                System.out.println("Opening the container: " + containerFileErrorLogs + ".....");
                XML_CONTAINER_ERROR_LOGS = XML_MANAGER.openContainer(containerFileErrorLogs.getCanonicalPath(), xmlContainerConfig);
                //System.out.println("Container is transactional: " + XML_CONTAINER.getContainerConfig().getTransactional());
                XML_CONTAINER_ERROR_LOGS.setAutoIndexing(false);
                System.out.println("Container opened!");
                //----------------------ERROR LOGS DOCUMENT INITIALIZATION----------------------------------
                try {
                    XML_CONTAINER_ERROR_LOGS.getDocument(ERROR_LOGS_DOCUMENT_NAME);
                    //System.out.println("errorLogsDoc no es nulo: " + errorLogsDoc == null);
                } catch (XmlException e) {
                    if (e.getErrorCode() == XmlException.DOCUMENT_NOT_FOUND) {
                        //System.out.println("El documento " + ERROR_LOGS_DOCUMENT_NAME + " no existe");
                        //System.out.println("Añadiendo documento....");
                        XML_CONTAINER_ERROR_LOGS.putDocument(ERROR_LOGS_DOCUMENT_NAME, ERROR_LOGS_DOCUMENT_INITIAL_CONTENT);
            } else {
                throw new DbxmlException(DbxmlException.CONTAINER_DOES_NOT_EXIST);
         *  Init XmlManager
        protected void initXmlManager() throws XmlException
            if(XML_MANAGER == null){
                //---------XmlManager----------------
                //System.out.println("Creating the XmlManager.....");
                XML_MANAGER = new XmlManager(ENVIRONMENT, xmlManagerConfig);
                XmlManager.setLogLevel(XML_MANAGER_LOG_LEVEL, XML_MANAGER_LOG_ENABLED);
                XmlManager.setLogCategory(XML_MANAGER_LOG_CATEGORY, XML_MANAGER_LOG_ENABLED);
                //System.out.println("XmlManager created!");
         *  Init Database
        protected void initSequenceDataBase() throws DatabaseException, FileNotFoundException
            if(SEQUENCE_DATABASE == null)
                //---------Sequence Database------------------
                //System.out.println("Creating/opening the sequence database....");
                SEQUENCE_DATABASE = ENVIRONMENT.openDatabase(null, SEQUENCE_DB_NAME, SEQUENCE_DB_FILE_NAME, sequenceDatabaseConfig);
                //System.out.println("Sequence database opened/created!!");
         *  Configure BdbxmlManager
        protected synchronized void init(String ENVIRONMENT_PATH_NAME) {
            if (ENVIRONMENT_CONFIG == null) {
                System.out.println("new config en");
                ENVIRONMENT_CONFIG = initEnvironmentConfiguration();
                System.out.println("run "+ENVIRONMENT_CONFIG.getRunRecovery());
            if (ENVIRONMENT == null) {
                System.out.println("nuevo envi");
                ENVIRONMENT = initEnvironment(ENVIRONMENT_PATH_NAME);
            if (xmlContainerConfig == null) {
                xmlContainerConfig = initXmlContainerConfiguration();
            if (xmlManagerConfig == null) {
                xmlManagerConfig = initXmlManagerConfiguration();
            if (sequenceConfig == null) {
                sequenceConfig = initSequenceConfiguration();
            if (sequenceDatabaseConfig == null) {
                sequenceDatabaseConfig = initSequenceDatabaseConfig();
         *  INIT ENVIRONMENT CONFIGURATION
        protected static EnvironmentConfig initEnvironmentConfiguration() {
            //System.out.println("Initializing environment configuration....");
            EnvironmentConfig environmentConfig = new EnvironmentConfig();
            environmentConfig.setErrorStream(System.err);
            // If the environment does not exists, create it
            environmentConfig.setAllowCreate(true);
            // Turn on the shared memory region
            environmentConfig.setInitializeCache(true);
            // Turn on the locking subsystem
            environmentConfig.setInitializeRegions(true);
            environmentConfig.setInitializeLocking(true);
            // Turn on the logging subsystem
            environmentConfig.setInitializeLogging(true);
            //environmentConfig.setThreaded(ENVIRONMENT_THREADED);
            environmentConfig.setMaxMutexes(30000);//1000000);//10000);
            environmentConfig.setMutexIncrement(30000);//1000000);//10000);
            environmentConfig.setMaxLockers(DEFAULT_MAX_LOCKERS);
            environmentConfig.setMaxLocks(DEFAULT_MAX_LOCKS);
            environmentConfig.setMaxLockObjects(DEFAULT_MAX_LOCK_OBJECTS);
            //----------------------Cache configuration--------------------
            //environmentConfig.setCacheCount(1);
            environmentConfig.setCacheMax(MAX_CACHE_SIZE);
            environmentConfig.setCacheSize(CACHE_SIZE_BY_DEFAULT);
            //----------------------Logging configuration--------------------
            environmentConfig.setLogRegionSize(ENVIRONMENT_LOG_REGION_SIZE);
            environmentConfig.setLogBufferSize(LOG_BUFFER_SIZE_BY_DEFAULT);
            environmentConfig.setLogDirectory(new File(LOGS_PATH_NAME));
            environmentConfig.setLogInMemory(ENVIRONMENT_LOG_IN_MEMORY);
            environmentConfig.setLogAutoRemove(ENVIRONMENT_LOG_AUTO_REMOVE);
            //----------------------Transactions configuration--------------------
            //Turn on the transactional subsystem
            environmentConfig.setTransactional(ENVIRONMENT_TRANSACTIONAL);
            environmentConfig.setTxnMaxActive(ENVIRONMENT_TXN_MAX_ACTIVE);
            //environmentConfig.setTxnNoSync(false);
            //environmentConfig.setTxnNotDurable(false);
            //environmentConfig.setTxnSnapshot(true);
            //environmentConfig.setTxnWriteNoSync(false);
            //-------------------Run recovery configuration-------------
            environmentConfig.setRunRecovery(RUN_RECOVERY_BY_DEFAULT);
            System.out.println("EnvironmentConfig initialized! run "+environmentConfig.getRunRecovery());
            return environmentConfig;
         *  INIT ENVIRONMENT
        protected Environment initEnvironment(String ENVIRONMENT_PATH_NAME) {
            Environment env = null;
            //---------Environment--------------
            //System.out.println("Creating the environment....");
            try {
                System.out.println("start ");
                System.out.println("run recovery "+ENVIRONMENT_CONFIG.getRunRecovery());
                //ENVIRONMENT_CONFIG.setRunRecovery(true);
                System.out.println("run recovery "+ENVIRONMENT_CONFIG.getRunRecovery());
                env = new Environment(new File(ENVIRONMENT_PATH_NAME), ENVIRONMENT_CONFIG);
            } catch (DatabaseException ex) {
                Logger.getLogger(BdbxmlManager.class.getName()).log(Level.SEVERE, null, ex);
            } catch (FileNotFoundException ex) {
                Logger.getLogger(BdbxmlManager.class.getName()).log(Level.SEVERE, null, ex);
            } catch (Exception ex) {
                Logger.getLogger(BdbxmlManager.class.getName()).log(Level.SEVERE, null, ex);
            return env;
         *  CONFIGURE CONTAINER
        protected static XmlContainerConfig initXmlContainerConfiguration() {
            //System.out.println("Initializing XmlContainer configuration....");
            XmlContainerConfig config = new XmlContainerConfig();
            config.setContainerType(XmlContainer.NodeContainer);
            config.setTransactional(ENVIRONMENT_TRANSACTIONAL);
            if(XML_CONTAINER_INDEX_NODES_AND_STATISTICS_ENABLED)
                config.setIndexNodes(XmlContainerConfig.On);
                config.setStatisticsEnabled(XmlContainerConfig.On);
            }else
                config.setIndexNodes(XmlContainerConfig.Off);
                config.setStatisticsEnabled(XmlContainerConfig.Off);
            config.setAllowValidation(XML_CONTAINER_ALLOW_VALIDATION);
            //System.out.println("XmlContainer configuration initialized!");
            return config;
         *  INIT XML MANAGER CONFIGURATION
        protected static XmlManagerConfig initXmlManagerConfiguration() {
            //System.out.println("Initializing XmlManager configuration....");
            XmlManagerConfig config = new XmlManagerConfig();
            config.setAdoptEnvironment(false);
            config.setAllowAutoOpen(true);
            config.setAllowExternalAccess(true);
            //System.out.println("XmlManager configuration initialized!");
            return config;
         *  INIT SEQUENCE CONFIGURATION
        protected SequenceConfig initSequenceConfiguration() {
            //System.out.println("Initializing Sequence configuration....");
            SequenceConfig config = new SequenceConfig();
            config.setAllowCreate(ALLOW_CREATE_SEQUENCE_CONFIG);
            config.setCacheSize(SEQUENCE_CACHE_SIZE);
            config.setDecrement(DECREMENT_SEQUENCE_CONFIG);
            config.setRange(SEQUENCE_MIN_VALUE, SEQUENCE_MAX_VALUE);
            config.setInitialValue(SEQUENCE_INITIAL_VALUE);
            config.setExclusiveCreate(EXCLUSIVE_CREATE_SEQUENCE_CONFIG);
            config.setWrap(WRAP_SEQUENCE_CONFIG);
            //System.out.println("Sequence configuration initialized!");
            return config;
         *  INIT SEQUENCE DATABASE CONFIG
        protected DatabaseConfig initSequenceDatabaseConfig() {
            DatabaseConfig config = new DatabaseConfig();
            config.setAllowCreate(ALLOW_CREATE_SEQUENCE_DATABASE_CONFIG);
            config.setTransactional(TRANSACTIONAL_SEQUENCE_DATABASE_CONFIG);
            config.setType(DatabaseType.BTREE);
            return config;
         * Creates a new Xml transaction
         * @return
         * @throws XmlException
        public XmlTransaction createTransaction() throws XmlException {
            XmlTransaction xmlTransaction = XML_MANAGER.createTransaction();
            return xmlTransaction;
        public XmlResults executeQuery(XmlTransaction transaction, DbxmlQuery query,
                boolean commitTransaction) throws XmlException, DbxmlException {
            XmlQueryExpression queryExpression = query.getXmlQueryExpression();
            if (queryExpression.isUpdateExpression()) {
                throw new DbxmlException(DbxmlException.UPDATE_ATTEMPTED_IN_READ_QUERY);
            } else {
                XmlResults results = null;
                try {
                    if (transaction != null) {
                        results = queryExpression.execute(transaction, query.getXmlQueryContext());
                        if (commitTransaction) {
                            transaction.commit();
                    } else {
                        results = queryExpression.execute(query.getXmlQueryContext());
                } catch (Exception e) {
                    e.printStackTrace();
                    //Aborting the transaction since there was an exception and it
                    //could not be committed
                    if (transaction != null) {
                        //System.out.println("Aborting the transaction due to underlying exception... ");
                        transaction.abort();
                        //System.out.println("Transaction aborted :(");
                    if (results != null) {
                        //System.out.println("Deleting the XmlResults due to aborting the transaction...");
                        results.delete();
                        //System.out.println("XmlResults deleted :(");
                    if (queryExpression != null) {
                        //System.out.println("Deleting the QueryExpression due to aborting the transaction...");
                        queryExpression.delete();
                        //System.out.println("Query expression deleted :(");
                return results;
        public XmlResults executeUpdateQuery(XmlTransaction transaction, DbxmlQuery query,
                boolean commitTransaction) throws XmlException, DbxmlException {
            XmlQueryExpression queryExpression = query.getXmlQueryExpression();
            if (!queryExpression.isUpdateExpression()) {
                throw new DbxmlException(DbxmlException.UPDATE_QUERY_EXPECTED);
            } else {
                XmlResults results = null;
                try {
                    BasicMonitor.getMonitor().getLock();
                    if (transaction != null) {
                        results = queryExpression.execute(transaction, query.getXmlQueryContext());
                        if (commitTransaction) {
                            transaction.commit();
                    } else {
                        results = queryExpression.execute(query.getXmlQueryContext());
                } catch (Exception e) {
                    e.printStackTrace();
                    //Aborting the transaction since there was an exception and it
                    //could not be committed
                    if (transaction != null) {
                        //System.out.println("Aborting the transaction due to underlying exception... ");
                        transaction.abort();
                        //System.out.println("Transaction aborted :(");
                    if (results != null) {
                        //System.out.println("Deleting the XmlResults due to aborting the transaction...");
                        results.delete();
                        //System.out.println("XmlResults deleted :(");
                    if (queryExpression != null) {
                        //System.out.println("Deleting the QueryExpression due to aborting the transaction...");
                        queryExpression.delete();
                        //System.out.println("Query expression deleted :(");
                } finally {
                    BasicMonitor.getMonitor().releaseLock();
                return results;
         * Closes all resources associated to this manager
        public synchronized void close() {
            //xmlContainer.close();
            if(XML_MANAGER != null)
            {   try {
                    closeSequenceDataBase();
                    closeXmlContainer();
                    //System.out.println("Closing XML_MANAGER...");
                    XML_MANAGER.close();
                    //System.out.println("XML_MANAGER closed! :)");
                } catch (Exception e) {
                    e.printStackTrace();
         * Get the XmlManager
        public XmlManager getXmlManager() {
            return XML_MANAGER;
         * Get the Database
        public Database getDatabase() {
            return SEQUENCE_DATABASE;
         * Return the SequenceConfig
        public SequenceConfig getSequenceConfig() {
            return sequenceConfig;
         * Close the DataBase
        private synchronized void closeSequenceDataBase() {
            if (SEQUENCE_DATABASE != null) {
                try {
                    //System.out.println("Closing the sequence database...");
                    SEQUENCE_DATABASE.close(false);
                    //System.out.println("Sequence database closed! :)");
                } catch (DatabaseException ex) {
                    //System.out.println("There was a problem closing the sequence database... :(");
                    Logger.getLogger(BdbxmlManager.class.getName()).log(Level.SEVERE, null, ex);
         * Close the XmlContainer
        private synchronized void closeXmlContainer() {
            if (XML_CONTAINER != null) {
                try {
                    System.out.println("Closing the XmlContainer....");
                    XML_CONTAINER.close();
                    //System.out.println("XmlContainer closed! :)");
                } catch (Exception ex) {
                    //System.out.println("There was a problem closing the XmlContainer... :(");
                    Logger.getLogger(BdbxmlManager.class.getName()).log(Level.SEVERE, null, ex);
            if (XML_CONTAINER_LOGS != null) {
                try {
                    System.out.println("Closing the XmlContainer....");
                    XML_CONTAINER_LOGS.close();
                    //System.out.println("XmlContainer closed! :)");
                } catch (Exception ex) {
                    //System.out.println("There was a problem closing the XmlContainer... :(");
                    Logger.getLogger(BdbxmlManager.class.getName()).log(Level.SEVERE, null, ex);
            if (XML_CONTAINER_ERROR_LOGS != null) {
                try {
                    System.out.println("Closing the XmlContainer....");
                    XML_CONTAINER_ERROR_LOGS.close();
                    //System.out.println("XmlContainer closed! :)");
                } catch (Exception ex) {
                    //System.out.println("There was a problem closing the XmlContainer... :(");
                    Logger.getLogger(BdbxmlManager.class.getName()).log(Level.SEVERE, null, ex);
            if (XML_CONTAINER_MESSAGE != null) {
                try {
                    System.out.println("Closing the message XmlContainer....");
                    XML_CONTAINER_MESSAGE.close();
                    //System.out.println("XmlContainer closed! :)");
                } catch (Exception ex) {
                    //System.out.println("There was a problem closing the XmlContainer... :(");
                    Logger.getLogger(BdbxmlManager.class.getName()).log(Level.SEVERE, null, ex);
         * Close the Environment
        public synchronized void closeEnvironment() {
            if (ENVIRONMENT != null) {
                try {
                    System.out.println("Closing the environment....");
                    System.out.println("Closing the environment....");
                    ENVIRONMENT.close();
                    System.out.println("Environment closed! :)");
                    //singleton = null;
                } catch (IllegalArgumentException ex) {
                    System.out.println("There was IllegalArgumentException");
                    System.out.println("There was a problem closing the environment... :( "+ex.toString());
                    Logger.getLogger(BdbxmlManager.class.getName()).log(Level.SEVERE, null, ex);
                } catch (DatabaseException ex) {
                    //System.out.println("There was a problem closing the environment... :(");
                    Logger.getLogger(BdbxmlManager.class.getName()).log(Level.SEVERE, null, ex);
                } catch (Exception ex) {
                    System.out.println("There was general problem "+ex.toString());
                    Logger.getLogger(BdbxmlManager.class.getName()).log(Level.SEVERE, null, ex);
    }

    I continue the message before....
    After using the application for many days, the application failed and it hangs. The glassfish went down.
    So when I deploy the appllication again it stops in the line and I get no exception or error.
    if (XML_MANAGER.existsContainer(containerMessage.getCanonicalPath()) != 0) {Then I started to debug the code and I realize that when I open the environment in this line:
    env = new Environment(new File(ENVIRONMENT_PATH_NAME), ENVIRONMENT_CONFIG);then configuration of ENVIRONMENT_CONFIG.getRunRecovery() was set to false.
    So then I changed the settings and I set ENVIRONMENT_CONFIG.setRunRecovery(true).
    After that I deployed the application again and I got this errors:
    +[#|2011-03-04T15:05:27.900+0000|SEVERE|glassfishv3.0|javax.enterprise.system.std.com.sun.enterprise.v3.services.impl|_ThreadID=11;_ThreadName=Thread-1;|Log+
    sequence error: page LSN 12 3990397; previous LSN 13 675423
    +|#]+
    +[#|2011-03-04T15:05:27.900+0000|SEVERE|glassfishv3.0|javax.enterprise.system.std.com.sun.enterprise.v3.services.impl|_ThreadID=11;_ThreadName=Thread-1;|Recovery+
    function for LSN 13 705277 failed on forward pass
    +|#]+
    +[#|2011-03-04T15:05:27.901+0000|SEVERE|glassfishv3.0|javax.enterprise.system.std.com.sun.enterprise.v3.services.impl|_ThreadID=11;_ThreadName=Thread-1;|PANIC:+
    Invalid argument
    +|#]+
    +[#|2011-03-04T15:05:28.203+0000|SEVERE|glassfishv3.0|javax.enterprise.system.std.com.sun.enterprise.v3.services.impl|_ThreadID=11;_ThreadName=Thread-1;|unable+
    to join the environment
    +|#]+
    +[#|2011-03-04T15:05:28.258+0000|SEVERE|glassfishv3.0|com.era7.lib.bdbxmlapi.BdbxmlManager|_ThreadID=11;_ThreadName=Thread-1;|The+
    log message is null.
    com.sleepycat.db.RunRecoveryException: DB_RUNRECOVERY: Fatal error,
    run database recovery: PANIC: Invalid argument
    unable to join the environment: DB_RUNRECOVERY: Fatal error, run
    database recovery
    at com.sleepycat.db.internal.db_javaJNI.DbEnv_open(Native Method)
    at com.sleepycat.db.internal.DbEnv.open(DbEnv.java:317)
    at com.sleepycat.db.EnvironmentConfig.openEnvironment(EnvironmentConfig.java:3886)
    at com.sleepycat.db.Environment.<init>(Environment.java:93)
    at com.era7.lib.bdbxmlapi.BdbxmlManager.initEnvironment(BdbxmlManager.java:384)
    at com.era7.lib.bdbxmlapi.BdbxmlManager.init(BdbxmlManager.java:294)
    at com.era7.lib.bdbxmlapi.BdbxmlManager.<init>(BdbxmlManager.java:135)
    at com.era7.doPlanning.appConf.listeners.DoPlanningApplicationListener.createManager(DoPlanningApplicationListener.java:177)
    at com.era7.doPlanning.appConf.listeners.DoPlanningApplicationListener.configureBdbxmlInitializationParams(DoPlanningApplicationListener.java:105)
    at com.era7.lib.slbdbxml.listeners.AbstractApplicationListener.contextInitialized(AbstractApplicationListener.java:51)
    at org.apache.catalina.core.StandardContext.contextListenerStart(StandardContext.java:4591)
    at com.sun.enterprise.web.WebModule.contextListenerStart(WebModule.java:535)
    at org.apache.catalina.core.StandardContext.start(StandardContext.java:5193)
    at com.sun.enterprise.web.WebModule.start(WebModule.java:499)
    at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:928)
    at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:912)
    at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:694)
    at com.sun.enterprise.web.WebContainer.loadWebModule(WebContainer.java:1933)
    at com.sun.enterprise.web.WebContainer.loadWebModule(WebContainer.java:1605)
    at com.sun.enterprise.web.WebApplication.start(WebApplication.java:90)
    at org.glassfish.internal.data.EngineRef.start(EngineRef.java:126)
    at org.glassfish.internal.data.ModuleInfo.start(ModuleInfo.java:241)
    at org.glassfish.internal.data.ApplicationInfo.start(ApplicationInfo.java:236)
    at com.sun.enterprise.v3.server.ApplicationLifecycle.deploy(ApplicationLifecycle.java:339)
    at com.sun.enterprise.v3.server.ApplicationLoaderService.processApplication(ApplicationLoaderService.java:340)
    at com.sun.enterprise.v3.server.ApplicationLoaderService.postConstruct(ApplicationLoaderService.java:163)
    at com.sun.hk2.component.AbstractWombImpl.inject(AbstractWombImpl.java:174)
    at com.sun.hk2.component.ConstructorWomb$1.run(ConstructorWomb.java:87)
    at java.security.AccessController.doPrivileged(Native Method)
    at com.sun.hk2.component.ConstructorWomb.initialize(ConstructorWomb.java:84)
    at com.sun.hk2.component.AbstractWombImpl.get(AbstractWombImpl.java:77)
    at com.sun.hk2.component.SingletonInhabitant.get(SingletonInhabitant.java:58)
    at com.sun.hk2.component.LazyInhabitant.get(LazyInhabitant.java:107)
    at com.sun.hk2.component.AbstractInhabitantImpl.get(AbstractInhabitantImpl.java:60)
    at com.sun.enterprise.v3.server.AppServerStartup.run(AppServerStartup.java:236)
    at com.sun.enterprise.v3.server.AppServerStartup.start(AppServerStartup.java:128)
    at com.sun.enterprise.module.bootstrap.Main.launch(Main.java:457)
    at com.sun.enterprise.module.bootstrap.Main.launch(Main.java:401)
    at org.jvnet.hk2.osgiadapter.HK2Main.start(HK2Main.java:125)
    at org.apache.felix.framework.util.SecureAction.startActivator(SecureAction.java:640)
    at org.apache.felix.framework.Felix.activateBundle(Felix.java:1700)
    at org.apache.felix.framework.Felix.startBundle(Felix.java:1622)
    at org.apache.felix.framework.BundleImpl.start(BundleImpl.java:915)
    at org.jvnet.hk2.osgimain.Main.start(Main.java:140)
    at org.apache.felix.framework.util.SecureAction.startActivator(SecureAction.java:640)
    at org.apache.felix.framework.Felix.activateBundle(Felix.java:1700)
    at org.apache.felix.framework.Felix.startBundle(Felix.java:1622)
    at org.apache.felix.framework.Felix.setActiveStartLevel(Felix.java:1077)
    at org.apache.felix.framework.StartLevelImpl.run(StartLevelImpl.java:264)
    at java.lang.Thread.run(Thread.java:619)
    +|#]+
    +[#|2011-03-04T15:05:28.272+0000|SEVERE|glassfishv3.0|com.era7.doPlanning.appConf.listeners.DoPlanningApplicationListener|_ThreadID=11;_ThreadName=Thread-1;|The+
    log message is null.
    com.sleepycat.dbxml.XmlException: Invalid Environment object, may be
    closed., errcode = DATABASE_ERROR
    at com.sleepycat.db.XmlHelper.getDbEnv(XmlHelper.java:29)
    at com.sleepycat.dbxml.XmlManager.<init>(XmlManager.java:55)
    at com.era7.lib.bdbxmlapi.BdbxmlManager.initXmlManager(BdbxmlManager.java:265)
    at com.era7.lib.bdbxmlapi.BdbxmlManager.<init>(BdbxmlManager.java:137)
    at com.era7.doPlanning.appConf.listeners.DoPlanningApplicationListener.createManager(DoPlanningApplicationListener.java:177)
    at com.era7.doPlanning.appConf.listeners.DoPlanningApplicationListener.configureBdbxmlInitializationParams(DoPlanningApplicationListener.java:105)
    at com.era7.lib.slbdbxml.listeners.AbstractApplicationListener.contextInitialized(AbstractApplicationListener.java:51)
    at org.apache.catalina.core.StandardContext.contextListenerStart(StandardContext.java:4591)
    at com.sun.enterprise.web.WebModule.contextListenerStart(WebModule.java:535)
    at org.apache.catalina.core.StandardContext.start(StandardContext.java:5193)
    at com.sun.enterprise.web.WebModule.start(WebModule.java:499)
    at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:928)
    at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:912)
    at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:694)
    at com.sun.enterprise.web.WebContainer.loadWebModule(WebContainer.java:1933)
    at com.sun.enterprise.web.WebContainer.loadWebModule(WebContainer.java:1605)
    at com.sun.enterprise.web.WebApplication.start(WebApplication.java:90)
    at org.glassfish.internal.data.EngineRef.start(EngineRef.java:126)
    at org.glassfish.internal.data.ModuleInfo.start(ModuleInfo.java:241)
    at org.glassfish.internal.data.ApplicationInfo.start(ApplicationInfo.java:236)
    at com.sun.enterprise.v3.server.ApplicationLifecycle.deploy(ApplicationLifecycle.java:339)
    at com.sun.enterprise.v3.server.ApplicationLoaderService.processApplication(ApplicationLoaderService.java:340)
    at com.sun.enterprise.v3.server.ApplicationLoaderService.postConstruct(ApplicationLoaderService.java:163)
    at com.sun.hk2.component.AbstractWombImpl.inject(AbstractWombImpl.java:174)
    at com.sun.hk2.component.ConstructorWomb$1.run(ConstructorWomb.java:87)
    at java.security.AccessController.doPrivileged(Native Method)
    at com.sun.hk2.component.ConstructorWomb.initialize(ConstructorWomb.java:84)
    at com.sun.hk2.component.AbstractWombImpl.get(AbstractWombImpl.java:77)
    at com.sun.hk2.component.SingletonInhabitant.get(SingletonInhabitant.java:58)
    at com.sun.hk2.component.LazyInhabitant.get(LazyInhabitant.java:107)
    at com.sun.hk2.component.AbstractInhabitantImpl.get(AbstractInhabitantImpl.java:60)
    at com.sun.enterprise.v3.server.AppServerStartup.run(AppServerStartup.java:236)
    at com.sun.enterprise.v3.server.AppServerStartup.start(AppServerStartup.java:128)
    at com.sun.enterprise.module.bootstrap.Main.launch(Main.java:457)
    at com.sun.enterprise.module.bootstrap.Main.launch(Main.java:401)
    at org.jvnet.hk2.osgiadapter.HK2Main.start(HK2Main.java:125)
    at org.apache.felix.framework.util.SecureAction.startActivator(SecureAction.java:640)
    at org.apache.felix.framework.Felix.activateBundle(Felix.java:1700)
    at org.apache.felix.framework.Felix.startBundle(Felix.java:1622)
    at org.apache.felix.framework.BundleImpl.start(BundleImpl.java:915)
    at org.jvnet.hk2.osgimain.Main.start(Main.java:140)
    at org.apache.felix.framework.util.SecureAction.startActivator(SecureAction.java:640)
    at org.apache.felix.framework.Felix.activateBundle(Felix.java:1700)
    at org.apache.felix.framework.Felix.startBundle(Felix.java:1622)
    at org.apache.felix.framework.Felix.setActiveStartLevel(Felix.java:1077)
    at org.apache.felix.framework.StartLevelImpl.run(StartLevelImpl.java:264)
    at java.lang.Thread.run(Thread.java:619)
    +|#]+
    For more information, when I run db_recover I got this errors
    BXML.2.5/bin/db_recover -c
    db_recover: Log sequence error: page LSN 12 3990397; previous LSN 13 675423
    db_recover: Recovery function for LSN 13 705277 failed on forward pass
    db_recover: PANIC: Invalid argument
    db_recover: PANIC: fatal region error detected; run recovery
    db_recover: /DBPool/DoPlanning/DoPlanningDB/era7/doPlanning.dbxml:
    write failed for page 764
    db_recover: /DBPool/DoPlanning/DoPlanningDB/era7/doPlanning.dbxml:
    unable to flush page: 764
    db_recover: process-private: unable to find environment
    db_recover: DB_ENV->open: DB_RUNRECOVERY: Fatal error, run database recovery
    BXML.2.5/bin/db_recover -c -v
    Finding last valid log LSN: file: 34 offset 10311907
    Recovery starting from [1][28]
    db_recover: Log sequence error: page LSN 12 3990397; previous LSN 13 675423
    db_recover: Recovery function for LSN 13 705277 failed on forward pass
    db_recover: PANIC: Invalid argument
    db_recover: PANIC: fatal region error detected; run recovery
    db_recover: /DBPool/DoPlanning/DoPlanningDB/era7/doPlanning.dbxml:
    write failed for page 764
    db_recover: /DBPool/DoPlanning/DoPlanningDB/era7/doPlanning.dbxml:
    unable to flush page: 764
    db_recover: process-private: unable to find environment
    db_recover: DB_ENV->open: DB_RUNRECOVERY: Fatal error, run database recovery
    When I run db_stat -e:
    Mon Mar  7 09:22:23 2011        Local time
    +0x120897 Magic number+
    +0 Panic value+
    +4.8.24 Environment version+
    +9 Btree version+
    +9 Hash version+
    +1 Lock version+
    +15 Log version+
    +4 Queue version+
    +2 Sequence version+
    +1 Txn version+
    Fri Mar  4 15:34:36 2011        Creation time
    +0xcf201e5f Environment ID+
    +2 Primary region allocation and reference count mutex [0/4 0% !Own]+
    +3 References+
    +=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=+
    +0x40988 Log magic number+
    +15 Log version number+
    +50MB Log record cache size+
    +0 Log file mode+
    +10Mb Current log file size+
    +9777 Records entered into the log+
    +895KB 899B Log bytes written+
    +895KB 899B Log bytes written since last checkpoint+
    +123 Total log file I/O writes+
    +0 Total log file I/O writes due to overflow+
    +123 Total log file flushes+
    +24737 Total log file I/O reads+
    +34 Current log file number+
    +10435138 Current log file offset+
    +34 On-disk log file number+
    +10435138 On-disk log file offset+
    +1 Maximum commits in a log flush+
    +1 Minimum commits in a log flush+
    +50MB 256KB Log region size+
    +0 The number of region locks that required waiting (0%)+
    +=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=+
    +=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=+
    +2123 Last allocated locker ID+
    +0x7fffffff Current maximum unused locker ID+
    +9 Number of lock modes+
    +15000 Maximum number of locks possible+
    +15000 Maximum number of lockers possible+
    +15000 Maximum number of lock objects possible+
    +1 Number of lock object partitions+
    +176 Number of current locks+
    +182 Maximum number of locks at any one time+
    +20 Maximum number of locks in any one bucket+
    +0 Maximum number of locks stolen by for an empty partition+
    +0 Maximum number of locks stolen for any one partition+
    +346 Number of current lockers+
    +361 Maximum number of lockers at any one time+
    +44 Number of current lock objects+
    +70 Maximum number of lock objects at any one time+
    +2 Maximum number of lock objects in any one bucket+
    +0 Maximum number of objects stolen by for an empty partition+
    +0 Maximum number of objects stolen for any one partition+
    +158M Total number of locks requested (158999583)+
    +158M Total number of locks released (158999340)+
    +0 Total number of locks upgraded+
    +727 Total number of locks downgraded+
    +19 Lock requests not available due to conflicts, for which we waited+
    +11 Lock requests not available due to conflicts, for which we did not wait+
    +0 Number of deadlocks+
    +0 Lock timeout value+
    +0 Number of locks that have timed out+
    +0 Transaction timeout value+
    +0 Number of transactions that have timed out+
    +7MB 840KB The size of the lock region+
    +0 The number of partition locks that required waiting (0%)+
    +0 The maximum number of times any partition lock was waited for (0%)+
    +0 The number of object queue operations that required waiting (0%)+
    +0 The number of locker allocations that required waiting (0%)+
    +115 The number of region locks that required waiting (0%)+
    +2 Maximum hash bucket length+
    +=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=+
    +6MB 257KB 604B Total cache size+
    +1 Number of caches+
    +1 Maximum number of caches+
    +6MB 264KB Pool individual cache size+
    +0 Maximum memory-mapped file size+
    +0 Maximum open file descriptors+
    +0 Maximum sequential buffer writes+
    +0 Sleep after writing maximum sequential buffers+
    +10 Requested pages mapped into the process' address space+
    +344M Requested pages found in the cache (99%)+
    +1282817 Requested pages not found in the cache+
    +3319 Pages created in the cache+
    +1282817 Pages read into the cache+
    +7780 Pages written from the cache to the backing file+
    +1277963 Clean pages forced from the cache+
    +7779 Dirty pages forced from the cache+
    +0 Dirty pages written by trickle-sync thread+
    +395 Current total page count+
    +389 Current clean page count+
    +6 Current dirty page count+
    +1031 Number of hash buckets used for page location+
    +4096 Assumed page size used+
    +346M Total number of times hash chains searched for a page (346931510)+
    +4 The longest hash chain searched for a page+
    +389M Total number of hash chain entries checked for page (389374869)+
    +0 The number of hash bucket locks that required waiting (0%)+
    +0 The maximum number of times any hash bucket lock was waited for (0%)+
    +0 The number of region locks that required waiting (0%)+
    +0 The number of buffers frozen+
    +0 The number of buffers thawed+
    +0 The number of frozen buffers freed+
    +1286173 The number of page allocations+
    +5923486 The number of hash buckets examined during allocations+
    +29 The maximum number of hash buckets examined for an allocation+
    +1285743 The number of pages examined during allocations+
    +2 The max number of pages examined for an allocation+
    +0 Threads waited on page I/O+
    +0 The number of times a sync is interrupted+
    Pool File: /DBPool/DoPlanning/DoPlanningDB/era7/doPlanningLogs.dbxml
    +16384 Page size+
    +0 Requested pages mapped into the process' address space+
    +766861 Requested pages found in the cache (99%)+
    +3408 Requested pages not found in the cache+
    +9 Pages created in the cache+
    +3408 Pages read into the cache+
    +595 Pages written from the cache to the backing file+
    Pool File: /DBPool/DoPlanning/DoPlanningDB/era7/doPlanning.dbxml
    +16384 Page size+
    +0 Requested pages mapped into the process' address space+
    +344M Requested pages found in the cache (99%)+
    +1278423 Requested pages not found in the cache+
    +3309 Pages created in the cache+
    +1278423 Pages read into the cache+
    +7117 Pages written from the cache to the backing file+
    Pool File: sequenceDb
    +16384 Page size+
    +0 Requested pages mapped into the process' address space+
    +2 Requested pages found in the cache (25%)+
    +6 Requested pages not found in the cache+
    +0 Pages created in the cache+
    +6 Pages read into the cache+
    +1 Pages written from the cache to the backing file+
    Pool File: /DBPool/DoPlanning/DoPlanningDB/era7/doPlanningMessages.dbxml
    +16384 Page size+
    +0 Requested pages mapped into the process' address space+
    +7111 Requested pages found in the cache (88%)+
    +926 Requested pages not found in the cache+
    +1 Pages created in the cache+
    +926 Pages read into the cache+
    +58 Pages written from the cache to the backing file+
    Pool File: /DBPool/DoPlanning/DoPlanningDB/era7/doPlanningErrorLogs.dbxml
    +16384 Page size+
    +0 Requested pages mapped into the process' address space+
    +1322 Requested pages found in the cache (96%)+
    +54 Requested pages not found in the cache+
    +0 Pages created in the cache+
    +54 Pages read into the cache+
    +9 Pages written from the cache to the backing file+
    +=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=+
    +0/0 No checkpoint LSN+
    Fri Mar  4 15:34:47 2011        Checkpoint timestamp
    +0x80000b22 Last transaction ID allocated+
    +5000 Maximum number of active transactions configured+
    +18 Active transactions+
    +22 Maximum active transactions+
    +2850 Number of transactions begun+
    +12 Number of transactions aborted+
    +2820 Number of transactions committed+
    +0 Snapshot transactions+
    +0 Maximum snapshot transactions+
    +0 Number of transactions restored+
    +1MB 456KB Transaction region size+
    +0 The number of region locks that required waiting (0%)+
    Active transactions:
    +800009c2: running; pid/thread 29365/1322; begin LSN: file/offset 0/0+
    +800009d2: running; pid/thread 29365/1323; begin LSN: file/offset 0/0+
    +800009e0: running; pid/thread 29365/1332; begin LSN: file/offset 0/0+
    +800009ec: running; pid/thread 29365/1333; begin LSN: file/offset 0/0+
    +800009f8: running; pid/thread 29365/1334; begin LSN: file/offset 0/0+
    +80000a04: running; pid/thread 29365/1335; begin LSN: file/offset 0/0+
    +80000a10: running; pid/thread 29365/1336; begin LSN: file/offset 0/0+
    +80000a17: running; pid/thread 29365/1337; begin LSN: file/offset 0/0+
    +80000a23: running; pid/thread 29365/1338; begin LSN: file/offset 0/0+
    +80000a35: running; pid/thread 29365/1339; begin LSN: file/offset 0/0+
    +80000a58: running; pid/thread 29365/1341; begin LSN: file/offset 0/0+
    +80000a62: running; pid/thread 29365/1349; begin LSN: file/offset 0/0+
    +80000a74: running; pid/thread 29365/1350; begin LSN: file/offset 0/0+
    +80000a80: running; pid/thread 29365/1351; begin LSN: file/offset 0/0+
    +80000a8c: running; pid/thread 29365/1352; begin LSN: file/offset 0/0+
    +80000a98: running; pid/thread 29365/1353; begin LSN: file/offset 0/0+
    +80000aa6: running; pid/thread 29365/1354; begin LSN: file/offset 0/0+
    +80000ad1: running; pid/thread 29365/134; begin LSN: file/offset 0/0+
    +=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=+
    +3MB 448KB Mutex region size+
    +0 The number of region locks that required waiting (0%)+
    +4 Mutex alignment+
    +1 Mutex test-and-set spins+
    +30000 Mutex total count+
    +28206 Mutex free count+
    +1794 Mutex in-use count+
    +1819 Mutex maximum in-use count+
    Mutex counts
    +28206 Unallocated+
    +116 db handle+
    +2 env dblist+
    +4 env handle+
    +1 env region+
    +4 lock region+
    +182 logical lock+
    +1 log filename+
    +1 log flush+
    +3 log region+
    +5 mpoolfile handle+
    +395 mpool buffer+
    +10 mpool filehandle+
    +17 mpool file bucket+
    +2 mpool handle+
    +1031 mpool hash bucket+
    +1 mpool region+
    +1 mutex region+
    +12 sequence+
    +2 twister+
    +2 txn active list+
    +1 transaction checkpoint+
    +1 txn region+
    I try to run db_verify but I don't know the right way and I get:
    +db_verify [-NoqV] [-h home] [-P password] db_file ...+
    Thank you for everything

  • Error opening environment more than once

    Hi,
    I have two java classes which both need to access a container in an environment (in parallel). When the first class is instantiated the environment is opened successfully. However, when the second class subsequently attempts to open the same environment I get an error. (I do not want to close the env from the first class, while the second class does its thing)
    The classes are Stylesheet extensions for an xmleditor which allows the stylesheet to look up item ID codes and display their names to the user by looking up the values in an xml file stored in a bdbxml container. There is a situation where two different objects need to have access to the environment at the same time - but its giving me an error when I instantiate the env for the second time - without having closed the first one)
    Any help would by gratefully received
    Kind Regards
    Swami Kevala
    I thought I could create multiple handles to the same environment?

    First is a class to encapsulate the environment (lifted mostly from the example code)
    package org.isha.archives.bdbxml;
    import java.io.*;
    import java.util.*;
    import com.sleepycat.db.*;
    import com.sleepycat.dbxml.*;
    //Class used to open and close a Berkeley DB environment
    public class DbEnv
    private Environment dbEnv_ = null;
    private XmlManager mgr_ = null;
    private boolean dbEnvIsOpen_ = false;
    private File path2DbEnv_ = null;
    public DbEnv(File path2DbEnv)
         throws Throwable {
              if (! path2DbEnv.isDirectory()) {
                   throw new Exception(path2DbEnv.getPath() +
                             " does not exist or is not a directory.");
              EnvironmentConfig config = new EnvironmentConfig();
              config.setCacheSize(50 * 1024 * 1024);
              config.setAllowCreate(true);
              config.setInitializeCache(true);
              config.setTransactional(true);
              config.setInitializeLocking(true);
              config.setInitializeLogging(true);
              config.setErrorStream(System.err);
              config.setThreaded(true);
              config.setRunRecovery(true);
              config.setLogAutoRemove(true);
              dbEnv_ = new Environment(path2DbEnv, config);
              //Boolean used to know whether to close the environment
              // when the cleanup() method is called.
              dbEnvIsOpen_ = true;
              path2DbEnv_ = path2DbEnv;
              mgr_ = new XmlManager(dbEnv_, null);
    //Returns the path to the database environment
    public File getDbEnvPath() { return path2DbEnv_; }
    //Returns the database environment encapsulated by this class.
    public Environment getEnvironment() { return dbEnv_; }
    //Returns the XmlManager encapsulated by this class.
    public XmlManager getManager() { return mgr_; }
    //Used to close the environment
    public void cleanup() throws DatabaseException
    if (dbEnvIsOpen_) {
    dbEnv_.close();
    dbEnvIsOpen_ = false;
    Second is a class which encapsulates a container with a method for querying itself
    package org.isha.archives.bdbxml;
    import java.io.*;
    import java.util.*;
    import com.sleepycat.db.*;
    import com.sleepycat.dbxml.*;
    //Class used to open, query and close a Berkeley DB container
    public class DbContainer
         private XmlContainer dbCont_ = null;
    private XmlManager mgr_ = null;
    private boolean dbContainerIsOpen_ = false;
    private File path2DbContainer_ = null;
    private XmlContainerConfig cfg_= null;
    private String cntr_ = "";
    public DbContainer(XmlManager myManager, String containerFileName, XmlContainerConfig containerConfig)
              throws Throwable {
              String containerFilepath = myManager.getHome() + "\\" + containerFileName;
              path2DbContainer_ = new File(containerFilepath);
              mgr_ = myManager;
              cfg_ = containerConfig;
              cntr_ = containerFileName;
              if (! path2DbContainer_.isFile()) {
                   throw new Exception(path2DbContainer_.getPath() +
                             " does not exist or is not a directory.");
              dbCont_ = new XmlContainer();
    //Return the XmlContainer itself
    public XmlContainer getContainer() { return dbCont_; }
    //Returns the filename of the container
         public String getFilename() { return cntr_; }
    //Returns the XmlManager encapsulated by this class.
    public XmlManager getManager() { return mgr_; }
    //Used to close the container
    public void close() throws DatabaseException
    if (dbContainerIsOpen_) {
    dbCont_.close();
    dbContainerIsOpen_ = false;
    //Used to open the container
    public void open() {
              try {
                   dbCont_ = mgr_.openContainer(cntr_, cfg_);
                   dbContainerIsOpen_ = true;
              catch (Exception e) {
    //Used to query the container
    public String[] runQuery(String myQuery){
              String [] queryOutput = null;
              int counter = 0;
              try {
                   XmlQueryContext context = mgr_.createQueryContext();
                   //Default namespace declaration does not work yet - this will work in the next release of BDB XML
                   //Until then we have to remove the namespace declaration from the reference.xml root element
                   //When this becomes available we can add the namespace declaration and uncomment the following line
                   //context.setNamespace("", defaultNS);
                   XmlResults results = mgr_.query(myQuery, context);
                   //Get the result set
                   queryOutput = new String[results.size()];
                   XmlValue value = results.next();
                   while (value != null)
                        queryOutput[counter] = value.asString().replaceAll("\\n", "").replaceAll(" "," ");
                        System.out.println(queryOutput[counter]);
                        counter ++;
                        value = results.next();
              catch (Exception e) {
                   //Exception Handling code here
              return queryOutput;
    Now to explain what is happening:
    When I open an xml document in xmlmind, it displays the document according to a prespecified CSS sheet. Sometimes the CSS rules alone are not sufficient to achieve the necessary effect/functionality, so the API allows you to write your own class, which contains methods to do what you want. As soon as the xml document is displayed, the CSS extension class gets instantiated.
    Here is my extension class (called StyleSheetExtension). It contains a method called getKeywords. This method can then be invoked from within the CSS sheet, and is used to replace the keyword ID codes in the xml document with their corresponding keyword names - stored in an xml reference look-up document...
    package org.isha.archives.xmlmind;
    import com.xmlmind.xmledit.xmlutil.*;
    import com.xmlmind.xmledit.doc.*;
    import com.xmlmind.xmledit.view.DocumentView;
    import com.xmlmind.xmledit.stylesheet.StyleValue;
    import com.xmlmind.xmledit.stylesheet.StyleSpec;
    import com.xmlmind.xmledit.stylesheet.StyleSpecsBase;
    import com.xmlmind.xmledit.styledview.StyledViewFactory;
    import com.xmlmind.xmledit.styledview.CustomViewManager;
    import com.sleepycat.dbxml.*;
    import com.sleepycat.db.*;
    import java.io.File;
    import java.util.logging.*;
    import java.util.*;
    import org.isha.archives.bdbxml.DbContainer;
    import org.isha.archives.bdbxml.DbEnv;
    public class StyleSheetExtension {
         //Logging variables
         private Logger logger = Logger.getLogger("StyleSheetExtension");
         private Handler fh = null;
         private java.util.logging.Formatter sf = null;
         //XMLMind variables
         private static final Namespace NS = Namespace.get("http://www.ishafoundation.org/archives/schema/transcript");
         //BDB variables
         private DbEnv myDbEnv = null;
         private File envDir = new File("C:\\BerkeleyDB");
         private DbContainer myDbContainer = null;
         private String containerFileName = "reference.dbxml";
         private XmlContainerConfig containerCfg = null;
         //Define Constructor
         public StyleSheetExtension(String[] args, StyledViewFactory viewFactory) {
    //Set up simple logging system
    try {
    fh = new FileHandler("%t/_styleSheetExtn.log");
    sf = new SimpleFormatter();
    fh.setFormatter(sf);
    logger.addHandler(fh);
    logger.setLevel(Level.ALL);
    logger.info("Starting StyleSheetExtension Class constructor");
    } catch (Exception e)
    {System.out.println("CustomErr: " + e.getMessage());
                    //Exception Handling code
    //Create custom BDB Environment and Container Objects
    try {
                        myDbEnv = new DbEnv(envDir);
                        containerCfg = new XmlContainerConfig();
                        myDbContainer = new DbContainer(myDbEnv.getManager(), containerFileName, containerCfg);
                        myDbContainer.open();
                   } catch (Throwable t) {
                        logger.severe("Problem with Env or Container new thing");
    viewFactory.addDependency( NS, "topic", NS, "keywordIDs");
         public StyleValue getKeywords (StyleValue[] args, Node contextNode,
                             StyledViewFactory viewFactory) {
    //Get keyword IDs as a String array
    String[] keywordID = null;
    String[] keywordValue = null;
    String keywordIDStr = "";
    String keywordValueStr ="";
    Name keywordIDs = Name.get("keywordIDs");
    keywordIDStr = contextNode.attributeValue(keywordIDs).trim();
    keywordID = keywordIDStr.split("\\s+");
    keywordValue = new String[keywordID.length];
    //for each keyword ID element retrieve the corresponding keyword value
    logger.info("getting values");
                   keywordValue = getKeywordValuesFromDB(keywordID);
                   Arrays.sort(keywordValue);
                   logger.info(keywordValue[0] + " " + keywordValue[1]);
                   int i = 0;
                   for(i=0; i < keywordID.length; i++) {
                        keywordValueStr += keywordValue[i] + " ";
                   keywordValueStr = keywordValueStr.trim();
              return StyleValue.createString(keywordValueStr);
    private String[] getKeywordValuesFromDB(String[] IDs){
                   String[] values = new String[IDs.length];
                   String id = "";
                   String value = "";
                   String flwor = "";
                   int i = 0;
                   for(i=0; i < IDs.length; i++) {
                        id = IDs.trim();
                        flwor = "for $i in collection('" + myDbContainer.getFilename() + "') /reference/keywords/keyword \n";
                        flwor += "let $id := $i/@id/text() \n";
                        flwor += "let $val := $i/@value/text() \n";
                        flwor += "where $id = '" + id + "'\n";
                        flwor += "return $val";
                        String[] temp = new String[1];
                        temp = myDbContainer.runQuery(flwor);
                        values[i] = temp[0];
                        logger.info("value is: " + values[i]);
                   return values;
    package org.isha.archives.xmlmind;
    import com.xmlmind.xmledit.xmlutil.*;
    import com.xmlmind.xmledit.doc.*;
    import com.xmlmind.xmledit.view.DocumentView;
    import com.xmlmind.xmledit.stylesheet.StyleValue;
    import com.xmlmind.xmledit.stylesheet.StyleSpec;
    import com.xmlmind.xmledit.stylesheet.StyleSpecsBase;
    import com.xmlmind.xmledit.styledview.StyledViewFactory;
    import com.xmlmind.xmledit.styledview.CustomViewManager;
    import com.sleepycat.dbxml.*;
    import com.sleepycat.db.*;
    import java.io.File;
    import java.util.logging.*;
    import java.util.*;
    import org.isha.archives.bdbxml.DbContainer;
    import org.isha.archives.bdbxml.DbEnv;
    public class StyleSheetExtension {
         //Logging variables
         private Logger logger = Logger.getLogger("StyleSheetExtension");
         private Handler fh = null;
         private java.util.logging.Formatter sf = null;
         //XMLMind variables
         private static final Namespace NS = Namespace.get("http://www.ishafoundation.org/archives/schema/transcript");
         //BDB variables
         private DbEnv myDbEnv = null;
         private File envDir = new File("C:\\BerkeleyDB");
         private DbContainer myDbContainer = null;
         private String containerFileName = "reference.dbxml";
         private XmlContainerConfig containerCfg = null;
         //Define Constructor
         public StyleSheetExtension(String[] args, StyledViewFactory viewFactory) {
    //Set up simple logging system
    try {
    fh = new FileHandler("%t/_styleSheetExtn.log");
    sf = new SimpleFormatter();
    fh.setFormatter(sf);
    logger.addHandler(fh);
    logger.setLevel(Level.ALL);
    logger.info("Starting StyleSheetExtension Class constructor");
    } catch (Exception e)
    {System.out.println("CustomErr: " + e.getMessage());
                    //Exception Handling code
    //Create custom BDB Environment and Container Objects
    try {
                        myDbEnv = new DbEnv(envDir);
                        containerCfg = new XmlContainerConfig();
                        myDbContainer = new DbContainer(myDbEnv.getManager(), containerFileName, containerCfg);
                        myDbContainer.open();
                   } catch (Throwable t) {
                        logger.severe("Problem with Env or Container new thing");
    viewFactory.addDependency( NS, "topic", NS, "keywordIDs");
         public StyleValue getKeywords (StyleValue[] args, Node contextNode,
                             StyledViewFactory viewFactory) {
    //Get keyword IDs as a String array
    String[] keywordID = null;
    String[] keywordValue = null;
    String keywordIDStr = "";
    String keywordValueStr ="";
    Name keywordIDs = Name.get("keywordIDs");
    keywordIDStr = contextNode.attributeValue(keywordIDs).trim();
    keywordID = keywordIDStr.split("\\s+");
    keywordValue = new String[keywordID.length];
    //for each keyword ID element retrieve the corresponding keyword value
    logger.info("getting values");
                   keywordValue = getKeywordValuesFromDB(keywordID);
                   Arrays.sort(keywordValue);
                   logger.info(keywordValue[0] + " " + keywordValue[1]);
                   int i = 0;
                   for(i=0; i < keywordID.length; i++) {
                        keywordValueStr += keywordValue[i] + " ";
                   keywordValueStr = keywordValueStr.trim();
              return StyleValue.createString(keywordValueStr);
    private String[] getKeywordValuesFromDB(String[] IDs){
                   String[] values = new String[IDs.length];
                   String id = "";
                   String value = "";
                   String flwor = "";
                   int i = 0;
                   for(i=0; i < IDs.length; i++) {
                        id = IDs[i].trim();
                        flwor = "for $i in collection('" + myDbContainer.getFilename() + "') /reference/keywords/keyword \n";
                        flwor += "let $id := $i/@id/text() \n";
                        flwor += "let $val := $i/@value/text() \n";
                        flwor += "where $id = '" + id + "'\n";
                        flwor += "return $val";
                        String[] temp = new String[1];
                        temp = myDbContainer.runQuery(flwor);
                        values[i] = temp[0];
                        logger.info("value is: " + values[i]);
                   return values;
    This instance (and consequently the newly created env and container objects) stay alive until the document is closed.
    The xmlmind API also allows you to specify custom classes that will return a component that can be embedded in the stylesheet. (My class returns a JButton which - when clicked - brings up a dialog box which allows the user to specify /modify/addnew keywords to the selected text). As soon as the button is pressed I create a new env and container instance, for the duration of the pop-up window (since I have no way to pass the reference to the existing environment created by the StyleSheetExtension class.
    Here's the class defn: (Here goes!) The env and container stuff is at the start of the nested-nested class called KpForm.
    package org.isha.archives.xmlmind;
    import com.sleepycat.dbxml.*;
    import com.sleepycat.db.*;
    import java.awt.*;
    import java.io.*;
    import javax.swing.*;
    import javax.swing.text.AttributeSet;
    import javax.swing.text.AbstractDocument;
    import javax.swing.text.DocumentFilter;
    import javax.swing.text.BadLocationException;
    import javax.swing.event.*;
    import javax.swing.text.DocumentFilter.FilterBypass;
    import java.util.*;
    import java.util.regex.*;
    import java.lang.*;
    import com.xmlmind.xmledit.xmlutil.*;
    import com.xmlmind.xmledit.doc.Element;
    import com.xmlmind.xmledit.edit.*;
    import com.xmlmind.xmledit.stylesheet.*;
    import com.xmlmind.xmledit.styledgadget.*;
    import com.xmlmind.xmledit.styledview.*;
    import com.xmlmind.xmledit.doc.*;
    import java.util.logging.*;
    import org.isha.archives.bdbxml.DbEnv;
    import org.isha.archives.bdbxml.DbContainer;
    public class OpenKeywordPicker implements ComponentFactory {
    public Component createComponent(Element element,
    Style style, StyleValue[] parameters,
    StyledViewFactory viewFactory,
    boolean[] stretch){
    KeywordEdit topic = new KeywordEdit();
    return topic;
         private class KeywordEdit extends JButton {
              //private Element element;
              public KeywordEdit()
                   super.setText("Edit");
                   super.addMouseListener(new java.awt.event.MouseAdapter() {
                                  public void mouseClicked(java.awt.event.MouseEvent evt) {
                                       myJButtonMouseClicked(evt);
              private void myJButtonMouseClicked(java.awt.event.MouseEvent evt) {
                        KpForm myForm = new KpForm();
                        myForm.setVisible(true);
    private class KpForm extends javax.swing.JFrame {
         // Variables declaration - do not modify
         private javax.swing.JButton jButton1;
         private javax.swing.JButton jButton2;
         private javax.swing.JButton jButton3;
         private javax.swing.JButton jButton4;
         private javax.swing.JButton jButton5;
         private javax.swing.JButton jButton6;
         private javax.swing.JLabel jLabel1;
         private javax.swing.JLabel jLabel2;
         private javax.swing.JLabel jLabel3;
         private javax.swing.JLabel jLabel4;
         private javax.swing.JLabel jLabel5;
         private javax.swing.JList jList1;
         private javax.swing.JList jList2;
         private javax.swing.JList jList3;
         private javax.swing.JScrollPane jScrollPane1;
         private javax.swing.JScrollPane jScrollPane2;
         private javax.swing.JScrollPane jScrollPane3;
         private javax.swing.JScrollPane jScrollPane4;
         private javax.swing.JTextArea jTextArea1;
         private javax.swing.JTextField jTextField1;
         private DefaultListModel model_1 = new DefaultListModel();
              private DefaultListModel model_2 = new DefaultListModel();
              private DefaultListModel model_3 = new DefaultListModel();
              private javax.swing.JOptionPane jOptionPane1;
              //private KeywordFilter filter_1 = new KeywordFilter();
              //BDB variables
              private DbEnv myDbEnv = null;
              private File envDir = new File("C:\\BerkeleyDB");
              private DbContainer myDbContainer = null;
              private String containerFileName = "reference.dbxml";
              private XmlContainerConfig containerCfg = null;
              private Logger logger = Logger.getLogger("OpenKeywordPicker.KeywordEdit.KpForm");
              private Handler fh = null;
              private java.util.logging.Formatter sf = null;
    // End of variables declaration
         /** Creates new form kpForm */
         public KpForm() {
                   super();
         initComponents();
         customInit();
              private void customInit(){
                        //Set up simple logging system
                   try {
                        fh = new FileHandler("%t/_keywordPicker.log");
                        sf = new SimpleFormatter();
                        fh.setFormatter(sf);
                        logger.addHandler(fh);
                        logger.setLevel(Level.ALL);
                        logger.info("Starting Custom initialization");
                   } catch (Exception e) {System.out.println("CustomErr: " + e.getMessage());
                              //Exception Handling code
                        //Create custom BDB Environment and Container Objects
                        try {
                             logger.info("0");
                             myDbEnv = new DbEnv(envDir);
                             logger.info("1");
                             containerCfg = new XmlContainerConfig();
                             logger.info("2");
                             myDbContainer = new DbContainer(myDbEnv.getManager(), containerFileName, containerCfg);
                             logger.info("3");
                             myDbContainer.open();
                        } catch (Throwable t) {
                             logger.severe("Problem with Env or Container new thing - Component: "+ t.getMessage());
              String[] dbIDKeywords;
              jList1.setModel(model_1);
              jList2.setModel(model_2);
              jList3.setModel(model_3);
              dbIDKeywords = getKeywordsFromDB();
              int i=0;
              for(i=0; i < dbIDKeywords.length; i+=2){
              model_1.addElement(new keywordOb(dbIDKeywords[i], dbIDKeywords[i+1]));
              jList1.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
              jList2.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
              jList3.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
              //Setup Document Filter for TextField component
              AbstractDocument doc;
              doc = (AbstractDocument)(jTextField1.getDocument());
              doc.setDocumentFilter(filter_1);
              //Setup Document Listener for TextField component
              jTextField1.getDocument().addDocumentListener(new DocumentListener(){
              public void insertUpdate(DocumentEvent e) {
              String val = jTextField1.getText();
              if(val != null & val.trim() != ""){
              jButton1.setEnabled(true);
              else {
              jButton1.setEnabled(false);
              public void removeUpdate(DocumentEvent e) {
              String val = jTextField1.getText();
              if(val != null & !val.trim().equals("")){
              jButton1.setEnabled(true);
              else {
              jButton1.setEnabled(false);
              public void changedUpdate(DocumentEvent e) {
              //Plain text components do not fire these events
              private String[] getKeywordsFromDB(){
              String[] k = null;
              String flwor = "";
              flwor = "for $i in collection('" + containerFileName + "') /reference/keywords/keyword \n";
              flwor += "let $id := $i/@id/text() \n";
              flwor += "let $val := $i/@value/text() \n";
              flwor += "order by $val ascending \n";
              flwor += "return ($id, $val)";
              return k = myDbContainer.runQuery(flwor);
              private class keywordOb implements Comparable{
              private String id;
              private String value;
              public keywordOb(String id, String value){
              this.id = id;
              this.value = value;
              public String getId(){
              return id;
              public String getValue(){
              return value;
              public String toString(){
              return value;
              public int compareTo(Object o){
                                  int result = (((keywordOb)this).toString()).compareTo(((keywordOb)o).toString());
                                  return result;
              private class questionOb implements Comparable{
              private String id;
              private String value;
              private String[] keywordRefs;
              public questionOb(String id, String value, String[] keywordRefs){
              this.id = id;
              this.value = value;
              this.keywordRefs = keywordRefs;
              public questionOb(){
              this.id = "";
              this.value = "";
              this.keywordRefs = null;
              public String getId(){
              return id;
              public String getValue(){
              return value;
              public String toString(){
              return value;
              public String[] getKeywordRefs(){
              return keywordRefs;
              public void setId(String id){
              this.id = id;
              public void setValue(String value){
              this.value = value;
              public void setKeywordRefs(String[] keywords){
              this.keywordRefs = keywordRefs;
              public int compareTo(Object o){
                             int result = (((questionOb)this).toString()).compareTo(((questionOb)o).toString());
                             return result;
              //Add New Keyword to xml reference File
              private void addNewKeyword(String k){
              String keyword = k;
              int len = jTextField1.getDocument().getLength();
              //Tidy up string
              keyword = keyword.trim();
              keyword = keyword.replaceAll("\\s+"," ");
              keyword = capitalizeWords(keyword);
              String flwor = "";
              //Check that the keyword value doesn't already exist
              flwor = "let $i := collection('" + containerFileName + "')/reference/keywords/keyword[@value = '" + keyword + "'] \n";
              flwor += "return \n";
              flwor += "if(count($i)) then fn:true() \n";
              flwor += "else fn:false() \n";
              boolean keywordExists = bDbConnection.runBooleanQuery(flwor);
              if (keywordExists){
              jOptionPane1.showMessageDialog(new Frame(),
              "The keyword '" + keyword + "' already exists", "Message", jOptionPane1.INFORMATION_MESSAGE);
              try {
              jTextField1.getDocument().remove(0,len);
              } catch (Exception ex) {
              ex.printStackTrace();
              //Terminate method execution
              return;
              //Need to get ID of last keyword
              flwor = "for $i in collection('" + containerFileName + "')/reference/keywords/keyword/@id/text() \n";
              flwor += "order by $i descending \n";
              flwor += "return $i[fn:last()]";
              String[] lastIDArray = new String[1];
              lastIDArray = bDbConnection.runQuery(flwor);
              String lastIDStr = lastIDArray[0];
              //create incremented ID value
              //Note: XML ID attributes must start with a letter - that's why we need to do all this nonsense!
              int lastIDNum = new Integer(lastIDStr.substring(1));
              int nextIDNum = ++lastIDNum;
              String nextIDStr = String.format("%04d", nextIDNum);
              nextIDStr = "K" + nextIDStr;
              //OK Finally - actually add the keyword to the xml reference file
              //use BDB API for updating - since XQuery does not allow
              try
              XmlQueryContext qc = myManager.createQueryContext();
              XmlUpdateContext uc = myManager.createUpdateContext();
              XmlModify mod = myManager.createModify();
              XmlQueryExpression select = myManager.prepare("/reference/keywords", qc);
              mod.addAppendStep(select, XmlModify.Element, "keyword", "");
              select = myManager.prepare("/reference/keywords/keyword[fn:last()]", qc);
              mod.addAppendStep(select, XmlModify.Attribute, "id", nextIDStr);
              mod.addAppendStep(select, XmlModify.Attribute, "value", keyword);
              XmlDocument updateDoc = myContainer.getDocument(docName);
              XmlValue docValue = new XmlValue(updateDoc);
              mod.execute(docValue, qc, uc);
              catch(Exception e){
              System.out.println("Error adding keyword: " + e.getMessage());
              //Add the new keyword to the list of selected keywords
              model_2.addElement(keyword);
              sortModelElements(model_2);
              try {
              jTextField1.getDocument().remove(0,len);
              } catch (Exception ex) {
              ex.printStackTrace();
              private questionOb[] getQuestionsFromDB(keywordOb[] keywordIDs){
              questionOb[] qobs = null;
              String seq = "";
              String flwor = "";
              int num = 0;
              seq = keywordObsToSeq(keywordIDs);
              flwor = "for $i in " + seq + "\n";
              flwor += "let $q := collection('" + containerFileName + "') /reference/questions/question[./keywordRef/@idref/text() = $i] \n";
              flwor += "return $q";
              try
              XmlQueryContext context = myManager.createQueryContext();
              context.setEvaluationType(XmlQueryContext.Eager);
              context.setReturnType(XmlQueryContext.DeadValues);
              XmlResults results = myManager.query(flwor, context);
              // Report Query Info
              String message = "Found ";
              message += results.size() + " entries for query: '";
              message += flwor + "'\n";
              System.out.println(message);
              int numQuestions;
              numQuestions = results.size();
              qobs = new questionOb[numQuestions];
              String[] keyRefs = new String[1];
              String[] keyRefs2 = new String[1];
              XmlResults atts, atts2 = null;
              XmlValue keyRefElem, keyRefAtt = null;
              int i;
              for(i=0; i < numQuestions; i++){
              XmlValue val = results.next();
              atts = val.getAttributes();
              String id = atts.next().getNodeValue();
              String value = atts.next().getNodeValue();
              keyRefElem = val.getFirstChild();
              int j=0;
              while (!keyRefElem.isType(XmlValue.NONE)){
              if(keyRefElem.getType() == XmlValue.TEXT_NODE){
              keyRefElem = keyRefElem.getNextSibling();
              if(keyRefElem.isType(XmlValue.NONE)){
              break;
              System.out.println("1");
              atts2 = keyRefElem.getAttributes();
              System.out.println("2");
              keyRefs[j] = atts2.next().getNodeValue();
              System.out.println("3" + keyRefs[j]);
              System.arraycopy(keyRefs,0,keyRefs2,0,j+1);
              System.out.println("4");
              keyRefs = new String[j+2];
              System.out.println("5");
              System.arraycopy(keyRefs2,0,keyRefs,0,j+1);
              System.out.println("6");
              keyRefs2 = new String[j+2];
              System.out.println("7");
              keyRefElem = keyRefElem.getNextSibling();
              System.out.println("8");
              j++;
              System.out.println(keyRefs[0]+keyRefs[1]);
              //Create new Question Object with retrieved values
              System.out.println("bef");
              questionOb qo = new questionOb(id, value, keyRefs);
              System.out.println("aft");
              qobs[i] = qo;
                        catch(Exception e)
              System.out.println("XML Exception is "+ e.getMessage());
              return qobs;
              private void sortModelElements(DefaultListModel model){
              //Getting the size of the model
              int size = model.getSize();
              //Creating the keyword object based on the size of the model
              keywordOb[] word = new keywordOb[size];
              int i=0;
              //keywordOb j;
              for(i=0; i < size; i++){
              word[i] = (keywordOb) model.getElementAt(i);
              Arrays.sort(word);
              for(i=0; i < size; i++){
              //model.setElementAt(word[i], i);
              model.set(i,word[i]);
              public void messageBox(String message)
              jOptionPane1.showMessageDialog(new Frame(), message , "Message", jOptionPane1.INFORMATION_MESSAGE);
              class KeywordFilter extends DocumentFilter {
              public void insertString(FilterBypass fb, int offset, String string, AttributeSet attr)
              throws BadLocationException {
              int len = fb.getDocument().getLength();
              if(len==0 & noFunnyChars(string) & !string.trim().equals("")){
              fb.insertString(offset, string, attr);
              if(len > 0 & noFunnyChars(string) & len < 30){
              fb.insertString(offset, string, attr);
              public void replace(FilterBypass fb, int offset, int length, String string, AttributeSet attr)
              throws BadLocationException {
              int len = fb.getDocument().getLength();
              if(len==0 & noFunnyChars(string) & !string.trim().equals("")){
              fb.replace(offset, length, string, attr);
              if(len > 0 & noFunnyChars(string) & len < 30){
              fb.insertString(offset, string, attr);
              private boolean noFunnyChars(String s){
              String regex = "[A-Za-z\\s]+";
              boolean b = Pattern.matches(regex, s);
              return b;
              private String capitalizeWords(String s){
              String s2;
              char[] c = s.toCharArray();
              int i = 0;
              c[0] = Character.toUpperCase(c[0]);
              for(i=0; i < c.length; i++){
              if (!Character.isLetter(c[i])){
              c[i+1] = Character.toUpperCase(c[i+1]);
              s2 = String.valueOf(c);
              return s2;
              private String keywordObsToSeq(keywordOb[] a) {
              StringBuffer result = new StringBuffer();
              String resultStr = "";
              result.append("('" + a[0].getId() + "', ");
              for (int i=1; i < a.length; i++) {
              result.append("'" + a[i].getId() + "', ");
              resultStr = result.toString();
              resultStr = resultStr.trim();
              resultStr = resultStr.substring(0,resultStr.length()-1) + ")";
              return resultStr;
         // <editor-fold defaultstate="collapsed" desc=" Generated Code ">
              private void initComponents() {
              jScrollPane1 = new javax.swing.JScrollPane();
              jList1 = new javax.swing.JList();
              jScrollPane2 = new javax.swing.JScrollPane();
              jList2 = new javax.swing.JList();
              jLabel1 = new javax.swing.JLabel();
              jLabel2 = new javax.swing.JLabel();
              jLabel3 = new javax.swing.JLabel();
              jTextField1 = new javax.swing.JTextField();
              jButton1 = new javax.swing.JButton();
              jButton2 = new javax.swing.JButton();
              jButton3 = new javax.swing.JButton();
              jScrollPane3 = new javax.swing.JScrollPane();
              jList3 = new javax.swing.JList();
              jLabel4 = new javax.swing.JLabel();
              jButton4 = new javax.swing.JButton();
              jButton5 = new javax.swing.JButton();
              jLabel5 = new javax.swing.JLabel();
              jScrollPane4 = new javax.swing.JScrollPane();
              jTextArea1 = new javax.swing.JTextArea();
              jButton6 = new javax.swing.JButton();
              setDefaultCloseOperation(javax.swing.WindowConstants.DO_NOTHING_ON_CLOSE);
              jList1.addMouseListener(new java.awt.event.MouseAdapter() {
              public void mouseClicked(java.awt.event.MouseEvent evt) {
              jList1MouseClicked(evt);
              jScrollPane1.setViewportView(jList1);
              jList2.addMouseListener(new java.awt.event.MouseAdapter() {
              public void mouseClicked(java.awt.event.MouseEvent evt) {
              jList2MouseClicked(evt);
              jScrollPane2.setViewportView(jList2);
              jLabel1.setText("Available Keywords");
              jLabel2.setText("Selected Keywords");
              jLabel3.setText("Add New Keyword");
              jTextField1.setFont(new java.awt.Font("Tahoma", 0, 12));
              jTextField1.addActionListener(new java.awt.event.ActionListener() {
              public void actionPerformed(java.awt.event.ActionEvent evt) {
              jTextField1ActionPerformed(evt);
              jButton1.setText("Add Keyword");
              jButton1.setEnabled(false);
              jButton1.addActionListener(new java.awt.event.ActionListener() {
              public void actionPerformed(java.awt.event.ActionEvent evt) {
              jButton1ActionPerformed(evt);
              jButton2.setText("Modify Keyword");
              jButton3.setText("Remove Keyword");
              jList3.setModel(new javax.swing.AbstractListModel() {
              String[] strings = { "Item 1", "Item 2", "Item 3", "Item 4", "Item 5" };
              public int getSize() { return strings.length; }
              public Object getElementAt(int i) { return strings[i]; }
              jScrollPane3.setViewportView(jList3);
              jLabel4.setText("Questions");
              jButton4.setText("OK");
              jButton4.addActionListener(new java.awt.event.ActionListener() {
              public void actionPerformed(java.awt.event.ActionEvent evt) {
              jButton4ActionPerformed(evt);
              jButton5.setText("Cancel");
              jLabel5.setText("Add New Question");
              jTextArea1.setColumns(20);
              jTextArea1.setRows(2);
              jScrollPane4.setViewportView(jTextArea1);
              jButton6.setText("Add Question");
              javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
              getContentPane().setLayout(layout);
              layout.setHorizontalGroup(
              layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
              .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
              .addContainerGap(488, Short.MAX_VALUE)
              .addComponent(jButton5)
              .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
              .addComponent(jButton4, javax.swing.GroupLayout.PREFERRED_SIZE, 65, javax.swing.GroupLayout.PREFERRED_SIZE)
              .addGap(29, 29, 29))
              .addGroup(layout.createSequentialGroup()
              .addGap(38, 38, 38)
              .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
              .addGroup(layout.createSequentialGroup()
              .addComponent(jButton6)
              .addContainerGap())
              .addGroup(layout.createSequentialGroup()
              .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
              .addComponent(jScrollPane4, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 559, Short.MAX_VALUE)
              .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
              .addComponent(jLabel5)
              .addComponent(jLabel4)
              .addGroup(layout.createSequentialGroup()
              .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
              .addComponent(jLabel1)
              .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 148, javax.swing.GroupLayout.PREFERRED_SIZE))
              .addGap(31, 31, 31)
              .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
              .addComponent(jLabel2)
              .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 152, javax.swing.GroupLayout.PREFERRED_SIZE))
              .addGap(32, 32, 32)
              .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
              .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 155, javax.swing.GroupLayout.PREFERRED_SIZE)
              .addComponent(jLabel3)
              .addComponent(jButton1)
              .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
              .addComponent(jButton2, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
              .addComponent(jButton3, javax.swing.GroupLayout.Alignment.LEADING))))
              .addComponent(jScrollPane3, javax.swing.GroupLayout.DEFAULT_SIZE, 559, Short.MAX_VALUE)))
              .addContainerGap(58, Short.MAX_VALUE))))
              layout.setVerticalGroup(
              layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
              .addGroup(layout.createSequentialGroup()
              .addGap(24, 24, 24)
              .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
              .addGroup(layout.createSequentialGroup()
              .addComponent(jLabel1)
              .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
              .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 146, javax.swing.GroupLayout.PREFERRED_SIZE))
              .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
              .addGroup(layout.createSequentialGroup()
              .addComponent(jLabel2)
              .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
              .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 146, javax.swing.GroupLayout.PREFERRED_SIZE))
              .addGroup(layout.createSequentialGroup()
              .addComponent(jLabel3)
              .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
              .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
              .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
              .addComponent(jButton1)
              .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
              .addComponent(jButton2)
              .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
              .addComponent(jButton3))))
              .addGap(29, 29, 29)
              .addComponent(jLabel4)
              .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
              .addComponent(jScrollPane3, javax.swing.GroupLayout.PREFERRED_SIZE, 185, javax.swing.GroupLayout.PREFERRED_SIZE)
              .addGap(20, 20, 20)
              .addComponent(jLabel5)
              .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
              .addComponent(jScrollPane4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
              .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
              .addComponent(jButton6)
              .addGap(31, 31, 31)
              .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
              .addComponent(jButton4)
              .addComponent(jButton5))
              .addGap(21, 21, 21))
              pack();
    }// </editor-fold>
              //Event handlers
              private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {
              // TODO add your handling code here:
                        try {
                             myDbContainer.close();
                             myDbEnv.cleanup();
                        } catch (Exception e) {
                             logger.info("Could not close container/or env - Component");
                        super.setVisible(false);
                        super.dispose();
                   private void jTextField1ActionPerformed(java.awt.event.ActionEvent evt) {
              // TODO add your handling code here:
                        String val;
                        val = jTextField1.getText();
                        if(val != null & val.trim() != "" & noFunnyChars(val) ){
                             jButton1.setEnabled(true);
                        else {
                             jButton1.setEnabled(false);
                   private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
              // TODO add your handling code here:
                   // Add new keyword to the xml reference file
                        //addNewKeyword(jTextField1.getText());
                   private void jList2MouseClicked(java.awt.event.MouseEvent evt) {
              // TODO add your handling code here:
                        if(evt.getClickCount() == 2) {
                             keywordOb k = (keywordOb)jList2.getSelectedValue();
                             model_2.removeElement(k);
                             model_1.addElement(k);
                             sortModelElements(model_1);
                             questionOb q = null;
                             //Remove associated questions from listbox
                             int i,j;
                             for(i=0; i < model_3.size(); i++){
                                  q = (questionOb)model_3.getElementAt(i);
                                  for(j=0; j < model_3.size(); j++){
                                       if (q.getKeywordRefs()[j].equals(k.getId())){
                                            model_3.removeElement(q);
                                            i--;
                                            break;
                   private void jList1MouseClicked(java.awt.event.MouseEvent evt) {
              // TODO add your handling code here:
                   if(evt.getClickCount() == 2) {
                             //Getting properties of the selecteditem item in jList1.
                        keywordOb k = (keywordOb)jList1.getSelectedValue();
                        //Removing the element from jList1
                        model_1.removeElement(k);
                        //Adding the element to jList2
                        model_2.addElement(k);
                        sortModelElements(model_2);
                        //Load the questions for the selected keywords
                        int len;
                        len = model_2.getSize();
                        keywordOb[] dbQuestionsOb = new keywordOb[5];
                        keywordOb[] selectedKeywordsOb = new keywordOb[len];
                        String[] selectedKeywordIDs = new String[len];
                        int i;
                        for(i=0; i < len; i++) {
                             selectedKeywordsOb[i] = (keywordOb)model_2.getElementAt(i);
                             selectedKeywordIDs[i] = selectedKeywordsOb[i].getId();
                        questionOb[] questionsOb = getQuestionsFromDB(selectedKeywordsOb);
                        model_3.removeAllElements();
                        for(i=0; i < questionsOb.length; i++){
                             model_3.addElement(questionsOb[i]);
                        // sortModelElements(model_3);
    I think thats too much code for one post!

  • DB_VERSION_MISMATCH error when opening environment.

    I am using version 5.0.26.NC.
    I create an environment using an executable linked with win32 libdb50.dll (release build).
    If I try to open same environment using an executable linked with win32 libdb50d.dll (debug build) I get a DB_VERSION_MISMATCH error.
    This did not happen with older BerkeleyDB versions.

    I am using version 5.0.26.NC.
    I create an environment using an executable linked with win32 libdb50.dll (release build).
    If I try to open same environment using an executable linked with win32 libdb50d.dll (debug build) I get a DB_VERSION_MISMATCH error.
    This did not happen with older BerkeleyDB versions.

  • OutOfMemoryError when opening environment using Java API

    I've been getting a strange error recently and I can't seem to figure out why. Whenever my DBXML environment gets opened, I receive a "java.lang.OutOfMemoryError: Cannot allocate memory" error. The machine has over 700 MB of free RAM. Here is the code I use to create/open the environment.
    EnvironmentConfig envConf = new EnvironmentConfig();
    envConf.setAllowCreate(true); // If the environment does not exits, create it.
    envConf.setInitializeCache(true); // Turn on the shared memory region.
    envConf.setInitializeLocking(true); // Turn on the locking subsystem.
    envConf.setInitializeLogging(true); // Turn on the logging subsystem.
    envConf.setTransactional(true); // Turn on the transactional subsystem.
    envConf.setThreaded(true); //Turn on thread-safe
    envConf.setLogRegionSize(500000); //Increase logging region
    envConf.setErrorStream(System.err); //Set error stream
    envConf.setMaxLocks(5000); //Set max # of locks
    envConf.setMaxLockers(5000); //Set max # of lockers
    envConf.setMaxLockObjects(5000); //Set max # of lock objects
    envConf.setMaxMutexes(10);
    //Set the error stream to write to a log file
    String fileName = SystemProps.DATA_HOME + "/dbxml.log";
    File f = new File(fileName);
    FileOutputStream fos = new FileOutputStream(f);
    envConf.setErrorStream(fos);
    return new Environment(envHome, envConf);
    Is there something specific I'm doing here that would require lots of RAM? Could it be related to the size/contents of my DBXML containers?
    Thanks in advance.

    I'm not exactly sure why this worked, but running recovery seems to have fixed my problem.

  • Open Environment with different flags

    Hi,
    Is it correct to open an environment with different flags from that when it was created? For example, I use DB_INIT_CDB to open an environment directory which was not created using this flag? Will the environment support concurrency then? Thank you.

    on subsequent 'reopens' you should use the same set of flags as used when it the db files were created.   The exception is with create flag.  If you create a db file with one purpose in mind and want to change that purpose, you should recreate the db file with a new set of flags.    You can use dump/restore to dump and reload the data in the newly created db file
    thanks
    mike

  • Ligthroom 2-open catalog- failure to relaunch   (using Win XP)

    When I try to open (an exiting) catalog the dialog box telling me LR 2 must relaunch to open this catalog pops up and asks is that what I want to do. When I respond yes LR 2 closes but then it never re launches. I upgraded from LR 1.4 or the latest LR version. Anybody know what is going on ?

    Hi
    Are you sure that you entered the ADDRESS correctly? It seems that in hosts you wrote TC0239.NBTH and in tnsnames.ora and listener.ora you entered NBTH.TC0239.
    Ensure that the executable for the server exists (perhaps "oracle" is missing.)
    Error:     ORA-12545 / TNS-12545
    Text:     Connect failed because target host or object does not exist
    Cause:     The address specified is not valid, or the program being connected to
         does not exist.
    Action:     Ensure the ADDRESS parameters have been entered correctly; the most
         likely incorrect parameter is the node name. Ensure that the executable
         for the server exists (perhaps "oracle" is missing.) If the protocol is
         TCP/IP, edit the TNSNAMES.ORA file to change the host name to a numeric
         IP address and try again.TNS-12545 "Connect failed because target host or object does not exist"
    https://metalink.oracle.com/metalink/plsql/showdoc?db=NOT&id=12101.1&blackframe=1
    I can't connect to SQL*Plus as 'SYS' - Any suggestions as to what might be preventing me from connecting?
    Do you have a password file?
    Bye, Aron

  • Bdb deadlocks when opening database

    When I call _dbp->open(), the library hangs.  I am attempting to test how BDB works during system crashes, in order to code my application appropriately, but these hangs are difficult to work with.
    I am running multiple processes all reading and writing to a single database. I then kill off the processes one at a time, until one of the terminations hangs all the other processes reading or writing to that database. I understand the database may at that time be in a bad state and may need to be re-opened with the DB_RECOVER flag, but I don't get any kind of an error message on the other processes reading or writing to the database. They just hang. (it looks like they are waiting for the lock of the terminated process to be closed).
    I have code to check for a DB_RUNRECOVERY error number returned as part of the exception thrown during a db->open() operation, so I can then can db->open() again with the DB_RECOVER option, but db->open() never returns.
    I have tried setting the transaction timeout values and lock timeout values, but nothing seems to be working.
    I have tried working with the DB_REGISTER option, but would prefer not to limit each process to a single environment. I'd like to hide the BDB environment entirely from the caller and simply require the database name.
    Any assistance would be appreciated,
    Todd

    I do not have the option of launching a separate process to monitor the database. Unfortunately, I have resigned to the fact I must provide a separate thread to test for failures and deadlocks.
    As a result, I have created a static process-wide "EnvironmentManager" class to maintain a collection of Environments and Databases opened by the current process. This ensures the process will only have a single instance of any Environment open. As a result, I should be able to open my environment(s) with DB_REGISTER and DB_RECOVER.
    I also created a monitor thread. This thread does the following:
    foreach open environment
    envp->lock_detect(0,DB_LOCK_DEFAULT,NULL);
    envp->failchk(0);
    If a DbException with errno set to DB_RUNRECORY occurs, I do the following:
         Close each database opened within the faulted environment
         Close the environment
         Re-Open the environment
         Re-Open each database
    I would like to cycle through any open transactions, locks and cursors to close them, but it appears I do not have access to them.
    My test engine runs in an infinite loop doing the following:
    - Open Environment and Database
    - Write 200 records
    - Read 200 records
    - Get a count of records
    - Close the database and environment
    To test the failures, I launch multiple instances of the test engine then kill the processes one at a time. Obviously my production application with do a normal shut-down under normal conditions, but I need to handle time when an application crashes unexpectedly. I understand problems will occur, my goal is simply to get the system to throw exceptions that I can recover from. I need to resolve all dead-lock issues that can hang my application and all unexpected application-aborts that occur as a result of DB_ASSERT failures.
    The problems I am now encountering after implementing all of this:
    1) After a process has crashed and I attempt to ‘recover’ from within another running process, I am getting an exception regarding an open file handle to __db.register.
    PANIC: fatal region error detected; run recovery
    File handles still open at environment close
    Open file handle: C:\__db.register
    assert failure: ..\mutex\mut_win32.c/174: "__ip != NULL && __ip->dbth_state != THREAD_OUT"
    2) If I try to run the same application multiple times quickly by double clicking on the same executable, I get the following exception:
    DB_REGISTER limits processes to one open DB_ENV handle per environment
    DbEnv::open: Invalid argument
    Both of these issues appear to be with the DB_REGISTER option being specified when I open the environment, but things get much murkier if I remove that option.
    If I do not specify DB_REGISTER and DB_RECOVER on the command line, it is possible for my call to DbEnv->Open() to hang indefinitely. Otherwise, I would call Open() once and if it failed, call it again with DB_RECOVER.
    Please let me know how to proceed. How have other people handled running Berkeley DB across multiple processes?
    Regards,
    Todd

  • Environment recovery required when accessing lockstats

    we just upgraded from 2.4.* to 2.5.16 and we are trying to figure out our best locking strategy and running into some issues. While displaying stats works fine on most of our environments, it crashes in one every time with
    <pre>
    logging.error("Lock stats: %s"%env.lock_stat())
    bsddb3.db.DBRunRecoveryError: (-30974, 'DB_RUNRECOVERY: Fatal error, run database recovery -- PANIC: fatal region error detected; run recovery')
    </pre>
    I get the same error when trying to get documents from the shell. These happen even after recovery. Any idea what could be amiss here or what I need to reset to fix it?
    Thanks!
    eleddy

    Hi Bogdan -
    The flags are
    <pre>
    # open environment flags
    DB_CREATE|DB_THREAD|DB_INIT_LOCK|DB_INIT_LOG|DB_INIT_MPOOL|DB_INIT_TXN|DB_MULTIVERSION
    # recover flags, always run on startup
    DB_CREATE|DB_THREAD|DB_INIT_LOCK|DB_INIT_LOG|DB_INIT_MPOOL|DB_INIT_TXN|
    DB_RECOVER|DB_MULTIVERSION
    #manager open flgs
    DBXML_ADOPT_DBENV|DBXML_ALLOW_AUTO_OPEN
    # create container flags
    DB_CREATE|DB_EXCL|DBXML_TRANSACTIONAL
    #open container flags
    DBXML_TRANSACTIONAL
    # other settings
    environment.set_lk_detect(DB_LOCK_OLDEST)
    environment.set_lk_max_lockers(40000)
    environment.set_lk_max_locks(20000)
    environment.set_lk_max_objects(10000)
    environment.set_lg_max(104857600)
    environment.set_lg_bsize(20971520)
    environment.set_lg_regionmax(41943040)
    environment.set_lg_dir("logs")
    environment.set_data_dir("data")
    environment.set_timeout(1000000, DB_SET_TXN_TIMEOUT)
    environment.set_timeout(1000000, DB_SET_LOCK_TIMEOUT)
    environment.set_cachesize(0, 1073741824, 3)
    </pre>
    Let me know if I missed some flags. I can't seem to add any documents to this environment either, via api or shell. It seems to be one container. When I try to add via the shell I get
    <pre>
    stdin:6517: putDocument failed, Error: Invalid argument
    dbxml> exit
    Segmentation fault
    </pre>
    Finally, If I run the same command in a non-transacted shell environment everything runs smoothly. I'm trying a dump and reload test now but its 9GBs and live data so doing that for real isn't something I'm very excited about. FWIW we have another db that is crashing twice a day but its not re-creatable yet and goes straight to segfault. The issues don't seem to be related except they both started after the upgrade.
    Thanks in advance!
    eleddy
    Edited by: eleddy on Mar 3, 2010 11:27 AM
    Edited by: eleddy on Mar 3, 2010 11:29 AM
    Edited by: eleddy on Mar 3, 2010 11:43 AM

  • Most simple code always recovers the environment

    Hi,
    The code below recovers the environment on every run. This happens, if
    I specify DB_REGISTER without DB_RECOVER.
    Version: 4.6.21
    #include <stdio.h>
    #include <db.h>
    #ifdef WIN32
    #define DIRECTORY_ENVIRONMENT "C:\\Temp"
    #else
    #define DIRECTORY_ENVIRONMENT "/tmp"
    #endif
    static DB_ENV *environment = NULL;
    static int connect( int flags )
    db_env_create( &environment, 0 );
    environment->set_errfile( environment, stderr );
    return environment->open( environment, DIRECTORY_ENVIRONMENT, flags, 0644 );
    int main( int argc, char *argv[] )
    int status = connect( DB_CREATE | DB_INIT_MPOOL | DB_INIT_LOCK | DB_INIT_LOG | DB_INIT_TXN | DB_REGISTER );
    if( status == DB_RUNRECOVERY )
    printf("Run recovery...\n");
    status = connect( DB_CREATE | DB_INIT_MPOOL | DB_INIT_LOCK | DB_INIT_LOG | DB_INIT_TXN | DB_RECOVER ); // "DB_REGISTER" fails
    status = environment->close( environment, 0 );
    return 0;
    }

    Hello,
    Please let me know if I am misunderstanding your question.
    Using DB_REGISTER will check to see if recovery needs to be performed
    before opening the database environment. If recovery needs to be
    performed for any reason (including the initial use of the DB_REGISTER flag),
    and DB_RECOVER is also specified, recovery will be performed and the
    open will proceed normally. If recovery needs to be performed and DB_RECOVER
    is not specified, DB_RUNRECOVERY will be returned. If recovery does not need
    to be performed, the DB_RECOVER flag will be ignored.
    Thanks,
    Sandra

  • Safari fails to open after recent hard drive replacement and data transfer from time machine

    The hard drive was replaced by apple under replacement scheme due to seagate failures. It was reloaded with latest ios, but safari would not open, reported failure.
    I had re -installed my backed up info from time machine. i did go into back ups and copied previous safari app, and dropped it on my desk top. It opened ok. Is there an easy way to get this app onto the system and delete the faulty safari file.
    Hope this makes sense.

    guess what, all fixed, the safari app installed by apple on new hard drive was 5 something, but 6.02 was needed, i installed 6.02 but it told me i needed OSX10.8.2 which cost me £13.99 but it now works.
    happy days

  • Multiple environment instances in the same process with DB_REGISTER flag

    Hello,
    I'm having two applications in the tomcat that should use the same environment. I have the DB_REGISTER flag set, and since tomcat has a java single process for all applications, I can't open an environment in the second application since I get a "DB_REGISTER limits processes to one open DB_ENV handle per environment" error message. This is understandable. So my question is: is there a way to "join" the first opened environment instance. Or do I have to run applications in two different processes, i.e. using 2 tomcat instances?
    Thanks,
    Vyacheslav

    Thanks for reply Sandra.
    I have a follow-up question. Is it possible to get an environment instance if it's already opened in the process. For instance like:
    Application1 in the tomcat process:
    Environment env  = new Environment(envHome, envConfig) //openning an env under "envHome" directoryApplication2 in the same tomcat process:
    Environment env;
    try{
      env  = new Environment(envHome, envConfig) //openning an env under "envHome" directory
    } catch (DbException e) {
      if(isAlreadyOpenedException(e)) { //checking that our exception is "DB_REGISTER flag permits only 1 opened env handle per process"
         env = Enviroment.getEnvironmentHandleFromTheSameProcess(); //here I'm improvising. Is there any similar method?
    } So my question is if it's something that is possible.
    Thanks in advance,
    Vyacheslav

Maybe you are looking for

  • How to do aging for Net Debit for 0DEB_CRE_LC

    Hi to all, i am doing aging for receivables(0FI_AR_4) for Net debit > 0. I have created CKF excaption aggregation at query level to get Net debit greater than zero, via ( 0DEB_CRE_LC > 0 ) * 0DEB_CRE_LC for every customer. it gives correct result . b

  • Empty ACL Message

    Hi, I found the there are lots of entry like "[09/2/2003:19:34:38 CST] ERROR [B3100]: Unexpected Broker Internal Error : [Internal Error: Empty Ack Message 542-192.168.3.37(b9:a9:66:a0:47:70)-2605-1044790478667] " in the imq (version 3.01) log file.

  • Transfer photos from galaxy note 2 onto my laptop.

    I have a Galaxy Note 2.  My laptop has Chrome downloaded and Firefox and runs Windows 8.  I can't find on my Galaxy Note 2 how to transfer all my photos/albums onto my microcard so I can just take it out and transfer them with the adaptor to my lapto

  • [SOLVED] changing keyboard layouts in openbox

    HI again ! I'm using openbox and i want to change between gb (united kingdom) and gr (Greece) languages so i 've tried to add the following code to xorg.conf without any result : Section "InputDevice" Identifier "Keyboard0" Driver "kbd" Option "XkbLa

  • Maintain user profile t-code

    Can any one please tell me the t-code or path to reach user profile where we have decimal settings, date settings ect. Thanks.