Glassfish初体验之六

上篇使用annotation来创建客户端代码发送消息到JMS队列中,非常的简单但是必须要把客户端部署到server上。很多情况我们并不一定要在服务器上去执行客户端代码或者说我们并不一定要部署到服务器上。
下面就是要使用java 应用来执行JMS客户端代码。
package com.test.jms;

import java.util.Enumeration;
import java.util.Properties;
import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageProducer;
import javax.jms.Queue;
import javax.jms.QueueBrowser;
import javax.jms.Session;
import javax.jms.TextMessage;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;

public class TestSendMessage
{

/**
* @param args
*/
public static void main(String[] args)
{

java.util.Properties properties = new Properties();

// set the properties of the connection

properties.put(Context.INITIAL_CONTEXT_FACTORY,
"com.sun.enterprise.naming.SerialInitContextFactory");

properties.put(Context.PROVIDER_URL, "localhost:8080");

properties.put(Context.SECURITY_PRINCIPAL, "admin");

properties.put(Context.SECURITY_CREDENTIALS, "adminadmin");

// start the initial context with the specified properties
ConnectionFactory queueCF = null;
Queue queue = null;
try
{
InitialContext context = new InitialContext(properties);
queueCF = (ConnectionFactory) context.lookup("jms/myCF");

if (queueCF == null)
{
System.out.println("ConnectionFactory is null");
}

queue = (Queue) context.lookup("jms/myQueue");
if (queue == null)
{
System.out.println("Queue is null");
}
} catch (NamingException e)
{ //
}

try
{
Connection connection = queueCF.createConnection();
Session session = connection.createSession(false,
Session.AUTO_ACKNOWLEDGE);
MessageProducer producer = session.createProducer((Destination) queue);
TextMessage message = session.createTextMessage();
message.setText("This is message ");
producer.send(message);

QueueBrowser browser = session.createBrowser(queue);
Enumeration msgs = browser.getEnumeration();

System.out.println("TCF: " + queueCF);
System.out.println("<br />Topic: " + queue);

if (!msgs.hasMoreElements())
{
System.out.println("No messages in queue");
} else
{
while (msgs.hasMoreElements())
{
Message tempMsg = (Message) msgs.nextElement();
System.out.println("Message: " + ((TextMessage) tempMsg).getText()
+ "<br>");
}
}

browser.close();
producer.close();
session.close();
connection.close();

} catch (JMSException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

执行后显示:

TCF: com.sun.messaging.jms.ra.ConnectionFactoryAdapter@1988886
<br />Topic: Sun Java System MQ Destination
getName(): myQueueDes
Class: com.sun.messaging.Queue
getVERSION(): 3.0
isReadonly(): false
getProperties(): {imqDestinationName=myQueueDes, imqDestinationDescription=A Description for the Destination Object}
Message: This is message <br>
Message: This is message <br>
Message: This is message <br>
Message: This is message <br>
Message: This is message <br>

即说明我们的测试成功了。

你可能感兴趣的:(应用服务器,Security,jms,sun,Glassfish)