forked from ISPGroup/Term-Project
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathRecordManager.java
1338 lines (1259 loc) · 41 KB
/
RecordManager.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.util.ArrayList;
import java.io.*;
import java.util.*;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import javax.swing.table.*;
import java.security.*;
/**
* Creates a library manager in which users can create a number of book records. Information will
* be stored in an ArrayList. There is a tool bar that has six buttons: previous, next,
* save, new, delete, and borrow. The user can cycle through the previous profiles created as well as
* create new ones and delete old ones. The user can also save and open files.
*
* @author JDL Development - Lily&David
* @version 1.0, May 12/14
*/
public class RecordManager extends JPanel implements ActionListener
{
/**
* d (JDialog) points to the JDialog class
*/
JDialog d;
/**
* book (ArrayList) creates a reference for the BookRecord array
*/
ArrayList <BookRecord> book = new ArrayList <BookRecord> ();
/**
* The panel in which all components are placed.
*/
JPanel thePanel = new JPanel ();
/**
* currentRec (int) signals the current record being viewed.
*/
private static int currentRec;
/**
* toolBarTop This is the toolbar at the top of the window.
*/
JToolBar toolBarTop = new JToolBar ("Top Bar");
/**
* PREVIOUS (String) stores a string used to reference the button.
*/
static final private String PREVIOUS = "previous";
/**
* NEXT (String) stores a string used to reference the button.
*/
static final private String NEXT = "next";
/**
* SAVE (String) stores a string used to reference the button.
*/
static final private String SAVE = "save";
/**
* NEW (String) stores a string used to reference the button.
*/
static final private String NEW = "new";
/**
* DELETE (String) stores a string used to reference the button.
*/
static final private String DELETE = "delete";
/**
* BORROW (String) stores a string used to reference the button.
*/
static final private String BORROW = "borrow";
/**
* RETURN (String) stores a string used to reference the button.
*/
static final private String RETURN = "return";
/**
* This variable holds the username of the current user.
*/
String username;
/**
* entryLabel (JLabel) points to the JLabel class.
*/
JLabel entryLabel;
/**
* titleField (JTextField) creates a new textfield.
*/
JTextField titleField;
/**
* authorField (JTextField) creates a new textfield.
*/
JTextField authorField;
/**
* genreBox (JComboBox) creates a new JComboBox.
*/
JComboBox genreBox;
/**
* locationField (JTextField) creates a new textfield.
*/
JTextField locationField;
/**
* borrowField (JTextField) creates a new textfield.
*/
JTextField borrowField;
/**
* returnField (JTextField) creates a new textfield.
*/
JTextField returnField;
/**
* genreBoxItems (String []) stores an array of the items to be stored in genreBox.
*/
String [] genreBoxItems = {"---", "Action", "Historical", "Horror", "Humour", "Kids", "Mystery", "Romance", "Sci-fi/Fantasy", "Supernatural", "Young Adult", "Other"};
/**
* This is a boolean statement that holds whether or not the current record has been saved.
*/
boolean recSaved;
/**
* This is a boolean statement that holds whether or not the current file has been saved.
*/
boolean fileSaved = true;
/**
* fileName The name of the file.
*/
String fileName;
/**
* theFile The file that will be saved and opened.
*/
File theFile;
/**
* optionPaneResult Stores value from the error dialogue box.
*/
int optionPaneResult;
/**
* admin is true if the admin is accessing the program, false if it is a guest
*/
boolean admin = true;
/**
* columnNames stores the names of columns
*/
Object columnNames[];
/**
* dataValues stores the data for the table
*/
Object dataValues[] [];
/**
* myTable creates a new JTable
*/
JTable myTable = new JTable ();
/**
* This is the order of the records to be displayed
*/
int [] order;
/**
* This stores which field will be sorted.
*/
int sortWhichField = 0;
/**
*The constructor creates a new entry in the array list and starts the display method.
*/
SearchAndSort s = new SearchAndSort ();
/**
*The constructor creates a new entry in the array list and starts the display method.
*/
DataBaseApp dba;
/**
*Boolean variable to identify whether the JTable is sorted.
*/
boolean sorted = false;
/**
*Boolean variable to identify whether the JTable should display search results.
*/
boolean searchMode = false;
/**
* This is the index of records found by the search
*/
int [] searchIndex;
/**
* This stores which field will be searched.
*/
int searchWhichField = 0;
/**
* This stores which type of search to use.
*/
int whichSearch = 0;
/**
* Variable which holds whether a partial search or whole search is requested.
*/
int partialOrWhole = 0;
/**
* The text to be searched.
*/
String searchText = "";
/**
* This variable keeps track of amount of searches found.
*/
int amountFound = 0;
/**
* This is a boolean statement that holds whether or not the correct password has been entered.
*/
boolean successPass = true;
/**
* Points to the MessageDigest class.
*/
private static MessageDigest md;
/**
* Constructor for the RecordManager class.
*/
public RecordManager ()
{
recSaved = true;
fileSaved = true;
currentRec = 0;
}
/**
* This method lets the user change the password.
*
* @param changePassword1 creates a new JLabel.
* @param changePassword2 creates a new JLabel.
* @param changePassword3 creates a new JLabel.
* @param changePassword4 creates a new JLabel.
* @param OLDPASSFIELD creates a new JTextField.
* @param NEWPASSFIELD creates a new JTextField.
* @param NEWPASSFIELD2 creates a new JTextField.
* @param ok creates a new JButton.
* @param cancel creates a new JButton.
* @param newPassFile writes the new password into the file.
* @param e points to the ActionEvent class.
* @param ie is for the IOException.
* @e IOException catches IO errors.
*/
public void changePassword ()
{
d = new JDialog ();
d.setSize (300, 270);
d.setResizable (true);
JLabel changePassword1 = new JLabel ("Change the admin password");
JLabel changePassword2 = new JLabel ("Old password");
JLabel changePassword3 = new JLabel ("New password");
JLabel changePassword4 = new JLabel ("Confirm password");
final JTextField OLDPASSFIELD = new JTextField (20);
final JTextField NEWPASSFIELD = new JTextField (20);
final JTextField NEWPASSFIELD2 = new JTextField (20);
JButton ok = new JButton ("Change Password");
JButton cancel = new JButton ("Cancel");
d.setLayout (new BoxLayout(d.getContentPane(),BoxLayout.Y_AXIS));
d.add (changePassword1);
d.add(Box.createRigidArea(new Dimension(0,10)));
d.add (changePassword2);
d.add (OLDPASSFIELD);
d.add(Box.createRigidArea(new Dimension(0,10)));
d.add (changePassword3);
d.add (NEWPASSFIELD);
d.add(Box.createRigidArea(new Dimension(0,10)));
d.add (changePassword4);
d.add (NEWPASSFIELD2);
d.add(Box.createRigidArea(new Dimension(0,10)));
d.add (ok);
d.add (cancel);
ok.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e) {
try
{
BufferedReader passFile = new BufferedReader (new FileReader ("Misc/pass.txt"));
if (passFile.readLine ().equals (encryptPassword(OLDPASSFIELD.getText ())))
{
if (NEWPASSFIELD.getText ().equals (NEWPASSFIELD2.getText ()))
{
PrintWriter newPassFile = new PrintWriter (new FileWriter ("Misc/pass.txt"));
newPassFile.print (encryptPassword(NEWPASSFIELD.getText ()));
newPassFile.close ();
JOptionPane.showMessageDialog (thePanel, "You have successfully changed your password.", "Successful", JOptionPane.INFORMATION_MESSAGE);
d.dispose ();
}
else
{
JOptionPane.showMessageDialog (thePanel, "The new passwords do not match. Please try again.", "New Passwords Don't Match", JOptionPane.ERROR_MESSAGE);
NEWPASSFIELD2.requestFocus ();
NEWPASSFIELD2.setText ("");
}
}
else
{
JOptionPane.showMessageDialog (thePanel, "Incorrect old password. Please try again.", "Old Password Incorrect", JOptionPane.ERROR_MESSAGE);
OLDPASSFIELD.requestFocus ();
OLDPASSFIELD.setText ("");
}
}
catch (IOException ie)
{
}
}
});
cancel.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e) {
d.dispose();
}
});
d.setVisible (true);
}
/**
* Encrypts the password.
*
* @param ex for the NoSuchAlgorithmException.
* @return the encrypted password.
* @e NoSuchAlgorithmException catches algorithm errors.
*/
public String encryptPassword(String pass)
{
try
{
md = MessageDigest.getInstance("MD5");
byte[] passBytes = pass.getBytes();
md.reset();
byte[] digested = md.digest(passBytes);
StringBuffer sb = new StringBuffer();
for(int i = 0; i < digested.length ; i++)
{
sb.append(Integer.toHexString(0xff & digested[i]));
}
return sb.toString();
}
catch (NoSuchAlgorithmException ex)
{
}
return null;
}
/**
* Prints the database.
*
* @param p points to the Printer class.
*/
public void printDatabase ()
{
Printer p = new Printer ();
p.println ("Data in Library Manager");
p.println ();
for (int x = 0; x < BookRecord.recNum; x ++)
{
p.println ("Record Number: " + (x + 1));
p.println ("Book Title: " + book.get(x).getTitle());
p.println ("Author Name: " + book.get(x).getAuthor());
p.println ("Book Genre: " + book.get(x).getGenre());
p.println ("Location: " + book.get(x).getLocation());
p.println ("Borrow Date: " + book.get(x).getBorrowDate());
p.println ("Return Date: " + book.get(x).getReturnDate());
p.println ();
}
p.printUsingDialog ();
}
/**
* Switches from an alternate view to the textfield view.
*
* @param icon icon that holds the background image.
* @param bg label that holds background image.
*/
public void fieldView ()
{
thePanel.removeAll();
thePanel.setLayout(null);
thePanel.setPreferredSize(new Dimension (400,500));
entryLabel = new JLabel ("Entry " + (currentRec + 1) + " of " + BookRecord.recNum);
entryLabel.setFont (new Font ("Calibri", Font.PLAIN, 24));
titleField = new JTextField (30);
authorField = new JTextField (30);
genreBox = new JComboBox (genreBoxItems);
genreBox.setSelectedItem ("---");
locationField = new JTextField (30);
borrowField = new JTextField (30);
returnField = new JTextField (30);
toolBarTop.setBounds (0,0,400,50);
entryLabel.setBounds (243,349,200,200);
titleField.setBounds (30,120,170, 25);
authorField.setBounds (30,200,170, 25);
genreBox.setBounds (30,260,170, 25);
locationField.setBounds (30,320,170, 25);
borrowField.setBounds (30,380,170, 25);
returnField.setBounds (30,440,170, 25);
Icon icon = new ImageIcon(".//Graphics/TextFieldBG.jpg");
JLabel bg = new JLabel(icon);
bg.setBounds (0,50,400,450);
thePanel.add (toolBarTop);
thePanel.add (entryLabel);
thePanel.add (titleField);
thePanel.add (authorField);
thePanel.add (genreBox);
thePanel.add (locationField);
thePanel.add (borrowField);
thePanel.add (returnField);
thePanel.add (bg);
}
/**
* Switches from an alternate view to the JTable view, and creates the JTable.
*
* @param tableModel sets the table model for the JTable.
* @param scroll creates a scroll bar.
*/
public void tableView()
{
thePanel.removeAll();
thePanel.setLayout(new BorderLayout());
thePanel.setPreferredSize(new Dimension (580,(80+(BookRecord.recNum*20))));
createColumns();
createData();
DefaultTableModel tableModel = new DefaultTableModel (dataValues, columnNames);
myTable.setModel (tableModel);
myTable.setColumnSelectionAllowed(false);
myTable.setCellSelectionEnabled(false);
myTable.setRowSelectionAllowed(false);
myTable.setRowHeight(20);
myTable.setAutoResizeMode (JTable.AUTO_RESIZE_OFF);
myTable.getColumnModel().getColumn(0).setPreferredWidth(25);
myTable.getColumnModel().getColumn(1).setPreferredWidth(140);
myTable.getColumnModel().getColumn(2).setPreferredWidth(100);
myTable.getColumnModel().getColumn(3).setPreferredWidth(78);
myTable.getColumnModel().getColumn(4).setPreferredWidth(87);
myTable.getColumnModel().getColumn(6).setPreferredWidth(73);
myTable.setShowVerticalLines(true);
myTable.setShowHorizontalLines(true);
myTable.setGridColor(Color.LIGHT_GRAY);
JScrollPane scroll = new JScrollPane (myTable);
thePanel.add(scroll, BorderLayout.CENTER);
}
/**
* This method creates the toolbar.
*
* @param button This is a new JButton.
*/
public void toolbarMaker ()
{
toolBarTop.setLayout (new FlowLayout (FlowLayout.CENTER));
toolBarTop.setFloatable (false);
JButton button = null;
button = makeNavigationButton ("previous", PREVIOUS, "Previous Record", "Previous");
toolBarTop.add (button);
button = makeNavigationButton ("next", NEXT, "Next Record", "Next");
toolBarTop.add (button);
if (admin)
{
button = makeNavigationButton ("save", SAVE, "Save Record", "Save");
toolBarTop.add (button);
button = makeNavigationButton ("delete", DELETE, "Delete Record", "Del");
toolBarTop.add (button);
button = makeNavigationButton ("new", NEW, "New Record", "New");
toolBarTop.add (button);
}
else
{
button = makeNavigationButton ("borrow", BORROW, "Borrow this Book", "Borrow");
toolBarTop.add (button);
button = makeNavigationButton ("return", RETURN, "Return this Book", "Return");
toolBarTop.add (button);
}
}
/**
* This method creates the butons for the toolbar.
*
* @param imageName is the name of the image to be added
* @param actionCommand this is the string value that ActionPerformed will pick up
* @param toolTipText this is the text that appears on mouse-over
* @param altText this the alternate text for the button
* @param imgLocation is the location of the image to be added
* @param imageGIF is the image that will be added to the button
* @param button is a new JButton
* @return the new button on the toolbar.
*/
protected JButton makeNavigationButton (String imageName, String actionCommand, String toolTipText, String altText)
{
String imgLocation = "Graphics/"+imageName + ".png";
Image imageGIF = Toolkit.getDefaultToolkit ().getImage (imgLocation);
JButton button = new JButton ();
button.setActionCommand (actionCommand);
button.setToolTipText (toolTipText);
button.addActionListener (this);
button.setIcon (new ImageIcon (imageGIF, altText));
return button;
}
/**
* Empties the old database and creates a new one.
*/
public void newDatabase ()
{
book.clear ();
BookRecord.recNum = 0;
book.add (new BookRecord());
currentRec = 0;
recSaved = true;
fileSaved = true;
}
/**
* Updates the info being displayed.
*/
public void updateDisplay ()
{
titleField.setText (book.get(currentRec).getTitle());
authorField.setText (book.get(currentRec).getAuthor());
genreBox.setSelectedIndex (findIndex (book.get(currentRec).getGenre ()));
locationField.setText (book.get(currentRec).getLocation());
borrowField.setText (book.get(currentRec).getBorrowDate());
returnField.setText (book.get(currentRec).getReturnDate());
entryLabel.setText ("Entry " + (currentRec + 1) + " of " + BookRecord.recNum);
fileSaved = false;
}
/**
* Finds the index of the item in the genreBoxItem array.
*
* @param item (String) the item that needs to be found in the array.
* @return the index of the item
*/
public int findIndex (String item)
{
for (int x = 0; x < 12; x++)
{
if (genreBoxItems [x].equals (item))
{
return x;
}
}
return -1;
}
/**
* Shows the previous profile from the current one. Allows for wrapping (if the current
* profile is the first one, it shows the last one).
*/
private void prevRec ()
{
if (recSaved)
{
if (currentRec == 0)
{
currentRec = BookRecord.recNum-1;
}
else
{
currentRec --;
}
updateDisplay ();
}
else
{
JOptionPane.showMessageDialog (this, "Please save/delete this record first!", "Not Saved", JOptionPane.ERROR_MESSAGE);
}
}
/**
* Shows the next profile from the current one. Allows for wrapping. (if the current
* profile is the last one, it shows the first one).
*/
private void nextRec ()
{
if (recSaved)
{
if (currentRec == (BookRecord.recNum - 1))
{
currentRec = 0;
}
else
{
currentRec ++;
}
updateDisplay ();
}
else
{
JOptionPane.showMessageDialog (this, "Please save/delete this record first!", "Not Saved", JOptionPane.ERROR_MESSAGE);
}
}
/**
* Creates a new profile IF all the fields are not empty.
*/
private void newRec ()
{
if (!(titleField.getText ().equals ("") && recSaved == false))
{
book.add (new BookRecord());
currentRec = BookRecord.recNum - 1;
updateDisplay ();
genreBox.setSelectedItem ("---");
recSaved = false;
fileSaved = false;
}
}
/**
* Deletes the current profile being viewed and displays the previous file.
*/
public void deleteRec ()
{
book.remove(currentRec);
BookRecord.recNum --;
if (BookRecord.recNum == 0)
{
book.add (new BookRecord());
}
recSaved = true;
prevRec ();
fileSaved = false;
}
/**
* Takes the current date and sets the borrow date and also adds 10 days for the return date.
*
* @param tempBDate stores the borrow date
* @param tempRDate stores the return date
* @param dateFormat stores the format the date is displayed
* @param date gets the current date
* @param isLeapYear true if the year is a leap year, false if not
*/
public void borrowBook ()
{
String tempBDate = "";
String tempRDate = "";
if (!(book.get(currentRec).getBorrowDate() == null || book.get(currentRec).getBorrowDate().equals ("") || book.get(currentRec).getLocation().substring (12).equals (username)))
{
JOptionPane.showMessageDialog (this, "This book has already been borrowed by someone else!", "Unavailable", JOptionPane.ERROR_MESSAGE);
}
else
{
DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
Date date = new Date();
tempBDate = (String)(dateFormat.format(date));
tempRDate = determineReturnDate (tempBDate);
book.get(currentRec).setBorrowDate(tempBDate);
book.get(currentRec).setReturnDate(tempRDate);
book.get(currentRec).setLocation("Borrowed by " + username);
save (fileName);
updateDisplay ();
}
}
/**
* Determines the return date based off of the borrow date.
*
* @param returnDay stores the day the book is returned from 1-28/29/30/31.
* @param returnMonth stores the month the book is returned from 1-12.
* @param returnYear stores the year the book is returned.
* @param tempBDate gets the borrow date that the return date is based off of.
* @param tempRDate stores the new return date.
* @return the determined return date.
*/
public String determineReturnDate (String tempBDate)
{
int returnDay = 0;
int returnMonth = 0;
int returnYear = 0;
String tempRDate = "";
returnDay = Integer.parseInt (tempBDate.substring (0, 2)) + 10;
returnMonth = Integer.parseInt (tempBDate.substring (3, 5));
returnYear = Integer.parseInt (tempBDate.substring (6, 10));
if (returnMonth == 1 || returnMonth == 3 || returnMonth == 5 || returnMonth == 7 || returnMonth == 8 || returnMonth == 10 || returnMonth == 12)
{
if (returnDay > 31)
{
returnDay = returnDay - 31;
returnMonth ++;
}
}
else if (returnMonth == 4 || returnMonth == 4 || returnMonth == 4 || returnMonth == 4)
{
if (returnDay > 30)
{
returnDay = returnDay - 30;
returnMonth ++;
}
}
else
{
boolean isLeapYear = ((returnYear % 4 == 0) && (returnYear % 100 != 0) || (returnYear % 400 == 0));
if (isLeapYear)
{
if (returnDay > 29)
{
returnDay = returnDay - 29;
returnMonth ++;
}
}
else
{
if (returnDay > 28)
{
returnDay = returnDay - 28;
returnMonth ++;
}
}
}
if (returnMonth > 12)
{
returnMonth = returnMonth - 12;
returnYear ++;
}
if (returnDay < 10)
{
tempRDate = "0" + returnDay + "/";
}
else
{
tempRDate = returnDay + "/";
}
if (returnMonth < 10)
{
tempRDate = tempRDate + "0" + returnMonth + "/";
}
else
{
tempRDate = tempRDate + returnMonth + "/";
}
return (tempRDate + returnYear);
}
/**
* Returns the book to the library and clears the borrow date data and the location data.
*/
public void returnBook ()
{
if (!(book.get(currentRec).getBorrowDate() == null || book.get(currentRec).getBorrowDate().equals ("")))
{
try
{
if (book.get(currentRec).getLocation().substring (12).equals (username))
{
book.get(currentRec).setBorrowDate("");
book.get(currentRec).setReturnDate("");
book.get(currentRec).setLocation("");
save (fileName);
updateDisplay ();
}
else
{
JOptionPane.showMessageDialog (this, "This book has been borrowed by someone else, so you cannot return it!", "Unavailable", JOptionPane.ERROR_MESSAGE);
}
}
catch (Exception e)
{
JOptionPane.showMessageDialog (this, "This book has been borrowed by someone else, so you cannot return it!", "Unavailable", JOptionPane.ERROR_MESSAGE);
}
}
else
{
JOptionPane.showMessageDialog (this, "This book is already in the library!", "Unavailable", JOptionPane.ERROR_MESSAGE);
}
}
/**
* Saves the information to the ArrayList if the fields are not empty.
*
* @param title (String) the book title to be stored
* @param author (String) the author name to be stored
* @param genre (String) the genre to be stored
* @param location (String) the location to be stored
* @param borrowD (String) the borrow date to be stored
* @param returnD (String) the return date to be stored
*/
private void saveRec (String title, String author, String genre, String location, String borrowD, String returnD)
{
if (!title.equals (""))
{
if (DataCheck.checkDate (borrowD) == false)
{
borrowD = "";
JOptionPane.showMessageDialog (this, "The borrow date is improperly formatted.", "INVALID DATE", JOptionPane.WARNING_MESSAGE);
}
else if (DataCheck.checkDate (returnD) == false)
{
returnD = "";
JOptionPane.showMessageDialog (this, "The return date is improperly formatted.", "INVALID DATE", JOptionPane.WARNING_MESSAGE);
}
else
{
if (!(borrowD == null || borrowD.equals ("")))
{
location = "Borrowed";
returnD = determineReturnDate (borrowD);
}
else
{
if (!(location == null || location.equals ("")))
{
if (location.charAt (0) == 'B')
{
if (location.substring (0, 8).equals ("Borrowed"))
{
location = "";
}
}
returnD = "";
}
}
book.get(currentRec).setTitle (title);
book.get(currentRec).setAuthor (author);
book.get(currentRec).setGenre (genre);
book.get(currentRec).setLocation (location);
book.get(currentRec).setBorrowDate (borrowD);
book.get(currentRec).setReturnDate(returnD);
recSaved = true;
fileSaved = false;
}
}
else
JOptionPane.showMessageDialog (this, "You must fill in at least the book title for a valid entry!", "BOOK FIELD EMPTY", JOptionPane.INFORMATION_MESSAGE);
updateDisplay ();
}
/**
* This method saves data onto a previously existing file or creates a new file.
*
* @param pw References the PrintWriter class and makes its methods and features available.
* @param fileNameString passes a string value through.
* @param e IOException catches FileIO errors
* @e IOException catches FileIO errors..
*/
public void save (String fileName)
{
if (fileName != null)
{
PrintWriter output;
try
{PrintWriter ouput = new PrintWriter (new FileWriter ("Documents/"+fileName));
ouput.println ("Storing the library data like a boss.");
ouput.println (BookRecord.recNum);
for (int z = 0; z < BookRecord.recNum; z++ )
{
ouput.println (book.get(z).getTitle());
ouput.println (book.get(z).getAuthor());
ouput.println (book.get(z).getGenre());
ouput.println (book.get(z).getLocation());
ouput.println (book.get(z).getBorrowDate());
ouput.println (book.get(z).getReturnDate());
}
ouput.close();
fileSaved = true;
}
catch (IOException e)
{
JOptionPane.showMessageDialog (this, "Error occured while saving file.", "Save Error", JOptionPane.ERROR_MESSAGE);
}
}
else
saveAs ();
}
/**
* This method creates a new file to store the current data and allows the user to name the file.
*
* @param fileChooser references the JFileChooser class.
* @param filter creates a new ExampleFileFilter class.
* @param result stores the action commands of the user in the JFileChooser dialog.
* @param br references the BufferedReader class.
* @param e catches FileIO errors.
* @e IOException catches FileIO errors.
*/
public void saveAs ()
{
JFileChooser fileChooser = new JFileChooser (".\\Documents");
ExampleFileFilter filter = new ExampleFileFilter ( );
filter.addExtension ("lmf");
filter.setDescription ("Library Manager Files");
fileChooser.setFileFilter (filter);
int result = fileChooser.showSaveDialog (this);
if (result == JFileChooser.APPROVE_OPTION)
{
fileName = addExtension(fileChooser.getSelectedFile().getName());
if (!(fileName == null || fileName.equals ("")))
{
try
{
BufferedReader input = new BufferedReader (new FileReader ("Documents/" + fileName));
optionPaneResult = JOptionPane.showConfirmDialog (this, "Would you like to overwite this file?", "Overwrite?", JOptionPane.YES_NO_OPTION);
if (optionPaneResult == 0)
save (fileName);
else if (optionPaneResult == 1)
JOptionPane.showMessageDialog(this,"No changes will be made.","No Changes",JOptionPane.WARNING_MESSAGE);
}
catch (IOException e)
{
save (fileName);
}
}
}
}
/**
* This method adds the ".lmf" extension
*
* @param fileName the original filename to be added onto.
* @return the filename with the extension added.
*/
public String addExtension (String fileName)
{
for (int x = 0; x < fileName.length ()-1; x++)
{
if (fileName.charAt (x) == '.')
fileName = fileName.substring (0, x);
}
return (fileName + ".lmf");
}
/**
* This method opens a user chosen file.
*
* @param headerLine this is the first line of all lmf files.
* @param titleLine this stores the book title taken from the file.
* @param authorLine this stores the author name taken from the file.
* @param genreLine this stores the genre taken from the file.
* @param locationLine this stores the location taken from the file.
* @param borrowDLine this stores the borrow date taken from the file.
* @param returnDLine this stores the return date taken from the file.
* @param fileChooser instance of the FileChooser class.
* @param recAmount this stores the amount of records to be created.
* @param filter instance of the ExampleFileFilter class.
* @param openDialog opens the dialogue to allow the user to pick a file.
* @param input stores the input from reading the file.
* @param e catches IOException errors.
* @e IOException catches IO errors.
*/
public void openFile ()
{
String headerLine = "";
String titleLine;
String authorLine;
String genreLine;
String locationLine;
String borrowDLine;
String returnDLine;
JFileChooser fileChooser = new JFileChooser (".\\Documents");
int recAmount;
ExampleFileFilter filter = new ExampleFileFilter ( );
filter.addExtension ("lmf");
filter.setDescription ("Library Manager Files");
fileChooser.setFileFilter (filter);
int openDialog = fileChooser.showOpenDialog (this);
if (openDialog != JFileChooser.APPROVE_OPTION)
return;
theFile = fileChooser.getSelectedFile();
BufferedReader input;
try
{
input = new BufferedReader (new FileReader (theFile));
headerLine = input.readLine ();
}
catch (Exception e){}
if (theFile == null || theFile.getName ().equals ("") || theFile.getName ().length () > 255)
{
JOptionPane.showMessageDialog (this, "Please pick a file. Go to File > Open.", "No File Chosen", JOptionPane.ERROR_MESSAGE);
theFile = null;
}
else if (!(filter.getExtension (theFile)).equals ("lmf"))
{
JOptionPane.showMessageDialog (this, "Wrong Extension", "Invalid Extension", JOptionPane.ERROR_MESSAGE);
theFile = null;
}
else if (!headerLine.equals ("Storing the library data like a boss."))
{
JOptionPane.showMessageDialog (this, "Incorrect Header.", "Invalid Header", JOptionPane.ERROR_MESSAGE);
theFile = null;
}
else
{
try
{