Java/Database SQL JDBC/JDBC EJB
Ejb and JDBC
/*
MySQL and Java Developer"s Guide
Mark Matthews, Jim Cole, Joseph D. Gradecki
Publisher Wiley,
Published February 2003,
ISBN 0471269239
*/
import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Enumeration;
import java.util.StringTokenizer;
import java.util.Vector;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
import javax.swing.border.TitledBorder;
public class TaskManager extends JFrame {
TaskManager(Tasks taskList) {
super("MySQL-Java Task Manager");
this.taskList = taskList;
buildGui();
pack();
setVisible(true);
}
private void buildGui() {
fileMenu.add(fileExit);
menuBar.add(fileMenu);
setJMenuBar(menuBar);
frameContainer.setLayout(new BorderLayout());
frameContainer.add(new TaskPanel(taskList));
setContentPane(frameContainer);
addWindowListener(new WindowHandler());
fileExit.addActionListener(new MenuHandler());
}
private JPanel frameContainer = new JPanel();
private JMenuBar menuBar = new JMenuBar();
private JMenu fileMenu = new JMenu("File");
private JMenuItem fileExit = new JMenuItem("Exit");
private Tasks taskList;
class WindowHandler extends WindowAdapter {
public void windowClosing(WindowEvent we) {
System.exit(0);
}
}
class MenuHandler implements ActionListener {
public void actionPerformed(ActionEvent ae) {
if (ae.getActionCommand().equals("Exit")) {
System.exit(0);
}
}
}
public static void main(String[] args) {
String configFileName = "tasks.conf";
if (args.length == 1) {
configFileName = args[0];
}
File configFile = new File(configFileName);
if (!configFile.exists() || !configFile.canRead()) {
System.err.println("Can"t read config file "" + configFileName
+ """);
System.exit(1);
}
FileReader configReader = null;
try {
configReader = new FileReader(configFile);
} catch (FileNotFoundException fnfX) {
}
Tasks taskList = new Tasks(configReader);
try {
configReader.close();
} catch (IOException ioX) {
}
TaskManager ex = new TaskManager(taskList);
}
}
interface TaskDelegate {
public boolean execute(Connection conn);
}
class TaskPanel extends JPanel {
public TaskPanel(Tasks taskList) {
this.taskList = taskList;
setLayout(new BorderLayout());
connPane = new ConnectionPane();
connPane.setBorder(new TitledBorder("Connection Data"));
taskPane = new TaskPane();
taskPane.setBorder(new TitledBorder("Tasks"));
add(connPane, BorderLayout.NORTH);
add(taskPane, BorderLayout.SOUTH);
}
private Tasks taskList;
private ConnectionPane connPane;
private TaskPane taskPane;
class ConnectionPane extends JPanel {
ConnectionPane() {
setLayout(new GridLayout(5, 2));
add(hostNameLabel);
add(hostNameField);
add(dbNameLabel);
add(dbNameField);
add(portNumberLabel);
add(portNumberField);
add(usernameLabel);
add(usernameField);
add(passwordLabel);
add(passwordField);
}
ConnectionData getConnectionData() {
String password = new String(passwordField.getPassword());
ConnectionData data = new ConnectionData(hostNameField.getText(),
dbNameField.getText(), portNumberField.getText(),
usernameField.getText(), password);
return (data);
}
private JLabel hostNameLabel = new JLabel("Host Name:");
private JLabel dbNameLabel = new JLabel("Database Name:");
private JLabel portNumberLabel = new JLabel("Port Number:");
private JLabel usernameLabel = new JLabel("Username:");
private JLabel passwordLabel = new JLabel("Password:");
private JTextField hostNameField = new JTextField(20);
private JTextField dbNameField = new JTextField(20);
private JTextField portNumberField = new JTextField("3306", 6);
private JTextField usernameField = new JTextField(20);
private JPasswordField passwordField = new JPasswordField(20);
}
class TaskPane extends JPanel {
TaskPane() {
int taskCount = TaskPanel.this.taskList.getTaskCount();
int rows = ((taskCount % COLS) == 0) ? (taskCount / COLS)
: ((taskCount / COLS) + 1);
setLayout(new GridLayout(rows, COLS));
taskButtons = new JButton[taskCount];
TaskHandler handler = new TaskHandler();
Enumeration tasks = taskList.getTasks();
int task = 0;
while (tasks.hasMoreElements()) {
TaskDefinition taskDef = (TaskDefinition) (tasks.nextElement());
if (!taskDef.isEnabled()) {
continue;
}
String taskName = taskDef.getName();
taskButtons[task] = new JButton(taskName);
taskButtons[task].addActionListener(handler);
add(taskButtons[task++]);
}
}
private JButton[] taskButtons;
final static int COLS = 2;
}
class TaskHandler implements ActionListener {
public void actionPerformed(ActionEvent ae) {
ConnectionData connData = connPane.getConnectionData();
Connection conn = connData.buildConnection();
if (conn == null) {
String msg = "Could not build connection. Check provided\n"
+ "connection data and verify server availability.";
JOptionPane.showMessageDialog(TaskPanel.this, msg,
"Connection Failure", JOptionPane.ERROR_MESSAGE);
return;
}
String taskName = ae.getActionCommand();
Enumeration tasks = taskList.getTasks();
boolean dispatched = false;
while (tasks.hasMoreElements()) {
TaskDefinition taskDef = (TaskDefinition) (tasks.nextElement());
if (!taskDef.isEnabled()) {
continue;
}
if (taskName.equals(taskDef.getName())) {
try {
Class delegateClass = taskDef.getDelegate();
Object delegateObject = delegateClass.newInstance();
TaskDelegate delegate = (TaskDelegate) delegateObject;
dispatched = delegate.execute(conn);
if (!dispatched) {
String msg = "Could not execute task: "
+ taskDef.getName();
JOptionPane.showMessageDialog(TaskPanel.this, msg,
"Task Failure", JOptionPane.ERROR_MESSAGE);
}
} catch (InstantiationException iX) {
String msg = "Failed to instantiate delegate for task: "
+ taskDef.getName();
JOptionPane.showMessageDialog(TaskPanel.this, msg,
"Task Failure", JOptionPane.ERROR_MESSAGE);
} catch (IllegalAccessException iaX) {
String msg = "Cound not access delegate for task: "
+ taskDef.getName();
JOptionPane.showMessageDialog(TaskPanel.this, msg,
"Task Failure", JOptionPane.ERROR_MESSAGE);
}
break;
}
}
if (!dispatched) {
try {
conn.close();
} catch (SQLException sqlX) {
}
}
}
}
}
class ConnectionData {
public ConnectionData(String hostName, String dbName, String port,
String username, String password) {
this.hostName = hostName;
this.dbName = dbName;
this.port = port;
this.username = username;
this.password = password;
}
public String getUsername() {
return (username);
}
public String getPassword() {
return (password);
}
public String getUrl() {
String url = "jdbc:mysql://" + hostName + ":" + port + "/" + dbName;
return (url);
}
public Connection buildConnection() {
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException cnfX) {
cnfX.printStackTrace(System.err);
return (null);
}
try {
Connection conn = DriverManager.getConnection(getUrl(),
getUsername(), getPassword());
return (conn);
} catch (SQLException sqlX) {
System.out.println(SqlExceptionReader.readException(sqlX));
return (null);
}
}
private String hostName;
private String dbName;
private String port;
private String username;
private String password;
}
class SqlExceptionReader {
public static String readException(SQLException sqlX) {
StringBuffer msg = new StringBuffer(1024);
SQLException nextX;
int exceptionNumber = 0;
do {
++exceptionNumber;
msg.append("Exception " + exceptionNumber + ": \n");
msg.append(" Message: " + sqlX.getMessage() + "\n");
msg.append(" State : " + sqlX.getSQLState() + "\n");
msg.append(" Code : " + sqlX.getErrorCode() + "\n");
} while ((nextX = sqlX.getNextException()) != null);
return (msg.toString());
}
}
class Tasks {
public Tasks(InputStreamReader taskS) {
readTasks(taskS);
}
public int getTaskCount() {
return (taskDefs.size());
}
public Enumeration getTasks() {
return (taskDefs.elements());
}
private void readTasks(InputStreamReader taskS) {
try {
BufferedReader reader = new BufferedReader(taskS);
String taskLine;
while ((taskLine = reader.readLine()) != null) {
addTaskDefinition(taskLine);
}
} catch (IOException ioX) {
System.err.println("Failed to fully parse task file: " + ioX);
}
}
private void addTaskDefinition(String taskLine) {
StringTokenizer taskTok = new StringTokenizer(taskLine, DELIM);
if (taskTok.countTokens() != TOKEN_NUM) {
System.err.println("Invalid task definition: " + taskLine);
return;
}
Class taskClass = null;
String taskClassName = taskTok.nextToken();
try {
taskClass = Class.forName(taskClassName);
} catch (ClassNotFoundException cnfX) {
System.err.println("Class "" + taskClassName + "" not found: "
+ cnfX);
return;
}
boolean taskEnabled = false;
if (taskTok.nextToken().equalsIgnoreCase("enabled")) {
taskEnabled = true;
}
String taskName = taskTok.nextToken();
TaskDefinition def = new TaskDefinition(taskName, taskClass,
taskEnabled);
taskDefs.add(def);
}
private Vector taskDefs = new Vector();
final static int TOKEN_NUM = 3;
final static String DELIM = ":";
}
class TaskDefinition {
public TaskDefinition(String name, Class delegate, boolean enabled) {
this.name = name;
this.delegate = delegate;
this.enabled = enabled;
}
public String getName() {
return (name);
}
public Class getDelegate() {
return (delegate);
}
public boolean isEnabled() {
return (enabled);
}
private String name;
private Class delegate;
private boolean enabled;
}