dbpersistencemanager.java

来自「JGRoups源码」· Java 代码 · 共 688 行 · 第 1/2 页

JAVA
688
字号
package org.jgroups.persistence;/** * @author Mandar Shinde * This class implements the DB storage pattern for the Persistence * Manager interface. The implementation is open and can be used (and * tested) over more than one databases. It uses a string (VARCHAR) * as the key and either BLOB or VARBINARY db-datatype for the * serialized objects. THe user has the option to choose his/her own * schema over the ones provided. */import org.apache.commons.logging.Log;import org.apache.commons.logging.LogFactory;import java.io.*;import java.sql.*;import java.util.*;/** * Class will be utilized */public class DBPersistenceManager implements PersistenceManager {    protected final Log log=LogFactory.getLog(this.getClass());    /**     * Default construct     * @param filename absolute filepath     * @exception Exception;     */    public DBPersistenceManager(String filename) throws Exception {        String home_dir = null;        // PropertyPermission not granted if running in an untrusted environment with JNLP.        try {            home_dir = System.getProperty("user.home");        }        catch (SecurityException ex1) {        }        // 1. Try ${user.home}/persist.properties        try {            home_dir=home_dir + '/' + filename;            init(new FileInputStream(home_dir));            return;        }        catch(Exception ex) {            ;        }        // 2. Try to find persist.properties from somewhere on the CLASSPATH        try {            InputStream in=DBPersistenceManager.class.getResourceAsStream('/' + filename);            if(in != null) {                init(in);                return;            }        }        catch(Exception x) {            if(log.isErrorEnabled()) log.error("failed reading database properties from " + filename + ", exception=" + x);        }        // 3. Finally maybe the user specified -Dpersist.properties=/home/user/mypersist.properties        try {            home_dir=System.getProperty("persist.properties");            init(new FileInputStream(home_dir));            return;        }        catch(Exception ex) {            ;        }        // 4. If none of the above helped us to find persist.properties, give up and throw an exception        throw new Exception("DBPersistenceManager.DBPersistenceManager(): " +                            "failed reading database properties from " + filename);    }    /**     * Duplicate constructor allowing inputstream     * @param input     * @exception Exception     */    public DBPersistenceManager(InputStream input) throws Exception {        init(input);    }    /**     * used to intitiailize complete DB access. THis method will use     * existing database to create schema (if it doesnt exist) and     * get PersistenceManager in usable condition     * @param in     * @exception Exception;     */    protected void init(InputStream in) throws Exception {        list=new Vector();        readProps(in);        loadDriver();        //check conn        Connection conn=this.getConnection();        this.closeConnection(conn);        createDBTables();        retrieveAll(); // work around to make sure, no duplicates are created.        log.error(" Done constructing DB Persist Manager");    }    // TODO list for this implementation    // add constructor for xml file    // add constructor for default    /**     * Saves NV pair as serializable object;      * creates if new, stores new state if already exists.     * @param key     * @param val     * @exception CannotPersistException;     */    public void save(Serializable key, Serializable val) throws CannotPersistException {        // checking if this is update or new entry        if(!entryExists(key)) {            log.error(" entry doesnt exist for " + key.toString());            try {                addNewEntry(key, val);                list.add(key.toString());                return;            }            catch(Throwable t1) {                t1.printStackTrace();                //trace here                throw new CannotPersistException(t1, " error adding a completely new entry in to DB ");            }        }// checking entries        // THis is for regular updates to the key,val pair        Connection conn=null;        PreparedStatement prepStat=null;        try {            conn=this.getConnection();            String keyStr=null;            keyStr=key.toString();            byte[] keyBytes=getBytes(key);            byte[] valBytes=getBytes(val);            log.error(" value is " + val);            //use simple execute, do not create prepared statement            prepStat=conn.prepareStatement(updateStat);            prepStat.setString(3, keyStr);            prepStat.setBytes(1, keyBytes);            prepStat.setBytes(2, valBytes);            prepStat.executeQuery();        }        catch(Throwable t) {            //trace here            t.printStackTrace();            // throw exception here            throw new CannotPersistException(t, "error updating an existing entry in to the database ");        }                // cleanup        finally {            try {                if(prepStat != null) prepStat.close();                this.closeConnection(conn);            }            catch(Throwable t) {                // trace                conn=null;                prepStat=null;            }        }    }    /**     * Removes existing entry.     * @param key     * @exception CannotRemoveException;     */    public Serializable remove(Serializable key) throws CannotRemoveException {        Connection conn=null;        Statement stat=null;        PreparedStatement prepStat=null;        ResultSet set=null;        Serializable val=null;        try {            conn=this.getConnection();            stat=conn.createStatement();            String exQuery=" select * from replhashmap where key like '" + key.toString() + '\'';            set=stat.executeQuery(exQuery);            set.next();            val=getSerializable(set.getBinaryStream(3));        }        catch(Throwable t3) {            //trace            t3.printStackTrace();            throw new CannotRemoveException(t3, " Error retrieving value for given key");        }        finally {            try {                if(prepStat != null) prepStat.close();                this.closeConnection(conn);            }            catch(Throwable t) {                // trace                conn=null;                prepStat=null;            }        }        try {            conn=this.getConnection();            prepStat=conn.prepareStatement(removeStat);            prepStat.setString(1, key.toString());            prepStat.executeQuery();            list.remove(key.toString());        }        catch(Throwable t) {            //trace here..            t.printStackTrace();            // throw Exception            throw new CannotRemoveException(t, "Could not remove existing entry due to error in jdbc transaction");        }                // cleanup        finally {            try {                set.close();                stat.close();                if(prepStat != null) prepStat.close();                this.closeConnection(conn);            }            catch(Throwable t) {                // trace                conn=null;                stat=null;            }//end of try..catch        }// end of finally..        return val;    }// end of remove    /**     * Saves all row entries for the map to DB.     * @param map     * @exception CannotPersistException;     */    public synchronized void saveAll(Map map) throws CannotPersistException {        Iterator iter=null;        try {            Set keySet=map.keySet();            iter=keySet.iterator();        }        catch(Throwable t) {            t.printStackTrace();            //trace here            throw new CannotPersistException(t, "Error with the map entered to saveAll");        }        //Individually saving all        while(iter.hasNext()) {            try {                Serializable key=(Serializable) iter.next();                Serializable val=(Serializable) map.get(key);                // dont this in same thread, optimization can be added                this.save(key, val);            }            catch(Throwable t2) {                t2.printStackTrace();                //trace here                continue;            }        }// end of while..    }// end of saveall    /**     * Used to retrieve the persisted map back to its last known state     * @return Map;     * @exception CannotRetrieveException;     */    public synchronized Map retrieveAll() throws CannotRetrieveException {        Connection conn=null;        Statement stat=null;        ResultSet set=null;        Map map=null;        try {            conn=this.getConnection();            stat=conn.createStatement();            set=stat.executeQuery(" select * from replhashmap");            map=retrieveAll(set);        }        catch(Throwable t) {            //trace here            throw new CannotRetrieveException(t, "Error happened while querying the database for bulk retrieve, try starting DB manually");        }        //finally        try {            stat.close();            this.closeConnection(conn);        }        catch(Throwable t1) {            // trace it            // ignore        }        return map;    }// end of retrieveall    /**     * Helper method to get get back the map     * @return Map;     * @exception Exception;     */    private Map retrieveAll(ResultSet result) throws Exception {        HashMap map=new HashMap();        while(result.next()) {            InputStream inputStrKey=result.getBinaryStream(2);            InputStream inputStrVal=result.getBinaryStream(3);            Serializable key=getSerializable(inputStrKey);            Serializable val=getSerializable(inputStrVal);            map.put(key, val);            list.add(key.toString());        }// end of while..        return map;    }    /**     * Clears the key-cache as well as all entries     * @exception CannotRemoveException;     */    public void clear() throws CannotRemoveException {        Connection conn=null;

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?