All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.objectweb.jonas.db.hsqldb.HsqlDBServiceImpl Maven / Gradle / Ivy

The newest version!
/**
 * JOnAS: Java(TM) Open Application Server
 * Copyright (C) 2004 Bull S.A.
 * Contact: [email protected]
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307
 * USA
 *
 * --------------------------------------------------------------------------
 * $Id: HsqlDBServiceImpl.java 10050 2007-03-07 10:45:32Z sauthieg $
 * --------------------------------------------------------------------------
 */
package org.objectweb.jonas.db.hsqldb;

import java.io.File;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.Iterator;
import java.util.List;

import org.hsqldb.Server;
import org.hsqldb.ServerConstants;
import org.objectweb.jonas.common.JProp;
import org.objectweb.jonas.db.AbsDBServiceImpl;
import org.objectweb.jonas.db.AbsDBServiceImplMBean;
import org.objectweb.jonas.db.DBService;
import org.objectweb.jonas.db.User;
import org.objectweb.jonas.service.ServiceException;
import org.objectweb.util.monolog.api.BasicLevel;

/**
 * Embeds the HSQL database in JOnAS
 * @author Florent Benoit
 */
public class HsqlDBServiceImpl extends AbsDBServiceImpl implements DBService, AbsDBServiceImplMBean {

    /**
     * List of users
     */
    private List users = null;

    /**
     * Name of database
     */
    private String databaseName = null;

    /**
     * Default port number
     */
    private static final String DEFAULT_PORT = "9001";

    /**
     * Sleep value
     */
    private static final int SLEEP_VALUE = 100;

    /**
     * Max retry number
     */
    private static final int MAX_RETRY_NB = 20;

    /**
     * port number used
     */
    private String portNumber = null;

    /**
     * HsqlDB server
     */
    private Server server = null;

    /**
     * Create a database with the specified arguments.
     * @param users user/password (separated by a ":")
     * @param databaseName name of the database
     * @param portNumber port number of the database
     */

    protected void initServer(List users, String databaseName, String portNumber) {
        this.users = users;
        if (portNumber != null) {
            this.portNumber = portNumber;
        } else {
            this.portNumber = DEFAULT_PORT;
        }
        this.databaseName = databaseName;
        String jBase = JProp.getJonasBase();

        server = new Server();
        // Remove all traces if level != DEBUG
        if (!getLogger().isLoggable(BasicLevel.DEBUG)) {
            server.setLogWriter(null);
            server.setErrWriter(null);
            server.setSilent(true);
            server.setTrace(false);
            server.setLogWriter(null);
        } else {
            // Enable all traces : verbose mode (as user needs DEBUG)
            server.setSilent(false);
            server.setTrace(true);
        }

        String baseDir = jBase + File.separator + "work" + File.separator + "hsqldb" + File.separator + databaseName;
        String pString = "";
        if (portNumber != null) {
            pString = ";port=" + portNumber;
        }
        String serverProps = "database.0=" + baseDir + ";dbname.0=" + databaseName + pString;
        server.putPropertiesFromString(serverProps);

    }

    /**
     * Start the service.
     * @throws ServiceException if the startup failed.
     */
    protected void doStart() throws ServiceException {
        super.doStart();
        if (getLogger().isLoggable(BasicLevel.INFO)) {
            getLogger().log(BasicLevel.INFO, "Starting " + server.getProductName() + " " + server.getProductVersion() + " on port " + portNumber);
        }
        if (getLogger().isLoggable(BasicLevel.DEBUG)) {
            getLogger().log(BasicLevel.DEBUG, "serverState=" + server.getState());
        }
        server.start();

        // Wait the start
        int retryNb = 0;
        while (server.getState() != ServerConstants.SERVER_STATE_ONLINE) {
            try {
                Thread.sleep(SLEEP_VALUE);
            } catch (InterruptedException ie) {
                getLogger().log(BasicLevel.ERROR, "Can't wait that the service is online", ie);
            }
            // Error if server state is "SHUTDOWN" during a long period
            // Maybe strange but 'SHUTDOWN' state seems to be an intermediate state during startup
            retryNb++;
            if (server.getState() == ServerConstants.SERVER_STATE_SHUTDOWN && retryNb >= MAX_RETRY_NB) {
                    Throwable t = server.getServerError();
                    throw new ServiceException("The server was shutdown :", t);
            }
            if (getLogger().isLoggable(BasicLevel.DEBUG)) {
                getLogger().log(BasicLevel.DEBUG, "retry=" + retryNb + ", serverState=" + server.getState());
            }
        }

        getLogger().log(BasicLevel.INFO, server.getProductName() + " started.");
        Connection conn = null;
        Statement st = null;
        try {

            Class.forName("org.hsqldb.jdbcDriver");
            conn = DriverManager.getConnection("jdbc:hsqldb:hsql://localhost:" + portNumber + "/" + databaseName, "sa",
                    "");
            st = conn.createStatement();
        } catch (Exception e) {
            throw new ServiceException("Cannot access to HSQL", e);
        }

        // Drop users before recreating it
        User user = null;
        String userName = null;
        String password = null;
        ResultSet rs = null;
        for (Iterator it = users.iterator(); it.hasNext();) {
            user = (User) it.next();
            try {
                password = user.getPassword();
                userName = user.getUserName();
                getLogger().log(BasicLevel.INFO,
                        "Dropping and adding user '" + userName + "' with password '" + password + "'.");
                try {
                    rs = st.executeQuery("DROP USER " + userName);
                } catch (Exception ee) {
                    if (getLogger().isLoggable(BasicLevel.DEBUG)) {
                        getLogger().log(BasicLevel.DEBUG, "User '" + userName + "' doesn't exists", ee);
                    }
                }
                rs = st.executeQuery("Create USER " + userName + " PASSWORD " + password + " ADMIN");
                rs.close();
            } catch (Exception e) {
                getLogger().log(BasicLevel.ERROR, "Error while creating/adding user", e);
            }

        }

        try {
            st.close();
        } catch (Exception e) {
            if (getLogger().isLoggable(BasicLevel.DEBUG)) {
                getLogger().log(BasicLevel.DEBUG, "Error while closing statement object", e);
            }
        }

    }

    /**
     * Stop the service.
     * @throws ServiceException if the stop failed.
     */
    protected void doStop() throws ServiceException {
        super.doStop();

        server.shutdown();
    }

}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy