package database;
import java.io.Serializable;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.AnnotationConfiguration;
import org.hibernate.connection.C3P0ConnectionProvider;
import org.hibernate.tool.hbm2ddl.SchemaExport;
import org.hibernate.Session;
import domain.Event;
import domain.EventId;
import domain.EventType;
import domain.PermissionType;
import domain.RepetitionType;
import domain.Role;
import domain.User;
/**
* Class responsible for all the database tasks, such is creating a database session
* setting up the database, etc. This class implements the singleton pattern.
* @author Yury Michurin
*
*/
public class Database implements Serializable {
private static final long serialVersionUID = -5572180101330095214L;
private static Database instance = null;
private String hostname;
private String username;
private String password;
private String database;
private SessionFactory sessionFactory;
private AnnotationConfiguration annotationConfiguration;
/**
* Creates the database object, if possible, read the settings from a file
*/
private Database() {
setInfo("yuryweb", "winblows", "calendar", "localhost");
}
/**
* Changes the settings of the database and re-configures hibernate
* @param username username of the database
* @param password password of the database
* @param database database name
* @param hostname hostname of mysql
*/
public void setInfo(String username, String password, String database, String hostname) {
this.username = username;
this.password = password;
this.database = database;
this.hostname = hostname;
configureHibernate();
}
/**
* Destroys the current instance, so another one with different settings could be created
*/
public static void dispose() {
Database.instance = null;
}
/**
* singleton pattern getInstance()
* @return instance of the database
*/
public static Database getInstance() {
if ( null == Database.instance ) {
Database.instance = new Database();
}
return Database.instance;
}
/**
* Performs configuration on hibernate
*/
private void configureHibernate() {
this.annotationConfiguration = new AnnotationConfiguration()
//.addPackage("domain") //the fully qualified package name
.addAnnotatedClass(EventId.class)
.addAnnotatedClass(Event.class)
.addAnnotatedClass(EventType.class)
.addAnnotatedClass(PermissionType.class)
.addAnnotatedClass(RepetitionType.class)
.addAnnotatedClass(Role.class)
.addAnnotatedClass(User.class)
//.configure()
.setProperty("hibernate.dialect", "org.hibernate.dialect.MySQLDialect")
.setProperty("hibernate.connection.driver_class", "com.mysql.jdbc.Driver")
.setProperty("hibernate.connection.url", getConnectionString())
//.setProperty("hibernate.show_sql", "true")
//.setProperty("hibernate.format_sql", "true")
//.setProperty("hibernate.use_sql_comments", "true")
.setProperty("hibernate.connection.provider_class", C3P0ConnectionProvider.class.getName())
.setProperty("hibernate.c3p0.min_size", "5")
.setProperty("hibernate.c3p0.max_size", "10")
.setProperty("hibernate.c3p0.timeout", "300")
.setProperty("hibernate.c3p0.max_statements", "50")
.setProperty("hibernate.c3p0.idle_test_period", "3000");
this.sessionFactory = this.annotationConfiguration.buildSessionFactory();
}
/**
* Get hibernate's session factory
* @return session factory
*/
public SessionFactory getSessionFactory() {
return this.sessionFactory;
}
/**
* Constructs connection string from all the info
* @return connection string
*/
public String getConnectionString() {
return String.format("jdbc:mysql://%s/%s?user=%s&password=%s&useUnicode=true&characterEncoding=utf8", hostname, database, username, password);
}
/**
* Creates database from the settings
* @return true on success, false on failure
*/
public Boolean createDatabase() {
Connection connection = null;
Boolean result = false;
try {
connection = DriverManager.getConnection(String.format("jdbc:mysql://%s/?user=%s&password=%s&useUnicode=true&characterEncoding=utf8", hostname, username, password));
Statement stmt = connection.createStatement();
stmt.execute("DROP DATABASE IF EXISTS " + database);
int queryResult = stmt.executeUpdate("CREATE DATABASE `" + database + "` DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci");
if (queryResult == 1) {
result = true;
}
} catch (SQLException e) {
result = false;
} finally {
if (connection != null) {
try {
connection.close();
} catch (SQLException e) {
// Can't do anything about it.
}
}
}
return result;
}
/**
* Creates all the tables
* @return true on success, false on failure
*/
public Boolean createTables() {
this.configureHibernate();
new SchemaExport(annotationConfiguration).create(false, true);
return true;
}
/**
* load the initial data to the database. some necessary, some not.
* @return true if the load succeed, else false
*/
public boolean loadData() {
Boolean success = false;
Session session = Database.getInstance().getSessionFactory().openSession();
// load initial event-types
EventType eventType1 = new EventType();
eventType1.setColor("#C0C0C0"); // Silver
eventType1.setDescription("Conference");
EventType eventType2 = new EventType();
eventType2.setColor("#90EE90"); // LightGreen
eventType2.setDescription("Meeting");
EventType eventType3 = new EventType();
eventType3.setColor("#87CEEB"); // SkyBlue
eventType3.setDescription("Lecture");
EventType eventType4 = new EventType();
eventType4.setColor("#FA8072"); // Salmon
eventType4.setDescription("Call");
EventType eventType5 = new EventType();
eventType5.setColor("#DDA0DD"); // Plum
eventType5.setDescription("Birthday");
EventType eventType6 = new EventType();
eventType6.setColor("#FFA07A"); // LightSalmon
eventType6.setDescription("Party");
EventType eventType7 = new EventType();
eventType7.setColor("#FFFF00"); // Yellow
eventType7.setDescription("Other");
// load initial roles
Role role1 = new Role();
role1.setDescription("User");
Role role2 = new Role();
role2.setDescription("Admin");
// load initial permission-types
PermissionType permissionType1 = new PermissionType();
permissionType1.setDescription("Public");
PermissionType permissionType2 = new PermissionType();
permissionType2.setDescription("Protected");
PermissionType permissionType3 = new PermissionType();
permissionType3.setDescription("Private");
// load initial repetition-types
RepetitionType repetitionType1 = new RepetitionType();
repetitionType1.setDescription("None");
RepetitionType repetitionType2 = new RepetitionType();
repetitionType2.setDescription("Daily");
RepetitionType repetitionType3 = new RepetitionType();
repetitionType3.setDescription("Weekly");
RepetitionType repetitionType4 = new RepetitionType();
repetitionType4.setDescription("Monthly");
RepetitionType repetitionType5 = new RepetitionType();
repetitionType5.setDescription("Yearly");
Transaction transaction = session.beginTransaction();
transaction.begin();
try {
session.save(eventType1);
session.save(eventType2);
session.save(eventType3);
session.save(eventType4);
session.save(eventType5);
session.save(eventType6);
session.save(eventType7);
session.save(role1);
session.save(role2);
session.save(permissionType1);
session.save(permissionType2);
session.save(permissionType3);
session.save(repetitionType1);
session.save(repetitionType2);
session.save(repetitionType3);
session.save(repetitionType4);
session.save(repetitionType5);
transaction.commit();
success = true;
} catch (Exception ex) {
transaction.rollback();
} finally {
session.close();
}
return success;
}
/**
* Getter for hostname
* @return the hostname
*/
public String getHostname() {
return hostname;
}
/**
* Getter for username
* @return the username
*/
public String getUsername() {
return username;
}
/**
* Getter for password
* @return the password
*/
public String getPassword() {
return password;
}
/**
* Getter for database
* @return the database
*/
public String getDatabase() {
return database;
}
}