Guest User

Untitled

a guest
Jan 15th, 2018
93
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 14.25 KB | None | 0 0
  1. package dao;
  2.  
  3. import java.sql.Connection;
  4. import java.sql.Date;
  5. import java.sql.DriverManager;
  6. import java.sql.PreparedStatement;
  7. import java.sql.ResultSet;
  8. import java.sql.SQLException;
  9. import java.sql.Statement;
  10. import java.sql.Time;
  11. import java.util.ArrayList;
  12. import java.util.Calendar;
  13. import java.util.Properties;
  14.  
  15. import time.Entry;
  16.  
  17.  
  18.  
  19.  
  20.  
  21.  
  22.  
  23.  
  24. /**
  25. * @author Anders Njøs Slinde
  26. *
  27. */
  28. public class TimeDAO {
  29.  
  30. private String driver = "org.apache.derby.jdbc.EmbeddedDriver";
  31. private String protocol = "jdbc:derby:";
  32. private Statement statement;
  33. private Connection connection;
  34. private String dbName = "timeDB"; // the name of the database
  35.  
  36. //ID and name of the user logged in.
  37. private int userID;
  38. private String userName;
  39. private double userWage = 0;
  40.  
  41. /**
  42. * Constructor is private to make creation of class illegal except by the singleton.
  43. * connect 'jdbc:derby://localhost:1527/timeDB';
  44. */
  45. private TimeDAO() {
  46. try {
  47. Class.forName(driver).newInstance();
  48. Properties props = new Properties();
  49. connection = DriverManager.getConnection(protocol + dbName + ";create=true", props);
  50. statement = connection.createStatement();
  51.  
  52. //createTimeDB();
  53. } catch (Exception e) {
  54. e.printStackTrace();
  55. }
  56. }
  57.  
  58. /**
  59. * Method to create new database
  60. */
  61. private void createTimeDB() {
  62. String query1 =
  63. "CREATE TABLE entries (" +
  64. "id INT NOT NULL PRIMARY KEY GENERATED ALWAYS AS IDENTITY (START WITH 1, INCREMENT BY 1)," +
  65. "userID INT NOT NULL," +
  66. "date DATE NOT NULL," +
  67. "start TIME NOT NULL," +
  68. "finish TIME NOT NULL," +
  69. "hours INT NOT NULL," +
  70. "factor INT NOT NULL," +
  71. "comment VARCHAR(500)," +
  72. "type VARCHAR(100)" +
  73. ")";
  74.  
  75. String query2 =
  76. "CREATE TABLE users (" +
  77. "id INT NOT NULL PRIMARY KEY GENERATED ALWAYS AS IDENTITY (START WITH 1, INCREMENT BY 1)," +
  78. "name VARCHAR(100) NOT NULL," +
  79. "wage DOUBLE NOT NULL" +
  80. ")";
  81.  
  82. try {
  83. statement.execute(query1);
  84. statement.execute(query2);
  85.  
  86.  
  87. } catch (SQLException e) {
  88. e.printStackTrace();
  89. }
  90. }
  91.  
  92. /**
  93. * Method to insert a User record into the users table
  94. * @param record
  95. * @throws SQLException
  96. * @return true if user inserted successfully
  97. */
  98. public boolean insertUser(String name, double wage) {
  99. name = name.toLowerCase();
  100. String query = "insert into users values" +
  101. "(DEFAULT, '" +
  102. name + "' ," +
  103. wage +
  104. ")";
  105.  
  106. try {
  107. statement.execute(query);
  108. } catch (SQLException e) {
  109. e.printStackTrace();
  110. return false;
  111. }
  112. return true;
  113. }
  114.  
  115.  
  116. /**
  117. * @param user name of the user
  118. * @return the id of the user
  119. */
  120. public int checkUser(String user) {
  121. user = user.toLowerCase();
  122. String query = "select * from users where NAME='" + user + "'";
  123. try {
  124. ResultSet rs = statement.executeQuery(query);
  125.  
  126. if(rs.next()) {
  127. int id = rs.getInt(1);
  128. return id;
  129. } else {
  130. return -1;
  131. }
  132. } catch (SQLException e) {
  133. e.printStackTrace();
  134. return -1;
  135. }
  136. }
  137.  
  138.  
  139.  
  140. /**
  141. * @param id
  142. * @return users name
  143. */
  144. public double getWageById(int id) {
  145. String query = "select wage from users where ID=" + id + "";
  146. try {
  147. ResultSet rs = statement.executeQuery(query);
  148.  
  149. if(rs.next()) {
  150. double wage = rs.getDouble(1);
  151. return wage;
  152. } else {
  153. return -1;
  154. }
  155. } catch (SQLException e) {
  156. e.printStackTrace();
  157. return -1;
  158. }
  159. }
  160.  
  161. /**
  162. * Method to update a users wage
  163. * @param wage what wage does the user want
  164. * @param userID what user wants his wage changed
  165. * @return true if it was a success
  166. */
  167. public boolean changeWage(double wage, int userID) {
  168. String query = "UPDATE users SET wage=" + wage + " where id=" + userID;
  169. try {
  170. statement.execute(query);
  171. return true;
  172. } catch (SQLException e) {
  173. //e.printStackTrace();
  174. return false;
  175. }
  176.  
  177.  
  178. }
  179.  
  180. /**
  181. * Helper method used to create a SQL time object.
  182. * @param hour
  183. * @param min
  184. * @return {@link Time} timeOject
  185. */
  186. public Time createTime(int hour, int min) {
  187. Calendar cal = Calendar.getInstance();
  188. // set Date portion to January 1, 1970
  189. cal.set(Calendar.YEAR, 1970 );
  190. cal.set(Calendar.MONTH, Calendar.JANUARY );
  191. cal.set(Calendar.DATE, 1 );
  192. cal.set(Calendar.HOUR_OF_DAY, hour);
  193. cal.set(Calendar.MINUTE, min);
  194. return new Time(cal.getTimeInMillis());
  195. }
  196.  
  197. /**
  198. * Helper method used to create a SQL date object.
  199. * @param year
  200. * @param month
  201. * @param day
  202. * @return {@link Date} dateOject
  203. */
  204. public Date createDate(int year, int month, int day) {
  205. Calendar cal = Calendar.getInstance();
  206. // set Date portion to January 1, 1970
  207. cal.set(Calendar.YEAR, year );
  208. cal.set(Calendar.MONTH, month-1);
  209. cal.set(Calendar.DATE, day );
  210. cal.set(Calendar.HOUR_OF_DAY, 0);
  211. cal.set(Calendar.MINUTE, 0);
  212. return new Date(cal.getTimeInMillis());
  213. }
  214.  
  215. /**
  216. * Inserts a new entry into the database
  217. * @param entry to be inserted
  218. * @return true if the entry was inserted successfully
  219. */
  220. public boolean insertEntry(Entry entry) {
  221. PreparedStatement psInsert;
  222. try {
  223. psInsert = connection.prepareStatement("insert into entries values " +
  224. "(DEFAULT," + // primary key is generated
  225. " ?," + // userid
  226. " ?," + // date
  227. " ?," + // start
  228. " ?," + //finish
  229. " ?," + //hours
  230. " ?," + //factor
  231. " ?," + //comment
  232. " ?" + // type
  233. ")");
  234. psInsert.setInt(1, entry.getUserId());
  235. psInsert.setDate(2, entry.getDate());
  236. psInsert.setTime(3, entry.getStart());
  237. psInsert.setTime(4, entry.getFinish());
  238. psInsert.setInt(5, entry.getHours());
  239. psInsert.setInt(6, entry.getFactor());
  240. psInsert.setString(7, entry.getComment());
  241. psInsert.setString(8, entry.getType());
  242. psInsert.executeUpdate();
  243. //System.out.println("HALLO???");
  244. return true;
  245. } catch (SQLException e) {
  246. e.printStackTrace();
  247. return false;
  248. }
  249. }
  250.  
  251. /**
  252. * Method to update an entry
  253. * @param entry What entry to be updated
  254. * @param entryID id for the entry to be updated
  255. * @return true if entry was updated without mishaps
  256. */
  257. public boolean updateEntry(Entry entry, int entryID) {
  258. PreparedStatement psInsert;
  259. try {
  260. psInsert = connection.prepareStatement("UPDATE entries SET " +
  261. " userid=?," + // userid
  262. " date=?," + // date
  263. " start=?," + // start
  264. " finish=?," + //finish
  265. " hours=?," + //hours
  266. " factor=?," + //factor
  267. " comment=?," + //comment
  268. " type=?" + // type
  269. "WHERE id=?" +
  270. "");
  271. psInsert.setInt(1, entry.getUserId());
  272. psInsert.setDate(2, entry.getDate());
  273. psInsert.setTime(3, entry.getStart());
  274. psInsert.setTime(4, entry.getFinish());
  275. psInsert.setInt(5, entry.getHours());
  276. psInsert.setInt(6, entry.getFactor());
  277. psInsert.setString(7, entry.getComment());
  278. psInsert.setString(8, entry.getType());
  279. psInsert.setInt(9, entryID);
  280. psInsert.executeUpdate();
  281. //System.out.println("HALLO???");
  282. return true;
  283. } catch (SQLException e) {
  284. e.printStackTrace();
  285. return false;
  286. }
  287. }
  288.  
  289. /**
  290. * Method to retrieve all the entries from the entries table
  291. * @return {@link ArrayList} an ArrayList containing all the entries
  292. */
  293. public ArrayList<Entry> retrieveAllEntries() {
  294. ArrayList<Entry> entries = new ArrayList<Entry>();
  295.  
  296. try {
  297. ResultSet rs = statement.executeQuery("select * from entries inner join users on entries.userid=users.id");
  298. while (rs.next()) {
  299. int entryId = rs.getInt(1);
  300. int userId = rs.getInt(2);
  301. Date date = rs.getDate(3);
  302. Time start = rs.getTime(4);
  303. Time finish = rs.getTime(5);
  304. int hours = rs.getInt(6);
  305. int factor = rs.getInt(7);
  306. String comment = rs.getString(8);
  307. String type = rs.getString(9);
  308.  
  309. String username = rs.getString(11);
  310.  
  311. Entry entry = new Entry(entryId, start, finish, date, hours, userId, username, comment, factor, type);
  312. entries.add(entry);
  313. }
  314. } catch (SQLException e){
  315. //e.printStackTrace();
  316. }
  317. return entries;
  318. }
  319.  
  320. /**
  321. * Method to retrieve the entries from a specified month
  322. * @return {@link ArrayList} an ArrayList containing all the entries
  323. */
  324. public ArrayList<Entry> retrieveEntriesByMonth(int month) {
  325. ArrayList<Entry> entries = new ArrayList<Entry>();
  326. month = month - 1;
  327. try {
  328. ResultSet rs = statement.executeQuery("select * from entries inner join users on entries.userid=users.id");
  329. while (rs.next()) {
  330. int entryId = rs.getInt(1);
  331. int userId = rs.getInt(2);
  332. Date date = rs.getDate(3);
  333. Time start = rs.getTime(4);
  334. Time finish = rs.getTime(5);
  335. int hours = rs.getInt(6);
  336. int factor = rs.getInt(7);
  337. String comment = rs.getString(8);
  338. String type = rs.getString(9);
  339.  
  340. String username = rs.getString(11);
  341. if(date.getMonth() == month) {
  342. Entry entry = new Entry(entryId, start, finish, date, hours, userId, username, comment, factor, type);
  343. entries.add(entry);
  344. }
  345. }
  346. } catch (SQLException e){
  347. //e.printStackTrace();
  348. }
  349. return entries;
  350. }
  351.  
  352. /**
  353. * Method to retrieve the entries from a specified month
  354. * @return {@link ArrayList} an ArrayList containing all the entries
  355. */
  356. public ArrayList<Entry> retrieveEntriesByYear(int year) {
  357. ArrayList<Entry> entries = new ArrayList<Entry>();
  358.  
  359. try {
  360. ResultSet rs = statement.executeQuery("select * from entries inner join users on entries.userid=users.id");
  361. while (rs.next()) {
  362. int entryId = rs.getInt(1);
  363. int userId = rs.getInt(2);
  364. Date date = rs.getDate(3);
  365. Time start = rs.getTime(4);
  366. Time finish = rs.getTime(5);
  367. int hours = rs.getInt(6);
  368. int factor = rs.getInt(7);
  369. String comment = rs.getString(8);
  370. String type = rs.getString(9);
  371.  
  372. String username = rs.getString(11);
  373. if(date.getYear() == year) {
  374. Entry entry = new Entry(entryId, start, finish, date, hours, userId, username, comment, factor, type);
  375. entries.add(entry);
  376. }
  377. }
  378. } catch (SQLException e){
  379. //e.printStackTrace();
  380. }
  381. return entries;
  382. }
  383.  
  384. /**
  385. * Method to retrieve the entries from a specified type
  386. * @return {@link ArrayList} an ArrayList containing all the entries
  387. */
  388. public ArrayList<Entry> retrieveEntriesByType(String type1) {
  389. ArrayList<Entry> entries = new ArrayList<Entry>();
  390.  
  391. try {
  392. ResultSet rs = statement.executeQuery("select * from entries inner join users on entries.userid=users.id");
  393. while (rs.next()) {
  394. int entryId = rs.getInt(1);
  395. int userId = rs.getInt(2);
  396. Date date = rs.getDate(3);
  397. Time start = rs.getTime(4);
  398. Time finish = rs.getTime(5);
  399. int hours = rs.getInt(6);
  400. int factor = rs.getInt(7);
  401. String comment = rs.getString(8);
  402. String type = rs.getString(9);
  403.  
  404. String username = rs.getString(11);
  405. if(type.compareTo(type1) == 0) {
  406. Entry entry = new Entry(entryId, start, finish, date, hours, userId, username, comment, factor, type);
  407. entries.add(entry);
  408. }
  409. }
  410. } catch (SQLException e){
  411. //e.printStackTrace();
  412. }
  413. return entries;
  414. }
  415.  
  416.  
  417. /**
  418. * Helper method to create new entry from user input
  419. * @param start
  420. * @param finish
  421. * @param date
  422. * @param hours
  423. * @param userName
  424. * @param comment
  425. * @param factor
  426. * @param type
  427. * @return an EntryObject
  428. */
  429. public Entry createEntry(String start, String finish, String dateString, String hourString,
  430. int userID, String userName, String comment, String factorString, String type) throws NumberFormatException {
  431.  
  432. int startHour = 0;
  433. int startMinute = 0;
  434. int finishHour = 0;
  435. int finishMinute = 0;
  436. int dateDay = 0;
  437. int dateMonth = 0;
  438. int dateYear = 0;
  439. try {
  440. startHour = java.lang.Integer.parseInt(start.substring(0, 2));
  441. startMinute = java.lang.Integer.parseInt(start.substring(3, 5));
  442.  
  443. finishHour = java.lang.Integer.parseInt(finish.substring(0, 2));
  444. finishMinute = java.lang.Integer.parseInt(finish.substring(3, 5));
  445.  
  446. dateDay = java.lang.Integer.parseInt(dateString.substring(0, 4));
  447. dateMonth = java.lang.Integer.parseInt(dateString.substring(5, 7));
  448. dateYear = java.lang.Integer.parseInt(dateString.substring(8, 10));
  449. } catch (Exception e) {
  450. return null;
  451. }
  452.  
  453. Time finishTime = createTime(finishHour, finishMinute);
  454. Time startTime = createTime(startHour, startMinute);
  455. Date date = createDate(dateYear, dateMonth, dateDay);
  456.  
  457. int hours = java.lang.Integer.parseInt(hourString);
  458.  
  459. int factor = java.lang.Integer.parseInt(factorString);
  460.  
  461. Entry returnEntry = new Entry(startTime, finishTime, date, hours, userID, userName, comment, factor, type);
  462.  
  463. return returnEntry;
  464.  
  465. }
  466.  
  467. /**
  468. * Deletes an entry after entry id
  469. * @param entryID
  470. * @return true if entry was removed
  471. */
  472. public boolean removeEntry(int entryID) {
  473.  
  474. String query = "delete from entries where id=" + entryID;
  475.  
  476. try {
  477. statement.execute(query);
  478. return true;
  479. } catch (SQLException e) {
  480. e.printStackTrace();
  481. return false;
  482. }
  483. }
  484.  
  485. /**
  486. * Logges the user in, can be expanded to include a password
  487. * @param name
  488. * @return true if the user was logged in
  489. */
  490. public boolean logInn(String name) {
  491. name = name.toLowerCase();
  492. int id = checkUser(name);
  493. double wage = getWageById(id);
  494. if(id > 0) {
  495. this.setUserID(id);
  496. this.setUserName(name);
  497. this.setUserWage(wage);
  498. return true;
  499. }
  500. return false;
  501. }
  502.  
  503. /**
  504. * @return wage
  505. */
  506. public double getUserWage() {
  507. return userWage;
  508. }
  509.  
  510. /**
  511. * Saves the logged in users name
  512. * @param userWage
  513. */
  514. public void setUserWage(double userWage) {
  515. this.userWage = userWage;
  516. }
  517.  
  518. /**
  519. * sets the logged in users Id
  520. * @param id
  521. */
  522. private void setUserID(int id) {
  523. this.userID = id;
  524.  
  525. }
  526. /**
  527. * @return the userID
  528. */
  529. public int getUserID() {
  530. return userID;
  531. }
  532.  
  533. /**
  534. * @param userName
  535. */
  536. public void setUserName(String userName) {
  537. this.userName = userName;
  538. }
  539.  
  540. /**
  541. * @return the userName
  542. */
  543. public String getUserName() {
  544. return userName;
  545. }
  546.  
  547. /**
  548. * Singleton class to instantiate only one object of the database connector.
  549. */
  550. private static class SingletonHolder {
  551. private static final TimeDAO INSTANCE = new TimeDAO();
  552. }
  553.  
  554. public static TimeDAO getInstance() {
  555. return SingletonHolder.INSTANCE;
  556. }
  557.  
  558.  
  559.  
  560.  
  561.  
  562.  
  563. }
Add Comment
Please, Sign In to add comment