/**
 * ÀÌ ¼Ò½º´Â Spring ÇÁ·¹ÀÓ¿öÅ© ¿öÅ©ºÏ¿¡¼­ »ç¿ëÇÑ ¿¹Á¦ ¼Ò½ºÀÔ´Ï´Ù. 
 * ÀÌ ¼Ò½º´Â ¸ðµç °³¹ßÀÚµéÀÌ ÀÚÀ¯·Ó°Ô ¼öÁ¤ ¹× ¹èÆ÷ÇÒ ¼ö ÀÖ½À´Ï´Ù. 
 * ´Ü, ÀÌ ¼Ò½º¸¦ ±â¹ÝÀ¸·Î »õ·Î¿î ¾ÖÇÃ¸®ÄÉÀÌ¼ÇÀ» °³¹ßÇÒ °æ¿ì ÃâÃ³¸¦ ¸í½ÃÇØ ÁÖ½Ã¸é µË´Ï´Ù. 
 */
package net.javajigi.common.service;

import java.util.Hashtable;

import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.Queue;
import javax.jms.QueueConnection;
import javax.jms.QueueConnectionFactory;
import javax.jms.QueueSender;
import javax.jms.QueueSession;
import javax.jms.TextMessage;
import javax.naming.InitialContext;
import javax.naming.NamingException;


public class SendRecvClient {
	static final int N = 1;

	QueueConnection conn;

	QueueSession session;

	Queue queB;

	public void setupPTP() throws JMSException, NamingException {
		Hashtable props = new Hashtable();

		// ----------------------JBOSS
		props.put(InitialContext.INITIAL_CONTEXT_FACTORY,
				"org.jnp.interfaces.NamingContextFactory");
		props.put(InitialContext.PROVIDER_URL, "jnp://127.0.0.1:1099");
		// ----------------------JBOSS

		InitialContext iniCtx = new InitialContext(props);
		Object tmp = iniCtx.lookup("UIL2ConnectionFactory");
		QueueConnectionFactory qcf = (QueueConnectionFactory) tmp;

		conn = qcf.createQueueConnection();
		queB = (Queue) iniCtx.lookup("queue/B");
		session = conn.createQueueSession(false, QueueSession.AUTO_ACKNOWLEDGE);
		conn.start();
	}

	public void sendRecvAsync(String textBase) throws JMSException,
			NamingException, InterruptedException {
		System.out.println("Begin sendRecvAsync");
		// Setup the PTP connection, session
		setupPTP();

		// Send a few text msgs to queB
		QueueSender send = session.createSender(queB);
		for (int m = 0; m < N; m++) {
			TextMessage tm = session.createTextMessage(textBase + "#" + m);
			send.send(tm);
			System.out.println("sendRecvAsync, sent text=" + tm.getText());
		}
		System.out.println("End sendRecvAsync");
	}

	public void stop() throws JMSException {
		conn.stop();
		session.close();
		conn.close();
	}

	public static void main(String args[]) throws Exception {
		System.out.println("Begin SendRecvClient, now="
				+ System.currentTimeMillis());
		SendRecvClient client = new SendRecvClient();
		client.sendRecvAsync("A text msg");
		client.stop();
		System.exit(0);
		System.out.println("End SendRecvClient");
	}
}
