By GokiSoft.com|
19:15 06/11/2020|
Java Web + EJB (EAD)
Share Code- Chữa bài tập quản lý công ty - SessionBean EJB - Phần 2 - TMS
Hướng dẫn chữa bài tập
[EAD][EJB] Assignment viết chương trình quản lý công ty
/*
* 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 company;
/**
*
* @author DiepTV
*/
public class MessageData {
String name, description, dateTime;
public MessageData() {
}
public MessageData(String name, String description, String dateTime) {
this.name = name;
this.description = description;
this.dateTime = dateTime;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getDateTime() {
return dateTime;
}
public void setDateTime(String dateTime) {
this.dateTime = dateTime;
}
}
/*
* 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 company;
import entities.Company;
import java.text.SimpleDateFormat;
import java.util.List;
import javax.ejb.EJB;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;
import session.CompanySessionBeanRemote;
import java.util.Date;
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.Message;
import javax.jms.MessageProducer;
import javax.jms.ObjectMessage;
import javax.jms.Queue;
import javax.jms.Session;
import javax.jms.TextMessage;
/**
*
* @author DiepTV
*/
public class MainFrame extends javax.swing.JFrame {
@Resource(mappedName = "jms/myQueue")
private static Queue myQueue;
@Resource(mappedName = "jms/__defaultConnectionFactory")
private static ConnectionFactory myQueueFactory;
@EJB
private static CompanySessionBeanRemote companySessionBean;
DefaultTableModel tableModel;
/**
* Creates new form MainFrame
*/
public MainFrame() {
initComponents();
tableModel = (DefaultTableModel) tblCompany.getModel();
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
ReceiverFrame receiverFrame = new ReceiverFrame();
receiverFrame.setVisible(true);
//cho phep lang nghe message len ReceiverFrame
JMSContext context = myQueueFactory.createContext();
JMSConsumer consumer = context.createConsumer(myQueue);
consumer.setMessageListener(receiverFrame);
}
});
}
/**
* 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() {
jPanel1 = new javax.swing.JPanel();
jLabel1 = new javax.swing.JLabel();
txtId = new javax.swing.JTextField();
jLabel2 = new javax.swing.JLabel();
txtName = new javax.swing.JTextField();
jLabel3 = new javax.swing.JLabel();
txtCompanyKey = new javax.swing.JTextField();
jLabel4 = new javax.swing.JLabel();
txtAddress = new javax.swing.JTextField();
cbEnabled = new javax.swing.JCheckBox();
jLabel5 = new javax.swing.JLabel();
jScrollPane1 = new javax.swing.JScrollPane();
txtDescription = new javax.swing.JTextArea();
btnShowAll = new javax.swing.JButton();
btnFind = new javax.swing.JButton();
btnUpdate = new javax.swing.JButton();
btnSendMsg = new javax.swing.JButton();
jScrollPane2 = new javax.swing.JScrollPane();
tblCompany = new javax.swing.JTable();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("Input Company Information"));
jLabel1.setText("ID: ");
jLabel2.setText("Name: ");
jLabel3.setText("Company Key: ");
jLabel4.setText("Address: ");
cbEnabled.setText("Enabled");
jLabel5.setText("Description:");
txtDescription.setColumns(20);
txtDescription.setRows(5);
jScrollPane1.setViewportView(txtDescription);
btnShowAll.setText("Show All");
btnShowAll.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnShowAllActionPerformed(evt);
}
});
btnFind.setText("Find");
btnFind.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnFindActionPerformed(evt);
}
});
btnUpdate.setText("Update");
btnUpdate.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnUpdateActionPerformed(evt);
}
});
btnSendMsg.setText("Send Msg");
btnSendMsg.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnSendMsgActionPerformed(evt);
}
});
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(19, 19, 19)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(jLabel5)
.addGap(0, 0, Short.MAX_VALUE))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanel1Layout.createSequentialGroup()
.addComponent(jLabel1)
.addGap(89, 89, 89)
.addComponent(txtId, javax.swing.GroupLayout.PREFERRED_SIZE, 242, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(btnShowAll))
.addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel3)
.addComponent(jLabel4)
.addComponent(jLabel2))
.addGap(34, 34, 34)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(txtName, javax.swing.GroupLayout.PREFERRED_SIZE, 242, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(txtAddress, javax.swing.GroupLayout.DEFAULT_SIZE, 242, Short.MAX_VALUE)
.addComponent(txtCompanyKey, javax.swing.GroupLayout.DEFAULT_SIZE, 242, Short.MAX_VALUE)
.addComponent(cbEnabled)
.addComponent(jScrollPane1))
.addGap(18, 18, 18)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(btnFind)
.addComponent(btnUpdate)
.addComponent(btnSendMsg))))))
.addContainerGap(14, Short.MAX_VALUE))))
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel1)
.addComponent(txtId, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(btnShowAll))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel2)
.addComponent(txtName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel3)
.addComponent(txtCompanyKey, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(btnFind))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel4)
.addComponent(txtAddress, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(btnUpdate))
.addGap(18, 18, 18)
.addComponent(cbEnabled)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(29, 29, 29)
.addComponent(jLabel5))
.addGroup(jPanel1Layout.createSequentialGroup()
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(btnSendMsg)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
tblCompany.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
},
new String [] {
"ID", "Name", "Company Key", "Address", "Enabled", "Description"
}
) {
boolean[] canEdit = new boolean [] {
false, false, false, false, false, false
};
public boolean isCellEditable(int rowIndex, int columnIndex) {
return canEdit [columnIndex];
}
});
jScrollPane2.setViewportView(tblCompany);
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(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jScrollPane2))
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 154, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
pack();
}// </editor-fold>
private void btnShowAllActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
List<Company> list = companySessionBean.findAll();
tableModel.setRowCount(0);
for (Company company : list) {
tableModel.addRow(new Object[]{company.getId(), company.getName(), company.getCompanyKey(),
company.getAddress(), company.getEnabled(), company.getDescription()});
}
}
private void btnFindActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
if(txtId.getText().trim().length() == 0) {
JOptionPane.showMessageDialog(this, "Nhap ID can tim kiem");
return;
}
int id = Integer.parseInt(txtId.getText());
Company company = companySessionBean.find(id);
if(company != null) {
txtName.setText(company.getName());
txtCompanyKey.setText(company.getCompanyKey());
txtAddress.setText(company.getAddress());
if(company.getEnabled() == 1) {
cbEnabled.setSelected(true);
} else {
cbEnabled.setSelected(false);
}
txtDescription.setText(company.getDescription());
} else {
JOptionPane.showMessageDialog(this, "Khong tim thay thong tin cty vs ID nhap vao");
}
}
private void btnUpdateActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
Company company = new Company();
company.setId(Integer.parseInt(txtId.getText()));
company.setName(txtName.getText());
company.setAddress(txtAddress.getText());
company.setCompanyKey(txtCompanyKey.getText());
if(cbEnabled.isSelected()) {
company.setEnabled(1);
} else {
company.setEnabled(0);
}
company.setDescription(txtDescription.getText());
companySessionBean.update(company);
}
private void btnSendMsgActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
String name = txtName.getText();
String des = txtDescription.getText();
SimpleDateFormat format = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
Date date = new Date();
String currentTimeStr = format.format(date);
MessageData messageData = new MessageData(name, des, currentTimeStr);
try {
sendJMSMessageToMyQueue(messageData);
} catch (JMSException ex) {
Logger.getLogger(MainFrame.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(MainFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(MainFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(MainFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(MainFrame.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 MainFrame().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JButton btnFind;
private javax.swing.JButton btnSendMsg;
private javax.swing.JButton btnShowAll;
private javax.swing.JButton btnUpdate;
private javax.swing.JCheckBox cbEnabled;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JLabel jLabel5;
private javax.swing.JPanel jPanel1;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JScrollPane jScrollPane2;
private javax.swing.JTable tblCompany;
private javax.swing.JTextField txtAddress;
private javax.swing.JTextField txtCompanyKey;
private javax.swing.JTextArea txtDescription;
private javax.swing.JTextField txtId;
private javax.swing.JTextField txtName;
// End of variables declaration
private Message createJMSMessageForjmsMyQueue(Session session, MessageData messageData) throws JMSException {
// TODO create and populate message to send
ObjectMessage tm = session.createObjectMessage();
tm.setStringProperty("name", messageData.getName());
tm.setStringProperty("description", messageData.getDescription());
tm.setStringProperty("currentTime", messageData.getDateTime());
return tm;
}
private void sendJMSMessageToMyQueue(MessageData messageData) throws JMSException {
Connection connection = null;
Session session = null;
try {
connection = myQueueFactory.createConnection();
session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
MessageProducer messageProducer = session.createProducer(myQueue);
messageProducer.send(createJMSMessageForjmsMyQueue(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 company;
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 DiepTV
*/
public class ReceiverFrame extends javax.swing.JFrame implements MessageListener{
DefaultTableModel tableModel;
/**
* Creates new form ReceiverFrame
*/
public ReceiverFrame() {
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", "Description", "Date Time"
}
) {
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, 482, Short.MAX_VALUE)
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 324, 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(ReceiverFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(ReceiverFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(ReceiverFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(ReceiverFrame.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 ReceiverFrame().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) {
if(message instanceof ObjectMessage) {
try {
String name = ((ObjectMessage) message).getStringProperty("name");
String description = ((ObjectMessage) message).getStringProperty("description");
String currentTime = ((ObjectMessage) message).getStringProperty("currentTime");
tableModel.addRow(new Object[] {name, description, currentTime});
} catch (JMSException ex) {
Logger.getLogger(ReceiverFrame.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}
Tags:
Phản hồi từ học viên
5
(Dựa trên đánh giá ngày hôm nay)