-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathServer.java
More file actions
721 lines (637 loc) · 27.6 KB
/
Server.java
File metadata and controls
721 lines (637 loc) · 27.6 KB
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
import java.io.*;
import java.net.*;
import java.nio.file.*;
import java.util.*;
import java.util.stream.Collectors;
public class Server {
public static void main(String[] args) throws IOException {
System.out.println("Welcome to the server");
ServerSocket serverSocket = new ServerSocket(8080);
while (true){
System.out.println("Waiting for client...");
new ClientHandler(serverSocket.accept()).start();
}
}
}
class ClientHandler extends Thread {
Socket socket;
DataOutputStream dos;
DataInputStream dis;
public ClientHandler(Socket socket) throws IOException {
this.socket = socket;
dos = new DataOutputStream(socket.getOutputStream());
dis = new DataInputStream(socket.getInputStream());
System.out.println("Connected to server");
}
public String listener() throws IOException {
System.out.println("listener");
StringBuilder sb = new StringBuilder();
int index = dis.read();
while (index != 0) {
sb.append((char) index);
index = dis.read();
}
System.out.println("listener2");
return sb.toString();
}
public void writer(String text) throws IOException {
dos.writeBytes(text);
dos.flush();
dos.close();
dis.close();
socket.close();
System.out.println(text);
System.out.println("command finished and response sent to server");
}
@Override
public void run() {
super.run();
String command;
try {
command = listener();
System.out.println("command received: { " + command + " }");
} catch (IOException e) {
throw new RuntimeException(e);
}
String[] split = command.split("~");//login$402243000$fg1999
for (String s : split) {
System.out.println(s);
}
try {
switch (split[0]) {
case "login": //login~studentID~password
logJava(split); //Enter the student
break;
case "sign in": //sign in~studentID~password~fullName
signJava(split); //Student registration
break;
case "viewProf": //viewProf~ID
viewProf(split); //Display full name, number of units and average
break;
case "delete account": //deleteAccount~ID
deleteAccount(split); //Delete the student from the database
break;
case "changePass": //changePass~ID~newPass
changePass(split); //Change the password in the file
break;
case "viewSara": //viewSara~ID
sara(split); //Display number of assignments, maximum and minimum grade
break;
case "myCourses": //myCourses~ID
myCourses(split); // Display courseName, teacherName, numberOfUnits, numberOfAssignments
break;
case "takeCourse": // takeCourse~ID~courseName
takeCourse(split); //Adding student to a course and sending course details
break;
case "viewCourses": //viewCourses~ID
viewCourses(split); //View every course in the database
break;
case "assignments"://assignments~ID
seeAssignments(split); //View assignments (courseName~assignmentName~deadline~activeOrNot)
break;
case "doAssignment": //doAssignment~ID~courseName
doAssignment(split); // Change the status to "not active" in assignmentFile
break;
case "addWork": //addWork~ID~workName~workDate
addWork(split); //Add work in the database
break;
case "doWork": //doWork~ID~workName
doWork(split); // Change "active" to "not active"
break;
case "deleteWork": //deleteWork~ID~workName
deleteWork(split); // Remove the work from database and application
break;
case "viewWorks": // viewWorks~ID
viewWorks(split); // read works from database
break;
}
} catch (IOException e) {
e.printStackTrace();
}
}
public void logJava(String[] split) {
boolean logIn = false;
int responseOfDatabase = 100;
try {
responseOfDatabase = Database.loginChecker(split[1], split[2]);
} catch (Exception e) {
e.printStackTrace();
}
if (responseOfDatabase == 2) {
logIn = true;
System.out.println("status code is 200");
System.out.println("Successfully logged in!");
try {
writer("200");
} catch (IOException e) {
e.printStackTrace();
}
} else if (responseOfDatabase == 1) {
System.out.println("status code is 401");
System.out.println("Password is incorrect!");
try {
writer("401");
} catch (IOException e) {
e.printStackTrace();
}
} else {
System.out.println("status code is 404");
System.out.println("username not found!");
try {
writer("404");
} catch (IOException e) {
e.printStackTrace();
}
}
if (logIn) {
long l = Long.parseLong(split[1]);
Student student = null;
try {
student = new Student(l);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
public void signJava(String[] split) throws IOException {
boolean signIn = false;
int responseOfDatabase = 100;
String fullName = split[3];
responseOfDatabase = Database.signInChecker(split[1], split[2]);
if (responseOfDatabase == 2) {
signIn = true;
System.out.println("status code is 200");
System.out.println("Successfully signed in!");
try {
Student st = new Student(Long.parseLong(split[1]));
FileWriter fw = new FileWriter("D:\\University\\AP\\project\\project files\\students\\studentInfos\\"
+ split[1] + "_info.txt", true);
fw.write("Full Name: " + fullName + "\n");
fw.flush();
fw.close();
writer("200");
} catch (IOException e) {
e.printStackTrace();
}
} else if (responseOfDatabase == 1) {
System.out.println("status code is 401");
System.out.println("Password is incorrect!");
try {
writer("401");
} catch (IOException e) {
e.printStackTrace();
}
} else {
System.out.println("status code is 404");
System.out.println("username is incorrect");
try {
writer("404");
} catch (IOException e) {
e.printStackTrace();
}
}
}
public void viewProf (String[] split) throws IOException {
String studentId = split[1];
String filePath = "D:\\University\\AP\\project\\project files\\students\\studentInfos\\"
+ studentId + "_info.txt";
Scanner scanner = new Scanner(new File(filePath));
String units = null;
String fullName = null;
double average = 0;
while (scanner.hasNextLine()){
String line = scanner.nextLine();
if (line.startsWith("Number")){
units = line.substring(17);
}
if (line.startsWith("Full")){
fullName = line.substring(11);
}
}
BufferedReader reader2 = new BufferedReader(new FileReader("D:\\University\\AP\\project\\project files\\students\\studentCourses\\"
+ studentId + "_courses.txt"));
String line;
double totalGrade = 0.0;
int courseCount = 0;
while ((line = reader2.readLine()) != null) {
if (line.contains("grade:")) {
String gradeString = line.split("grade: ")[1].trim();
double grade = Double.parseDouble(gradeString);
totalGrade += grade;
courseCount++;
}
}
reader2.close();
if (courseCount > 0) {
average = totalGrade / courseCount;
}
writer(fullName + "~" + units + "~" + average);
}
public void deleteAccount(String[] split) throws IOException {
String studentId = split[1];
File stInfo = new File("D:\\University\\AP\\project\\project files\\students\\studentInfos\\"
+ studentId + "_info.txt");
File stCourses = new File("D:\\University\\AP\\project\\project files\\students\\studentCourses\\"
+ studentId + "_courses.txt");
String courseStudentsFolderPath = "D:\\University\\AP\\project\\project files\\courses\\courseStudents\\";
String line;
try {
BufferedReader reader = new BufferedReader(new FileReader(stCourses));
while ((line = reader.readLine()) != null ) {
String courseName = reader.readLine().split(", ")[0].substring(8).trim();
String courseFilePath = courseStudentsFolderPath + courseName + "_students.txt";
File courseFile = new File(courseFilePath);
if (courseFile.exists()) {
StringBuilder content = new StringBuilder();
Scanner courseScanner = new Scanner(courseFile);
while (courseScanner.hasNextLine()) {
String lineX = courseScanner.nextLine();
if (!lineX.contains(studentId)) {
content.append(lineX).append("\n");
}
}
courseScanner.close();
FileWriter writer = new FileWriter(courseFile);
writer.write(content.toString());
writer.close();
}
}
reader.close();
System.out.println("Student data removed successfully.");
} catch (IOException e) {
e.printStackTrace();
}
stInfo.delete();
stCourses.delete();
String filePath = "D:\\University\\AP\\project\\project files\\Student info.txt";
String fileContent = Files.readString(Paths.get(filePath));
// Java 8 is coming!
List<String> lines = fileContent.lines()
.filter(lineXX -> !lineXX.contains(studentId))
.collect(Collectors.toList());
Files.write(Paths.get(filePath), lines);
writer("200");
}
public void changePass(String [] split) throws IOException {
String studentId = split[1];
String newPass = split[2];
String filePath = "D:\\University\\AP\\project\\project files\\Student info.txt";
if (!cli.passwordValidator(newPass)){
writer("404");
return;
}
try {
File file = new File(filePath);
FileReader fileReader = new FileReader(file);
BufferedReader bufferedReader = new BufferedReader(fileReader);
String line;
StringBuilder fileContent = new StringBuilder();
while ((line = bufferedReader.readLine()) != null) {
if (line.contains("Username: " + studentId)) {
line = line.replaceFirst("Password: .*", "Password: " + newPass);
}
fileContent.append(line).append("\n");
}
bufferedReader.close();
FileWriter fileWriter = new FileWriter(file);
fileWriter.write(fileContent.toString());
fileWriter.close();
writer("200");
} catch (IOException e) {
e.printStackTrace();
}
}
public void sara(String[] split) {
String studentId = split[1];
String filePath = "D:\\University\\AP\\project\\project files\\students\\studentCourses\\"
+ studentId + "_courses.txt";
try {
BufferedReader reader = new BufferedReader(new FileReader(filePath));
String line;
double highestGrade = 0;
double lowestGrade = 20;
while ((line = reader.readLine()) != null) {
if (line.contains("grade:")) {
String gradeString = line.split(": ")[2].trim();
double grade = Double.parseDouble(gradeString);
highestGrade = Math.max(highestGrade, grade);
lowestGrade = Math.min(lowestGrade, grade);
}
}
reader.close();
String courseInformationsPath = "D:\\University\\AP\\project\\project files\\courses\\courseInformations\\";
BufferedReader reader2= new BufferedReader(new FileReader(filePath));
int asNum = 0;
String courseName;
String lineX;
while ((lineX = reader2.readLine()) != null) {
String[] parts = lineX.split(",");
courseName = parts[0].substring(8).trim();
String assignmentFilePath = courseInformationsPath + courseName + "_info.txt";
BufferedReader assignmentReader = new BufferedReader(new FileReader(assignmentFilePath));
String assignmentLine;
while ((assignmentLine = assignmentReader.readLine()) != null) {
if (assignmentLine.contains("Assignment")) {
asNum++;
}
}
assignmentReader.close();
}
reader2.close();
writer(asNum + "~" + highestGrade + "~" + lowestGrade);
} catch (IOException e) {
e.printStackTrace();
}
}
public void myCourses(String[] split) throws IOException {
List<String> studentCourses = new ArrayList<>();
String studentId = split[1];
StringBuilder result = new StringBuilder();
int asses = 0;
try {
File file = new File("D:\\University\\AP\\project\\project files\\students\\studentCourses\\"
+ studentId + "_courses.txt");
Scanner reader = new Scanner(file);
while (reader.hasNextLine()) {
String line = reader.nextLine();
String courseName = line.split(": ")[1];
if (courseName.contains(", grade")) {
courseName = courseName.split(",")[0];
}
studentCourses.add(courseName);
}
reader.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
String courseInfosPath = "D:\\University\\AP\\project\\project files\\courses\\courseInformations\\";
String teachersPath = "D:\\University\\AP\\project\\project files\\teachers\\teacherInfo\\";
for (String course : studentCourses) {
try {
result.append(course).append("~");
File courseFile = new File(courseInfosPath + course + "_info.txt");
Scanner courseReader = new Scanner(courseFile);
while (courseReader.hasNextLine()) {
String line = courseReader.nextLine();
if (line.startsWith("Teacher")){
String teacherId = line.substring(12, 21);
File teacherFile = new File(teachersPath + teacherId + "_info.txt");
Scanner scanner = new Scanner(teacherFile);
while (scanner.hasNextLine()){
String scLine = scanner.nextLine();
if (scLine.startsWith("Fullname: ")){
String teacherName = scLine.substring(10);
result.append(teacherName).append("~");
}
}
//result.append(line, 12, 21).append("~");
}
if (line.startsWith("number")){
result.append(line.charAt(21)).append("~");
}
if (line.startsWith("Assignment: ")){
asses++;
}
}
courseReader.close();
result.append(asses).append("~");
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
writer(result.substring(0,result.length()-1));
}
public void takeCourse(String[] split) throws IOException {
boolean done = false;
int responseOfDatabase = 100;
String courseInfosPath = "D:\\University\\AP\\project\\project files\\courses\\courseInformations\\";
String teachersPath = "D:\\University\\AP\\project\\project files\\teachers\\teacherInfo\\";
StringBuilder result = new StringBuilder();
int assignmets = 0;
responseOfDatabase = Database.takeCourseChecker(split[1], split[2]);
if (responseOfDatabase == 0){
System.out.println("this course does not exist");
writer("404");
} else if (responseOfDatabase == 1) {
done = true;
System.out.println("status code is 200");
System.out.println("Successfully take course");
try {
result.append(split[2]).append("~");
File courseFile = new File(courseInfosPath + split[2] + "_info.txt");
Scanner courseReader = new Scanner(courseFile);
while (courseReader.hasNextLine()) {
String line = courseReader.nextLine();
if (line.startsWith("Teacher")){
String teacherId = line.substring(12, 21);
File teacherFile = new File(teachersPath + teacherId + "_info.txt");
Scanner scanner = new Scanner(teacherFile);
while (scanner.hasNextLine()){
String scLine = scanner.nextLine();
if (scLine.startsWith("Fullname: ")){
String teacherName = scLine.substring(10);
result.append(teacherName).append("~");
}
}
}
if (line.startsWith("number")){
result.append(line.charAt(21)).append("~");
}
if (line.startsWith("Assignment: ")){
assignmets++;
}
}
courseReader.close();
result.append(assignmets).append("~");
} catch (IOException e) {
e.printStackTrace();
}
writer(result.substring(0,result.length()-1));
}
}
public void viewCourses (String[] split) throws IOException {
List<String> studentCourses = new ArrayList<>();
String studentId = split[1];
try {
File file = new File("D:\\University\\AP\\project\\project files\\students\\studentCourses\\"
+ studentId + "_courses.txt");
Scanner reader = new Scanner(file);
while (reader.hasNextLine()) {
String line = reader.nextLine();
String courseName = line.split(": ")[1];
if (courseName.contains(", grade")) {
courseName = courseName.split(",")[0];
}
studentCourses.add(courseName);
}
reader.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
String courseInfosPath = "D:\\University\\AP\\project\\project files\\courses\\courseInformations\\";
for (String course : studentCourses) {
try {
System.out.println(course + ":");
File courseFile = new File(courseInfosPath + course + "_info.txt");
Scanner courseReader = new Scanner(courseFile);
while (courseReader.hasNextLine()) {
String line = courseReader.nextLine();
writer(line);
}
courseReader.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
public void doAssignment(String[] split) throws IOException {
String studentId = split[1];
String courseName = split[2];
String assignmentName = null;
String line;
BufferedReader courseReader = new BufferedReader(new FileReader("D:\\University\\AP\\project\\project files\\courses\\courseInformations\\"
+ courseName + "_info.txt"));
while ((line = courseReader.readLine()) != null){
if (line.contains("Assignment")){
assignmentName = line.split(",")[0].substring(12);
}
}
File assignmentFile = new File("D:\\University\\AP\\project\\project files\\assignments\\" +
assignmentName + ".txt");
FileWriter assignmentWriter = new FileWriter(assignmentFile , true);
assignmentWriter.write(studentId + "\n");
assignmentWriter.flush();
assignmentWriter.close();
writer("200");
}
public void seeAssignments(String[] split) {
String studentId = split[1];
String studentCoursesFilePath = "D:\\University\\AP\\project\\project files\\students\\studentCourses\\"
+ studentId + "_courses.txt";
String courseInformationsPath = "D:\\University\\AP\\project\\project files\\courses\\courseInformations\\";
StringBuilder stringBuilder = new StringBuilder();
try {
BufferedReader studentCoursesReader = new BufferedReader(new FileReader(studentCoursesFilePath));
String line;
while ((line = studentCoursesReader.readLine()) != null) {
String[] parts = line.split(",");
String courseName = parts[0].substring(8).trim();
String assignmentFilePath = courseInformationsPath + courseName + "_info.txt";
BufferedReader assignmentReader = new BufferedReader(new FileReader(assignmentFilePath));
String assignmentLine;
while ((assignmentLine = assignmentReader.readLine()) != null) {
if (assignmentLine.contains("Assignment")) {
stringBuilder.append("Course: ").append(courseName).append("\n");
stringBuilder.append(assignmentLine).append("\n");
}
}
assignmentReader.close();
}
studentCoursesReader.close();
String result = convertToDesiredFormat(String.valueOf(stringBuilder), studentId);
writer(result);
} catch (IOException e) {
e.printStackTrace();
}
}
public String convertToDesiredFormat(String input, String id) throws IOException {
String[] lines = input.split("\n");
StringBuilder output = new StringBuilder();
for (int i = 0; i < lines.length; i += 2) {
String course = lines[i].split(": ")[1];
String[] assignmentParts = lines[i + 1].split(", ");
String assignment = assignmentParts[0].substring(12);
String deadline = assignmentParts[1].split(": ")[1];
String status = assignmentParts[2];
BufferedReader br = new BufferedReader(new FileReader("D:\\University\\AP\\project\\project files\\assignments\\"
+ assignment + ".txt"));
String line;
while ((line = br.readLine()) != null){
if (line.contains(id)){
status = "not active";
}
}
br.close();
output.append(course).append("~").append(deadline).append("~").append(status);
if (i < lines.length - 2) {
output.append("~");
}
}
return output.toString();
}
public void addWork(String[] split) throws IOException {
String studentId = split[1];
String workName = split[2];
String workDate = split[3];
FileWriter workWriter = new FileWriter("D:\\University\\AP\\project\\project files\\students\\studentWorks\\"
+ studentId + "_works.txt", true);
workWriter.write(workName + "~" + workDate + "~" + "active" + "\n");
workWriter.flush();
workWriter.close();
System.out.println("200");
writer("200");
}
public void doWork(String[] split) throws IOException {
String studentId = split[1];
String workName = split[2];
String path = "D:\\University\\AP\\project\\project files\\students\\studentWorks\\"
+ studentId + "_works.txt";
String tempPath = "D:\\University\\AP\\project\\project files\\students\\studentWorks\\"
+ studentId + "_works_temp.txt";
try (BufferedReader reader = new BufferedReader(new FileReader(path));
BufferedWriter writer = new BufferedWriter(new FileWriter(tempPath))) {
String line;
while ((line = reader.readLine()) != null) {
if (line.startsWith(workName)) {
line = line.replace("active", "not active");
}
writer.write(line);
writer.newLine();
}
reader.close();
writer.close();
System.out.println("200");
writer("200");
} catch (IOException e) {
e.printStackTrace();
}
Files.move(Paths.get(tempPath), Paths.get(path), StandardCopyOption.REPLACE_EXISTING);
}
public void deleteWork(String[] split){
String studentId = split[1];
String workName = split[2];
String filePath = "D:\\University\\AP\\project\\project files\\students\\studentWorks\\"
+ studentId + "_works.txt";
try {
String fileContent = new String(Files.readAllBytes(Paths.get(filePath)));
String[] works = fileContent.split("\n");
StringBuilder updatedContent = new StringBuilder();
for(String work : works){
if (!work.contains(workName)){
updatedContent.append(work);
}
}
Files.write(Paths.get(filePath), updatedContent.toString().getBytes());
System.out.println("200");
writer("200");
} catch (IOException e) {
e.printStackTrace();
}
}
public void viewWorks(String[] split) throws IOException {
String studentId = split[1];
StringBuilder sb = new StringBuilder();
File workFile = new File("D:\\University\\AP\\project\\project files\\students\\studentWorks\\"
+ studentId + "_works.txt");
Scanner workScanner = new Scanner(workFile);
String line;
while (workScanner.hasNextLine()){
line = workScanner.nextLine();
sb.append(line).append("~");
}
String result = sb.toString().substring(0, sb.length()-1);
System.out.println("200");
writer(result);
workScanner.close();
}
}