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

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

// Java classes
import javax.jms.JMSException;
import javax.jms.Session;
import javax.jms.Topic;
import javax.jms.TopicConnection;
import javax.jms.TopicConnectionFactory;
import javax.jms.TopicSession;

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

// Framework

/** Encapsulates JMS-related information neccessary to send and receive JMS messages.
 * 
 * @author Venky Kullampalle
 * @version 1.0
 */
public class TopicDescriptor extends AbstractMessageDescriptor {  

   private String topicName = null;   

   /** Creates a new instance of JMSService */
   public TopicDescriptor() {
      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 (topicName == null ) {
         throw new ServiceException(
               "Missing properties: topicName");
      }
   }

    public void setTopicName(String name) {
      this.topicName = name;
   }

   public String getTopicName() {
      return topicName;
   }

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

   public Topic getTopic(String providerURL) throws ServiceException {
      return (Topic)getDestination(providerURL, getTopicName(),Topic.class);
   }  

   public TopicConnection createTopicConnection(String providerURL) throws ServiceException {
      return createTopicConnection(getConnectionFactory(providerURL));
   }

   public TopicConnection createTopicConnection(TopicConnectionFactory factory) throws ServiceException {

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

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

   public TopicSession createTopicSession(TopicConnection connection) throws ServiceException {
      return createTopicSession(connection, true, Session.AUTO_ACKNOWLEDGE);
   }
}