-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathDatabase.java
834 lines (687 loc) · 20 KB
/
Database.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
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.Statement;
import java.sql.SQLException;
import java.io.File;
import java.io.FileReader;
import java.io.FileInputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.util.Scanner;
/**
* <h1>Abstract class to represent a table in the database.</h1>
*
* @author Hayder
* @version 1.0
*/
abstract class Table {
final String name;
final String definition;
final boolean isTemp;
/**
* Constructs a new table.
*
* @param name String represents name of the table.
* @param definition String showing the definition of the table creation.
* @param isTemp boolean representing whether table is temporary or not.
* @throws SQLException
*/
public Table(String name, String definition, boolean isTemp) throws SQLException {
this.name = name;
this.definition = definition;
this.isTemp = isTemp;
initialise();
}
/**
* Abstract method to insert data in table which is implemented differently
* depending on the table.
*
* @throws SQLException
*/
abstract void insertData() throws SQLException;
/**
* Checks if table already exists before creating it. If it does, drop the table first.
*
* @throws SQLException
*/
public void initialise() throws SQLException {
if (alreadyExists()) {
drop();
create();
} else {
create();
}
}
/**
* Checks if table already exsts in database.
*
* @return true if table already exists in database otherwise return false.
* @throws SQLException
*/
public boolean alreadyExists() throws SQLException {
boolean exists = false;
ResultSet rs = Database.connection.getMetaData().getTables(null, null, this.name, null);
while (rs.next()) {
String name = rs.getString("TABLE_NAME");
if (name != null && name.equals(this.name)) {
exists = true;
break;
}
}
return exists;
}
/**
* Drops table from database.
*
* @throws SQLException
*/
public void drop() throws SQLException {
Statement st = Database.connection.createStatement();
st.execute("DROP TABLE " + this.name + " CASCADE;");
st.close();
}
/**
* Creates table in database.
*
* @throws SQLException
*/
public void create() throws SQLException {
Statement st = Database.connection.createStatement();
String createQuery;
if (isTempTable()) {
createQuery = "CREATE TEMP TABLE " + this.name + " (" + this.definition + ");";
} else {
createQuery = "CREATE TABLE " + this.name + " (" + this.definition + ");";
}
st.execute(createQuery);
st.close();
}
/**
* Checks if table is temporary or not.
*
* @return true if table is temporary, otherwise return false.
*/
public boolean isTempTable() {
return this.isTemp;
}
}
/**
* <h1>Abstract class to represent a view in the database.</h1>
*
* @author Hayder
* @version 1.0
*/
abstract class View {
final String name;
final String definition;
/**
* Constructs a new view.
*
* @param name String represents name of the view.
* @param definition String showing the definition of the view creation.
* @throws SQLException
*/
public View(String name, String definition) throws SQLException {
this.name = name;
this.definition = definition;
initialise();
}
/**
* Checks if view already exists before creating it. If it does, drop the view first.
*
* @throws SQLException
*/
public void initialise() throws SQLException {
if (alreadyExists()) {
drop();
create();
} else {
create();
}
}
/**
* Checks if view already exsts in database.
*
* @return true if view already exists in database otherwise return false.
* @throws SQLException
*/
public boolean alreadyExists() throws SQLException {
boolean exists = false;
ResultSet rs = Database.connection.getMetaData().getTables(null, null, this.name, new String[]{"VIEW"});
while (rs.next()) {
String name = rs.getString("TABLE_NAME");
if (name != null && name.equals(this.name)) {
exists = true;
break;
}
}
return exists;
}
/**
* Drops view from database.
*
* @throws SQLException
*/
public void drop() throws SQLException {
Statement st = Database.connection.createStatement();
st.execute("DROP VIEW " + this.name + " CASCADE;");
st.close();
}
/**
* Creates view in database.
*
* @throws SQLException
*/
public void create() throws SQLException {
Statement st = Database.connection.createStatement();
st.execute("CREATE VIEW " + this.name + " AS " + this.definition + ";");
st.close();
}
}
/**
* Class to represent the mapping table in database. Implements {@link Table} abstract class.
*
* @author Hayder
* @version 1.0
*
* @see Table
*/
class Mapping extends Table {
public final static String name = "mapping";
public final static String definition = "tld VARCHAR(15), description VARCHAR(200) NOT NULL, PRIMARY KEY (tld)";
public final static boolean isTemp = false;
public final static String insertQuery = "INSERT INTO mapping (tld, description) VALUES (?, ?) "
+ "ON CONFLICT DO NOTHING";
public String filepath = new File("").getAbsolutePath();
public String mapping_file = filepath + "/mapping";
/**
* Constructor calls parent constructor to set up table.
*
* @throws SQLException
*
* @see Table#Table(String, String, boolean)
*/
public Mapping() throws SQLException {
super(name, definition, isTemp);
insertData();
}
/**
* Inserts data from mapping file into table.
*
* @throws SQLException
*/
@Override
public void insertData() throws SQLException {
PreparedStatement preparedStatement;
preparedStatement = Database.connection.prepareStatement(insertQuery);
BufferedReader reader;
try {
reader = new BufferedReader(new FileReader(mapping_file));
String line = reader.readLine();
while (line != null) {
String[] values = line.split("\t");
int i = 1;
for (String value : values) {
preparedStatement.setString(i++, value);
}
preparedStatement.addBatch();
line = reader.readLine();
}
preparedStatement.executeBatch();
preparedStatement.close();
reader.close();
} catch (IOException e) {
e.printStackTrace();
System.out.println("Error reading file");
}
}
}
/**
* Class to represent the url_temp table in database. Implements {@link Table} abstract class.
*
* @author Hayder
* @version 1.0
*
* @see Table
*/
class UrlTemp extends Table {
public final static String name = "url_temp";
public final static String definition = "pos INT,\n" +
" domain_name VARCHAR(50),\n" +
" tld1 VARCHAR(15) NOT NULL,\n" +
" tld2 VARCHAR(15)";
public final static boolean isTemp = true;
public String insertQuery = "INSERT INTO url_temp (pos, domain_name, tld1, tld2) "
+ "VALUES (?, ?, ?, ?)";
public String filepath = new File("").getAbsolutePath();
public String file = filepath + "/TopURLs";
/**
* Constructor calls parent constructor to set up table.
*
* @throws SQLException
*
* @see Table#Table(String, String, boolean)
*/
public UrlTemp() throws SQLException {
super(name, definition, isTemp);
insertData();
}
/**
* Inserts data from TopURLs file into table.
*
* @throws SQLException
*/
@Override
public void insertData() throws SQLException {
PreparedStatement preparedStatement;
preparedStatement = Database.connection.prepareStatement(insertQuery);
Scanner scanner;
try {
scanner = new Scanner(new FileInputStream(file));
while(scanner.hasNextLine()) {
String line = scanner.nextLine();
String[] values = line.split("\t");
int id = Integer.parseInt(values[0]);
String domain = values[1];
String tld1 = values[2];
String tld2;
// check if the line has two tlds or one and handle accordingly
if (values.length == 4) {
tld2 = values[3];
} else {
tld2 = "";
}
preparedStatement.setInt(1, id);
preparedStatement.setString(2, domain);
preparedStatement.setString(3, tld1);
preparedStatement.setString(4, tld2);
preparedStatement.addBatch();
}
preparedStatement.executeBatch();
preparedStatement.close();
scanner.close();
} catch (IOException e) {
e.printStackTrace();
System.out.println("Error reading file");
}
}
}
/**
* Class to represent the tld table in database. Implements {@link Table} abstract class.
*
* @author Hayder
* @version 1.0
*
* @see Table
*/
class Tld extends Table {
public final static String name = "tld";
public final static String definition = "tld_id INT, tld1 VARCHAR(15) NOT NULL, tld2 VARCHAR(15), PRIMARY KEY (tld_id)";
public final static boolean isTemp = false;
public final static String insertQuery = "SELECT row_number() OVER (ORDER BY min(pos)), tld1, tld2\n" +
"FROM url_temp\n" +
"GROUP BY tld1, tld2";
/**
* Constructor calls parent constructor to set up table.
*
* @throws SQLException
*
* @see Table#Table(String, String, boolean)
*/
public Tld() throws SQLException {
super(name, definition, isTemp);
insertData();
}
/**
* Inserts data from url table into this table.
*
* @throws SQLException
*/
@Override
public void insertData() throws SQLException {
Statement st = Database.connection.createStatement();
st.executeUpdate("INSERT INTO " + name + " " + insertQuery + " ON CONFLICT DO NOTHING;");
st.close();
}
}
/**
* Class to represent the domain table in database. Implements {@link Table} abstract class.
*
* @author Hayder
* @version 1.0
*
* @see Table
*/
class Domain extends Table {
public final static String name = "domain";
public final static String definition = "domain_name VARCHAR(50), PRIMARY KEY (domain_name)";
public final static boolean isTemp = false;
public final static String insertQuery = "SELECT domain_name\n" +
"FROM url_temp\n" +
"GROUP BY domain_name\n" +
"ORDER BY domain_name";
/**
* Constructor calls parent constructor to set up table.
*
* @throws SQLException
*
* @see Table#Table(String, String, boolean)
*/
public Domain() throws SQLException {
super(name, definition, isTemp);
insertData();
}
/**
* Inserts data from url table into this table.
*
* @throws SQLException
*/
@Override
public void insertData() throws SQLException {
Statement st = Database.connection.createStatement();
st.executeUpdate("INSERT INTO " + name + " " + insertQuery + " ON CONFLICT DO NOTHING;");
st.close();
}
}
/**
* Class to represent the url table in database. Implements {@link Table} abstract class.
*
* @author Hayder
* @version 1.0
*
* @see Table
*/
class Url extends Table {
public final static String name = "url";
public final static String definition = "domain_name VARCHAR(50) NOT NULL, tld_id INT NOT NULL,\n" +
" position INT NOT NULL, PRIMARY KEY (domain_name, tld_id), "
+ "FOREIGN KEY (domain_name) REFERENCES domain,\n" +
" FOREIGN KEY (tld_id) REFERENCES tld,\n" +
" UNIQUE (position),\n" +
" CHECK (position >= 1 AND position <= 10000)";
public final static boolean isTemp = false;
public final static String insertQuery = "INSERT INTO url (position, domain_name, tld_id) VALUES (?, ?, ?) ON CONFLICT DO NOTHING";
/**
* Constructor calls parent constructor to set up table.
*
* @throws SQLException
*
* @see Table#Table(String, String, boolean)
*/
public Url() throws SQLException {
super(name, definition, isTemp);
insertData();
}
/**
* Inserts data from url_temp into table.
*
* @throws SQLException
*/
@Override
public void insertData() throws SQLException {
PreparedStatement preparedStatement;
preparedStatement = Database.connection.prepareStatement(insertQuery);
ResultSet rs = Database.executeSelect("SELECT pos, domain_name, tld_id "
+ "FROM url_temp "
+ "NATURAL JOIN tld "
+ "WHERE url_temp.tld1 = tld.tld1 AND url_temp.tld2 = tld.tld2 "
+ "ORDER BY pos;");
try {
while (rs.next()) {
preparedStatement.setInt(1, rs.getInt(1));
preparedStatement.setString(2, rs.getString(2));
preparedStatement.setInt(3, rs.getInt(3));
preparedStatement.addBatch();
}
} catch (SQLException e) {
e.printStackTrace();
}
rs.close();
preparedStatement.executeBatch();
preparedStatement.close();
}
}
/**
* Class to represent the url view in database. Implements {@link View} abstract class.
*
* @author Hayder
* @version 1.0
*
* @see View
*/
class UrlView extends View {
public final static String name = "top_10_urls";
public final static String definition = "SELECT position, domain_name, tld1, tld2\n" +
" FROM url\n" +
" NATURAL JOIN tld\n" +
" ORDER BY position\n" +
" LIMIT 10;";
/**
* Constructor calls parent constructor to set up view.
*
* @throws SQLException
*
* @see View#View(String, String)
*/
public UrlView() throws SQLException {
super(name, definition);
}
}
/**
* Class to represent the url view in database. Implements {@link View} abstract class.
*
* @author Hayder
* @version 1.0
*
* @see View
*/
class TldView extends View {
public final static String name = "top_10_tlds";
public final static String definition = "SELECT min(position) AS best_position, tld1, tld2, description\n" +
" FROM url\n" +
" NATURAL JOIN tld, mapping\n" +
" WHERE\n" +
" (\n" +
" CASE\n" +
" WHEN tld.tld2 = '' THEN tld.tld1\n" +
" ELSE tld.tld2\n" +
" END\n" +
" ) = mapping.tld\n" +
" GROUP BY tld1, tld2, description\n" +
" ORDER BY best_position\n" +
" LIMIT 10;";
/**
* Constructor calls parent constructor to set up view.
*
* @throws SQLException
*
* @see View#View(String, String)
*/
public TldView() throws SQLException {
super(name, definition);
}
}
/**
* Class to represent the url view in database. Implements {@link View} abstract class.
*
* @author Hayder
* @version 1.0
*
* @see View
*/
class DomainView extends View {
public final static String name = "top_10_repeated_domains";
public final static String definition = "SELECT min(position) AS best_position, domain_name\n" +
" FROM url\n" +
" GROUP BY domain_name\n" +
" HAVING count(*) > 1\n" +
" ORDER BY best_position\n" +
" LIMIT 10;";
/**
* Constructor calls parent constructor to set up view.
*
* @throws SQLException
*
* @see View#View(String, String)
*/
public DomainView() throws SQLException {
super(name, definition);
}
}
/**
* <h1>Class to represent a query in the database.</h1>
*
* @author Hayder
* @version 1.0
*/
class Query {
private String title;
private String query;
private String formatting;
/**
* Constructor initialises the instance fields of this class.
*
* @param title String represents the title to be displayed for this query.
* @param query String represents the actual statment to query.
* @param formatting String represents how the query results should be formatted.
* @throws SQLException
*/
public Query(String title, String query, String formatting) throws SQLException {
this.title = title;
this.query = query;
this.formatting = formatting;
}
/**
* Iterates through resultset of query and prints the formatted results to console.
*
* @throws SQLException
*/
public void print() throws SQLException {
ResultSet rs = Database.executeSelect(this.query);
ResultSetMetaData rsmd = rs.getMetaData();
int columns = rsmd.getColumnCount();
String[] format = this.formatting.split(" ");
System.out.println("\n##" + this.title + "##\n");
for (int i = 0; i < columns; i++) {
System.out.printf(format[i], rsmd.getColumnName(i + 1).toUpperCase());
}
try {
while (rs.next()) {
for (int i = 1; i <= columns; i++) {
if (rs.getObject(i) instanceof Integer) {
System.out.printf(format[i-1], rs.getInt(i));
} else {
System.out.printf(format[i-1], rs.getString(i));
}
}
}
} catch (SQLException e) {
e.printStackTrace();
}
rs.close();
System.out.println("\n");
}
}
/**
* Conntains main method and is where program is launched from.
*
* @author Hayder
* @version 1.0
*/
public class Database {
public static Connection connection;
/**
* Establishes a connection to database.
*
* @param user String represents username for database.
* @param password String represents the password for user.
* @param database String represents the name of database (including the username).
* @return a {@link Connection} if database connection successful, otherwise return null.
*/
public static Connection connectToDatabase(String user, String password, String database) {
Connection connection = null;
try {
connection=DriverManager.getConnection(database, user, password);
} catch (SQLException e) {
System.out.println("Connection Failed! Check output console");
e.printStackTrace();
}
return connection;
}
/**
* Shows the resultset of a query.
*
* @param query String represents the statement to query.
* @return the resultset of the query.
* @throws SQLException
*/
public static ResultSet executeSelect (String query) throws SQLException {
Statement st = null;
st = connection.createStatement();
ResultSet rs = null;
rs = st.executeQuery(query);
return rs;
}
/**
* Loads database by initialising all tables and views as well printing out the queries.
*
* @throws SQLException
*/
public static void loadDatabase() throws SQLException {
Table mapping = new Mapping();
Table url_temp = new UrlTemp();
Table tld = new Tld();
Table domain = new Domain();
Table url = new Url();
View top_10_urls = new UrlView();
View top_10_tlds = new TldView();
View top_10_repeated_domains = new DomainView();
Query queryOne = new Query(
"Query 1: 10 most popular URLs in descending order of popularity",
"SELECT * FROM top_10_urls;",
"%-10.10s %-15.50s %-7.15s %-7.15s%n");
Query queryTwo = new Query(
"Query 2: 10 distinct most popular top level domains in descending order of popularity",
"SELECT tld1, tld2 FROM top_10_tlds;",
"%-7.15s %-7.15s%n");
Query queryThree = new Query(
"Query 3: 10 distinct most popular descriptions of the rightmost part of tld in descending order of popularity",
"SELECT description FROM top_10_tlds;",
"%-50.200s%n");
Query queryFour = new Query(
"Query 4: top 10 distinct domain names that appear more than once, ordered by popularity",
"SELECT domain_name FROM top_10_repeated_domains;",
"%-15.50s%n");
Query[] queries = {queryOne, queryTwo, queryThree, queryFour};
for (Query query : queries) {
query.print();
}
}
/**
* Main method launches program.
*
* @param args String array requires exactly two arguments, username and password.
* @throws SQLException
*/
public static void main(String[] args) throws SQLException {
String user;
String password;
String database;
if (args.length != 2) {
System.out.println("Please enter your username and password as command line arguments.");
} else {
user = args[0];
password = args[1];
database = "jdbc:postgresql://localhost/CS2855/" + user;
connection = connectToDatabase(user, password, database);
}
if (connection != null) {
loadDatabase();
} else {
System.out.println("Failed to make connection!");
}
}
}