import org.hibernate.*;
import org.hibernate.cfg.Configuration;
import org.hibernate.cfg.Environment;
import javax.swing.*;
import java.util.List;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
/**
* User: Alan P. Sexton
* Date: 26-Jan-2007
* Time: 09:42:00
*/
public class Main
{
private static final Log LOG = LogFactory.getLog(Main.class);
private static SessionFactory sessions = null;
public static void main(String[] args)
{
boolean createDb = false;
if (args.length == 1 && "create".equals(args[0].toLowerCase()))
createDb = true;
else if (args.length != 0)
{
System.err.println("Usage: java Main [create]");
System.exit(1);
}
Configuration cfg = new Configuration();
try
{
cfg.addClass(Message.class);
String username = cfg.getProperty("hibernate.connection.username");
// get the username and password via a Swing JDialog box
String[] userNamePassword = getUsernamePassword(username);
if (userNamePassword == null)
{
LOG.info("No valid user name/password pair was entered");
System.exit(1) ;
}
else
{
cfg.setProperty("hibernate.connection.username", userNamePassword[0]);
cfg.setProperty("hibernate.connection.password", userNamePassword[1]);
}
if (createDb)
{
LOG.info("(Re-)creating the database: old data will be destroyed");
cfg.setProperty(Environment.HBM2DDL_AUTO, "create");
}
LOG.debug("Building the Session Factory");
sessions = cfg.buildSessionFactory();
LOG.debug("About to add message");
String msgText = "Hello World";
Long id ;
id = addMessage(msgText);
LOG.debug("Added Message");
LOG.debug("Message saved to database");
System.out.println(getMessagesAsString()) ;
String[] msgs = {"Take me to your leader...", "...(please)"};
updateMessage(id, "Greetings Earthling", msgs);
LOG.debug("Message Updated");
System.out.println(getMessagesAsString()) ;
}
catch (Exception e)
{
e.printStackTrace();
}
System.exit(0);
}
private static Long addMessage(String msgText)
throws HibernateException
{
Session session = sessions.openSession();
Transaction tx = null;
Message message = null;
try
{
tx = session.beginTransaction();
message = new Message(msgText);
// At this point, Message is "Transient"
session.save(message);
// Now it is "Persistent"
tx.commit();
}
catch (HibernateException e)
{
if (tx != null)
tx.rollback();
throw e;
}
finally
{
session.close();
}
// Note that the following works even though message is no longer associated with a session,
// i.e., it is "Detached":
return message.getId();
}
private static String getMessagesAsString()
throws HibernateException
{
StringBuilder retMessages = new StringBuilder();
Session session = sessions.openSession();
Transaction tx = null;
try
{
tx = session.beginTransaction();
List messages = session.createQuery("from Message as m order by m.id asc"). list();
System.out.println("Number of messages found: " + messages.size());
for (Object message : messages)
{
Message m = (Message) message;
retMessages.append(String.format("%d:%s%n", m.getId(), m.getText()));
}
tx.commit();
}
catch (HibernateException e)
{
if (tx != null)
tx.rollback();
throw e;
}
finally
{
session.close();
}
return retMessages.toString() ;
}
private static void updateMessage(Long msgID, String msgText, String[] msgTexts)
throws HibernateException
{
Session session = sessions.openSession();
Transaction tx = null;
try
{
tx = session.beginTransaction();
Message message = (Message) session.load(Message.class, msgID);
message.setText(msgText);
for (String msgText1 : msgTexts)
{
Message nextMessage = new Message(msgText1);
message.setNextMessage(nextMessage);
message = nextMessage;
}
tx.commit();
}
catch (HibernateException e)
{
if (tx != null)
tx.rollback();
throw e;
}
finally
{
session.close();
}
}
/**
* Shows a dialog box for the user to enter a password and a username. Note that using this
* method means that the application must be terminated by calling System.exit(0)
* to ensure that all the Swing threads created by this method are terminated and the JVM
* can exit.
*
* @param initialUsername the String that the username field in the dialog
* should be initialised to.
* @return null if the user clicked on the CANCEL button or on
* the window close button. Otherwise an array of 2 Strings is returned.
* The first String in the array is the username entered, the second
* is the password.
*/
private static String[] getUsernamePassword(String initialUsername)
{
JTextField username = new JTextField((initialUsername == null) ? "" : initialUsername, 20);
JPasswordField password = new JPasswordField(20);
final Object[] fields = {"Enter your database username:",
username,
"Enter your database password:",
password
};
JOptionPane pane = new JOptionPane(fields,
JOptionPane.QUESTION_MESSAGE,
JOptionPane.OK_CANCEL_OPTION,
null);
JDialog d = pane.createDialog(null, "Database Access");
d.setVisible(true);
Integer returnValue = (Integer) pane.getValue();
d.dispose();
if (returnValue == null || returnValue != JOptionPane.OK_OPTION)
return null;
return new String[]{username.getText(), new String(password.getPassword())};
}
}