Advertisement
Guest User

MailDAO

a guest
Oct 5th, 2016
123
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 9.45 KB | None | 0 0
  1. package mail;
  2.  
  3. import java.sql.*;
  4. import javafx.collections.FXCollections;
  5. import javafx.collections.ObservableList;
  6. import javafx.scene.control.Alert;
  7. import javafx.scene.control.Alert.AlertType;
  8.  
  9. /* The MailDAO is the most important class in the client application.
  10.  
  11. The MailDAO class acts as the data access object for the application.
  12. All data going into or out of the database passes through this class.
  13. Naturally, this is where the database connection lives. */
  14. public class MailDAO {
  15.  
  16. Connection connection;
  17. Statement stmt;
  18. // This is the user id of the user who is currently logged in.
  19. int user;
  20. String name;
  21. ObservableList<Handle> handles;
  22.  
  23. public MailDAO() {
  24. handles = FXCollections.observableArrayList();
  25. }
  26.  
  27. public String getUserName() {
  28. return name;
  29. }
  30.  
  31. private String getUserNameFromID(int id) {
  32. String sqlStr = "SELECT name from user where iduser =" + id;
  33. String userName = null;
  34. try {
  35. ResultSet rset = stmt.executeQuery(sqlStr);
  36. if (rset.next()) {
  37. userName = rset.getString(1);
  38. }
  39. } catch (SQLException ex) {
  40. userName = null;
  41. }
  42. return userName;
  43. }
  44.  
  45. private int getUserIDFromName(String userName) {
  46. String sqlStr = "SELECT iduser from user where name =\'" + userName + "\'";
  47. int id = 0;
  48. try {
  49. ResultSet rset = stmt.executeQuery(sqlStr);
  50. if (rset.next()) {
  51. id = rset.getInt(1);
  52. }
  53. } catch (SQLException ex) {
  54. id = 0;
  55. }
  56. return id;
  57. }
  58.  
  59. public boolean logIn(String userName, String password) {
  60. connect();
  61. boolean success = false;
  62. try {
  63. String query = "select iduser from user where name=\'"
  64. + userName + "\' and password=\'" + password + "\'";
  65. ResultSet rset = stmt.executeQuery(query);
  66.  
  67. if (rset.next()) {
  68. success = true;
  69. this.user = rset.getInt(1);
  70. this.name = userName;
  71. this.refreshHandles();
  72. }
  73. } catch (SQLException ex) {
  74. this.user = 0;
  75. this.name = null;
  76. }
  77. return success;
  78. }
  79. String newAcctSQL = "insert into user (name,password) values(?,?)";
  80. PreparedStatement newAcctStmt;
  81.  
  82. public boolean createNewAccount(String userName, String password) {
  83. connect();
  84. boolean success = false;
  85. try {
  86. newAcctStmt.setString(1, userName);
  87. newAcctStmt.setString(2, password);
  88. newAcctStmt.executeUpdate();
  89. success = true;
  90. String query = "select iduser from user where name=\'"
  91. + userName + "\' and password=\'" + password + "\'";
  92. ResultSet rset = stmt.executeQuery(query);
  93.  
  94. if (rset.next()) {
  95. this.user = rset.getInt(1);
  96. this.name = userName;
  97. this.refreshHandles();
  98. }
  99. } catch (SQLException ex) {
  100. this.user = 0;
  101. this.name = null;
  102. success = false;
  103. }
  104. return success;
  105. }
  106.  
  107. public Message getMessage(int id) {
  108. Message result = null;
  109. try {
  110. String sqlStr1 = "SELECT sender, subject, body, sent from message where idmessage=" + id;
  111. ResultSet rset1 = stmt.executeQuery(sqlStr1);
  112.  
  113. int sender_id = 0;
  114. String subject = null;
  115. String body = null;
  116. String time = null;
  117. if (rset1.next()) {
  118. sender_id = rset1.getInt(1);
  119. subject = rset1.getString(2);
  120. body = rset1.getString(3);
  121. time = rset1.getString(4);
  122. }
  123.  
  124. String sender = this.getUserNameFromID(sender_id);
  125. result = new Message(sender, this.name, subject, body, time);
  126. } catch (SQLException ex) {
  127. showMessageDialog("An SQL error took place." + ex.getMessage());
  128. }
  129. return result;
  130. }
  131.  
  132. public void deleteMessage(int id) {
  133. try {
  134. String whereClause = "where message=" + id;
  135. String sqlStr = "delete from recipient " + whereClause
  136. + " and recipient=\'" + this.user + "\'";
  137. stmt.execute(sqlStr);
  138.  
  139. // If we just removed the last recipient for this message, remove it from the
  140. // messages table, too.
  141. sqlStr = "select recipient from recipient " + whereClause;
  142. ResultSet results = stmt.executeQuery(sqlStr);
  143. if (!results.isBeforeFirst()) {
  144. sqlStr = "delete from message where idmessage=" + id;
  145. stmt.execute(sqlStr);
  146. }
  147.  
  148. this.refreshHandles();
  149. } catch (SQLException ex) {
  150. showMessageDialog("An SQL error took place." + ex.getMessage());
  151. }
  152. }
  153. String insertMsgSQL = "insert into message (subject,body,sender,sent) values (?,?,?,CURDATE())";
  154. PreparedStatement insertMsgStmt;
  155. String insertRecipientSQL = "insert into recipient (message,recipient) values (?,?)";
  156. PreparedStatement insertRecipientStmt;
  157.  
  158. public void sendMessage(Message msg) {
  159. try {
  160. // Data in this message has to be spread over two tables, the messages
  161. // table and the recipients table. We do the insertion into the messages
  162. // table so the database can generate a messageID for this message. We
  163. // then use that messageID to do the insertions into the recipients table.
  164. insertMsgStmt.setString(1, msg.getSubject());
  165. insertMsgStmt.setString(2, msg.getContents());
  166. insertMsgStmt.setInt(3, this.user);
  167. insertMsgStmt.executeUpdate();
  168. // The id for the new message is generated automatically by the database
  169. // We have to query the database to see what it is.
  170. String query2 = "select LAST_INSERT_ID()";
  171. ResultSet rset = stmt.executeQuery(query2);
  172. if (rset.next()) {
  173. int messageID = Integer.parseInt(rset.getString(1));
  174. String[] recipients = msg.getRecipients().split("[ ,]");
  175. insertRecipientStmt.setInt(1, messageID);
  176. for (int n = 0; n < recipients.length; n++) {
  177. int recipient_id = this.getUserIDFromName(recipients[n]);
  178. if (recipient_id != 0) {
  179. insertRecipientStmt.setInt(2, recipient_id);
  180. insertRecipientStmt.executeUpdate();
  181. }
  182. }
  183. }
  184. } catch (SQLException ex) {
  185. showMessageDialog("An SQL error took place." + ex.getMessage());
  186. }
  187. }
  188.  
  189. public void logOut() {
  190. shutDown();
  191. handles.clear();
  192. user = 0;
  193. name = null;
  194. }
  195.  
  196. public ObservableList<Handle> getHandles() { return handles; }
  197.  
  198. public void refreshHandles() {
  199. handles.clear();
  200. try {
  201. String sqlString1 = "SELECT message, concat(sender,':',subject) from handle where receiver='" + user + "\'";
  202. ResultSet rset = stmt.executeQuery(sqlString1);
  203.  
  204. while (rset.next()) {
  205. handles.add(new Handle(rset.getInt(1), rset.getString(2)));
  206. }
  207. } catch (SQLException ex) {
  208. showMessageDialog("Could not fetch handles: " + ex.getMessage());
  209. }
  210. }
  211.  
  212. private void connect() {
  213. try {
  214. Class.forName("com.mysql.jdbc.Driver").newInstance();
  215. } catch (Exception ex) {
  216. showMessageDialog("Unable to load JDBC driver. Application will exit.");
  217. System.exit(0);
  218. }
  219.  
  220. // Establish a connection
  221. try {
  222. String url = "jdbc:mysql://localhost:3306/mail?user=root&password=cmsc250";
  223. connection = DriverManager.getConnection(url);
  224. stmt = connection.createStatement();
  225. newAcctStmt = connection.prepareStatement(newAcctSQL);
  226. insertMsgStmt = connection.prepareStatement(insertMsgSQL);
  227. insertRecipientStmt = connection.prepareStatement(insertRecipientSQL);
  228. } catch (SQLException ex) {
  229. showMessageDialog("Unable to connect to database. Application will exit.");
  230. System.exit(0);
  231. }
  232. }
  233.  
  234. private void shutDown() {
  235. try {
  236. if(stmt != null) {
  237. stmt.close();
  238. stmt = null;
  239. }
  240. if(newAcctStmt != null) {
  241. newAcctStmt.close();
  242. newAcctStmt = null;
  243. }
  244. if(insertMsgStmt != null) {
  245. insertMsgStmt.close();
  246. insertMsgStmt = null;
  247. }
  248. if(insertRecipientStmt != null) {
  249. insertRecipientStmt.close();
  250. insertRecipientStmt = null;
  251. }
  252. if(connection != null) {
  253. connection.close();
  254. connection = null;
  255. }
  256. } catch (Exception e) {
  257. showMessageDialog("Error on shutdown:" + e.getMessage());
  258. }
  259. }
  260.  
  261. private void showMessageDialog(String message) {
  262. Alert alert = new Alert(AlertType.ERROR);
  263. alert.setTitle("Error");
  264. alert.setContentText(message);
  265. alert.showAndWait();
  266. }
  267. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement