By GokiSoft.com|
09:28 09/09/2022|
Java Web + EJB (EAD)
EJB-EAD- Tạo dự án TMS sử dụng Topic/Queue - Phần 1
Tags:
Phản hồi từ học viên
5
(Dựa trên đánh giá ngày hôm nay)
![Trần Văn Điệp [Teacher]](https://www.gravatar.com/avatar/ae8d66100c882095c429167b0fc6737f.jpg?s=80&d=mm&r=g)
Trần Văn Điệp
2020-03-12 15:49:44
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package aptech;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.Resource;
import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.JMSConsumer;
import javax.jms.JMSContext;
import javax.jms.JMSException;
import javax.jms.MapMessage;
import javax.jms.Message;
import javax.jms.MessageProducer;
import javax.jms.ObjectMessage;
import javax.jms.Queue;
import javax.jms.Session;
/**
*
* @author diep.tv
*/
public class FormSender extends javax.swing.JFrame {
@Resource(mappedName = "java:app/myQueue")
private static Queue java_appMyQueue;
@Resource(mappedName = "java:comp/DefaultJMSConnectionFactory")
private static ConnectionFactory java_compDefaultJMSConnectionFactory;
/**
* Creates new form FormSender
*/
public FormSender() {
initComponents();
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
FormReceiver receiver = new FormReceiver();
receiver.setVisible(true);
JMSContext context = java_compDefaultJMSConnectionFactory.createContext();
JMSConsumer consumer = context.createConsumer(java_appMyQueue);
consumer.setMessageListener(receiver);
}
});
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
jLabel1 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
jLabel3 = new javax.swing.JLabel();
txtName = new javax.swing.JTextField();
txtSubject = new javax.swing.JTextField();
jScrollPane1 = new javax.swing.JScrollPane();
txtMessage = new javax.swing.JTextArea();
sendBtn = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jLabel1.setText("Name:");
jLabel2.setText("Subject:");
jLabel3.setText("Message:");
txtMessage.setColumns(20);
txtMessage.setRows(5);
jScrollPane1.setViewportView(txtMessage);
sendBtn.setText("Send");
sendBtn.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
sendBtnActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel1)
.addComponent(jLabel2)
.addComponent(jLabel3))
.addGap(50, 50, 50)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(sendBtn)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(txtSubject, javax.swing.GroupLayout.DEFAULT_SIZE, 309, Short.MAX_VALUE)
.addComponent(txtName)
.addComponent(jScrollPane1)))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(31, 31, 31)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel1)
.addComponent(txtName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(42, 42, 42)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel2)
.addComponent(txtSubject, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(51, 51, 51)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel3)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 80, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(31, 31, 31)
.addComponent(sendBtn)
.addContainerGap(22, Short.MAX_VALUE))
);
pack();
}// </editor-fold>
private void sendBtnActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
String name = txtName.getText().toString();
String subject = txtSubject.getText().toString();
String message = txtMessage.getText().toString();
MessageData messageData = new MessageData(name, subject, message);
try {
System.out.println("Starting..................");
sendJMSMessageToMyQueue(messageData);
System.out.println("End...................");
} catch (JMSException ex) {
Logger.getLogger(FormSender.class.getName()).log(Level.SEVERE, null, ex);
}
}
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(FormSender.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(FormSender.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(FormSender.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(FormSender.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new FormSender().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JButton sendBtn;
private javax.swing.JTextArea txtMessage;
private javax.swing.JTextField txtName;
private javax.swing.JTextField txtSubject;
// End of variables declaration
private Message createJMSMessageForjava_appMyQueue(Session session, MessageData messageData) throws JMSException {
// TODO create and populate message to send
ObjectMessage message = session.createObjectMessage();
message.setStringProperty("name", messageData.getName());
message.setStringProperty("subject", messageData.getSubject());
message.setStringProperty("message", messageData.getMessage());
return message;
}
private void sendJMSMessageToMyQueue(MessageData messageData) throws JMSException {
Connection connection = null;
Session session = null;
try {
connection = java_compDefaultJMSConnectionFactory.createConnection();
session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
MessageProducer messageProducer = session.createProducer(java_appMyQueue);
messageProducer.send(createJMSMessageForjava_appMyQueue(session, messageData));
} finally {
if (session != null) {
try {
session.close();
} catch (JMSException e) {
Logger.getLogger(this.getClass().getName()).log(Level.WARNING, "Cannot close session", e);
}
}
if (connection != null) {
connection.close();
}
}
}
}
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package aptech;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.ObjectMessage;
import javax.swing.table.DefaultTableModel;
/**
*
* @author diep.tv
*/
public class FormReceiver extends javax.swing.JFrame implements MessageListener{
private DefaultTableModel tableModel;
/**
* Creates new form FormReceiver
*/
public FormReceiver() {
initComponents();
tableModel = (DefaultTableModel) tblMessage.getModel();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
jScrollPane1 = new javax.swing.JScrollPane();
tblMessage = new javax.swing.JTable();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
tblMessage.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
},
new String [] {
"Name", "Subject", "Message"
}
) {
boolean[] canEdit = new boolean [] {
false, false, false
};
public boolean isCellEditable(int rowIndex, int columnIndex) {
return canEdit [columnIndex];
}
});
jScrollPane1.setViewportView(tblMessage);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 595, Short.MAX_VALUE)
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 353, Short.MAX_VALUE)
.addContainerGap())
);
pack();
}// </editor-fold>
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(FormReceiver.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(FormReceiver.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(FormReceiver.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(FormReceiver.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new FormReceiver().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JTable tblMessage;
// End of variables declaration
@Override
public void onMessage(Message message) {
System.out.println("Form Receiver.....................");
if(message instanceof ObjectMessage) {
try {
String name = message.getStringProperty("name");
String subject = message.getStringProperty("subject");
String msg = message.getStringProperty("message");
tableModel.addRow(new Object[] {name, subject, msg});
} catch (JMSException ex) {
Logger.getLogger(FormReceiver.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package aptech;
import java.io.Serializable;
/**
*
* @author diep.tv
*/
public class MessageData implements Serializable{
String name, subject, message;
public MessageData(String name, String subject, String message) {
this.name = name;
this.subject = subject;
this.message = message;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSubject() {
return subject;
}
public void setSubject(String subject) {
this.subject = subject;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
@Override
public String toString() {
return "MessageData{" + "name=" + name + ", subject=" + subject + ", message=" + message + '}';
}
}