User: chirino 
  Date: 01/07/10 19:52:17

  Added:       src/main/org/jbossmq/pm/jdbc MessageLog.java
                        PersistenceManager.java
                        PersistenceManagerMBean.java TxLog.java
  Log:
  These are the 3 PersistenceManager implementations we have so far.  The are now all 
configured via JMX
  
  Revision  Changes    Path
  1.1                  jbossmq/src/main/org/jbossmq/pm/jdbc/MessageLog.java
  
  Index: MessageLog.java
  ===================================================================
  /*
   * JBossMQ, the OpenSource JMS implementation
   *
   * Distributable under LGPL license.
   * See terms of license at gnu.org.
   */
  package org.jbossmq.pm.jdbc;
  
  import java.io.IOException;
  import java.io.Serializable;
  import java.io.FileOutputStream;
  import java.io.ObjectOutputStream;
  import java.io.FileInputStream;
  import java.io.ObjectInputStream;
  import java.io.File;
  import java.sql.*;
  import java.io.*;
  
  import javax.jms.JMSException;
  import javax.sql.*;
  
  import org.jbossmq.SpyMessage;
  import org.jbossmq.SpyDestination;
  
  /**
   * This is used to keep SpyMessages on the disk and is used reconstruct the
   * queue in case of provider failure.
   *
   * @author: Jayesh Parayali ([EMAIL PROTECTED])
   * @version $Revision: 1.1 $
   */
  public class MessageLog {
  
    /////////////////////////////////////////////////////////////////////
    // Attributes
    /////////////////////////////////////////////////////////////////////
    //private File queueName;
    protected static DataSource datasource;
  
    /////////////////////////////////////////////////////////////////////
    // Constructor
    /////////////////////////////////////////////////////////////////////
    public MessageLog(DataSource datasource, String dest, String queueId) throws 
JMSException {
           if (this.datasource == null)
                 this.datasource = datasource;
    }    
  
  
    /////////////////////////////////////////////////////////////////////
    // Public Methods
    /////////////////////////////////////////////////////////////////////
    public void close() throws JMSException {
    }    
  
    public void add( SpyMessage message, Long transactionId ) throws JMSException {
        PreparedStatement pstmt = null;
        Connection con = null;
  
        try{
          con = datasource.getConnection();
          ByteArrayOutputStream baos = new ByteArrayOutputStream();
          ObjectOutputStream oos = new ObjectOutputStream(baos);
          oos.writeObject(message);
          byte[] messageAsBytes = baos.toByteArray();
          pstmt =
                 con.prepareStatement
                        ("insert into jms_messages (messageid, destination, 
messageblob) VALUES(?,?,?)");
          ByteArrayInputStream bais =
                 new ByteArrayInputStream(messageAsBytes);
          pstmt.setString(2,((SpyDestination)message.getJMSDestination()).getName());
          pstmt.setBinaryStream(3,bais, messageAsBytes.length);
          String hexString = null;
          if (message.messageId <= 0)
                hexString = "-"+ Long.toHexString((-1)*message.messageId);
          else
                hexString = Long.toHexString(message.messageId);
  
          pstmt.setString(1,hexString);
          pstmt.executeUpdate();
  
          pstmt.close();
        } catch ( IOException e ) {
          throwJMSException("Could serialize the message.",e);
        } catch ( SQLException e ) {
          throwJMSException("Could not write message to the database.",e);
        } finally {
          try {
                //if (pstmt != null)
                  //pstmt.close();
                if (con != null)
                  con.close();
          }
          catch (SQLException e) {
                throwJMSException("Could not close the database.",e);
          }
  
        }
    }    
  
    public void remove( SpyMessage message, Long transactionId ) throws JMSException {
        PreparedStatement pstmt = null;
        Connection con = null;
        try{
          con = datasource.getConnection();
          pstmt =
                 con.prepareStatement
                        ("delete from jms_messages where messageid = ? and destination 
= ?");
          String hexString = null;
          if (message.messageId <= 0)
                hexString = "-"+ Long.toHexString((-1)*message.messageId);
          else
                hexString = Long.toHexString(message.messageId);
          pstmt.setString(1,hexString);
          
pstmt.setString(2,((SpyDestination)message.getJMSDestination()).getName().trim());
  
          pstmt.execute();
        } catch ( SQLException e ) {
          throwJMSException("Could not remove the message.",e);
        } finally {
          try {
                if (pstmt != null)
                  pstmt.close();
                if (con != null)
                  con.close();
          }
          catch (SQLException e) {
                throwJMSException("Could not close the database.",e);
          }
  
        }
    }    
  
    public SpyMessage[] restore(java.util.TreeSet comittingTXs, String dest) throws 
JMSException {
        String destin = dest.substring(21,dest.length());
  
        java.util.TreeMap messageIndex = new java.util.TreeMap();
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        Connection con = null;
  
        try{
          con = datasource.getConnection();
          pstmt =
                 con.prepareStatement
                        ("select messageblob, messageid from jms_messages where 
destination = ?");
          pstmt.setString(1,destin);
          rs = pstmt.executeQuery();
  
          while (rs.next()) {
                 byte[] st = (byte[])rs.getObject(1);
                 ByteArrayInputStream baip =
                         new ByteArrayInputStream(st);
                 ObjectInputStream ois =
                         new ObjectInputStream(baip);
                 // re-create the object
                 SpyMessage message = (SpyMessage)ois.readObject();
  
  
                 //Long msgId = new Long(Long.parseLong(rs.getString(2).trim(),16));
                 //restore the messageId which is not persistent.
                 message.messageId = Long.parseLong(rs.getString(2).trim(),16);
                 Long msgId = new Long(message.messageId);
                 messageIndex.put(msgId, message);
                 }
        }
        catch ( SQLException e ) {
          throwJMSException("SQL error while rebuilding the tranaction log.",e);
        }
        catch ( Exception e ) {
          throwJMSException("Could not rebuild the queue from the queue's tranaction 
log.",e);
        }
        finally {
           try {
                 if (rs != null)
                   rs.close();
                 if (pstmt != null)
                   pstmt.close();
                 if (con != null)
                   con.close();
           }
           catch (SQLException e) {
                throwJMSException("SQL error while closing the database connection",e);
           }
        }
  
        SpyMessage rc[] = new SpyMessage[messageIndex.size()];
        java.util.Iterator iter = messageIndex.values().iterator();
        for( int i=0; iter.hasNext(); i++ )
          rc[i] = (SpyMessage)iter.next();
        return rc;
    }    
  
    private void throwJMSException(String message, Exception e) throws JMSException {
        JMSException newE = new JMSException(message);
        newE.setLinkedException(e);
        throw newE;
    }    
  
  }
  
  
  1.1                  jbossmq/src/main/org/jbossmq/pm/jdbc/PersistenceManager.java
  
  Index: PersistenceManager.java
  ===================================================================
  /*
   * JBossMQ, the OpenSource JMS implementation
   *
   * Distributable under LGPL license.
   * See terms of license at gnu.org.
   */
  package org.jbossmq.pm.jdbc;
  
  import javax.rmi.PortableRemoteObject;
  import javax.jms.JMSException;
  import javax.sql.*;
  import javax.naming.*;
  
  
  import java.net.URL;
  import java.util.HashMap;
  import java.util.TreeSet;
  import java.util.Iterator;
  import java.util.LinkedList;
  import java.util.Properties;
  import java.sql.*;
  import java.io.*;
  
  import org.jbossmq.xml.XElement;
  import org.jbossmq.server.JMSServer;
  import org.jbossmq.server.JMSDestination;
  import org.jbossmq.SpyMessage;
  import org.jbossmq.SpyDestination;
  
  
  import org.jboss.util.ServiceMBeanSupport;
  import org.jbossmq.ConnectionToken;
  import javax.naming.InitialContext;
  import org.jbossmq.pm.TxManager;
  import javax.management.*;
  
  /**
   *  This class manages all persistence related services for file based
   *  persistence.
   *
   * @author: Jayesh Parayali ([EMAIL PROTECTED])
   *
   *  @version $Revision: 1.1 $
   */
  public class PersistenceManager extends ServiceMBeanSupport  
        implements org.jbossmq.pm.PersistenceManager, PersistenceManagerMBean, 
MBeanRegistration {
  
  
  
  
  
    protected static DataSource datasource;
  
  
    // Log file used to store commited transactions.
    TxLog txLog;
    // Maps SpyDestinations to SpyMessageLogs
    HashMap messageLogs = new HashMap();
    // Maps (Long)txIds to LinkedList of AddFile tasks
    HashMap transactedTasks = new HashMap();
  
    static class LogInfo {
        MessageLog log;
        SpyDestination destination;
        String queueId;
  
        LogInfo(MessageLog log, SpyDestination destination, String queueId) {
          this.log=log;
          this.destination=destination;
          this.queueId=queueId;
        }
    }
  
  
  
  
  
    public Long createPersistentTx() throws javax.jms.JMSException {
        Long txId = txLog.createTx();
        synchronized (transactedTasks) {
          transactedTasks.put(txId, new LinkedList());
        }
        return txId;
    }    
  
    public void commitPersistentTx(Long txId) throws javax.jms.JMSException {
  
        LinkedList transacted;
        synchronized (transactedTasks) {
          transacted = (LinkedList)transactedTasks.remove(txId);
        }
        synchronized(transacted){
          Iterator iter = transacted.iterator();
          while( iter.hasNext() ) {
                Transaction task = (Transaction)iter.next();
                task.commit();
          }
        }
  
        txLog.commitTx(txId);
    }    
  
    public void rollbackPersistentTx(Long txId) throws javax.jms.JMSException {
  
        LinkedList transacted;
        synchronized(transactedTasks){
          transacted = (LinkedList)transactedTasks.remove(txId);
        }
        synchronized(transacted){
          Iterator iter = transacted.iterator();
          while( iter.hasNext() ) {
                Transaction task = (Transaction)iter.next();
                task.rollback();
          }
        }
  
        txLog.rollbackTx(txId);
    }    
  
    public void initQueue( SpyDestination dest, String queueId ) throws 
javax.jms.JMSException {
        try {
          //URL logDir = new URL(dataDirectory, dest.toString()+"-"+queueId);
  
          MessageLog log = new MessageLog(datasource, dest.toString(), queueId);
  
          LogInfo info = new LogInfo(log, dest, queueId);
  
          synchronized(messageLogs){
                messageLogs.put(""+dest+"-"+queueId, info);
          }
  
        } catch (javax.jms.JMSException e) {
          throw e;
        } catch (Exception e) {
          javax.jms.JMSException newE = new javax.jms.JMSException("Invalid 
configuration.");
          newE.setLinkedException(e);
          throw newE;
        }
  
    }    
  
    public void destroyQueue( SpyDestination dest, String queueId ) throws 
javax.jms.JMSException {
  
        try {
  
          //URL logDir = new URL(dataDirectory, dest.toString()+"-"+queueId);
          //java.io.File file = new java.io.File(logDir.getFile());
  
          LogInfo logInfo;
          synchronized(messageLogs){
                logInfo = (LogInfo)messageLogs.remove(""+dest+"-"+queueId);
          }
          if( logInfo == null )
                throw new JMSException("The persistence log was never initialized");
  
          logInfo.log.close();
          //file.delete();
  
        } catch (javax.jms.JMSException e) {
          throw e;
        } catch (Exception e) {
          javax.jms.JMSException newE = new javax.jms.JMSException("Invalid 
configuration.");
          newE.setLinkedException(e);
          throw newE;
        }
  
    }    
  
    public void add(String queueId, org.jbossmq.SpyMessage message, Long txId) throws 
javax.jms.JMSException {
        LogInfo logInfo;
  
        synchronized (messageLogs) {
          logInfo = (LogInfo) 
messageLogs.get(""+message.getJMSDestination()+"-"+queueId);
        }
  
        if (logInfo == null)
          throw new javax.jms.JMSException("Destination was not initalized with the 
PersistenceManager");
  
        logInfo.log.add(message, txId);
  
        if( txId != null ) {
          LinkedList tasks;
          synchronized( transactedTasks ) {
                tasks = (LinkedList)transactedTasks.get(txId);
          }
          if( tasks == null )
                throw new javax.jms.JMSException("Transaction is not active 5.");
          synchronized(tasks){
                tasks.addLast(new Transaction(true, logInfo, message, txId));
          }
        }
  
    }    
  
    public void remove(String queueId, org.jbossmq.SpyMessage message, Long txId) 
throws javax.jms.JMSException {
        LogInfo logInfo;
  
        synchronized (messageLogs) {
          logInfo = (LogInfo) 
messageLogs.get(""+message.getJMSDestination()+"-"+queueId);
        }
  
        if (logInfo == null)
          throw new javax.jms.JMSException("Destination was not initalized with the 
PersistenceManager");
  
        if( txId == null )
          logInfo.log.remove(message, txId);
        else {
          LinkedList tasks;
          synchronized (transactedTasks) {
                tasks = (LinkedList)transactedTasks.get(txId);
          }
          if( tasks == null )
                throw new javax.jms.JMSException("Transaction is not active 6.");
          synchronized(tasks){
                tasks.addLast(new Transaction(false, logInfo, message, txId));
          }
        }
  
    }    
  
    class Transaction {
        private LogInfo logInfo;
        private SpyMessage message;
        private Long txId;
        private boolean add;
        public Transaction(boolean add, LogInfo logInfo, SpyMessage message, Long 
txId) {
          this.add = add;
          this.logInfo = logInfo;
          this.message = message;
          this.txId = txId;
        }
        public void commit() throws JMSException {
          if(!add)
                logInfo.log.remove(message, txId);
        }
        public void rollback() throws JMSException {
          if(add)
                logInfo.log.remove(message, txId);
        }
    }
  
    private String jmsDBPoolName;
    TxManager   txManager;
  
  /**
   * Insert the method's description here.
   * Creation date: (6/27/2001 1:07:07 AM)
   * @return java.lang.String
   */
  public java.lang.String getJmsDBPoolName() {
        return jmsDBPoolName;
  }
  
        public String getName() {
                return "JBossMQ-PersistenceManager";
        }
  
  /**
   * getTxManager method comment.
   */
  public org.jbossmq.pm.TxManager getTxManager() {
        return txManager;
  }
  
        public void initService() throws Exception {
  
            //Get an InitialContext
            InitialContext ctx= new InitialContext();
            datasource= (DataSource) ctx.lookup(jmsDBPoolName);
            txLog= new TxLog(datasource);
  
                JMSServer server = (JMSServer)getServer().invoke(new 
ObjectName(org.jbossmq.server.JBossMQServiceMBean.OBJECT_NAME), "getJMSServer", new 
Object[] {}, new String[] {} );                
                server.setPersistenceManager(this);
  
        }
  
    public void restore(org.jbossmq.server.JMSServer server) throws 
javax.jms.JMSException {
  
        TreeSet committingTXs = txLog.restore();
        HashMap clone;
        synchronized (messageLogs) {
          clone = (HashMap) messageLogs.clone();
        }
  
        Iterator iter = clone.values().iterator();
        while (iter.hasNext()) {
  
          LogInfo logInfo = (LogInfo)iter.next();
  
          JMSDestination q = server.getJMSDestination(logInfo.destination);
  
          SpyMessage rebuild[] = logInfo.log.restore(committingTXs, q.toString());
  
          //TODO: make sure this lock is good enough
          synchronized (q) {
                for (int i = 0; i < rebuild.length; i++) {
                  q.restoreMessage(rebuild[i], logInfo.queueId);
                }
          }
        }
  
    }      
  
  /**
   * Insert the method's description here.
   * Creation date: (6/27/2001 1:07:07 AM)
   * @param newJmsDBPoolName java.lang.String
   */
  public void setJmsDBPoolName(java.lang.String newJmsDBPoolName) {
        jmsDBPoolName = newJmsDBPoolName;
  }
  
        public void startService() throws Exception {
  
                JMSServer server = (JMSServer)getServer().invoke(new 
ObjectName(org.jbossmq.server.JBossMQServiceMBean.OBJECT_NAME), "getJMSServer", new 
Object[] {}, new String[] {} );                
                restore(server);
  
        }
  }
  
  
  1.1                  
jbossmq/src/main/org/jbossmq/pm/jdbc/PersistenceManagerMBean.java
  
  Index: PersistenceManagerMBean.java
  ===================================================================
  package org.jbossmq.pm.jdbc;
  
  /*
   * jBoss, the OpenSource EJB server
   *
   * Distributable under LGPL license.
   * See terms of license at gnu.org.
   */
  
  /*
   * jBoss, the OpenSource EJB server
   *
   * Distributable under LGPL license.
   * See terms of license at gnu.org.
   */
  
  /*
   * jBoss, the OpenSource EJB server
   *
   * Distributable under LGPL license.
   * See terms of license at gnu.org.
   */
  
  /*
   * jBoss, the OpenSource EJB server
   *
   * Distributable under LGPL license.
   * See terms of license at gnu.org.
   */
  
  /*
   * jBoss, the OpenSource EJB server
   *
   * Distributable under LGPL license.
   * See terms of license at gnu.org.
   */
  
  /**
   *   <description> 
   * MBean interface for the JBossMQ JMX service.
   *      
   *   @see <related>
   *   @author Vincent Sheffer ([EMAIL PROTECTED])
   *   @version $Revision: 1.1 $
   */
  public interface PersistenceManagerMBean
     extends org.jboss.util.ServiceMBean
  {
     // Constants -----------------------------------------------------
     public static final String OBJECT_NAME = ":service=JBossMQ";
        
     // Public --------------------------------------------------------
  
        
     // Public --------------------------------------------------------
  
        
     // Public --------------------------------------------------------
  
        
     // Public --------------------------------------------------------
  public java.lang.String getJmsDBPoolName();
  public void setJmsDBPoolName(java.lang.String newJmsDBPoolName);
  }
  
  
  
  1.1                  jbossmq/src/main/org/jbossmq/pm/jdbc/TxLog.java
  
  Index: TxLog.java
  ===================================================================
  /*
   * JBossMQ, the OpenSource JMS implementation
   *
   * Distributable under LGPL license.
   * See terms of license at gnu.org.
   */
  package org.jbossmq.pm.jdbc;
  
  import java.io.Serializable;
  import java.io.IOException;
  import java.io.RandomAccessFile;
  import java.util.TreeSet;
  import java.util.Iterator;
  
  import javax.jms.JMSException;
  import javax.naming.*;
  import javax.sql.*;
  import java.sql.*;
  
  /**
   * This is used to keep a log of active transactions.
   * It is used to rollback transactions when the system restarts.
   *
   * @author: Jayesh Parayali ([EMAIL PROTECTED])
   * @version $Revision: 1.1 $
   */
  public class TxLog {
  
    /////////////////////////////////////////////////////////////////////
    // Attributes
    /////////////////////////////////////////////////////////////////////
    protected long nextTransactionId = Long.MIN_VALUE;
    protected static DataSource ds = null;
  
    /////////////////////////////////////////////////////////////////////
    // Constructors
    /////////////////////////////////////////////////////////////////////
    public TxLog(DataSource datasource) throws JMSException {
                  if (ds == null)
                ds = datasource;
    }    
  
    private final Connection getConnection() throws SQLException {
        return ds.getConnection();
    }    
  
    synchronized public Long createTx() throws JMSException {
        Long id = new Long(nextTransactionId++);
        Connection con = null;
        PreparedStatement stmt = null;
        try {
          con = getConnection();
          stmt = con.prepareStatement("insert into jms_transactions values(?)");
          String hexString = null;
          long lId = id.longValue();
          if (lId <= 0L)
                hexString = "-"+ Long.toHexString((-1)*lId);
          else
                hexString = Long.toHexString(lId);
  
          stmt.setString(1,hexString);
          stmt.executeUpdate();
          con.commit();
        } catch ( SQLException e ) {
          throwJMSException("Could not write transaction log on commit.",e);
        }
          try {
                if(stmt != null)
                  stmt.close();
                if(con != null)
                  con.close();
          }
          catch(SQLException e) {
                throwJMSException("Could not close database connection in transaction 
log (createTx).",e);
          }
        return id;
    }    
  
    synchronized public void commitTx(Long txId) throws JMSException {
        Connection con = null;
        PreparedStatement stmt = null;
        try {
          con = getConnection();
          stmt = con.prepareStatement("delete from jms_transactions where id = ?");
          String hexString = null;
          long id = txId.longValue();
          if (id <= 0L)
                hexString = "-"+ Long.toHexString((-1)*id);
          else
                hexString = Long.toHexString(id);
  
          stmt.setString(1,hexString);
          stmt.executeUpdate();
          con.commit();
        } catch ( SQLException e ) {
          throwJMSException("Could not write transaction log on commit.",e);
        }
          try {
                if(stmt != null)
                  stmt.close();
                if(con != null)
                  con.close();
          }
          catch(SQLException e) {
                throwJMSException("Could not close database connection in transaction 
log (commitTx)",e);
          }
    }    
  
    synchronized public void rollbackTx(Long txId) throws JMSException {
        Connection con = null;
        PreparedStatement stmt = null;
        try {
          con = getConnection();
          stmt = con.prepareStatement("delete from jms_transactions where id = ?");
          String hexString = null;
          long id = txId.longValue();
          if (id <= 0L)
                hexString = "-"+ Long.toHexString((-1)*id);
          else
                hexString = Long.toHexString(id);
  
          stmt.setString(1,hexString);
          stmt.executeUpdate();
          con.commit();
        } catch ( SQLException e ) {
          throwJMSException("Could not write transaction log on commit.",e);
        }
          try {
                if(stmt != null)
                  stmt.close();
                if(con != null)
                  con.close();
          }
          catch(SQLException e) {
                throwJMSException("Could not close database connection in transaction 
log (rollbackTx)",e);
          }
    }    
  
    synchronized public java.util.TreeSet restore() throws JMSException {
        TreeSet items = new TreeSet();;
        Connection con = null;
        PreparedStatement stmt = null;
        ResultSet rs = null;
        try {
          con = getConnection();
          stmt = con.prepareStatement("select  id from jms_transactions");
          rs = stmt.executeQuery();
          while(rs.next()) {
                long id = Long.parseLong(rs.getString(1).trim(),16);
                items.add(new Long(id));
          }
        } catch ( SQLException e ) {
          throwJMSException("Could not write transaction log on commit.",e);
        }
        finally {
          try {
                if(rs != null)
                  rs.close();
                if(stmt != null)
                  stmt.close();
                if(con != null)
                  con.close();
          }
          catch(SQLException e) {
                throwJMSException("Could not close database connection in transaction 
log (restore)",e);
          }
        }
  
        return items;
    }    
  
    /////////////////////////////////////////////////////////////////////
    // Private Methods
    /////////////////////////////////////////////////////////////////////
    private void throwJMSException(String message, Exception e) throws JMSException {
        JMSException newE = new JMSException(message);
        newE.setLinkedException(e);
        throw newE;
    }    
  
  }
  
  

_______________________________________________
Jboss-development mailing list
[EMAIL PROTECTED]
http://lists.sourceforge.net/lists/listinfo/jboss-development

Reply via email to