View
231
Download
0
Embed Size (px)
Citation preview
Topics:Topics:JMS & JavaMailJMS & JavaMail
Chin-Yi TsaiChin-Yi Tsai
22
JMSJMS
JMSJMS提供一種可以在提供一種可以在 J2EEJ2EE程式和元件間傳送訊息程式和元件間傳送訊息的方式的方式 Message agentMessage agent
J2EEJ2EE應用程式和元件使用應用程式和元件使用 JMS APIJMS API 和和 JMSJMS溝通溝通
JMSJMS由五個元素所組成由五個元素所組成 ProviderProvider ClientClient MessageMessage Administered object: designation factory, connectionAdministered object: designation factory, connection Native serverNative server
33
訊息傳遞架構訊息傳遞架構
Point-to-pointPoint-to-point 同步同步
Subscriber/publisherSubscriber/publisher
44
Point-to-Point MessagingPoint-to-Point Messaging
Client1 Client2Queuesends
acknowledges
consumesMsg
Msg
55
Publish/Subscribe MessagingPublish/Subscribe Messaging
Client1
Client2
publishes subscribes
subscribes
Msg
Topic
Client3
delivers
delivers
66
The basic building blocks of a JMS application The basic building blocks of a JMS application
Administered objectsAdministered objects connection factories and destinations connection factories and destinations
Connections Connections
Sessions Sessions
Message producers Message producers
Message consumers Message consumers
Messages Messages
77
JMS API Programming ModelJMS API Programming Model
Connection
creates creates
creates
MsgDestination
receives from
sends to
ConnectionFactory
Destination
MessageConsumerSession
MessageProducer
creates
88
JMS Message TypesJMS Message Types
Message TypeMessage Type ContainsContains Some MethodsSome Methods
TextMessageTextMessage StringString getText,setTextgetText,setText
MapMessageMapMessage set of name/value pairsset of name/value pairs setString,setDouble,setLonsetString,setDouble,setLong,getDouble,getStringg,getDouble,getString
BytesMessageBytesMessage stream of uninterpreted stream of uninterpreted bytesbytes
writeBytes,readByteswriteBytes,readBytes
StreamMessageStreamMessage stream of primitive valuesstream of primitive values writeString,writeDouble,writwriteString,writeDouble,writeLong,readStringeLong,readString
ObjectMessageObjectMessage serialize objectserialize object setObject,getObjectsetObject,getObject
Message Format Message Header Message Properties Message Body
99
javax.jms Packagejavax.jms Package
ConnectionConnection Encapsulates a virtual connection with a JMS API provider
SessionSession Single-threaded context for producing and consuming messages
QueueSenderQueueSender An object created by a session used for sending messages to a
queue
QueueReceiverQueueReceiver An object created by a session used for receiving messages from
a queue
1010
Creating a Point-to-Point JMS API ApplicationCreating a Point-to-Point JMS API Application
1. Look up a Connection factory using the J.N.D.I. API.
2. Look up the message queue using the J.N.D.I. API.
3. Create a Connection using the factory.
4. Create a Session object.
5. Create a MessageSender object.
6. Create one or more Message objects.
7. Send one or more Message objects using the MessageSender object.
8. Send a control message to the Queue object that allmessages have been sent.
1111
try {INitialContext jnidiContext = new InitialContext();queueConnectionFactory = (QueueConnectionFactory)
jndiContext.lookup( "QueueConnectionFactory" );queue = (Queue) jndiContext.lookup( queueName );queueConnection =
queueConnectionFactory.createQueueConnection( );queueSession = queueConnection.createQueueSession( false ,
Session.AUTO_ACKNOWLEDGE );queueSender = queueSession.createSender( queue );message = queueSession.createTextMessage( );message.setText( "This is a simple message” );queueSender.send( message );queueConnection.close( );
} catch (JMSException e) {
System.out.println("Exception occurred: " +
}Send message
1212
try {InitialContext jndiContext = new InitialContext();factory = (QueueConnectionFactory)
jndiContext.lookup("QueueConnectionFactory");queue = (Queue) jndiContext.lookup(queueName);QueueConnection connection = factory.createQueueConnection ();QueueSession session = connection.createQueueSession(false,
QueueSession.CLIENT_ACKNOWLEDGE );receiver = session.createReceiver(queue);
receiver.setMessageListener (new MessageListener(){ public void onMessage (Message newMessage){ try { TextMessage message = (TextMessage) newMessage; System.out.println("Message received "); System.out.println( message.getText() ); message.acknowledge ( ); } catch (Exception e) {} } }); connection.start(); } catch (JMSException e){ } catch (NamingException e) { }
Receive message
1313
Creating a Publish/Subscribe JMS API ApplicationCreating a Publish/Subscribe JMS API Application
1. Look up a TopicConnection factory using the J.N.D.I. API.
2. Look up a Topic object using the J.N.D.I. API.
3. Create Connection and Session objects.
4. Create a TopicPublisher object.
5. Create one or more Message objects.
6. Publish one or more messages using the TopicPublisher object.
1414
try {
topicConnectionFactory = (TopicConnectionFactory)jndiContext.lookup("TopicConnectionFactory");topic = (Topic) jndiContext.lookup(topicName);topicConnection = topicConnectionFactory.createTopicConnection();topicSession = topicConnection.createTopicSession(false,
Session.AUTO_ACKNOWLEDGE); topicPublisher = topicSession.createPublisher(topic);
message = topicSession.createTextMessage(); message.setText("This is a simple publish/subscribe message”); topicPublisher.publish(message);
} catch (JMSException e) {
System.out.println("Exception occurred: " + e.toString());
}
Publisher
1515
try {TopicConnectionFactory factory =(TopicConnectionFactory)jndiContext.lookup("TopicConnectionFactory");topic = (Topic) jndiContext.lookup(topicName);TopicConnection connection = factory.createTopicConnection ();TopicSession session = connection.createTopicSession(false,TopicSession.CLIENT_ACKNOWLEDGE );subscriber = session.createSubscriber(topic);
subscriber.setMessageListener (new MessageListener(){ public void onMessage (Message newMessage){ try { TextMessage message = (TextMessage) newMessage; System.out.println("Message received "); System.out.println( message.getText() ); message.acknowledge (); } catch (Exception e) {} } }); connection.start();
} catch (JMSException e){ } Subscriber
1616
JavaMailJavaMail
1717
JavaMail APIJavaMail API
傳送電子郵件傳送電子郵件接收電子郵件接收電子郵件刪除電子郵件刪除電子郵件回覆和發送一封電子郵件回覆和發送一封電子郵件發送電子郵件發送電子郵件傳送附加檔案傳送附加檔案接收附加檔案接收附加檔案搜索一個電子郵件資料夾搜索一個電子郵件資料夾
1818
Java Mail API PackageJava Mail API Package
javax.mailjavax.mail Classes modeling a mail system. Classes modeling a mail system.
javax.mail.eventjavax.mail.event Listeners and events for the JavaMail API. Listeners and events for the JavaMail API.
javax.mail.internetjavax.mail.internet Classes specific to Internet mail systems. Classes specific to Internet mail systems.
javax.mail.searchjavax.mail.search Message search terms for the JavaMail API. Message search terms for the JavaMail API.
1919
Important ClassesImportant Classes
javax.mail.javax.mail.SessionSession
Javax.mail.Javax.mail.MessageMessage
Javax.mail.AddressJavax.mail.Address
Javax.mail.AuthenticatorJavax.mail.Authenticator
Javax.mail.Javax.mail.TransportTransport
Javax.mail.Javax.mail.StoreStore
Javax.mail.FolderJavax.mail.Folder
2020
Main Java mail main classesMain Java mail main classes
MessMessageage
MessMessageage
SessionSession
FolderFolderFolderFolder
TransportTransport
Connection to serverConnection to server
Sending mailSending mailusing SMTPusing SMTP
Receiving mail usingReceiving mail usingPOP or IMAPPOP or IMAP
StoreStore
Connection toConnection toa remove mail foldera remove mail folder(mainly the INBOX)(mainly the INBOX)
Receive and arrayReceive and arrayof messagesof messages
Sending a messageSending a message
收 送
2121
傳送電子郵件傳送電子郵件Session sendMailSession;Store store;Transport transport;
Properties props = new Properties();
sendMailSession = Session.getInstance(props, null);
props.put("mail.smtp.host", "smtp.jspinsider.com");
Message newMessage = new MimeMessage(sendMailSession);
newMessage.setFrom(new InternetAddress(request.getParameter("from")));newMessage.setRecipient(Message.RecipientType.TO,
new InternetAddress ( request.getParameter ("to")));newMessage.setSubject(request.getParameter("subject"));newMessage.setSentDate(new Date());newMessage.setText(request.getParameter("text"));
transport = sendMailSession.getTransport("smtp");
transport.send(newMessage);
Session
Message
Transport
2222
接收電子郵件接收電子郵件
Properties props = new Properties( );Session ses1 = Session.getDefaultInstance( props , null );
Store store1 = ses1.getStore(“pop3”);
Store1.connect( host, username, password);
Folder folder1 = store1.getFolder(“INBOX”);Folder1.open(Folder.READ_ONLY);
Message msg[] = folder1.getMessage();
folder1.close(false);store1.close();
Session
Store
Folder
Message
2323
referencereference
http://java.sun.com/products/javamail/javadocs/indhttp://java.sun.com/products/javamail/javadocs/index.htmlex.html
http://java.sun.com/j2ee/1.4/docs/api/http://java.sun.com/j2ee/1.4/docs/api/