/********************************************************************
 * Copyright © 2004 VHA. All rights reserved
 ********************************************************************/

// Package
package gov.va.med.fw.service.jms;

// Java classes
import javax.jms.JMSException;
import javax.jms.Queue;
import javax.jms.QueueConnection;
import javax.jms.QueueConnectionFactory;
import javax.jms.QueueSession;
import javax.jms.Session;

import gov.va.med.fw.service.ServiceException;

// Framework

/** Encapsulates JMS-related information neccessary to send and receive JMS messages.
 * 
 * @author Vu Le
 * @version 1.0
 */
public class QueueDescriptor extends AbstractMessageDescriptor {
    
   private String queueName = null;


   /** Creates a new instance of JMSService */
   public QueueDescriptor() {
      super();
   }

   /**
    * Checks if a service broker is set correctly
    * @throws Exception Thrown if a service broker is not set
    */
   public void afterPropertiesSet() throws Exception {
       super.afterPropertiesSet();
      if ( queueName == null ) {
         throw new ServiceException(
               "Missing properties: factoryName, queueName, providerURL or contextName");
      }
   }

  
   public void setQueueName(String name) {
      this.queueName = name;
   }

   public String getQueueName() {
      return queueName;
   }
  
   public QueueConnectionFactory getConnectionFactory(String providerURL) throws ServiceException {
      return (QueueConnectionFactory)getConnectionFactory(providerURL, getFactoryName(),QueueConnectionFactory.class);
   }

  

   public Queue getQueue(String providerURL) throws ServiceException {
      return (Queue)getDestination(providerURL, getQueueName(), Queue.class);
   }

   

   public QueueConnection createQueueConnection(String providerURL) throws ServiceException {
      return createQueueConnection(getConnectionFactory(providerURL));
   }

   public QueueConnection createQueueConnection(QueueConnectionFactory factory) throws ServiceException {

      QueueConnection connection = null;
      try {
         connection = factory.createQueueConnection();
         connection.start();
      }
      catch (JMSException e) {
         throw new ServiceException("Failed to create a connection", e);
      }
      return connection;
   }

   public QueueSession createQueueSession(QueueConnection connection,
         boolean transacted,
         int mode) throws ServiceException {
      QueueSession session = null;
      try {
         session = connection.createQueueSession(transacted, mode);
      }
      catch (JMSException e) {
         throw new ServiceException("Failed to create a session", e);
      }
      return session;
   }

   public QueueSession createQueueSession(QueueConnection connection) throws ServiceException {
      return createQueueSession(connection, true, Session.AUTO_ACKNOWLEDGE);
   }
}